text:
@interface PodsDummy_Pods_THPod_Tests : NSObject
@end
@implementation PodsDummy_Pods_THPod_Tests
@end

redpajama_set_name: RedPajamaGithub


text:
title: Package & Distribute WPF Apps using Azure DevOps
header:
  overlay_image: 'https://i.imgur.com/KekaUZe.png'
  show_overlay_excerpt: false
  overlay_filter: 0.7
  caption: 'Photo credit: [**Mixkit**](https://mixkit.co/free-stock-art/)'
  og_image: 'https://i.imgur.com/KekaUZe.png'
published: true
---

Packaging and delivering a WPF application to end users can be challenging for someone who is new to Desktop application development, and implementing a reliable DevOps pipeline is even harder, due to the tooling support. But a lot of improvements in the desktop application workflow and the .NET platform itself over the last couple of years, have made this process much smoother.

The .Net team recently released a new **mage** dotnet tool to create ClickOnce packages. In the past, we had to rely on mage.exe (Manifest Generation and Editing Tool) to create ClickOnce packages. While mage.exe works perfectly, it is challenging to integrate with DevOps. And also there are a few unique challenges with ClickOnce packages:

- **Unique Application Names** - To avoid installation failures, unique application names must be used in application and deployment manifest files for each environment. This is because Windows doesn't allow installing multiple applications with the same name. For example, if an app is to be named 'MyApp', the staging application would need to be denoted as 'My App (STG)' while the production application should be 'My App'. Both cannot be named 'My App'.
- **Custom Settings** - There are instances when different settings need to be used for each environment. For example, different API urls based on the environment.
- **Download Location -** The ClickOnce package needs to be hosted in a place where users can download and install it. The same location will be used to push new updates to the application.

If you are new to ClickOnce and Azure DevOps, it is best to go through the following articles first.

