text:
using DasMulli.Win32.ServiceUtils;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using TWCore.Settings;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable UnusedMember.Global

namespace TWCore.Services
{
    /// <inheritdoc />
    /// <summary>
    /// Windows Service container
    /// </summary>
    internal class WindowsServiceContainer : ServiceContainer
    {
        private WindowsServiceSettings _settings;

        #region .ctor
        public WindowsServiceContainer(IService service, Action initAction) :
            base(service, initAction) => Init();
        public WindowsServiceContainer(IService service) :
            base(service) => Init();
        public WindowsServiceContainer(string serviceName, IService service) :
            base(serviceName, service) => Init();
        public WindowsServiceContainer(string serviceName, IService service, Action initAction) :
            base(serviceName, service, initAction) => Init();
        #endregion

        #region Override Methods

        protected override void ShowHelp()
        {
            ShowHeader();
            Console.WriteLine("Parameters:");
            Console.WriteLine("  {0,-30}  : {1}", "/help | /?", "This Help.");
            if (Service != null)
            {
                Console.WriteLine("  {0,-30}  : {1}", "/service-install", "Install Windows Service.");
                Console.WriteLine("  {0,-30}  : {1}", "/service-uninstall", "Uninstall Windows Service.");
                Console.WriteLine("  {0,-30}  : {1}", "/service-run", "Run as a Windows Service.");
            }
            Console.WriteLine("  {0,-30}  : {1}", "/showsettings | /w", "Show all loaded settings from app.config and settings.xml file.");
            Console.WriteLine("  {0,-30}  : {1}", "/version", "Show all loaded assemblies version.");
            if (ParametersHandlers?.Any() == true)
            {
                foreach (var par in ParametersHandlers.OrderBy(p => p.Key))
                {
                    switch (par.Key)
                    {
                        case "service-install":
                            continue;
                        case "service-uninstall":
                            continue;
                        default:
                            Console.WriteLine("  {0,-30}  : {1}", "/" + par.Key, par.Value.Description);
                            break;
                    }
                }
            }
            Console.WriteLine();
        }

        public override void Run(string[] args)
        {
            if (args.Length > 0)
            {
                switch (args[0])
                {
                    case "/service-install":
                        InstallService(null);
                        Core.Dispose();
                        return;
                    case "/service-uninstall":
                        UninstallService(null);
                        Core.Dispose();
                        return;
                }
            }
            if (args.Contains("/service-run", StringComparer.OrdinalIgnoreCase) && Service is null)
            {
                Core.Log.Error("THERE IS NO SERVICE TO START.");
                return;
            }
            base.Run(args);
        }

        protected override void InternalRun(string[] args)
        {
            if (args.Contains("/service-run", StringComparer.OrdinalIgnoreCase))
            {
                Directory.SetCurrentDirectory(AppContext.BaseDirectory);
                Core.Log.LibDebug("Starting...");
                Core.Log.InfoBasic("Current Directory: {0}", Directory.GetCurrentDirectory());
                InitAction?.Invoke();
                if (!string.IsNullOrWhiteSpace(BannerText))
                {
                    var bannerText = BannerText.Split("\r\n");
                    foreach (var line in bannerText)
                        Core.Log.InfoBasic(line);
                }
                Core.Log.InfoBasic("*** RUNNING AS WINDOWS SERVICE ***");
                ShowFullHeader();
                try
                {
                    var win32Service = new Win32Service(ServiceName, Service);
                    var serviceHost = new Win32ServiceHost(win32Service);
                    serviceHost.Run();
                }
                catch (Exception ex)
                {
                    Core.Log.Write(ex);
                }
            }
            else
                base.InternalRun(args);
        }

        #endregion

        #region Install/Uninstall Service
        private void Init()
        {
            if (Service is null) return;
            _settings = Core.GetSettings<WindowsServiceSettings>();
            RegisterParametersHandler("service-install", "Install Windows Service", InstallService);
            RegisterParametersHandler("service-uninstall", "Uninstall Windows Service", UninstallService);
        }
        private void InstallService(ParameterHandlerInfo parameterHandlerInfo)
        {
            try
            {
                // Environment.GetCommandLineArgs() includes the current DLL from a "dotnet my.dll --register-service" call, which is not passed to Main()
                var remainingArgs = Environment.GetCommandLineArgs()
                    .Where(arg => arg != "/service-install")
                    .Select(EscapeCommandLineArgument)
                    .Append("/service-run");

                var host = Process.GetCurrentProcess().MainModule.FileName;
                if (!host.EndsWith("dotnet.exe", StringComparison.OrdinalIgnoreCase))
                {
                    // For self-contained apps, skip the dll path
                    remainingArgs = remainingArgs.Skip(1);
                }
                var fullServiceCommand = host + " " + string.Join(" ", remainingArgs);

                _settings.DisplayName = _settings.DisplayName ?? Core.ApplicationDisplayName;
                _settings.Description = _settings.Description ?? Core.ApplicationDisplayName;

                Win32ServiceCredentials credentials;
                switch (_settings.Credentials)
                {
                    case ServiceCredentials.LocalSystem:
                        credentials = Win32ServiceCredentials.LocalSystem;
                        break;
                    case ServiceCredentials.LocalService:
                        credentials = Win32ServiceCredentials.LocalService;
                        break;
                    case ServiceCredentials.NetworkService:
                        credentials = Win32ServiceCredentials.NetworkService;
                        break;
                    case ServiceCredentials.Custom:
                        credentials = new Win32ServiceCredentials(_settings.Username, _settings.Password);
                        break;
                    default:
                        throw new ArgumentException("The Credentials enum has a wrong value.");
                }

                var serviceManager = new Win32ServiceManager();
                serviceManager.CreateOrUpdateService(
                    ServiceName,
                    _settings.DisplayName,
                    _settings.Description,
                    fullServiceCommand,
                    credentials,
                    _settings.AutoStart
                );

                Core.Log.Warning($"The Service \"{ServiceName}\" was installed successfully.");
            }
            catch (Exception ex)
            {
                Core.Log.Error(ex.Message);
            }
        }
        private void UninstallService(ParameterHandlerInfo parameterHandlerInfo)
        {
            try
            {
                var serviceManager = new Win32ServiceManager();
                serviceManager.DeleteService(ServiceName);
                Core.Log.Warning($"The Service \"{ServiceName}\" was uninstalled successfully.");
            }
            catch (Exception ex)
            {
                Core.Log.Error(ex.Message);
            }
        }
        private static string EscapeCommandLineArgument(string arg)
        {
            // http://stackoverflow.com/a/6040946/784387
            arg = Regex.Replace(arg, @"(\\*)" + "\"", @"$1$1\" + "\"");
            arg = "\"" + Regex.Replace(arg, @"(\\+)$", @"$1$1") + "\"";
            return arg;
        }
        #endregion

        #region Nested Types
        [SettingsContainer("Core.Services.Windows")]
        private class WindowsServiceSettings : SettingsBase
        {
            public string DisplayName { get; set; }
            public string Description { get; set; }
            public ServiceCredentials Credentials { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
            public bool AutoStart { get; set; }
        }
        public enum ServiceCredentials
        {
            LocalSystem,
            LocalService,
            NetworkService,
            Custom
        }
        #endregion
    }
}


text:
package org.epnoi.learner.relations.patterns.syntactic;

public interface SyntacticPatternGraphElement {

}

redpajama_set_name: RedPajamaGithub


text:
package com.spring.example.metrics;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlets.MetricsServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class BootApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class,args);
    }

    @Bean
    public MetricRegistry metricRegistry() {
        return new MetricRegistry();
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean(MetricRegistry metricRegistry){
        return new ServletRegistrationBean(new MetricsServlet(metricRegistry),"/metric");
    }

}


text:
layout: post
title: "Things we like: Upstart"
excerpt: I once worked in an organization whose CEO repeated in 90% of meetings he attended, "People don't want auto loans; they want cars." He also loved making exceptions at the front-line, lending on character over credit score alone.
legacy: false
draft: false
author:
  name: Trey Reeme
  twitter: creeme
  bio: Cofounder and COO of Trabian
  image: authors/trey.png
---

I once worked in an organization whose CEO repeated in 90% of meetings he attended, "People don't want auto loans; they want cars." He also loved making exceptions at the front-line, lending on character over credit score alone.

[Upstart](https://www.upstart.com/) reminds me of that CEO and his mantra in two ways. First, Upstart focuses on what a borrower wants to do with the funds before focusing on the loan itself. Second, Upstart focuses on a borrower's potential in addition to past.

If you remember from the first day of lending school, *Character* is first among the "Four C's of Credit".

Sadly, consumers have come to believe banks and credit unions only measure said character with a silly three digit number ranging somewhere between 300 and 850.

Kudos to Upstart for taking an approach that acknowledges consumers deserve more than the standard model and relies on data to incorporate potential into the credit decision. Its message stands out distinctly when lined up next to its competitors (psssst... that's you).


text:
from __future__ import absolute_import, unicode_literals
from ....unittest import TestCase

import json
import mock
from oauthlib.common import Request
from oauthlib.oauth2.rfc6749.grant_types import RefreshTokenGrant
from oauthlib.oauth2.rfc6749.tokens import BearerToken
from oauthlib.oauth2.rfc6749 import errors

class RefreshTokenGrantTest(TestCase):

    def setUp(self):
        mock_client = mock.MagicMock()
        mock_client.user.return_value = 'mocked user'
        self.request = Request('http://a.b/path')
        self.request.grant_type = 'refresh_token'
        self.request.refresh_token = 'lsdkfhj230'
        self.request.client = mock_client
        self.request.scope = 'foo'
        self.mock_validator = mock.MagicMock()
        self.auth = RefreshTokenGrant(
                request_validator=self.mock_validator)

    def test_create_token_response(self):
        self.mock_validator.get_original_scopes.return_value = ['foo', 'bar']
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 1)
        self.assertIn('access_token', token)
        self.assertIn('token_type', token)
        self.assertIn('expires_in', token)
        self.assertEqual(token['scope'], 'foo')

    def test_create_token_inherit_scope(self):
        self.request.scope = None
        self.mock_validator.get_original_scopes.return_value = ['foo', 'bar']
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 1)
        self.assertIn('access_token', token)
        self.assertIn('token_type', token)
        self.assertIn('expires_in', token)
        self.assertEqual(token['scope'], 'foo bar')

    def test_create_token_within_original_scope(self):
        self.mock_validator.get_original_scopes.return_value = ['baz']
        self.mock_validator.is_within_original_scope.return_value = True
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 1)
        self.assertIn('access_token', token)
        self.assertIn('token_type', token)
        self.assertIn('expires_in', token)
        self.assertEqual(token['scope'], 'foo')

    def test_invalid_scope(self):
        self.mock_validator.get_original_scopes.return_value = ['baz']
        self.mock_validator.is_within_original_scope.return_value = False
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 0)
        self.assertEqual(token['error'], 'invalid_scope')
        self.assertEqual(status_code, 401)

    def test_invalid_token(self):
        self.mock_validator.validate_refresh_token.return_value = False
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 0)
        self.assertEqual(token['error'], 'invalid_grant')
        self.assertEqual(status_code, 401)

    def test_invalid_client(self):
        self.mock_validator.authenticate_client.return_value = False
        bearer = BearerToken(self.mock_validator)
        headers, body, status_code = self.auth.create_token_response(
                self.request, bearer)
        token = json.loads(body)
        self.assertEqual(self.mock_validator.save_token.call_count, 0)
        self.assertEqual(token['error'], 'invalid_client')
        self.assertEqual(status_code, 401)

    def test_authentication_required(self):
        """
        ensure client_authentication_required() is properly called
        """
        self.mock_validator.authenticate_client.return_value = False
        self.mock_validator.authenticate_client_id.return_value = False
        self.request.code = 'waffles'
        self.assertRaises(errors.InvalidClientError, self.auth.validate_token_request,
                          self.request)
        self.mock_validator.client_authentication_required.assert_called_once_with(self.request)

    def test_invalid_grant_type(self):
        self.request.grant_type = 'wrong_type'
        self.assertRaises(errors.UnsupportedGrantTypeError,
                          self.auth.validate_token_request, self.request)

    def test_authenticate_client_id(self):
        self.mock_validator.client_authentication_required.return_value = False
        self.request.refresh_token = mock.MagicMock()
        self.mock_validator.authenticate_client_id.return_value = False
        self.assertRaises(errors.InvalidClientError,
                          self.auth.validate_token_request, self.request)

    def test_invalid_refresh_token(self):
        # invalid refresh token
        self.mock_validator.authenticate_client_id.return_value = True
        self.mock_validator.validate_refresh_token.return_value = False
        self.assertRaises(errors.InvalidGrantError,
                          self.auth.validate_token_request, self.request)
        # no token provided
        del self.request.refresh_token
        self.assertRaises(errors.InvalidRequestError,
                          self.auth.validate_token_request, self.request)

    def test_invalid_scope_original_scopes_empty(self):
        self.mock_validator.validate_refresh_token.return_value = True
        self.mock_validator.is_within_original_scope.return_value = False
        self.assertRaises(errors.InvalidScopeError,
                          self.auth.validate_token_request, self.request)

    def test_valid_token_request(self):
        self.request.scope = 'foo bar'
        self.mock_validator.get_original_scopes = mock.Mock()
        self.mock_validator.get_original_scopes.return_value = 'foo bar baz'
        self.auth.validate_token_request(self.request)
        self.assertEqual(self.request.scopes, self.request.scope.split())
        # all ok but without request.scope
        del self.request.scope
        self.auth.validate_token_request(self.request)
        self.assertEqual(self.request.scopes, 'foo bar baz'.split())


