text:
copyright:
  years: 2015, 2016
lastupdated: "2016-11-29"

---

{:shortdesc: .shortdesc}
{:screen: .screen}
{:new_window: target="_blank"}
{:codeblock: .codeblock}

#Incorporazione di una distribuzione nel flusso iFrame {{site.data.keyword.Bluemix_notm}}
{: #embed-d2bm-iframe}

Puoi incorporare la distribuzione nel flusso {{site.data.keyword.Bluemix_notm}} come
un iFrame in molti tipi di contenuto che supportano le markup. Ad esempio, puoi incorporare l'iFrame nei file readme, nei blog, negli articoli e nelle pagine web.

{: shortdesc}

Il flusso iFrame è utile quando desideri mantenere il branding della tua azienda. Quando le persone fanno clic sul tuo iFrame incorporato, restano nel
tuo contenuto invece di essere reindirizzati al sito web di bluemix.net. Se non sei interessato al branding dell'azienda, puoi inserire un [pulsante Distribuisci a {{site.data.keyword.Bluemix_notm}}](/docs/develop/deploy_button.html) standard nel contenuto invece dell'iFrame.

##Passi nel flusso iFrame {: #iframe-steps}

1. Se non hai un account {{site.data.keyword.Bluemix_notm}} attivo,
procedi alla creazione di un account di prova.

2. Puoi selezionare una regione, un'organizzazione (org), uno spazio e un nome applicazione. Il nome applicazione consigliato viene creato dal nome applicazione precedente, dal tuo nome utente e dalla data/ora.

3. Il ramo master del repository Git pubblico originale viene clonato in un nuovo progetto {{site.data.keyword.jazzhub_short}} privato con un nuovo repository Git.

4. Se l'applicazione richiede un file di build, esso viene rilevato automaticamente e l'applicazione viene creata.

5. L'applicazione viene distribuita alla tua organizzazione {{site.data.keyword.Bluemix_notm}}.

##Esempi del flusso iFrame {: #iframe-example}

L'IBM
Bluemix D2BM iFrame Sample fornisce un esempio di flusso iFrame
per un repository Git pubblico.

Per visualizzare l'origine per questo esempio, fai clic su origine.

##Incorporazione del flusso iFrame {: #embed-iframe}

Carica il programma di utilità JavaScript da https://bluemix.net/deploy/embed.js. Questo programma di utilità dipende da jQuery e viene caricato aggiungendo la seguente tag di script al tuo documento:

<script type="text/javascript" src="https://bluemix.net/deploy/embed.js"></script>

 Istanzia il constructor DeployToBluemixIFrame utilizzando questi argomenti:

domNodeId

L'ID del domNode in cui desideri inserire l'iFrame nel tuo contenuto.

callback

Questo argomento viene richiamato quando il flusso iFrame viene completato oppure
se si verifica un errore. L'argomento risponde con il risultato. Il seguente frammento di
codice mostra un callback del risultato che ha avuto esito positivo:

args

L'oggetto che contiene i parametri di input al widget. Sono disponibili i seguenti parametri:

repository

Il repository Git da utilizzare come origine per la clonazione e la distribuzione. Questo valore è obbligatorio.

app_name

Il nome applicazione predefinito da utilizzare come valore specifico nel campo app_name all'interno
dell'iFrame. Questo valore è facoltativo.

region_id

L'ID della regione di destinazione predefinita. Ad esempio: ibm:yp:us-south. Questo valore è facoltativo.

organization_guid

Il guid dell'organizzazione di destinazione predefinita. Per trovare questo valore, fai clic su Gestisci organizzazioni > nome_organizzazione. L'URL per l'organizzazione contiene il guid per tale organizzazione. Questo valore è facoltativo.

space_guid

Il guid dello spazio di destinazione predefinito. Per trovare questo valore, fai clic su Gestisci organizzazioni > nome_spazio. L'URL per lo spazio
contiene il guid per tale spazio. Questo valore è facoltativo.

auto_login

Specifica se l'iFrame effettua automaticamente l'accesso dell'utente. Il
valore predefinito è true. Questo valore è facoltativo.

width

La larghezza dell'iFrame. Questo valore è facoltativo. Il valore predefinito è 620.

height

L'altezza dell'iFrame. Questo valore è facoltativo. Il
valore predefinito è 470.

**Suggerimento:** per ridurre al minimo l'interazione con l'iFrame, puoi precompilare i campi **app_name**, **region_id**, **organization_guid**, **space_guid** e **auto_login**.


text:
require 'rails/all'
require 'pry'
require 'minitest/spec'
require 'minitest/autorun'

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

redpajama_set_name: RedPajamaGithub


text:
module Fog
  module Compute
    class XenServer
      module Models
        class Roles < Collection
          model Fog::Compute::XenServer::Models::Role
        end
      end
    end
  end
end


text:
<?php

namespace Opifer\EavBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use Opifer\EavBundle\Model\AttributeInterface;
use Opifer\EavBundle\Model\OptionInterface;
use Opifer\EavBundle\Model\ValueInterface;
use Opifer\EavBundle\Model\ValueSetInterface;

/**
 * Value
 *
 * @ORM\Table(name="value")
 * @ORM\Entity(repositoryClass="Opifer\EavBundle\Repository\ValueRepository")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 *
 * The discriminatorMap is handled dynamically by the DiscriminatorListener. It
 * retrieves the mapped classes from the ValueProvider Pool and adds them to the
 * map.
 * @see  Opifer\EavBundle\EventListener\DiscriminatorListener
 *
 * @JMS\ExclusionPolicy("all")
 */
class Value implements ValueInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var Attribute
     *
     * @ORM\ManyToOne(targetEntity="Opifer\EavBundle\Model\AttributeInterface", inversedBy="values", cascade={"persist"}, fetch="EAGER")
     * @ORM\JoinColumn(name="attribute_id", referencedColumnName="id")
     */
    protected $attribute;

    /**
     * @var ValueSet
     *
     * @ORM\ManyToOne(targetEntity="Opifer\EavBundle\Model\ValueSetInterface", inversedBy="values", cascade={"persist"})
     * @ORM\JoinColumn(name="valueset_id", referencedColumnName="id")
     */
    protected $valueSet;

    /**
     * @var string
     *
     * @JMS\Expose
     * @ORM\Column(name="value", type="text", nullable=true)
     */
    protected $value;

    /**
     * @var  ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Opifer\EavBundle\Model\OptionInterface", inversedBy="values", cascade={"detach"})
     * @ORM\JoinTable(name="value_options",
     *     joinColumns={@ORM\JoinColumn(name="value_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="option_id", referencedColumnName="id")}
     * )
     */
    protected $options;

    /**
     * @var string
     * @ORM\Column(name="sort", type="text", nullable=true)
     */
    protected $sort;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->options = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set value
     *
     * @param string $value
     *
     * @return ValueInterface
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * Override this method in child schemas to return the desired format
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Set attribute
     *
     * @param AttributeInterface $attribute
     *
     * @return ValueInterface
     */
    public function setAttribute(AttributeInterface $attribute = null)
    {
        $this->attribute = $attribute;

        return $this;
    }

    /**
     * Get attribute
     *
     * @return AttributeInterface
     */
    public function getAttribute()
    {
        return $this->attribute;
    }

    /**
     * Set valueSet
     *
     * @param ValueSetInterface $valueSet
     *
     * @return ValueInterface
     */
    public function setValueSet(ValueSetInterface $valueSet = null)
    {
        $this->valueSet = $valueSet;

        return $this;
    }

    /**
     * Get valueSet
     *
     * @return ValueSetInterface
     */
    public function getValueSet()
    {
        return $this->valueSet;
    }

    /**
     * Add option
     *
     * @param  OptionInterface $option
     * @return Value
     */
    public function addOption(OptionInterface $option)
    {
        $this->options[] = $option;

        return $this;
    }

    /**
     * Remove option
     *
     * @param OptionInterface $options
     */
    public function removeOption(OptionInterface $option)
    {
        $this->options->removeElement($option);

        return $this;
    }

    /**
     * Set options
     *
     * @param array $options
     */
    public function setOptions($options)
    {
        if (!is_array($options)) {
            $this->options = $options->toArray();
        } else {
            foreach ($options as $option) {
                $this->addOption($option);
            }
        }

        return $this;
    }

    /**
     * Get options
     *
     * @return ArrayCollection
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Check whether this value is actually just a value without any content
     *
     * @return boolean
     */
    public function isEmpty()
    {
        return (is_null($this->getValue()) && count($this->options) < 1) ? true : false;
    }

    /**
     * Get the sorting in case the value has multiple values
     *
     * @return string
     */
    public function getSort()
    {
        return $this->sort;
    }

    /**
     * Set the sort
     *
     * @param string $sort
     * @return $this
     */
    public function setSort($sort)
    {
        $this->sort = $sort;

        return $this;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revta Biol. , Lisb. 12: 18 (1983)

#### Original name
Cyathicula stipae var. ammophilae Dennis

### Remarks
null


text:
package com.amazonaws.services.databasemigrationservice.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.databasemigrationservice.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * StartReplicationTaskRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StartReplicationTaskRequestMarshaller {

    private static final MarshallingInfo<String> REPLICATIONTASKARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReplicationTaskArn").build();
    private static final MarshallingInfo<String> STARTREPLICATIONTASKTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StartReplicationTaskType").build();
    private static final MarshallingInfo<java.util.Date> CDCSTARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CdcStartTime").build();

    private static final StartReplicationTaskRequestMarshaller instance = new StartReplicationTaskRequestMarshaller();

    public static StartReplicationTaskRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(StartReplicationTaskRequest startReplicationTaskRequest, ProtocolMarshaller protocolMarshaller) {

        if (startReplicationTaskRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(startReplicationTaskRequest.getReplicationTaskArn(), REPLICATIONTASKARN_BINDING);
            protocolMarshaller.marshall(startReplicationTaskRequest.getStartReplicationTaskType(), STARTREPLICATIONTASKTYPE_BINDING);
            protocolMarshaller.marshall(startReplicationTaskRequest.getCdcStartTime(), CDCSTARTTIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
namespace YAF
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;

    using YAF.Core;
    using YAF.Core.Services.Auth;
    using YAF.Types.Constants;
    using YAF.Types.Extensions;
    using YAF.Types.Interfaces;
    using YAF.Utils;

    /// <summary>
    /// The Twitter Authentication Page
    /// </summary>
    public partial class Auth : Page
    {
        /// <summary>
        /// The script begin tag
        /// </summary>
        private const string ScriptBeginTag = "<script type='text/javascript'>";

        /// <summary>
        /// The script end tag
        /// </summary>
        private const string ScriptEndTag = "</script>";

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            var closeScript = new StringBuilder();

            closeScript.Append("if (window.opener != null)");
            closeScript.AppendFormat(
                "{{window.opener.location.href = '{0}';window.close();}}",
                BuildLink.GetLink(ForumPages.Login).Replace(
                    "auth.aspx",
                    "default.aspx"));
            closeScript.AppendFormat(
                "else {{ window.location.href = '{0}' }}",
                BuildLink.GetLink(ForumPages.Login).Replace(
                    "auth.aspx",
                    "default.aspx"));

            if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("denied"))
            {
                BoardContext.Current.Get<HttpResponseBase>().Clear();

                BoardContext.Current.Get<HttpResponseBase>().Write($"{ScriptBeginTag} {closeScript} {ScriptEndTag}");

                return;
            }

            var loginAuth = (AuthService)Enum.Parse(
                typeof(AuthService),
                BoardContext.Current.Get<HttpRequestBase>().QueryString
                    .GetFirstOrDefaultAs<string>("auth"),
                true);

            switch (loginAuth)
            {
                case AuthService.twitter:
                    this.HandleTwitterReturn();
                    break;
                case AuthService.facebook:
                    this.HandleFacebookReturn();
                    break;
                case AuthService.google:
                    this.HandleGoogleReturn();
                    break;
                default:
                    BoardContext.Current.Get<HttpResponseBase>()
                        .Write($"{ScriptBeginTag} {closeScript} {ScriptEndTag}");
                    break;
            }
        }

        /// <summary>
        /// Handles the twitter return.
        /// </summary>
        private void HandleTwitterReturn()
        {
            string message;

            var twitterAuth = new Twitter();

            if (BoardContext.Current.Get<HttpRequestBase>().QueryString
                .GetFirstOrDefaultAs<bool>("connectCurrent"))
            {
                try
                {
                    twitterAuth.ConnectUser(this.Request, null, out message);
                }
                catch (Exception ex)
                {
                    BoardContext.Current.Get<ILogger>().Error(
                        ex,
                        "Error while trying to connect the twitter user");

                    message = ex.Message;
                }

                if (message.IsSet())
                {
                    BoardContext.Current.Get<HttpResponseBase>().Write(
                        string.Format(
                            "{2} alert('{0}');window.location.href = '{1}'; {3}",
                            message,
                            BuildLink.GetLink(ForumPages.Login).Replace(
                                "auth.aspx",
                                "default.aspx"),
                            ScriptBeginTag,
                            ScriptEndTag));
                }
                else
                {
                    BuildLink.Redirect(ForumPages.forum);
                }
            }
            else
            {
                try
                {
                    twitterAuth.LoginOrCreateUser(this.Request, null, out message);
                }
                catch (Exception ex)
                {
                    BoardContext.Current.Get<ILogger>().Error(
                        ex,
                        "Error while trying to login or register the twitter user");

                    message = ex.Message;
                }

                BoardContext.Current.Get<HttpResponseBase>().Clear();

                if (message.IsSet())
                {
                    BoardContext.Current.Get<HttpResponseBase>().Write(
                        string.Format(
                            "{2} alert('{0}');window.opener.location.href = '{1}';window.close(); {3}>",
                            message,
                            BuildLink.GetLink(ForumPages.Login).Replace(
                                "auth.aspx",
                                "default.aspx"),
                            ScriptBeginTag,
                            ScriptEndTag));
                }
                else
                {
                    BoardContext.Current.Get<HttpResponseBase>().Write(
                        string.Format(
                            "{1} window.opener.location.href = '{0}';window.close(); {2}>",
                            BuildLink.GetLink(ForumPages.forum).Replace(
                                "auth.aspx",
                                "default.aspx"),
                            ScriptBeginTag,
                            ScriptEndTag));
                }
            }
        }

        /// <summary>
        /// Handles the facebook return.
        /// </summary>
        private void HandleFacebookReturn()
        {
            var facebookAuth = new Facebook();

            if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("code"))
            {
                var authorizationCode = BoardContext.Current.Get<HttpRequestBase>().QueryString
                    .GetFirstOrDefault("code");
                var accessToken = facebookAuth.GetAccessToken(
                    authorizationCode,
                    this.Request);

                if (accessToken.IsNotSet())
                {
                    BoardContext.Current.Get<HttpResponseBase>().Write(
                        string.Format(
                            "{2} alert('{0}');window.location.href = '{1}'; {3}",
                            BoardContext.Current.Get<ILocalization>().GetText("AUTH_NO_ACCESS_TOKEN"),
                            BuildLink.GetLink(ForumPages.Login).Replace(
                                "auth.aspx",
                                "default.aspx"),
                            ScriptBeginTag,
                            ScriptEndTag));

                    return;
                }

                if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("state")
                    && BoardContext.Current.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("state")
                    == "connectCurrent")
                {
                    string message;

                    try
                    {
                        facebookAuth.ConnectUser(this.Request, accessToken, out message);
                    }
                    catch (Exception ex)
                    {
                        BoardContext.Current.Get<ILogger>().Error(
                            ex,
                            "Error while trying to connect the facebook user");

                        message = ex.Message;
                    }

                    if (message.IsSet())
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{2} alert('{0}');window.location.href = '{1}'; {3}",
                                message,
                                BuildLink.GetLink(ForumPages.forum).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                    else
                    {
                        BuildLink.Redirect(ForumPages.forum);
                    }
                }
                else
                {
                    string message;

                    try
                    {
                        facebookAuth.LoginOrCreateUser(
                            this.Request,
                            accessToken,
                            out message);
                    }
                    catch (Exception ex)
                    {
                        BoardContext.Current.Get<ILogger>().Error(
                            ex,
                            "Error while trying to login or register the facebook user");

                        message = ex.Message;
                    }

                    BoardContext.Current.Get<HttpResponseBase>().Clear();

                    if (message.IsSet())
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{2} alert('{0}');window.location.href = '{1}';window.close(); {3}",
                                message,
                                BuildLink.GetLink(ForumPages.Login).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                    else
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{1} window.location.href = '{0}';window.close(); {2}",
                                BuildLink.GetLink(ForumPages.forum).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                }
            }
            else if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("error"))
            {
                // Return to login page if user cancels social login
                BoardContext.Current.Get<HttpResponseBase>()
                    .Redirect(BuildLink.GetLink(ForumPages.Login, true));
            }
            else
            {
                // Authorize first
                BoardContext.Current.Get<HttpResponseBase>().Redirect(
                    facebookAuth.GetAuthorizeUrl(this.Request),
                    true);
            }
        }

        /// <summary>
        /// Handles the Google return.
        /// </summary>
        private void HandleGoogleReturn()
        {
            var googleAuth = new Google();

            if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("code"))
            {
                var authorizationCode = BoardContext.Current.Get<HttpRequestBase>().QueryString
                    .GetFirstOrDefault("code");
                var accessTokens = googleAuth.GetAccessToken(
                    authorizationCode,
                    this.Request);

                if (accessTokens.AccessToken == null)
                {
                    BoardContext.Current.Get<HttpResponseBase>().Write(
                        string.Format(
                            "{2} alert('{0}');window.location.href = '{1}'; {3}",
                            BoardContext.Current.Get<ILocalization>().GetText("AUTH_NO_ACCESS_TOKEN"),
                            BuildLink.GetLink(ForumPages.Login).Replace(
                                "auth.aspx",
                                "default.aspx"),
                            ScriptBeginTag,
                            ScriptEndTag));

                    return;
                }

                if (BoardContext.Current.Get<HttpRequestBase>().QueryString
                    .GetFirstOrDefaultAs<bool>("connectCurrent"))
                {
                    string message;

                    try
                    {
                        googleAuth.ConnectUser(
                            this.Request,
                            accessTokens.AccessToken,
                            out message);
                    }
                    catch (Exception ex)
                    {
                        BoardContext.Current.Get<ILogger>().Error(
                            ex,
                            "Error while trying to connect the google user");

                        message = ex.Message;
                    }

                    if (message.IsSet())
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{2} alert('{0}');window.location.href = '{1}'; {3}",
                                message,
                                BuildLink.GetLink(ForumPages.forum).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                    else
                    {
                        BuildLink.Redirect(ForumPages.forum);
                    }
                }
                else
                {
                    string message;

                    try
                    {
                        googleAuth.LoginOrCreateUser(
                            this.Request,
                            accessTokens.AccessToken,
                            out message);
                    }
                    catch (Exception ex)
                    {
                        BoardContext.Current.Get<ILogger>().Error(
                            ex,
                            "Error while trying to login or register the google user");

                        message = ex.Message;
                    }

                    BoardContext.Current.Get<HttpResponseBase>().Clear();

                    if (message.IsSet())
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{2} alert('{0}');window.location.href = '{1}';window.close(); {3}",
                                message,
                                BuildLink.GetLink(ForumPages.Login).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                    else
                    {
                        BoardContext.Current.Get<HttpResponseBase>().Write(
                            string.Format(
                                "{1} window.location.href = '{0}';window.close(); {2}",
                                BuildLink.GetLink(ForumPages.forum).Replace(
                                    "auth.aspx",
                                    "default.aspx"),
                                ScriptBeginTag,
                                ScriptEndTag));
                    }
                }
            }
            else if (BoardContext.Current.Get<HttpRequestBase>().QueryString.Exists("error"))
            {
                // Return to login page if user cancels social login
                BoardContext.Current.Get<HttpResponseBase>()
                    .Redirect(BuildLink.GetLink(ForumPages.Login, true));
            }
            else
            {
                // Authorize first
                BoardContext.Current.Get<HttpResponseBase>().Redirect(
                    googleAuth.GetAuthorizeUrl(this.Request),
                    true);
            }
        }
    }
}