- [Clickonce Security & Deployment](https://docs.microsoft.com/en-us/visualstudio/deployment/clickonce-security-and-deployment?view=vs-2019)
- [Clickonce Application Manifest](https://docs.microsoft.com/en-us/visualstudio/deployment/clickonce-application-manifest?view=vs-2019)
- [Clickonce Deployment Manifest](https://docs.microsoft.com/en-us/visualstudio/deployment/clickonce-deployment-manifest?view=vs-2019)
- [Azure DevOps Pipelines](https://docs.microsoft.com/en-us/azure/devops/pipelines/?view=azure-devops)
- [Multi Stage Pipelines](https://docs.microsoft.com/en-us/learn/modules/create-multi-stage-pipeline/)
- [Azure Pipeline Templates](https://docs.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops)

 In this post,

  1. We will be deploying WPF ClickOnce package to Azure App Service.
  2. We will have ClickOnce packages and installations per environment (DEV, SIT etc..)
  3. Most importantly, we are going use the Azure DevOps Pipeline to achieve both of above

## Build & Publish

Publishing a WPF application and Razor page web app is pretty straightforward. The `dotnet publish` command can simply be used. Both Razor page web apps and WPF apps are published to the artifact staging directory so they can be easily uploaded to the pipeline artifacts. A WPF app is published to `wwwroot\client\files` folder so it will be accessible for users when deployed. `publishWebProjects` needs to be set to `false` when publishing a WPF app, and `zipAfterPublish` should be  `false` as we don't need the published package to be zipped.

```yaml
steps:
    - task: NuGetToolInstaller@1

    - task: DotNetCoreCLI@2
      displayName: 'Publish Web'
      inputs:
        command: 'publish'
        publishWebProjects: true
        zipAfterPublish: false
        arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'

    - task: DotNetCoreCLI@2
      displayName: 'Publish Client'
      inputs:
        command: 'publish'
        publishWebProjects: false
        projects: '**/PrismClient.csproj'
        arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)\PrismWeb\wwwroot\client\files'
        zipAfterPublish: false
        modifyOutputPath: false

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'
```

## Update Settings

Here, a simple PowerShell script is used to replace variables, as only one variable is being updated. If there are more variables to be replaced, and if key vault integration is needed, it is better to use thirty custom steps like [XDT Transform](https://marketplace.visualstudio.com/items?itemName=qetza.xdttransform) and [Replace Tokens](https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens).

```yaml
- task: PowerShell@2
      displayName: 'Update Variables'
      inputs:
        targetType: 'inline'
        script: |
              $config = "$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client\files\PrismClient.dll.config"
              Write-Host "$config"
              $xml = [xml](get-content $config)
              Write-Host "$xml"
              $env  = $xml.SelectSingleNode("//*[local-name()='setting'][@name='Env']/*[local-name()='value']");
              $env.InnerText = "${{ parameters.env }}"
              $xml.Save($config)
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client'
```

## Generate ClickOnce Package

#### First, install the **mage** dotnet tool

```yaml
- task: CmdLine@2
      displayName: 'Install dotnet mage tool'
      inputs:
        script: 'dotnet tool install --global microsoft.dotnet.mage --version 5.0.0'
```

#### Generate launcher.exe

```yaml
- task: CmdLine@2
      displayName: 'ClickOnce - Add Launcher'
      inputs:
        script: 'dotnet mage -al PrismClient.exe -td files'
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client'
```

#### Create the application manifest

```yaml
- task: CmdLine@2
      displayName: 'ClickOnce - Create application manifest'
      inputs:
        script: 'dotnet mage -new Application -t files\PrismClient.manifest -n "Prism App (${{ parameters.env }})" -fd files -v "1.0.0.$(Build.BuildId)"'
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client'
```

#### Create the deployment manifest

```yaml
- task: CmdLine@2
      displayName: 'ClickOnce - Create deployment manifest'
      inputs:
        script: 'dotnet mage -new Deployment -Install true -pub "Prism Tech" -n "Prism App (${{ parameters.env }})" -v "1.0.0.$(Build.BuildId)" -AppManifest files\PrismClient.manifest -t PrismClient.application -pu "https://prism-web-as-${{ parameters.env }}-ae.azurewebsites.net/client/PrismClient.application"'
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client'
```

#### Update the file extension to .deploy as a workaround for download restrictions

```yaml
- task: PowerShell@2
      displayName: 'Change File Extension to .deploy'
      inputs:
        targetType: 'inline'
        script: 'Get-ChildItem -File -Recurse -Exclude "*.manifest" | % { Rename-Item -Path $_.PSPath -NewName "$($_.Name).deploy" }'
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client\files'
```

#### mapFileExtensions needs to be set to true in the deployment manifest when files have .deploy extension

```yaml
- task: PowerShell@2
      displayName: 'Set mapFileExtensions'
      inputs:
        targetType: 'inline'
        script: |
              $applicationManifest = "$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client\PrismClient.application"
              Write-Host "$applicationManifest"
              $xml = [xml](get-content $applicationManifest)
              Write-Host "$xml"
              $deployment = $xml.SelectSingleNode("//*[local-name()='deployment']")
              $mapFileExtensions = $xml.CreateAttribute("mapFileExtensions");
              $mapFileExtensions.set_Value("true");
              $deployment.SetAttributeNode($mapFileExtensions)
              $xml.Save($applicationManifest)
        workingDirectory: '$(Pipeline.Workspace)\drop\PrismWeb\wwwroot\client'
```

#### Sign Manifest

The `CertFile` parameter can be used to sign the application and deployment manifest files. When the ClickOnce package is signed, the ClickOnce application publisher is shown on the install prompt, so end-users can verify the publisher of the WPF application.

```powershell
dotnet mage -new Application -t files\PrismClient.manifest -fd files -v 1.0.0.2 -CertFile .\Prism.pfx  -Password Prism@1

dotnet mage -new Deployment -Install true -pub "Prism Tech" -v 1.0.0.2 -AppManifest files\PrismClient.manifest -t PrismClient.application  -CertFile .\Prism.pfx  -Password Prism@1
```

![Install prompt](https://i.imgur.com/7gh9Sz6.png)

## Deploy Website

```yaml
- task: AzureWebApp@1
      displayName: 'Deploy Web'
      inputs:
        azureSubscription: 'LankapuraPAYG'
        appType: 'webApp'
        appName: 'prism-web-as-${{ parameters.env }}-ae'
        package: '$(Pipeline.Workspace)/drop/PrismWeb'
        deploymentMethod: 'auto'
```

## Outcome

- Azure DevOps Pipelines

  Multi stage pipeline to build and deploy Razor pages app with ClickOnce package.
  ![Multi stage pipeline to build and deploy Razor pages app with ClickOnce package.](https://i.imgur.com/m5vuBV5.png)

  Pipeline steps of Build stage and Dev Deploy stage.
  ![Pipeline steps of Build stage and Dev Deploy stage.](https://i.imgur.com/dOVcWP6.png)

  DevOps URL: [https://dev.azure.com/pridevops/Prism/_build?definitionId=2&_a=summary](https://dev.azure.com/pridevops/Prism/_build?definitionId=2&_a=summary)

- Website to download ClickOnce package - [https://prism-web-as-dev-ae.azurewebsites.net/](https://prism-web-as-dev-ae.azurewebsites.net/)

  ![ClickOnce download page](https://i.imgur.com/ePWCNPZ.png)

  Here's how deployed files look like in Azure app service

  ![Deployed files in Azure app service](https://i.imgur.com/3Gma5eY.png)
  <!-- ![Deployed files in Azure app service](azure-app-service-editor.png) -->

- Installed WPF App

  WPF sample apps in the start menu.

  ![App on Start Menu](https://i.imgur.com/66DE9zR.png)

  WPF sample apps running side by side.

  ![Installed WPF sample app running side by side](https://i.imgur.com/8Fndv1L.png)

Full source code is available at [https://github.com/lankaapura/prism](https://github.com/lankaapura/prism)

Documentation for the dotnet mage and mage.exe can be found at:

- [https://github.com/dotnet/deployment-tools/tree/master/Documentation/dotnet-mage](https://github.com/dotnet/deployment-tools/tree/master/Documentation/dotnet-mage)
- [https://docs.microsoft.com/en-us/dotnet/framework/tools/mage-exe-manifest-generation-and-editing-tool](https://docs.microsoft.com/en-us/dotnet/framework/tools/mage-exe-manifest-generation-and-editing-tool)


text:
package org.artifactory.ui.rest.model.artifacts.browse.treebrowser.action.recalculateindex;

import org.artifactory.addon.nuget.UiNuGetAddon;
import org.codehaus.jackson.annotate.JsonTypeName;

/**
 * @author Chen Keinan
 */
@JsonTypeName("NuGet")
public class NuGetIndexCalculator extends BaseIndexCalculator {

    @Override
    public void calculateIndex() throws Exception {
        UiNuGetAddon npmAddon = addonsManager.addonByType(UiNuGetAddon.class);
        if (npmAddon != null) {
            npmAddon.requestAsyncReindexNuPkgs(getRepoKey());
        }
    }
}


text:
/****************************************************************************
 * lib/libc/misc/lib_envpath.c
 *
 *   Copyright (C) 2012, 2018 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <tinyara/envpath.h>

#include "libc.h"

#if defined(CONFIG_LIB_ENVPATH)

/****************************************************************************
 * Private Types
 ****************************************************************************/

struct envpath_s {
	FAR char *next;				/* Pointer to the next (unterminated) value in the PATH variable */
	char path[1];
};

#define SIZEOF_ENVPATH_S(n) (sizeof(struct envpath_s) + (n) - 1)

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: envpath_init
 *
 * Description:
 *   Initialize for the traversal of each value in the PATH variable.  The
 *   usage is sequence is as follows:
 *
 *   1) Call envpath_init() to initialize for the traversal.  envpath_init()
 *      will return an opaque handle that can then be provided to
 *      envpath_next() and envpath_release().
 *   2) Call envpath_next() repeatedly to examine every file that lies
 *      in the directories of the PATH variable
 *   3) Call envpath_release() to free resources set aside by envpath_init().
 *
 * Input Parameters:
 *   None
 *
 * Returned Value:
 *   On success, envpath_init() return a non-NULL, opaque handle that may
 *   subsequently be used in calls to envpath_next() and envpath_release().
 *   On error, a NULL handle value will be returned.  The most likely cause
 *   of an error would be that there is no value associated with the PATH
 *   variable.
 *
 ****************************************************************************/

ENVPATH_HANDLE envpath_init(FAR const char *name)
{
	FAR struct envpath_s *envpath;
	FAR char *path;

	/* Get the value of the PATH variable */

	path = getenv(name);
	if (!path) {
		/* getenv() will return a NULL value if the PATH variable does not
		 * exist in the environment.
		 */
		printf("%s variable does not exist in the environment\n", name);
		return (ENVPATH_HANDLE) NULL;
	}

	/* Allocate a container for the PATH variable contents */

	envpath = (FAR struct envpath_s *)
			  lib_malloc(SIZEOF_ENVPATH_S(strlen(path) + 1));

	if (!envpath) {
		/* Ooops.. we are out of memory */

		printf("Allocate a container failed\n");
		return (ENVPATH_HANDLE) NULL;
	}

	/* Populate the container */

	strcpy(envpath->path, path);
	envpath->next = envpath->path;

	/* And return the containing cast to an opaque handle */

	return (ENVPATH_HANDLE) envpath;
}

/****************************************************************************
 * Name: envpath_next
 *
 * Description:
 *   Traverse all possible values in the PATH variable in attempt to find
 *   the full path to an envcutable file when only a relative path is
 *   provided.
 *
 * Input Parameters:
 *   handle - The handle value returned by envpath_init
 *   relpath - The relative path to the file to be found.
 *
 * Returned Value:
 *   On success, a non-NULL pointer to a null-terminated string is provided.
 *   This is the full path to a file that exists in the file system.  This
 *   function will verify that the file exists (but will not verify that it
 *   is marked envcutable).
 *
 *   NOTE: The string pointer return in the success case points to allocated
 *   memory.  This memory must be freed by the called by calling lib_free().
 *
 *   NULL is returned if no path is found to any file with the provided
 *   'relpath' from any absolute path in the PATH variable.  In this case,
 *   there is no point in calling envpath_next() further; envpath_release()
 *   must be called to release resources set aside by expath_init().
 *
 ****************************************************************************/

FAR char *envpath_next(ENVPATH_HANDLE handle, FAR const char *relpath)
{
	FAR struct envpath_s *envpath = (FAR struct envpath_s *)handle;
	struct stat buf;
	FAR char *endptr;
	FAR char *path;
	FAR char *fullpath;
	int pathlen;
	int ret;

	/* Verify that a value handle and relative path were provided */

	DEBUGASSERT(envpath && relpath);
	DEBUGASSERT(relpath[0] != '\0' && relpath[0] != '/');

	/* Loop until (1) we find a file with this relative path from one of the
	 * absolute paths in the PATH variable, or (2) all of the absolute paths
	 * in the PATH variable have been considered.
	 */

	for (;;) {
		/* Make sure that envpath->next points to the beginning of a string */

		path = envpath->next;
		if (*path == '\0') {
			/* If it points to a NULL it means that either (1) the PATH varialbe
			 * is empty, or (2) we have already examined all of the paths in the
			 * path variable.
			 */

			printf("PATH variable is empty or all of the paths are examined\n");
			return (FAR char *)NULL;
		}

		/* Okay... 'path' points to the beginning of the string.  The string may
		 * be termined either with (1) ':' which separates the path from the
		 * next path in the list, or (2) NUL which marks the end of the list.
		 */

		endptr = strchr(path, ':');
		if (endptr == NULL) {
			/* If strchr returns NUL it means that ':' does not appear in the
			 * string.  Therefore, this must be the final path in the PATH
			 * variable content.
			 */

			endptr = &path[strlen(path)];
			envpath->next = endptr;
			DEBUGASSERT(*endptr == '\0');
		} else {
			DEBUGASSERT(*endptr == ':');
			envpath->next = endptr + 1;
			*endptr = '\0';
		}

		pathlen = strlen(path) + strlen(relpath) + 2;
		fullpath = (FAR char *)lib_malloc(pathlen);
		if (fullpath == NULL) {
			/* Failed to allocate memory */

			printf("Failed to allocate memory\n");
			return (FAR char *)NULL;
		}

		/* Construct the full path */

		sprintf(fullpath, "%s/%s", path, relpath);

		/* Verify that a regular file exists at this path */

		ret = stat(fullpath, &buf);
		if (ret == OK && S_ISREG(buf.st_mode)) {
			return fullpath;
		}

		/* Failed to stat the file.  Just free the allocated memory and
		 * continue to try the next path.
		 */

		lib_free(fullpath);
	}

	/* We will not get here */
}

/****************************************************************************
 * Name: envpath_release
 *
 * Description:
 *   Release all resources set aside by envpath_init() when the handle value
 *   was created.  The handle value is invalid on return from this function.
 *   Attempts to all envpath_next() or envpath_release() with such a 'stale'
 *   handle will result in undefined (i.e., not good) behavior.
 *
 * Input Parameters:
 *   handle - The handle value returned by envpath_init
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void envpath_release(ENVPATH_HANDLE handle)
{
	lib_free(handle);
}

#endif							/* CONFIG_LIBC_ENVPATH */


text:
package org.spongepowered.common.data.processor.value.entity;

import com.flowpowered.math.vector.Vector3d;
import net.minecraft.entity.Entity;
import org.spongepowered.api.data.DataTransactionBuilder;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.common.data.processor.common.AbstractSpongeValueProcessor;
import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue;
import org.spongepowered.common.data.value.mutable.SpongeValue;

import java.util.Optional;

public class VelocityValueProcessor extends AbstractSpongeValueProcessor<Entity, Vector3d, Value<Vector3d>> {

    public VelocityValueProcessor() {
        super(Entity.class, Keys.VELOCITY);
    }

    @Override
    public Value<Vector3d> constructValue(Vector3d defaultValue) {
        return new SpongeValue<>(Keys.VELOCITY, Vector3d.ZERO, defaultValue);
    }

    @Override
    protected boolean set(Entity container, Vector3d value) {
        container.motionX = value.getX();
        container.motionY = value.getY();
        container.motionZ = value.getZ();
        container.velocityChanged = true;
        return true;
    }

    @Override
    protected Optional<Vector3d> getVal(Entity container) {
        return Optional.of(new Vector3d(container.motionX, container.motionY, container.motionZ));
    }

    @Override
    protected ImmutableValue<Vector3d> constructImmutableValue(Vector3d value) {
        return new ImmutableSpongeValue<>(Keys.VELOCITY, Vector3d.ZERO, value);
    }

    @Override
    public DataTransactionResult removeFrom(ValueContainer<?> container) {
        return DataTransactionBuilder.failNoData();
    }
}


text:
namespace BABYLON {
namespace Samples {

struct PolygonMeshStarsWithHolesScene : public IRenderableScene {

  PolygonMeshStarsWithHolesScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
  {
  }

  ~PolygonMeshStarsWithHolesScene() override = default;

  const char* getName() override
  {
    return "Polygon Mesh Stars With Holes Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // Create a ArcRotateCamera (non-mesh)
    auto camera
      = ArcRotateCamera::New("Camera", -Math::PI_2, Math::PI / 4.f, 25.f, Vector3::Zero(), scene);

    // Attach the camera to the canvas
    camera->attachControl(canvas, true);

    // Create a basic light, aiming 0,1,0 - meaning, to the sky
    auto light = HemisphericLight::New("light1", Vector3(0, 10, 0), scene);

    // Default intensity is 1. Let's dim the light a small amount
    light->intensity = 0.5f;

    const std::vector<Vector2> corners{
      Vector2(4, -4),  //
      Vector2(2, 0),   //
      Vector2(5, 2),   //
      Vector2(1, 2),   //
      Vector2(-5, 5),  //
      Vector2(-3, 1),  //
      Vector2(-4, -4), //
      Vector2(-2, -3), //
      Vector2(2, -3),  //
    };

    const std::vector<Vector2> hole{
      Vector2(1.f, -1.f),  //
      Vector2(1.5f, 0.f),  //
      Vector2(1.4f, 1.f),  //
      Vector2(0.5f, 1.5f), //
    };

    PolygonMeshBuilder polytri{"polytri", corners, scene};
    polytri.addHole(hole);
    auto polygon          = polytri.build(false, 0.5f);
    polygon->position().y = 4.f;

    Path2 polyPath{2.f, 0.f};
    polyPath.addLineTo(5, 2);
    polyPath.addLineTo(1, 2);
    polyPath.addLineTo(-5, 5);
    polyPath.addLineTo(-3, 1);
    polyPath.addLineTo(-4, -4);
    polyPath.addArcTo(0, -2, 4, -4, 100);

    PolygonMeshBuilder polytri2("polytri2", polyPath, scene);
    polytri2.addHole(hole);
    auto polygon2          = polytri2.build(false, 0.5f);
    polygon2->position().y = -4.f;
  }

}; // end of struct PolygonMeshStarsWithHolesScene

BABYLON_REGISTER_SAMPLE("Meshes", PolygonMeshStarsWithHolesScene)

} // end of namespace Samples
} // end of namespace BABYLON


text:
namespace YAF.Types.Extensions
{
    using System.Reflection;

    /// <summary>
    /// The property info extensions.
    /// </summary>
    public static class PropertyInfoExtensions
    {
        #region Public Methods and Operators

        /// <summary>
        /// The get value as.
        /// </summary>
        /// <param name="propertyInfo">
        /// The property info.
        /// </param>
        /// <param name="obj">
        /// The obj.
        /// </param>
        /// <param name="index">
        /// The index.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public static T GetValueAs<T>([NotNull] this PropertyInfo propertyInfo, object obj, object[] index = null)
        {
            CodeContracts.VerifyNotNull(propertyInfo, "propertyInfo");

            return propertyInfo.GetValue(obj, index).ToType<T>();
        }

        #endregion
    }
}


text:
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib import auth
from django.contrib.auth.models import User

from core import test_utils

class RegistrationTest(TestCase):
    def test_fail(self):
        # No data.
        self.client.post(reverse("user_registration"))
        self.assertFalse(User.objects.all().exists())
        # Password mismatch.
        self.client.post(
            reverse("user_registration"),
            {
                "username": test_utils.get_data(length=30),
                "password1": "P4ssw0rd*",
                "password2": "P4ssw0rd",
            },
        )
        self.assertFalse(User.objects.all().exists())

    def test_success(self):
        self.client.post(
            reverse("user_registration"),
            {
                "username": test_utils.get_data(length=30),
                "password1": "P4ssw0rd*",
                "password2": "P4ssw0rd*",
            },
        )
        self.assertTrue(User.objects.all().exists())

    def test_username_remembered_when_fail(self):
        username = test_utils.get_data(length=30)
        response = self.client.post(
            reverse("user_registration"),
            {"username": username},
        )
        self.assertIn(username, response.content)

    def test_honeypot(self):
        """Honeypot is CAPTCHA alternative."""
        response = self.client.post(
            reverse("user_registration"),
            {
                "username": test_utils.get_data(length=30),
                "password1": "P4ssw0rd*",
                "password2": "P4ssw0rd*",
                "im_bot": "on",
            },
        )
        self.assertEqual(response.status_code, 403)
        self.assertFalse(User.objects.all().exists())

class LoginTest(TestCase):
    def test_fail(self):
        self.client.post(reverse("user_login"),
                         {"username": test_utils.get_data(),
                          "password": test_utils.get_data()})
        logged_in = test_utils.logged_in(self.client)
        self.assertFalse(logged_in)

    def test_success(self):
        username = test_utils.get_data(length=16)
        password = test_utils.get_data()
        test_utils.create_user(username, password)
        self.client.post(reverse("user_login"),
                         {"username": username,
                          "password": password})
        logged_in = test_utils.logged_in(self.client)
        self.assertTrue(logged_in)

class LogoutTest(TestCase):
    def test_success(self):
        username = test_utils.get_data()
        password = test_utils.get_data()
        test_utils.create_user(username, password)
        auth.authenticate(username=username, password=password)
        self.client.get(reverse("user_logout"))
        logged_in = test_utils.logged_in(self.client)
        self.assertFalse(logged_in)


text:
package esilatest

/*
200 ok object */
type GetCorporationsCorporationIdStandings200Ok struct {
	/*
	 from_id integer */
	FromId int32 `json:"from_id,omitempty"`
	/*
	 from_type string */
	FromType string `json:"from_type,omitempty"`
	/*
	 standing number */
	Standing float32 `json:"standing,omitempty"`
}


text:
/// <summary>
/// Creates new object containing mouse coordinates which are extracted from
/// the supplied JavaScript mouse event.
/// </summary>
/// <param name="e">JavaScript mouse event.</param>
/// <returns>New object containing mouse coordinates..</returns>
function MouseEventArgs(e)
{
    if (e.pageX)
    {
        this.x = e.pageX;
    }
    else if (e.clientX)
    {
        this.x = e.clientX;
    }

    if (e.pageY)
    {
        this.y = e.pageY;
    }
    else if (e.clientY)
    {
        this.y = e.clientY;
    }
}

function GetStyleValue(obj, propertyName)
{
    if (!obj || !propertyName)
    {
        alert("Error: At GetStyleValue(): Parameters 'obj' and 'parameterName' can't be null.");

        return null;
    }

    var result = null;

    if (obj.currentStyle)
    {
        result = obj.currentStyle[propertyName];
    }
    else if (window.getComputedStyle)
    {
        try
        {
            var objStyle = window.getComputedStyle(obj, "")

            result = objStyle.getPropertyValue(propertyName);
        }
        catch (exc)
        {
            alert("Error: At GetStyleValue(): Couldn't access style information for the specified object.");
        }
    }
    else
    {
        alert("Error: At GetStyleValue(): Couldn't access style information for the specified object.");

        return null;
    }

    if (!result && propertyName.indexOf('-') != -1)
    {
        var modifiedPropertyName = "";

        for (var i = 0; i < propertyName.length; i++)
        {
            var ch = propertyName.charAt(i);

            if (ch == '-')
            {
                if (i + 1 < propertyName.length)
                {
                    var nextCh = propertyName.charAt(i + 1);

                    if (nextCh != '-')
                    {
                        modifiedPropertyName += nextCh.toUpperCase();
                        i++;
                    }
                }
            }
            else
            {
                modifiedPropertyName += ch;
            }
        }

        return GetStyleValue(obj, modifiedPropertyName);
    }

    return result;
}


text:
/*
 * Grafeas API
 *
 * An API to insert and retrieve annotations on cloud artifacts.
 *
 * API version: v1alpha1
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package grafeas

// Provides information about the scan status of a discovered resource.
type DiscoveryDiscoveredDetails struct {
	// Output only. An operation that indicates the status of the current scan.
	Operation *LongrunningOperation `json:"operation,omitempty"`
}


text:
github-editorconfig
===================

**DEPRECATED: as of 08-Jun-2015, Github [added native support](https://github.com/editorconfig/editorconfig.github.com/pull/48) for EditorConfig.**

This is a browser extension that provides [EditorConfig](http://editorconfig.org/) support for GitHub.

Download links
--------------

You can download extension for your browser from the corresponding store:

* [Chrome](https://chrome.google.com/webstore/detail/github-editorconfig/bppnolhdpdfmmpeefopdbpmabdpoefjh)
* [Firefox](https://github.com/RReverser/github-editorconfig/releases/download/1.1.0/githubeditorconfig_1.1.0.xpi)
* [Opera](https://addons.opera.com/extensions/details/github-editorconfig/)

Description
-----------

Extension looks for [`.editorconfig`](http://editorconfig.org/#example-file) files in the repository the current file belongs to, and applies it's settings to code viewer and editor. Branch is always taken into account.

On options page you can also set [default editorconfig](src/common/res/default.editorconfig).

You can test extension on files in [demo](demo) folder of this repo.

Extension is built with [Kango - cross-browser extension framework](http://kangoextensions.com/).

Screenshots
-----------

Sample .editorconfig:

![Sample .editorconfig](https://cloud.githubusercontent.com/assets/557590/4751070/01e62090-5a9a-11e4-96e8-85d0d1e3c79e.png)

Code viewer (tabs are set to preconfigured width of 4 instead of GitHub's default 8):

![Code viewer](https://cloud.githubusercontent.com/assets/557590/4751072/01e6e6e2-5a9a-11e4-862d-53b65d109958.png)

Code editor (preconfigured options are chosen and marked as **(auto)**; `trim_trailing_whitespace` and `insert_final_newline` are taken into account on commit):

![Code editor](https://cloud.githubusercontent.com/assets/557590/4751069/01e2c918-5a9a-11e4-83fe-be49db527d28.png)

Options page (just a default `.editorconfig`):

![Options page (default editorconfig)](https://cloud.githubusercontent.com/assets/557590/4751071/01e66b9a-5a9a-11e4-91f3-36800fbc8466.png)


text:
{-# OPTIONS_GHC -fplugin=System.Hardware.Haskino.ShallowDeepPlugin #-}
-------------------------------------------------------------------------------------------------
-- |
-- Module      :  System.Hardware.Haskino.Parts.LCD
--                Based on System.Hardware.Arduino
-- Copyright   :  (c) University of Kansas
--                System.Hardware.Arduino (c) Levent Erkok
-- License     :  BSD3
-- Stability   :  experimental
--
-- LCD (Liquid Crystal Display) parts supported by Haskino. The Haskell code
-- below has partly been implemented following the Arduino LiquidCrystal project
-- source code: <http://code.google.com/p/arduino/source/browse/trunk/libraries/LiquidCrystal/>
--
-- The Hitachi44780 data sheet is at: <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>
--
-- For an example program using this library, see "System.Hardware.Arduino.SamplePrograms.LCD".
-------------------------------------------------------------------------------------------------

{-# LANGUAGE NamedFieldPuns #-}

module System.Hardware.Haskino.SamplePrograms.Rewrite.LCD(
  -- * LCD types and registration
  LCD, LCDController(..), lcdRegister
  -- * Writing text on the LCD
  , lcdClear, lcdWrite, lcdWriteChar
  -- * Moving the cursor
  , lcdHome, lcdSetCursor
  -- * Scrolling
  , lcdAutoScrollOn, lcdAutoScrollOff
  , lcdScrollDisplayLeft, lcdScrollDisplayRight
  -- * Display properties
  , lcdLeftToRight, lcdRightToLeft
  , lcdBlinkOn, lcdBlinkOff
  , lcdCursorOn, lcdCursorOff
  , lcdDisplayOn, lcdDisplayOff
  -- * Accessing internal symbols,
  --, LCDSymbol, lcdInternalSymbol, lcdWriteSymbol
  -- Creating custom symbols
  --, lcdCreateSymbol
  -- * Misc helpers
  , lcdFlash, lcdBacklightOn, lcdBacklightOff
  )  where

import Control.Monad       (when)
import Control.Monad.State (gets, liftIO)
import Data.Char           (ord, isSpace)
import Data.Maybe          (fromMaybe, isJust)
import Data.Word           (Word8, Word32)
import qualified Data.Bits as B
import Data.Boolean
import Data.Boolean.Bits

import qualified Data.Map as M

import System.Hardware.Haskino.Comm
import System.Hardware.Haskino.Data
import System.Hardware.Haskino.Expr
import System.Hardware.Haskino.Protocol

import qualified System.Hardware.Haskino.Utils as U

-- | LCD's connected to the board
data LCD = LCD {
                 lcdController   :: LCDController  -- ^ Actual controller
               , lcdState        :: LCDData        -- ^ State information
               }

-- | Hitachi LCD controller: See: <http://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller>.
-- We model only the 4-bit variant, with RS and EN lines only. (The most common Arduino usage.)
-- The data sheet can be seen at: <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>.
data LCDController =
    Hitachi44780 {
                       lcdRS       :: Pin  -- ^ Hitachi pin @ 4@: Register-select
                     , lcdEN       :: Pin  -- ^ Hitachi pin @ 6@: Enable
                     , lcdD4       :: Pin  -- ^ Hitachi pin @11@: Data line @4@
                     , lcdD5       :: Pin  -- ^ Hitachi pin @12@: Data line @5@
                     , lcdD6       :: Pin  -- ^ Hitachi pin @13@: Data line @6@
                     , lcdD7       :: Pin  -- ^ Hitachi pin @14@: Data line @7@
                     , lcdBL       :: Maybe Pin -- ^ Backlight control pin (if present)
                     , lcdRows     :: Word8  -- ^ Number of rows (typically 1 or 2, upto 4)
                     , lcdCols     :: Word8  -- ^ Number of cols (typically 16 or 20, upto 40)
                     , dotMode5x10 :: Bool -- ^ Set to True if 5x10 dots are used
                     }
    | I2CHitachi44780 {
                       address     :: Word8 -- ^ I2C Slave Address of LCD
                     , lcdRows     :: Word8  -- ^ Number of rows (typically 1 or 2, upto 4)
                     , lcdCols     :: Word8  -- ^ Number of cols (typically 16 or 20, upto 40)
                     , dotMode5x10 :: Bool -- ^ Set to True if 5x10 dots are used
                     }
                     deriving Show

-- | State of the LCD, a mere 8-bit word for the Hitachi
data LCDData = LCDData {
                  lcdDisplayMode    :: RemoteRef Word8         -- ^ Display mode (left/right/scrolling etc.)
                , lcdDisplayControl :: RemoteRef Word8         -- ^ Display control (blink on/off, display on/off etc.)
                , lcdGlyphCount     :: RemoteRef Word8         -- ^ Count of custom created glyphs (typically at most 8)
                , lcdBacklightState :: RemoteRef Bool
                }

-- | Commands understood by Hitachi
data Cmd = LCD_INITIALIZE
         | LCD_INITIALIZE_END
         | LCD_FUNCTIONSET
         | LCD_DISPLAYCONTROL
         | LCD_CLEARDISPLAY
         | LCD_ENTRYMODESET
         | LCD_RETURNHOME
         | LCD_SETDDRAMADDR
         | LCD_CURSORSHIFT
         | LCD_SETCGRAMADDR
         | LCD_NOOP

-- | Convert a command to a data-word
getCmdVal :: LCDController -> Cmd -> Word8 -> Word8
getCmdVal c cmd w = get cmd w
  where
    get :: Cmd -> Word8 -> Word8
    get LCD_NOOP _             = 0x00
    get LCD_INITIALIZE _       = 0x33
    get LCD_INITIALIZE_END _   = 0x32
    get LCD_FUNCTIONSET _      = 0x20 B..|.
                                 (if (lcdRows c) > 1 then 0x08 else 0x00) B..|.
                                 (if (dotMode5x10 c) then 0x04 else 0x00)
    get LCD_DISPLAYCONTROL w   = 0x08 B..|. w
    get LCD_CLEARDISPLAY _     = 0x01
    get LCD_ENTRYMODESET w     = 0x04 B..|. w
    get LCD_RETURNHOME _       = 0x02
    get LCD_SETDDRAMADDR w     = 0x80 B..|. w
    get LCD_CURSORSHIFT w      = 0x10 B..|. 0x08 B..|. w   -- NB. LCD_DISPLAYMOVE (0x08) hard coded here
    get LCD_SETCGRAMADDR w     = 0x40 B..|. (w `B.shiftL` 3)

-- | Initialize the LCD. Follows the data sheet <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>,
-- page 46; figure 24.
initLCD :: LCD -> Arduino ()
initLCD lcd = do
    let c = lcdController lcd
    case c of
        Hitachi44780{} -> initLCDDigital c
        I2CHitachi44780{} -> i2cConfig
    -- Wait for 50ms, data-sheet says at least 40ms for 2.7V version, so be safe
    delayMillis 50
    sendCmd lcd LCD_INITIALIZE 0
    delayMillis 5
    sendCmd lcd LCD_INITIALIZE_END 0
    sendCmd lcd LCD_FUNCTIONSET 0
    lcdCursorOff lcd
    lcdBlinkOff lcd
    lcdLeftToRight lcd
    lcdAutoScrollOff lcd
    lcdHome lcd
    lcdClear lcd
    lcdDisplayOn lcd

-- | Initialize the LCD. Follows the data sheet <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>,
-- page 46; figure 24.
initLCDDigital :: LCDController -> Arduino ()
initLCDDigital c@Hitachi44780{lcdRS, lcdEN, lcdD4, lcdD5, lcdD6, lcdD7, lcdBL} = do
    if isJust lcdBL then let Just p = lcdBL in setPinMode p OUTPUT else return ()
    setPinMode lcdRS OUTPUT
    setPinMode lcdEN OUTPUT
    setPinMode lcdD4 OUTPUT
    setPinMode lcdD5 OUTPUT
    setPinMode lcdD6 OUTPUT
    setPinMode lcdD7 OUTPUT

-- | Send a command to the LCD controller
sendCmd :: LCD -> Cmd -> Word8 -> Arduino ()
sendCmd lcd c w = transmit False lcd $ getCmdVal (lcdController lcd) c w

-- | Send 4-bit data to the LCD controller
sendData :: LCD -> Word8 -> Arduino ()
sendData lcd n = transmit True lcd n

-- | By controlling the enable-pin, indicate to the controller that
-- the data is ready for it to process - Done with Digtial writes
pulseEnableDig :: LCDController -> Arduino ()
-- To Do: pulseEnableDig Hitachi44780{lcdEN} = do
pulseEnableDig c = do
  digitalWrite (lcdEN c) False
  delayMicros 1
  digitalWrite (lcdEN c) True
  delayMicros 1
  digitalWrite (lcdEN c) False
  delayMicros 2000

-- | Transmit data down to the LCD
transmit :: Bool -> LCD -> Word8 -> Arduino ()
transmit mode c val = case lcdController c of
    Hitachi44780{}    -> transmitDig mode (lcdController c) val
    I2CHitachi44780{} -> transmitI2C mode c val

-- | Transmit data down to the LCD digital writes
transmitDig :: Bool -> LCDController -> Word8 -> Arduino ()
transmitDig mode c@Hitachi44780{lcdRS, lcdEN, lcdD4} val = do
  digitalWrite lcdRS mode
  digitalWrite lcdEN false
  -- Send down the first 4 bits
  digitalPortWrite lcdD4 (val `B.shiftR` 4) 0x0F
  pulseEnableDig c
  -- Send down the remaining batch
  digitalPortWrite lcdD4 (val B..&. 0x0F) 0x0F
  pulseEnableDig c

data LCD_I2C_Bits =
  LCD_I2C_BACKLIGHT |
  LCD_I2C_ENABLE |
  LCD_I2C_RS

lcdI2CBitsToVal :: LCD_I2C_Bits -> Word8
lcdI2CBitsToVal LCD_I2C_BACKLIGHT = 8
lcdI2CBitsToVal LCD_I2C_ENABLE    = 4
lcdI2CBitsToVal LCD_I2C_RS        = 1

-- | Transmit data down to the I2CLCD using I2C writes
transmitI2C :: Bool -> LCD -> Word8 -> Arduino ()
transmitI2C mode lcd val = return ()
{-
    let c@I2CHitachi44780{address} = lcdController lcd
    let lcds = lcdState lcd
    bls <- readRemoteRef (lcdBacklightState lcds)
    let bl = if bls then (lcdI2CBitsToVal LCD_I2C_BACKLIGHT) else 0
        lors = lo B..|. rs B..|. bl
        hirs = hi B..|. rs B..|. bl
    -- i2cWrite address $ pack [hirs]
    pulseEnableI2C c hirs
    -- i2cWrite address $ pack [lors]
    pulseEnableI2C c lors
  where rs = if mode then (lcdI2CBitsToVal LCD_I2C_RS) else 0
        lo =  (val `B.shiftL` 4) B..&. 0xF0    -- lower four bits
        hi =  val B..&. 0xF0                 -- upper four bits
-}

-- | By controlling the enable-pin, indicate to the controller that
-- the data is ready for it to process - Done with I2C writes
pulseEnableI2C :: LCDController -> Word8 -> Arduino ()
pulseEnableI2C c@I2CHitachi44780{address} d = return ()
{-
    -- ToDo: Finish
    -- i2cWrite address $ pack [d | en]
    delayMicros 1
    -- i2cWrite address $ pack [d & (complement en)]
    delayMillis 2
  where
    en = lcdI2CBitsToVal LCD_I2C_ENABLE
-}

---------------------------------------------------------------------------------------
-- High level interface, exposed to the user
---------------------------------------------------------------------------------------

-- | Register an LCD controller. When registration is complete, the LCD will be initialized so that:
--
--   * Set display ON (Use 'lcdDisplayOn' / 'lcdDisplayOff' to change.)
--
--   * Set cursor OFF (Use 'lcdCursorOn' / 'lcdCursorOff' to change.)
--
--   * Set blink OFF  (Use 'lcdBlinkOn' / 'lcdBlinkOff' to change.)
--
--   * Clear display (Use 'lcdClear' to clear, 'lcdWrite' to display text.)
--
--   * Set entry mode left to write (Use 'lcdLeftToRight' / 'lcdRightToLeft' to control.)
--
--   * Set autoscrolling OFF (Use 'lcdAutoScrollOff' / 'lcdAutoScrollOn' to control.)
--
--   * Put the cursor into home position (Use 'lcdSetCursor' or 'lcdHome' to move around.)
lcdRegister :: LCDController -> Arduino LCD
lcdRegister controller = do
    mode <- newRemoteRef 0
    control <- newRemoteRef 0
    count <- newRemoteRef 0
    backlight <- newRemoteRef True
    let ld = LCDData { lcdDisplayMode    = mode
                     , lcdDisplayControl = control
                     , lcdGlyphCount     = count
                     , lcdBacklightState = backlight
                     }
    let c = LCD { lcdController = controller
                , lcdState = ld
                }
    initLCD c
    return c

-- | Turn backlight on if there is one, otherwise do nothing
lcdBacklightOn :: LCD -> Arduino ()
lcdBacklightOn lcd = lcdBacklight lcd True

-- | Turn backlight off if there is one, otherwise do nothing
lcdBacklightOff :: LCD -> Arduino ()
lcdBacklightOff lcd = lcdBacklight lcd False

-- | Turn backlight on/off if there is one, otherwise do nothing
lcdBacklight :: LCD -> Bool -> Arduino ()
lcdBacklight lcd on = do
   let lcdc = lcdController lcd
   case lcdc of
      Hitachi44780{} -> do
        let bl = lcdBL lcdc
        if isJust bl
            then let Just p = bl in digitalWrite p on
            else return()
      I2CHitachi44780{} -> do
        let lcds = lcdState lcd
        writeRemoteRef (lcdBacklightState lcds) on
        -- Send a noop so backlight state line gets updated
        sendCmd lcd LCD_NOOP 0

-- | Write a string on the LCD at the current cursor position
lcdWrite :: LCD -> [Word8] -> Arduino ()
lcdWrite lcd ws = lcdWrite' ws
  where
    lcdWrite' :: [Word8] -> Arduino ()
    lcdWrite' l = if null l
                  then return ()
                  else do
                    lcdWriteChar lcd $ head l
                    lcdWrite' $ tail l

-- | Write a string on the LCD at the current cursor position
lcdWriteChar :: LCD -> Word8 -> Arduino ()
lcdWriteChar lcd w = sendData lcd w

-- | Clear the LCD
lcdClear :: LCD -> Arduino ()
lcdClear lcd = do sendCmd lcd LCD_CLEARDISPLAY 0
                  delayMicros 200 -- give some time to make sure LCD is really cleared

-- | Send the cursor to home position
lcdHome :: LCD -> Arduino ()
lcdHome lcd = do sendCmd lcd LCD_RETURNHOME 0
                 delayMicros 200

-- | Set the cursor location. The pair of arguments is the new column and row numbers
-- respectively:
--
--   * The first value is the column, the second is the row. (This is counter-intuitive, but
--     is in line with what the standard Arduino programmers do, so we follow the same convention.)
--
--   * Counting starts at 0 (both for column and row no)
--
--   * If the new location is out-of-bounds of your LCD, we will put it the cursor to the closest
--     possible location on the LCD.
lcdSetCursor :: LCD -> Word8 -> Word8 -> Arduino ()
lcdSetCursor lcd givenCol givenRow = sendCmd lcd LCD_SETDDRAMADDR offset
              where align :: Word8 -> Word8 -> Word8
                    align i m = if (i >= m) then (m-1) else i
                    col = align givenCol $ lcdCols (lcdController lcd)
                    row = align givenRow $ lcdRows (lcdController lcd)
                    -- The magic row-offsets come from various web sources
                    -- I don't follow the logic in these numbers, but it seems to work
                    offset = col + if (row == 0) then 0
                                        else if (row == 1) then 0x40
                                              else if (row == 2) then 0x14 else 0x54

-- | Scroll the display to the left by 1 character. Project idea: Using a tilt sensor, scroll the contents of the display
-- left/right depending on the tilt.
lcdScrollDisplayLeft :: LCD -> Arduino ()
lcdScrollDisplayLeft lcd = sendCmd lcd LCD_CURSORSHIFT lcdMoveLeft
  where lcdMoveLeft = 0x00

-- | Scroll the display to the right by 1 character
lcdScrollDisplayRight :: LCD -> Arduino ()
lcdScrollDisplayRight lcd = sendCmd lcd LCD_CURSORSHIFT lcdMoveRight
  where lcdMoveRight = 0x04

-- | Update the display control word
updateDisplayControl :: Bool -> Int -> LCD -> Arduino ()
updateDisplayControl set w lcd = do
  let c = lcdController lcd
  let lcds = lcdState lcd
  old <- readRemoteRef (lcdDisplayControl lcds)
  if set
  then writeRemoteRef (lcdDisplayControl lcds) (old `B.setBit` w )
  else writeRemoteRef (lcdDisplayControl lcds) (old `B.clearBit` w )
  new <- readRemoteRef (lcdDisplayControl lcds)
  sendCmd lcd LCD_DISPLAYCONTROL new

-- | Update the display mode word
updateDisplayMode :: Bool -> Int -> LCD -> Arduino ()
updateDisplayMode set w lcd = do
  let c = lcdController lcd
  let lcds = lcdState lcd
  old <- readRemoteRef (lcdDisplayMode lcds)
  if set
  then writeRemoteRef (lcdDisplayMode lcds) (old `B.setBit` w )
  else writeRemoteRef (lcdDisplayMode lcds) (old `B.clearBit` w )
  new <- readRemoteRef (lcdDisplayMode lcds)
  sendCmd lcd LCD_DISPLAYCONTROL new

-- | Various control masks for the Hitachi44780
data Hitachi44780Mask = LCD_BLINKON              -- ^ bit @0@ Controls whether cursor blinks
                      | LCD_CURSORON             -- ^ bit @1@ Controls whether cursor is on
                      | LCD_DISPLAYON            -- ^ bit @2@ Controls whether display is on
                      | LCD_ENTRYSHIFTINCREMENT  -- ^ bit @0@ Controls left/right scroll
                      | LCD_ENTRYLEFT            -- ^ bit @1@ Controls left/right entry mode

-- | Convert the mask value to the bit no
maskBit :: Hitachi44780Mask -> Int
maskBit LCD_BLINKON             = 0
maskBit LCD_CURSORON            = 1
maskBit LCD_DISPLAYON           = 2
maskBit LCD_ENTRYSHIFTINCREMENT = 0
maskBit LCD_ENTRYLEFT           = 1

--- | Do not blink the cursor
lcdBlinkOff :: LCD -> Arduino ()
lcdBlinkOff lcd = updateDisplayControl False (maskBit LCD_BLINKON) lcd

-- | Blink the cursor
lcdBlinkOn :: LCD -> Arduino ()
lcdBlinkOn lcd = updateDisplayControl True (maskBit LCD_BLINKON) lcd

-- | Hide the cursor. Note that a blinking cursor cannot be hidden, you must first
-- turn off blinking.
lcdCursorOff :: LCD -> Arduino ()
lcdCursorOff lcd = updateDisplayControl False (maskBit LCD_CURSORON) lcd

-- | Show the cursor
lcdCursorOn :: LCD -> Arduino ()
lcdCursorOn lcd = updateDisplayControl True (maskBit LCD_CURSORON) lcd

-- | Turn the display off. Note that turning the display off does not mean you are
-- powering it down. It simply means that the characters will not be shown until
-- you turn it back on using 'lcdDisplayOn'. (Also, the contents will /not/ be
-- forgotten when you call this function.) Therefore, this function is useful
-- for temporarily hiding the display contents.
lcdDisplayOff :: LCD -> Arduino ()
lcdDisplayOff lcd = updateDisplayControl False (maskBit LCD_DISPLAYON) lcd

-- | Turn the display on
lcdDisplayOn :: LCD -> Arduino ()
lcdDisplayOn lcd = updateDisplayControl True (maskBit LCD_DISPLAYON) lcd

-- | Set writing direction: Left to Right
lcdLeftToRight :: LCD -> Arduino ()
lcdLeftToRight lcd = updateDisplayMode True (maskBit LCD_ENTRYLEFT) lcd

-- | Set writing direction: Right to Left
lcdRightToLeft :: LCD -> Arduino ()
lcdRightToLeft lcd = updateDisplayMode False (maskBit LCD_ENTRYLEFT) lcd

-- | Turn on auto-scrolling. In the context of the Hitachi44780 controller, this means that
-- each time a letter is added, all the text is moved one space to the left. This can be
-- confusing at first: It does /not/ mean that your strings will continuously scroll:
-- It just means that if you write a string whose length exceeds the column-count
-- of your LCD, then you'll see the tail-end of it. (Of course, this will create a scrolling
-- effect as the string is being printed character by character.)
--
-- Having said that, it is easy to program a scrolling string program: Simply write your string
-- by calling 'lcdWrite', and then use the 'lcdScrollDisplayLeft' and 'lcdScrollDisplayRight' functions
-- with appropriate delays to simulate the scrolling.
lcdAutoScrollOn :: LCD -> Arduino ()
lcdAutoScrollOn lcd = updateDisplayMode True (maskBit LCD_ENTRYSHIFTINCREMENT) lcd

-- | Turn off auto-scrolling. See the comments for 'lcdAutoScrollOn' for details. When turned
-- off (which is the default), you will /not/ see the characters at the end of your strings that
-- do not fit into the display.
lcdAutoScrollOff :: LCD -> Arduino ()
lcdAutoScrollOff lcd = updateDisplayMode False (maskBit LCD_ENTRYSHIFTINCREMENT) lcd

-- | Flash contents of the LCD screen
lcdFlash :: LCD
         -> Word32  -- ^ Flash count
         -> Word32  -- ^ Delay amount (in milli-seconds)
         -> Arduino ()
lcdFlash lcd n d = lcdFlash' 0
  where
    lcdFlash' :: Word32 -> Arduino ()
    lcdFlash' c = if c == n then return () else do
        lcdDisplayOff lcd
        delayMillis d
        lcdDisplayOn lcd
        delayMillis d
        lcdFlash' $ c+1
{-
-- | An abstract symbol type for user created symbols
newtype LCDSymbol = LCDSymbol Word8

-- | Create a custom symbol for later display. Note that controllers
-- have limited capability for such symbols, typically storing no more
-- than 8. The behavior is undefined if you create more symbols than your
-- LCD can handle.
--
-- The input is a simple description of the glyph, as a list of precisely 8
-- strings, each of which must have 5 characters. Any space character is
-- interpreted as a empty pixel, any non-space is a full pixel, corresponding
-- to the pixel in the 5x8 characters we have on the LCD.  For instance, here's
-- a happy-face glyph you can use:
--
-- >
-- >   [ "     "
-- >   , "@   @"
-- >   , "     "
-- >   , "     "
-- >   , "@   @"
-- >   , " @@@ "
-- >   , "     "
-- >   , "     "
-- >   ]
-- >
lcdCreateSym :: LCD -> [Word8] -> Arduino LCDSymbol
lcdCreateSym lcd glyph =
    do let c = lcdControllerE lcd
       let lcds = lcdStateE lcd
       i <- readRemoteRef (lcdGlyphCountE lcds)
       modifyRemoteRef (lcdGlyphCountE lcds) (\x -> x + 1)
       sendCmd lcd c (LCD_SETCGRAMADDR i)
       forInE glyph (\w -> sendData lcd c w)
       return $ LCDSymbolE i

lcdCreateSymbol :: LCD -> [String] -> Arduino LCDSymbol
lcdCreateSymbol lcd glyph
  | length glyph /= 8 || any (/= 5) (map length glyph)
  = do die "Haskino: lcdCreateSymbol: Invalid glyph description: must be 8x5!" ("Received:" : glyph)
       return $ LCDSymbolE 255
  | True
  = do let cvt :: String -> Word8
           cvt s = lit $ foldr (B..|.) 0 [B.bit p | (ch, p) <- zip (reverse s) [0..], not (isSpace ch)]
       let rawGlyph = pack $ map cvt glyph
       lcdCreateSymE lcd rawGlyph

-- | Display a user created symbol on the LCD. (See 'lcdCreateSymbol' for details.)
lcdWriteSymbol :: LCD -> LCDSymbol -> Arduino ()
lcdWriteSymbol lcd (LCDSymbol i) = lcdWriteChar lcd i

-- | Access an internally stored symbol, one that is not available via its ASCII equivalent. See
-- the Hitachi datasheet for possible values: <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>, Table 4 on page 17.
--
-- For instance, to access the symbol right-arrow:
--
--   * Locate it in the above table: Right-arrow is at the second-to-last row, 7th character from left.
--
--   * Check the upper/higher bits as specified in the table: For Right-arrow, upper bits are @0111@ and the
--     lower bits are @1110@; which gives us the code @01111110@, or @0x7E@.
--
--   * So, right-arrow can be accessed by symbol code 'lcdInternalSymbol' @0x7E@, which will give us a 'LCDSymbol' value
--   that can be passed to the 'lcdWriteSymbol' function. The code would look like this: @lcdWriteSymbol lcd (lcdInternalSymbol 0x7E)@.
lcdInternalSymbol :: Word8 -> LCDSymbol
lcdInternalSymbol = LCDSymbol
-}


text:
package org.owasp.dependencycheck.data.lucene;

import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.miscellaneous.WordDelimiterFilter;
import org.apache.lucene.util.Version;

/**
 *

 * A Lucene Analyzer that utilizes the WhitespaceTokenizer, WordDelimiterFilter, LowerCaseFilter, and StopFilter. The intended
 * purpose of this Analyzer is to index the CPE fields vendor and product.

 *
 * @author Jeremy Long
 */
public class FieldAnalyzer extends Analyzer {

    /**
     * The Lucene Version used.
     */
    private final Version version;

    /**
     * Creates a new FieldAnalyzer.
     *
     * @param version the Lucene version
     */
    public FieldAnalyzer(Version version) {
        this.version = version;
    }

    /**
     * Creates the TokenStreamComponents
     *
     * @param fieldName the field name being analyzed
     * @param reader the reader containing the input
     * @return the TokenStreamComponents
     */
    @Override
    protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        final Tokenizer source = new AlphaNumericTokenizer(version, reader);

        TokenStream stream = source;

        stream = new WordDelimiterFilter(stream,
                WordDelimiterFilter.CATENATE_WORDS
                | WordDelimiterFilter.GENERATE_WORD_PARTS
                | WordDelimiterFilter.GENERATE_NUMBER_PARTS
                | WordDelimiterFilter.PRESERVE_ORIGINAL
                | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE
                | WordDelimiterFilter.SPLIT_ON_NUMERICS
                | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE, null);

        stream = new LowerCaseFilter(version, stream);
        stream = new StopFilter(version, stream, StopAnalyzer.ENGLISH_STOP_WORDS_SET);

        return new TokenStreamComponents(source, stream);
    }
}


text:
package main

import (
	"fmt"
	"net"
	"time"

	"github.com/sakeven/mika/protocols"
	"github.com/sakeven/mika/protocols/mika"
	"github.com/sakeven/mika/protocols/transfer/obfs"
	"github.com/sakeven/mika/protocols/transfer/tcp"
	"github.com/sakeven/mika/utils"

	"github.com/xtaci/kcp-go"
)

var conf *utils.Conf

func handle(c protocols.Protocol, cg *mika.CryptoGenerator) {
	mikaConn, err := mika.NewMika(c, cg.NewCrypto(), nil)
	if err != nil {
		c.Close()
		utils.Errorf("Create mika connection error %s", err)
		return
	}
	mika.Serve(mikaConn)
}

func listen(serverInfo *utils.ServerConf) {
	nl, err := net.Listen("tcp", fmt.Sprintf("%s:%d", serverInfo.Address, serverInfo.Port))
	if err != nil {
		utils.Fatalf("Create server error %s", err)
	}

	utils.Infof("Listen on tcp://%s:%d\n", serverInfo.Address, serverInfo.Port)
	cg := mika.NewCryptoGenerator(serverInfo.Method, serverInfo.Password)

	for {
		c, err := nl.Accept()
		if err != nil {
			utils.Errorf("Accept connection error %s", err)
			continue
		}

		go func() {
			var tcpConn protocols.Protocol = &tcp.Conn{
				Conn:    c,
				Timeout: time.Duration(serverInfo.Timeout) * time.Second,
			}
			if serverInfo.Protocol == protocols.ObfsHTTP {
				utils.Debugf("use protocol %s", serverInfo.Protocol)
				tcpConn = obfs.NewHTTP(tcpConn, true)
			}
			handle(tcpConn, cg)
		}()
	}
}

func listenKCP(serverInfo *utils.ServerConf) {
	nl, err := kcp.ListenWithOptions(fmt.Sprintf("%s:%d", serverInfo.Address, serverInfo.Port), nil, 10, 3)
	if err != nil {
		utils.Fatalf("Create server error %s", err)
	}

	utils.Infof("Listen on kcp://%s:%d\n", serverInfo.Address, serverInfo.Port)
	cg := mika.NewCryptoGenerator(serverInfo.Method, serverInfo.Password)

	for {
		conn, err := nl.AcceptKCP()
		if err != nil {
			utils.Errorf("Accept connection error %s", err)
			continue
		}

		go func() {
			conn.SetStreamMode(true)
			conn.SetNoDelay(1, 20, 2, 1)
			conn.SetACKNoDelay(true)
			conn.SetWindowSize(1024, 1024)
			kcpConn := &tcp.Conn{
				Conn:    conn,
				Timeout: time.Duration(serverInfo.Timeout) * time.Second,
			}
			handle(kcpConn, cg)
		}()
	}
}

func main() {
	conf = utils.ParseConf()
	utils.SetLevel(utils.DebugLevel)

	//TODO check conf

	for _, serverInfo := range conf.Server {
		if serverInfo.Timeout <= 0 {
			serverInfo.Timeout = 30
		}

		if serverInfo.Protocol == protocols.KCP {
			listenKCP(serverInfo)
		} else {
			listen(serverInfo)
		}
	}
}


text:
.class synthetic Lcom/htc/preference/HtcVolumePreference$1;
.super Ljava/lang/Object;
.source "HtcVolumePreference.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/preference/HtcVolumePreference;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1008
    name = null
.end annotation


text:
import os
import re
from lxml import etree
from io import BytesIO, StringIO
from copy import deepcopy

RESOURCES = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "unit", "resources")

class Crossref442ArticleFixtureFactory(object):
    """
    ~~Crossref442XML:Fixture->Crossref442:Crosswalk~~
    """

    NS = {'x': 'http://www.crossref.org/schema/4.4.2'}
    ARTICLES = os.path.join(RESOURCES, "crossref442_article_uploads.xml")

    @classmethod
    def _response_from_xpath(cls, xpath):
        with open(cls.ARTICLES) as f:
            doc = etree.parse(f)
        records = doc.getroot()
        articles = records.xpath(xpath, namespaces=cls.NS)
        ns = "{%s}" % cls.NS['x']
        nr = etree.Element(ns + "doi_batch")
        nr.append(records.xpath("//x:head", namespaces=cls.NS)[0])
        nr.append(etree.Element(ns + "body"))
        body = nr.find("x:body", cls.NS)
        for a in articles:
            body.append(a)
        out = etree.tostring(nr, encoding="UTF-8", xml_declaration=True)
        return BytesIO(out)

    @classmethod
    def upload_2_issns_correct(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs Correct']]")

    @classmethod
    def upload_2_issns_ambiguous(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs Ambiguous']]")

    @classmethod
    def upload_1_issn_correct(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='PISSN Correct']]")

    @classmethod
    def upload_author_email_address(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='author email address']]")

    @classmethod
    def upload_1_issn_superlong_should_not_clip(cls):
        return cls._response_from_xpath(
            "//x:body/x:journal[x:journal_metadata[x:full_title='PISSN Correct Superlong Abstract Expected to Not be Clipped']]")

    @classmethod
    def upload_1_issn_superlong_should_clip(cls):
        return cls._response_from_xpath(
            "//x:body/x:journal[x:journal_metadata[x:full_title='PISSN Correct Superlong Abstract Expected to be Clipped']]")

    @classmethod
    def invalid_schema_xml(cls):
        return StringIO("<this><isnot my='schema'></isnot></this>")

    @classmethod
    def noids(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='NOIDS']]")

    @classmethod
    def upload_1_issn_electronic(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='1 ISSN - electronic']]")

    @classmethod
    def upload_1_issn_print(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='1 ISSN - print']]")

    @classmethod
    def upload_1_issn_no_type(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='1 ISSN - no type']]")

    @classmethod
    def upload_2_issns_1_electronic_2_no_type(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - electronic then no type']]")

    @classmethod
    def upload_2_issns_1_electronic_2_print(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - electronic then print']]")

    @classmethod
    def upload_2_issns_1_no_type_2_electronic(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - no type then electronic']]")

    @classmethod
    def upload_2_issns_1_print_2_no_type(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - print then no type']]")

    @classmethod
    def upload_2_issns_1_print_2_electronic(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - print then electronic']]")

    @classmethod
    def upload_2_issns_1_no_type_2_print(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - no type then print']]")

    @classmethod
    def upload_2_issns_no_type(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - no types']]")

    @classmethod
    def upload_2_issns_same_types(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 ISSNs - same types']]")

    @classmethod
    def upload_3_issns(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='3 ISSNs']]")

    @classmethod
    def upload_html_tags_in_text(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='HTML tags in title']]")

    @classmethod
    def upload_html_tags_in_attrs(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='HTML tags in attribute']]")

    @classmethod
    def upload_the_same_issns(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='2 The Same ISSNs']]")

    @classmethod
    def upload_no_issns(cls):
        return cls._response_from_xpath("//record[journalTitle='No issns']")

    @classmethod
    def upload_multiple_affs(cls):
        return cls._response_from_xpath("//x:body/x:journal[x:journal_metadata[x:full_title='Multiple Affs']]")

class Crossref531ArticleFixtureFactory(Crossref442ArticleFixtureFactory):
    """
    ~~Crossref531XML:Fixture->Crossref531:Crosswalk~~
    """
    NS = {'x': 'http://www.crossref.org/schema/5.3.1'}
    ARTICLES = os.path.join(RESOURCES, "crossref531_article_uploads.xml")


text:
// Originally from UpdatedComponentTests/StandardTesting/REST/Rest_Post_RequestTypes_Set_SimpleSet_JSON_Empty.xls;
package com.betfair.cougar.tests.updatedcomponenttests.standardtesting.rest;

import com.betfair.testing.utils.cougar.misc.XMLHelpers;
import com.betfair.testing.utils.JSONHelpers;
import com.betfair.testing.utils.cougar.assertions.AssertionUtils;
import com.betfair.testing.utils.cougar.beans.HttpCallBean;
import com.betfair.testing.utils.cougar.beans.HttpResponseBean;
import com.betfair.testing.utils.cougar.manager.CougarManager;
import com.betfair.testing.utils.cougar.manager.RequestLogRequirement;

import org.json.JSONObject;
import org.testng.annotations.Test;
import org.w3c.dom.Document;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * Ensure that when a Rest (JSON) Post operation is performed, Cougar can correctly handle an empty simple Set in the post body
 */
public class RestPostRequestTypesSetSimpleSetJSONEmptyTest {
    @Test
    public void doTest() throws Exception {
        // Set up the Http Call Bean to make the request
        CougarManager cougarManager1 = CougarManager.getInstance();
        HttpCallBean getNewHttpCallBean1 = cougarManager1.getNewHttpCallBean("87.248.113.14");
        cougarManager1 = cougarManager1;

        getNewHttpCallBean1.setOperationName("simpleSetOperation");

        getNewHttpCallBean1.setServiceName("baseline", "cougarBaseline");

        getNewHttpCallBean1.setVersion("v2");
        // Set the post body to contain an empty simple set
        Map map2 = new HashMap();
        map2.put("RESTJSON","{\"message\":\n           {\"simpleSet\": \n           []\n}}");
        getNewHttpCallBean1.setPostQueryObjects(map2);
        // Get current time for getting log entries later

        Timestamp getTimeAsTimeStamp7 = new Timestamp(System.currentTimeMillis());
        // Make JSON call to the operation requesting an XML response
        cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.XML);
        // Make JSON call to the operation requesting a JSON response
        cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.JSON);
        // Create the expected response as an XML document
        XMLHelpers xMLHelpers4 = new XMLHelpers();
        Document createAsDocument10 = xMLHelpers4.getXMLObjectFromString("<SimpleSetOperationResponse><SimpleSetOperationResponseObject><responseSet/></SimpleSetOperationResponseObject></SimpleSetOperationResponse>");
        // Create the expected response as a JSON object
        JSONHelpers jSONHelpers5 = new JSONHelpers();
        JSONObject createAsJSONObject11 = jSONHelpers5.createAsJSONObject(new JSONObject("{\"responseSet\": []}"));
        // Check the 2 responses are as expected
        HttpResponseBean response6 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONXML);
        AssertionUtils.multiAssertEquals(createAsDocument10, response6.getResponseObject());
        AssertionUtils.multiAssertEquals((int) 200, response6.getHttpStatusCode());
        AssertionUtils.multiAssertEquals("OK", response6.getHttpStatusText());

        HttpResponseBean response7 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON);
        AssertionUtils.multiAssertEquals(createAsJSONObject11, response7.getResponseObject());
        AssertionUtils.multiAssertEquals((int) 200, response7.getHttpStatusCode());
        AssertionUtils.multiAssertEquals("OK", response7.getHttpStatusText());

        // generalHelpers.pauseTest(500L);
        // Check the log entries are as expected

        cougarManager1.verifyRequestLogEntriesAfterDate(getTimeAsTimeStamp7, new RequestLogRequirement("2.8", "simpleSetOperation"),new RequestLogRequirement("2.8", "simpleSetOperation") );
    }

}


text:
import { serialize } from "utils.js";
import { debounce } from "lodash";
import history from "./history.js";

export const URL_ROOT =
  window.location.href.indexOf("localhost") > -1
    ? "http://localhost:3000"
    : window.location.host.indexOf("10.55.") > -1
      ? "http://" + window.location.host.split(":")[0] + ":3000"
      : "";

export const NEW_ADS = "new_ads";
export const newAds = ads => ({
  type: NEW_ADS,
  value: ads
});

export const GOT_THAT_AD = "GOT_THAT_AD";
export const receiveOneAd = ad => ({
  type: GOT_THAT_AD,
  ad: ad
});

export const REQUESTING_ONE_AD = "REQUESTING_ONE_AD";
export const requestingOneAd = ad_id => ({
  type: REQUESTING_ONE_AD,
  ad_id: ad_id
});

export const GOT_RECENT_GROUPED_ATTR = "GOT_RECENT_GROUPED_ATTR";
export const receiveRecentGroupedAttr = groupedAttrs => ({
  type: GOT_RECENT_GROUPED_ATTR,
  groupedAttrs
});

export const REQUESTING_RECENT_GROUPED_ATTR = "REQUESTING_RECENT_GROUPED_ATTR";
export const requestingRecentGroupedAttr = () => ({
  type: REQUESTING_RECENT_GROUPED_ATTR
});

export const RECEIVE_STATES_AND_DISTRICTS = "RECEIVE_STATES_AND_DISTRICTS";
export const receiveStatesAndDistricts = statesAndDistricts => ({
  type: RECEIVE_STATES_AND_DISTRICTS,
  statesAndDistricts
});

export const REQUESTING_STATES_AND_DISTRICTS =
  "REQUESTING_STATES_AND_DISTRICTS";
export const requestingStatesAndDistricts = () => ({
  type: REQUESTING_STATES_AND_DISTRICTS
});

export const GOT_ADMIN_SUMMARY = "GOT_ADMIN_SUMMARY";
export const receivedAdminSummary = summary => ({
  type: GOT_ADMIN_SUMMARY,
  summary
});

export const REQUESTING_ADMIN_SUMMARY = "REQUESTING_ADMIN_SUMMARY";
export const requestingAdminSummary = () => ({
  type: REQUESTING_ADMIN_SUMMARY
});

export const GOT_HOMEPAGE_SUMMARY = "GOT_HOMEPAGE_SUMMARY";
export const receivedHomepageSummary = summary => ({
  type: GOT_HOMEPAGE_SUMMARY,
  summary
});

export const REQUESTING_HOMEPAGE_SUMMARY = "REQUESTING_HOMEPAGE_SUMMARY";
export const requestingHomepageSummary = () => ({
  type: REQUESTING_HOMEPAGE_SUMMARY
});

export const SET_LANG = "set_lang";
export const setLang = lang => ({
  type: SET_LANG,
  value: lang
});

export const NEW_SEARCH = "new_search";
export const newSearch = query => ({
  type: NEW_SEARCH,
  value: query
});

export const CLEAR_PERSONA = "clear_persona";
export const clearPersona = () => ({
  type: CLEAR_PERSONA
});
export const SET_PERSONA = "set_persona";
export const setPersona = persona => ({
  type: SET_PERSONA,
  value: persona
});

export const SET_PERSONA_FACET = "set_persona_facet";
export const setPersonaFacet = (facet_key, facet_val) => ({
  type: SET_PERSONA_FACET,
  value: { [facet_key]: facet_val }
});

const asyncResetPage = action => {
  return (dispatch, getState) => {
    dispatch(setPage(0));
    return async(action)(dispatch, getState);
  };
};

const async = (action, cb) => {
  return (dispatch, getState) => {
    dispatch(action);
    return cb ? cb(dispatch, getState) : getAds()(dispatch, getState);
  };
};
export const fetchSearch = query => asyncResetPage(newSearch(query));

export const throttledDispatch = debounce((dispatch, input) => {
  dispatch(fetchSearch(input));
}, 750);
// throttledDispatchAny(dispatch, fetchSearch, input) // TODO

export const throttledDispatchAny = debounce((dispatch, func, input) => {
  dispatch(func(input));
}, 750);

export const BATCH = "batch";
export const batch = (...actions) => ({
  type: BATCH,
  actions: actions
});

const a = type => arg => ({ type, value: arg });
export const NEW_ENTITIES = "new_entities";
export const NEW_ADVERTISERS = "new_advertisers";
export const NEW_TARGETS = "new_targets";
export const NEW_STATES = "new_states";
export const NEW_PARTIES = "new_parties";
export const NEW_DISTRICTS = "new_districts";
export const NEW_BY_STATE = "new_by_state"; // this is for the combined state page: ads targeted TO the state, ads mentioning or by candidates in the state
export const newEntities = a(NEW_ENTITIES);
export const newAdvertisers = a(NEW_ADVERTISERS);
export const newTargets = a(NEW_TARGETS);
export const newStates = a(NEW_STATES);
export const newParties = a(NEW_PARTIES);
export const newDistricts = a(NEW_DISTRICTS);
export const newByState = a(NEW_BY_STATE);

// resets advertisers, targets, entities, states, districts, parties
export const CLEAR_ALL_FILTERS = "clear_all_filters";
export const clearAllFilters = () => ({
  type: CLEAR_ALL_FILTERS
});

export const FILTER_ENTITY = "filter_entity";
export const FILTER_ADVERTISER = "filter_advertiser";
export const FILTER_TARGET = "filter_target";
export const FILTER_STATE = "filter_states";
export const FILTER_BY_BY_STATE = "filter_by_by_state"; // this is for the combined state page: ads targeted TO the state, ads mentioning or by candidates in the state
export const FILTER_PARTY = "filter_parties";
export const FILTER_DISTRICT = "filter_districts";
export const filterEntity = a(FILTER_ENTITY);
export const filterAdvertiser = a(FILTER_ADVERTISER);
export const filterTarget = a(FILTER_TARGET);
export const filterState = a(FILTER_STATE);
export const filterByByState = a(FILTER_BY_BY_STATE); // this is for the combined state page: ads targeted TO the state, ads mentioning or by candidates in the state

export const filterParty = a(FILTER_PARTY);
export const filterDistrict = a(FILTER_DISTRICT);
export const fetchEntity = e => asyncResetPage(filterEntity(e));
export const fetchAdvertiser = a => asyncResetPage(filterAdvertiser(a));
export const fetchTarget = t => asyncResetPage(filterTarget(t));
export const fetchState = e => asyncResetPage(filterState(e));
export const fetchParty = a => asyncResetPage(filterParty(a));
export const fetchDistrict = t => asyncResetPage(filterDistrict(t));

export const TOGGLE_TARGET = "toggle_target";
export const TOGGLE_ADVERTISER = "toggle_advertiser";
export const TOGGLE_ENTITY = "toggle_entity";
export const RESET_DROPDOWNS = "reset_dropdowns";
export const toggleTarget = () => ({ type: TOGGLE_TARGET });
export const toggleAdvertiser = () => ({ type: TOGGLE_ADVERTISER });
export const toggleEntity = () => ({ type: TOGGLE_ENTITY });
export const resetDropdowns = () => ({ type: RESET_DROPDOWNS });

export const CHANGE_POLITICAL_PROBABILITY = "change_poliprob";
export const filterbyPoliticalProbability = a(CHANGE_POLITICAL_PROBABILITY);
export const changePoliticalProbability = t =>
  asyncResetPage(filterbyPoliticalProbability(t));

export const SHOW_OLD_SEARCH = "show_old_search";
export const HIDE_OLD_SEARCH = "hide_old_search";
export const showOldSearch = () => ({ type: SHOW_OLD_SEARCH });
export const hideOldSearch = () => ({ type: HIDE_OLD_SEARCH });

export const NEXT_PAGE = "next_page";
export const PREV_PAGE = "prev_page";
export const SET_PAGE = "set_page";
export const SET_TOTAL = "set_total";
export const nextPage = () => ({ type: NEXT_PAGE });
export const fetchNextPage = cb => async(nextPage(), cb);
export const prevPage = () => ({ type: PREV_PAGE });
export const fetchPrevPage = cb => async(prevPage(), cb);
export const setPage = page => ({ type: SET_PAGE, value: page });
export const fetchPage = (page, cb) => async(setPage(page), cb);
export const setTotal = total => ({ type: SET_TOTAL, value: total });

export const TOGGLE_YOUGOV_ONLY = "yougov_only";
export const TOGGLE_NO_LISTFUND = "no_listfund";
export const toggleYouGovOnly = on_or_off => ({
  type: TOGGLE_YOUGOV_ONLY,
  value: on_or_off
});
export const toggleNoListfund = on_or_off => ({
  type: TOGGLE_NO_LISTFUND,
  value: on_or_off
});

// export const SET_BY_STATE = "set_by_state";
// export const setByState = a_state => ({ type: SET_BY_STATE, value: a_state });

export const getOneAd = (ad_id, url = "https://dashboard-backend.qz.ai/pp/ads") => {

  if (!ad_id) return () => null;

  let path = `${url}/${ad_id}`;
  return dispatch => {
    dispatch(requestingOneAd(ad_id));
    return fetch(path, { method: "GET", credentials: "include" })
      .then(res => res.json())
      .then(ad => {
        dispatch(receiveOneAd(ad));
      });
  };
};

export const getStatesAndDistricts = () => {
  let path = `${URL_ROOT}/fbpac-api/states_and_districts`;
  return (dispatch, getState) => {
    let state = getState();

    if (state.lang) {
      path = path + `?lang=${state.lang}`;
    }
    dispatch(requestingStatesAndDistricts());
    return fetch(path, {
      method: "GET",
      credentials: "include",
      redirect: "follow"
    })
      .then(resp => {
        if (resp.redirected === true) {
          window.location.href = `${URL_ROOT}/fbpac-api/partners/sign_in`;
          return null;
        }
        return resp.json();
      })
      .then(resp => {
        dispatch(receiveStatesAndDistricts(resp));
      });
  };
};

export const getGroupedAttrs = (
  groupingKind = "advertiser",
  recent = "by",
  root_url = "https://dashboard-backend.qz.ai/pp/ads"
) => {
  let path = `${root_url}/${recent}_${groupingKind + "s"}`;
  return (dispatch, getState) => {
    let state = getState();
    if (state.lang) {
      path = path + `?lang=${state.lang}`;
    }
    dispatch(requestingRecentGroupedAttr());
    return (
      fetch(path, {
        method: "GET",
        credentials: "include",
        redirect: "follow" // in case we get redirected to the login page.
      })
        .then(resp => {
          if (resp.redirected === true) {
            window.location.href = `${URL_ROOT}/fbpac-api/partners/sign_in`;
            return null;
          }
          return resp.json();
        })
        // .then(res => res.json())
        .then(resp => {
          dispatch(receiveRecentGroupedAttr(resp));
        })
    );
  };
};

export const getAdminSummary = (root_url = "https://dashboard-backend.qz.ai/pp/ads") => {
  let path = `${root_url}/summarize`;
  return (dispatch, getState) => {
    let state = getState();
    if (state.lang) {
      path = path + `?lang=${state.lang}`;
    }
    dispatch(requestingAdminSummary());
    return (
      fetch(path, {
        method: "GET",
        credentials: "include",
        redirect: "follow" // in case we get redirected to the login page.
      })
        .then(resp => {
          if (resp.redirected === true) {
            window.location.href = `${URL_ROOT}/fbpac-api/partners/sign_in`;
            return null;
          }
          return resp.json();
        })
        // .then(res => res.json())
        .then(resp => {
          dispatch(receivedAdminSummary(resp));
        })
    );
  };
};

export const getHomepageSummary = (root_url = "https://dashboard-backend.qz.ai/pp/ads") => {
  let path = `${root_url}/homepage_stats`;
  return (dispatch, getState) => {
    // only support English
    let state = getState();
    if (state.lang) {
      path = path + "?lang=en-US";
    }
    dispatch(requestingHomepageSummary());
    return fetch(path)
      .then(resp => resp.json())
      .then(resp => {
        dispatch(receivedHomepageSummary(resp));
      });
  };
};

export const getAdsByState = (url = `${URL_ROOT}/fbpac-api/ads/by_state`) => {
  return (dispatch, getState) => {
    let state = getState();

    let params = new URLSearchParams();

    if (state.pagination && state.pagination.page) {
      params.set("page", state.pagination.page);
    }

    let query = params.toString().length > 0 ? `?${params.toString()}` : "";
    let new_url = `${"/facebook-ads/admin/by_state/" + state.by_state}${query}`;
    if (location.search !== query) {
      // this history.push is just for when the state got changed  via dropdowns/searches
      // and then we got ads back
      // and then we changed the URL to match
      // we skip the history.push if location.search === query
      // which is true when we got here via a <Link>
      // mutating history OUTSIDE of react-router gets things very confused and you end up with dumb URLs.
      history.push({ search: query }, "", new_url);
    }

    params.set("state", state.by_state); // this is after the history.push because we have states not in the search params but in the path.
    let path = `${url}?${params.toString()}`;

    return fetch(path, { method: "GET", credentials: "include" })
      .then(res => res.json())
      .then(ads => {
        dispatch(
          batch(
            newAds(ads.ads),
            // newEntities(ads.entities),
            // newAdvertisers(ads.advertisers),
            // newTargets(ads.targets),
            setTotal(ads.total),
            setPage(parseInt(params.get("page"), 0) || 0)
          )
        );
      });
  };
};
export const getAds = (url = "https://dashboard-backend.qz.ai/pp/ads") => {
  return (dispatch, getState) => {
    let state = getState();

    let params = new URLSearchParams();
    if (state.persona) {
      /* this fork here is the equivalent of serialize() in utils.js */
      url = "https://dashboard-backend.qz.ai/pp/persona";
      if (state.persona.age) {
        params.set("age_bucket", state.persona.age);
      }
      if (state.persona.location) {
        params.set("location_bucket", state.persona.location);
      }
      if (state.persona.politics) {
        params.set("politics_bucket", state.persona.politics);
      }
      if (state.persona.gender) {
        params.set("gender", state.persona.gender);
      }
      // if (state.persona.name) {
      //   params.set("persona", state.persona.name);
      // }
      if (state.pagination && state.pagination.page) {
        params.set("page", state.pagination.page);
      }
    } else {
      params = serialize(state);
    }

    let path = `${url}?${params.toString()}`;

    let query = params.toString().length > 0 ? `?${params.toString()}` : "";
    let new_url = `${
      /* in admin, fix the URL if we've gotten somewhere weird */
      location.pathname.indexOf("/admin/")
        ? "/facebook-ads/admin/"
        : location.pathname
    }${query}`;
    if (location.search !== query) {
      // this history.push is just for when the state got changed  via dropdowns/searches
      // and then we got ads back
      // and then we changed the URL to match
      // we skip the history.push if location.search === query
      // which is true when we got here via a <Link>
      // mutating history OUTSIDE of react-router gets things very confused and you end up with dumb URLs.
      history.push({ search: query }, "", new_url);
    }
    return fetch(path, { method: "GET", credentials: "include" })
      .then(res => res.json())
      .then(ads => {
        if (state.persona) {
          dispatch(
            batch(
              newAds(ads.ads),
              // newEntities(ads.entities),
              // newAdvertisers(ads.advertisers),
              // newTargets(ads.targets),
              setTotal(ads.total),
              setPage(parseInt(params.get("page"), 0) || 0)
            )
          );
        } else {
          dispatch(
            batch(
              newAds(ads.ads),
              newEntities(ads.entities),
              newAdvertisers(ads.advertisers),
              newTargets(ads.targets),
              setTotal(ads.total),
              setPage(parseInt(params.get("page"), 0) || 0)
            )
          );
        }
      });
  };
};

// Admin actions
export const HIDE_AD = "hide_ad";
export const hideAd = ad => ({
  type: HIDE_AD,
  id: ad.id
});

export const suppressAd = ad => {
  return dispatch => {
    dispatch(hideAd(ad));
    return fetch(`${URL_ROOT}/fbpac-api/ads/${ad.id}/suppress`, {
      method: "PUT",
      body: ad.id,
      credentials: "include"
    }).then(resp => {
      if (!resp.ok) {
        window.location = `${URL_ROOT}/fbpac-api/partners/sign_in`;
      }
    });
  };
};


text:
<title>CHAPTER IX. The Mock Turtle's Story</title>

CHAPTER IX

The Mock Turtle's Story

'You can't think how glad I am to see you again, you dear old
thing!' said the Duchess, as she tucked her arm affectionately
into Alice's, and they walked off together.

Alice was very glad to find her in such a pleasant temper, and
thought to herself that perhaps it was only the pepper that had
made her so savage when they met in the kitchen.

'When I'm a Duchess,' she said to herself, (not in a
very hopeful tone though), 'I won't have any pepper in my kitchen
at all. Soup does very well without--Maybe it's always
pepper that makes people hot-tempered,' she went on, very much
pleased at having found out a new kind of rule, 'and vinegar that
makes them sour--and camomile that makes them bitter--and--and
barley-sugar and such things that make children sweet-tempered. I
only wish people knew that: then they wouldn't be so stingy about
it, you know--'

She had quite forgotten the Duchess by this time, and was a
little startled when she heard her voice close to her ear.
'You're thinking about something, my dear, and that makes you
forget to talk. I can't tell you just now what the moral of that
is, but I shall remember it in a bit.'

'Perhaps it hasn't one,' Alice ventured to remark.

'Tut, tut, child!' said the Duchess. 'Everything's got a
moral, if only you can find it.' And she squeezed herself up
closer to Alice's side as she spoke.

Alice did not much like keeping so close to her: first,
because the Duchess was very ugly; and secondly, because she was
exactly the right height to rest her chin upon Alice's shoulder,
and it was an uncomfortably sharp chin. However, she did not like
to be rude, so she bore it as well as she could.

'The game's going on rather better now,' she said, by way of
keeping up the conversation a little.

''Tis so,' said the Duchess: 'and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'

'Somebody said,' Alice whispered, 'that it's done by everybody
minding their own business!'

'Ah, well! It means much the same thing,' said the Duchess,
digging her sharp little chin into Alice's shoulder as she added,
'and the moral of that is--"Take care of the sense, and
the sounds will take care of themselves."'

'How fond she is of finding morals in things!' Alice thought
to herself.

'I dare say you're wondering why I don't put my arm round your
waist,' the Duchess said after a pause: 'the reason is, that I'm
doubtful about the temper of your flamingo. Shall I try the
experiment?'

'He might bite,' Alice cautiously replied, not feeling
at all anxious to have the experiment tried.

'Very true,' said the Duchess: 'flamingoes and mustard both
bite. And the moral of that is--"Birds of a feather flock
together."'

'Only mustard isn't a bird,' Alice remarked.

'Right, as usual,' said the Duchess: 'what a clear way you
have of putting things!'

'It's a mineral, I think,' said Alice.

'Of course it is,' said the Duchess, who seemed ready to agree
to everything that Alice said; 'there's a large mustard-mine near
here. And the moral of that is--"The more there is of mine, the
less there is of yours."'

'Oh, I know!' exclaimed Alice, who had not attended to this
last remark, 'it's a vegetable. It doesn't look like one, but it
is.'

'I quite agree with you,' said the Duchess; 'and the moral of
that is--"Be what you would seem to be"--or if you'd like it put
more simply--"Never imagine yourself not to be otherwise than
what it might appear to others that what you were or might have
been was not otherwise than what you had been would have appeared
to them to be otherwise."'

'I think I should understand that better,' Alice said very
politely, 'if I had it written down: but I can't quite follow it
as you say it.'

'That's nothing to what I could say if I chose,' the Duchess
replied, in a pleased tone.

'Pray don't trouble yourself to say it any longer than that,'
said Alice.

'Oh, don't talk about trouble!' said the Duchess. 'I make you
a present of everything I've said as yet.'

'A cheap sort of present!' thought Alice. 'I'm glad they don't
give birthday presents like that!' But she did not venture to say
it out loud.

'Thinking again?' the Duchess asked, with another dig of her
sharp little chin.

'I've a right to think,' said Alice sharply, for she was
beginning to feel a little worried.

'Just about as much right,' said the Duchess, 'as pigs have to
fly; and the m--'

But here, to Alice's great surprise, the Duchess's voice died
away, even in the middle of her favourite word 'moral,' and the
arm that was linked into hers began to tremble. Alice looked up,
and there stood the Queen in front of them, with her arms folded,
frowning like a thunderstorm.

'A fine day, your Majesty!' the Duchess began in a low, weak
voice.

'Now, I give you fair warning,' shouted the Queen, stamping on
the ground as she spoke; 'either you or your head must be off,
and that in about half no time! Take your choice!'

The Duchess took her choice, and was gone in a moment.

'Let's go on with the game,' the Queen said to Alice; and
Alice was too much frightened to say a word, but slowly followed
her back to the croquet-ground.

The other guests had taken advantage of the Queen's absence,
and were resting in the shade: however, the moment they saw her,
they hurried back to the game, the Queen merely remarking that a
moment's delay would cost them their lives.

All the time they were playing the Queen never left off
quarrelling with the other players, and shouting 'Off with his
head!' or 'Off with her head!' Those whom she sentenced were
taken into custody by the soldiers, who of course had to leave
off being arches to do this, so that by the end of half an hour
or so there were no arches left, and all the players, except the
King, the Queen, and Alice, were in custody and under sentence of
execution.

Then the Queen left off, quite out of breath, and said to
Alice, 'Have you seen the Mock Turtle yet?'

'No,' said Alice. 'I don't even know what a Mock Turtle
is.'

'It's the thing Mock Turtle Soup is made from,' said the
Queen.

'I never saw one, or heard of one,' said Alice.

'Come on, then,' said the Queen, 'and he shall tell you his
history,'

As they walked off together, Alice heard the King say in a low
voice, to the company generally, 'You are all pardoned.' 'Come,
that's a good thing!' she said to herself, for she had
felt quite unhappy at the number of executions the Queen had
ordered.

They very soon came upon a Gryphon, lying fast asleep in the
sun. (If you don't know what a Gryphon is, look at the picture.)
'Up, lazy thing!' said the Queen, 'and take this young lady to
see the Mock Turtle, and to hear his history. I must go back and
see after some executions I have ordered'; and she walked off,
leaving Alice alone with the Gryphon. Alice did not quite like
the look of the creature, but on the whole she thought it would
be quite as safe to stay with it as to go after that savage
Queen: so she waited.

The Gryphon sat up and rubbed its eyes: then it watched the
Queen till she was out of sight: then it chuckled. 'What fun!'
said the Gryphon, half to itself, half to Alice.

'What is the fun?' said Alice.

'Why, she,' said the Gryphon. 'It's all her fancy,
that: they never executes nobody, you know. Come on!'

'Everybody says "come on!" here,' thought Alice, as she went
slowly after it: 'I never was so ordered about in all my life,
never!'

They had not gone far before they saw the Mock Turtle in the
distance, sitting sad and lonely on a little ledge of rock, and,
as they came nearer, Alice could hear him sighing as if his heart
would break. She pitied him deeply. 'What is his sorrow?' she
asked the Gryphon, and the Gryphon answered, very nearly in the
same words as before, 'It's all his fancy, that: he hasn't got no
sorrow, you know. Come on!'

So they went up to the Mock Turtle, who looked at them with
large eyes full of tears, but said nothing.

'This here young lady,' said the Gryphon, 'she wants for to
know your history, she do.'

'I'll tell it her,' said the Mock Turtle in a deep, hollow
tone: 'sit down, both of you, and don't speak a word till I've
finished.'

So they sat down, and nobody spoke for some minutes. Alice
thought to herself, 'I don't see how he can even finish,
if he doesn't begin.' But she waited patiently.

'Once,' said the Mock Turtle at last, with a deep sigh, 'I was
a real Turtle.'

These words were followed by a very long silence, broken only
by an occasional exclamation of 'Hjckrrh!' from the Gryphon, and
the constant heavy sobbing of the Mock Turtle. Alice was very
nearly getting up and saying, 'Thank you, sir, for your
interesting story,' but she could not help thinking there
must be more to come, so she sat still and said
nothing.

'When we were little,' the Mock Turtle went on at last, more
calmly, though still sobbing a little now and then, 'we went to
school in the sea. The master was an old Turtle--we used to call
him Tortoise--'

'Why did you call him Tortoise, if he wasn't one?' Alice
asked.

'We called him Tortoise because he taught us,' said the Mock
Turtle angrily: 'really you are very dull!'

'You ought to be ashamed of yourself for asking such a simple
question,' added the Gryphon; and then they both sat silent and
looked at poor Alice, who felt ready to sink into the earth. At
last the Gryphon said to the Mock Turtle, 'Drive on, old fellow!
Don't be all day about it!' and he went on in these words:

'Yes, we went to school in the sea, though you mayn't believe
it--'

'I never said I didn't!' interrupted Alice.

'You did,' said the Mock Turtle.

'Hold your tongue!' added the Gryphon, before Alice could
speak again. The Mock Turtle went on.

'We had the best of educations--in fact, we went to school
every day--'

'I've been to a day-school, too,' said Alice; 'you
needn't be so proud as all that.'

'With extras?' asked the Mock Turtle a little anxiously.

'Yes,' said Alice, 'we learned French and music.'

'And washing?' said the Mock Turtle.

'Certainly not!' said Alice indignantly.

'Ah! then yours wasn't a really good school,' said the Mock
Turtle in a tone of great relief. 'Now at ours they had at
the end of the bill, "French, music, and
washing--extra."'

'You couldn't have wanted it much,' said Alice; 'living at the
bottom of the sea.'

'I couldn't afford to learn it.' said the Mock Turtle with a
sigh. 'I only took the regular course.'

'What was that?' inquired Alice.

'Reeling and Writhing, of course, to begin with,' the Mock
Turtle replied; 'and then the different branches of Arithmetic--
Ambition, Distraction, Uglification, and Derision.'

'I never heard of "Uglification,"' Alice ventured to say.
'What is it?'

The Gryphon lifted up both its paws in surprise. 'What! Never
heard of uglifying!' it exclaimed. 'You know what to beautify is,
I suppose?'

'Yes,' said Alice doubtfully: 'it
means--to--make--anything--prettier.'

'Well, then,' the Gryphon went on, 'if you don't know what to
uglify is, you are a simpleton.'

Alice did not feel encouraged to ask any more questions about
it, so she turned to the Mock Turtle, and said 'What else had you
to learn?'

'Well, there was Mystery,' the Mock Turtle replied, counting
off the subjects on his flappers, '--Mystery, ancient and modern,
with Seaography: then Drawling--the Drawling-master was an old
conger-eel, that used to come once a week: He taught us
Drawling, Stretching, and Fainting in Coils.'

'What was that like?' said Alice.

'Well, I can't show it you myself,' the Mock Turtle said: 'I'm
too stiff. And the Gryphon never learnt it.'

'Hadn't time,' said the Gryphon: 'I went to the Classics
master, though. He was an old crab, he was.'

'I never went to him,' the Mock Turtle said with a sigh: 'he
taught Laughing and Grief, they used to say.'

'So he did, so he did,' said the Gryphon, sighing in his turn;
and both creatures hid their faces in their paws.

'And how many hours a day did you do lessons?' said Alice, in
a hurry to change the subject.

'Ten hours the first day,' said the Mock Turtle: 'nine the
next, and so on.'

'What a curious plan!' exclaimed Alice.

'That's the reason they're called lessons,' the Gryphon
remarked: 'because they lessen from day to day.'

This was quite a new idea to Alice, and she thought it over a
little before she made her next remark. 'Then the eleventh day
must have been a holiday?'

'Of course it was,' said the Mock Turtle.

'And how did you manage on the twelfth?' Alice went on
eagerly.

'That's enough about lessons,' the Gryphon interrupted in a
very decided tone: 'tell her something about the games now.'