text:
Change Log
==========
## Version 0.1.2
_2017-08-29_
 * fix issue #61 android O compatible type_application_overlay

## Version 0.1.1
_2017-02-12_
 * Remove permission "SYSTEM_ALERT_WINDOW" for no-op release [Issue #50] (https://github.com/brianPlummer/TinyDancer/issues/50)
 * TinyDancerBuilder now only honors gravity flag if X or Y starting position is not set. [Issue #48] (https://github.com/brianPlummer/TinyDancer/issues/58)
 * Minor pretty enhancement to example

## Version 0.1.0
_2016-10-30_
* introducing a no-op aar option

## Version 0.0.9
_2015-12-16_
*  fix TinyDancer.hide() to take Context [Issue #26] (https://github.com/brianPlummer/TinyDancer/issues/26)

## Version 0.0.8

_2015-12-14_

 *  added CHANGELOG to keep Artem :-)

## Version 0.0.7

_2015-12-14_

*  Double tap to hide.  Removal of testing archives from artifact.

## Version 0.0.4

_2015-12-14_
* Added callback
* Cleaned up readme
* Minor code tweaks


text:
package cbgt

import (
	"encoding/json"
	"fmt"
	"hash"
	"hash/crc32"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	log "github.com/couchbase/clog"
)

const FILES_FEED_SLEEP_START_MS = 5000
const FILES_FEED_BACKOFF_FACTOR = 1.5
const FILES_FEED_MAX_SLEEP_MS = 1000 * 60 * 5 // 5 minutes.

func init() {
	RegisterFeedType("files", &FeedType{
		Start:      StartFilesFeed,
		Partitions: FilesFeedPartitions,
		Public:     true,
		Description: "general/files" +
			" - files under a dataDir subdirectory tree will be the data source",
		StartSample: &FilesFeedParams{
			RegExps:       []string{".txt$", ".md$"},
			SleepStartMS:  FILES_FEED_SLEEP_START_MS,
			BackoffFactor: FILES_FEED_BACKOFF_FACTOR,
			MaxSleepMS:    FILES_FEED_MAX_SLEEP_MS,
		},
	})
}

// FilesFeed is a Feed interface implementation that that emits file
// contents from a local subdirectory tree.
//
// The subdirectory tree lives under the dataDir...
//
//    <dataDir>/<sourceName/**
//
// FilesFeed supports optional regexp patterns to allow you to filter
// for only the file paths that you want.
//
// Limitations:
//
// - Only a small number of files will work well (hundreds to low
// thousands, not millions).
//
// - FilesFeed polls for file modification timestamp changes as a
// poor-man's approach instead of properly tracking sequence numbers.
// That has implications such as whenever a FilesFeed (re-)starts
// (e.g., the process restarts), the FilesFeed will re-emits all files
// and then track the max modification timestamp going forwards as it
// regularly polls for file changes.
type FilesFeed struct {
	mgr        *Manager
	name       string
	indexName  string
	sourceName string
	params     *FilesFeedParams
	dests      map[string]Dest
	disable    bool

	m       sync.Mutex
	closeCh chan struct{}
}

// FilesFeedParams represents the JSON expected as the sourceParams
// for a FilesFeed.
type FilesFeedParams struct {
	RegExps       []string `json:"regExps"`
	MaxFileSize   int64    `json:"maxFileSize"`
	NumPartitions int      `json:"numPartitions"`
	SleepStartMS  int      `json:"sleepStartMS"`
	BackoffFactor float32  `json:"backoffFactor"`
	MaxSleepMS    int      `json:"maxSleepMS"`
}

// FileDoc represents the JSON for each file/document that will be
// emitted by a FilesFeed as a data source.
type FileDoc struct {
	Name     string `json:"name"`
	Path     string `json:"path"` // Path relative to the source name.
	Contents string `json:"contents"`
}

// StartFilesFeed starts a FilesFeed and is the the callback function
// registered at init/startup time.
func StartFilesFeed(mgr *Manager, feedName, indexName, indexUUID,
	sourceType, sourceName, sourceUUID, params string,
	dests map[string]Dest) error {
	feed, err := NewFilesFeed(mgr, feedName, indexName, sourceName,
		params, dests, mgr.tagsMap != nil && !mgr.tagsMap["feed"])
	if err != nil {
		return fmt.Errorf("feed_files: NewFilesFeed,"+
			" feedName: %s, err: %v", feedName, err)
	}
	err = feed.Start()
	if err != nil {
		return fmt.Errorf("feed_files: could not start,"+
			" feedName: %s, err: %v", feedName, err)
	}
	err = mgr.registerFeed(feed)
	if err != nil {
		feed.Close()
		return err
	}
	return nil
}

// NewFilesFeed creates a ready-to-be-started FilesFeed.
func NewFilesFeed(mgr *Manager, name, indexName, sourceName,
	paramsStr string, dests map[string]Dest, disable bool) (
	*FilesFeed, error) {
	if sourceName == "" {
		return nil, fmt.Errorf("feed_files: missing source name")
	}

	if strings.Index(sourceName, "..") >= 0 {
		return nil, fmt.Errorf("feed_files: disallowed source name,"+
			" name: %s, sourceName: %q", name, sourceName)
	}

	params := &FilesFeedParams{}
	if paramsStr != "" {
		err := json.Unmarshal([]byte(paramsStr), params)
		if err != nil {
			return nil, err
		}
	}

	return &FilesFeed{
		mgr:        mgr,
		name:       name,
		indexName:  indexName,
		sourceName: sourceName,
		params:     params,
		dests:      dests,
		disable:    disable,
		closeCh:    make(chan struct{}),
	}, nil
}

func (t *FilesFeed) Name() string {
	return t.name
}

func (t *FilesFeed) IndexName() string {
	return t.indexName
}

func (t *FilesFeed) Start() error {
	if t.disable {
		log.Printf("feed_files: disable, name: %s", t.Name())
		return nil
	}

	startSleepMS := t.params.SleepStartMS
	if startSleepMS <= 0 {
		startSleepMS = FILES_FEED_SLEEP_START_MS
	}

	backoffFactor := t.params.BackoffFactor
	if backoffFactor <= 0 {
		backoffFactor = FILES_FEED_BACKOFF_FACTOR
	}

	maxSleepMS := t.params.MaxSleepMS
	if maxSleepMS <= 0 {
		maxSleepMS = FILES_FEED_MAX_SLEEP_MS
	}

	numPartitions := t.params.NumPartitions
	if numPartitions < 0 {
		numPartitions = 0
	}

	partitions := make([]string, numPartitions)
	for i := 0; i < len(partitions); i++ {
		partitions[i] = strconv.Itoa(i)
	}

	go func() {
		initTime := time.Now()
		initTimeMicroSecs := initTime.UnixNano() / int64(1000)

		// TODO: NOTE: We're assuming (lazily, incorrectly) that this
		// way of initializing a sequence number never goes downwards,
		// even during fast restarts or clock changes or node
		// rebalances/reassignments.
		seqs := map[string]uint64{}
		for partition, _ := range t.dests {
			seqs[partition] = uint64(initTimeMicroSecs)
		}

		var prevStartTime time.Time

		ExponentialBackoffLoop(t.Name(),
			func() int {
				t.m.Lock()
				closeCh := t.closeCh
				t.m.Unlock()

				select {
				case <-closeCh:
					return -1
				default:
				}

				h := crc32.NewIEEE()

				startTime := time.Now()

				progress := false

				paths, err := FilesFindMatches(t.mgr.DataDir(),
					t.sourceName, t.params.RegExps, prevStartTime,
					t.params.MaxFileSize)
				if err != nil {
					log.Printf("feed_files, FilesFindMatches, err: %v", err)
					return -1
				}

				seqDeltaMax := uint64(0)

				seqEnds := map[string]uint64{}

				for _, path := range paths {
					partition := FilesPathToPartition(h, partitions, path)

					if t.dests[partition] == nil {
						continue
					}

					seq := seqs[partition]

					seqEnd, exists := seqEnds[partition]
					if exists {
						seqEnd = seqEnd + 1
					} else {
						seqEnd = seq
					}
					seqEnds[partition] = seqEnd

					if seqDeltaMax < seqEnd-seq {
						seqDeltaMax = seqEnd - seq
					}
				}

				snapshotSent := map[string]bool{}

				for _, path := range paths {
					select {
					case <-closeCh:
						return -1
					default:
					}

					partition := FilesPathToPartition(h, partitions, path)

					dest := t.dests[partition]
					if dest == nil {
						continue
					}

					seqCur := seqs[partition]
					seqs[partition] = seqCur + 1

					buf, err := ioutil.ReadFile(path)
					if err != nil {
						log.Printf("feed_files: read file,"+
							" name: %s, path: %s, err: %v",
							t.Name(), path, err)
						continue
					}

					jbuf, err := json.Marshal(FileDoc{
						Name:     filepath.Base(path),
						Path:     path,
						Contents: string(buf),
					})
					if err != nil {
						log.Printf("feed_files: json marshal file,"+
							" name: %s, path: %s, err: %v",
							t.Name(), path, err)
						continue
					}

					if !snapshotSent[partition] {
						err = dest.SnapshotStart(partition, seqCur,
							seqEnds[partition])
						if err != nil {
							log.Printf("feed_files: SnapshotStart,"+
								" name: %s, partition: %s,"+
								" seqCur: %d, seqEnd: %d, err: %v",
								t.Name(), partition,
								seqCur, seqEnds[partition], err)
							return -1
						}

						snapshotSent[partition] = true
					}

					pathBuf := []byte(path)

					err = dest.DataUpdate(partition, pathBuf, seqCur,
						jbuf, 0, DEST_EXTRAS_TYPE_NIL, nil)
					if err != nil {
						log.Printf("feed_files: DataUpdate,"+
							" name: %s, path: %s, partition: %s,"+
							" seqCur: %d, err: %v",
							t.Name(), path, partition, seqCur, err)
						return -1
					}

					progress = true
				}

				prevStartTime = startTime

				// NOTE: We may need to sleep a certain amount in case
				// there were tons of file updates/mutations, and we
				// want to reduce the window of potentially repeating
				// sequence numbers.  The window still exists if we
				// crash and quickly restart during the sleep, where
				// the restarted process might have a
				// lower-than-wanted initTime.
				wantTime := initTime // Copy, because Add() mutates.
				wantTime.Add(time.Duration(int64(seqDeltaMax)))

				currTime := time.Now()
				if wantTime.After(currTime) {
					time.Sleep(wantTime.Sub(currTime))
				}

				if progress {
					return 1
				}
				return 0
			},
			startSleepMS,
			backoffFactor,
			maxSleepMS)
	}()

	return nil
}

func (t *FilesFeed) Close() error {
	t.m.Lock()
	if t.closeCh != nil {
		close(t.closeCh)
		t.closeCh = nil
	}
	t.m.Unlock()

	return nil
}

func (t *FilesFeed) Dests() map[string]Dest {
	return t.dests
}

func (t *FilesFeed) Stats(w io.Writer) error {
	_, err := w.Write([]byte("{}"))
	return err
}

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

// FilesFeedPartitions returns the partitions, controlled by
// FilesFeedParams.NumPartitions, for a FilesFeed instance.
func FilesFeedPartitions(sourceType, sourceName, sourceUUID, sourceParams,
	server string) ([]string, error) {
	ffp := &FilesFeedParams{}
	if sourceParams != "" {
		err := json.Unmarshal([]byte(sourceParams), ffp)
		if err != nil {
			return nil, fmt.Errorf("feed_files:"+
				" could not parse sourceParams: %s, err: %v",
				sourceParams, err)
		}
	}
	rv := make([]string, ffp.NumPartitions)
	for i := 0; i < ffp.NumPartitions; i++ {
		rv[i] = strconv.Itoa(i)
	}
	return rv, nil
}

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

// FilesFindMatches finds all leaf file paths in a subdirectory tree
// that match any in an optional array of regExps (regular expression
// strings).  If regExps is nil, though, then all leaf file paths are
// considered as a potential candidate match.  The regExps are with
// respect to a path from filepath.Walk().
//
// Additionally, a candidate file must have been modified since a
// modTimeGTE and (if maxSize is > 0) should have size that's <=
// maxSize.
func FilesFindMatches(dataDir, sourceName string,
	regExps []string, modTimeGTE time.Time, maxSize int64) (
	[]string, error) {
	walkPath, err := filepath.EvalSymlinks(dataDir +
		string(os.PathSeparator) + "files" +
		string(os.PathSeparator) + sourceName)
	if err != nil {
		return nil, err
	}

	pathsOk := []string(nil)

	err = filepath.Walk(walkPath,
		func(path string, fi os.FileInfo, err error) error {
			if err != nil ||
				fi.IsDir() ||
				fi.ModTime().Before(modTimeGTE) ||
				(maxSize > 0 && fi.Size() > maxSize) {
				return nil
			}

			if len(regExps) <= 0 {
				pathsOk = append(pathsOk, path)
				return nil
			}

			for _, reStr := range regExps {
				matched, err := regexp.MatchString(reStr, path)
				if err != nil {
					return fmt.Errorf("feed_files, MatchString,"+
						" reStr: %s, path: %s, err: %v",
						reStr, path, err)
				}
				if matched {
					pathsOk = append(pathsOk, path)
					return nil
				}
			}

			return nil
		})
	if err != nil {
		return nil, err
	}

	return pathsOk, nil
}

// FilesPathToPartition hashes a file path to a partition.
func FilesPathToPartition(h hash.Hash32,
	partitions []string, path string) string {
	if len(partitions) <= 0 {
		return ""
	}

	h.Reset()
	io.WriteString(h, path)
	i := h.Sum32() % uint32(len(partitions))
	return partitions[i]
}


text:
package imap

import (
	"errors"
	"fmt"
	"io"
	"net"
	"runtime/debug"
	"sort"
	"strings"
	"sync"
	"time"
)

// Timeout arguments for Client.recv.
const (
	block = time.Duration(-1) // Block until a complete response is received
	poll  = time.Duration(0)  // Check for buffered responses without blocking
)

// ErrTimeout is returned when an operation does not finish successfully in the
// allocated time.
var ErrTimeout = errors.New("imap: operation timeout")

// ErrExclusive is returned when an attempt is made to execute multiple commands
// in parallel, but one of the commands requires exclusive client access.
var ErrExclusive = errors.New("imap: exclusive client access violation")

// ErrNotAllowed is returned when a command cannot be issued in the current
// connection state. Client.CommandConfig[<name>].States determines valid states
// for each command.
var ErrNotAllowed = errors.New("imap: command not allowed in the current state")

// NotAvailableError is returned when the requested command, feature, or
// capability is not supported by the client and/or server. The error may be
// temporary. For example, servers should disable the LOGIN command by
// advertising LOGINDISABLED capability while the connection is unencrypted.
// Enabling encryption via STARTTLS should allow the use of LOGIN.
type NotAvailableError string

func (err NotAvailableError) Error() string {
	return "imap: not available (" + string(err) + ")"
}

// response transports the output of Client.next through the rch channel.
type response struct {
	rsp *Response
	err error
}

// Client manages a single connection to an IMAP server.
type Client struct {
	// FIFO queue for unilateral server data. The first response is the server
	// greeting. Subsequent responses are those that were rejected by all active
	// command filters. Commands documented as expecting "no specific responses"
	// (e.g. NOOP) use nil filters by default, which reject all responses.
	Data []*Response

	// Set of current server capabilities. It is updated automatically anytime
	// new capabilities are received, which could be in a data response or a
	// status response code.
	Caps map[string]bool

	// Status of the selected mailbox. It is set to nil unless the Client is in
	// the Selected state. The fields are updated automatically as the server
	// sends solicited and unsolicited status updates.
	Mailbox *MailboxStatus

	// Execution parameters of known commands. Client.Send will return an error
	// if an attempt is made to execute a command whose name does not appear in
	// this map. The server may not support all commands known to the client.
	CommandConfig map[string]*CommandConfig

	// Server host name for authentication and STARTTLS commands.
	host string

	// Current connection state. Initially set to unknown.
	state ConnState

	// Command tag generator.
	tag tagGen

	// FIFO queue of tags for the commands in progress (keys of cmds). Response
	// filtering is performed according to the command issue order to support
	// server-side ambiguity resolution, as described in RFC 3501 section 5.5.
	tags []string

	// Map of tags to Command objects. A command is "in progress" and may
	// receive responses as long as it has an entry in this map.
	cmds map[string]*Command

	// Control and response channels for the receiver goroutine. A new response
	// channel rch is created for each time-limited receive request, and is sent
	// via cch to the receiver. The receiver sends back the output of c.next via
	// rch. There can be at most one active receive request (rch != nil).
	cch chan<- chan<- *response
	rch <-chan *response

	// Low-level transport for sending commands and receiving responses.
	t *transport
	r *reader

	// Protection against multiple close calls.
	closer sync.Once

	// Debug message logging.
	*debugLog
}

// NewClient returns a new Client instance connected to an IMAP server via conn.
// The function waits for the server to send a greeting message, and then
// requests server capabilities if they weren't included in the greeting. An
// error is returned if either operation fails or does not complete before the
// timeout, which must be positive to have any effect. If an error is returned,
// it is the caller's responsibility to close the connection.
func NewClient(conn net.Conn, host string, timeout time.Duration) (c *Client, err error) {
	log := newDebugLog(DefaultLogger, DefaultLogMask)
	cch := make(chan chan<- *response, 1)

	c = &Client{
		Caps:          make(map[string]bool),
		CommandConfig: defaultCommands(),
		host:          host,
		state:         unknown,
		tag:           *newTagGen(0),
		cmds:          make(map[string]*Command),
		t:             newTransport(conn, log),
		debugLog:      log,
	}
	c.r = newReader(c.t, MemoryReader{}, string(c.tag.id))
	c.Logf(LogConn, "Connected to %v (Tag=%s)", conn.RemoteAddr(), c.tag.id)

	if err = c.greeting(timeout); err != nil {
		c.Logln(LogConn, "Greeting error:", err)
		return nil, err
	}
	c.cch = cch
	go c.receiver(cch)
	return
}

// State returns the current connection state (Login, Auth, Selected, Logout, or
// Closed). See RFC 3501 page 15 for a state diagram. The caller must continue
// receiving responses until this method returns Closed (same as c.Recv
// returning io.EOF). Failure to do so may result in memory leaks.
func (c *Client) State() ConnState {
	return c.state
}

// Send issues a new command, returning as soon as the last line is flushed from
// the send buffer. This may involve waiting for continuation requests if
// non-synchronizing literals (RFC 2088) are not supported by the server.
//
// This is the raw command interface that does not encode or perform any
// validation of the supplied fields. It should only be used for implementing
// new commands that do not change the connection state. For commands already
// supported by this package, use the provided wrapper methods instead.
func (c *Client) Send(name string, fields ...Field) (cmd *Command, err error) {
	if cmd = newCommand(c, name); cmd == nil {
		return nil, NotAvailableError(name)
	} else if cmd.config.States&c.state == 0 {
		return nil, ErrNotAllowed
	} else if len(c.tags) > 0 {
		other := c.cmds[c.tags[0]]
		if cmd.config.Exclusive || other.config.Exclusive {
			return nil, ErrExclusive
		}
	}

	// Build command
	raw, err := cmd.build(c.tag.Next(), fields)
	if err != nil {
		return nil, err
	}

	// Write first line and update command state
	c.Logln(LogCmd, ">>>", cmd)
	if err = c.t.WriteLine(raw.ReadLine()); err != nil {
		return nil, err
	}
	c.tags = append(c.tags, cmd.tag)
	c.cmds[cmd.tag] = cmd

	// Write remaining parts, flushing the transport buffer as needed
	var rsp *Response
	for i := 0; i < len(raw.literals) && err == nil; i++ {
		if rsp, err = c.checkContinue(cmd, !raw.nonsync); err == nil {
			if rsp == nil || rsp.Type == Continue {
				if _, err = raw.literals[i].WriteTo(c.t); err == nil {
					err = c.t.WriteLine(raw.ReadLine())
				}
			} else {
				err = ResponseError{rsp, "unexpected command completion"}
			}
		}
	}

	// Flush buffer after the last line
	if err == nil {
		if err = c.t.Flush(); err == nil {
			return
		}
	}
	c.done(cmd, abort)
	return nil, err
}

// Recv receives at most one response from the server, updates the client state,
// and delivers the response to its final destination (c.Data or one of the
// commands in progress). io.EOF is returned once all responses have been
// received and the connection is closed.
//
// If the timeout is negative, Recv blocks indefinitely until a response is
// received or an error is encountered. If the timeout is zero, Recv polls for
// buffered responses, returning ErrTimeout immediately if none are available.
// Otherwise, Recv blocks until a response is received or the timeout expires.
func (c *Client) Recv(timeout time.Duration) error {
	rsp, err := c.recv(timeout)
	if err == nil && !c.deliver(rsp) {
		if rsp.Type == Continue {
			err = ResponseError{rsp, "unexpected continuation request"}
		} else {
			err = ResponseError{rsp, "undeliverable response"}
		}
	}
	return err
}

// SetLiteralReader installs a custom LiteralReader implementation into the
// response receiver pipeline. It returns the previously installed LiteralReader
// instance.
func (c *Client) SetLiteralReader(lr LiteralReader) LiteralReader {
	prev := c.r.LiteralReader
	if lr != nil {
		c.r.LiteralReader = lr
	}
	return prev
}

// Quote attempts to represent v, which must be string, []byte, or fmt.Stringer,
// as a quoted string for use with Client.Send. A literal string representation
// is used if v cannot be quoted.
func (c *Client) Quote(v interface{}) Field {
	var b []byte
	var cp bool
	switch s := v.(type) {
	case string:
		b = []byte(s)
	case []byte:
		b, cp = s, true
	case fmt.Stringer:
		b = []byte(s.String())
	default:
		return nil
	}
	if q := QuoteBytes(b, false); q != nil {
		return string(q)
	} else if cp {
		b = append([]byte(nil), b...)
	}
	return NewLiteral(b)
}

// next returns the next server response obtained directly from the reader.
func (c *Client) next() (rsp *Response, err error) {
	raw, err := c.r.Next()
	if err == nil {
		rsp, err = raw.Parse()
	}
	return
}

// greeting receives the server greeting, sets initial connection state, and
// requests server capabilities if they weren't included in the greeting.
func (c *Client) greeting(timeout time.Duration) (err error) {
	if timeout > 0 {
		// If c.recv fails, c.t.conn may be nil by the time the deferred
		// function executes; keep a reference to avoid a panic.
		conn := c.t.conn
		conn.SetDeadline(time.Now().Add(timeout))
		defer func() {
			conn.SetDeadline(time.Time{})
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				err = ErrTimeout
			}
		}()
	}

	// Wait for server greeting
	rsp, err := c.recv(block)
	if err != nil {
		return
	} else if rsp.Type != Status || !c.deliver(rsp) {
		return ResponseError{rsp, "invalid server greeting"}
	}

	// Set initial connection state
	switch rsp.Status {
	case OK:
		c.setState(Login)
	case PREAUTH:
		c.setState(Auth)
	case BYE:
		c.setState(Logout)
		fallthrough
	default:
		return ResponseError{rsp, "invalid greeting status"}
	}
	c.Logln(LogConn, "Server greeting:", rsp.Info)

	// Request capabilities if not included in the greeting
	if len(c.Caps) == 0 {
		_, err = c.Capability()
	}
	return
}

// receiver runs in a separate goroutine, reading a single server response for
// each request sent on the cch channel.
func (c *Client) receiver(cch <-chan chan<- *response) {
	recv := func() (r *response) {
		defer func() {
			if err := recover(); err != nil {
				r = &response{nil, fmt.Errorf("imap: receiver panic: %v", err)}
				c.Logf(LogGo, "Receiver panic (Tag=%s): %v\n%s", c.tag.id, err, debug.Stack())
			}
		}()
		rsp, err := c.next()
		return &response{rsp, err}
	}

	c.Logf(LogGo, "Receiver started (Tag=%s)", c.tag.id)
	defer c.Logf(LogGo, "Receiver finished (Tag=%s)", c.tag.id)

	for rch := range cch {
		rch <- recv()
	}
}

// recv returns the next server response, updating the client state beforehand.
func (c *Client) recv(timeout time.Duration) (rsp *Response, err error) {
	if c.state == Closed {
		return nil, io.EOF
	} else if c.rch == nil && (timeout < 0 || c.cch == nil) {
		rsp, err = c.next()
	} else {
		if c.rch == nil {
			rch := make(chan *response, 1)
			c.cch <- rch
			c.rch = rch
		}
		var r *response
		if timeout < 0 {
			r = <-c.rch
		} else {
			select {
			case r = <-c.rch:
			default:
				if timeout == 0 {
					return nil, ErrTimeout
				}
				select {
				case r = <-c.rch:
				case <-time.After(timeout):
					return nil, ErrTimeout
				}
			}
		}
		c.rch = nil
		rsp, err = r.rsp, r.err
	}
	if err == nil {
		c.update(rsp)
	} else if rsp == nil {
		defer c.setState(Closed)
		if err != io.EOF {
			c.close("protocol error")
		} else if err = c.close("end of stream"); err == nil {
			err = io.EOF
		}
	}
	return
}

// update examines server responses and updates client state as needed.
func (c *Client) update(rsp *Response) {
	if rsp.Label == "CAPABILITY" {
		c.setCaps(rsp.Fields[1:])
		return
	}
	switch rsp.Type {
	case Data:
		if c.Mailbox == nil {
			return
		}
		switch rsp.Label {
		case "FLAGS":
			c.Mailbox.Flags.Replace(rsp.Fields[1])
		case "EXISTS":
			c.Mailbox.Messages = rsp.Value()
		case "RECENT":
			c.Mailbox.Recent = rsp.Value()
		case "EXPUNGE":
			c.Mailbox.Messages--
			if c.Mailbox.Recent > c.Mailbox.Messages {
				c.Mailbox.Recent = c.Mailbox.Messages
			}
			if c.Mailbox.Unseen == rsp.Value() {
				c.Mailbox.Unseen = 0
			}
		}
	case Status:
		switch rsp.Status {
		case BAD:
			// RFC 3501 is a bit vague on how the client is expected to react to
			// an untagged BAD response. It's probably best to close this
			// connection and open a new one; leave this up to the caller. For
			// now, abort all active commands to avoid waiting for completion
			// responses that may never come.
			c.Logln(LogCmd, "ABORT!", rsp.Info)
			c.deliver(abort)
		case BYE:
			c.Logln(LogConn, "Logout reason:", rsp.Info)
			c.setState(Logout)
		}
		fallthrough
	case Done:
		if rsp.Label == "ALERT" {
			c.Logln(LogConn, "ALERT!", rsp.Info)
			return
		} else if c.Mailbox == nil {
			return
		}
		switch selected := (c.state == Selected); rsp.Label {
		case "PERMANENTFLAGS":
			c.Mailbox.PermFlags.Replace(rsp.Fields[1])
		case "READ-ONLY":
			if selected && !c.Mailbox.ReadOnly {
				c.Logln(LogState, "Mailbox access change: RW -> RO")
			}
			c.Mailbox.ReadOnly = true
		case "READ-WRITE":
			if selected && c.Mailbox.ReadOnly {
				c.Logln(LogState, "Mailbox access change: RO -> RW")
			}
			c.Mailbox.ReadOnly = false
		case "UIDNEXT":
			c.Mailbox.UIDNext = rsp.Value()
		case "UIDVALIDITY":
			v := rsp.Value()
			if u := c.Mailbox.UIDValidity; selected && u != v {
				c.Logf(LogState, "Mailbox UIDVALIDITY change: %d -> %d", u, v)
			}
			c.Mailbox.UIDValidity = v
		case "UNSEEN":
			c.Mailbox.Unseen = rsp.Value()
		case "UIDNOTSTICKY":
			c.Mailbox.UIDNotSticky = true
		}
	}
}

// deliver saves the response to its final destination. It returns false for
// continuation requests and unknown command completions. The abort response is
// delivered to all commands in progress.
func (c *Client) deliver(rsp *Response) bool {
	if rsp.Type&(Data|Status) != 0 {
		for _, tag := range c.tags {
			cmd := c.cmds[tag]
			if filter := cmd.config.Filter; filter != nil && filter(cmd, rsp) {
				cmd.Data = append(cmd.Data, rsp)
				return true
			}
		}
		c.Data = append(c.Data, rsp)
		return true
	} else if rsp.Type == Done {
		if cmd := c.cmds[rsp.Tag]; cmd != nil {
			c.done(cmd, rsp)
			return true
		}
		c.Logln(LogCmd, "<<<", rsp.Tag, "(Unknown)")
	} else if rsp == abort {
		for _, tag := range c.tags {
			c.done(c.cmds[tag], abort)
		}
		return true
	}
	return false
}

// done completes command execution by setting cmd.result to rsp and updating
// the client's command state.
func (c *Client) done(cmd *Command, rsp *Response) {
	if cmd.result != nil {
		return
	}
	cmd.result = rsp
	if tag := cmd.tag; c.cmds[tag] != nil {
		delete(c.cmds, tag)
		if c.tags[0] == tag {
			c.tags = c.tags[1:]
		} else if n := len(c.tags); c.tags[n-1] == tag {
			c.tags = c.tags[:n-1]
		} else {
			for i, v := range c.tags {
				if v == tag {
					c.tags = append(c.tags[:i], c.tags[i+1:]...)
					break
				}
			}
		}
	}
	if rsp == abort {
		c.Logln(LogCmd, "<<<", cmd.tag, "(Abort)")
	} else {
		c.Logln(LogCmd, "<<<", rsp)
	}
}

// checkContinue returns the next continuation request or completion result of
// cmd. In synchronous mode (sync == true), it flushes the buffer and blocks
// until a continuation request or cmd completion response is received. In
// asynchronous mode, it polls for cmd completion, returning as soon as all
// buffered responses are processed. A continuation request is not expected in
// asynchronous mode and results in an error.
func (c *Client) checkContinue(cmd *Command, sync bool) (rsp *Response, err error) {
	mode := poll
	if sync {
		if err = c.t.Flush(); err != nil {
			return
		}
		mode = block
	}
	for cmd.InProgress() {
		if rsp, err = c.recv(mode); err != nil {
			if err == ErrTimeout {
				err = nil
			}
			return
		} else if !c.deliver(rsp) {
			if rsp.Type == Continue {
				if !sync {
					err = ResponseError{rsp, "unexpected continuation request"}
				}
			} else {
				err = ResponseError{rsp, "undeliverable response"}
			}
			return
		}
	}
	return cmd.Result(0)
}

// setState changes connection state and performs the associated client updates.
// If the new state is Selected, it is assumed that c.Mailbox is already set.
func (c *Client) setState(s ConnState) {
	prev := c.state
	if prev == s || prev == Closed {
		return
	}
	c.state = s
	if s != Selected {
		c.Logf(LogState, "State change: %v -> %v", prev, s)
		c.Mailbox = nil
		if s == Closed {
			if c.cch != nil {
				close(c.cch)
			}
			c.setCaps(nil)
			c.deliver(abort)
		}
	} else if c.debugLog.mask&LogState != 0 {
		mb, rw := c.Mailbox.Name, "[RW]"
		if c.Mailbox.ReadOnly {
			rw = "[RO]"
		}
		c.Logf(LogState, "State change: %v -> %v (%+q %s)", prev, s, mb, rw)
	}
}

// setCaps updates the server capability set.
func (c *Client) setCaps(caps []Field) {
	for v := range c.Caps {
		delete(c.Caps, v)
	}
	for _, f := range caps {
		if v := toUpper(AsAtom(f)); v != "" {
			c.Caps[v] = true
		} else {
			c.Logln(LogState, "Invalid capability:", f)
		}
	}
	if c.debugLog.mask&LogState != 0 {
		caps := strings.Join(c.getCaps(""), " ")
		if caps == "" {
			caps = "(none)"
		}
		c.Logln(LogState, "Capabilities:", caps)
	}
}

// getCaps returns a sorted list of capabilities that share a common prefix. The
// prefix is stripped from the returned strings.
func (c *Client) getCaps(prefix string) []string {
	caps := make([]string, 0, len(c.Caps))
	if n := len(prefix); n == 0 {
		for v := range c.Caps {
			caps = append(caps, v)
		}
	} else {
		for v := range c.Caps {
			if strings.HasPrefix(v, prefix) {
				caps = append(caps, v[n:])
			}
		}
	}
	sort.Strings(caps)
	return caps
}

// close closes the connection without sending any additional data or updating
// client state. After the first invocation this method becomes a no-op.
func (c *Client) close(reason string) (err error) {
	c.closer.Do(func() {
		if reason != "" {
			c.Logln(LogConn, "Close reason:", reason)
		}
		if err = c.t.Close(false); err != nil {
			c.Logln(LogConn, "Close error:", err)
		}
	})
	return
}


text:
# Portions Copyright (c) 2015-present, Facebook, Inc. All rights reserved.

SHELL=bash -o pipefail

default: build

build:
	dune build

install:
	opam pin add reason . -y

# CI uses opam. Regular workflow needn't.
test-ci: install test-once-installed

# Can be run with esy x - no need to build beforehand.
test-once-installed: clean-tests
	./miscTests/rtopIntegrationTest.sh
	./miscTests/backportSyntaxTests.sh
	cd formatTest; ./test.sh

.PHONY: coverage
coverage:
	find -iname "bisect*.out" -exec rm {} \;
	make test-once-installed
	bisect-ppx-report -ignore-missing-files -I _build/ -html coverage-after/ bisect*.out ./*/*/*/bisect*.out
	find -iname "bisect*.out" -exec rm {} \;

clean-tests:
	rm -rf ./formatTest/**/actual_output
	rm -rf ./formatTest/**/intf_output
	rm -rf ./formatTest/**/**/TestTest.cmi
	rm -f ./formatTest/failed_tests
	rm -f ./miscTests/reactjs_jsx_ppx_tests/*.cm*

testFormat: build clean-tests
	cd formatTest; ./test.sh

all_errors:
	@ echo "Regenerate all the possible error states for Menhir."
	@ echo "Warning: This will take a while and use a lot of CPU and memory."
	@ echo "---"
	menhir --explain --strict --unused-tokens src/reason-parser/reason_parser.mly --list-errors > src/reason-parser/reason_parser.messages.checked-in

clean: clean-tests
	dune clean

clean-for-ci: clean-tests
	rm -rf ./_build

.PHONY: build clean

ROOT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
SUBSTS:=$(ROOT_DIR)/pkg/substs

# For publishing esy releases to npm
esy-prepublish: build clean-tests pre_release
	node ./scripts/esy-prepublish.js

# For OPAM
pre_release:
ifndef version
	$(error environment variable 'version' is undefined)
endif
	export git_version="$(shell git rev-parse --verify HEAD)"; \
	export git_short_version="$(shell git rev-parse --short HEAD)"; \
	$(SUBSTS) $(ROOT_DIR)/src/refmt/package.ml.in

.PHONY: pre_release

# For OPAM
release_check:
	./scripts/release-check.sh

# For OPAM
release: release_check pre_release
	git add package.json src/refmt/package.ml reason.opam
	git commit -m "Version $(version)"
	git tag -a $(version) -m "Version $(version)."
	# Push first the objects, then the tag.
	git push "git@github.com:facebook/Reason.git"
	git push "git@github.com:facebook/Reason.git" tag $(version)
	git clean -fdx
	./scripts/opam-release.sh

.PHONY: release

all-supported-ocaml-versions:
# the --dev flag has been omitted here but should be re-introduced eventually
	dune build @install @runtest --root .

.PHONY: all-supported-ocaml-versions


text:
#pragma once

#include "ocilibcpp/types.hpp"

// ReSharper disable CppClangTidyHicppUseEqualsDefault
// ReSharper disable CppClangTidyModernizeUseEqualsDefault
// ReSharper disable CppClangTidyMiscMisplacedConst

namespace ocilib
{

inline Object::Object()
{
}

inline Object::Object(const TypeInfo &typeInfo)
{
    Connection connection = typeInfo.GetConnection();
    Acquire(core::Check(OCI_ObjectCreate(connection, typeInfo)), reinterpret_cast<HandleFreeFunc>(OCI_ObjectFree), nullptr, connection.GetHandle());
}

inline Object::Object(OCI_Object *pObject, core::Handle *parent)
{
    Acquire(pObject, nullptr, nullptr, parent);
}

inline Object Object::Clone() const
{
    Object result(GetTypeInfo());

    core::Check(OCI_ObjectAssign(result, *this));

    return result;
}

inline bool Object::IsAttributeNull(const ostring& name) const
{
    return (core::Check(OCI_ObjectIsNull(*this, name.c_str())) == TRUE);
}

inline void Object::SetAttributeNull(const ostring& name)
{
    core::Check(OCI_ObjectSetNull(*this, name.c_str()));
}

inline TypeInfo Object::GetTypeInfo() const
{
    return TypeInfo(core::Check(OCI_ObjectGetTypeInfo(*this)));
}

inline Reference Object::GetReference() const
{
    TypeInfo typeInfo = GetTypeInfo();
    Connection connection = typeInfo.GetConnection();

    OCI_Ref *pRef = OCI_RefCreate(connection, typeInfo);

    core::Check(OCI_ObjectGetSelfRef(*this, pRef));

    return Reference(pRef, GetHandle());
}

inline Object::ObjectType Object::GetType() const
{
    return ObjectType(static_cast<ObjectType::Type>(core::Check(OCI_ObjectGetType(*this))));
}

template<>
inline bool Object::Get<bool>(const ostring& name) const
{
    return (core::Check(OCI_ObjectGetBoolean(*this, name.c_str())) == TRUE);
}

template<>
inline short Object::Get<short>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetShort(*this, name.c_str()));
}

template<>
inline unsigned short Object::Get<unsigned short>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetUnsignedShort(*this, name.c_str()));
}

template<>
inline int Object::Get<int>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetInt(*this, name.c_str()));
}

template<>
inline unsigned int Object::Get<unsigned int>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetUnsignedInt(*this, name.c_str()));
}

template<>
inline big_int Object::Get<big_int>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetBigInt(*this, name.c_str()));
}

template<>
inline big_uint Object::Get<big_uint>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetUnsignedBigInt(*this, name.c_str()));
}

template<>
inline float Object::Get<float>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetFloat(*this, name.c_str()));
}

template<>
inline double Object::Get<double>(const ostring& name) const
{
    return core::Check(OCI_ObjectGetDouble(*this, name.c_str()));
}

template<>
inline Number Object::Get<Number>(const ostring& name) const
{
    return Number(core::Check(OCI_ObjectGetNumber(*this, name.c_str())), GetHandle());
}

template<>
inline ostring Object::Get<ostring>(const ostring& name) const
{
    return core::MakeString(core::Check(OCI_ObjectGetString(*this,name.c_str())));
}

template<>
inline Date Object::Get<Date>(const ostring& name) const
{
    return Date(core::Check(OCI_ObjectGetDate(*this,name.c_str())), GetHandle());
}

template<>
inline Timestamp Object::Get<Timestamp>(const ostring& name) const
{
    return Timestamp(core::Check(OCI_ObjectGetTimestamp(*this,name.c_str())), GetHandle());
}

template<>
inline Interval Object::Get<Interval>(const ostring& name) const
{
    return Interval(core::Check(OCI_ObjectGetInterval(*this,name.c_str())), GetHandle());
}

template<>
inline Object Object::Get<Object>(const ostring& name) const
{
    return Object(core::Check(OCI_ObjectGetObject(*this,name.c_str())), GetHandle());
}

template<>
inline Reference Object::Get<Reference>(const ostring& name) const
{
    return Reference(core::Check(OCI_ObjectGetRef(*this,name.c_str())), GetHandle());
}

template<>
inline Clob Object::Get<Clob>(const ostring& name) const
{
    return Clob(core::Check(OCI_ObjectGetLob(*this,name.c_str())), GetHandle());
}

template<>
inline NClob Object::Get<NClob>(const ostring& name) const
{
    return NClob(core::Check(OCI_ObjectGetLob(*this, name.c_str())), GetHandle());
}

template<>
inline Blob Object::Get<Blob>(const ostring& name) const
{
    return Blob(core::Check(OCI_ObjectGetLob(*this,name.c_str())), GetHandle());
}

template<>
inline File Object::Get<File>(const ostring& name) const
{
    return File(core::Check(OCI_ObjectGetFile(*this,name.c_str())), GetHandle());
}

template<>
inline Raw Object::Get<Raw>(const ostring& name) const
{
    unsigned int size = core::Check(OCI_ObjectGetRawSize(*this, name.c_str()));

    core::ManagedBuffer<unsigned char> buffer(static_cast<size_t>(size + 1));

    size = static_cast<unsigned int>(core::Check(OCI_ObjectGetRaw(*this, name.c_str(), static_cast<AnyPointer>(buffer), size)));

    return core::MakeRaw(buffer, size);
}

template<class T>
T Object::Get(const ostring& name) const
{
    return T(core::Check(OCI_ObjectGetColl(*this, name.c_str())), GetHandle());
}

template<>
inline void Object::Set<bool>(const ostring& name, const bool &value)
{
    core::Check(OCI_ObjectSetBoolean(*this, name.c_str(), static_cast<boolean>(value)));
}

template<>
inline void Object::Set<short>(const ostring& name, const short &value)
{
    core::Check(OCI_ObjectSetShort(*this, name.c_str(), value));
}

template<>
inline void Object::Set<unsigned short>(const ostring& name, const unsigned short &value)
{
    core::Check(OCI_ObjectSetUnsignedShort(*this, name.c_str(), value));
}

template<>
inline void Object::Set<int>(const ostring& name, const int &value)
{
    core::Check(OCI_ObjectSetInt(*this, name.c_str(), value));
}

template<>
inline void Object::Set<unsigned int>(const ostring& name, const unsigned int &value)
{
    core::Check(OCI_ObjectSetUnsignedInt(*this, name.c_str(), value));
}

template<>
inline void Object::Set<big_int>(const ostring& name, const big_int &value)
{
    core::Check(OCI_ObjectSetBigInt(*this, name.c_str(), value));
}

template<>
inline void Object::Set<big_uint>(const ostring& name, const big_uint &value)
{
    core::Check(OCI_ObjectSetUnsignedBigInt(*this, name.c_str(), value));
}

template<>
inline void Object::Set<float>(const ostring& name, const float &value)
{
    core::Check(OCI_ObjectSetFloat(*this, name.c_str(), value));
}

template<>
inline void Object::Set<double>(const ostring& name, const double &value)
{
    core::Check(OCI_ObjectSetDouble(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Number>(const ostring& name, const Number &value)
{
    core::Check(OCI_ObjectSetNumber(*this, name.c_str(), value));
}

template<>
inline void Object::Set<ostring>(const ostring& name, const ostring &value)
{
    core::Check(OCI_ObjectSetString(*this, name.c_str(), value.c_str()));
}

template<>
inline void Object::Set<Date>(const ostring& name, const Date &value)
{
    core::Check(OCI_ObjectSetDate(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Timestamp>(const ostring& name, const Timestamp &value)
{
    core::Check(OCI_ObjectSetTimestamp(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Interval>(const ostring& name, const Interval &value)
{
    core::Check(OCI_ObjectSetInterval(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Object>(const ostring& name, const Object &value)
{
    core::Check(OCI_ObjectSetObject(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Reference>(const ostring& name, const Reference &value)
{
    core::Check(OCI_ObjectSetRef(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Clob>(const ostring& name, const Clob &value)
{
    core::Check(OCI_ObjectSetLob(*this, name.c_str(), value));
}

template<>
inline void Object::Set<NClob>(const ostring& name, const NClob &value)
{
    core::Check(OCI_ObjectSetLob(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Blob>(const ostring& name, const Blob &value)
{
    core::Check(OCI_ObjectSetLob(*this, name.c_str(), value));
}

template<>
inline void Object::Set<File>(const ostring& name, const File &value)
{
    core::Check(OCI_ObjectSetFile(*this, name.c_str(), value));
}

template<>
inline void Object::Set<Raw>(const ostring& name, const Raw &value)
{
    const AnyPointer data = value.empty() ? nullptr : static_cast<AnyPointer>(const_cast<Raw::value_type*>(&value[0])) ;

    core::Check(OCI_ObjectSetRaw(*this, name.c_str(), data, static_cast<unsigned int>(value.size())));

}

template<class T>
void Object::Set(const ostring& name, const T &value)
{
    core::Check(OCI_ObjectSetColl(*this, name.c_str(), value));
}

inline ostring Object::ToString() const
{
    if (!IsNull())
    {
        unsigned int len = 0;

        core::Check(OCI_ObjectToText(*this, &len, nullptr));

        core::ManagedBuffer<otext> buffer(static_cast<size_t>(len + 1));

        core::Check(OCI_ObjectToText(*this, &len, buffer));

        return core::MakeString(static_cast<const otext *>(buffer), static_cast<int>(len));
    }

    return OCI_STRING_NULL;
}

}


text:
/**
 * Implement operations that provide compatibility with NXP
 * PN544 controller.  Specifically facilitate peer-to-peer
 * operations with PN544 controller.
 */
#include "Pn544Interop.h"

#include "NfcDebug.h"
#include "NfcNciUtil.h"
#include "IntervalTimer.h"
#include "Mutex.h"
#include "NfcTag.h"

extern void StartStopPolling(bool aIsStartPolling);
static void Pn544InteropStartPolling(union sigval); // Callback function for interval timer.

static const int gIntervalTime = 1000; // Millisecond between the check to restore polling.
static IntervalTimer gTimer;
static Mutex gMutex;
static bool gIsBusy = false;   // Is timer busy?
static bool gAbortNow = false; // Stop timer during next callback.

void Pn544InteropStopPolling()
{
  NCI_DEBUG("enter");
  gMutex.Lock();
  gTimer.Kill();
  StartStopPolling(false);
  gIsBusy = true;
  gAbortNow = false;
  gTimer.Set(gIntervalTime, Pn544InteropStartPolling); // After some time, start polling again.
  gMutex.Unlock();
  NCI_DEBUG("exit");
}

void Pn544InteropStartPolling(union sigval)
{
  NCI_DEBUG("enter");

  gMutex.Lock();
  NfcTag::ActivationState state = NfcTag::GetInstance().GetActivationState();

  if (gAbortNow) {
    NCI_DEBUG("abort now");

    gIsBusy = false;
    goto TheEnd;
  }

  if (state == NfcTag::Idle) {
    NCI_DEBUG("start polling");

    StartStopPolling(true);
    gIsBusy = false;
  } else {
    NCI_DEBUG("try again later");

    gTimer.Set(gIntervalTime, Pn544InteropStartPolling); // After some time, start polling again.
  }

TheEnd:
  gMutex.Unlock();

  NCI_DEBUG("exit");
}

bool Pn544InteropIsBusy()
{
  bool isBusy = false;
  gMutex.Lock();
  isBusy = gIsBusy;
  gMutex.Unlock();

  NCI_DEBUG("%u", isBusy);
  return isBusy;
}

void Pn544InteropAbortNow()
{
  NCI_DEBUG("enter");

  gMutex.Lock();
  gAbortNow = true;
  gMutex.Unlock();
}


text:
DAEMON="ssl-check"
SSL_CHECK_RC="/etc/sslcheckrc"

# Defaults
declare -a SSL_CHECK

Remove_known_ssl_values() {
    grep -vFx "issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3" \
    | grep -vFx "issuer=/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA" \
    | grep -vFx "Server public key is 2048 bit" \
    | grep -vFx "Secure Renegotiation IS supported" \
    | grep -vFx "    Protocol  : TLSv1.2" \
    | grep -vFx "    Cipher    : ECDHE-RSA-AES128-GCM-SHA256" \
    | grep -vFx "    Cipher    : ECDHE-RSA-AES256-GCM-SHA384" \
    # Keeping last backslash inactive
}

set -e

# shellcheck disable=SC1090
source "$SSL_CHECK_RC"

# Check hosts
for SERVICE in "${SSL_CHECK[@]}"; do
    HOST="$(cut -d ":" -f 1 <<< "$SERVICE")"
    PORT="$(cut -d ":" -f 2 <<< "$SERVICE")"
    STARTTLS="$(cut -d ":" -f 3 <<< "$SERVICE")"
    SSL_ARGS=""

    # Optional STARTTLS
    if [ -n "$STARTTLS" ]; then
        SSL_ARGS="-starttls ${STARTTLS}"
    fi

    # Support SNI
    # shellcheck disable=SC2086
    SSL_OUTPUT="$(timeout 40 openssl s_client -purpose "sslserver" -verify_return_error \
        -connect "${HOST}:${PORT}" -servername "$HOST" ${SSL_ARGS} \
        < /dev/null 2> /dev/null \
        | grep -E "^(issuer=|Server public key is|Secure Renegotiation|    Protocol  :|    Cipher    :|    Verify return code:)" \
        | Remove_known_ssl_values)"
    if [ "$SSL_OUTPUT" != "    Verify return code: 0 (ok)" ]; then
        echo "${DAEMON}: Unexpected output for ${SERVICE}" 1>&2
    fi
done

exit 0


text:
Remove Python 2 packages

```no-highlight
# apt-get remove --purge -y python-dev python-pip
```

Install Python 3 packages

```no-highlight
# apt-get install -y python3 python3-dev python3-pip
```

Install Python Packages

```no-highlight
# cd /opt/netbox
# pip3 install -r requirements.txt
```

Gunicorn Update

```no-highlight
# pip uninstall gunicorn
# pip3 install gunicorn
```

Re-install LDAP Module (optional if using LDAP for auth)

```no-highlight
sudo pip3 install django-auth-ldap
```


text:
package org.jboss.hal.testsuite.page.configuration;

import org.jboss.hal.resources.Ids;
import org.jboss.hal.testsuite.fragment.FormFragment;
import org.jboss.hal.testsuite.fragment.TabsFragment;
import org.jboss.hal.testsuite.page.BasePage;
import org.jboss.hal.testsuite.page.Place;
import org.openqa.selenium.support.FindBy;

@Place(Ids.UNDERTOW_SERVLET_CONTAINER)
public class UndertowServletContainerPage extends BasePage {

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_TAB_CONTAINER)
    private TabsFragment configurationTab;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_CONFIGURATION_FORM)
    private FormFragment attributesForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_MIME_MAPPING_FORM)
    private FormFragment mimeMappingForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_WELCOME_FILE_FORM)
    private FormFragment welcomeFileForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_JSP + "-form")
    private FormFragment jspForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_WEBSOCKET + "-form")
    private FormFragment webSocketsForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_SESSION + "-form")
    private FormFragment sessionsForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_COOKIE + "-form")
    private FormFragment cookiesForm;

    @FindBy(id = Ids.UNDERTOW_SERVLET_CONTAINER_CRAWLER + "-form")
    private FormFragment crawlerForm;

    public FormFragment getJspForm() {
        return jspForm;
    }

    public FormFragment getWebSocketsForm() {
        return webSocketsForm;
    }

    public FormFragment getSessionsForm() {
        return sessionsForm;
    }

    public FormFragment getCookiesForm() {
        return cookiesForm;
    }

    public FormFragment getCrawlerForm() {
        return crawlerForm;
    }

    public TabsFragment getConfigurationTab() {
        return configurationTab;
    }

    public FormFragment getAttributesForm() {
        configurationTab.select(Ids.UNDERTOW_SERVLET_CONTAINER_CONFIGURATION_TAB);
        return attributesForm;
    }

    public FormFragment getMimeMappingForm() {
        configurationTab.select(Ids.UNDERTOW_SERVLET_CONTAINER_MIME_MAPPING_TAB);
        return mimeMappingForm;
    }

    public FormFragment getWelcomeFileForm() {
        configurationTab.select(Ids.UNDERTOW_SERVLET_CONTAINER_WELCOME_FILE_TAB);
        return welcomeFileForm;
    }
}


