text:
using System;
using System.Windows.Forms;
using stClient;
using System.Globalization;

namespace stCoCClient
{
    public partial class ClientForm : Form
    {
        public void _IRCInit()
        {
            try
            {
                if (!this._CheckSetupIRCChat())
                {
                    throw new ArgumentException(Properties.Resources.txtIRCSetupErrorComplette);
                }

                int port = 0;

                if (!Int32.TryParse(Properties.Settings.Default.IRCPort, out port))
                {
                    throw new ArgumentException(Properties.Resources.txtIRCSetupErrorPort);
                }

                if (this.Irc != null)
                {
                    this.Irc.Disconnect();
                    this.Irc.Dispose();
                    this.Irc = null;
                }

                this.Irc = new IrcClient(
                    Properties.Settings.Default.IRCServer,
                    port
                );
                this.Irc.Nick = this._IRCGetNickName(Properties.Settings.Default.IRCNik);
                this.Irc.ConsoleOutput = false;
                this.Irc.KickRespawn = Properties.Settings.Default.IRCKickRespawn;
                this.Irc.ServerPass =
                    ((!string.IsNullOrWhiteSpace(Properties.Settings.Default.IRCPassword)) ?
                        Properties.Settings.Default.IRCPassword : ""
                    );
                this.Irc.iLog = this._iLog;
                this._InitIrcCallBack();
            }
            catch (Exception ex)
            {
                this._winMessageError(ex.Message);
            }
        }
        public void _WBInit()
        {
            this.isWebBrowser = false;
            ((HtmlDocument)this.WBChat.Document).Write(String.Empty);
            this.WBChat.DocumentText = Properties.Resources.webChatTemplate;
            this.WBChat.ObjectForScripting = this;
            while (this.WBChat.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            this.isWebBrowser = true;
            lock (webwLock)
            {
                this.WBChat.Document.InvokeScript("MsgPrn",
                    new object[]
                    {
                        "msghistory",
                        this._IRCArchiveUrl(),
                        Properties.Resources.txtChatIrcArchive
                    }
                );
            }
        }
        public string _IRCGetNickName(string val)
        {
            if (val.Length < 8)
            {
                for (int i = val.Length; i <= 8; i++)
                {
                    val += "_";
                }
            }
            return val;
        }
        public string _IRCChatToHTML(string val)
        {
            if (Properties.Settings.Default.IRCChatEmojiEnabled)
            {
                val = val.EmoticonsToHtml(Properties.Resources.fmtEmojiHtml);
            }
            if (Properties.Settings.Default.IRCChatBBCodeEnabled)
            {
                val = val.BBCodeToHtml();
            }
            return val;
        }
        private string _IRCArchiveUrl()
        {
            try
            {
                return string.Format(
                    Properties.Settings.Default.URLIrcArchive,
                    Properties.Settings.Default.USRCoCServer,
                    ((Properties.Settings.Default.USRUrl.Count >= 4) ? Properties.Settings.Default.USRUrl[3] : "irclog"),
                    DateTime.Now.AddDays(-1).ToString("yyyy/MM/dd", CultureInfo.InvariantCulture)
                );
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


text:
<?php

final class DrydockLogListController extends DrydockLogController {

  public function shouldAllowPublic() {
    return true;
  }

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $engine = new DrydockLogSearchEngine();

    $id = $request->getURIData('id');
    $type = $request->getURIData('type');
    switch ($type) {
      case 'blueprint':
        $blueprint = id(new DrydockBlueprintQuery())
          ->setViewer($viewer)
          ->withIDs(array($id))
          ->executeOne();
        if (!$blueprint) {
          return new Aphront404Response();
        }
        $engine->setBlueprint($blueprint);
        $this->setBlueprint($blueprint);
        break;
      case 'resource':
        $resource = id(new DrydockResourceQuery())
          ->setViewer($viewer)
          ->withIDs(array($id))
          ->executeOne();
        if (!$resource) {
          return new Aphront404Response();
        }
        $engine->setResource($resource);
        $this->setResource($resource);
        break;
      case 'lease':
        $lease = id(new DrydockLeaseQuery())
          ->setViewer($viewer)
          ->withIDs(array($id))
          ->executeOne();
        if (!$lease) {
          return new Aphront404Response();
        }
        $engine->setLease($lease);
        $this->setLease($lease);
        break;
      default:
        return new Aphront404Response();
    }

    $query_key = $request->getURIData('queryKey');

    $controller = id(new PhabricatorApplicationSearchController())
      ->setQueryKey($query_key)
      ->setSearchEngine($engine)
      ->setNavigation($this->buildSideNavView());

    return $this->delegateToController($controller);
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Tests\Core\Fixtures;

class DependedClass
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var SampleClass
     */
    private $sample;

    /**
     * @param string      $name
     * @param SampleClass $sample
     */
    public function __construct(string $name, SampleClass $sample)
    {
        $this->name = $name;
        $this->sample = $sample;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return SampleClass
     */
    public function getSample()
    {
        return $this->sample;
    }
}


text:
import gulp from 'gulp';
import jasmine from 'gulp-jasmine'
import plumber from 'gulp-plumber';

gulp.task('spec-run', () => {
  return gulp.src(['spec/**/*_spec.js', '!spec/fixtures/**/*.js'])
    .pipe(plumber())
    .pipe(jasmine({includeStackTrace: true}));
});

gulp.task('spec', gulp.series('build', 'spec-run'));


text:
package br.com.agneresteves.ef.core.transformer.parser.text;

import br.com.agneresteves.ef.core.transformer.parser.Parseable;
import br.com.agneresteves.ef.core.transformer.parser.ReferenceParser;
import br.com.agneresteves.ef.core.transformer.processor.text.AnyTextProcessor;
import org.petitparser.parser.Parser;

import static org.petitparser.parser.primitive.CharacterParser.any;
import static org.petitparser.parser.primitive.StringParser.of;

/**
 * AnyTextParser
 * I
 *
 * @author Agner Esteves Ballejo
 * @since 19/11/2017
 */
public class AnyTextParser extends Parseable {

    @Override
    public String getRefName() {
        return "anyText";
    }

    @Override
    public Parser getParser() {
        return
            this.map(
                any().starLazy(of(ReferenceParser.MAIN_TAG.getOpenTag())).trim().flatten()
                .or(any().starLazy(of(ReferenceParser.SHOW_VALUE_TAG.getOpenTag())).trim().flatten())
                .or(any().star().flatten())
            );
    }

    private Parser map(Parser parser) {
        return parser.map((String text) -> {
            return new AnyTextProcessor(text);
        });
    }

}


text:
**Tutorials:**
- [Configuration](./tutorials/config.md)
- [Working with branches](./tutorials/working_with_branches.md (`branch`, `merge`, `rebase`))
- [Git damage control](./tutorials/damage_control.md)
- [Submodules](./tutorials/submodule.md)
- [Repositories](./tutorials/repositories.md)
- [Diff files](./tutorials/diff.md)

-----------------------------------------------------------

**Commands:**
- [`checkout`](./commands/checkout.md)
- [`commit`](./commands/commit.md)
- [`diff`](./commands/diff.md)
- [`fetch`](./commands/fetch.md)
- [`log`](./commands/log.md)
- [`merge`](./commands/merge.md)
- [`pull`](./commands/pull.md)
- [`push`](./commands/push.md)
- [`stash`](./commands/stash.md)
- [`tag`](./commands/tag.md)

------------------------------------------------------------

**Troubleshooting**
- [Resolving merge conflict](./troubleshooting/merge_conficts.md)
- [Troubleshooting](./troubleshooting/troubleshooting.md)

------------------------------------------------------------

**`git` and editor(s):**
- [vim](./editors/vim/)

------------------------------------------------------------

**Other:**
- [ssh](./other/ssh.md)


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.AppPlatform.Models;

namespace Azure.ResourceManager.AppPlatform
{
    internal partial class CustomDomainsRestOperations
    {
        private readonly TelemetryDetails _userAgent;
        private readonly HttpPipeline _pipeline;
        private readonly Uri _endpoint;
        private readonly string _apiVersion;

        /// <summary> Initializes a new instance of CustomDomainsRestOperations. </summary>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="applicationId"> The application id to use for user agent. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
        public CustomDomainsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
        {
            _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
            _endpoint = endpoint ?? new Uri("https://management.azure.com");
            _apiVersion = apiVersion ?? "2022-03-01-preview";
            _userAgent = new TelemetryDetails(GetType().Assembly, applicationId);
        }

        internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.AppPlatform/Spring/", false);
            uri.AppendPath(serviceName, true);
            uri.AppendPath("/apps/", false);
            uri.AppendPath(appName, true);
            uri.AppendPath("/domains/", false);
            uri.AppendPath(domainName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Get the custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<AppPlatformCustomDomainResourceData>> GetAsync(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AppPlatformCustomDomainResourceData value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = AppPlatformCustomDomainResourceData.DeserializeAppPlatformCustomDomainResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((AppPlatformCustomDomainResourceData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Get the custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<AppPlatformCustomDomainResourceData> Get(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));

            using var message = CreateGetRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AppPlatformCustomDomainResourceData value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = AppPlatformCustomDomainResourceData.DeserializeAppPlatformCustomDomainResourceData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((AppPlatformCustomDomainResourceData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.AppPlatform/Spring/", false);
            uri.AppendPath(serviceName, true);
            uri.AppendPath("/apps/", false);
            uri.AppendPath(appName, true);
            uri.AppendPath("/domains/", false);
            uri.AppendPath(domainName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(data);
            request.Content = content;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Create or update custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="data"> Parameters for the create or update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/>, <paramref name="domainName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName, data);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Create or update custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="data"> Parameters for the create or update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/>, <paramref name="domainName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName, data);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 201:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Delete;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.AppPlatform/Spring/", false);
            uri.AppendPath(serviceName, true);
            uri.AppendPath("/apps/", false);
            uri.AppendPath(appName, true);
            uri.AppendPath("/domains/", false);
            uri.AppendPath(domainName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Delete the custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Delete the custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Delete(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));

            using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                case 204:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Patch;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.AppPlatform/Spring/", false);
            uri.AppendPath(serviceName, true);
            uri.AppendPath("/apps/", false);
            uri.AppendPath(appName, true);
            uri.AppendPath("/domains/", false);
            uri.AppendPath(domainName, true);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();
            content.JsonWriter.WriteObjectValue(data);
            request.Content = content;
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Update custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="data"> Parameters for the create or update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/>, <paramref name="domainName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response> UpdateAsync(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName, data);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Update custom domain of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="domainName"> The name of the custom domain resource. </param>
        /// <param name="data"> Parameters for the create or update operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/>, <paramref name="domainName"/> or <paramref name="data"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/>, <paramref name="appName"/> or <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response Update(string subscriptionId, string resourceGroupName, string serviceName, string appName, string domainName, AppPlatformCustomDomainResourceData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));
            Argument.AssertNotNullOrEmpty(domainName, nameof(domainName));
            Argument.AssertNotNull(data, nameof(data));

            using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, serviceName, appName, domainName, data);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                case 202:
                    return message.Response;
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string serviceName, string appName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/subscriptions/", false);
            uri.AppendPath(subscriptionId, true);
            uri.AppendPath("/resourceGroups/", false);
            uri.AppendPath(resourceGroupName, true);
            uri.AppendPath("/providers/Microsoft.AppPlatform/Spring/", false);
            uri.AppendPath(serviceName, true);
            uri.AppendPath("/apps/", false);
            uri.AppendPath(appName, true);
            uri.AppendPath("/domains", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> List the custom domains of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<CustomDomainResourceList>> ListAsync(string subscriptionId, string resourceGroupName, string serviceName, string appName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));

            using var message = CreateListRequest(subscriptionId, resourceGroupName, serviceName, appName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        CustomDomainResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = CustomDomainResourceList.DeserializeCustomDomainResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> List the custom domains of one lifecycle application. </summary>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<CustomDomainResourceList> List(string subscriptionId, string resourceGroupName, string serviceName, string appName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));

            using var message = CreateListRequest(subscriptionId, resourceGroupName, serviceName, appName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        CustomDomainResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = CustomDomainResourceList.DeserializeCustomDomainResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string serviceName, string appName)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> List the custom domains of one lifecycle application. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is an empty string, and was expected to be non-empty. </exception>
        public async Task<Response<CustomDomainResourceList>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string serviceName, string appName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));

            using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, serviceName, appName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        CustomDomainResourceList value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = CustomDomainResourceList.DeserializeCustomDomainResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> List the custom domains of one lifecycle application. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="subscriptionId"> Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
        /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
        /// <param name="serviceName"> The name of the Service resource. </param>
        /// <param name="appName"> The name of the App resource. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is null. </exception>
        /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serviceName"/> or <paramref name="appName"/> is an empty string, and was expected to be non-empty. </exception>
        public Response<CustomDomainResourceList> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string serviceName, string appName, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));
            Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
            Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
            Argument.AssertNotNullOrEmpty(serviceName, nameof(serviceName));
            Argument.AssertNotNullOrEmpty(appName, nameof(appName));

            using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, serviceName, appName);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        CustomDomainResourceList value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = CustomDomainResourceList.DeserializeCustomDomainResourceList(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary">

        <TextView
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textSize="22sp"
            android:textColor="#fff"
            />

        <Button
            android:id="@+id/back_button"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:background="@drawable/ic_back"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"/>

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="ifContentScrolls">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
import contextlib
import os
import pexpect
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import threading
import warnings
import weakref

# A list of weakrefs to all plots ever created.
_allplots = []

class CommunicationError(RuntimeError):
    """Raised when communication with Gnuplot subprocess failed."""

class GnuplotError(RuntimeError):
    """Raised when Gnuplot (is known to have) responded with an error."""

class RawGnuplot(object):
    """Low-level manager for communication with a Gnuplot subprocess.

    A RawGnuplot instance encapsulates a dedicated Gnuplot process and the
    means for communication with it through a pseudoterminal. It can pass data
    to Gnuplot using a temporary file or pipe, but is agnostic of the format of
    commands and data (see __call__()).

    Methods:
    __init__() - constructor
    __call__() - send command(s), optionally passing data, and receive output
    interact() - allow user to interact directly with Gnuplot
    close() - close the Gnuplot process (called automatically on destruction)
    terminate() - terminate the Gnuplot process
    isalive() - check whether the Gnuplot process is alive
    pause() - send a `pause' command to Gnuplot (disregarding timeout)
    quote() (static method) - quote a filename for use in a Gnuplot command

    Attributes:
    timeout - timeout for pty i/o (in seconds)
    debug - if true, echo commands sent and output received
    """

    gp_prompt = "gnuplot> "
    send_chunk_length = 512

    def __init__(self, command=None, persist=False, tempdir=None,
                 testecho=False):
        """Return a new Gnuplot object.

        Keyword Arguments:
        command - The command used to invoke Gnuplot. Defaults to `gnuplot',
                  unless the environment variable XNUPLOT_GNUPLOT is defined,
                  in which case its value is used.
        persist - Whether the plot window should stay open after this object
                  (and hence the Gnuplot subprocess) is destroyed.
        tempdir - Directory to use for temporary data. A new directory is
                  created within the given directory, whose name is stored in
                  self.tempdir.
        testecho - Check to see if the assumptions we make about how Gnuplot
                   echoes commands are correct. Try setting this to True if
                   you suspect xnuplot is not properly communicating with
                   Gnuplot.
        """
        self._debug = False
        self.tempdir = tempfile.mkdtemp(prefix="xnuplot.", dir=tempdir)

        if not command:
            if "XNUPLOT_GNUPLOT" in os.environ:
                command = os.environ["XNUPLOT_GNUPLOT"]
            else:
                command = "gnuplot"

        if persist:
            command += " -persist"
        try:
            self.gp_proc = pexpect.spawn(command)
            self.gp_proc.delaybeforesend = 0
        except:
            os.rmdir(self.tempdir)
            raise

        ok = False
        try:
            self.gp_proc.expect_exact(self.gp_prompt)
            ok = True
        except pexpect.EOF:
            raise CommunicationError("Gnuplot died before showing prompt")
        except pexpect.TIMEOUT:
            raise CommunicationError("timeout")
        finally:
            if not ok:
                self.terminate()

        if testecho:
            self._test_readline_echo()

        global _allplots
        _allplots.append(weakref.ref(self))

    def __enter__(self):
        return self
    def __exit__(self, type, value, traceback):
        self.close()
    def __del__(self):
        self.close()

    def close(self):
        """Close the Gnuplot subprocess and remove all temporary files."""
        # Soft quitting is no different from force-quitting.
        self.terminate()

    def terminate(self):
        """Force-quit the Gnuplot subprocess and remove all temporary files."""
        if self.gp_proc is not None:
            self.gp_proc.close(force=True)
            self.gp_proc = None
        if self.tempdir:
            shutil.rmtree(self.tempdir)
            self.tempdir = None

    def isalive(self):
        return self.gp_proc is not None and self.gp_proc.isalive()

    def __call__(self, command, **data):
        """Send a command (or commands) to Gnuplot.

        The output from Gnuplot is returned as a string. If command contains
        multiple lines, nonempty outputs from each command are concatenated
        with newlines as separators. Thus, if none of the commands printed
        anything, an empty string is returned.

        A special mechanism is provided to send data to Gnuplot, using what
        Gnuplot calls a `datafile'. This can be done by placing strings of the
        form `{{foo}}' (we call this a data placefolder with name `foo') within
        the command, where normally a quoted filename would appear. Then, the
        data that Gnuplot should read should be supplied as a keyword argument.
        The data can be any object that, when written to a file, generates the
        correct representation for Gnuplot.

        For example:
        gp = Gnuplot()
        gp("plot {{data}} volatile notitle with lines", data="1 2\n2 1\n3 3")

        The actual passing of data is achieved, by default, through the use of
        named pipes (FIFOs). This works well most of the time, but there are
        some cases where Gnuplot requires random access to the data, where
        pipes fail (one example of this is the `binary matrix' data format). To
        handle such cases, use of a temporary file can be forced by the syntax
        `{{file:foo}}'. The default syntax (`{{foo}}') is equivalent to
        `{{pipe:foo}}'.
        """
        if not self.isalive():
            raise CommunicationError("Gnuplot process has exited.")
        results = []
        for cmd in command.split("\n"):
            result = self._send_one_command(cmd, **data)
            if result is None:
                # None is returned when Gnuplot exited normally.
                break
            if result:
                results.append(result)
        return "\n".join(results)

    _placeholder_pattern = re.compile(
            r"\{\{((?P<mode>file|pipe):)?(?P<name>[a-zA-Z_][a-zA-Z0-9_]*)\}\}")
    @contextlib.contextmanager
    def _placeholders_substituted(self, command, **data):
        substituted_command = ""
        start_of_next_chunk = 0 # Position after current placeholder.
        pipes = []
        for placeholder in self._placeholder_pattern.finditer(command):
            name = placeholder.group("name")
            mode = placeholder.group("mode")
            pipeclass = (_OutboundTempFile if mode == "file"
                         else _OutboundNamedPipe)
            pipe = pipeclass(data[name], dir=self.tempdir)
            pipe.debug = self.debug
            pipes.append(pipe)
            span_start, span_stop = placeholder.span(0)
            substituted_command += command[start_of_next_chunk:span_start]
            substituted_command += Gnuplot.quote(pipe.path)
            start_of_next_chunk = span_stop
        substituted_command += command[start_of_next_chunk:]
        yield substituted_command
        for pipe in pipes:
            pipe.cleanup()

    def _sendline(self, line):
        # The os.write() call used by pexpect seems to hang when the string
        # sent is too long, at least on Mac OS X and Gnuplot built with GNU
        # readline. Merely sending the line in small chunks does not prevent
        # the hangs; it is necessary to read the echo after each chunk is sent.
        # (Thus, it appears that Gnuplot or libreadline blocks on the echo
        # write.) To work around this issue, we send the line in small chunks
        # and make pexpect read and buffer the echo after each send.
        chunk_length = self.send_chunk_length
        n_nonend_chunks = len(line) // chunk_length
        for i in xrange(n_nonend_chunks):
            start = i * chunk_length
            stop = start + chunk_length
            self.gp_proc.send(line[start:stop])
            # Cause pexpect to read in the echo.
            self.gp_proc.expect(pexpect.TIMEOUT, timeout=0)
        start = n_nonend_chunks * chunk_length
        self.gp_proc.sendline(line[start:])
        # Skip over the echoed command (see _test_readline_echo()).
        self.gp_proc.expect_exact("\r\n")

    def _send_one_command(self, command, _extra_newline=False, **data):
        # Do the acutal work for __call__().
        with self._placeholders_substituted(command, **data) as command:
            try:
                self._sendline(command)
            except KeyboardInterrupt, e:
                # Kill Gnuplot if it hangs and the user terminates the
                # command.
                self.terminate()
                raise CommunicationError("killed by user")
            if _extra_newline:
                self.gp_proc.sendline("")

            try:
                self.gp_proc.expect_exact(self.gp_prompt)
                result = self.gp_proc.before
                if _extra_newline:
                    self.gp_proc.expect_exact(self.gp_prompt)
                return result.replace("\r\n", "\n")
            except pexpect.EOF:
                self.terminate()
                if re.match(r"\s*(quit|exit)(\W|$)", command):
                    return None
                else:
                    raise CommunicationError("Gnuplot died")
            except pexpect.TIMEOUT:
                self.terminate()
                raise CommunicationError("timeout")

    def pause(self, *params):
        command = " ".join(("pause",) + params)
        # At least with the tested build of Gnuplot 4.4.0 on Mac OS X, closing
        # the window does not cause `pause mouse close' to immediately return.
        # Sending an extra newline appears to get around the block, so here is
        # a special workaround.
        send_extra_newline = False
        if len(params) and params[0].startswith("mouse"):
            send_extra_newline = True

        # Temporarily disable the timeout for a `pause' command.
        save_timeout = self.timeout
        try:
            self.timeout = None
            self._send_one_command(command, _extra_newline=send_extra_newline)
        finally:
            if self.isalive():
                self.timeout = save_timeout

    def _test_readline_echo(self):
        # Determine how Gnuplot echoes the command. If Gnuplot is built without
        # readline support, it will simply let the tty do the echo. However, if
        # built with readline support (builtin, GNU readline, or BSD libedit),
        # then it will turn off the tty echo and echo each input character on
        # its own. Thus, we expect to receive an echo regardless of what
        # gp_proc.getecho() reports.
        #
        # To further complicate matters, GNU readline and BSD libedit insert
        # control characters into the echoed text, in an attempt to move the
        # cursor to the beginning of the next line whenever a character is
        # entered in what would be the rightmost column of a real terminal.
        # This causes us to see the sequence " \r" (GNU) or " \b" (BSD) every
        # 80 characters (or whatever the width of the tty), at least with the
        # versions I've tested (Gnuplot's builtin readline does not insert any
        # extra characters). The exact behavior may also depend on the
        # particular terminal in use.
        #
        # Fortunately, we can still just skip over to the first "\r\n" in
        # all of the known cases. We just make sure here that these assumptions
        # hold.

        unknown_behavior_msg = ("Gnuplot is echoing commands in an unexpected "
                                "fashion. Xnuplot does not (yet) know how to "
                                "handle this. Please file a bug report. ")
        # First, test a single-character command line.
        self.gp_proc.sendline("#")
        self.gp_proc.expect_exact(self.gp_prompt)
        echo = self.gp_proc.before
        if echo != "#\r\n":
            raise CommunicationError(unknown_behavior_msg +
                                     "(\"#\" -> \"{0}\")".format(repr(echo)))
        # Second, test a command line long enough to be wrapped.
        rows, cols = self.gp_proc.getwinsize()
        test_cmd = "#" * (cols * 3)
        self.gp_proc.sendline(test_cmd)
        self.gp_proc.expect_exact(self.gp_prompt)
        echo = self.gp_proc.before[:-2] # Remove trailing "\r\n".
        if echo == test_cmd:
            # Okay: exact echo.
            return
        breaks = filter(None, echo.split("#"))
        for b in breaks[1:]:
            if b != breaks[0]:
                raise CommunicationError(unknown_behavior_msg +
                                         "(nonuniform linebreaks)")
        if "\r\n" in breaks[0]:
            raise CommunicationError(unknown_behavior_msg +
                                     "(extra CRLFs inserted)")
        else:
            # Okay: whatever is inserted into the echo, it does not contain
            # the "\r\n" sequence.
            return

    def interact(self):
        """Interact directly with the Gnuplot subprocess.

        Handles control of the subprocess to the user.
        The interactive session can be terminated by typing CTRL-].
        """
        if not self.isalive():
            raise CommunicationError("Gnuplot process has exited.")
        # TODO Should probably check that (Python's) stdin is a terminal.
        # Debug mode (echoing) is a mere annoyance when in interactive mode.
        @contextlib.contextmanager
        def debug_turned_off():
            save_debug = self.debug
            self.debug = False
            yield
            self.debug = save_debug
        with debug_turned_off():
            print >>sys.stderr, "escape character is `^]'"
            # Send a black command so that the prompt is printed.
            self.gp_proc.sendline("")
            self.gp_proc.interact()

        # The user could have quit Gnuplot.
        if not self.gp_proc.isalive():
            self.terminate()

    @property
    def timeout(self):
        "Timeout (in seconds) for replies from Gnuplot."
        if not self.isalive():
            raise CommunicationError("Gnuplot process has exited.")
        return self.gp_proc.timeout

    @timeout.setter
    def timeout(self, seconds):
        if not self.isalive():
            raise CommunicationError("Gnuplot process has exited.")
        self.gp_proc.timeout = seconds

    @property
    def debug(self):
        "Echo communication with Gnuplot if true."
        return self._debug

    @debug.setter
    def debug(self, debug):
        self._debug = debug
        if self.isalive():
            self.gp_proc.logfile_read = (sys.stderr if debug else None)

    @staticmethod
    def quote(filename):
        """Return a quoted string for use as part of a Gnuplot command."""
        quoted =  "'" + filename.replace("\\", "\\\\").replace("'", "\\'") + "'"
        return quoted

class Gnuplot(RawGnuplot):
    """Manager for communication with a Gnuplot subprocess.

    The Gnuplot class inherits from RawGnuplot and adds methods (plot(),
    splot(), replot(), fit(), script()) that simplify the passing of data when
    issuing commands that require data to be read from files.
    """
    def _datafilespec(self, data, name):
        if not isinstance(data, PlotData):
            data = PlotData(*data)
        double_brace = lambda s: "{{" + s + "}}"
        if data.mode == "file":
            spec = double_brace("file:{0}".format(name))
        else:
            spec = double_brace("pipe:{0}".format(name))
        spec += " volatile"
        if data.options:
            spec = " ".join((spec, data.options))
        return spec, data.data

    def _plot(self, cmd, *items):
        if not items:
            return
        # Common implementation for plot() and splot().
        item_strings = []
        data_dict = {}
        for i, item in enumerate(items):
            if isinstance(item, basestring):
                item_strings.append(item)
            else:
                placeholder = "item{0:03d}".format(i)
                spec, data = self._datafilespec(item, placeholder)
                item_strings.append(spec)
                data_dict[placeholder] = data
        result = self(cmd + " " + ", ".join(item_strings), **data_dict)
        # Result should be the empty string if successful.
        if len(result):
            # Remove Gnuplot's syntax error pointer.
            msg = result.strip().lstrip("^").strip()
            # XXX Our handling of Gnuplot warnings is not perfect.
            warnings_only = True
            for line in msg.splitlines():
                if re.match(r"\s*[Ww]arning: ", line):
                    warnings.warn(line.strip())
                elif line.strip():
                    warnings_only = False
            if not warnings_only:
                raise GnuplotError("`{0}' returned error".format(cmd), msg)

    def plot(self, *items):
        """Issue a `plot' command with the given items.

        Each item can be a string, a PlotData instance, or a tuple (which is
        used as the argument list to construct a PlotData instance).

        See also: splot(), replot()

        Example:
        Gnuplot().plot("sin(x) notitle", "'some_file.dat' with lp",
                       (some_data, "binary array=(512,512) with image"))
        """
        self._plot("plot", *items)

    def splot(self, *items):
        """Issue an `splot' command with the given items.

        See the documentation for plot().
        """
        self._plot("splot", *items)

    def replot(self, *items):
        """Issue a `replot' command with the given items.

        See the documentation for plot().

        Note that `replot' does not work when the previous plot was made by
        passing data to Gnuplot, unless temporary files were used explicitly.
        """
        self._plot("replot", *items)

    def fit(self, data, expr, via, ranges=None):
        """Issue a `fit' command.

        As with the items in plot(), data can be a PlotData instance or a tuple
        (which is used as the argument list to construct a PlotData), but not a
        string.
        The other arguments (expr, via, and ranges) must be strings.
        """
        spec, fitdata = self._datafilespec(data, "fitdata")
        cmd = " ".join(filter(None, ("fit", ranges, expr, spec, "via", via)))
        return self(cmd, fitdata=fitdata)

    def source(self, script):
        """Issue a `load' command, piping the given script as input."""
        if not script.endswith("\n"):
            script += "\n"
        return self("load {{script}}", script=script)

class PlotData(object):
    """Wrapper for a data item in a Gnuplot `plot' or `splot' command."""
    __slots__ = ("data", "options", "mode")

    def __init__(self, data, options=None, mode=None):
        """Initialize a PlotData object.

        Arguments:
        data    - The data to be sent to Gnuplot.
        options - Datafile modifiers and plot options for the command line (a
                  string, such as "using 2:1 with linespoints").
        mode    - One of "pipe" or "file". If "file", a temporary file will be
                  used to pass the data to Gnuplot. This can be useful if you
                  want to send `binary matrix' data, which doesn't work with
                  named pipes. By default ("pipe"), a named pipe is used.
        """
        self.data = data
        self.options = options
        if mode is None:
            mode = "pipe"
        if mode not in ("pipe", "file"):
            raise ValueError('PlotData mode must be either "pipe" or "file"')
        self.mode = mode

    def __repr__(self):
        data_str = " source=" + type(self.data).__name__
        options_str = " options=" + repr(self.options) if self.options else ""
        mode_str = " mode=file" if self.mode == "file" else " mode=pipe"
        return "<PlotData{0}{1}{2}>".format(data_str, options_str, mode_str)

class _OutboundNamedPipe(threading.Thread):
    # Asynchronous manager for named pipe for sending data.
    # Once constructed, takes responsibility for cleanup after data is sent.
    def __init__(self, data, dir=None):
        self.data = data
        self.debug = False
        if dir:
            self.dir = dir
            self.made_dir = False
        else:
            self.dir = tempfile.mkdtemp()
            self.made_dir = True
        self.path = tempfile.mktemp(prefix="fifo.", dir=self.dir)
        super(_OutboundNamedPipe, self).__init__(name=self.path)
        # Make the named pipe synchronously, so that it's guaranteed to be
        # ready for immediate use by the reader.
        os.mkfifo(self.path)
        self.start()

    def cleanup(self):
        # Cleanup is done in run() to avoid race conditions.
        pass

    def run(self):
        try:
            with open(self.path, "wb") as pipe:
                pipe.write(self.data)
            if self.debug:
                msg = "<<wrote {0} bytes to pipe {1}>>".format(len(self.data),
                                                               self.path)
                print >>sys.stderr, msg
            if self.debug >= 2:
                dump = subprocess.Popen(shlex.split("od -A x -t x2"),
                                        stdin=subprocess.PIPE,
                                        stdout=sys.stderr,
                                        stderr=sys.stderr)
                dump.communicate(input=self.data)
        finally:
            os.unlink(self.path)
            if self.made_dir:
                os.rmdir(self.dir)

class _OutboundTempFile(object):
    # Temporary file with same interface as _OutboundNamedPipe.
    def __init__(self, data, dir=None):
        self.data = data
        self.debug = False
        fd, self.path = tempfile.mkstemp(prefix="file.", dir=dir)
        os.write(fd, self.data)
        os.close(fd)
        if self.debug:
            msg = "<<wrote {0} bytes to tempfile {1}>>".format(len(self.data),
                                                               self.path)
            print >>sys.stderr, msg
        if self.debug >= 2:
            dump = subprocess.Popen(shlex.split("od -A x -t x2"),
                                    stdin=subprocess.PIPE,
                                    stdout=sys.stderr,
                                    stderr=sys.stderr)
            dump.communicate(input=self.data)

    def cleanup(self):
        if self.path:
            os.unlink(self.path)
            self.path = None

def closeall():
    """Close all currently open RawGnuplot instances."""
    global _allplots
    for ref in _allplots:
        plot = ref()
        if plot:
            plot.close()


text:
int test_allocator_region_insert_test(void) {
    struct allocator_map map;
    struct allocator_region a, b, c;

    printf("simple insertion\n");
    allocator_map_init(&map);
    a.address = 1;
    a.size = 4;
    a.flags = 0;
    allocator_region_insert(&map, &a);
    assert(map.regions);
    assert(map.regions->address == 1);
    assert(map.regions->size == 4);

    printf("append\n");
    allocator_map_init(&map);
    a.address = 1;
    a.size = 4;
    a.flags = 0;
    b.address = 6;
    b.size = 4;
    b.flags = 0;
    allocator_region_insert(&map, &a);
    allocator_region_insert(&map, &b);
    assert(map.regions->address == 1);
    assert(map.regions->size == 4);
    assert(map.regions->next);
    assert(map.regions->next->address == 6);
    assert(map.regions->next->size == 4);

    printf("lhs\n");
    allocator_map_init(&map);
    a.address = 6;
    a.size = 4;
    a.flags = 0;
    b.address = 1;
    b.size = 4;
    b.flags = 0;
    allocator_region_insert(&map, &a);
    allocator_region_insert(&map, &b);
    assert(map.regions);
    assert(map.regions->address == 1);
    assert(map.regions->size == 4);
    assert(map.regions->next);
    assert(map.regions->next->address == 6);
    assert(map.regions->next->size == 4);

    printf("rhs\n");
    allocator_map_init(&map);
    a.address = 1;
    a.size = 4;
    a.flags = 0;
    b.address = 10;
    b.size = 4;
    b.flags = 0;
    c.address = 6;
    c.size = 3;
    c.flags = 0;
    allocator_region_insert(&map, &a);
    allocator_region_insert(&map, &b);
    allocator_region_insert(&map, &c);
    assert(map.regions);
    assert(map.regions->address == 1);
    assert(map.regions->size == 4);
    assert(map.regions->next);
    assert(map.regions->next->address == 6);
    assert(map.regions->next->size == 3);
    assert(map.regions->next->next);
    assert(map.regions->next->next->address == 10);
    assert(map.regions->next->next->size == 4);

    return 0;

}


text:
module ArcherSysOS
require 'drb/drb'

URI="druby://localhost:8787"

class Logger

    # Make dRuby send Logger instances as dRuby references,
    # not copies.
    include DRb::DRbUndumped

    def initialize(n, fname)
        @name = n
        @filename = fname
    end

    def log(message)
        File.open(@filename, "a") do |f|
            f.puts("#{Time.now}: #{@name}: #{message}")
        end
    end

end

# We have a central object for creating and retrieving loggers.
# This retains a local reference to all loggers created.  This
# is so an existing logger can be looked up by name, but also
# to prevent loggers from being garbage collected.  A dRuby
# reference to an object is not sufficient to prevent it being
# garbage collected!
class LoggerFactory

    def initialize(bdir)
        @basedir = bdir
        @loggers = {}
    end

    def get_logger(name)
        if !@loggers.has_key? name
            # make the filename safe, then declare it to be so
            fname = name.gsub(/[.\/\\:]/, "_").untaint
            @loggers[name] = Logger.new(name, @basedir + "/" + fname)
        end
        return @loggers[name]
    end

end

FRONT_OBJECT=LoggerFactory.new("/tmp/dlog")

$SAFE = 1   # disable eval() and friends

DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join
end


text:
package io.cloudslang.score.api;

import org.apache.commons.lang.builder.HashCodeBuilder;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * Date: 8/1/11
 *
 */
public class ExecutionPlan implements Serializable {
    private static final long serialVersionUID = -7685110912034208064L;

    protected String flowUuid;

    protected Long beginStep;

    private String executionPlanUuid;

    protected String name;
    //the name of the flow language this execution plan  represents, such as afl
    protected String language;

    private String workerGroup;

    public ExecutionPlan() {
        this.executionPlanUuid= UUID.randomUUID().toString();
    }

    protected Map<Long, ExecutionStep> steps = new HashMap<Long, ExecutionStep>();

    //Holds the list of it's direct subflows UUIDs
    protected Set<String> subflowsUUIDs = new HashSet<>();

    protected Set<String> sysAccPaths = new HashSet<>();

    public Set<String> getSubflowsUUIDs() {
        return subflowsUUIDs;
    }

    public void setSubflowsUUIDs(Set<String> subflowsUUIDs) {
        this.subflowsUUIDs = subflowsUUIDs;
    }

    public Set<String> getSysAccPaths() {
        return sysAccPaths;
    }

    public void setSysAccPaths(Set<String> sysAccPaths) {
        this.sysAccPaths = sysAccPaths;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getFlowUuid() {
        return flowUuid;
    }

    public ExecutionPlan setFlowUuid(String flowUuid) {
        this.flowUuid = flowUuid;
        return this;
    }

    public String getExecutionPlanUuid() {
        return executionPlanUuid;
    }

    public Long getBeginStep() {
        return beginStep;
    }

    public ExecutionPlan setBeginStep(Long beginStep) {
        this.beginStep = beginStep;
        return this;
    }

    public Map<Long, ExecutionStep> getSteps() {
        return steps;
    }

    public ExecutionStep getStep(Long stepId) {
        return steps.get(stepId);
    }

    public ExecutionPlan addStep(ExecutionStep step) {
        this.steps.put(step.getExecStepId(), step);
        return this;
    }

    public ExecutionPlan addSteps(List<ExecutionStep> steps) {
        for (ExecutionStep curStep : steps) {
            this.steps.put(curStep.getExecStepId(), curStep);
        }
        return this;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWorkerGroup() {
        return workerGroup;
    }

    public void setWorkerGroup(String workerGroup) {
        this.workerGroup = workerGroup;
    }

    @Override
    public String toString() {
        return "ExecutionPlan: \n" +
                "FlowUuid= '" + flowUuid + '\'' +
                "\n BeginStep= " + beginStep +
                "\n Name= '" + name + '\'' +
                "\n Worker Group= '" + workerGroup + '\'' +
                "\n Steps: \n" + printSteps();
    }

    private String printSteps() {
        StringBuilder strBld = new StringBuilder();
        for (Map.Entry entry : steps.entrySet()) {
            strBld.append("\t" + entry.getKey() + " -> " + entry.getValue().toString() + "\n");
            strBld.append("______________________________________________________________________________________________________________________________________________________________________________________________\n");
        }
        return strBld.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ExecutionPlan)) {
            return false;
        }

        ExecutionPlan other = (ExecutionPlan) o;
        return other.getExecutionPlanUuid().equals(this.getExecutionPlanUuid());
     }

    @Override
    public int hashCode() {
        HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();

        hashCodeBuilder.append(this.getFlowUuid());
        hashCodeBuilder.append(this.getBeginStep());
        hashCodeBuilder.append(this.getName());
        hashCodeBuilder.append(this.getLanguage());
        hashCodeBuilder.append(this.getSubflowsUUIDs());
        hashCodeBuilder.append(this.getSysAccPaths());
        hashCodeBuilder.append(this.getSteps());
        hashCodeBuilder.append(this.getWorkerGroup());

        return new HashCodeBuilder().toHashCode();
    }
}


text:
var SiteAjax = (function($,w){
  'use strict';
  var ajaxer = {page: null, title: null, href: null};

  function checkForProperties(obj, props) {
    if (obj == null || typeof obj == "undefined") return false;
    if (typeof props == "string") return (obj.hasOwnProperty(props) || checkForProperties(Object.getPrototypeOf(obj), props));
    else if (!Array.isArray(props)) throw "Illegal Argument Error: props parameter is not valid, must be a string or an Array of strings.";
    for (var i in props) {
      if (!checkForProperties(obj, props[i]) && !checkForProperties(Object.getPrototypeOf(obj), props[i])) return false;
    }
    return true;
  }

  function displayLoader() {
    var loaderICON = "http://i.imgur.com/6ZwRMCn.gif";
    $("body").append(`

`);
  }

  function hideLoader() {
    $("#loader").remove();
  }

  function loadComplete() {
    hideLoader();
    w.history.replaceState({page: ajaxer.page}, ajaxer.title, ajaxer.href);
    document.title=ajaxer.title;
    initAjax();
  }

  function loadPage(a) { // a should be an html "a" element
    if (!checkForProperties(a, ["href","textContent"])) throw "Invalid Parameter: a is not a valid object.";

    displayLoader();

    ajaxer = {page: "forum", title: a.textContent, href: a.href};

    $("#page-body").load(a.href + " #page-body > div", loadComplete); // Actual load operation
  }

  function clickHandler() {
    if (typeof w.history == "undefined" || typeof w.history.replaceState == "undefined") return true; // AJAX loading not supported fully. Just reload the page instead.

    loadPage(this); // jshint ignore:line
    return false; // Cancel normal navigation.
  }

  function initAjax(){
    if ($("#chatbox_top").length > 0) { // Reinitiate chatbox if found.
      $("#chatbox_top").html(`<iframe src="/chatbox/index.forum?page=front&" id="frame_chatbox" scrolling="no" width="100%" height="100%" marginwidth="0" marginheight="0" frameborder="0"></iframe>`);
    }

    $("a").each(function(i,e) {
      if (e.host=="pmd-roleplay.forumotion.org" && /https?:\/\/pmd-roleplay\.forumotion\.org\/[ft].+/.test(e.href)) {

        $(e).unbind("click.pmdAjax").bind("click.pmdAjax", clickHandler);
      }
    });
  }

  function init() {
    initAjax();
  }

  return {init: init};
})(jQuery, window);
SiteAjax.init();


text:
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// clang-format off

#ifndef ROCKETCOREDECORATORTILEDIMAGEINSTANCER_H
#define ROCKETCOREDECORATORTILEDIMAGEINSTANCER_H

#include "DecoratorTiledInstancer.h"

namespace Rocket {
namespace Core {

/**
        @author Peter Curry
 */

class DecoratorTiledImageInstancer : public DecoratorTiledInstancer {
public:
  DecoratorTiledImageInstancer(Context* _context);
  virtual ~DecoratorTiledImageInstancer();

  /// Instances an image decorator.
  virtual Decorator* InstanceDecorator(
      const String& name, const PropertyDictionary& properties) override;
  /// Releases the given decorator.
  virtual void ReleaseDecorator(Decorator* decorator) override;

  /// Releases the instancer.
  virtual void Release() override;
};
}  // namespace Core
}  // namespace Rocket

#endif


text:
class ChallengeTextView < BaseView
  stylesheet :call

  attr_accessor :words

  def render
    @title = subview(UILabel, :challenge_text_title)
    @words = subview(UILabel, :challenge_text_words)
  end
end


text:
<?php

namespace Google\Cloud\Samples\Bookshelf\DataModel;

use PDO;

/**
 * Class CloudSql implements the DataModelInterface with a mysql database.
 *
 */
class CloudSql implements DataModelInterface
{
    private $dsn;
    private $user;
    private $password;

    /**
     * Creates the SQL books table if it doesn't already exist.
     */
    public function __construct($dsn, $user, $password)
    {
        $this->dsn = $dsn;
        $this->user = $user;
        $this->password = $password;

        $columns = array(
            'id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ',
            'title VARCHAR(255)',
            'author VARCHAR(255)',
            'publishedDate DATE',
            'imageUrl VARCHAR(255)',
            'description VARCHAR(255)',
            'createdBy VARCHAR(255)',
            'createdById VARCHAR(255)',
        );

        $this->columnNames = array_map(function ($columnDefinition) {
            return explode(' ', $columnDefinition)[0];
        }, $columns);
        $columnText = implode(', ', $columns);
        $pdo = $this->newConnection();
        $pdo->query("CREATE TABLE IF NOT EXISTS books ($columnText)");
    }

    /**
     * Creates a new PDO instance and sets error mode to exception.
     *
     * @return PDO
     */
    private function newConnection()
    {
        $pdo = new PDO($this->dsn, $this->user, $this->password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return $pdo;
    }

    /**
     * Throws an exception if $book contains an invalid key.
     *
     * @param $book array
     *
     * @throws \Exception
     */
    private function verifyBook($book)
    {
        if ($invalid = array_diff_key($book, array_flip($this->columnNames))) {
            throw new \Exception(sprintf(
                'unsupported book properties: "%s"',
                implode(', ', $invalid)
            ));
        }
    }

    public function listBooks($limit = 10, $cursor = null)
    {
        $pdo = $this->newConnection();
        if ($cursor) {
            $query = 'SELECT * FROM books WHERE id > :cursor ORDER BY id' .
                ' LIMIT :limit';
            $statement = $pdo->prepare($query);
            $statement->bindValue(':cursor', $cursor, PDO::PARAM_INT);
        } else {
            $query = 'SELECT * FROM books ORDER BY id LIMIT :limit';
            $statement = $pdo->prepare($query);
        }
        $statement->bindValue(':limit', $limit + 1, PDO::PARAM_INT);
        $statement->execute();
        $rows = array();
        $last_row = null;
        $new_cursor = null;
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
            if (count($rows) == $limit) {
                $new_cursor = $last_row['id'];
                break;
            }
            array_push($rows, $row);
            $last_row = $row;
        }

        return array(
            'books' => $rows,
            'cursor' => $new_cursor,
        );
    }

    public function create($book, $id = null)
    {
        $this->verifyBook($book);
        if ($id) {
            $book['id'] = $id;
        }
        $pdo = $this->newConnection();
        $names = array_keys($book);
        $placeHolders = array_map(function ($key) {
            return ":$key";
        }, $names);
        $sql = sprintf(
            'INSERT INTO books (%s) VALUES (%s)',
            implode(', ', $names),
            implode(', ', $placeHolders)
        );
        $statement = $pdo->prepare($sql);
        $statement->execute($book);

        return $pdo->lastInsertId();
    }

    public function read($id)
    {
        $pdo = $this->newConnection();
        $statement = $pdo->prepare('SELECT * FROM books WHERE id = :id');
        $statement->bindValue('id', $id, PDO::PARAM_INT);
        $statement->execute();

        return $statement->fetch(PDO::FETCH_ASSOC);
    }

    public function update($book)
    {
        $this->verifyBook($book);
        $pdo = $this->newConnection();
        $assignments = array_map(
            function ($column) {
                return "$column=:$column";
            },
            $this->columnNames
        );
        $assignmentString = implode(',', $assignments);
        $sql = "UPDATE books SET $assignmentString WHERE id = :id";
        $statement = $pdo->prepare($sql);
        $values = array_merge(
            array_fill_keys($this->columnNames, null),
            $book
        );
        $statement->execute($values);

        return $statement->rowCount();
    }

    public function delete($id)
    {
        $pdo = $this->newConnection();
        $statement = $pdo->prepare('DELETE FROM books WHERE id = :id');
        $statement->bindValue('id', $id, PDO::PARAM_INT);
        $statement->execute();

        return $statement->rowCount();
    }
}