text:
copyright:

  years: 2016
lastupdated: "2016-12-01"

---

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

# Mise à niveau et unification des comptes de facturation {{site.data.keyword.Bluemix_notm}} et SoftLayer
{: #softlayerlink}

Si vous disposez d'un compte d'essai {{site.data.keyword.Bluemix_notm}} et voulez accéder au tableau de bord Infrastructure, vous devez
procéder à la mise à niveau vers un compte {{site.data.keyword.Bluemix_notm}} Paiement à la carte. Vous devez également effectuer une mise à niveau si vous voulez utiliser d'autres ressources payantes qui ne sont pas disponible dans un compte d'essai ou une fois votre compte d'essai arrivé à expiration.

Vous pouvez unifier vos comptes de facturation {{site.data.keyword.Bluemix_notm}} et SoftLayer en les liant. Lorsque vous liez vos
comptes, vous êtes facturé via {{site.data.keyword.Bluemix_notm}} pour l'utilisation de ressources {{site.data.keyword.Bluemix_notm}} et
SoftLayer.

**Attention :** Un compte d'abonnement {{site.data.keyword.Bluemix_notm}} ne peut pas être lié à un compte SoftLayer. Pour
accéder au tableau de bord Infrastructure, vous devez créer un compte Paiement
à la carte, un second compte qui est automatiquement lié à un
compte SoftLayer. Vous recevez ensuite deux factures, une pour chaque compte {{site.data.keyword.Bluemix_notm}}. Même
si vos ressources d'infrastructure sont facturées dans un compte Paiement à la
carte distinct, elles peuvent être utilisées avec les applications et les
services de votre compte d'abonnement. Ainsi, si vous activez un service Watson
dans votre compte d'abonnement, vous pouvez copier les données d'identification
du service et les ajouter à votre application Bare Metal provenant de
votre compte Paiement à la carte. {:shortdesc}

## Mise à niveau vers un compte {{site.data.keyword.Bluemix_notm}} Paiement à la carte
{: #upgradetopayg}

Lorsque vous vous connectez à {{site.data.keyword.Bluemix_notm}} avec un compte d'essai, vous ne parvenez pas à accéder au tableau de bord
Infrastructure {{site.data.keyword.Bluemix_notm}}. Si vous voulez que vos applications utilisent les ressources d'infrastructure, vous devez
procéder à la mise à niveau vers un compte Paiement à la carte.

Pour mettre à niveau votre compte d'essai vers un compte {{site.data.keyword.Bluemix_notm}} Paiement à la carte, procédez comme suit :

 1. Cliquez sur **Compte** > **Facturation**.
 2. Ensuite, cliquez sur **Ajouter une carte de crédit**.
 3. Entrez les détails de facturation requis.
 4. Lisez et acceptez les dispositions relatives au compte Paiement à la carte.
 5. Une fois que vous avez terminé, cliquez sur **Mise à niveau**.

Une fois la mise à niveau vers un compte Paiement à la carte effectuée, les options **Infrastructure** sont
répertoriées dans le **catalogue** {{site.data.keyword.Bluemix_notm}}. Si vous utilisez plus que la franchise, vous recevrez
une facture {{site.data.keyword.Bluemix_notm}} mensuelle. Celle-ci est en dollars américains (USD) et détaille le prix des ressources.

## Unification de vos comptes {{site.data.keyword.Bluemix_notm}} et SoftLayer
{: #unifyingaccounts}

Vous pouvez unifier vos comptes {{site.data.keyword.Bluemix_notm}} et SoftLayer afin d'utiliser les ressources combinées. Si vous liez
vos comptes {{site.data.keyword.Bluemix_notm}} et Softlayer, vous ne recevrez qu'une seule facture {{site.data.keyword.Bluemix_notm}}. Si vous possédez un compte {{site.data.keyword.Bluemix_notm}}, la facturation via {{site.data.keyword.Bluemix_notm}} pour des ressources
SoftLayer est appliquée lors du nouveau cycle de facturation qui démarre après la liaison des comptes.

**Important :** tous les comptes liés dans {{site.data.keyword.Bluemix_notm}} doivent être du type Paiement à la carte. Vous pouvez
en créer un nouveau ou utiliser un compte Paiement à la carte existant. Vous pouvez aussi lier un compte d'essai existant, mais celui-ci sera transformé en
compte Paiement à la carte. Les comptes d'abonnement {{site.data.keyword.Bluemix_notm}} ne peuvent pas être liés.

Une fois vos comptes liés :

* Vous devez utiliser vos données d'identification IBMid pour accéder à votre compte SoftLayer et à votre compte
{{site.data.keyword.Bluemix_notm}}.
* Les remises SoftLayer existantes sont appliquées à tous les prix {{site.data.keyword.Bluemix_notm}}.
* Vous recevez une facture en dollars américains (USD).
* Vous pouvez surveiller l'utilisation de vos ressources {{site.data.keyword.BluSoftlayer}} dans l'interface utilisateur
{{site.data.keyword.Bluemix_notm}}.

**Attention :** la liaison des comptes est irréversible.

Si vous disposez d'un compte SoftLayer et voulez lier des comptes SoftLayer et {{site.data.keyword.Bluemix_notm}}, procédez comme suit :

 1. Depuis le {{site.data.keyword.slportal}}, cliquez sur **Link a {{site.data.keyword.Bluemix_notm}}** Account.
 2. Lisez et acceptez les dispositions pour la liaison de comptes SoftLayer et {{site.data.keyword.Bluemix_notm}}.
 3. A l'invite, indiquez l'adresse électronique associée à votre compte {{site.data.keyword.Bluemix_notm}}. Si vous ne disposez pas d'un compte
{{site.data.keyword.Bluemix_notm}}, indiquez l'adresse électronique que vous voulez utiliser, puis suivez les instructions pour être invité dans
{{site.data.keyword.Bluemix_notm}} et créer un compte.

Vous devez être défini comme utilisateur principal dans le compte SoftLayer pour lier des comptes.

Après avoir lié vos comptes, le lien **Accéder à {{site.data.keyword.Bluemix_notm}}** est disponible dans l'en-tête
global SoftLayer. En cliquant sur ce lien, vous accédez à la page de connexion de {{site.data.keyword.Bluemix_notm}}. De plus, le lien
**SoftLayer** est désormais disponible dans l'en-tête {{site.data.keyword.Bluemix_notm}}. En cliquant sur ce lien, vous accédez à la
page d'accueil du {{site.data.keyword.slportal}} dans une nouvelle fenêtre.

Les offres d'infrastructure {{site.data.keyword.Bluemix_notm}} sont connectées à un réseau à trois niveaux qui segmente le trafic public,
privé et de gestion. Les offres d'infrastructure sur un compte {{site.data.keyword.Bluemix_notm}} de client peuvent transférer les données dans une infrastructure de ce type sur le réseau privé gratuitement. Les offres d'infrastructure, telles que les serveurs Bare Metal, les serveurs virtuels et le stockage en cloud se connectent à d'autres
applications et services figurant dans le catalogue {{site.data.keyword.Bluemix_notm}}, comme des services Watson, des conteneurs ou des contextes
d'exécution, sur le réseau public. Le transfert de données entre ces deux types d'offre est mesuré et facturé en fonction des tarifs de bande
passante de réseau public
standard.

## Invitation de membres d'équipe SoftLayer dans {{site.data.keyword.Bluemix_notm}}
{: #invite_users}

Vous pouvez inviter vos membres d'équipe SoftLayer à rejoindre {{site.data.keyword.Bluemix_notm}} lorsque vous liez les comptes
{{site.data.keyword.Bluemix_notm}} et SoftLayer. Vous pouvez également inviter plus tard des membres d'équipe SoftLayer depuis l'interface utilisateur de
{{site.data.keyword.Bluemix_notm}}.
{:shortdesc}

Depuis l'interface utilisateur de {{site.data.keyword.Bluemix_notm}}, vous pouvez inviter en bloc tous les membres de votre compte
SoftLayer ou sélectionner des membres individuels. Lorsque vous invitez des membres de l'équipe, vous devez les affecter au rôle de
compte {{site.data.keyword.Bluemix_notm}}. Pour plus d'informations sur les différents rôles dans
{{site.data.keyword.Bluemix_notm}}, voir
[Rôles utilisateur](https://console.ng.bluemix.net/docs/admin/users_roles.html#userrolesinfo).

Vous devez être défini comme utilisateur principal dans le compte SoftLayer pour inviter des membres d'équipe dans le compte {{site.data.keyword.Bluemix_notm}}.

Pour inviter des membres d'équipe dans {{site.data.keyword.Bluemix_notm}}, procédez comme suit :

 1. Cliquez sur **Compte** > **Inviter des membres d'équipe**.
 2. Cliquez sur **Ajouter** pour vous authentifier dans votre compte SoftLayer et afficher la liste des membres d'équipe de votre
compte {{site.data.keyword.BluSoftlayer}}.
 3. Sélectionnez les membres de l'équipe à ajouter et cliquez sur **Envoyer**.

Le membre de l'équipe reçoit un courrier électronique incluant un lien **Join the organization**. Si le membre d'équipe ne dispose
pas d'un
IBMid, il est redirigé vers une page d'enregistrement. Il peut alors soumettre des informations de base et créer son compte
{{site.data.keyword.Bluemix_notm}}.

Pour plus d'informations sur l'invitation de membres d'équipe via l'interface utilisateur de {{site.data.keyword.Bluemix_notm}}, voir
[Invitation de membres d'équipe](https://console.ng.bluemix.net/docs/admin/users_roles.html#inviteteammembers).

## Passage à l'IBMid
{: #ibmid_switch}

Désormais, l'authentification dans SoftLayer utilise l'IBMid afin de fournir une connexion unique pour {{site.data.keyword.Bluemix_notm}}. Si
vous possédez un compte SoftLayer, vous pouvez passez à un IBMid. Un assistant de migration vous guidera tout au long de cette opération.
{:shortdesc}

Si vous avez commencé le passage à l'IBMid, vous pouvez l'annuler tant que vous ne l'avez pas terminé. Toutefois, vous serez à nouveau invité à passer à l'IBMid à votre prochaine connexion.

Pour passer de votre nom d'utilisateur SoftLayer existant à un IBMid, procédez comme suit :

 1. Dans le {{site.data.keyword.slportal}}, accédez à la page Edit User Profile et cliquez sur **Switch to
IBMid**.
 2. Suivez les invites de l'assistant de migration afin de créer votre IBMid. Une fois l'IBMid créé, vous ne pouvez pas changer l'ID, qui est
une adresse électronique. Vous pouvez mettre à jour l'adresse électronique associée à votre profil, mais par défaut, cette valeur est la même que celle
que vous avez définie pour votre IBMid. Une fois l'assistant terminé, un courrier électronique vous est envoyé.
 3. Lorsque vous recevez le courrier électronique, suivez le lien ou copiez l'adresse URL dans un navigateur et entrez votre code
d'enregistrement. Le code est valable pendant sept jours et ne peut être utilisé qu'une fois.  Vous ne pouvez pas le réutiliser.
 Après avoir configuré le
lien utilisateur IBMid vers SoftLayer, vous ne pouvez vous connecter à votre compte qu'avec l'IBMid.  Dans la boîte de dialogue de connexion, vous devez
cliquer sur le bouton **Log in with IBMid** au lieu d'entrer votre nom d'utilisateur et votre mot de passe SoftLayer.

Si vous êtes un nouveau client, vous êtes invité à entrer une adresse électronique pour votre compte IBMid existant, ou à créer un compte IBMid,
lorsque vous passez au paiement de votre commande.

### Mappage de plusieurs comptes SoftLayer à un IBMid
{: #map_multiple_accounts}

Vous pouvez associer un IBMid à plusieurs comptes SoftLayer en utilisant une adresse électronique IBMid existante lorsque vous configurez le
compte. Vous ne pouvez mapper qu'un seul utilisateur SoftLayer pour chaque compte à l'IBMid unique. L'IBMid doit être unique dans chaque compte SoftLayer. Toutefois,
un utilisateur disposant de l'accès à plusieurs comptes SoftLayer peut utiliser un IBMid afin d'accéder à plusieurs comptes SoftLayer.

Par exemple, un IBMid peut être mappé à un utilisateur principal dans les comptes A et B, et à un utilisateur supplémentaire dans les comptes C et D.
L'un des comptes mappés à cet IBMid est le compte par défaut.  En général, le compte par défaut est celui qui a été mappé en premier à l'IBMid. Toutefois,
vous pouvez changer le compte par défaut à l'aide d'une fonction de changement de compte dans le portail client.

Pour un utilisateur disposant d'un accès IBMid à plusieurs comptes pour lesquels l'authentification à deux facteurs est activée, un code de
vérification pour l'authentification à deux facteurs approprié par compte est requis lors de la connexion de compte et du changement de compte.

## Utilisation de services {{site.data.keyword.Bluemix_notm}} avec des actifs SoftLayer
{: #bluemix_services}

Vous pouvez utiliser sans difficulté des services {{site.data.keyword.Bluemix_notm}} publics reposant sur des API avec vos actifs
SoftLayer. Toutes les API sont
sécurisées et chiffrées de sorte que vos données sont protégées.
{:shortdesc}

Par exemple, souhaiteriez-vous ajouter des capacités cognitives de Watson à vos applications s'exécutant sur des serveurs sans système d'exploitation depuis
SoftLayer ? Vous pouvez ajouter un service tel que {{site.data.keyword.personalityinsightsshort}} pour mieux comprendre l'utilisateur de
votre application
en quatre étapes simples :

1. Recherchez le service dans le catalogue {{site.data.keyword.Bluemix_notm}}.
2. Mettez en place une instance du service en quelques clics.
3. Configurez le service pour son exécution avec le code existant en copiant les données d'identification au service et en les ajoutant à votre application.
4. Après la mise à jour de l'application, déployez sa nouvelle version dans votre infrastructure SoftLayer.

Vous pouvez dégager des enseignements *Insights and Cognitive* en appelant des API Watson
depuis vos applications dans SoftLayer pour les personnaliser davantage. Vous pouvez également utiliser les services *Data and Analytics* pour exploiter des analyses à hautes performances dans vos
applications. Vous pouvez aussi opter pour une approche DBaaS (database-as-a-service) où la gestion est laissée à {{site.data.keyword.Bluemix_notm}}.

Modernisez votre développement d'applications en utilisant des conteneurs avec des services tels que
{{site.data.keyword.activedeployshort}} et {{site.data.keyword.deliverypipeline}}. Vous pourrez ensuite utiliser le service
{{site.data.keyword.vpn_short}} pour communiquer avec SoftLayer et
connecter votre conteneur dans un réseau privé au réseau privé SoftLayer. Tous les frais d'utilisation des ressources de traitement et des services sont reflétés dans votre facture
{{site.data.keyword.Bluemix_notm}}.

### Services {{site.data.keyword.Bluemix_notm}} reposant sur des API
Certains services {{site.data.keyword.Bluemix_notm}} ne peuvent pas être utilisés avec SoftLayer. Les services suivants peuvent être configurés pour
s'exécuter avec votre code d'application :
* {{site.data.keyword.alchemyapishort}}
* {{site.data.keyword.alertnotificationshort}}
* {{site.data.keyword.sparks}}
* {{site.data.keyword.appseccloudshort}}
* {{site.data.keyword.blockchain}}
* {{site.data.keyword.cloudant}}
* {{site.data.keyword.conceptinsightsshort}}
* {{site.data.keyword.iotmapinsights_short}}
* {{site.data.keyword.dashdbshort}}
* {{site.data.keyword.dialogshort}}
* {{site.data.keyword.documentconversionshort}}
* {{site.data.keyword.twittershort}}
* {{site.data.keyword.weather_short}}
* {{site.data.keyword.iotdriverinsights_short}}
* {{site.data.keyword.geospatialshort_Geospatial}}
* {{site.data.keyword.graphshort}}
* {{site.data.keyword.iotelectronics}}
* {{site.data.keyword.languagetranslationshort}}
* {{site.data.keyword.messagehub}}
* {{site.data.keyword.mqa}}
* {{site.data.keyword.mobileappbuilder_short}}
* {{site.data.keyword.mql}}
* {{site.data.keyword.nlclassifierlshort}}
* {{site.data.keyword.objectstorageshort}}
* {{site.data.keyword.personalityinsightsshort}}
* {{site.data.keyword.presenceinsightsshort}}
* {{site.data.keyword.relationshipextractionshort}}
* {{site.data.keyword.retrieveandrankshort}}
* {{site.data.keyword.servicediscoveryshort}}
* {{site.data.keyword.speechtotextshort}}
* {{site.data.keyword.sqldb}}
* {{site.data.keyword.streaminganalyticsshort}}
* {{site.data.keyword.texttospeechshort}}
* {{site.data.keyword.toneanalyzershort}}
* {{site.data.keyword.tradeoffanalyticsshort}}
* {{site.data.keyword.visualinsightsshort}}
* {{site.data.keyword.visualrecognitionshort}}
* {{site.data.keyword.workflow}}
* {{site.data.keyword.workloadscheduler}}

**Remarque :** certains plans ne sont pas disponibles pour ces services. Seuls les plans activés pour les comptes Paiement à la
carte peuvent être utilisés avec des comptes liés. Toutefois,
vous pouvez utiliser n'importe quel plan pour l'un de ces services si vous disposez d'un compte {{site.data.keyword.Bluemix_notm}} séparé qui est facturé
à part.

## Facturation pour l'utilisation de {{site.data.keyword.Bluemix_notm}} lorsque les comptes sont liés
{: #bill_usage}

Une fois que vous avez lié vos comptes {{site.data.keyword.Bluemix_notm}} et SoftLayer, le prochain cycle de facturation sera imputé dans une
seule facture {{site.data.keyword.Bluemix_notm}}.
{:shortdesc}

Votre cycle d'utilisation de {{site.data.keyword.Bluemix_notm}} est basé sur le mois calendaire et votre compte sera facturé chaque mois le jour de facturation établi pour votre contrat de crédit. Avec SoftLayer, votre cycle d'utilisation débute au moment où vous avez commencé à utiliser SoftLayer, et vous êtes donc facturé chaque mois le
même jour où vous avez ouvert votre compte SoftLayer.

Lorsque vos comptes sont liés, votre utilisation de {{site.data.keyword.Bluemix_notm}} continue d'être mesurée pour le cycle du mois en
cours et vous
serez facturé pour cette utilisation sur une facture {{site.data.keyword.Bluemix_notm}}. A compter du premier jour du mois suivant, vos frais
{{site.data.keyword.Bluemix_notm}} et SoftLayer seront combinés sur votre facture {{site.data.keyword.Bluemix_notm}}.

Par exemple, si vous avez lié vos comptes le 16 avril, vous recevrez une facture Bluemix pour votre consommation en avril. Selon la date à
laquelle vous avez lié vos comptes, vous pouvez recevoir une facture distincte pour votre utilisation de SoftLayer. Votre utilisation en mai pour SoftLayer
et {{site.data.keyword.Bluemix_notm}} sera facturée via votre compte {{site.data.keyword.Bluemix_notm}}.

![Récapitulatif de la liaison de comptes Bluemix et SoftLayer](images/BluemixSoftLayerBill.svg)

Une fois vos factures liées, votre facture {{site.data.keyword.Bluemix_notm}} répertorie les prix de chaque ressource que vous avez
utilisée sous les en-têtes suivants :

* **Bare Metal Servers and Attached Services**
* **Virtual Servers and Attached Services**
* **Unattached Services**

Pour plus d'informations sur l'affichage de l'utilisation de {{site.data.keyword.Bluemix_notm}}, voir
[Affichage des détails de l'utilisation](https://console.ng.bluemix.net/docs/pricing/index.html#usage).


text:
@interface SimpleStack : NSObject

- (id)pop;
- (void)push:(id)item;
- (NSUInteger)count;

@end

redpajama_set_name: RedPajamaGithub


text:
import sbt._
import Keys._
import sbtassembly.AssemblyPlugin.autoImport._
import sbtdocker.DockerPlugin.autoImport._
import sbtdocker.mutable.Dockerfile

object settings {

  private val compilerFlags = Seq(
    "-deprecation",
    "-Xfuture",
    "-encoding", "UTF-8",
    "-Ywarn-adapted-args",
    "-Ywarn-dead-code",
    "-Ywarn-inaccessible",
    "-unchecked",
    "-feature",
    "-language:higherKinds",
    "-language:implicitConversions",
    "-language:postfixOps",
    "-Xfatal-warnings"
  )

  private val lintingFlags = Seq(
    "-Xlint:adapted-args",
    "-Xlint:nullary-override",
    "-Xlint:package-object-classes",
    "-Xlint:unsound-match",
    "-Xlint:missing-interpolator",
    "-Xlint:doc-detached",
    "-Xlint:private-shadow",
    "-Xlint:poly-implicit-overload",
    "-Xlint:option-implicit",
    "-Xlint:type-parameter-shadow",
    "-Xlint:delayedinit-select",
    "-Xlint:by-name-right-associative",
    "-Xlint:stars-align",
    "-Xlint:nullary-unit",
    "-Xlint:inaccessible"
  )

  def compiler = Seq(
    scalacOptions in Compile ++= compilerFlags ++ lintingFlags
  )

  def resolution = Seq(
    resolvers ++= dependencies.repositories
  )

  def dockerSettings = Seq(
      dockerfile in docker := {
        val artifact: File = assembly.value
        val artifactTargetPath = s"/bin/${artifact.name}"
        new Dockerfile {
          from("tcnksm/centos-java")
          maintainer(organization.value)
          add(artifact, artifactTargetPath)
          expose(8080)
          entryPoint("java", "-jar", artifactTargetPath)
        }
      },
    imageNames in docker := Seq(
      ImageName(
        namespace = Some(organization.value.filterNot(_ == '.')),
        repository = organization.value.filterNot(_ == '.'),
        tag = Some("latest")
      )
    ),
    buildOptions in docker := BuildOptions(
      removeIntermediateContainers = BuildOptions.Remove.Always
    )
  )

  def publishing = Seq(
    publishTo := bintray.getPublishResolver(System.getenv("BINTRAY_USER"), System.getenv("BINTRAY_API_KEY"), moduleName.value, false)
  )

  def common = console.settings ++ compiler ++ resolution ++ publishing

  def deploy = dockerSettings
}


text:
using Screener.Portfolio.Model.Common;

namespace Screener.Portfolio.Model.Brokerage.CommisionTerms
{
    public abstract class ComissionCalculationProcedureBase
    {
        public abstract CurrencyValue Calculate(CurrencyValue currentComission, TradeActionRequest actionRequest);
    }
}


text:
/*!
  JS group for layout Home or Post
  Chirpy v2.3
  https://github.com/cotes2020/jekyll-theme-chirpy
  © 2020 Cotes Chung
  MIT License
*/

{% include_relative _commons.js %}

{% include_relative _utils/timeago.js %}

{% if site.google_analytics.pv.enabled %}

  {% include_relative data/pv-data.js %}

  {% include_relative _utils/pageviews.js %}

  {% include_relative lib/_countUp.min.js %}

{% endif %}


text:
package edu.mayo.mprc.swift.configuration.server;

import com.google.common.base.Objects;
import edu.mayo.mprc.config.ResourceConfig;

/**
 * Reference to a property within a particular resource configuration.
 * This is used in {@link ConfigurationData} to bind listeners to specific properties.
 */
class ConcreteProperty {
	private ResourceConfig resourceConfig;
	private String propertyName;

	ConcreteProperty(final ResourceConfig resourceConfig, final String propertyName) {
		this.resourceConfig = resourceConfig;
		this.propertyName = propertyName;
	}

	public ResourceConfig getResourceConfig() {
		return resourceConfig;
	}

	public String getPropertyName() {
		return propertyName;
	}

	@Override
	public boolean equals(final Object o) {
		if (this == o) {
			return true;
		}
		if (!(o instanceof ConcreteProperty)) {
			return false;
		}

		final ConcreteProperty that = (ConcreteProperty) o;
		return Objects.equal(resourceConfig, that.resourceConfig) &&
				Objects.equal(propertyName, that.propertyName);
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(resourceConfig, propertyName);
	}
}


text:
import React from 'react';
import { Link, IndexLink } from 'react-router';

const Header = () => {
    return (
        <div className="header">
            <IndexLink to="/" activeClassName="active">Home</IndexLink>
            {" | "}
            <Link to="/quizList" activeClassName="active">Quizzes</Link>
            {" | "}
            <Link to="/about" activeClassName="active">About</Link>
        </div>
    );
};

export default Header;


text:
<?php

namespace CarBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * Class DynamicsType
 * @package CarBundle\Form
 */
class DynamicsType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('acceleration', NumberType::class, [
                'translation_domain' => 'DynamicsType',
                'label' => 'form.label.acceleration',
                'required' => false,
                'attr' => [
                    'placeholder' => 'form.placeholder.acceleration',
                ],
                'constraints' => [
                    new NotBlank()
                ]
            ])
            ->add('speed', NumberType::class, [
                'translation_domain' => 'DynamicsType',
                'label' => 'form.label.speed',
                'required' => false,
                'attr' => [
                    'placeholder' => 'form.placeholder.speed',
                ],
                'constraints' => [
                    new NotBlank()
                ]
            ])
        ;
    }

    /**
     * Configuration options
     *
     * Set configuration params for current form
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'CarBundle\Entity\Dynamics'
        ]);
    }

    /**
     * Get block prefix
     *
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'car_bundle_dynamics_type';
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Vigilante Game Framework: VRenderGroup Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Vigilante Game Framework
    1.0.0.8

A 2D/3D C++ Game Framework using SFML.

Public Types |
Public Member Functions |
Public Attributes |
Protected Member Functions |
Protected Attributes |
List of all members

VRenderGroup Class Reference

Processes a group of objects and renders them all to a sprite object.
 More...

#include <VRenderGroup.h>

Inheritance diagram for VRenderGroup:

  <map id="VRenderGroup_map" name="VRenderGroup_map">
<area href="class_v_group.html" title="An object management class that stores a set of objects to be updated and rendered in a batch..." alt="VGroup" shape="rect" coords="53,56,150,80"/>
<area href="class_v_base.html" title="Base class that any object that updates or renders (including VState) inherints from this class..." alt="VBase" shape="rect" coords="53,0,150,24"/>
<area href="class_v3_d_scene.html" title="A special VRenderGroup for Rendering 3D scenes. " alt="V3DScene" shape="rect" coords="0,168,97,192"/>
<area href="class_v_trail_area.html" title="Special VRenderGroup that applies a trail to objects it contains within the area. ..." alt="VTrailArea" shape="rect" coords="107,168,204,192"/>
</map>

Public Types

enum  	VRenderGroupOutside : unsigned char { VRENDERGROUP_NO,
VRENDERGROUP_BEFORE,
VRENDERGROUP_AFTER,
VRENDERGROUP_BOTH
 }

 	Options for what happens to renderable objects outside of the VRenderGroup area.  More...

typedef VGroup 	VSUPERCLASS

 	Used to call parent class functions when they are overrided in class.

 Public Types inherited from VGroup

typedef VBase 	VSUPERCLASS

 	Used to call parent class functions when they are overrided in class.

Public Member Functions

 	VRenderGroup (unsigned int maxSize=0)

 	Default Constructor for VRenderGroup.

 	VRenderGroup (float x, float y, unsigned int width, unsigned int height, unsigned int maxSize=0)

 	VRenderGroup (sf::Vector2f position, sf::Vector2u size, unsigned int maxSize=0)

virtual void 	Resize (int width, int height)

virtual const sf::Texture & 	GetTexture ()

virtual void 	Destroy () override

 	Removes and/or destroys all objects inside the group and sprite before destroying extra data. (If an object is referenced in another VGroup, the object won't be destroyed)

virtual void 	Kill () override

 	Kills all living objects before killing the group and the sprite themselves.

virtual void 	Revive () override

 	Revives all dead objects before reviving the group and the sprite themselves.

virtual void 	Update (float dt) override

virtual void 	Draw (sf::RenderTarget &RenderTarget) override

 Public Member Functions inherited from VGroup

 	VGroup (unsigned int maxSize=0)

int 	Length ()

VBase * 	Add (VBase *object)

VBase * 	Remove (VBase *object, bool splice=false)

VBase * 	FirstAvailable ()

int 	FirstNULL ()

VBase * 	FirstExisting ()

VBase * 	FirstAlive ()

VBase * 	FirstDead ()

int 	CountAlive (bool Recursive=false)

int 	CountDead (bool Recursive=false)

VBase * 	GetRandom (int min=0, int max=0)

void 	ForEach (std::function< void(VBase *)> function, bool recursive=false)

void 	ForEachAlive (std::function< void(VBase *)> function, bool recursive=false)

void 	ForEachDead (std::function< void(VBase *)> function, bool recursive=false)

void 	ForEachExists (std::function< void(VBase *)> function, bool recursive=false)

VBase * 	GetGroupItem (int index)

template<class T >

T * 	GetGroupItemAsType (int index)

int 	GetIndexOfItem (VBase *object)

void 	OrganiseNULLS ()

 	Sort nullptr members to the bottom of the group.

void 	Swap (int a, int b)

void 	Sort (std::function< bool(VBase *, VBase *)> func)

void 	Reverse ()

 	Reverse order of group.

void 	Clear ()

 	Clears the whole group (does not destroy any of the members, that must be done using the Destroy method).

Public Attributes

std::unique_ptr< VSprite > 	Sprite = nullptr

 	The sprite that the group will render to. Refer to this if you want to transform the render output.

sf::Color 	BackgroundTint = sf::Color::Transparent

 	The background colour the sprite will have.

std::unique_ptr< VPostEffectBase > 	PostEffect = nullptr

 	Post Process (Shader) Effect to apply to the sprite.

std::unique_ptr< VCamera > 	Camera = nullptr

 	Camera for the sprite's render view.

bool 	RenderViewTransform = true

 	If true, the camera's render view will be transformed based on the sprite's current transform, else it will use the camera's render view.

VRenderGroupOutside 	RenderOutside = VRENDERGROUP_NO

 	If true, the content data would also be rendered outside of the sprite area. Used if you want an effect to apply to a specific area.

 Public Attributes inherited from VBase

bool 	active = true

 	Base can be updated using Update if true.

bool 	visible = true

 	Base can be rendered using Draw if true.

bool 	alive = true

 	Helper member that is mainly used filter out behaviours to objects which aren't alive in the scene.

bool 	exists = true

 	Base can be updated and rendered if true, else it would no longer be treated as being part of the scene.

VType 	type = NONE

 	Base object type, typically set in the constructor of an inherited object to specify what type it is.

uint32_t 	RefCount = 0

 	Counts the amount of times the object is referenced in groups, ensures an object is only destroyed when no longer part of a single group.

Protected Member Functions

void 	updateTransform ()

 	Updates the transform.

void 	updateTexture (const sf::Texture &texture)

 	Update the texture of the sprite.

Protected Attributes

sf::RenderTexture 	renderTex

 	The sf::RenderTexture to render all the objects to.

sf::RenderTexture 	postProcessTex

 	Another sf::RenderTexture for outputting the post process effect onto.

 Protected Attributes inherited from VGroup

std::vector< VBase * > 	members

 	VBase List.

int 	length = 0

 	Current amount of members in the list.

unsigned int 	MaxSize = 0

 	Maximum Size of the list, used if VGroup is set to have a fixed size.

Additional Inherited Members

 Static Public Member Functions inherited from VBase

static const wchar_t * 	VString (const char *fmt,...)

static void 	VLog (const char *fmt,...)

static void 	VLogError (const char *fmt,...)

static void 	VClearLog ()

Detailed Description

Processes a group of objects and renders them all to a sprite object.

Member Enumeration Documentation

◆ VRenderGroupOutside

          enum VRenderGroup::VRenderGroupOutside : unsigned char

Options for what happens to renderable objects outside of the VRenderGroup area.

Enumerator

VRENDERGROUP_NO
No rendering.

VRENDERGROUP_BEFORE
Render before the final texture of the render group.

VRENDERGROUP_AFTER
Render after the final texture of the render group.

VRENDERGROUP_BOTH
Render both before and after the final texture of the render group.

Constructor & Destructor Documentation

◆ VRenderGroup() [1/2]

          VRenderGroup::VRenderGroup
          (
          float
          x,

          float
          y,

          unsigned int
          width,

          unsigned int
          height,

          unsigned int
          maxSize = 0

          )

Parameters

x	X position of the sprite.

y	Y position of the sprite

width	Width of the sprite (also sets the width of the render area).

height	Height of the sprite (also sets the height of the render area).

maxSize	The fixed length of the group. If 0, then the VGroup has no limit in size.

◆ VRenderGroup() [2/2]

          VRenderGroup::VRenderGroup
          (
          sf::Vector2f
          position,

          sf::Vector2u
          size,

          unsigned int
          maxSize = 0

          )

Parameters

position	Position of the sprite.

size	Size of the sprite (also sets the size of the render area).

maxSize	The fixed length of the group. If 0, then the VGroup has no limit in size.

Member Function Documentation

◆ Draw()

          virtual void VRenderGroup::Draw
          (
          sf::RenderTarget &
          RenderTarget	)

overridevirtual

Renders all alive and visible objects in the group.

Parameters

RenderTarget	The game's sf::RenderTarget object to render data onto.

Reimplemented from VGroup.

Reimplemented in V3DScene, and VTrailArea.

◆ GetTexture()

          virtual const sf::Texture& VRenderGroup::GetTexture
          (
          	)

virtual

Returns

The sprite's texture after the scene is rendered to it.

Reimplemented in V3DScene.

◆ Resize()

          virtual void VRenderGroup::Resize
          (
          int
          width,

          int
          height

          )

virtual

Resizes sprite and render area of the group.

Parameters

width	Width of the sprite and texture area.

height	Height of the sprite and texture area.

Reimplemented in V3DScene.

◆ Update()

          virtual void VRenderGroup::Update
          (
          float
          dt	)

overridevirtual

Updates all alive and active objects in the group.

Parameters

dt	Delta Time between the previous and current frame.

Reimplemented from VGroup.

Reimplemented in V3DScene.

The documentation for this class was generated from the following file:

D:/Development/Libs/Vigilante-Game-Framework/VFrame/VRenderGroup.h

<address class="footer">
Generated by

 1.8.14
</address>


text:
def remove_duplicates(input_list=[]):
    output = []
    while(len(input_list)>0):
        tmp = input_list.pop()
        if tmp not in output:
            output.append(tmp)
    return(output)


text:
@implementation MSVChatUserMe

@end


text:
using System.Collections.Generic;

namespace Umbraco.Core.Models
{
    /// <summary>
    /// Defines a ContentType, which Content is based on
    /// </summary>
    public interface IContentType : IContentTypeComposition
    {
        /// <summary>
        /// Gets the default Template of the ContentType
        /// </summary>
        ITemplate DefaultTemplate { get; }

        /// <summary>
        /// Gets or Sets a list of Templates which are allowed for the ContentType
        /// </summary>
        IEnumerable<ITemplate> AllowedTemplates { get; set; }

        /// <summary>
        /// Determines if AllowedTemplates contains templateId
        /// </summary>
        /// <param name="templateId">The template id to check</param>
        /// <returns>True if AllowedTemplates contains the templateId else False</returns>
        bool IsAllowedTemplate(int templateId);

        /// <summary>
        /// Determines if AllowedTemplates contains templateId
        /// </summary>
        /// <param name="templateAlias">The template alias to check</param>
        /// <returns>True if AllowedTemplates contains the templateAlias else False</returns>
        bool IsAllowedTemplate(string templateAlias);

        /// <summary>
        /// Sets the default template for the ContentType
        /// </summary>
        /// <param name="template">Default <see cref="ITemplate"/></param>
        void SetDefaultTemplate(ITemplate template);

        /// <summary>
        /// Removes a template from the list of allowed templates
        /// </summary>
        /// <param name="template"><see cref="ITemplate"/> to remove</param>
        /// <returns>True if template was removed, otherwise False</returns>
        bool RemoveTemplate(ITemplate template);

        /// <summary>
        /// Creates a deep clone of the current entity with its identity/alias and it's property identities reset
        /// </summary>
        /// <param name="newAlias"></param>
        /// <returns></returns>
        IContentType DeepCloneWithResetIdentities(string newAlias);
    }
}


text:
require 'spec_helper'

describe CrystalForge::DocumentParser::AST do
  let!(:extended_class) { Class.new(described_class) }

  describe 'asts' do
    subject { described_class.asts }
    it { is_expected.to be_kind_of(Array) }
    it { is_expected.to include(extended_class) }
  end

  describe 'understands?' do
    it 'raises a NotImplemented error explaining how it should be used' do
      expect { described_class.understands? 'garblooly goop' }.to raise_error(NotImplementedError)
    end
  end

  describe 'parse' do
    let(:subclass_ast) { double(:parser, understands?: false, new: :foobar) }
    before do
      expect(described_class).to receive(:asts).and_return([subclass_ast])
    end

    it 'raises an exception when no subclassed parser understands it' do
      expect { described_class.parse('ahoy!') }
        .to raise_error(CrystalForge::DocumentParser::AST::UnkownFormat)
    end

    it 'uses the first subclassed ast that understands the format' do
      expect(subclass_ast).to receive(:understands?).and_return(true)
      expect(described_class.parse('ahoy!')).to eq(:foobar)
    end
  end
end


text:
static int CompareColors(const void* p1, const void* p2) {
  const uint32_t a = *(const uint32_t*)p1;
  const uint32_t b = *(const uint32_t*)p2;
  assert(a != b);
  return (a < b) ? -1 : 1;
}

// If number of colors in the image is less than or equal to MAX_PALETTE_SIZE,
// creates a palette and returns true, else returns false.
static int AnalyzeAndCreatePalette(const WebPPicture* const pic,
                                   uint32_t palette[MAX_PALETTE_SIZE],
                                   int* const palette_size) {
  int i, x, y, key;
  int num_colors = 0;
  uint8_t in_use[MAX_PALETTE_SIZE * 4] = { 0 };
  uint32_t colors[MAX_PALETTE_SIZE * 4];
  static const uint32_t kHashMul = 0x1e35a7bd;
  const uint32_t* argb = pic->argb;
  const int width = pic->width;
  const int height = pic->height;
  uint32_t last_pix = ~argb[0];   // so we're sure that last_pix != argb[0]

  for (y = 0; y < height; ++y) {
    for (x = 0; x < width; ++x) {
      if (argb[x] == last_pix) {
        continue;
      }
      last_pix = argb[x];
      key = (kHashMul * last_pix) >> PALETTE_KEY_RIGHT_SHIFT;
      while (1) {
        if (!in_use[key]) {
          colors[key] = last_pix;
          in_use[key] = 1;
          ++num_colors;
          if (num_colors > MAX_PALETTE_SIZE) {
            return 0;
          }
          break;
        } else if (colors[key] == last_pix) {
          // The color is already there.
          break;
        } else {
          // Some other color sits there.
          // Do linear conflict resolution.
          ++key;
          key &= (MAX_PALETTE_SIZE * 4 - 1);  // key mask for 1K buffer.
        }
      }
    }
    argb += pic->argb_stride;
  }

  // TODO(skal): could we reuse in_use[] to speed up EncodePalette()?
  num_colors = 0;
  for (i = 0; i < (int)(sizeof(in_use) / sizeof(in_use[0])); ++i) {
    if (in_use[i]) {
      palette[num_colors] = colors[i];
      ++num_colors;
    }
  }

  qsort(palette, num_colors, sizeof(*palette), CompareColors);
  *palette_size = num_colors;
  return 1;
}

static int AnalyzeEntropy(const uint32_t* argb,
                          int width, int height, int argb_stride,
                          double* const nonpredicted_bits,
                          double* const predicted_bits) {
  int x, y;
  const uint32_t* last_line = NULL;
  uint32_t last_pix = argb[0];    // so we're sure that pix_diff == 0

  VP8LHistogramSet* const histo_set = VP8LAllocateHistogramSet(2, 0);
  if (histo_set == NULL) return 0;

  for (y = 0; y < height; ++y) {
    for (x = 0; x < width; ++x) {
      const uint32_t pix = argb[x];
      const uint32_t pix_diff = VP8LSubPixels(pix, last_pix);
      if (pix_diff == 0) continue;
      if (last_line != NULL && pix == last_line[x]) {
        continue;
      }
      last_pix = pix;
      {
        const PixOrCopy pix_token = PixOrCopyCreateLiteral(pix);
        const PixOrCopy pix_diff_token = PixOrCopyCreateLiteral(pix_diff);
        VP8LHistogramAddSinglePixOrCopy(histo_set->histograms[0], &pix_token);
        VP8LHistogramAddSinglePixOrCopy(histo_set->histograms[1],
                                        &pix_diff_token);
      }
    }
    last_line = argb;
    argb += argb_stride;
  }
  *nonpredicted_bits = VP8LHistogramEstimateBitsBulk(histo_set->histograms[0]);
  *predicted_bits = VP8LHistogramEstimateBitsBulk(histo_set->histograms[1]);
  VP8LFreeHistogramSet(histo_set);
  return 1;
}

static int AnalyzeAndInit(VP8LEncoder* const enc, WebPImageHint image_hint) {
  const WebPPicture* const pic = enc->pic_;
  const int width = pic->width;
  const int height = pic->height;
  const int pix_cnt = width * height;
  // we round the block size up, so we're guaranteed to have
  // at max MAX_REFS_BLOCK_PER_IMAGE blocks used:
  int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;
  assert(pic != NULL && pic->argb != NULL);

  enc->use_palette_ =
      AnalyzeAndCreatePalette(pic, enc->palette_, &enc->palette_size_);

  if (image_hint == WEBP_HINT_GRAPH) {
    if (enc->use_palette_ && enc->palette_size_ < MAX_COLORS_FOR_GRAPH) {
      enc->use_palette_ = 0;
    }
  }

  if (!enc->use_palette_) {
    if (image_hint == WEBP_HINT_PHOTO) {
      enc->use_predict_ = 1;
      enc->use_cross_color_ = 1;
    } else {
      double non_pred_entropy, pred_entropy;
      if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride,
                          &non_pred_entropy, &pred_entropy)) {
        return 0;
      }
      if (pred_entropy < 0.95 * non_pred_entropy) {
        enc->use_predict_ = 1;
        enc->use_cross_color_ = 1;
      }
    }
  }
  if (!VP8LHashChainInit(&enc->hash_chain_, pix_cnt)) return 0;

  // palette-friendly input typically uses less literals
  //  -> reduce block size a bit
  if (enc->use_palette_) refs_block_size /= 2;
  VP8LBackwardRefsInit(&enc->refs_[0], refs_block_size);
  VP8LBackwardRefsInit(&enc->refs_[1], refs_block_size);

  return 1;
}

static int GetHuffBitLengthsAndCodes(
    const VP8LHistogramSet* const histogram_image,
    HuffmanTreeCode* const huffman_codes) {
  int i, k;
  int ok = 0;
  uint64_t total_length_size = 0;
  uint8_t* mem_buf = NULL;
  const int histogram_image_size = histogram_image->size;
  int max_num_symbols = 0;
  uint8_t* buf_rle = NULL;
  HuffmanTree* huff_tree = NULL;

  // Iterate over all histograms and get the aggregate number of codes used.
  for (i = 0; i < histogram_image_size; ++i) {
    const VP8LHistogram* const histo = histogram_image->histograms[i];
    HuffmanTreeCode* const codes = &huffman_codes[5 * i];
    for (k = 0; k < 5; ++k) {
      const int num_symbols =
          (k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits_) :
          (k == 4) ? NUM_DISTANCE_CODES : 256;
      codes[k].num_symbols = num_symbols;
      total_length_size += num_symbols;
    }
  }

  // Allocate and Set Huffman codes.
  {
    uint16_t* codes;
    uint8_t* lengths;
    mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,
                                       sizeof(*lengths) + sizeof(*codes));
    if (mem_buf == NULL) goto End;

    codes = (uint16_t*)mem_buf;
    lengths = (uint8_t*)&codes[total_length_size];
    for (i = 0; i < 5 * histogram_image_size; ++i) {
      const int bit_length = huffman_codes[i].num_symbols;
      huffman_codes[i].codes = codes;
      huffman_codes[i].code_lengths = lengths;
      codes += bit_length;
      lengths += bit_length;
      if (max_num_symbols < bit_length) {
        max_num_symbols = bit_length;
      }
    }
  }

  buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);
  huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,
                                           sizeof(*huff_tree));
  if (buf_rle == NULL || huff_tree == NULL) goto End;

  // Create Huffman trees.
  for (i = 0; i < histogram_image_size; ++i) {
    HuffmanTreeCode* const codes = &huffman_codes[5 * i];
    VP8LHistogram* const histo = histogram_image->histograms[i];
    VP8LCreateHuffmanTree(histo->literal_, 15, buf_rle, huff_tree, codes + 0);
    VP8LCreateHuffmanTree(histo->red_, 15, buf_rle, huff_tree, codes + 1);
    VP8LCreateHuffmanTree(histo->blue_, 15, buf_rle, huff_tree, codes + 2);
    VP8LCreateHuffmanTree(histo->alpha_, 15, buf_rle, huff_tree, codes + 3);
    VP8LCreateHuffmanTree(histo->distance_, 15, buf_rle, huff_tree, codes + 4);
  }
  ok = 1;
 End:
  WebPSafeFree(huff_tree);
  WebPSafeFree(buf_rle);
  if (!ok) {
    WebPSafeFree(mem_buf);
    memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));
  }
  return ok;
}

static void StoreHuffmanTreeOfHuffmanTreeToBitMask(
    VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {
  // RFC 1951 will calm you down if you are worried about this funny sequence.
  // This sequence is tuned from that, but more weighted for lower symbol count,
  // and more spiking histograms.
  static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {
    17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  };
  int i;
  // Throw away trailing zeros:
  int codes_to_store = CODE_LENGTH_CODES;
  for (; codes_to_store > 4; --codes_to_store) {
    if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
      break;
    }
  }
  VP8LWriteBits(bw, 4, codes_to_store - 4);
  for (i = 0; i < codes_to_store; ++i) {
    VP8LWriteBits(bw, 3, code_length_bitdepth[kStorageOrder[i]]);
  }
}

static void ClearHuffmanTreeIfOnlyOneSymbol(
    HuffmanTreeCode* const huffman_code) {
  int k;
  int count = 0;
  for (k = 0; k < huffman_code->num_symbols; ++k) {
    if (huffman_code->code_lengths[k] != 0) {
      ++count;
      if (count > 1) return;
    }
  }
  for (k = 0; k < huffman_code->num_symbols; ++k) {
    huffman_code->code_lengths[k] = 0;
    huffman_code->codes[k] = 0;
  }
}

static void StoreHuffmanTreeToBitMask(
    VP8LBitWriter* const bw,
    const HuffmanTreeToken* const tokens, const int num_tokens,
    const HuffmanTreeCode* const huffman_code) {
  int i;
  for (i = 0; i < num_tokens; ++i) {
    const int ix = tokens[i].code;
    const int extra_bits = tokens[i].extra_bits;
    VP8LWriteBits(bw, huffman_code->code_lengths[ix], huffman_code->codes[ix]);
    switch (ix) {
      case 16:
        VP8LWriteBits(bw, 2, extra_bits);
        break;
      case 17:
        VP8LWriteBits(bw, 3, extra_bits);
        break;
      case 18:
        VP8LWriteBits(bw, 7, extra_bits);
        break;
    }
  }
}

// 'huff_tree' and 'tokens' are pre-alloacted buffers.
static void StoreFullHuffmanCode(VP8LBitWriter* const bw,
                                 HuffmanTree* const huff_tree,
                                 HuffmanTreeToken* const tokens,
                                 const HuffmanTreeCode* const tree) {
  uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };
  uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };
  const int max_tokens = tree->num_symbols;
  int num_tokens;
  HuffmanTreeCode huffman_code;
  huffman_code.num_symbols = CODE_LENGTH_CODES;
  huffman_code.code_lengths = code_length_bitdepth;
  huffman_code.codes = code_length_bitdepth_symbols;

  VP8LWriteBits(bw, 1, 0);
  num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);
  {
    uint32_t histogram[CODE_LENGTH_CODES] = { 0 };
    uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };
    int i;
    for (i = 0; i < num_tokens; ++i) {
      ++histogram[tokens[i].code];
    }

    VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);
  }

  StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);
  ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);
  {
    int trailing_zero_bits = 0;
    int trimmed_length = num_tokens;
    int write_trimmed_length;
    int length;
    int i = num_tokens;
    while (i-- > 0) {
      const int ix = tokens[i].code;
      if (ix == 0 || ix == 17 || ix == 18) {
        --trimmed_length;   // discount trailing zeros
        trailing_zero_bits += code_length_bitdepth[ix];
        if (ix == 17) {
          trailing_zero_bits += 3;
        } else if (ix == 18) {
          trailing_zero_bits += 7;
        }
      } else {
        break;
      }
    }
    write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);
    length = write_trimmed_length ? trimmed_length : num_tokens;
    VP8LWriteBits(bw, 1, write_trimmed_length);
    if (write_trimmed_length) {
      const int nbits = VP8LBitsLog2Ceiling(trimmed_length - 1);
      const int nbitpairs = (nbits == 0) ? 1 : (nbits + 1) / 2;
      VP8LWriteBits(bw, 3, nbitpairs - 1);
      assert(trimmed_length >= 2);
      VP8LWriteBits(bw, nbitpairs * 2, trimmed_length - 2);
    }
    StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);
  }
}

// 'huff_tree' and 'tokens' are pre-alloacted buffers.
static void StoreHuffmanCode(VP8LBitWriter* const bw,
                             HuffmanTree* const huff_tree,
                             HuffmanTreeToken* const tokens,
                             const HuffmanTreeCode* const huffman_code) {
  int i;
  int count = 0;
  int symbols[2] = { 0, 0 };
  const int kMaxBits = 8;
  const int kMaxSymbol = 1 << kMaxBits;

  // Check whether it's a small tree.
  for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {
    if (huffman_code->code_lengths[i] != 0) {
      if (count < 2) symbols[count] = i;
      ++count;
    }
  }

  if (count == 0) {   // emit minimal tree for empty cases
    // bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0
    VP8LWriteBits(bw, 4, 0x01);
  } else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {
    VP8LWriteBits(bw, 1, 1);  // Small tree marker to encode 1 or 2 symbols.
    VP8LWriteBits(bw, 1, count - 1);
    if (symbols[0] <= 1) {
      VP8LWriteBits(bw, 1, 0);  // Code bit for small (1 bit) symbol value.
      VP8LWriteBits(bw, 1, symbols[0]);
    } else {
      VP8LWriteBits(bw, 1, 1);
      VP8LWriteBits(bw, 8, symbols[0]);
    }
    if (count == 2) {
      VP8LWriteBits(bw, 8, symbols[1]);
    }
  } else {
    StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);
  }
}

static void WriteHuffmanCode(VP8LBitWriter* const bw,
                             const HuffmanTreeCode* const code,
                             int code_index) {
  const int depth = code->code_lengths[code_index];
  const int symbol = code->codes[code_index];
  VP8LWriteBits(bw, depth, symbol);
}

static void StoreImageToBitMask(
    VP8LBitWriter* const bw, int width, int histo_bits,
    VP8LBackwardRefs* const refs,
    const uint16_t* histogram_symbols,
    const HuffmanTreeCode* const huffman_codes) {
  // x and y trace the position in the image.
  int x = 0;
  int y = 0;
  const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  while (VP8LRefsCursorOk(&c)) {
    const PixOrCopy* const v = c.cur_pos;
    const int histogram_ix = histogram_symbols[histo_bits ?
                                               (y >> histo_bits) * histo_xsize +
                                               (x >> histo_bits) : 0];
    const HuffmanTreeCode* const codes = huffman_codes + 5 * histogram_ix;
    if (PixOrCopyIsCacheIdx(v)) {
      const int code = PixOrCopyCacheIdx(v);
      const int literal_ix = 256 + NUM_LENGTH_CODES + code;
      WriteHuffmanCode(bw, codes, literal_ix);
    } else if (PixOrCopyIsLiteral(v)) {
      static const int order[] = { 1, 2, 0, 3 };
      int k;
      for (k = 0; k < 4; ++k) {
        const int code = PixOrCopyLiteral(v, order[k]);
        WriteHuffmanCode(bw, codes + k, code);
      }
    } else {
      int bits, n_bits;
      int code, distance;

      VP8LPrefixEncode(v->len, &code, &n_bits, &bits);
      WriteHuffmanCode(bw, codes, 256 + code);
      VP8LWriteBits(bw, n_bits, bits);

      distance = PixOrCopyDistance(v);
      VP8LPrefixEncode(distance, &code, &n_bits, &bits);
      WriteHuffmanCode(bw, codes + 4, code);
      VP8LWriteBits(bw, n_bits, bits);
    }
    x += PixOrCopyLength(v);
    while (x >= width) {
      x -= width;
      ++y;
    }
    VP8LRefsCursorNext(&c);
  }
}

// Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31
static int EncodeImageNoHuffman(VP8LBitWriter* const bw,
                                const uint32_t* const argb,
                                VP8LHashChain* const hash_chain,
                                VP8LBackwardRefs refs_array[2],
                                int width, int height, int quality) {
  int i;
  int ok = 0;
  int max_tokens = 0;
  VP8LBackwardRefs* refs;
  HuffmanTreeToken* tokens = NULL;
  HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };
  const uint16_t histogram_symbols[1] = { 0 };    // only one tree, one symbol
  VP8LHistogramSet* const histogram_image = VP8LAllocateHistogramSet(1, 0);
  HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
        3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
  if (histogram_image == NULL || huff_tree == NULL) goto Error;

  // Calculate backward references from ARGB image.
  refs = VP8LGetBackwardReferences(width, height, argb, quality, 0, 1,
                                   hash_chain, refs_array);
  if (refs == NULL) {
    goto Error;
  }
  // Build histogram image and symbols from backward references.
  VP8LHistogramStoreRefs(refs, histogram_image->histograms[0]);

  // Create Huffman bit lengths and codes for each histogram image.
  assert(histogram_image->size == 1);
  if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
    goto Error;
  }

  // No color cache, no Huffman image.
  VP8LWriteBits(bw, 1, 0);

  // Find maximum number of symbols for the huffman tree-set.
  for (i = 0; i < 5; ++i) {
    HuffmanTreeCode* const codes = &huffman_codes[i];
    if (max_tokens < codes->num_symbols) {
      max_tokens = codes->num_symbols;
    }
  }

  tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
  if (tokens == NULL) goto Error;

  // Store Huffman codes.
  for (i = 0; i < 5; ++i) {
    HuffmanTreeCode* const codes = &huffman_codes[i];
    StoreHuffmanCode(bw, huff_tree, tokens, codes);
    ClearHuffmanTreeIfOnlyOneSymbol(codes);
  }

  // Store actual literals.
  StoreImageToBitMask(bw, width, 0, refs, histogram_symbols, huffman_codes);
  ok = 1;

 Error:
  WebPSafeFree(tokens);
  WebPSafeFree(huff_tree);
  VP8LFreeHistogramSet(histogram_image);
  WebPSafeFree(huffman_codes[0].codes);
  return ok;
}

static int EncodeImageInternal(VP8LBitWriter* const bw,
                               const uint32_t* const argb,
                               VP8LHashChain* const hash_chain,
                               VP8LBackwardRefs refs_array[2],
                               int width, int height, int quality,
                               int cache_bits, int histogram_bits) {
  int ok = 0;
  const int use_2d_locality = 1;
  const int use_color_cache = (cache_bits > 0);
  const uint32_t histogram_image_xysize =
      VP8LSubSampleSize(width, histogram_bits) *
      VP8LSubSampleSize(height, histogram_bits);
  VP8LHistogramSet* histogram_image =
      VP8LAllocateHistogramSet(histogram_image_xysize, cache_bits);
  int histogram_image_size = 0;
  size_t bit_array_size = 0;
  HuffmanTree* huff_tree = NULL;
  HuffmanTreeToken* tokens = NULL;
  HuffmanTreeCode* huffman_codes = NULL;
  VP8LBackwardRefs refs;
  VP8LBackwardRefs* best_refs;
  uint16_t* const histogram_symbols =
      (uint16_t*)WebPSafeMalloc(histogram_image_xysize,
                                sizeof(*histogram_symbols));
  assert(histogram_bits >= MIN_HUFFMAN_BITS);
  assert(histogram_bits <= MAX_HUFFMAN_BITS);

  VP8LBackwardRefsInit(&refs, refs_array[0].block_size_);
  if (histogram_image == NULL || histogram_symbols == NULL) {
    VP8LFreeHistogramSet(histogram_image);
    WebPSafeFree(histogram_symbols);
    return 0;
  }

  // 'best_refs' is the reference to the best backward refs and points to one
  // of refs_array[0] or refs_array[1].
  // Calculate backward references from ARGB image.
  best_refs = VP8LGetBackwardReferences(width, height, argb, quality,
                                        cache_bits, use_2d_locality,
                                        hash_chain, refs_array);
  if (best_refs == NULL || !VP8LBackwardRefsCopy(best_refs, &refs)) {
    goto Error;
  }
  // Build histogram image and symbols from backward references.
  if (!VP8LGetHistoImageSymbols(width, height, &refs,
                                quality, histogram_bits, cache_bits,
                                histogram_image,
                                histogram_symbols)) {
    goto Error;
  }
  // Create Huffman bit lengths and codes for each histogram image.
  histogram_image_size = histogram_image->size;
  bit_array_size = 5 * histogram_image_size;
  huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,
                                                   sizeof(*huffman_codes));
  if (huffman_codes == NULL ||
      !GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
    goto Error;
  }
  // Free combined histograms.
  VP8LFreeHistogramSet(histogram_image);
  histogram_image = NULL;

  // Color Cache parameters.
  VP8LWriteBits(bw, 1, use_color_cache);
  if (use_color_cache) {
    VP8LWriteBits(bw, 4, cache_bits);
  }

  // Huffman image + meta huffman.
  {
    const int write_histogram_image = (histogram_image_size > 1);
    VP8LWriteBits(bw, 1, write_histogram_image);
    if (write_histogram_image) {
      uint32_t* const histogram_argb =
          (uint32_t*)WebPSafeMalloc(histogram_image_xysize,
                                    sizeof(*histogram_argb));
      int max_index = 0;
      uint32_t i;
      if (histogram_argb == NULL) goto Error;
      for (i = 0; i < histogram_image_xysize; ++i) {
        const int symbol_index = histogram_symbols[i] & 0xffff;
        histogram_argb[i] = 0xff000000 | (symbol_index << 8);
        if (symbol_index >= max_index) {
          max_index = symbol_index + 1;
        }
      }
      histogram_image_size = max_index;

      VP8LWriteBits(bw, 3, histogram_bits - 2);
      ok = EncodeImageNoHuffman(bw, histogram_argb, hash_chain, refs_array,
                                VP8LSubSampleSize(width, histogram_bits),
                                VP8LSubSampleSize(height, histogram_bits),
                                quality);
      WebPSafeFree(histogram_argb);
      if (!ok) goto Error;
    }
  }

  // Store Huffman codes.
  {
    int i;
    int max_tokens = 0;
    huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * CODE_LENGTH_CODES,
                                             sizeof(*huff_tree));
    if (huff_tree == NULL) goto Error;
    // Find maximum number of symbols for the huffman tree-set.
    for (i = 0; i < 5 * histogram_image_size; ++i) {
      HuffmanTreeCode* const codes = &huffman_codes[i];
      if (max_tokens < codes->num_symbols) {
        max_tokens = codes->num_symbols;
      }
    }
    tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens,
                                               sizeof(*tokens));
    if (tokens == NULL) goto Error;
    for (i = 0; i < 5 * histogram_image_size; ++i) {
      HuffmanTreeCode* const codes = &huffman_codes[i];
      StoreHuffmanCode(bw, huff_tree, tokens, codes);
      ClearHuffmanTreeIfOnlyOneSymbol(codes);
    }
  }

  // Store actual literals.
  StoreImageToBitMask(bw, width, histogram_bits, &refs,
                      histogram_symbols, huffman_codes);
  ok = 1;

 Error:
  WebPSafeFree(tokens);
  WebPSafeFree(huff_tree);
  VP8LFreeHistogramSet(histogram_image);
  VP8LBackwardRefsClear(&refs);
  if (huffman_codes != NULL) {
    WebPSafeFree(huffman_codes->codes);
    WebPSafeFree(huffman_codes);
  }
  WebPSafeFree(histogram_symbols);
  return ok;
}

// -----------------------------------------------------------------------------
// Transforms

// Check if it would be a good idea to subtract green from red and blue. We
// only impact entropy in red/blue components, don't bother to look at others.
static int EvalAndApplySubtractGreen(VP8LEncoder* const enc,
                                     int width, int height,
                                     VP8LBitWriter* const bw) {
  if (!enc->use_palette_) {
    int i;
    const uint32_t* const argb = enc->argb_;
    double bit_cost_before, bit_cost_after;
    // Allocate histogram with cache_bits = 1.
    VP8LHistogram* const histo = VP8LAllocateHistogram(1);
    if (histo == NULL) return 0;
    for (i = 0; i < width * height; ++i) {
      const uint32_t c = argb[i];
      ++histo->red_[(c >> 16) & 0xff];
      ++histo->blue_[(c >> 0) & 0xff];
    }
    bit_cost_before = VP8LHistogramEstimateBits(histo);

    VP8LHistogramInit(histo, 1);
    for (i = 0; i < width * height; ++i) {
      const uint32_t c = argb[i];
      const int green = (c >> 8) & 0xff;
      ++histo->red_[((c >> 16) - green) & 0xff];
      ++histo->blue_[((c >> 0) - green) & 0xff];
    }
    bit_cost_after = VP8LHistogramEstimateBits(histo);
    VP8LFreeHistogram(histo);

    // Check if subtracting green yields low entropy.
    enc->use_subtract_green_ = (bit_cost_after < bit_cost_before);
    if (enc->use_subtract_green_) {
      VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
      VP8LWriteBits(bw, 2, SUBTRACT_GREEN);
      VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);
    }
  }
  return 1;
}

static int ApplyPredictFilter(const VP8LEncoder* const enc,
                              int width, int height, int quality,
                              VP8LBitWriter* const bw) {
  const int pred_bits = enc->transform_bits_;
  const int transform_width = VP8LSubSampleSize(width, pred_bits);
  const int transform_height = VP8LSubSampleSize(height, pred_bits);

  VP8LResidualImage(width, height, pred_bits, enc->argb_, enc->argb_scratch_,
                    enc->transform_data_);
  VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  VP8LWriteBits(bw, 2, PREDICTOR_TRANSFORM);
  assert(pred_bits >= 2);
  VP8LWriteBits(bw, 3, pred_bits - 2);
  if (!EncodeImageNoHuffman(bw, enc->transform_data_,
                            (VP8LHashChain*)&enc->hash_chain_,
                            (VP8LBackwardRefs*)enc->refs_,  // cast const away
                            transform_width, transform_height,
                            quality)) {
    return 0;
  }
  return 1;
}

static int ApplyCrossColorFilter(const VP8LEncoder* const enc,
                                 int width, int height, int quality,
                                 VP8LBitWriter* const bw) {
  const int ccolor_transform_bits = enc->transform_bits_;
  const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);
  const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);

  VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
                          enc->argb_, enc->transform_data_);
  VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  VP8LWriteBits(bw, 2, CROSS_COLOR_TRANSFORM);
  assert(ccolor_transform_bits >= 2);
  VP8LWriteBits(bw, 3, ccolor_transform_bits - 2);
  if (!EncodeImageNoHuffman(bw, enc->transform_data_,
                            (VP8LHashChain*)&enc->hash_chain_,
                            (VP8LBackwardRefs*)enc->refs_,  // cast const away
                            transform_width, transform_height,
                            quality)) {
    return 0;
  }
  return 1;
}

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

static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,
                                         size_t riff_size, size_t vp8l_size) {
  uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
    'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
    'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
  };
  PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
  PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
  if (!pic->writer(riff, sizeof(riff), pic)) {
    return VP8_ENC_ERROR_BAD_WRITE;
  }
  return VP8_ENC_OK;
}

static int WriteImageSize(const WebPPicture* const pic,
                          VP8LBitWriter* const bw) {
  const int width = pic->width - 1;
  const int height = pic->height - 1;
  assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);

  VP8LWriteBits(bw, VP8L_IMAGE_SIZE_BITS, width);
  VP8LWriteBits(bw, VP8L_IMAGE_SIZE_BITS, height);
  return !bw->error_;
}

static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
  VP8LWriteBits(bw, 1, has_alpha);
  VP8LWriteBits(bw, VP8L_VERSION_BITS, VP8L_VERSION);
  return !bw->error_;
}

static WebPEncodingError WriteImage(const WebPPicture* const pic,
                                    VP8LBitWriter* const bw,
                                    size_t* const coded_size) {
  WebPEncodingError err = VP8_ENC_OK;
  const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
  const size_t webpll_size = VP8LBitWriterNumBytes(bw);
  const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
  const size_t pad = vp8l_size & 1;
  const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;

  err = WriteRiffHeader(pic, riff_size, vp8l_size);
  if (err != VP8_ENC_OK) goto Error;

  if (!pic->writer(webpll_data, webpll_size, pic)) {
    err = VP8_ENC_ERROR_BAD_WRITE;
    goto Error;
  }

  if (pad) {
    const uint8_t pad_byte[1] = { 0 };
    if (!pic->writer(pad_byte, 1, pic)) {
      err = VP8_ENC_ERROR_BAD_WRITE;
      goto Error;
    }
  }
  *coded_size = CHUNK_HEADER_SIZE + riff_size;
  return VP8_ENC_OK;

 Error:
  return err;
}

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

// Allocates the memory for argb (W x H) buffer, 2 rows of context for
// prediction and transform data.
static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
                                                 int width, int height) {
  WebPEncodingError err = VP8_ENC_OK;
  const int tile_size = 1 << enc->transform_bits_;
  const uint64_t image_size = width * height;
  const uint64_t argb_scratch_size = tile_size * width + width;
  const int transform_data_size =
      VP8LSubSampleSize(width, enc->transform_bits_) *
      VP8LSubSampleSize(height, enc->transform_bits_);
  const uint64_t total_size =
      image_size + argb_scratch_size + (uint64_t)transform_data_size;
  uint32_t* mem = (uint32_t*)WebPSafeMalloc(total_size, sizeof(*mem));
  if (mem == NULL) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }
  enc->argb_ = mem;
  mem += image_size;
  enc->argb_scratch_ = mem;
  mem += argb_scratch_size;
  enc->transform_data_ = mem;
  enc->current_width_ = width;

 Error:
  return err;
}

static void ApplyPalette(uint32_t* src, uint32_t* dst,
                         uint32_t src_stride, uint32_t dst_stride,
                         const uint32_t* palette, int palette_size,
                         int width, int height, int xbits, uint8_t* row) {
  int i, x, y;
  int use_LUT = 1;
  for (i = 0; i < palette_size; ++i) {
    if ((palette[i] & 0xffff00ffu) != 0) {
      use_LUT = 0;
      break;
    }
  }

  if (use_LUT) {
    uint8_t inv_palette[MAX_PALETTE_SIZE] = { 0 };
    for (i = 0; i < palette_size; ++i) {
      const int color = (palette[i] >> 8) & 0xff;
      inv_palette[color] = i;
    }
    for (y = 0; y < height; ++y) {
      for (x = 0; x < width; ++x) {
        const int color = (src[x] >> 8) & 0xff;
        row[x] = inv_palette[color];
      }
      VP8LBundleColorMap(row, width, xbits, dst);
      src += src_stride;
      dst += dst_stride;
    }
  } else {
    // Use 1 pixel cache for ARGB pixels.
    uint32_t last_pix = palette[0];
    int last_idx = 0;
    for (y = 0; y < height; ++y) {
      for (x = 0; x < width; ++x) {
        const uint32_t pix = src[x];
        if (pix != last_pix) {
          for (i = 0; i < palette_size; ++i) {
            if (pix == palette[i]) {
              last_idx = i;
              last_pix = pix;
              break;
            }
          }
        }
        row[x] = last_idx;
      }
      VP8LBundleColorMap(row, width, xbits, dst);
      src += src_stride;
      dst += dst_stride;
    }
  }
}

// Note: Expects "enc->palette_" to be set properly.
// Also, "enc->palette_" will be modified after this call and should not be used
// later.
static WebPEncodingError EncodePalette(VP8LBitWriter* const bw,
                                       VP8LEncoder* const enc, int quality) {
  WebPEncodingError err = VP8_ENC_OK;
  int i;
  const WebPPicture* const pic = enc->pic_;
  uint32_t* src = pic->argb;
  uint32_t* dst;
  const int width = pic->width;
  const int height = pic->height;
  uint32_t* const palette = enc->palette_;
  const int palette_size = enc->palette_size_;
  uint8_t* row = NULL;
  int xbits;

  // Replace each input pixel by corresponding palette index.
  // This is done line by line.
  if (palette_size <= 4) {
    xbits = (palette_size <= 2) ? 3 : 2;
  } else {
    xbits = (palette_size <= 16) ? 1 : 0;
  }

  err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);
  if (err != VP8_ENC_OK) goto Error;
  dst = enc->argb_;

  row = (uint8_t*)WebPSafeMalloc(width, sizeof(*row));
  if (row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;

  ApplyPalette(src, dst, pic->argb_stride, enc->current_width_,
               palette, palette_size, width, height, xbits, row);

  // Save palette to bitstream.
  VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  VP8LWriteBits(bw, 2, COLOR_INDEXING_TRANSFORM);
  assert(palette_size >= 1);
  VP8LWriteBits(bw, 8, palette_size - 1);
  for (i = palette_size - 1; i >= 1; --i) {
    palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);
  }
  if (!EncodeImageNoHuffman(bw, palette, &enc->hash_chain_, enc->refs_,
                            palette_size, 1, quality)) {
    err = VP8_ENC_ERROR_INVALID_CONFIGURATION;
    goto Error;
  }

 Error:
  WebPSafeFree(row);
  return err;
}

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

static int GetHistoBits(int method, int use_palette, int width, int height) {
  const int hist_size = VP8LGetHistogramSize(MAX_COLOR_CACHE_BITS);
  // Make tile size a function of encoding method (Range: 0 to 6).
  int histo_bits = (use_palette ? 9 : 7) - method;
  while (1) {
    const int huff_image_size = VP8LSubSampleSize(width, histo_bits) *
                                VP8LSubSampleSize(height, histo_bits);
    if ((uint64_t)huff_image_size * hist_size <= MAX_HUFF_IMAGE_SIZE) break;
    ++histo_bits;
  }
  return (histo_bits < MIN_HUFFMAN_BITS) ? MIN_HUFFMAN_BITS :
         (histo_bits > MAX_HUFFMAN_BITS) ? MAX_HUFFMAN_BITS : histo_bits;
}

static int GetTransformBits(int method, int histo_bits) {
  const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;
  return (histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;
}

static int GetCacheBits(float quality) {
  return (quality <= 25.f) ? 0 : 7;
}

static void FinishEncParams(VP8LEncoder* const enc) {
  const WebPConfig* const config = enc->config_;
  const WebPPicture* const pic = enc->pic_;
  const int method = config->method;
  const float quality = config->quality;
  const int use_palette = enc->use_palette_;
  enc->histo_bits_ = GetHistoBits(method, use_palette, pic->width, pic->height);
  enc->transform_bits_ = GetTransformBits(method, enc->histo_bits_);
  enc->cache_bits_ = GetCacheBits(quality);
}

// -----------------------------------------------------------------------------
// VP8LEncoder

static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,
                                   const WebPPicture* const picture) {
  VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));
  if (enc == NULL) {
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
    return NULL;
  }
  enc->config_ = config;
  enc->pic_ = picture;

  VP8LDspInit();

  return enc;
}

static void VP8LEncoderDelete(VP8LEncoder* enc) {
  if (enc != NULL) {
    VP8LHashChainClear(&enc->hash_chain_);
    VP8LBackwardRefsClear(&enc->refs_[0]);
    VP8LBackwardRefsClear(&enc->refs_[1]);
    WebPSafeFree(enc->argb_);
    WebPSafeFree(enc);
  }
}

// -----------------------------------------------------------------------------
// Main call

WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
                                   const WebPPicture* const picture,
                                   VP8LBitWriter* const bw) {
  WebPEncodingError err = VP8_ENC_OK;
  const int quality = (int)config->quality;
  const int width = picture->width;
  const int height = picture->height;
  VP8LEncoder* const enc = VP8LEncoderNew(config, picture);
  const size_t byte_position = VP8LBitWriterNumBytes(bw);

  if (enc == NULL) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  // ---------------------------------------------------------------------------
  // Analyze image (entropy, num_palettes etc)

  if (!AnalyzeAndInit(enc, config->image_hint)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  FinishEncParams(enc);

  if (enc->use_palette_) {
    err = EncodePalette(bw, enc, quality);
    if (err != VP8_ENC_OK) goto Error;
    // Color cache is disabled for palette.
    enc->cache_bits_ = 0;
  }

  // In case image is not packed.
  if (enc->argb_ == NULL) {
    int y;
    err = AllocateTransformBuffer(enc, width, height);
    if (err != VP8_ENC_OK) goto Error;
    for (y = 0; y < height; ++y) {
      memcpy(enc->argb_ + y * width,
             picture->argb + y * picture->argb_stride,
             width * sizeof(*enc->argb_));
    }
    enc->current_width_ = width;
  }

  // ---------------------------------------------------------------------------
  // Apply transforms and write transform data.

  if (!EvalAndApplySubtractGreen(enc, enc->current_width_, height, bw)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  if (enc->use_predict_) {
    if (!ApplyPredictFilter(enc, enc->current_width_, height, quality, bw)) {
      err = VP8_ENC_ERROR_INVALID_CONFIGURATION;
      goto Error;
    }
  }

  if (enc->use_cross_color_) {
    if (!ApplyCrossColorFilter(enc, enc->current_width_, height, quality, bw)) {
      err = VP8_ENC_ERROR_INVALID_CONFIGURATION;
      goto Error;
    }
  }

  VP8LWriteBits(bw, 1, !TRANSFORM_PRESENT);  // No more transforms.

  // ---------------------------------------------------------------------------
  // Estimate the color cache size.

  if (enc->cache_bits_ > 0) {
    if (!VP8LCalculateEstimateForCacheSize(enc->argb_, enc->current_width_,
                                           height, quality, &enc->hash_chain_,
                                           &enc->refs_[0], &enc->cache_bits_)) {
      err = VP8_ENC_ERROR_INVALID_CONFIGURATION;
      goto Error;
    }
  }

  // ---------------------------------------------------------------------------
  // Encode and write the transformed image.

  if (!EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,
                           enc->current_width_, height, quality,
                           enc->cache_bits_, enc->histo_bits_)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  if (picture->stats != NULL) {
    WebPAuxStats* const stats = picture->stats;
    stats->lossless_features = 0;
    if (enc->use_predict_) stats->lossless_features |= 1;
    if (enc->use_cross_color_) stats->lossless_features |= 2;
    if (enc->use_subtract_green_) stats->lossless_features |= 4;
    if (enc->use_palette_) stats->lossless_features |= 8;
    stats->histogram_bits = enc->histo_bits_;
    stats->transform_bits = enc->transform_bits_;
    stats->cache_bits = enc->cache_bits_;
    stats->palette_size = enc->palette_size_;
    stats->lossless_size = (int)(VP8LBitWriterNumBytes(bw) - byte_position);
  }

 Error:
  VP8LEncoderDelete(enc);
  return err;
}

int VP8LEncodeImage(const WebPConfig* const config,
                    const WebPPicture* const picture) {
  int width, height;
  int has_alpha;
  size_t coded_size;
  int percent = 0;
  int initial_size;
  WebPEncodingError err = VP8_ENC_OK;
  VP8LBitWriter bw;

  if (picture == NULL) return 0;

  if (config == NULL || picture->argb == NULL) {
    err = VP8_ENC_ERROR_NULL_PARAMETER;
    WebPEncodingSetError(picture, err);
    return 0;
  }

  width = picture->width;
  height = picture->height;
  // Initialize BitWriter with size corresponding to 16 bpp to photo images and
  // 8 bpp for graphical images.
  initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
                 width * height : width * height * 2;
  if (!VP8LBitWriterInit(&bw, initial_size)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  if (!WebPReportProgress(picture, 1, &percent)) {
 UserAbort:
    err = VP8_ENC_ERROR_USER_ABORT;
    goto Error;
  }
  // Reset stats (for pure lossless coding)
  if (picture->stats != NULL) {
    WebPAuxStats* const stats = picture->stats;
    memset(stats, 0, sizeof(*stats));
    stats->PSNR[0] = 99.f;
    stats->PSNR[1] = 99.f;
    stats->PSNR[2] = 99.f;
    stats->PSNR[3] = 99.f;
    stats->PSNR[4] = 99.f;
  }

  // Write image size.
  if (!WriteImageSize(picture, &bw)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  has_alpha = WebPPictureHasTransparency(picture);
  // Write the non-trivial Alpha flag and lossless version.
  if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
    err = VP8_ENC_ERROR_OUT_OF_MEMORY;
    goto Error;
  }

  if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;

  // Encode main image stream.
  err = VP8LEncodeStream(config, picture, &bw);
  if (err != VP8_ENC_OK) goto Error;

  // TODO(skal): have a fine-grained progress report in VP8LEncodeStream().
  if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;

  // Finish the RIFF chunk.
  err = WriteImage(picture, &bw, &coded_size);
  if (err != VP8_ENC_OK) goto Error;

  if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;

  // Save size.
  if (picture->stats != NULL) {
    picture->stats->coded_size += (int)coded_size;
    picture->stats->lossless_size = (int)coded_size;
  }

  if (picture->extra_info != NULL) {
    const int mb_w = (width + 15) >> 4;
    const int mb_h = (height + 15) >> 4;
    memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));
  }

 Error:
  if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  VP8LBitWriterDestroy(&bw);
  if (err != VP8_ENC_OK) {
    WebPEncodingSetError(picture, err);
    return 0;
  }
  return 1;
}

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


text:
package com.intellij.openapi.keymap;

import com.intellij.openapi.keymap.impl.BundledKeymapProvider;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.List;

/**
 * @author yole
 */
public class JBuilderKeymapProvider implements BundledKeymapProvider {
  @NotNull
  @Override
  public List<String> getKeymapFileNames() {
    return Collections.singletonList("JBuilder.xml");
  }
}


text:
//
//    Copyright 2016 KeyleXiao.
//    Project Site : http://keylexiao.github.io/SmartUIBuilderFramework
//    Contact to Me : Keyle_xiao@hotmail.com
//
//   	Licensed under the Apache License, Version 2.0 (the "License");
//   	you may not use this file except in compliance with the License.
//   	You may obtain a copy of the License at
//
//   		http://www.apache.org/licenses/LICENSE-2.0
//
//   		Unless required by applicable law or agreed to in writing, software
//   		distributed under the License is distributed on an "AS IS" BASIS,
//   		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   		See the License for the specific language governing permissions and
//   		limitations under the License.
//
using System;
using Vitality.Framework.Api;

namespace Vitality.Framework.Impl
{
	public class StyleSheetResolveBase:IStyleSheetResolve
	{
		#region IStyleSheetResolve implementation

		public virtual T SetStyleSheet<T> (T obj, string style)
		{
			return default(T);
		}

		public virtual object SetStyleSheet (Type t, object obj, string style)
		{
			return obj;
		}

		#endregion
	}
}


text:
TEST(Switches, Empty) {
  Switches switches;
  CommandLine cmd(CommandLine::NO_PROGRAM);
  switches.AppendToCommandLine(&cmd);
  ASSERT_EQ(0u, cmd.GetSwitches().size());
  ASSERT_EQ("", switches.ToString());
}

TEST(Switches, NoValue) {
  Switches switches;
  switches.SetSwitch("hello");

  ASSERT_TRUE(switches.HasSwitch("hello"));
  ASSERT_EQ("", switches.GetSwitchValue("hello"));

  CommandLine cmd(CommandLine::NO_PROGRAM);
  switches.AppendToCommandLine(&cmd);
  ASSERT_TRUE(cmd.HasSwitch("hello"));
  ASSERT_EQ(FILE_PATH_LITERAL(""), cmd.GetSwitchValueNative("hello"));
  ASSERT_EQ("--hello", switches.ToString());
}

TEST(Switches, Value) {
  Switches switches;
  switches.SetSwitch("hello", "there");

  ASSERT_TRUE(switches.HasSwitch("hello"));
  ASSERT_EQ("there", switches.GetSwitchValue("hello"));

  CommandLine cmd(CommandLine::NO_PROGRAM);
  switches.AppendToCommandLine(&cmd);
  ASSERT_TRUE(cmd.HasSwitch("hello"));
  ASSERT_EQ(FILE_PATH_LITERAL("there"), cmd.GetSwitchValueNative("hello"));
  ASSERT_EQ("--hello=there", switches.ToString());
}

TEST(Switches, FromOther) {
  Switches switches;
  switches.SetSwitch("a", "1");
  switches.SetSwitch("b", "1");

  Switches switches2;
  switches2.SetSwitch("b", "2");
  switches2.SetSwitch("c", "2");

  switches.SetFromSwitches(switches2);
  ASSERT_EQ("--a=1 --b=2 --c=2", switches.ToString());
}

TEST(Switches, Remove) {
  Switches switches;
  switches.SetSwitch("a", "1");
  switches.RemoveSwitch("a");
  ASSERT_FALSE(switches.HasSwitch("a"));
}

TEST(Switches, Quoting) {
  Switches switches;
  switches.SetSwitch("hello", "a  b");
  switches.SetSwitch("hello2", "  '\"  ");

  ASSERT_EQ("--hello=\"a  b\" --hello2=\"  '\\\"  \"", switches.ToString());
}

TEST(Switches, Multiple) {
  Switches switches;
  switches.SetSwitch("switch");
  switches.SetSwitch("hello", "there");

  CommandLine cmd(CommandLine::NO_PROGRAM);
  switches.AppendToCommandLine(&cmd);
  ASSERT_TRUE(cmd.HasSwitch("switch"));
  ASSERT_TRUE(cmd.HasSwitch("hello"));
  ASSERT_EQ(FILE_PATH_LITERAL("there"), cmd.GetSwitchValueNative("hello"));
  ASSERT_EQ("--hello=there --switch", switches.ToString());
}

TEST(Switches, Unparsed) {
  Switches switches;
  switches.SetUnparsedSwitch("a");
  switches.SetUnparsedSwitch("--b");
  switches.SetUnparsedSwitch("--c=1");
  switches.SetUnparsedSwitch("d=1");
  switches.SetUnparsedSwitch("-e=--1=1");

  ASSERT_EQ("---e=--1=1 --a --b --c=1 --d=1", switches.ToString());
}

TEST(ParseCapabilities, WithAndroidPackage) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetString("chromeOptions.androidPackage", "abc");
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_TRUE(capabilities.IsAndroid());
  ASSERT_EQ("abc", capabilities.android_package);
}

TEST(ParseCapabilities, EmptyAndroidPackage) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetString("chromeOptions.androidPackage", std::string());
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, IllegalAndroidPackage) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetInteger("chromeOptions.androidPackage", 123);
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, LogPath) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetString("chromeOptions.logPath", "path/to/logfile");
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_STREQ("path/to/logfile", capabilities.log_path.c_str());
}

TEST(ParseCapabilities, Args) {
  Capabilities capabilities;
  base::ListValue args;
  args.AppendString("arg1");
  args.AppendString("arg2=val");
  base::DictionaryValue caps;
  caps.Set("chromeOptions.args", args.DeepCopy());

  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());

  ASSERT_EQ(2u, capabilities.switches.GetSize());
  ASSERT_TRUE(capabilities.switches.HasSwitch("arg1"));
  ASSERT_TRUE(capabilities.switches.HasSwitch("arg2"));
  ASSERT_EQ("", capabilities.switches.GetSwitchValue("arg1"));
  ASSERT_EQ("val", capabilities.switches.GetSwitchValue("arg2"));
}

TEST(ParseCapabilities, Prefs) {
  Capabilities capabilities;
  base::DictionaryValue prefs;
  prefs.SetString("key1", "value1");
  prefs.SetString("key2.k", "value2");
  base::DictionaryValue caps;
  caps.Set("chromeOptions.prefs", prefs.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_TRUE(capabilities.prefs->Equals(&prefs));
}

TEST(ParseCapabilities, LocalState) {
  Capabilities capabilities;
  base::DictionaryValue local_state;
  local_state.SetString("s1", "v1");
  local_state.SetString("s2.s", "v2");
  base::DictionaryValue caps;
  caps.Set("chromeOptions.localState", local_state.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_TRUE(capabilities.local_state->Equals(&local_state));
}

TEST(ParseCapabilities, Extensions) {
  Capabilities capabilities;
  base::ListValue extensions;
  extensions.AppendString("ext1");
  extensions.AppendString("ext2");
  base::DictionaryValue caps;
  caps.Set("chromeOptions.extensions", extensions.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(2u, capabilities.extensions.size());
  ASSERT_EQ("ext1", capabilities.extensions[0]);
  ASSERT_EQ("ext2", capabilities.extensions[1]);
}

TEST(ParseCapabilities, UnrecognizedProxyType) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "unknown proxy type");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, IllegalProxyType) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetInteger("proxyType", 123);
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, DirectProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "DIRECT");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(1u, capabilities.switches.GetSize());
  ASSERT_TRUE(capabilities.switches.HasSwitch("no-proxy-server"));
}

TEST(ParseCapabilities, SystemProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "system");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(0u, capabilities.switches.GetSize());
}

TEST(ParseCapabilities, PacProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "PAC");
  proxy.SetString("proxyAutoconfigUrl", "test.wpad");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(1u, capabilities.switches.GetSize());
  ASSERT_EQ("test.wpad", capabilities.switches.GetSwitchValue("proxy-pac-url"));
}

TEST(ParseCapabilities, MissingProxyAutoconfigUrl) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "PAC");
  proxy.SetString("httpProxy", "http://localhost:8001");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, AutodetectProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "autodetect");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(1u, capabilities.switches.GetSize());
  ASSERT_TRUE(capabilities.switches.HasSwitch("proxy-auto-detect"));
}