text:
package job

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestJobStats(t *testing.T) {
	cache := NewMockCache()

	j := GetMockJobWithGenericSchedule()
	j.Init(cache)

	j.Run(cache)
	now := time.Now()

	assert.NotNil(t, j.Stats[0])
	assert.Equal(t, j.Stats[0].JobId, j.Id)
	assert.WithinDuration(t, j.Stats[0].RanAt, now, time.Second)
	assert.Equal(t, j.Stats[0].NumberOfRetries, uint(0))
	assert.True(t, j.Stats[0].Success)
	assert.NotNil(t, j.Stats[0].ExecutionDuration)
}

func TestKalaStats(t *testing.T) {
	cache := NewMockCache()

	for i := 0; i < 5; i++ {
		j := GetMockJobWithGenericSchedule()
		j.Init(cache)
		j.Run(cache)
	}
	now := time.Now()
	for i := 0; i < 5; i++ {
		j := GetMockJobWithGenericSchedule()
		j.Init(cache)
		j.Disable()
	}

	kalaStat := NewKalaStats(cache)
	createdAt := time.Now()
	nextRunAt := time.Now().Add(
		time.Duration(time.Minute * 5),
	)

	assert.Equal(t, kalaStat.Jobs, 10)
	assert.Equal(t, kalaStat.ActiveJobs, 5)
	assert.Equal(t, kalaStat.DisabledJobs, 5)
	assert.Equal(t, kalaStat.SuccessCount, uint(5))
	assert.Equal(t, kalaStat.ErrorCount, uint(0))
	assert.True(t, (nextRunAt.UnixNano()-kalaStat.NextRunAt.UnixNano()) > 0)
	assert.WithinDuration(t, kalaStat.NextRunAt, nextRunAt, time.Second)
	assert.WithinDuration(t, kalaStat.LastAttemptedRun, now, time.Millisecond*100)
	assert.WithinDuration(t, kalaStat.CreatedAt, createdAt, time.Millisecond*100)
}