text:
Bash Manager
============

Nos gusta trabajar con complementos para los distintas aplicaciones, BASHm permite usar distintos complementos que enriquecen tu experiencias usando bash.

![Demo Live](doc/images/demo_bashm_live.gif)

Índice
------

1. [Como instalar](#como-instalar)
2. [Instalar un Complemento](#instalar-un-complemento)
3. [Opciones](#opciones)
    1. [Dentro de `.bashrc` o `.bash_profile`](#dentro-de-bashrc-o-bash_profile)
4. [Log Function](#log-function)

Como Instalar
-------------

> **NOTA:** Windows no posee `bash` por su defecto, recomendamos instalar [Cygwin](https://www.cygwin.com/) o [MSYS-git UNIX tools](https://msysgit.github.io/).

```bash
git clone https://github.com/jonDotsoy/Bash-Manager.git bashm
```

Agregamos la siguiente líneas dentro del archivo `.bashrc` o `.bash_profile`.

```bash
export BASHM_PATH=${HOME}/bashm
source ${BASHM_PATH}/bashm.bash
```

Finalizando Inicializando el archivo de configuración.

```bash
bashm init
```

Instalar un Complemento
-----------------------

```bash
bashm install <name> [URL] [force]
# Example.
# $ bashm install alias_ls
# $ bashm install alias_ls https://cdn.rawgit.com/jonDotsoy/Bash-Manager/master/down_plugins/alias_ls.bash
```

Usamos el comando `bashm install` para poder instalar un complemento al bash usando bashm.

![Demo Bashm Install](doc/images/demo_bashm_install_success.jpg)

Opciones
========

## Dentro de `.bashrc` o `.bash_profile`

Las opciones se pueden fijar dentro del bash alternando los archivos `.bashrc` o `.bash_profile` para mantener las configuraciones dentro del shell.

```bash
# ~/.bashrc
...
export LOG_DECORATE=false
...
```

Log Function
------------

Es una herramienta que integra BashM para generar mensajes LOG en el terminal.

![Logs](doc/images/demo_log.jpg)

```bash
$ log [type] <Message>
# Example:
# log warn "This is a warning"
 ```

### Opción `LOG_DECORATE` (Boolean)

Muestra los mensajes con decoración.

![Docoration Log](doc/images/demo_log_decorate.jpg)

### Opción `LOG_PREFIX` y `LOG_SUFFIX`

Permite asociar mensajes a los logs decoraciones al final (LOG_SUFFIX) y al principio (LOG_PREFIX) de los mensajes.

![Decoration Suffix and Preffix](doc/images/demo_log_prefix_and_suffix.jpg)


text:
**This is an experimental fork of [evancz/start-app](https://github.com/evancz/start-app); see that for basic docs.**

This fork adds support for:

- Actions whose processing requires knowing what time it is
- Feeding in actions coming from ports
- Using tasks which result in an action getting pushed back into the app
- Using tasks which do not result in an action, and are solely processed by JS (e.g. sending something out a JS port)

See [this PR](https://github.com/evancz/start-app/pull/11) for more explanation/discussion.


text:
BEGIN;

CREATE OR REPLACE VIEW "liquid_feedback_version" AS
  SELECT * FROM (VALUES ('1.2.9', 1, 2, 9))
  AS "subquery"("string", "major", "minor", "revision");

CREATE OR REPLACE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
  RETURNS VOID
  LANGUAGE 'plpgsql' VOLATILE AS $$
    DECLARE
      "issue_row"   "issue"%ROWTYPE;
      "member_id_v" "member"."id"%TYPE;
    BEGIN
      PERFORM "lock_issue"("issue_id_p");
      SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
      DELETE FROM "delegating_voter"
        WHERE "issue_id" = "issue_id_p";
      DELETE FROM "direct_voter"
        WHERE "issue_id" = "issue_id_p"
        AND "autoreject" = TRUE;
      DELETE FROM "direct_voter" USING "member"
        WHERE "direct_voter"."member_id" = "member"."id"
        AND "direct_voter"."issue_id" = "issue_id_p"
        AND "member"."active" = FALSE;
      UPDATE "direct_voter" SET "weight" = 1
        WHERE "issue_id" = "issue_id_p";
      PERFORM "add_vote_delegations"("issue_id_p");
      FOR "member_id_v" IN
        SELECT "interest"."member_id"
          FROM "interest"
          JOIN "member"
            ON "interest"."member_id" = "member"."id"
          LEFT JOIN "direct_voter"
            ON "interest"."member_id" = "direct_voter"."member_id"
            AND "interest"."issue_id" = "direct_voter"."issue_id"
          LEFT JOIN "delegating_voter"
            ON "interest"."member_id" = "delegating_voter"."member_id"
            AND "interest"."issue_id" = "delegating_voter"."issue_id"
          WHERE "interest"."issue_id" = "issue_id_p"
          AND "interest"."autoreject" = TRUE
          AND "member"."active"
          AND "direct_voter"."member_id" ISNULL
          AND "delegating_voter"."member_id" ISNULL
        UNION SELECT "membership"."member_id"
          FROM "membership"
          JOIN "member"
            ON "membership"."member_id" = "member"."id"
          LEFT JOIN "interest"
            ON "membership"."member_id" = "interest"."member_id"
            AND "interest"."issue_id" = "issue_id_p"
          LEFT JOIN "direct_voter"
            ON "membership"."member_id" = "direct_voter"."member_id"
            AND "direct_voter"."issue_id" = "issue_id_p"
          LEFT JOIN "delegating_voter"
            ON "membership"."member_id" = "delegating_voter"."member_id"
            AND "delegating_voter"."issue_id" = "issue_id_p"
          WHERE "membership"."area_id" = "issue_row"."area_id"
          AND "membership"."autoreject" = TRUE
          AND "member"."active"
          AND "interest"."autoreject" ISNULL
          AND "direct_voter"."member_id" ISNULL
          AND "delegating_voter"."member_id" ISNULL
      LOOP
        INSERT INTO "direct_voter"
          ("member_id", "issue_id", "weight", "autoreject") VALUES
          ("member_id_v", "issue_id_p", 1, TRUE);
        INSERT INTO "vote" (
          "member_id",
          "issue_id",
          "initiative_id",
          "grade"
          ) SELECT
            "member_id_v" AS "member_id",
            "issue_id_p"  AS "issue_id",
            "id"          AS "initiative_id",
            -1            AS "grade"
          FROM "initiative" WHERE "issue_id" = "issue_id_p";
      END LOOP;
      PERFORM "add_vote_delegations"("issue_id_p");
      UPDATE "issue" SET
        "closed" = now(),
        "voter_count" = (
          SELECT coalesce(sum("weight"), 0)
          FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
        )
        WHERE "id" = "issue_id_p";
      UPDATE "initiative" SET
        "positive_votes" = "vote_counts"."positive_votes",
        "negative_votes" = "vote_counts"."negative_votes",
        "agreed" = CASE WHEN "majority_strict" THEN
          "vote_counts"."positive_votes" * "majority_den" >
          "majority_num" *
          ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
        ELSE
          "vote_counts"."positive_votes" * "majority_den" >=
          "majority_num" *
          ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
        END
        FROM
          ( SELECT
              "initiative"."id" AS "initiative_id",
              coalesce(
                sum(
                  CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
                ),
                0
              ) AS "positive_votes",
              coalesce(
                sum(
                  CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
                ),
                0
              ) AS "negative_votes"
            FROM "initiative"
            JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
            JOIN "policy" ON "issue"."policy_id" = "policy"."id"
            LEFT JOIN "direct_voter"
              ON "direct_voter"."issue_id" = "initiative"."issue_id"
            LEFT JOIN "vote"
              ON "vote"."initiative_id" = "initiative"."id"
              AND "vote"."member_id" = "direct_voter"."member_id"
            WHERE "initiative"."issue_id" = "issue_id_p"
            AND "initiative"."admitted"  -- NOTE: NULL case is handled too
            GROUP BY "initiative"."id"
          ) AS "vote_counts",
          "issue",
          "policy"
        WHERE "vote_counts"."initiative_id" = "initiative"."id"
        AND "issue"."id" = "initiative"."issue_id"
        AND "policy"."id" = "issue"."policy_id";
      -- NOTE: "closed" column of issue must be set at this point
      DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
      INSERT INTO "battle" (
        "issue_id",
        "winning_initiative_id", "losing_initiative_id",
        "count"
      ) SELECT
        "issue_id",
        "winning_initiative_id", "losing_initiative_id",
        "count"
        FROM "battle_view" WHERE "issue_id" = "issue_id_p";
    END;
  $$;

COMMIT;


text:
Permutations and placements

Package does K-permutations with sort.Interface data


text:
namespace foundation {
namespace bvh {

//
// BVH tree statistics.
//

template <typename Tree>
class TreeStatistics
  : public Statistics
{
  public:
    typedef typename Tree::NodeType NodeType;
    typedef typename NodeType::AABBType AABBType;

    // Constructor, collects statistics for a given tree.
    TreeStatistics(
        const Tree&         tree,
        const AABBType&     tree_bbox);

  private:
    typedef typename AABBType::ValueType ValueType;

    ValueType               m_leaf_volume;          // total volume of the leaves
    size_t                  m_leaf_count;           // number of leaf nodes
    Population<size_t>      m_leaf_depth;           // leaf depth statistics
    Population<size_t>      m_leaf_size;            // leaf size statistics
    Population<double>      m_sibling_overlap;      // amount of overlap between sibling nodes

    // Helper method to recursively traverse the tree and collect statistics.
    void collect_stats_recurse(
        const Tree&         tree,
        const NodeType&     node,
        const AABBType&     bbox,
        const size_t        depth);
};

//
// BVH traversal statistics.
//

class TraversalStatistics
  : public NonCopyable
{
  public:
    size_t                  m_traversal_count;      // number of times the tree was traversed
    Population<size_t>      m_visited_nodes;        // number of visited nodes
    Population<size_t>      m_visited_leaves;       // number of visited leaves
    Population<size_t>      m_intersected_bboxes;   // number of bounding boxes intersected
    Population<size_t>      m_discarded_nodes;      // number of discarded nodes (not hit by the ray)
    Population<size_t>      m_intersected_items;    // number of items tested for intersection

    // Constructor.
    TraversalStatistics();

    // Retrieve performance statistics.
    Statistics get_statistics() const;
};

//
// TreeStatistics class implementation.
//

template <typename Tree>
TreeStatistics<Tree>::TreeStatistics(
    const Tree&             tree,
    const AABBType&         tree_bbox)
  : m_leaf_volume(ValueType(0.0))
  , m_leaf_count(0)
{
    assert(!tree.m_nodes.empty());

    collect_stats_recurse(tree, tree.m_nodes.front(), tree_bbox, 1);

    const ValueType tree_volume =
        tree_bbox.is_valid() ? tree_bbox.volume() : ValueType(0.0);

    if (m_leaf_volume > tree_volume)
        m_leaf_volume = tree_volume;

    insert_size("size", tree.get_memory_size());
    insert(
        "nodes",
        "total " + pretty_uint(tree.m_nodes.size()) +
        "  interior " + pretty_uint(tree.m_nodes.size() - m_leaf_count) +
        "  leaves " + pretty_uint(m_leaf_count));
    insert_percent("leaf volume", m_leaf_volume, tree_volume);
    insert("leaf depth", m_leaf_depth);
    insert("leaf size", m_leaf_size);
    insert("sibling overlap", m_sibling_overlap, "%");
}

template <typename Tree>
void TreeStatistics<Tree>::collect_stats_recurse(
    const Tree&             tree,
    const NodeType&         node,
    const AABBType&         bbox,
    const size_t            depth)
{
    if (node.is_leaf())
    {
        // Gather leaf statistics.
        m_leaf_depth.insert(depth);
        m_leaf_size.insert(node.get_item_count());
        ++m_leaf_count;
        if (bbox.is_valid())
            m_leaf_volume += bbox.volume();
    }
    else
    {
        // Fetch left and right children.
        const size_t child_index = node.get_child_node_index();
        const AABBType left_bbox = node.get_left_bbox();
        const AABBType right_bbox = node.get_right_bbox();
        const NodeType& left_node = tree.m_nodes[child_index];
        const NodeType& right_node = tree.m_nodes[child_index + 1];

        // Keep track of the amount of overlap between children.
        m_sibling_overlap.insert(AABBType::overlap_ratio(left_bbox, right_bbox) * ValueType(100.0));

        // Recurse into the child nodes.
        collect_stats_recurse(tree, left_node, left_bbox, depth + 1);
        collect_stats_recurse(tree, right_node, right_bbox, depth + 1);
    }
}

}       // namespace bvh
}       // namespace foundation

#endif  // !APPLESEED_FOUNDATION_MATH_BVH_BVH_STATISTICS_H


text:
CREATE TABLE jangosworld.`spells` (
  `spellID` int(11) UNSIGNED DEFAULT '0',
  `fk_school` TINYINT(3) NOT NULL DEFAULT '0',
  `category` int(11) NOT NULL DEFAULT '0',
  `castUI` int(11) NOT NULL DEFAULT '0',
  fk_dispelType TINYINT(2) DEFAULT NULL,
  fk_mechanic TINYINT(2) DEFAULT NULL,
  attrUnknown0 TINYINT(1) NOT NULL DEFAULT '0',
  attrRanged TINYINT(1) NOT NULL DEFAULT '0',
  attrOnNextSwing TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown3 TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown4 TINYINT(1) NOT NULL DEFAULT '0',
  attrTrade TINYINT(1) NOT NULL DEFAULT '0',
  attrPassive TINYINT(1) NOT NULL DEFAULT '0',
  attrHide TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown8 TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown9 TINYINT(1) NOT NULL DEFAULT '0',
  attrOnNextSwing2 TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown11 TINYINT(1) NOT NULL DEFAULT '0',
  attrDayOnly TINYINT(1) NOT NULL DEFAULT '0',
  attrNightOnly TINYINT(1) NOT NULL DEFAULT '0',
  attrIndoorsOnly TINYINT(1) NOT NULL DEFAULT '0',
  attrOutdoorsOnly TINYINT(1) NOT NULL DEFAULT '0',
  attrNotShapeshift TINYINT(1) NOT NULL DEFAULT '0',
  attrOnlyStealthed TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown18 TINYINT(1) NOT NULL DEFAULT '0',
  attrLevelDamageCalc TINYINT(1) NOT NULL DEFAULT '0',
  attrStopAttack TINYINT(1) NOT NULL DEFAULT '0',
  attrNotAvoidable TINYINT(1) NOT NULL DEFAULT '0',
  attrTrackTarget TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown23 TINYINT(1) NOT NULL DEFAULT '0',
  attrCastOnMount TINYINT(1) NOT NULL DEFAULT '0',
  attrDisabledWhileActive TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown26 TINYINT(1) NOT NULL DEFAULT '0',
  attrCastSit TINYINT(1) NOT NULL DEFAULT '0',
  attrNotInCombat TINYINT(1) NOT NULL DEFAULT '0',
  attrUnaffectedByInvuln TINYINT(1) NOT NULL DEFAULT '0',
  attrUnknown30 TINYINT(1) NOT NULL DEFAULT '0',
  attrNotCancellable TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown0 TINYINT(1) NOT NULL DEFAULT '0',
  attrExDrainAllPower TINYINT(1) NOT NULL DEFAULT '0',
  attrExChanneled TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown3 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown4 TINYINT(1) NOT NULL DEFAULT '0',
  attrExRemainStealth TINYINT(1) NOT NULL DEFAULT '0',
  attrExChanneled2 TINYINT(1) NOT NULL DEFAULT '0',
  attrExNegative TINYINT(1) NOT NULL DEFAULT '0',
  attrExTargetNotInCombat TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown9 TINYINT(1) NOT NULL DEFAULT '0',
  attrExNoThreat TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown11 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown12 TINYINT(1) NOT NULL DEFAULT '0',
  attrExFarSight TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown14 TINYINT(1) NOT NULL DEFAULT '0',
  attrExRemoveAurasOnImmune TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnaffectedBySchoolImmune TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown17 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown18 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown19 TINYINT(1) NOT NULL DEFAULT '0',
  attrExTargetComboPoints TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown21 TINYINT(1) NOT NULL DEFAULT '0',
  attrExRequireComboPoints TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown23 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown24 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown25 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown26 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown27 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown28 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown29 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown30 TINYINT(1) NOT NULL DEFAULT '0',
  attrExUnknown31 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown0 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown1 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2CantReflect TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown3 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown4 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2AutoRepeat TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown6 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown7 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown8 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown9 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown10 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2HealthFunnel TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown12 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown13 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown14 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown15 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown16 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown17 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown18 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2NotRequireShapeshift TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown20 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Shield TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown22 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown23 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown24 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown25 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown26 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown27 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown28 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown29 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown30 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx2Unknown31 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown0 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown1 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown2 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown3 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown4 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown5 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown6 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown7 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3TargetPlayer TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown9 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3RequireMainHand TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3RequireBattleground TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3RequireTargetDeadPlayer TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown13 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown14 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown15 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown16 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3NoAggroOnSuccess TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3UnMissable TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown19 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3PersistWhileDeath TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown21 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3RequireWand TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown23 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3RequireOffHand TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown25 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown26 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown27 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown28 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown29 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown30 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx3Unknown31 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown0 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown1 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown2 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown3 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown4 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown5 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4NotStealable TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown7 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4StackDotModifier TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown9 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4SpellVsExtendCost TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown11 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown12 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown13 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown14 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown15 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4NotInArena TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4RequireArena TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown18 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown19 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown20 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown21 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown22 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown23 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown24 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown25 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4RequireOutland TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown27 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown28 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown29 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown30 TINYINT(1) NOT NULL DEFAULT '0',
  attrEx4Unknown31 TINYINT(1) NOT NULL DEFAULT '0',
  fk_spellfocus int(11) UNSIGNED DEFAULT NULL,
  fk_casterAuraState TINYINT(2) DEFAULT NULL,
  fk_targetAuraState TINYINT(2) DEFAULT NULL,
  spellcasttime INT(11) UNSIGNED DEFAULT '0',
  recoveryTime int(11) NOT NULL DEFAULT '0',
  categoryRecoveryTime int(11) NOT NULL DEFAULT '0',
  `startRecoveryCategory` int(11) NOT NULL DEFAULT '0',
  `startRecoveryCategoryTime` int(11) NOT NULL DEFAULT '0',
  interruptMove TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  interruptDamage TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  interruptInterrupt TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  interruptAutoAttack TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  interruptAbordOnDamage TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown0 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptDamage TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown2 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptMove TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptTurning TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptEnterCombat TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnmounting TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptEnterWater TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptLeavingWater TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnsheathing TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown10 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown11 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown12 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown13 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown14 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown15 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown16 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptMounting TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptStandUp TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptChangeMap TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptImmuneOrLostSelection TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown21 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptUnknown22 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptEnterPvPCombat TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  auraInterruptDirectDamage TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown1 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptDamage TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown4 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptMove TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptTurning TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown7 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown8 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptDamage2 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown10 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown11 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown12 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown13 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown14 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptUnknown15 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  channelInterruptDelay TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procTypeMask INT(11) UNSIGNED NOT NULL DEFAULT '0',
  procOnKilled TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnKill TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeAttackDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeAttackTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeSpellDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeSpellTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessRangedAttackDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessRangedAttackTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessRangedSpellDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessRangedSpellTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessPositiveAOEDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessPositiveAOETaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessAOEDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessAOETaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessPositiveSpellDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessPositiveSpellTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessNegativeSpellDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessNegativeSpellTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessDoTSpellDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessDoTSpellTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnDamageTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnTrapActivation TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeOffHandTaken TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procOnSuccessMeleeOffHandDone TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnNormalHit TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnCriticalHit TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnMiss TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnResist TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnDodge TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnParry TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnBlock TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnEvade TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnImmune TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnDeflect TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnAbsorb  TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnReflect TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOnInterrupt TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExReserved1 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExReserved2 TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExReserved3  TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExAlwaysTrigger TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExOneTimeTrigger TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procExPeriodicPositive TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
  procChance SMALLINT NOT NULL DEFAULT '0',
  `procCharges` SMALLINT NOT NULL DEFAULT '0',
  `maxLevel` SMALLINT NOT NULL DEFAULT '0',
  `baseLevel` SMALLINT NOT NULL DEFAULT '0',
  `spellLevel` SMALLINT NOT NULL DEFAULT '0',
  `maxTargetLevel` SMALLINT NOT NULL DEFAULT '0',
  `maxTargets` SMALLINT NOT NULL DEFAULT '0',
  fk_spellduration SMALLINT DEFAULT NULL,
  fk_power TINYINT(2) NOT NULL DEFAULT '0',
  `cost` int(11) NOT NULL DEFAULT '0',
  `costPct` int(11) NOT NULL DEFAULT '0',
  `costPerLevel` TINYINT(11) NOT NULL DEFAULT '0',
  `costPerSecond` TINYINT(11) NOT NULL DEFAULT '0',
  `costPerSecondPerLevel` TINYINT(11) NOT NULL DEFAULT '0',
  fk_spellrange TINYINT(1) DEFAULT NULL,
  `speed` TINYINT(2) NOT NULL DEFAULT '0',
  fk_modalNextSpell int(11) UNSIGNED DEFAULT NULL,
  `stackAmount` int(11) NOT NULL DEFAULT '0',
  `spellVisualID1` int(11) UNSIGNED NOT NULL DEFAULT'0',
  `spellVisualID2` int(11) UNSIGNED NOT NULL DEFAULT '0',
  `spellIconID` int(11) NOT NULL DEFAULT '0',
  `activeIconID` int(11) NOT NULL DEFAULT '0',
  `spellPriority` int(11) NOT NULL DEFAULT '0',
  `name` text NOT NULL,
  `name1` text NOT NULL,
  `name2` text NOT NULL,
  `name3` text NOT NULL,
  `name4` text NOT NULL,
  `name5` text NOT NULL,
  `name6` text NOT NULL,
  `name7` text NOT NULL,
  `nameSubText` text NOT NULL,
  `nameSubText1` text NOT NULL,
  `nameSubText2` text NOT NULL,
  `nameSubText3` text NOT NULL,
  `nameSubText4` text NOT NULL,
  `nameSubText5` text NOT NULL,
  `nameSubText6` text NOT NULL,
  `nameSubText7` text NOT NULL,
  `description` text NOT NULL,
  `description1` text NOT NULL,
  `description2` text NOT NULL,
  `description3` text NOT NULL,
  `description4` text NOT NULL,
  `description5` text NOT NULL,
  `description6` text NOT NULL,
  `description7` text NOT NULL,
  `auraDescription` text NOT NULL,
  `auraDescription1` text NOT NULL,
  `auraDescription2` text NOT NULL,
  `auraDescription3` text NOT NULL,
  `auraDescription4` text NOT NULL,
  `auraDescription5` text NOT NULL,
  `auraDescription6` text NOT NULL,
  `auraDescription7` text NOT NULL,
  `spellFamily` TINYINT(2) NOT NULL DEFAULT '0',
  `spellFamilyFlags` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  fk_damageType TINYINT(2) DEFAULT NULL,
  fk_preventionType tinyint(2) DEFAULT NULL,
  `stanceBarOrder` TINYINT(2) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table holds all the spell data of the game';


text:
namespace UGC{
class GRAPHICS3D_API UGVector2
{
public:
	Real x;
	Real y;
public:
	UGVector2(){};
	UGVector2(Real fx, Real fy){};
	UGVector2(Real fCoordinates[2]){};
	UGVector2(const UGVector2& vec ){};
	virtual ~UGVector2(){};
public:
	inline Real operator [] ( const UGuint i ) const;

	inline Real& operator [] (const UGuint i);

	inline UGVector2& operator = ( const UGVector2& vec )
	{
		this->x = vec.x;
		this->y =vec.y;
		return* this;
	};

	inline UGbool operator == ( const UGVector2& vec ) const;

	inline UGbool operator != ( const UGVector2& vec ) const;

	inline UGbool operator > ( const UGVector2& vec ) const;

	inline UGbool operator < ( const UGVector2& vec ) const;

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

	inline UGVector2 operator + ( const UGVector2& vec ) const;

	inline UGVector2 operator - ( const UGVector2& vec ) const;

	inline UGVector2 operator * ( const Real fScale ) const;

	inline UGVector2 operator * ( const UGVector2& vec ) const;

	inline UGVector2 operator / ( const Real fScale ) const;

	inline UGVector2 operator - () const;

	inline UGVector2& operator += ( const UGVector2& vec ) ;

	inline UGVector2& operator -= ( const UGVector2& vec );

	inline UGVector2& operator *= ( const Real fScale );

	inline UGVector2& operator /= ( const UGVector2& vec );

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

	inline Real Length() const;

	inline Real SquareLength() const;

	inline UGbool IsZeroLength( void ) const;

	inline UGVector2& Normalize();

	inline Real DotProduct( const UGVector2& vec ) const;

	inline  UGVector2 CrossProduct( const UGVector2 &vec ) const;

	inline void MakeCeil( const UGVector2& vec );

	inline void MakeFloor( const UGVector2& vec );

	inline UGVector2 Perpendicular( void ) const;

	inline UGVector2 NormalisedCopy( void ) const;

	inline UGVector2 Reflect( const UGVector2& normal );

	inline friend std::ostream& operator << ( std::ostream& o, const UGVector2& v );

};
typedef UGArray<UGVector2> UGVec2Array;

}

#endif // !defined(AFX_UGVECTOR2_H__9BA8C114_2B9D_43CB_8632_EB03D0850CE1__INCLUDED_)


text:
package org.apache.tinkerpop.gremlin.process.traversal.translator;

import org.apache.commons.configuration2.ConfigurationConverter;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.tinkerpop.gremlin.process.traversal.Bytecode;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.Pick;
import org.apache.tinkerpop.gremlin.process.traversal.SackFunctions;
import org.apache.tinkerpop.gremlin.process.traversal.Script;
import org.apache.tinkerpop.gremlin.process.traversal.Text;
import org.apache.tinkerpop.gremlin.process.traversal.TextP;
import org.apache.tinkerpop.gremlin.process.traversal.Translator;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.TraversalStrategyProxy;
import org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP;
import org.apache.tinkerpop.gremlin.process.traversal.util.OrP;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.NumberHelper;
import org.apache.tinkerpop.gremlin.util.function.Lambda;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

/**
 * Converts bytecode to a Javascript string of Gremlin.
 *
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public final class JavascriptTranslator implements Translator.ScriptTranslator {

    private final String traversalSource;
    private final TypeTranslator typeTranslator;

    private JavascriptTranslator(final String traversalSource, final TypeTranslator typeTranslator) {
        this.traversalSource = traversalSource;
        this.typeTranslator = typeTranslator;
    }

    /**
     * Creates the translator with a {@code false} argument to {@code withParameters} using
     * {@link #of(String, boolean)}.
     */
    public static JavascriptTranslator of(final String traversalSource) {
        return of(traversalSource, false);
    }

    /**
     * Creates the translator with the {@link DefaultTypeTranslator} passing the {@code withParameters} option to it
     * which will handle type translation in a fashion that should typically increase cache hits and reduce
     * compilation times if enabled at the sacrifice to rewriting of the script that could reduce readability.
     */
    public static JavascriptTranslator of(final String traversalSource, final boolean withParameters) {
        return of(traversalSource, new DefaultTypeTranslator(withParameters));
    }

    /**
     * Creates the translator with a custom {@link TypeTranslator} instance.
     */
    public static JavascriptTranslator of(final String traversalSource, final TypeTranslator typeTranslator) {
        return new JavascriptTranslator(traversalSource, typeTranslator);
    }

    @Override
    public Script translate(final Bytecode bytecode) {
        return typeTranslator.apply(traversalSource, bytecode);
    }

    @Override
    public String getTargetLanguage() {
        return "gremlin-javascript";
    }

    @Override
    public String toString() {
        return StringFactory.translatorString(this);
    }

    @Override
    public String getTraversalSource() {
        return this.traversalSource;
    }

    /**
     * Performs standard type translation for the TinkerPop types to Javascript.
     */
    public static class DefaultTypeTranslator extends AbstractTypeTranslator {

        public DefaultTypeTranslator(final boolean withParameters) {
            super(withParameters);
        }

        @Override
        protected String getNullSyntax() {
            return "null";
        }

        @Override
        protected String getSyntax(final String o) {
            return (o.contains("\"") ? "\"\"\"" + StringEscapeUtils.escapeJava(o) + "\"\"\"" : "\"" + StringEscapeUtils.escapeJava(o) + "\"")
                    .replace("$", "\\$");
        }

        @Override
        protected String getSyntax(final Boolean o) {
            return o.toString();
        }

        @Override
        protected String getSyntax(final Date o) {
            return "new Date(" + o.getTime() + ")";
        }

        @Override
        protected String getSyntax(final Timestamp o) {
            return "new Date(" + o.getTime() + ")";
        }

        @Override
        protected String getSyntax(final UUID o) {
            return "'" + o.toString() + "'";
        }

        @Override
        protected String getSyntax(final Lambda o) {
            return "() => \"" + StringEscapeUtils.escapeEcmaScript(o.getLambdaScript().trim()) + "\"";
        }

        @Override
        protected String getSyntax(final SackFunctions.Barrier o) {
            return "Barrier." + o.toString();
        }

        @Override
        protected String getSyntax(final VertexProperty.Cardinality o) {
            return "Cardinality." + o.toString();
        }

        @Override
        protected String getSyntax(final Pick o) {
            return "Pick." + o.toString();
        }

        @Override
        protected String getSyntax(final Number o) {
            if (o instanceof Float || o instanceof Double) {
                if (NumberHelper.isNaN(o))
                    return "Number.NaN";
                if (NumberHelper.isPositiveInfinity(o))
                    return "Number.POSITIVE_INFINITY";
                if (NumberHelper.isNegativeInfinity(o))
                    return "Number.NEGATIVE_INFINITY";
            }
            return o.toString();
        }

        @Override
        protected Script produceScript(final Set<?> o) {
            return produceScript(new ArrayList<>(o));
        }

        @Override
        protected Script produceScript(final List<?> o) {
            final Iterator<?> iterator = ((List<?>) o).iterator();
            script.append("[");

            while (iterator.hasNext()) {
                final Object nextItem = iterator.next();
                convertToScript(nextItem);
                if (iterator.hasNext())
                    script.append(",").append(" ");
            }

            return script.append("]");
        }

        @Override
        protected Script produceScript(final Map<?, ?> o) {
            script.append("new Map([");
            final Iterator<? extends Map.Entry<?, ?>> itty = ((Map<?, ?>) o).entrySet().iterator();
            while (itty.hasNext()) {
                final Map.Entry<?,?> entry = itty.next();
                script.append("[");
                convertToScript(entry.getKey());
                script.append(",");
                convertToScript(entry.getValue());
                script.append("]");
                if (itty.hasNext())
                    script.append(",");
            }
            return script.append("])");
        }

        @Override
        protected Script produceScript(final Class<?> o) {
            return script.append(o.getCanonicalName());
        }

        @Override
        protected Script produceScript(final Enum<?> o) {
            return script.append(o.getDeclaringClass().getSimpleName() + "." + o.toString());
        }

        @Override
        protected Script produceScript(final Vertex o) {
            script.append("new Vertex(");
            convertToScript(o.id());
            script.append(",");
            convertToScript(o.label());
            return script.append(", null)");
        }

        @Override
        protected Script produceScript(final Edge o) {
            script.append("new Edge(");
            convertToScript(o.id());
            script.append(", new Vertex(");
            convertToScript(o.outVertex().id());
            script.append(",");
            convertToScript(o.outVertex().label());
            script.append(", null),");
            convertToScript(o.label());
            script.append(", new Vertex(");
            convertToScript(o.inVertex().id());
            script.append(",");
            convertToScript(o.inVertex().label());
            return script.append(",null),null)");
        }

        @Override
        protected Script produceScript(final VertexProperty<?> o) {
            script.append("new Property(");
            convertToScript(o.id());
            script.append(",");
            convertToScript(o.label());
            script.append(",");
            convertToScript(o.value());
            script.append(",");
            return script.append("null)");
        }

        @Override
        protected Script produceScript(final TraversalStrategyProxy<?> o) {
            if (o.getConfiguration().isEmpty()) {
                return script.append("new " + o.getStrategyClass().getSimpleName() + "()");
            } else {
                script.append("new " + o.getStrategyClass().getSimpleName() + "(");
                final Map<Object,Object> conf = ConfigurationConverter.getMap(o.getConfiguration());
                script.append("{");
                conf.entrySet().stream().filter(entry -> !entry.getKey().equals(TraversalStrategy.STRATEGY)).forEach(entry -> {
                    script.append(entry.getKey().toString());
                    script.append(":");
                    convertToScript(entry.getValue()).getScript();
                    script.append(",");
                });
                script.setCharAtEnd('}');
                return script.append(")");
            }
        }

        @Override
        protected Script produceScript(final String traversalSource, final Bytecode o) {
            script.append(traversalSource);
            for (final Bytecode.Instruction instruction : o.getInstructions()) {
                final String methodName = instruction.getOperator();
                if (0 == instruction.getArguments().length) {
                    script.append(".").append(resolveSymbol(methodName)).append("()");
                } else {
                    script.append(".").append(resolveSymbol(methodName)).append("(");

                    // have to special case withSack() for Groovy because UnaryOperator and BinaryOperator signatures
                    // make it impossible for the interpreter to figure out which function to call. specifically we need
                    // to discern between:
                    //     withSack(A initialValue, UnaryOperator<A> splitOperator)
                    //     withSack(A initialValue, BinaryOperator<A> splitOperator)
                    // and:
                    //     withSack(Supplier<A> initialValue, UnaryOperator<A> mergeOperator)
                    //     withSack(Supplier<A> initialValue, BinaryOperator<A> mergeOperator)
                    if (methodName.equals(TraversalSource.Symbols.withSack) &&
                            instruction.getArguments().length == 2 && instruction.getArguments()[1] instanceof Lambda) {
                        final String castFirstArgTo = instruction.getArguments()[0] instanceof Lambda ?
                                Supplier.class.getName() : "";
                        final Lambda secondArg = (Lambda) instruction.getArguments()[1];
                        final String castSecondArgTo = secondArg.getLambdaArguments() == 1 ? UnaryOperator.class.getName() :
                                BinaryOperator.class.getName();
                        if (!castFirstArgTo.isEmpty())
                            script.append(String.format("(%s) ", castFirstArgTo));
                        convertToScript(instruction.getArguments()[0]);
                        script.append(", (").append(castSecondArgTo).append(") ");
                        convertToScript(instruction.getArguments()[1]);
                        script.append(",");
                    } else {
                        for (final Object object : instruction.getArguments()) {
                            convertToScript(object);
                            script.append(",");
                        }
                    }
                    script.setCharAtEnd(')');
                }
            }
            return script;
        }

        @Override
        protected Script produceScript(final P<?> p) {
            if (p instanceof TextP) {
                // special case the RegexPredicate since it isn't an enum. toString() for the final default will
                // typically cover implementations (generally worked for Text prior to 3.6.0)
                final BiPredicate<?, ?> tp = p.getBiPredicate();
                if (tp instanceof Text.RegexPredicate) {
                    final String regexToken = ((Text.RegexPredicate) p.getBiPredicate()).isNegate() ? "notRegex" : "regex";
                    script.append("TextP.").append(regexToken).append("(");
                } else if (tp instanceof Text) {
                    script.append("TextP.").append(((Text) p.getBiPredicate()).name()).append("(");
                } else {
                    script.append("TextP.").append(p.getBiPredicate().toString()).append("(");
                }
                convertToScript(p.getValue());
            } else if (p instanceof ConnectiveP) {
                // ConnectiveP gets some special handling because it's reduced to and(P, P, P) and we want it
                // generated the way it was written which was P.and(P).and(P)
                final List<P<?>> list = ((ConnectiveP) p).getPredicates();
                final String connector = p instanceof OrP ? "or" : "and";
                for (int i = 0; i < list.size(); i++) {
                    produceScript(list.get(i));

                    // for the first/last P there is no parent to close
                    if (i > 0 && i < list.size() - 1) script.append(")");

                    // add teh connector for all but last P
                    if (i < list.size() - 1) {
                        script.append(".").append(connector).append("(");
                    }
                }
            } else {
                script.append("P.").append(p.getBiPredicate().toString()).append("(");
                convertToScript(p.getValue());
            }
            script.append(")");
            return script;
        }

        protected String resolveSymbol(final String methodName) {
            return SymbolHelper.toJavascript(methodName);
        }
    }

    static final class SymbolHelper {

        private final static Map<String, String> TO_JS_MAP = new HashMap<>();
        private final static Map<String, String> FROM_JS_MAP = new HashMap<>();

        static {
            TO_JS_MAP.put("from", "from_");
            TO_JS_MAP.put("in", "in_");
            TO_JS_MAP.put("with", "with_");
            //
            TO_JS_MAP.forEach((k, v) -> FROM_JS_MAP.put(v, k));
        }

        private SymbolHelper() {
            // static methods only, do not instantiate
        }

        public static String toJavascript(final String symbol) {
            return TO_JS_MAP.getOrDefault(symbol, symbol);
        }

        public static String toJava(final String symbol) {
            return FROM_JS_MAP.getOrDefault(symbol, symbol);
        }

    }
}


text:
module StrictlySmallerSupport where

import Control.Monad.Bayes.Class

model :: MonadDist m => m Bool
model = do
  x <- bernoulli 0.5
  y <- uniformD (if x then [1, 2] else [1, 2, 3, 4] :: [Int])
  return x


text:
'use strict';

const EventEmitter = require('events').EventEmitter;
const emoji = require('node-emoji');
const _ = require('lodash');
const format = require('util').format;
const chalk = require('chalk');

let log;

const LEVELS = {
  debug: {
    color: chalk.dim,
    emoji: 'beetle',
    errorLevel: 0
  },
  log: {
    color: chalk.white,
    emoji: 'point_right',
    errorLevel: 1
  },
  info: {
    color: chalk.blue,
    emoji: 'bulb',
    errorLevel: 2
  },
  ok: {
    color: chalk.green,
    emoji: 'ok_hand',
    errorLevel: 3
  },
  warn: {
    color: chalk.yellow,
    emoji: 'warning',
    errorLevel: 4
  },
  error: {
    color: chalk.red,
    emoji: 'exclamation',
    errorLevel: 5
  }
};

class Logger extends EventEmitter {
  constructor(logLevel) {
    super();

    this.level = logLevel || 'log';

    _.each(LEVELS, (settings, name) => {
      this[name] = function logMethod() {
        const level = LEVELS[name];
        const args = [
          emoji.get(level.emoji),
          ' ',
          level.color.apply(null, arguments)
        ];
        if (settings.errorLevel >= LEVELS[this.level].errorLevel) {
          console.log.apply(this, args);
        }
        this.emit(level, format(arguments));
      };
    });

    /* eslint consistent-this:0 */
    log = this;
  }

  get level() {
    return this._level;
  }

  set level(value) {
    if (LEVELS[value]) {
      this._level = value;
    } else {
      throw new Error('invalid log level');
    }
  }
}

Logger.Logger = Logger;

module.exports = log || new Logger();


text:
require 'edmunds/api'
require 'edmunds/photo'
require 'edmunds/make'
require 'edmunds/model'
require 'edmunds/model_year'
require 'edmunds/style'

require 'edmunds/equipment'

require 'edmunds/cost_to_own.rb'
require 'edmunds/edmunds_ratings.rb'
require 'edmunds/incentives.rb'
require 'edmunds/maintenance.rb'
require 'edmunds/market_value.rb'
require 'edmunds/vehicle_ratings.rb'
require 'edmunds/vin.rb'


text:
routeName=$1
cd src/app
mkdir $routeName
cd $routeName
touch $routeName.js
touch $routeName.less
touch $routeName.spec.js
touch $routeName.tpl.html
touch README.md
cd ../..


text:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var phonesRoute = require('./routes/phones');
var hrmRoute = require('./routes/hrm');

var port = 4200;

var app = express();
// app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use(express.static(path.join(__dirname, '../dist')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
// app.use('/', indexRoute);
app.use('/api/phones', phonesRoute);
app.use('/api/hrm', hrmRoute);

app.listen(port, function() {
    console.log('server starter on port', port);
});


text:
<?php

namespace Backend\Modules\Menu\Actions;

use Backend\Core\Engine\Base\ActionAdd;
use Backend\Core\Engine\Form;
use Backend\Core\Engine\Language;
use Backend\Core\Engine\Meta;
use Backend\Core\Engine\Model;
use Backend\Modules\Menu\Engine\Model as BackendMenuModel;

/**
 * This is the add category-action, it will display a form to create a new category
 *
 * @author Jesse Dobbelaere <jesse@dobbelaere-ae.be>
 */
class AddCategory extends ActionAdd
{
    /**
     * Execute the action
     */
    public function execute()
    {
        parent::execute();

        $this->loadForm();
        $this->validateForm();

        $this->parse();
        $this->display();
    }

    /**
     * Load the form
     */
    private function loadForm()
    {
        $this->frm = new Form('addCategory');
        $this->frm->addText('title');

        $this->meta = new Meta($this->frm, null, 'title', true);
        $this->meta->setURLCallback('Backend\Modules\Menu\Engine\Model', 'getURLForCategory');
    }

    /**
     * Validate the form
     */
    private function validateForm()
    {
        if ($this->frm->isSubmitted()) {
            $this->frm->cleanupFields();

            // validate fields
            $this->frm->getField('title')->isFilled(Language::err('TitleIsRequired'));
            $this->meta->validate();

            if ($this->frm->isCorrect()) {
                // build item
                $item['title'] = $this->frm->getField('title')->getValue();
                $item['language'] = Language::getWorkingLanguage();
                $item['meta_id'] = $this->meta->save();
                $item['sequence'] = BackendMenuModel::getMaximumCategorySequence() + 1;

                // save the data
                $item['id'] = BackendMenuModel::insertCategory($item);
                Model::triggerEvent($this->getModule(), 'after_add_category', array('item' => $item));

                // everything is saved, so redirect to the overview
                $this->redirect(
                    Model::createURLForAction('categories') .
                    '&report=added-category&var=' . urlencode($item['title']) .
                    '&highlight=row-' . $item['id']
                );
            }
        }
    }
}


text:
#ifndef SQUID_AIODISKFILE_H
#define SQUID_AIODISKFILE_H

#if USE_DISKIO_AIO

#include "DiskIO/DiskFile.h"
#include "async_io.h"
#include "cbdata.h"
#include "SquidString.h"

class AIODiskIOStrategy;

class AIODiskFile : public DiskFile
{

public:

    friend class AIODiskIOStrategy;
    void * operator new (size_t);
    void operator delete (void *);
    AIODiskFile (char const *path, AIODiskIOStrategy *);
    ~AIODiskFile();

    /// \bug the code has this as "IORequestor::Pointer callback"
    virtual void open(int flags, mode_t mode, RefCount<IORequestor> callback);

    virtual void create (int, mode_t, RefCount<IORequestor>);
    virtual void read(ReadRequest *);
    virtual void write(WriteRequest *);
    virtual void close ();
    virtual bool canRead() const;
    virtual bool canWrite() const;

    /* During migration only */
    virtual int getFD() const;

    virtual bool error() const;

    /* Inform callers if there is IO in progress */
    virtual bool ioInProgress() const;

private:
    void error(bool const &);
    int fd;
    String path;
    AIODiskIOStrategy *strategy;
    RefCount<IORequestor> ioRequestor;
    bool closed;
    bool error_;
    CBDATA_CLASS(AIODiskFile);
};

#endif /* USE_DISKIO_AIO */
#endif /* SQUID_AIODISKFILE_H */


text:
(function() {
  'use strict';

  var homeDirectives = angular.module("home.directives", []);

  homeDirectives.directive('videoPlayer', function() {
    return {
      restrict: 'E',
      templateUrl: PARTIALS_ROOT + "/video.html",
      controller: function($scope) {
        $scope.poster = "{0}/img/poster.jpg".format(STATIC_ROOT);

        var plugins = {
          chromecast: {},
        };
        var player = videojs('video', {'plugins': plugins, 'techOrder' : ['Html5', 'ChromecastTech']});

        $scope.$on('$destroy', function () {
          player.dispose();
        });
      }
    };
  });
})();


text:
param (
[string]$sitename,
[string]$CollectionName
)

#####
#Functionality: creates a ConfigMgr collection
#Author: David O'Brien
#date: 25.02.2012
#####
Function Create-Collection($CollectionName)
{
	$CollectionArgs = @{
	Name = $CollectionName;
	CollectionType = "2"; 		# 2 means Collection_Device, 1 means Collection_User
	LimitToCollectionID = "SMS00001"
	}
	Set-WmiInstance -Class SMS_Collection -arguments $CollectionArgs -namespace "root\SMS\Site_$sitename" | Out-Null
}

#####
#Functionality: moves a ConfigMgr collection from one folder to an other
#Author: David O'Brien
#date: 25.02.2012
#####
function move-Collection($SourceContainerNodeID,$collID,$TargetContainerNodeID)
{
$Computer = "."
$Class = "SMS_ObjectContainerItem"
$Method = "MoveMembers"

$MC = [WmiClass]"\\$Computer\ROOT\SMS\site_$($sitename):$Class"

$InParams = $mc.psbase.GetMethodParameters($Method)

$InParams.ContainerNodeID = $SourceContainerNodeID #usually 0 when newly created Collection
$InParams.InstanceKeys = $collID
$InParams.ObjectType = "5000" #5000 for Collection_Device, 5001 for Collection_User
$InParams.TargetContainerNodeID = $TargetContainerNodeID #needs to be evaluated

"Calling SMS_ObjectContainerItem. : MoveMembers with Parameters :"
$inparams.PSBase.properties | select name,Value | format-Table

$R = $mc.PSBase.InvokeMethod($Method, $inParams, $Null)
}

create-collection $CollectionName

#evaluate newly created Collection properties, in this case $_.CollectionID is sufficient
$collection = gwmi -Namespace root\sms\site_$sitename -Class SMS_Collection | where {$_.Name -eq "$collectionName"}
$collID = $collection.CollectionID

$SourceContainerNodeID = "0" #usually 0 when newly created Collection
$TargetContainerNodeID = #Needs to be evaluated, depending on where you want to put the collection!

move-collection $SourceContainerNodeID $collID $TargetContainerNodeID


text:
pug.bin package
===============

Submodules
----------

pug.bin.push module
-------------------

.. automodule:: pug.bin.push
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: pug.bin
    :members:
    :undoc-members:
    :show-inheritance:


text:
package com.shuvam.customviewplayground;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.shuvam.customviewplayground.views.IndicatorView;

public class MainActivity extends AppCompatActivity {

    private IndicatorView mCustomView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final int [] res={R.drawable.ic_android_black_24dp,R.drawable.ic_archive_black_24dp,R.drawable.ic_audiotrack_black_24dp,R.drawable.ic_backup_black_24dp,R.drawable.ic_bluetooth_audio_black_24dp};
        mCustomView = (IndicatorView) findViewById(R.id.customView);
        mCustomView.setResources(res);

        mCustomView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                float section = (int)Math.floor(event.getX()*(res.length)/mCustomView.getWidth());

                Log.d("Touch event value",""+section);
                return false;
            }
        });
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wareninja.opensource</groupId>
  <artifactId>dizlink-api-client</artifactId>
  <version>1.1-SNAPSHOT</version>
  <name>dizlink-api-client</name>
  <description>Java client for Diz.Link API</description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source/>
          <target/>
        </configuration>
      </plugin>
      <!-- NOTE: uncomment below, if you want to generate executable jar -->
      <!--
        <plugin>
             <artifactId>maven-assembly-plugin</artifactId>
             <configuration>
                 <archive>
                     <manifest>
                         <addClasspath>true</addClasspath>
                         <mainClass>ExampleUsage</mainClass>
                     </manifest>
                 </archive>
                 <descriptorRefs>
                     <descriptorRef>jar-with-dependencies</descriptorRef>
                 </descriptorRefs>
             </configuration>
             <executions>
                 <execution>
                     <id>make-my-jar-with-dependencies</id>
                     <phase>package</phase>
                     <goals>
                         <goal>single</goal>
                     </goals>
                 </execution>
             </executions>
         </plugin>
         -->
    </plugins>
  </build>
	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!--
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
		  	<artifactId>commons-lang3</artifactId>
		  	<version>3.2.1</version>
	  	</dependency>
		 -->
	</dependencies>
	<developers>
        <developer>
            <id>WareNinja</id>
            <name>incognito</name>
            <email>yg@wareninja.com</email>
        </developer>
    </developers>
    <licenses>
        <license>
            <name>Apache License Version 2.0</name>
            <url>LICENSE.txt</url>
        </license>
    </licenses>
</project>


text:
cask "guilded" do
  version "1.0.9134613"
  sha256 "0b595eb3999cd23d4035b613c92e97d78328f3cd3ed7a6a1d5659a87f35475b6"

  url "https://s3-us-west-2.amazonaws.com/www.guilded.gg/AppBuilds/mac/Guilded-#{version}-release.dmg",
      verified: "s3-us-west-2.amazonaws.com/www.guilded.gg/AppBuilds/mac/"
  name "Guilded"
  desc "Group chat platform"
  homepage "https://www.guilded.gg/"

  livecheck do
    url "https://s3-us-west-2.amazonaws.com/www.guilded.gg/AppBuilds/mac/release-mac.yml"
    strategy :electron_builder do |data|
      data["version"].tr("-release", "")
    end
  end

  app "Guilded.app"

  zap trash: [
    "~/Library/Application Support/Guilded",
    "~/Library/Logs/Guilded",
    "~/Library/Preferences/com.electron.guilded.plist",
    "~/Library/Saved Application State/com.electron.guilded.savedState",
  ]
end


text:
package com.ikvant.loriapp.database.timeentry;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;

import java.util.Date;
import java.util.List;

/**
 * Created by ikvant.
 */

@Dao
public interface TimeEntryDao {
    @Query("SELECT * FROM TimeEntry WHERE deleted=:deleted ORDER BY date DESC LIMIT :size OFFSET :offset")
    List<TimeEntry> loadAll(Boolean deleted, int offset, int size);

    @Query("DELETE FROM TimeEntry WHERE id=:id")
    void delete(String id);

    @Query("SELECT * FROM TimeEntry WHERE id=:id LIMIT 1")
    TimeEntry load(String id);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void save(TimeEntry entry);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveAll(TimeEntry... timeEntries);

    @Query("SELECT * FROM TimeEntry WHERE sync=:sync")
    List<TimeEntry> loadUnSync(boolean sync);

    @Query("DELETE FROM TimeEntry")
    void deleteAll();

    @Query("SELECT * FROM TimeEntry WHERE description LIKE'%'||:text||'%'")
    List<TimeEntry> findByText(String text);

    @Query("SELECT * FROM TimeEntry WHERE date BETWEEN :from AND :to")
    List<TimeEntry> findByDate(Date from, Date to);
}


text:
<?php namespace Indemnity83\SolderToolbelt;

use GuzzleHttp\Client;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ChoiceQuestion;

class ModCommand extends Command {

	/**
	 * Configure the command options.
	 *
	 * @return void
	 */
	protected function configure()
	{
		$this->setName('mod')
			->setDescription('Work with mods on the TechnicSolder site')
			->addArgument(
					'action',
					InputArgument::REQUIRED,
					'info, get, pack'
				)
			->addArgument(
				 'mod',
				 InputArgument::REQUIRED,
				 'The filename or slug of the mod you wish to request'
			)
			->addArgument(
				 'version',
				 InputArgument::OPTIONAL,
				 'Specific modversion you wish to view'
			);
	}

	/**
	 * Execute the command.
	 *
	 * @param	\Symfony\Component\Console\Input\InputInterface	$input
	 * @param	\Symfony\Component\Console\Output\OutputInterface	$output
	 * @return void
	 */
	public function execute(InputInterface $input, OutputInterface $output)
	{
		$commandAction = $input->getArgument('action');
		$modName = $input->getArgument('mod');
		$modVersion = $input->getArgument('version');

		switch( $commandAction ) {
			case 'info':
				if( file_exists(realpath($modName)) ) {
					$this->infoModFile($output, realpath($modName));
				} else {
					$this->infoModApi($output, $modName, $modVersion);
				}
				break;
			case 'get':
				$this->getMod($output, $modName, $modVersion);
				break;
			case 'pack':
				$this->packModFile($input, $output, realpath($modName));
				break;
			default:
				throw new \InvalidArgumentException('Invalid arguments');
		}
	}

	private function infoModFile($output, $modFile)
	{
		$zip = new \ZipArchive;
		if ($zip->open($modFile) === TRUE) {
			$modList = json_decode($zip->getFromName('mcmod.info'));
			$zip->close();
		} else {
			throw new \OutOfBoundsException('Could not identify mod');
		}

		if( isset($modList->modlist)) {
			$modList = $modList->modlist;
		}

		foreach( $modList as $mod ) {
			$output->writeln('');
			$rows = array();
			foreach( $mod as $key => $value ) {
				if( is_array($value) ) {
					$rows[] = array("<info>$key</info>", implode($value,"\n"));
				} else {
					$rows[] = array("<info>$key</info>", mb_strimwidth($value, 0, 60, "..."));
				}
			}
			$output->writeln("<comment>{$mod->name}:</comment>");
			$table = new Table($output);
			$table
					->setRows($rows)
					->setStyle('compact')
					->render();
		}

		$output->writeln('');
	}

	private function infoModApi($output, $slug, $version)
	{
		displayServerInfo($output);

		$apiClient = new Client();
		$appConfig = solder_config();

		$apiResponse = $apiClient->get($appConfig->api . '/mod/' . $slug . '/' . $version)->json();
		if(isset($apiResponse['error'])) {
			throw new \Exception($apiResponse['error']);
		}

		$rows = array();
		foreach( $apiResponse as $key => $value ) {
			if( $key == 'versions' ) {
				$rows[] = array("<info>$key</info>", implode($value,"\n"));
			} else {
				$rows[] = array("<info>$key</info>", mb_strimwidth($value, 0, 60, "..."));
			}
		}

		$output->writeln('');
		$output->writeln("<comment>Mod:</comment>");
		$table = new Table($output);
		$table
				->setRows($rows)
				->setStyle('compact')
				->render();
	}

	private function getMod($output, $slug, $version)
	{
		if($slug == '' || $version == '') {
			throw new \InvalidArgumentException('Invalid arguments');
		}

		$apiClient = new Client();
		$appConfig = solder_config();

		$apiResponse = $apiClient->get($appConfig->api . '/mod/' . $slug . '/' . $version)->json();
		if(isset($apiResponse['error'])) {
			throw new \Exception($apiResponse['error']);
		}

		$url = $apiResponse['url'];
		$filename = basename($url);
		$md5 = $apiResponse['md5'];

		downloadFile($url, $filename, $output, $md5);
		$output->writeln('');

		if( md5_file($filename) != $md5 ) {
			throw new \Exception('Hash dosen\'t match');
		}
	}

	private function packModFile($input, $output, $modFile)
	{
		$helper = $this->getHelper('question');
		$zip = new \ZipArchive;

		if ($zip->open($modFile) === TRUE) {
			$modList = json_decode($zip->getFromName('mcmod.info'));
			$zip->close();
		} else {
			throw new \OutOfBoundsException('Could not identify mod');
		}

		if( isset($modList->modlist)) {
			$modList = $modList->modlist;
		}

		if( count($modList) > 1 ) {
			$options = array();
			foreach( $modList as $mod ) {
				$options[] = $mod->name;
			}

			$question = new ChoiceQuestion(
				"Mod List contains multiple definitions, please select the defintion to be used (default is `{$options[0]}`) ",
				$options,
				'0'
			);
			$question->setErrorMessage('%s is invalid.');
			$response = $helper->ask($input, $output, $question);
			$modsRow = array_search($response, $options);
			$output->writeln('');
		} else {
			$modsRow = 0;
		}

		if( isset($modList[$modsRow]->name) ) {
			$modName = $modList[$modsRow]->name;
		} else {
			$question = new Question('Please enter the name of the mod: ');
			$modName = $helper->ask($input, $output, $question);
		}

		if( isset($modList[$modsRow]->version) ) {
			$modVersion = $modList[$modsRow]->version;
		} else {
			$question = new Question('Please enter the version of the mod: ');
			$modVersion = $helper->ask($input, $output, $question);
		}

		if( isset($modList[$modsRow]->mcversion) ) {
			$mcVersion = $modList[$modsRow]->mcversion;
		} else {
			$question = new Question('Please enter the version of minecraft this is for: ');
			$mcVersion = $helper->ask($input, $output, $question);
		}

		$modSlug = slug($modName);
		$packName = $modSlug . '-' . $mcVersion  . '-' . $modVersion;
		$fileName = $modSlug . DIRECTORY_SEPARATOR . $packName . '.zip';
		$output->writeln("Archive: $packName.zip");

		if(!is_dir($modSlug)){
			$output->writeln("   creating: $modSlug" . DIRECTORY_SEPARATOR);
			mkdir($modSlug);
		}

		if ($zip->open($fileName, \ZipArchive::OVERWRITE) === TRUE) {
			$output->writeln("   deflating: " . basename($modFile));
			$zip->addFile($modFile, 'mods' . DIRECTORY_SEPARATOR . basename($modFile));
			$zip->close();
		} else {
			throw new \OutOfBoundsException('Could not write to file');
		}

	}

}