TEST(ParseCapabilities, ManualProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "manual");
  proxy.SetString("ftpProxy", "localhost:9001");
  proxy.SetString("httpProxy", "localhost:8001");
  proxy.SetString("sslProxy", "localhost:10001");
  proxy.SetString("noProxy", "google.com, youtube.com");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(2u, capabilities.switches.GetSize());
  ASSERT_EQ(
      "ftp=localhost:9001;http=localhost:8001;https=localhost:10001",
      capabilities.switches.GetSwitchValue("proxy-server"));
  ASSERT_EQ(
      "google.com, youtube.com",
      capabilities.switches.GetSwitchValue("proxy-bypass-list"));
}

TEST(ParseCapabilities, MissingSettingForManualProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "manual");
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, IgnoreNullValueForManualProxy) {
  Capabilities capabilities;
  base::DictionaryValue proxy;
  proxy.SetString("proxyType", "manual");
  proxy.SetString("ftpProxy", "localhost:9001");
  proxy.Set("sslProxy", base::Value::CreateNullValue());
  proxy.Set("noProxy", base::Value::CreateNullValue());
  base::DictionaryValue caps;
  caps.Set("proxy", proxy.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(1u, capabilities.switches.GetSize());
  ASSERT_TRUE(capabilities.switches.HasSwitch("proxy-server"));
  ASSERT_EQ(
      "ftp=localhost:9001",
      capabilities.switches.GetSwitchValue("proxy-server"));
}

TEST(ParseCapabilities, LoggingPrefsOk) {
  Capabilities capabilities;
  base::DictionaryValue logging_prefs;
  logging_prefs.SetString("Network", "INFO");
  base::DictionaryValue caps;
  caps.Set("loggingPrefs", logging_prefs.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(1u, capabilities.logging_prefs.size());
  ASSERT_EQ(Log::kInfo, capabilities.logging_prefs["Network"]);
}

TEST(ParseCapabilities, LoggingPrefsNotDict) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetString("loggingPrefs", "INFO");
  Status status = capabilities.Parse(caps);
  ASSERT_FALSE(status.IsOk());
}

TEST(ParseCapabilities, ExcludeSwitches) {
  Capabilities capabilities;
  base::ListValue exclude_switches;
  exclude_switches.AppendString("switch1");
  exclude_switches.AppendString("switch2");
  base::DictionaryValue caps;
  caps.Set("chromeOptions.excludeSwitches", exclude_switches.DeepCopy());
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_EQ(2u, capabilities.exclude_switches.size());
  const std::set<std::string>& switches = capabilities.exclude_switches;
  ASSERT_TRUE(switches.find("switch1") != switches.end());
  ASSERT_TRUE(switches.find("switch2") != switches.end());
}

TEST(ParseCapabilities, UseExistingBrowser) {
  Capabilities capabilities;
  base::DictionaryValue caps;
  caps.SetString("chromeOptions.debuggerAddress", "abc:123");
  Status status = capabilities.Parse(caps);
  ASSERT_TRUE(status.IsOk());
  ASSERT_TRUE(capabilities.IsExistingBrowser());
  ASSERT_EQ("abc", capabilities.debugger_address.host());
  ASSERT_EQ(123, capabilities.debugger_address.port());
}


text:
public class CloneGraph{
	public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null){
            return null;
        }
        //store neighbors
        Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
        //map (original node, copy node)
        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        q.offer(node);
        UndirectedGraphNode newHead = new UndirectedGraphNode(node.label);
        map.put(node, newHead);

        while(!q.isEmpty()){
            UndirectedGraphNode curr = q.poll();
            List<UndirectedGraphNode> neighbors = curr.neighbors;

            for(UndirectedGraphNode aNeighbor: neighbors){
                //map does not contain (original,copy) pair
                if(!map.containsKey(aNeighbor)){
                    //make a copy
                    UndirectedGraphNode copy = new UndirectedGraphNode(aNeighbor.label);
                    map.put(aNeighbor, copy);
                    //add copied neighbor to current copied node
                    map.get(curr).neighbors.add(copy);
                    q.offer(aNeighbor);
                }else{
                    map.get(curr).neighbors.add(map.get(aNeighbor));
                }
            }
        }
        return newHead;
    }
}


text:
@implementation PKTokenizer (Factory)
+ (PKTokenizer *)defaultTokenizer {
    PKTokenizer *defaultTokenizer = [PKTokenizer tokenizer];
    //sets the parsing of #import "header.h" not to behave as quoted string
    [defaultTokenizer setTokenizerState:(PKTokenizerState *)defaultTokenizer.symbolState
                                   from:'"'
                                     to:'"'];

    [defaultTokenizer setTokenizerState:(PKTokenizerState *)defaultTokenizer.symbolState
                                   from:0
                                     to:' '];

    //sets the parsing of anything that starts with a # as a word
//    [defaultTokenizer setTokenizerState:(PKTokenizerState *)defaultTokenizer.wordState
//                                   from:'#'
//                                     to:'#'];
    //sets the parsing of anything that starts with a @ as a word
    [defaultTokenizer setTokenizerState:(PKTokenizerState *)defaultTokenizer.wordState
                                   from:'@'
                                     to:'@'];
	return defaultTokenizer;
}
@end