func TestNextRunAt(t *testing.T) {
	cache := NewMockCache()

	sched := time.Now().Add(time.Second)
	j := GetMockJobWithSchedule(2, sched, "P1DT10M10S")
	j.Init(cache)
	j.Disable()

	sched2 := time.Now().Add(2 * time.Second)
	j2 := GetMockJobWithSchedule(2, sched2, "P1DT10M10S")
	j2.Init(cache)
	j2.Disable()

	kalaStat := NewKalaStats(cache)
	assert.Equal(t, j.NextRunAt.UnixNano(), kalaStat.NextRunAt.UnixNano())
	assert.Equal(t, j.Metadata.LastAttemptedRun.UnixNano(), kalaStat.LastAttemptedRun.UnixNano())
	assert.NotEqual(t, j2.NextRunAt.UnixNano(), kalaStat.NextRunAt.UnixNano())
}


text:
package org.spongepowered.common.entity.ai;

import com.google.common.base.MoreObjects;
import org.spongepowered.api.entity.ai.task.AITask;
import org.spongepowered.api.entity.ai.task.AITaskType;
import org.spongepowered.api.entity.living.Agent;

public final class SpongeAITaskType implements AITaskType {
    private final String id, name;
    private final Class<? extends AITask<? extends Agent>> aiClass;

    public SpongeAITaskType(String id, String name, Class<? extends AITask<? extends Agent>> aiClass) {
        this.id = id;
        this.name = name;
        this.aiClass = aiClass;
    }

    @Override
    public Class<? extends AITask<? extends Agent>> getAIClass() {
        return this.aiClass;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .addValue(this.id)
                .addValue(this.name)
                .add("aiClass", this.aiClass)
                .toString();
    }
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using System.Collections.Generic;
using EPiServerSimpleSite.Models.Blocks;

namespace EPiServerSimpleSite.Models.ViewModels
{
    public class PageListModel
    {
        public PageListModel(PageListBlock block)
        {
            Heading = block.Heading;
            ShowIntroduction = block.IncludeIntroduction;
            ShowPublishDate = block.IncludePublishDate;
        }
        public string Heading { get; set; }
        public IEnumerable<PageData> Pages { get; set; }
        public bool ShowIntroduction { get; set; }
        public bool ShowPublishDate { get; set; }
    }
}


text:
Showing which kind of async resource is covered by which test:

| Resource Type        | Test                                   |
|----------------------|----------------------------------------|
| CONNECTION           | test-connection.ssl.js                 |
| FSEVENTWRAP          | test-fseventwrap.js                    |
| FSREQWRAP            | test-fsreqwrap-{access,readFile}.js    |
| GETADDRINFOREQWRAP   | test-getaddrinforeqwrap.js             |
| GETNAMEINFOREQWRAP   | test-getnameinforeqwrap.js             |
| HTTPPARSER           | test-httpparser.{request,response}.js  |
| Immediate            | test-immediate.js                      |
| JSSTREAM             | TODO (crashes when accessing directly) |
| PBKDF2REQUEST        | test-crypto-pbkdf2.js                  |
| PIPECONNECTWRAP      | test-pipeconnectwrap.js                |
| PIPEWRAP             | test-pipewrap.js                       |
| PROCESSWRAP          | test-pipewrap.js                       |
| QUERYWRAP            | test-querywrap.js                      |
| RANDOMBYTESREQUEST   | test-crypto-randomBytes.js             |
| SHUTDOWNWRAP         | test-shutdownwrap.js                   |
| SIGNALWRAP           | test-signalwrap.js                     |
| STATWATCHER          | test-statwatcher.js                    |
| TCPCONNECTWRAP       | test-tcpwrap.js                        |
| TCPWRAP              | test-tcpwrap.js                        |
| TIMERWRAP            | test-timerwrap.set{Timeout,Interval}.js|
| TLSWRAP              | test-tlswrap.js                        |
| TTYWRAP              | test-ttywrap.{read,write}stream.js     |
| UDPSENDWRAP          | test-udpsendwrap.js                    |
| UDPWRAP              | test-udpwrap.js                        |
| WRITEWRAP            | test-writewrap.js                      |
| ZLIB                 | test-zlib.zlib-binding.deflate.js      |


text:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;

namespace Gear.Geometry
{
    /// <summary>
    /// Represents a three-dimensional vector using three double-precision floating point numbers.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct Vector3d : IEquatable<Vector3d>
    {
        #region Fields

        /// <summary>
        /// Backing field for the static <see cref="Vector3d.Zero"/> property.
        /// </summary>
        private static readonly Vector3d zero = new Vector3d(0.0, 0.0, 0.0);

        /// <summary>
        /// Backing field for the <see cref="Vector3d.X"/> property.
        /// </summary>
        private readonly double x;

        /// <summary>
        /// Backing field for the <see cref="Vector3d.Y"/> property.
        /// </summary>
        private readonly double y;

        /// <summary>
        /// Backing field for the <see cref="Vector3d.Z"/> property.
        /// </summary>
        private readonly double z;
        #endregion
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Vector3d"/> struct.
        /// </summary>
        /// <param name="vector">A <see cref="Gear.Geometry.Vector2d"/> instance supplying x and y values.</param>
        /// <remarks>The z value defaults to 0.</remarks>
        public Vector3d(Gear.Geometry.Vector2d vector)
        {
            this.x = vector.X;
            this.y = vector.Y;
            this.z = 0.0;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Vector3d"/> struct.
        /// </summary>
        /// <param name="vector">A <see cref="Vector3d"/> instance supplying x, y and z values.</param>
        public Vector3d(Vector3d vector)
        {
            this.x = vector.X;
            this.y = vector.Y;
            this.z = vector.Z;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Vector3d"/> struct.
        /// </summary>
        /// <param name="x">The X-component of the vector.</param>
        /// <param name="y">The Y-component of the vector.</param>
        /// <param name="z">The Z-component of the vector.</param>
        public Vector3d(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        #endregion
        #region Indexers
        public double this[int element]
        {
            get
            {
                Contract.Requires(element > -1);
                Contract.Requires(element < 3);

                if (element == 0)
                {
                    return this.x;
                }
                else if (element == 1)
                {
                    return this.y;
                }
                else if (element == 2)
                {
                    return this.z;
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
        #endregion
        #region Properties

        /// <summary>
        /// Gets the zero vector.
        /// </summary>
        public static Vector3d Zero
        {
            get
            {
                return Vector3d.zero;
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the positive X-axis.
        /// </summary>
        public static Vector3d Right
        {
            get
            {
                return new Vector3d(1.0, 0.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the negative X-axis.
        /// </summary>
        public static Vector3d Left
        {
            get
            {
                return new Vector3d(-1.0, 0.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the positive Y-axis.
        /// </summary>
        public static Vector3d Up
        {
            get
            {
                return new Vector3d(0.0, 1.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the negative Z-axis.
        /// </summary>
        public static Vector3d Down
        {
            get
            {
                return new Vector3d(0.0, -1.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the positive Y-axis.
        /// </summary>
        public static Vector3d Forward
        {
            get
            {
                return new Vector3d(0.0, 0.0, 1.0);
            }
        }

        /// <summary>
        /// Gets a unit vector that points along the negative Y-axis.
        /// </summary>
        public static Vector3d Backward
        {
            get
            {
                return new Vector3d(0.0, 0.0, -1.0);
            }
        }

        /// <summary>
        /// Gets or sets the X-component of the vector.
        /// </summary>
        public double X
        {
            get
            {
                return this.x;
            }
        }

        /// <summary>
        /// Gets or sets the Y-component of the vector.
        /// </summary>
        public double Y
        {
            get
            {
                return this.y;
            }
        }

        /// <summary>
        /// Gets or sets the Z-component of the vector.
        /// </summary>
        public double Z
        {
            get
            {
                return this.z;
            }
        }
        #endregion
        #region Operators

        /// <summary>
        /// Subtracts vector b from vector a and returns a new vector as the result.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns></returns>
        public static Vector3d operator -(Vector3d left, Vector3d right)
        {
            return new Vector3d(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
        }

        /// <summary>
        /// Calculates inequality of two vectors.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns></returns>
        public static bool operator !=(Vector3d left, Vector3d right)
        {
            return left.X != right.X || left.Y != right.Y || left.Z != right.Z;
        }

        /// <summary>
        /// Multiplies a vector by a scalar value and returns a new vector as the result.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns>A new <see cref="Vector3d"/> that is the result of the scalar multiplication.</returns>
        public static Vector3d operator *(Vector3d left, double right)
        {
            return new Vector3d(left.X * right, left.Y * right, left.Z * right);
        }

        /// <summary>
        /// Multiplies a vector by a scalar value and returns a new vector as the result.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns>A new <see cref="Vector3d"/> that is the result of the scalar multiplication.</returns>
        public static Vector3d operator *(double left, Vector3d right)
        {
            return new Vector3d(left * right.X, left * right.Y, left * right.Z);
        }

        /// <summary>
        /// Divides a vector by a scalar value and returns a new vector as the result.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns></returns>
        public static Vector3d operator /(Vector3d left, double right)
        {
            return new Vector3d(left.X / right, left.Y / right, left.Z / right);
        }

        /// <summary>
        /// Adds vector a and vector b and returns a new vector as the result.
        /// </summary>
        /// <param name="left">The left-hand vector to be added.</param>
        /// <param name="right">The right-hand vector to be added.</param>
        /// <returns></returns>
        public static Vector3d operator +(Vector3d left, Vector3d right)
        {
            return new Vector3d(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
        }

        /// <summary>
        /// Calculates equality of two vectors.
        /// </summary>
        /// <param name="left">The value that appears on the left-hand side of the operator.</param>
        /// <param name="right">The value that appears on the right-hand side of the operator.</param>
        /// <returns></returns>
        public static bool operator ==(Vector3d left, Vector3d right)
        {
            return left.X == right.X && left.Y == right.Y && left.Z == right.Z;
        }

        #endregion
        #region Methods
        public Vector3d Absolute()
        {
            return new Vector3d(Math.Abs(this.X), Math.Abs(this.Y), Math.Abs(this.Z));
        }

        /// <summary>
        /// Returns the absolute value of a specified <see cref="Vector3d"/>.
        /// </summary>
        /// <param name="vector">The <see cref="Vector3d"/> to get the absolute value of.</param>
        /// <returns>A new <see cref="Vector3d"/> that is the absolute value of <paramref name="vector"/>.</returns>
        public static Vector3d Absolute(Vector3d vector)
        {
            return new Vector3d(Math.Abs(vector.X), Math.Abs(vector.Y), Math.Abs(vector.Z));
        }

        public Vector3d Add(Vector3d other)
        {
            return new Vector3d(this.X + other.X, this.Y + other.Y, this.Z + other.Z);
        }

        /// <summary>
        /// Adds two vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Vector3d Add(Vector3d a, Vector3d b)
        {
            return new Vector3d(
                a.X + b.X,
                               a.Y + b.Y,
                               a.Z + b.Z);
        }

        /// <summary>
        /// Adds three vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static Vector3d Add(Vector3d a, Vector3d b, Vector3d c)
        {
            return new Vector3d(
                a.X + b.X + c.X,
                               a.Y + b.Y + c.Y,
                               a.Z + b.Z + c.Z);
        }

        /// <summary>
        /// Adds four vectors.
        /// </summary>
        /// <param name="a">The first vector to add.</param>
        /// <param name="b">The second vector to add.</param>
        /// <param name="c">The third vector to add.</param>
        /// <param name="d">The fourth vector to add.</param>
        /// <returns>A new <see cref="Vector3d"/> that is the result of the addition.</returns>
        public static Vector3d Add(Vector3d a, Vector3d b, Vector3d c, Vector3d d)
        {
            return new Vector3d(
                a.X + b.X + c.X + d.X,
                               a.Y + b.Y + c.Y + d.Y,
                               a.Z + b.Z + c.Z + d.Z);
        }

        /// <summary>
        /// Adds an array of vectors.
        /// </summary>
        /// <param name="vectors"></param>
        /// <returns></returns>
        public static Vector3d Add(Vector3d[] vectors)
        {
            if (vectors == null)
            {
                throw new ArgumentNullException("vectors");
            }
            else if (vectors.Length < 1)
            {
                return Vector3d.Zero;
            }
            else if (vectors.Length == 1)
            {
                return vectors[0];
            }

            var r = vectors[0];
            for (int i = 1; i < vectors.Length; i++)
            {
                r += vectors[i];
            }

            return r;
        }

        /// <summary>
        /// Returns the smallest <see cref="Vector3d"/> with whole number values which is greater than or equal to the current <see cref="Vector3d"/>.
        /// </summary>
        public Vector3d Ceiling()
        {
            return new Vector3d(
                Math.Ceiling(this.X),
                               Math.Ceiling(this.Y),
                               Math.Ceiling(this.Z));
        }

        /// <summary>
        /// Returns the smallest whole <see cref="Vector3d"/> greater than or equal to the specified <see cref="Vector3d"/>.
        /// </summary>
        /// <param name="vector"></param>
        /// <returns></returns>
        public static Vector3d Ceiling(Vector3d vector)
        {
            return new Vector3d(
                Math.Ceiling(vector.X),
                               Math.Ceiling(vector.Y),
                               Math.Ceiling(vector.Z));
        }

        /// <summary>
        /// Calculates the cross product of the current <see cref="Vector3d"/> and the specified <see cref="Vector3d"/>.
        /// </summary>
        /// <param name="other">The other <see cref="Vector3d"/> instance.</param>
        public Vector3d CrossProduct(Vector3d other)
        {
            return new Vector3d(
                (this.Y * other.Z) - (this.Z * other.Y),
                                    (this.Z * other.X) - (this.X * other.Z),
                                    (this.X * other.Y) - (this.Y * other.X));
        }

        /// <summary>
        /// Calculates the cross product of two <see cref="Vector3d">Vector3's</see>
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Vector3d CrossProduct(Vector3d a, Vector3d b)
        {
            return new Vector3d(
                (a.Y * b.Z) - (a.Z * b.Y),
                (a.Z * b.X) - (a.X * b.Z),
                (a.X * b.Y) - (a.Y * b.X));
        }

        /// <summary>
        /// Calculates the dot product of two vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static double DotProduct(Vector3d a, Vector3d b)
        {
            return (a.X * b.X) + (a.Y * b.Y) + (a.Z * b.Z);
        }

        public double DistanceTo(Vector3d other)
        {
            return Vector3d.DistanceBetween(this, other);
        }

        public static double DistanceBetween(Vector3d a, Vector3d b)
        {
            var xd = b.x - a.x;
            var yd = b.y - a.y;
            var zd = b.z - a.z;

            return Math.Sqrt((xd * xd) + (yd * yd) + (zd * zd));
        }

        /// <summary>
        /// Divides the current vector by a scalar value.
        /// </summary>
        /// <param name="scalar"></param>
        /// <returns></returns>
        public Vector3d Divide(double scalar)
        {
            return this / scalar;
        }

        /// <summary>
        /// Compares the current <see cref="Vector3d"/> and the specified object for equality.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (obj is Vector3d)
            {
                return Vector3d.Equals(this, (Vector3d)obj);
            }

            return false;
        }

        public static void OrthoNormalize(ref Vector3d normal, ref Vector3d tangent)
        {
            normal = normal.Normalize();

            var proj = normal * Vector3d.DotProduct(tangent, normal);

            tangent -= proj;

            tangent = tangent.Normalize();
        }

        /// <summary>
        /// Compares the current <see cref="Vector3d"/> and the specified <see cref="Vector3d"/> for equality.
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(Vector3d other)
        {
            return this.X == other.X && this.Y == other.Y && this.Z == other.Z;
        }

        /// <summary>
        /// Compares two <see cref="Vector3d"/> instances for equality.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool Equals(Vector3d a, Vector3d b)
        {
            return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
        }

        /// <summary>
        /// Calculates a unique hash code for the current instance.
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return __HashCode.Calculate(this.X, this.Y, this.Z);
        }

        /// <summary>
        /// Interpolates the midpoint of two vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Vector3d Interpolate(Vector3d a, Vector3d b)
        {
            return new Vector3d(
                (a.X * 0.5) + (b.X * 0.5),
                               (a.Y * 0.5) + (b.Y * 0.5),
                               (a.Z * 0.5) + (b.Z * 0.5));
        }

        /// <summary>
        /// Interpolates the weighted midpoint between two vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="weight"></param>
        /// <returns></returns>
        public static Vector3d Interpolate(Vector3d a, Vector3d b, double weight)
        {
            if (weight < 0.0 || weight > 1.0)
            {
                throw new ArgumentOutOfRangeException("weight", "Weight must be between 0.0 and 1.0");
            }

            return new Vector3d(
                (a.X * (1.0 - weight)) + (b.X * weight),
                (a.Y * (1.0 - weight)) + (b.Y * weight),
                (a.Z * (1.0 - weight)) + (b.Z * weight));
        }

        /// <summary>
        /// Returns the midpoint of three vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static Vector3d Interpolate(Vector3d a, Vector3d b, Vector3d c)
        {
            return Vector3d.Interpolate(Vector3d.Interpolate(a, b), c, 2.0 / 3.0);
        }

        public static Vector3d InterpolateN(params Vector3d[] vectors)
        {
            Contract.Requires(vectors != null);

            double weight = 1.0 / vectors.Length;
            Vector3d r = Vector3d.Zero;
            for (int i = 0; i < vectors.Length; i++)
            {
                r += vectors[i] * weight;
            }

            return r;
        }

        /// <summary>
        /// Returns the midpoint of four vectors.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        public static Vector3d Interpolate(Vector3d a, Vector3d b, Vector3d c, Vector3d d)
        {
            return Vector3d.Interpolate(Vector3d.Interpolate(a, c), Vector3d.Interpolate(b, d));
        }

        /// <summary>
        /// Inverts the current <see cref="Vector3d"/>.
        /// </summary>
        /// <returns>A new <see cref="Vector3d"/> that is the inversion of the current <see cref="Vector3d"/>.</returns>
        public Vector3d Invert()
        {
            return new Vector3d(-this.X, -this.Y, -this.Z);
        }

        /// <summary>
        /// Inverts the specified <see cref="Vector3d"/>.
        /// </summary>
        /// <param name="vector">The <see cref="Vector3d"/> instance to invert.</param>
        /// <returns>A new <see cref="Vector3d"/> that is the inversion of the specified <see cref="Vector3d"/>.</returns>
        public static Vector3d Invert(Vector3d vector)
        {
            return new Vector3d(-vector.X, -vector.Y, -vector.Z);
        }

        /// <summary>
        /// Determines if the current <see cref="Vector3d"/> is parallel to the specified <see cref="Vector3d"/>.
        /// </summary>
        /// <param name="other">Another <see cref="Vector3d"/> instance.</param>
        /// <returns>true if the current vector is parallel to the specified vector..</returns>
        public bool IsParallelTo(Vector3d other)
        {
            if (Vector3d.CrossProduct(this, other) == Vector3d.Zero)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Multiplies the current vector by a scalar value.
        /// </summary>
        /// <param name="scalar">The double-precision floating point value to multiply the X, Y, and Z components of the current vector.</param>
        /// <returns></returns>
        public Vector3d Multiply(double scalar)
        {
            return this * scalar;
        }

        /// <summary>
        /// Subtracts a vector from the current vector.
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public Vector3d Subtract(Vector3d other)
        {
            return this - other;
        }

        public Vector3d Normalize()
        {
            return Vector3d.Normalize(this);
        }

        public static Vector3d Normalize(Vector3d v)
        {
            var sum = (v.X * v.X) + (v.Y * v.Y) + (v.Z * v.Z);

            if (sum == 0)
            {
                return new Vector3d(0, 0, 0);
            }
            else
            {
                var d = Math.Sqrt(sum);
                return new Vector3d(v.X / d, v.Y / d, v.Z / d);
            }
        }

        public Vector3d Round(int digits)
        {
            Contract.Requires(digits >= 0);
            Contract.Requires(digits <= 15);

            return new Vector3d(
                Math.Round(this.x, digits),
                Math.Round(this.y, digits),
                Math.Round(this.z, digits));
        }

        public override string ToString()
        {
            return string.Format("({0}, {1}, {2})", this.X, this.Y, this.Z);
        }

        public Matrix4 ToTranslationMatrix()
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}


text:
TODO
====

* Jenkins
* Healthchecks
* Logging
* Stack and deploy
* Rolling updates (http://view.dckr.info:8080/#127)
* Swarm health checks
* SwarmKit (http://view.dckr.info:8080/#129)
* Logging (http://view.dckr.info:8080/#138)
* Docker for AWS
* Docker for Azure
* Drain


text:
package org.apache.camel.util;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class KeyValueHolderTest {

    @Test
    public void testKeyValueHolder() {
        KeyValueHolder<String, Integer> foo = new KeyValueHolder<>("foo", 123);

        assertEquals("foo", foo.getKey());
        assertEquals(123, foo.getValue().intValue());
    }

    @Test
    public void testEqualsAndHashCodeOnEqualObjects() {
        KeyValueHolder<String, Integer> foo1 = new KeyValueHolder<>("foo", 123);
        KeyValueHolder<String, Integer> foo2 = new KeyValueHolder<>("foo", 123);

        assertEquals(foo2, foo1, "Should be equals");
        assertEquals(foo2.hashCode(), foo1.hashCode(), "Hash code should be equal");
    }

    @Test
    public void testEqualsAndHashCodeOnUnequalObjects() {
        KeyValueHolder<String, Integer> foo = new KeyValueHolder<>("foo", 123);
        KeyValueHolder<String, Integer> bar = new KeyValueHolder<>("bar", 678);

        assertNotEquals(bar, foo, "Should not be equals");
        assertNotEquals(bar.hashCode(), foo.hashCode(), "Hash code should not be equal");
    }

    @Test
    public void testEqualsAndHashCodeOnUnequalObjectsWithSameKeys() {
        KeyValueHolder<String, Integer> foo1 = new KeyValueHolder<>("foo", 123);
        KeyValueHolder<String, Integer> foo2 = new KeyValueHolder<>("foo", 678);

        assertNotEquals(foo2, foo1, "Should not be equals");
        assertNotEquals(foo2.hashCode(), foo1.hashCode(), "Hash code should not be equal");
    }

    @Test
    public void testEqualsAndHashCodeOnUnequalObjectsWithSameValues() {
        KeyValueHolder<String, Integer> foo = new KeyValueHolder<>("foo", 123);
        KeyValueHolder<String, Integer> bar = new KeyValueHolder<>("bar", 123);

        assertNotEquals(bar, foo, "Should not be equals");
        assertNotEquals(bar.hashCode(), foo.hashCode(), "Hash code should not be equal");
    }

    @Test
    public void testToString() {
        KeyValueHolder<String, Integer> foo = new KeyValueHolder<>("foo", 123);

        assertEquals("foo -> 123", foo.toString());
    }
}


text:
package com.intellij.facet.ui;

import org.jetbrains.annotations.ApiStatus;

import javax.swing.*;

@ApiStatus.NonExtendable
public interface FacetValidatorsManager {

  void registerValidator(FacetEditorValidator validator, JComponent... componentsToWatch);

  void validate();

}


text:
<!DOCTYPE html>

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Heading

              Text that isn't wrapped in anything.

Followed by some text wrapped in a <p> paragraph.

              Maybe add a link or a different style of link with a highlight.

More content

a


text:
namespace ArduinoJson {

// Forward declaration
namespace Internals {
struct DynamicJsonBufferBlock;
}

// Implements a JsonBuffer with dynamic memory allocation.
// You are strongly encouraged to consider using StaticJsonBuffer which is much
// more suitable for embedded systems.
class DynamicJsonBuffer : public JsonBuffer {
 public:
  DynamicJsonBuffer();
  ~DynamicJsonBuffer();

  size_t size() const;

 protected:
  virtual void* alloc(size_t bytes);

 private:
  typedef Internals::DynamicJsonBufferBlock Block;

  static const size_t FIRST_BLOCK_CAPACITY = 32;

  static Block* createBlock(size_t capacity);

  inline bool canAllocInHead(size_t bytes) const;
  inline void* allocInHead(size_t bytes);
  inline void addNewBlock();

  Block* _head;
};
}