text:
#ifndef CCAN_COMPILER_H
#define CCAN_COMPILER_H
#include "config.h"

#ifndef COLD
#if HAVE_ATTRIBUTE_COLD
/**
 * COLD - a function is unlikely to be called.
 *
 * Used to mark an unlikely code path and optimize appropriately.
 * It is usually used on logging or error routines.
 *
 * Example:
 * static void COLD moan(const char *reason)
 * {
 *	fprintf(stderr, "Error: %s (%s)\n", reason, strerror(errno));
 * }
 */
#define COLD __attribute__((cold))
#else
#define COLD
#endif
#endif

#ifndef NORETURN
#if HAVE_ATTRIBUTE_NORETURN
/**
 * NORETURN - a function does not return
 *
 * Used to mark a function which exits; useful for suppressing warnings.
 *
 * Example:
 * static void NORETURN fail(const char *reason)
 * {
 *	fprintf(stderr, "Error: %s (%s)\n", reason, strerror(errno));
 *	exit(1);
 * }
 */
#define NORETURN __attribute__((noreturn))
#else
#define NORETURN
#endif
#endif

#ifndef PRINTF_FMT
#if HAVE_ATTRIBUTE_PRINTF
/**
 * PRINTF_FMT - a function takes printf-style arguments
 * @nfmt: the 1-based number of the function's format argument.
 * @narg: the 1-based number of the function's first variable argument.
 *
 * This allows the compiler to check your parameters as it does for printf().
 *
 * Example:
 * void PRINTF_FMT(2,3) my_printf(const char *prefix, const char *fmt, ...);
 */
#define PRINTF_FMT(nfmt, narg) \
	__attribute__((format(__printf__, nfmt, narg)))
#else
#define PRINTF_FMT(nfmt, narg)
#endif
#endif

#ifndef IDEMPOTENT
#if HAVE_ATTRIBUTE_CONST
/**
 * IDEMPOTENT - a function's return depends only on its argument
 *
 * This allows the compiler to assume that the function will return the exact
 * same value for the exact same arguments.  This implies that the function
 * must not use global variables, or dereference pointer arguments.
 */
#define IDEMPOTENT __attribute__((const))
#else
#define IDEMPOTENT
#endif
#endif

#if HAVE_ATTRIBUTE_UNUSED
#ifndef UNNEEDED
/**
 * UNNEEDED - a variable/function may not be needed
 *
 * This suppresses warnings about unused variables or functions, but tells
 * the compiler that if it is unused it need not emit it into the source code.
 *
 * Example:
 * // With some preprocessor options, this is unnecessary.
 * static UNNEEDED int counter;
 *
 * // With some preprocessor options, this is unnecessary.
 * static UNNEEDED void add_to_counter(int add)
 * {
 *	counter += add;
 * }
 */
#define UNNEEDED __attribute__((unused))
#endif

#ifndef NEEDED
#if HAVE_ATTRIBUTE_USED
/**
 * NEEDED - a variable/function is needed
 *
 * This suppresses warnings about unused variables or functions, but tells
 * the compiler that it must exist even if it (seems) unused.
 *
 * Example:
 *	// Even if this is unused, these are vital for debugging.
 *	static NEEDED int counter;
 *	static NEEDED void dump_counter(void)
 *	{
 *		printf("Counter is %i\n", counter);
 *	}
 */
#define NEEDED __attribute__((used))
#else
/* Before used, unused functions and vars were always emitted. */
#define NEEDED __attribute__((unused))
#endif
#endif

#ifndef UNUSED
/**
 * UNUSED - a parameter is unused
 *
 * Some compilers (eg. gcc with -W or -Wunused) warn about unused
 * function parameters.  This suppresses such warnings and indicates
 * to the reader that it's deliberate.
 *
 * Example:
 *	// This is used as a callback, so needs to have this prototype.
 *	static int some_callback(void *unused UNUSED)
 *	{
 *		return 0;
 *	}
 */
#define UNUSED __attribute__((unused))
#endif
#else
#ifndef UNNEEDED
#define UNNEEDED
#endif
#ifndef NEEDED
#define NEEDED
#endif
#ifndef UNUSED
#define UNUSED
#endif
#endif

#ifndef IS_COMPILE_CONSTANT
#if HAVE_BUILTIN_CONSTANT_P
/**
 * IS_COMPILE_CONSTANT - does the compiler know the value of this expression?
 * @expr: the expression to evaluate
 *
 * When an expression manipulation is complicated, it is usually better to
 * implement it in a function.  However, if the expression being manipulated is
 * known at compile time, it is better to have the compiler see the entire
 * expression so it can simply substitute the result.
 *
 * This can be done using the IS_COMPILE_CONSTANT() macro.
 *
 * Example:
 *	enum greek { ALPHA, BETA, GAMMA, DELTA, EPSILON };
 *
 *	// Out-of-line version.
 *	const char *greek_name(enum greek greek);
 *
 *	// Inline version.
 *	static inline const char *_greek_name(enum greek greek)
 *	{
 *		switch (greek) {
 *		case ALPHA: return "alpha";
 *		case BETA: return "beta";
 *		case GAMMA: return "gamma";
 *		case DELTA: return "delta";
 *		case EPSILON: return "epsilon";
 *		default: return "**INVALID**";
 *		}
 *	}
 *
 *	// Use inline if compiler knows answer.  Otherwise call function
 *	// to avoid copies of the same code everywhere.
 *	#define greek_name(g)						\
 *		 (IS_COMPILE_CONSTANT(greek) ? _greek_name(g) : greek_name(g))
 */
#define IS_COMPILE_CONSTANT(expr) __builtin_constant_p(expr)
#else
/* If we don't know, assume it's not. */
#define IS_COMPILE_CONSTANT(expr) 0
#endif
#endif

#ifndef WARN_UNUSED_RESULT
#if HAVE_WARN_UNUSED_RESULT
/**
 * WARN_UNUSED_RESULT - warn if a function return value is unused.
 *
 * Used to mark a function where it is extremely unlikely that the caller
 * can ignore the result, eg realloc().
 *
 * Example:
 * // buf param may be freed by this; need return value!
 * static char *WARN_UNUSED_RESULT enlarge(char *buf, unsigned *size)
 * {
 *	return realloc(buf, (*size) *= 2);
 * }
 */
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define WARN_UNUSED_RESULT
#endif
#endif
#endif /* CCAN_COMPILER_H */


text:
<?php namespace Pingpong\Admin\Console;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class MigrationCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'admin:migration';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Copy the migration file to the application.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $path = realpath(__DIR__ . '/../../../../src/migrations/');

        $this->laravel['files']->copyDirectory($path, $this->laravel['path'] . '/database/migrations');

        $this->info("Migrations published successfully.");
    }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @flow
 */
import React from 'react'
import PropTypes from 'prop-types'
import { observer } from 'mobx-react/native'
import styles from './styles'
import UserConnect_1 from './component'

@observer
class UserConnect_1Wrapper extends React.Component {

  render() {
    return (
      <UserConnect_1
        {...this.props}
      ></UserConnect_1>
    );
  }
}

export default UserConnect_1Wrapper


text:
package us.kbase.auth2.lib.token;

import static us.kbase.auth2.lib.Utils.checkStringNoCheckedException;
import static us.kbase.auth2.lib.Utils.nonNull;

import java.time.Instant;
import java.util.UUID;

import us.kbase.auth2.lib.TemporarySessionData;

/** A temporary token.
 * @author gaprice@lbl.gov
 *
 */
public class TemporaryToken {

	private final UUID id;
	private final String token;
	private final Instant creationDate;
	private final Instant expirationDate;

	/** Create a new temporary token.
	 * @param data the session data this token is associated with.
	 * @param token the token string.
	 */
	public TemporaryToken(
			final TemporarySessionData data,
			final String token) {
		nonNull(data, "data");
		checkStringNoCheckedException(token, "token");
		this.id = data.getId();
		this.token = token;
		this.creationDate = data.getCreated();
		this.expirationDate = data.getExpires();
	}

	/** Get the token string.
	 * @return the token string.
	 */
	public String getToken() {
		return token;
	}

	/** Get the date the token was created.
	 * @return the creation date.
	 */
	public Instant getCreationDate() {
		return creationDate;
	}

	/** Get the date the token expires.
	 * @return the expiration date.
	 */
	public Instant getExpirationDate() {
		return expirationDate;
	}

	/** Get the token's ID.
	 * @return the ID.
	 */
	public UUID getId() {
		return id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
		result = prime * result + ((expirationDate == null) ? 0 : expirationDate.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((token == null) ? 0 : token.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		TemporaryToken other = (TemporaryToken) obj;
		if (creationDate == null) {
			if (other.creationDate != null) {
				return false;
			}
		} else if (!creationDate.equals(other.creationDate)) {
			return false;
		}
		if (expirationDate == null) {
			if (other.expirationDate != null) {
				return false;
			}
		} else if (!expirationDate.equals(other.expirationDate)) {
			return false;
		}
		if (id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!id.equals(other.id)) {
			return false;
		}
		if (token == null) {
			if (other.token != null) {
				return false;
			}
		} else if (!token.equals(other.token)) {
			return false;
		}
		return true;
	}
}


text:
/*
 * PointGenerator.h
 *
 *  Created on: 2017-08-14
 *      Author: EmergencyTemporalShift
 */

struct Game;

#ifndef SRC_POINTGENERATOR_H_
#define SRC_POINTGENERATOR_H_

class PointGenerator {
public:
	PointGenerator(Game *game, float cost, float pointRate);
	virtual ~PointGenerator( void );

	int index;          // What is the index of this pointGenerator
	long int amount;         // How many of this PointGenerator are owned
	double cost;        // How much does this PointGenerator cost
	double pointRate;   // How many points does this PointGenerator give
	Game *game;        // Reference? to the game object. This might need to be a pointer.

	void collapseAllGenerators( void );

	int AddAmount( int number );
	int Add ( void );
	int SubtractAmount( int number );
	int Subtract( void );
	int BuyUpTo( int number );
	bool BuyAmount( int number);
	bool Buy( void );
	int BuyMax( void );
	int BuyPercentMax( float partOfMax );
	static double GenerateAllPoints( void );
	static double GeneratePoints( PointGenerator pointGenerator );
	double GeneratePoints( void );
	int getAmount( void );
	void setAmount(int amount );
};

#endif /* SRC_POINTGENERATOR_H_ */


text:
require "cgi"
require "webrat/core_extensions/blank"
require "webrat/merb/url_encoded_pair_parser"

module Webrat
  class ParamParser
    def self.parse_query_parameters(query_string)
      return {} if query_string.blank?

      pairs = query_string.split('&').collect do |chunk|
        next if chunk.empty?
        key, value = chunk.split('=', 2)
        next if key.empty?
        value = value.nil? ? nil : CGI.unescape(value)
        [ CGI.unescape(key), value ]
      end.compact

      UrlEncodedPairParser.new(pairs).result
    end
  end
end


text:
package org.metaeffekt.core.test.container;

import org.junit.Test;
import org.metaeffekt.core.inventory.processor.model.Artifact;
import org.metaeffekt.core.test.container.validation.AbstractContainerValidationTest;

import java.io.File;
import java.io.IOException;

public class CentOSContainerInventoryExtractionTest extends AbstractContainerValidationTest {

    @Test
    public void testInventory() throws IOException {
        assertInventory(
                new File("target/analysis"),
                new File("target/inventory/ae-centos-container-test-container-inventory.xls"));
    }

    protected void assertCommonPackageAttributes(Artifact artifact) {
        notNullOrEmpty("Component not set for " + artifact.getId(), artifact.getComponent());
        notNullOrEmpty("Version not set for " + artifact.getId(), artifact.getVersion());

        // NOTE:
        // - whether url is set depends on package meta data. No general assertion possible.
    }

}


text:
<?php

namespace Wall\Entity;

use Zend\Stdlib\Hydrator\ClassMethods;

class Link
{
    protected $id = null;
    protected $userId = null;
    protected $url = null;
    protected $title = null;
    protected $createdAt = null;
    protected $updatedAt = null;

    public function setId($id)
    {
        $this->id = (int)$id;
    }

    public function setUserId($userId)
    {
        $this->userId = (int)$userId;
    }

    public function setUrl($url)
    {
        $this->url = $url;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = new \DateTime($createdAt);
    }

    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = new \DateTime($updatedAt);
    }

    public function getId()
    {
        return $this->id;
    }

    public function getUserId()
    {
        return $this->userId;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}


text:
git config --global color.ui true

git config --global color.diff-highlight.oldNormal    "red bold"
git config --global color.diff-highlight.oldHighlight "red bold 52"
git config --global color.diff-highlight.newNormal    "green bold"
git config --global color.diff-highlight.newHighlight "green bold 22"

git config --global color.diff.meta       "yellow"
git config --global color.diff.frag       "magenta bold"
git config --global color.diff.commit     "yellow bold"
git config --global color.diff.old        "red bold"
git config --global color.diff.new        "green bold"
git config --global color.diff.whitespace "red reverse"


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

    const EntityFieldModel = require('oroquerydesigner/js/app/models/entity-field-model');

    const GroupingModel = EntityFieldModel.extend({
        fieldAttribute: 'name',

        defaults: {
            name: null,
            label: null,
            func: null,
            sorting: null
        },

        /**
         * @inheritDoc
         */
        constructor: function GroupingModel(...args) {
            GroupingModel.__super__.constructor.apply(this, args);
        }
    });

    return GroupingModel;
});


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace jgshort.SqlDom.Tests
{

    ///
    ///This is a test class for ConvertTest and is intended
    ///to contain all ConvertTest Unit Tests
    ///
    [TestClass()]
    public class ConvertTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for DataType
        ///
        public void DataTypeTestHelper<T>()
        {
            //
        }

        [TestMethod()]
        [DeploymentItem("jgshort.SqlDom.dll")]
        public void DataTypeTest()
        {
            DataTypeTestHelper<GenericParameterHelper>();
        }

        ///
        ///A test for Length
        ///
        public void LengthTestHelper<T>()
        {
            //
        }

        [TestMethod()]
        [DeploymentItem("jgshort.SqlDom.dll")]
        public void LengthTest()
        {
            LengthTestHelper<GenericParameterHelper>();
        }
    }
}


text:
package com.twitter.finagle

import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.prop.GeneratorDrivenPropertyChecks

@RunWith(classOf[JUnitRunner])
class FailureFlagsTest extends FunSuite with GeneratorDrivenPropertyChecks {
  import FailureFlags._

  case class FlagCheck(val flags: Long) extends FailureFlags[FlagCheck] {
    protected def copyWithFlags(f: Long): FlagCheck = FlagCheck(f)
  }

  private val flag = Gen.oneOf(
    0L,
    FailureFlags.Retryable,
    FailureFlags.Interrupted,
    FailureFlags.Wrapped,
    FailureFlags.Rejected,
    FailureFlags.Naming)
    // FailureFlags.NonRetryable - Conflicts with Restartable, so omitted here.

  private val flag2 = for (f1 <- flag; f2 <- flag if f1 != f2) yield f1|f2

  test("flagged, isFlagged, unflagged, masked") {
    for (flags <- Seq(flag, flag2)) {
      forAll(flags.suchThat(_ != 0)) { f =>
        assert(FlagCheck(f).isFlagged(f))
        assert(FlagCheck(Empty).flagged(f).flags == FlagCheck(f).flags)
        assert(FlagCheck(f).flags != FlagCheck(f).unflagged(f).flags)
        assert(!FlagCheck(Empty).isFlagged(f))
        assert(FlagCheck(f).masked(ShowMask).flags == (f & ShowMask))
      }
    }
  }

  test("FailureFlags.flagsOf") {
    val failures = Seq(
      FlagCheck(Interrupted|Retryable|Naming|Rejected|Wrapped),
      FlagCheck(NonRetryable),
      FlagCheck(Empty)
    )
    val names = Seq(
      Set("interrupted", "restartable", "wrapped", "rejected", "naming"),
      Set("nonretryable"),
      Set()
    )
    for ((f, n) <- failures.zip(names)) {
      assert(FailureFlags.flagsOf(f) == n)
    }
  }

  test("FailureFlags trait throws IllegalStateException when flagged with invalid combinations") {

    intercept[IllegalArgumentException] {
      FlagCheck(Retryable | NonRetryable)
    }
  }
}


text:
layout: post
title: Picking up the Blue Shell - Augmenting the Dev Workflow with PowerShell
speaker: Travis Jones
---

### Details

Explore the current state of Windows PowerShell tooling and how it can be the starting point for daily activities.

- Create a custom environment-tuned profile
- Minimize Windows Explorer usage by navigating with the shell
- Build Cmdlets to extend functionality
- Use the Powershell Gallery to discover and install modules

### About the Speaker

Travis Jones is a software developer that focuses on modernizing services in the financial industry. He particularly enjoys automation of all kinds, as well as MSSQL development and optimization.


text:
#ifndef VRunTimeType_Interface
#define VRunTimeType_Interface

/************************
 *****  Components  *****
 ************************/

#include "VStaticTransient.h"

#include "V_VRTTI.h"

/**************************
 *****  Declarations  *****
 **************************/

/*************************
 *****  Definitions  *****
 *************************/

namespace V {
    /**************************
     *----  VRunTimeType  ----*
     **************************/

    class V_API VRunTimeType : public VStaticTransient {
    //  MetaMaker Type
    public:
	typedef void (*MetaMaker)();

    //  Aliases
    public:
	typedef unsigned short index_t;
	typedef unsigned short level_t;

    //  Construction
    protected:
	VRunTimeType (std::type_info const &rRTTI, MetaMaker pMeta, VRunTimeType *pSuper);

    //  Destruction
    protected:
	~VRunTimeType ();

    //  Initialization
    protected:
	void initialize ();
	void addSubtype (VRunTimeType *pRTT);

    //  Access
    protected:
	MetaMaker meta () const {
	    return m_pMeta;
	}

    public:
	index_t index () const {
	    return m_xType;
	}
	level_t level () const {
	    return m_xLevel;
	}
	char const *name () const {
	    return m_iRTTI.name ();
	}
	index_t subtypeCount () const {
	    return m_cSubtypes;
	}
	VRunTimeType *supertype () const {
	    return m_pSuper;
	}

    //  Query
    public:
	bool isA (VRunTimeType const& rRTT) const;

    //  State
    protected:
	V::VRTTI		m_iRTTI;
	MetaMaker const		m_pMeta;
	VRunTimeType *const	m_pSuper;
	index_t			m_xType;
	level_t			m_xLevel;
	index_t			m_cSubtypes;
    };

    /******************************
     *----  V::VRunTimeType_  ----*
     ******************************/
    /*------------------------------------------------------------------------------------*
     *  In MSVC6, the obvious specialization:
     *
     *	template <> class VRunTimeType_<VReferenceable,VTransient> : public VRunTimeType {
     *	//  Construction
     *	public:
     *	    VRunTimeType_();
     *	};
     *
     *	doesn't work, so the following indirect specializations are used instead:
     *
     *------------------------------------------------------------------------------------*/
    template<typename T> class VRunTimeTypeTraits_ {
    public:
	static VRunTimeType *rtt () {
	    return &T::RTT;
	}
    };

    class VReferenceableBase;

    template<> class VRunTimeTypeTraits_<VReferenceableBase> {
    public:
	static VRunTimeType *rtt () {
	    return 0;
	}
    };

    template<typename T,typename B> class VRunTimeType_ : public VRunTimeType {
    //  Construction
    public:
	VRunTimeType_() : VRunTimeType (typeid (T), &T::MetaMaker, VRunTimeTypeTraits_<B>::rtt ()) {
	}
    };
}
using V::VRunTimeType;

#endif


text:
package apple.corebluetooth.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

/**
 * [@enum] CBConnectionEvent
 *

 * Represents the connection state of a peer.
 *

 * [@constant] CBConnectionEventPeerDisconnected Peer is disconnected.
 * [@constant] CBConnectionEventPeerConnected Peer is connected.
 */
@Generated
public final class CBConnectionEvent {
    @Generated
    private CBConnectionEvent() {
    }

    @Generated @NInt public static final long Disconnected = 0x0000000000000000L;
    @Generated @NInt public static final long Connected = 0x0000000000000001L;
}


text:
#include "s2n_test.h"

#include "testlib/s2n_testlib.h"

#include <sys/wait.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>

#include <s2n.h>

#include "tls/s2n_connection.h"
#include "tls/s2n_handshake.h"

int mock_nanoseconds_since_epoch(void *data, uint64_t *nanoseconds)
{
    static int called = 0;

    /* When first called return 0 seconds */
    *nanoseconds = 0;

    /* When next called return 31 seconds */
    if (called) {
        *nanoseconds += (uint64_t) 31 * 1000000000;
    }

    called = 1;

    return 0;
}

int mock_client(int writefd, int readfd, const char **protocols, int count, const char *expected)
{
    char buffer[0xffff];
    struct s2n_connection *client_conn;
    struct s2n_config *client_config;
    s2n_blocked_status blocked;
    int result = 0;

    /* Give the server a chance to listen */
    sleep(1);

    client_conn = s2n_connection_new(S2N_CLIENT);
    client_config = s2n_config_new();
    s2n_config_set_verify_cert_chain_cb(client_config, accept_all_rsa_certs, NULL);
    s2n_config_set_protocol_preferences(client_config, protocols, count);
    s2n_connection_set_config(client_conn, client_config);
    client_conn->server_protocol_version = S2N_TLS12;
    client_conn->client_protocol_version = S2N_TLS12;
    client_conn->actual_protocol_version = S2N_TLS12;

    s2n_connection_set_read_fd(client_conn, readfd);
    s2n_connection_set_write_fd(client_conn, writefd);

    result = s2n_negotiate(client_conn, &blocked);
    if (result < 0) {
        result = 1;
    }

    const char *got = s2n_get_application_protocol(client_conn);
    if ((got != NULL && expected == NULL) ||
        (got == NULL && expected != NULL) ||
        (got != NULL && expected != NULL && strcmp(expected, got) != 0)) {
        result = 2;
    }

    for (int i = 1; i < 0xffff; i += 100) {
        for (int j = 0; j < i; j++) {
            buffer[j] = 33;
        }

        s2n_send(client_conn, buffer, i, &blocked);
    }

    int shutdown_rc= -1;
    do {
        shutdown_rc = s2n_shutdown(client_conn, &blocked);
    } while(shutdown_rc != 0);

    s2n_connection_free(client_conn);

    /* Give the server a chance to a void a sigpipe */
    sleep(1);

    _exit(result);
}

int main(int argc, char **argv)
{
    char buffer[0xffff];
    struct s2n_connection *conn;
    struct s2n_config *config;
    s2n_blocked_status blocked;
    int status;
    pid_t pid;
    int server_to_client[2];
    int client_to_server[2];
    char *cert_chain_pem;
    char *private_key_pem;
    char *dhparams_pem;

    const char *protocols[] = { "http/1.1", "spdy/3.1" };
    const char *mismatch_protocols[] = { "spdy/2" };

    BEGIN_TEST();

    EXPECT_SUCCESS(setenv("S2N_ENABLE_CLIENT_MODE", "1", 0));
    EXPECT_NOT_NULL(cert_chain_pem = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(private_key_pem = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(dhparams_pem = malloc(S2N_MAX_TEST_PEM_SIZE));
    EXPECT_NOT_NULL(config = s2n_config_new());

    EXPECT_SUCCESS(s2n_read_test_pem(S2N_DEFAULT_TEST_CERT_CHAIN, cert_chain_pem, S2N_MAX_TEST_PEM_SIZE));
    EXPECT_SUCCESS(s2n_read_test_pem(S2N_DEFAULT_TEST_PRIVATE_KEY, private_key_pem, S2N_MAX_TEST_PEM_SIZE));
    EXPECT_SUCCESS(s2n_read_test_pem(S2N_DEFAULT_TEST_DHPARAMS, dhparams_pem, S2N_MAX_TEST_PEM_SIZE));

    EXPECT_SUCCESS(s2n_config_set_protocol_preferences(config, protocols, 2));
    EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key(config, cert_chain_pem, private_key_pem));
    EXPECT_SUCCESS(s2n_config_add_dhparams(config, dhparams_pem));

    /** Test no client ALPN request */
    /* Create a pipe */
    EXPECT_SUCCESS(pipe(server_to_client));
    EXPECT_SUCCESS(pipe(client_to_server));

    /* Create a child process */
    pid = fork();
    if (pid == 0) {
        /* This is the child process, close the read end of the pipe */
        EXPECT_SUCCESS(close(client_to_server[0]));
        EXPECT_SUCCESS(close(server_to_client[1]));

        /* Send the client hello with no ALPN extensions, and validate we didn't
         * negotiate an application protocol */
        mock_client(client_to_server[1], server_to_client[0], NULL, 0, NULL);
    }

    /* This is the parent */
    EXPECT_SUCCESS(close(client_to_server[1]));
    EXPECT_SUCCESS(close(server_to_client[0]));

    EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
    conn->server_protocol_version = S2N_TLS12;
    conn->client_protocol_version = S2N_TLS12;
    conn->actual_protocol_version = S2N_TLS12;

    EXPECT_SUCCESS(s2n_connection_set_config(conn, config));

    /* Set up the connection to read from the fd */
    EXPECT_SUCCESS(s2n_connection_set_read_fd(conn, client_to_server[0]));
    EXPECT_SUCCESS(s2n_connection_set_write_fd(conn, server_to_client[1]));

    /* Negotiate the handshake. */
    EXPECT_SUCCESS(s2n_negotiate(conn, &blocked));

    /* Expect NULL negotiated protocol */
    EXPECT_EQUAL(s2n_get_application_protocol(conn), NULL);

    for (int i = 1; i < 0xffff; i += 100) {
        char * ptr = buffer;
        int size = i;

        do {
            int bytes_read = 0;
            EXPECT_SUCCESS(bytes_read = s2n_recv(conn, ptr, size, &blocked));

            size -= bytes_read;
            ptr += bytes_read;
        } while(size);

        for (int j = 0; j < i; j++) {
            EXPECT_EQUAL(buffer[j], 33);
        }
    }

    EXPECT_SUCCESS(s2n_shutdown(conn, &blocked));
    EXPECT_SUCCESS(s2n_connection_free(conn));

    /* Clean up */
    EXPECT_EQUAL(waitpid(-1, &status, 0), pid);
    EXPECT_EQUAL(status, 0);

    /* Test a matching ALPN request */
    /* Create a pipe */
    EXPECT_SUCCESS(pipe(server_to_client));
    EXPECT_SUCCESS(pipe(client_to_server));

    /* Create a child process */
    pid = fork();
    if (pid == 0) {
        /* This is the child process, close the read end of the pipe */
        EXPECT_SUCCESS(close(client_to_server[0]));
        EXPECT_SUCCESS(close(server_to_client[1]));

        /* Clients ALPN preferences match our preferences, so we pick the
         * most preferred server one */
        mock_client(client_to_server[1], server_to_client[0], protocols, 2, protocols[0]);
    }

    /* This is the parent */
    EXPECT_SUCCESS(close(client_to_server[1]));
    EXPECT_SUCCESS(close(server_to_client[0]));

    EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
    conn->server_protocol_version = S2N_TLS12;
    conn->client_protocol_version = S2N_TLS12;
    conn->actual_protocol_version = S2N_TLS12;
    EXPECT_SUCCESS(s2n_connection_set_config(conn, config));

    /* Set up the connection to read from the fd */
    EXPECT_SUCCESS(s2n_connection_set_read_fd(conn, client_to_server[0]));
    EXPECT_SUCCESS(s2n_connection_set_write_fd(conn, server_to_client[1]));

    /* Negotiate the handshake. */
    EXPECT_SUCCESS(s2n_negotiate(conn, &blocked));

    /* Expect our most preferred negotiated protocol */
    EXPECT_STRING_EQUAL(s2n_get_application_protocol(conn), protocols[0]);

    for (int i = 1; i < 0xffff; i += 100) {
        char * ptr = buffer;
        int size = i;

        do {
            int bytes_read = 0;
            EXPECT_SUCCESS(bytes_read = s2n_recv(conn, ptr, size, &blocked));

            size -= bytes_read;
            ptr += bytes_read;
        } while(size);

        for (int j = 0; j < i; j++) {
            EXPECT_EQUAL(buffer[j], 33);
        }
    }

    EXPECT_SUCCESS(s2n_shutdown(conn, &blocked));
    EXPECT_SUCCESS(s2n_connection_free(conn));

    /* Clean up */
    EXPECT_EQUAL(waitpid(-1, &status, 0), pid);
    EXPECT_EQUAL(status, 0);

    /* Test a lower preferred matching ALPN request */
    /* Create a pipe */
    EXPECT_SUCCESS(pipe(server_to_client));
    EXPECT_SUCCESS(pipe(client_to_server));

    /* Create a child process */
    pid = fork();
    if (pid == 0) {
        /* This is the child process, close the read end of the pipe */
        EXPECT_SUCCESS(close(client_to_server[0]));
        EXPECT_SUCCESS(close(server_to_client[1]));

        /* Client only advertises our second choice, so we should negotiate it */
        mock_client(client_to_server[1], server_to_client[0], &protocols[1], 1, protocols[1]);
    }

    /* This is the parent */
    EXPECT_SUCCESS(close(client_to_server[1]));
    EXPECT_SUCCESS(close(server_to_client[0]));

    EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
    conn->server_protocol_version = S2N_TLS12;
    conn->client_protocol_version = S2N_TLS12;
    conn->actual_protocol_version = S2N_TLS12;
    EXPECT_SUCCESS(s2n_connection_set_config(conn, config));

    /* Set up the connection to read from the fd */
    EXPECT_SUCCESS(s2n_connection_set_read_fd(conn, client_to_server[0]));
    EXPECT_SUCCESS(s2n_connection_set_write_fd(conn, server_to_client[1]));

    /* Negotiate the handshake. */

    EXPECT_SUCCESS(s2n_negotiate(conn, &blocked));

    for (int i = 1; i < 0xffff; i += 100) {
        char * ptr = buffer;
        int size = i;

        do {
            int bytes_read = 0;
            EXPECT_SUCCESS(bytes_read = s2n_recv(conn, ptr, size, &blocked));

            size -= bytes_read;
            ptr += bytes_read;
        } while(size);

        for (int j = 0; j < i; j++) {
            EXPECT_EQUAL(buffer[j], 33);
        }
    }

    /* Expect our least preferred negotiated protocol */
    EXPECT_STRING_EQUAL(s2n_get_application_protocol(conn), protocols[1]);

    EXPECT_SUCCESS(s2n_shutdown(conn, &blocked));
    EXPECT_SUCCESS(s2n_connection_free(conn));

    /* Clean up */
    EXPECT_EQUAL(waitpid(-1, &status, 0), pid);
    EXPECT_EQUAL(status, 0);

    /* Test a non-matching ALPN request */
    /* Create a pipe */
    EXPECT_SUCCESS(pipe(server_to_client));
    EXPECT_SUCCESS(pipe(client_to_server));
    for (int i = 0; i < 2; i++) {
        EXPECT_NOT_EQUAL(fcntl(server_to_client[i], F_SETFL, fcntl(server_to_client[i], F_GETFL) | O_NONBLOCK), -1);
        EXPECT_NOT_EQUAL(fcntl(client_to_server[i], F_SETFL, fcntl(client_to_server[i], F_GETFL) | O_NONBLOCK), -1);
    }

    /* Create a child process */
    pid = fork();
    if (pid == 0) {
        /* This is the child process, close the read end of the pipe */
        EXPECT_SUCCESS(close(client_to_server[0]));
        EXPECT_SUCCESS(close(server_to_client[1]));

        /* Client doesn't support any of our protocols, so we shouldn't complete
         * the handshake */
        mock_client(client_to_server[1], server_to_client[0], mismatch_protocols, 1, NULL);
    }

    /* This is the parent */
    EXPECT_SUCCESS(close(client_to_server[1]));
    EXPECT_SUCCESS(close(server_to_client[0]));

    EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
    conn->server_protocol_version = S2N_TLS12;
    conn->client_protocol_version = S2N_TLS12;
    conn->actual_protocol_version = S2N_TLS12;
    EXPECT_SUCCESS(s2n_connection_set_config(conn, config));

    /* Set up the connection to read from the fd */
    EXPECT_SUCCESS(s2n_connection_set_read_fd(conn, client_to_server[0]));
    EXPECT_SUCCESS(s2n_connection_set_write_fd(conn, server_to_client[1]));

    /* s2n_negotiate will fail, which ordinarily would delay with a sleep.
     * Remove the sleep and fake the delay with a mock time routine */
    EXPECT_SUCCESS(s2n_connection_set_blinding(conn, S2N_SELF_SERVICE_BLINDING));
    EXPECT_SUCCESS(s2n_config_set_nanoseconds_since_epoch_callback(config, mock_nanoseconds_since_epoch, NULL));

    /* Negotiate the handshake. */
    int negotiate_rc;
    do {
        negotiate_rc = s2n_negotiate(conn, &blocked);
    } while(errno == EAGAIN && blocked);
    EXPECT_TRUE(negotiate_rc == -1 && s2n_errno == S2N_ERR_NO_APPLICATION_PROTOCOL);

    /* Expect NULL negotiated protocol */
    EXPECT_EQUAL(s2n_get_application_protocol(conn), NULL);

    /* Negotiation failed. Free the connection without shutdown */
    EXPECT_SUCCESS(s2n_connection_free(conn));

    /* Close the pipes */
    EXPECT_SUCCESS(close(client_to_server[0]));
    EXPECT_SUCCESS(close(server_to_client[1]));

    /* Clean up */
    EXPECT_EQUAL(waitpid(-1, &status, 0), pid);
    EXPECT_NOT_EQUAL(status, 0);

    EXPECT_SUCCESS(s2n_config_free(config));
    free(cert_chain_pem);
    free(private_key_pem);
    free(dhparams_pem);
    END_TEST();

    return 0;
}


text:
package org.apache.ignite.ml.environment;

import java.io.Serializable;
import java.util.Random;
import org.apache.ignite.ml.environment.logging.MLLogger;
import org.apache.ignite.ml.environment.parallelism.ParallelismStrategy;
import org.apache.ignite.ml.math.functions.IgniteFunction;

import static org.apache.ignite.ml.math.functions.IgniteFunction.constant;

/**
 * Builder of learning environment.
 */
public interface LearningEnvironmentBuilder extends Serializable {
    /**
     * Builds {@link LearningEnvironment} for worker on given partition.
     *
     * @param part Partition.
     * @return {@link LearningEnvironment} for worker on given partition.
     */
    public LearningEnvironment buildForWorker(int part);

    /**
     * Builds learning environment for trainer.
     *
     * @return Learning environment for trainer.
     */
    public default LearningEnvironment buildForTrainer() {
        return buildForWorker(-1);
    }

    /**
     * Specifies dependency (partition -> Parallelism Strategy Type for LearningEnvironment).
     *
     * @param stgyType Function describing dependency (partition -> Parallelism Strategy Type).
     * @return This object.
     */
    public LearningEnvironmentBuilder withParallelismStrategyTypeDependency(
        IgniteFunction<Integer, ParallelismStrategy.Type> stgyType);

    /**
     * Specifies Parallelism Strategy Type for LearningEnvironment. Same strategy type will be used for all partitions.
     *
     * @param stgyType Parallelism Strategy Type.
     * @return This object.
     */
    public default LearningEnvironmentBuilder withParallelismStrategyType(ParallelismStrategy.Type stgyType) {
        return withParallelismStrategyTypeDependency(constant(stgyType));
    }

    /**
     * Specifies dependency (partition -> Parallelism Strategy for LearningEnvironment).
     *
     * @param stgy Function describing dependency (partition -> Parallelism Strategy).
     * @return This object.
     */
    public LearningEnvironmentBuilder withParallelismStrategyDependency(IgniteFunction<Integer, ParallelismStrategy> stgy);

    /**
     * Specifies Parallelism Strategy for LearningEnvironment. Same strategy type will be used for all partitions.
     *
     * @param stgy Parallelism Strategy.
     * @param <T> Parallelism strategy type.
     * @return This object.
     */
    public default <T extends ParallelismStrategy & Serializable> LearningEnvironmentBuilder withParallelismStrategy(T stgy) {
        return withParallelismStrategyDependency(constant(stgy));
    }

    /**
     * Specify dependency (partition -> logging factory).
     *
     * @param loggingFactory Function describing (partition -> logging factory).
     * @return This object.
     */
    public LearningEnvironmentBuilder withLoggingFactoryDependency(IgniteFunction<Integer, MLLogger.Factory> loggingFactory);

    /**
     * Specify logging factory.
     *
     * @param loggingFactory Logging factory.
     * @return This object.
     */
    public default <T extends MLLogger.Factory & Serializable> LearningEnvironmentBuilder withLoggingFactory(T loggingFactory) {
        return withLoggingFactoryDependency(constant(loggingFactory));
    }

    /**
     * Specify dependency (partition -> seed for random number generator). Same seed will be used for all partitions.
     *
     * @param seed Function describing dependency (partition -> seed for random number generator).
     * @return This object.
     */
    public LearningEnvironmentBuilder withRNGSeedDependency(IgniteFunction<Integer, Long> seed);

    /**
     * Specify seed for random number generator.
     *
     * @param seed Seed for random number generator.
     * @return This object.
     */
    public default LearningEnvironmentBuilder withRNGSeed(long seed) {
        return withRNGSeedDependency(constant(seed));
    }

    /**
     * Specify dependency (partition -> random numbers generator).
     *
     * @param rngSupplier Function describing dependency (partition -> random numbers generator).
     * @return This object.
     */
    public LearningEnvironmentBuilder withRandomDependency(IgniteFunction<Integer, Random> rngSupplier);

    /**
     * Specify random numbers generator for learning environment. Same random will be used for all partitions.
     *
     * @param random Rrandom numbers generator for learning environment.
     * @return This object.
     */
    public default LearningEnvironmentBuilder withRandom(Random random) {
        return withRandomDependency(constant(random));
    }

    /**
     * Get default {@link LearningEnvironmentBuilder}.
     *
     * @return Default {@link LearningEnvironmentBuilder}.
     */
    public static LearningEnvironmentBuilder defaultBuilder() {
        return new DefaultLearningEnvironmentBuilder();
    }
}


text:
from .message import Message

@Message.register
class PeerUpNotification(Message):

    TYPE = Message.PEER_UP_NOTIFICATION
    TYPE_STR = 'peer-up-notification'

    @classmethod
    def unpack(cls, data):
        pass


text:
// ----- this file has been automatically generated - do not edit
import { UAGlassMaterialEvent, UAGlassMaterialEvent_Base } from "./ua_glass_material_event"
/**
 * |                |                                                  |
 * |----------------|--------------------------------------------------|
 * |namespace       |http://opcfoundation.org/UA/Glass/Flat/           |
 * |nodeClass       |ObjectType                                        |
 * |typedDefinition |13:MaterialReceivedEventType ns=13;i=1026         |
 * |isAbstract      |true                                              |
 */
export type UAMaterialReceivedEvent_Base = UAGlassMaterialEvent_Base;
export interface UAMaterialReceivedEvent extends UAGlassMaterialEvent, UAMaterialReceivedEvent_Base {
}


text:
title: Polygon labeling with polylabelr
categories:
  - R
tags:
  - euler diagrams
  - polygon
  - labeling
  - R
  - eulerr
  - polylabelr
  - geometry
excerpt: Using polylabelr to find visual centers of polygons and
  label Euler diagrams
---

## Labeling Euler diagram overlaps

The purpose of my R package [eulerr](https://github.com/jolars/eulerr)
is to fit and *visualize* Euler diagrams. Besides the various intricacies
involved in fitting the diagrams, there are many interesting
problems involved in their visualization. One of these is the labeling of the
overlaps.

Naturally, simply positioning the labels at the shapes' centers
fails more often than not. Nevertheless, this stategy is employed by
**venneuler**, for instance, and the plots usually demand
manual tuning.

```r
# an example set combination
s <- c("SE" = 13, "Treat" = 28, "Anti-CCP" = 101, "DAS28" = 91,
       "SE&Treat" = 1, "SE&DAS28" = 14, "Treat&Anti-CCP" = 6,
       "SE&Anti-CCP&DAS28" = 1)

library(venneuler, quietly = TRUE)
fit_venneuler <- venneuler(s)
plot(fit_venneuler)
```

A plot from venneuler with suboptimal label placements.

Up til now, I solved this in **eulerr** by, for each overlap,
filling one of the involved shapes (circles or ellipses) with points
and then numerically optimizing the location of the point using a
Nelder--Mead optimizer. However, given that the solution to
finding the distance between a point and an ellipse---at least one that
is rotated---itself requires a numerical solution {% cite eberly2013 %}, this procedure
turned out to be quite inefficient.

## The promise of polygons

R has powerful functionality for plotting in general, but lacks
capabilities for drawing ellipses using curves. High-resolution
polygons are thankfully a readily available remedy for this and have
since several version back been used also in **eulerr**.

The upside of using polygons, however, are that they are usually
much easier, even if sometimes inefficient,
to work with. For instance, they make constructing separate shapes
for each overlap a breeze using the polyclip package {% cite johnson2018 %}.

And because basically all shapes in digital maps are polygons,
there happens to exist a multitude of other useful tools to deal with
a wide variety of tasks related to polygons. One of these turned out
to be precisely what I needed: polylabel {% cite mapbox2018a %} from the Mapbox suite.
Because the details of the library
[have already been explained elsewhere](https://blog.mapbox.com/a-new-algorithm-for-finding-a-visual-center-of-a-polygon-7c77e6492fbc)
I will spare you the details, but briefly put it uses quadtree
binning to divide the polygon into square bins, pruning away dead-ends.
It is inefficient and will, according to the authors, find
a point that is "guaranteed to be a global optimum within the given precision".

Because it appeared to be such a valuable tool for R users, I decided
to create a wrapper for the c++ header for polylabel and bundle it as a package for R users.

```r
# install.packages("polylabelr")
library(polylabelr)

# a concave polygon with a hole
x <- c(0, 6, 3, 9, 10, 12, 4, 0, NA, 2, 5, 3)
y <- c(0, 0, 1, 3, 1, 5, 3, 0, NA, 1, 2, 2)

# locate the pole of inaccessibility
p <- poi(x, y, precision = 0.01)

plot.new()
plot.window(range(x, na.rm = TRUE), range(y, na.rm = TRUE), asp = 1)
polypath(x, y, col = "grey90", rule = "evenodd")
points(p, cex = 2, pch = 16)
```

Locating poles of inaccessibility with polylabel.

The package [is availabe on cran](https://CRAN.R-project.org/package=polylabelr),
the source code is located at <https://github.com/jolars/polylabelr> and
is documented at <https://jolars.github.io/polylabelr/>.

## Euler diagrams

To come back around to where we started at, **polylabelr** has now been
employed in the development branch
of **eulerr** where it is used to quickly and appropriately
figure out locations for the labels of the diagram.

```r
library(eulerr)

plot(euler(s))
```

An Euler diagram with appropriate label placement.

## References


text:
This is our small and short, ground-breaking todo list for the application.

Embed a (reactified) ready-to-use editor into contentEditable section. We need that one since we should represent a content of the selected file content formatted.

Integrate a tree component for left section of the app. It would be nice to have this feature for a better user/developer experience.

Add file interactions like saving and etc.

Create npm package of the app to be used as a global application. We need the app to run like the following:

```javascript
npm i ziya -g
```


text:
using Machine.Specifications;
using MarRoverChallenge.Implementation.Movers;
using MarRoverChallenge.Implementation.Positions;

namespace MarRoverChallenge.Tests
{
	public class given_rover_facing_north_at_location_2_2_when_moving_forward_by_one : RoverTestsBase
	{
		Establish context = () =>
		{
			Create100x100Grid_And_PlaceRoverFacingNorthAt(2,2);
		};

		Because of = () =>
		{
			var commands = new[]
			{
				NavigationCommand.Forward
			};
			Rover.Move(commands);
		};

		It should_be_at_position_2_3 = () =>
		{
			Rover.RoverPosition().ShouldEqual(Position.SepecificCoord(2,3));
		};
	}
}


text:
(function(angular) {
    'use strict';
    var devise = angular.module('Devise', []);

    devise.provider('AuthIntercept', function AuthInterceptProvider() {
    /**
     * Set to true to intercept 401 Unauthorized responses
     */
    var interceptAuth = false;

    // The interceptAuth config function
    this.interceptAuth = function(value) {
        interceptAuth = !!value || value === void 0;
        return this;
    };

    this.$get = ['$rootScope', '$q', function($rootScope, $q) {
        // Only for intercepting 401 requests.
        return {
            responseError: function(response) {
                // Determine if the response is specifically disabling the interceptor.
                var intercept = response.config.interceptAuth;
                intercept = !!intercept || (interceptAuth && intercept === void 0);

                if (intercept && response.status === 401) {
                    var deferred = $q.defer();
                    $rootScope.$broadcast('devise:unauthorized', response, deferred);
                    deferred.reject(response);
                    return deferred.promise;
                }

                return $q.reject(response);
            }
        };
    }];
}).config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('AuthIntercept');
}]);

    devise.provider('Auth', function AuthProvider() {
    /**
     * The default paths.
     */
    var paths = {
        login: '/users/sign_in.json',
        logout: '/users/sign_out.json',
        register: '/users.json',
        sendResetPasswordInstructions: '/users/password.json',
        resetPassword: '/users/password.json'
    };

    /**
     * The default HTTP methods to use.
     */
    var methods = {
        login: 'POST',
        logout: 'DELETE',
        register: 'POST',
        sendResetPasswordInstructions: 'POST',
        resetPassword: 'PUT'
    };

    /**
     * Default devise resource_name is 'user', can be set to any string.
     * If it's falsey, it will not namespace the data.
     */
    var resourceName = 'user';

    /**
     * The parsing function used to turn a $http
     * response into a "user".
     *
     * Can be swapped with another parsing function
     * using
     *
     *  angular.module('myModule', ['Devise']).
     *  config(function(AuthProvider) {
     *      AuthProvider.parse(function(response) {
     *          return new User(response.data);
     *      });
     *  });
     */
    var _parse = function(response) {
        return response.data;
    };

    // A helper function that will setup the ajax config
    // and merge the data key if provided
    function httpConfig(action, data, additionalConfig) {
        var config = {
            method: methods[action].toLowerCase(),
            url: paths[action]
        };

        if (data) {
            if (resourceName) {
                config.data = {};
                config.data[resourceName] = data;
            } else {
                config.data = data;
            }
        }

        angular.extend(config, additionalConfig);
        return config;
    }

    // A helper function to define our configure functions.
    // Loops over all properties in obj, and creates a get/set
    // method for [key + suffix] to set that property on obj.
    function configure(obj, suffix) {
        angular.forEach(obj, function(v, action) {
            this[action + suffix] = function(param) {
                if (param === undefined) {
                    return obj[action];
                }
                obj[action] = param;
                return this;
            };
        }, this);
    }
    configure.call(this, methods, 'Method');
    configure.call(this, paths, 'Path');

    // The resourceName config function
    this.resourceName = function(value) {
        if (value === undefined) {
            return resourceName;
        }
        resourceName = value;
        return this;
    };

    // The parse configure function.
    this.parse = function(fn) {
        if (typeof fn !== 'function') {
            return _parse;
        }
        _parse = fn;
        return this;
    };

    // Creates a function that always
    // returns a given arg.
    function constant(arg) {
        return function() {
            return arg;
        };
    }

    this.$get = ['$q', '$http', '$rootScope', function($q, $http, $rootScope) {
        // Our shared save function, called
        // by `then`s.
        function save(user) {
            service._currentUser = user;
            return user;
        }
        // A reset that saves null for currentUser
        function reset() {
            save(null);
            service._promise = null;
        }

        function broadcast(name) {
            return function(data) {
                $rootScope.$broadcast('devise:' + name, data);
                return data;
            };
        }

        var service = {
            /**
             * The Auth service's current user.
             * This is shared between all instances of Auth
             * on the scope.
             */
            _currentUser: null,

            /**
             * The Auth service's parsing function.
             * Defaults to the parsing function set in the provider,
             * but may also be overwritten directly on the service.
             */
            parse: _parse,

            /**
             * The Auth service's current promise
             * This is shared between all instances of Auth
             * on the scope.
             */
            _promise: null,

            /* reset promise and current_user, after call this method all
             * xhr request will be reprocessed when they will be call
             */
            reset: function(){
                reset();
                service.currentUser();
            },

            /**
             * A login function to authenticate with the server.
             * Keep in mind, credentials are sent in plaintext;
             * use a SSL connection to secure them. By default,
             * `login` will POST to '/users/sign_in.json'.
             *
             * The path and HTTP method used to login are configurable
             * using
             *
             *  angular.module('myModule', ['Devise']).
             *  config(function(AuthProvider) {
             *      AuthProvider.loginPath('path/on/server.json');
             *      AuthProvider.loginMethod('GET');
             *  });
             *
             * @param {Object} [creds] A hash of user credentials.
             * @param {Object} [config] Optional, additional config which
             *                  will be added to http config for underlying
             *                  $http.
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            login: function(creds, config) {
                var withCredentials = arguments.length > 0,
                    loggedIn = service.isAuthenticated();

                creds = creds || {};
                return $http(httpConfig('login', creds, config))
                    .then(service.parse)
                    .then(save)
                    .then(function(user) {
                        if (withCredentials && !loggedIn) {
                            return broadcast('new-session')(user);
                        }
                        return user;
                    })
                    .then(broadcast('login'));
            },

            /**
             * A logout function to de-authenticate from the server.
             * By default, `logout` will DELETE to '/users/sign_out.json'.
             *
             * The path and HTTP method used to logout are configurable
             * using
             *
             *  angular.module('myModule', ['Devise']).
             *  config(function(AuthProvider) {
             *      AuthProvider.logoutPath('path/on/server.json');
             *      AuthProvider.logoutMethod('GET');
             *  });
             * @param {Object} [config] Optional, additional config which
             *                  will be added to http config for underlying
             *                  $http.
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            logout: function(config) {
                var returnOldUser = constant(service._currentUser);
                return $http(httpConfig('logout', undefined, config))
                    .then(reset)
                    .then(returnOldUser)
                    .then(broadcast('logout'));
            },

            /**
             * A register function to register and authenticate
             * with the server. Keep in mind, credentials are sent
             * in plaintext; use a SSL connection to secure them.
             * By default, `register` will POST to '/users.json'.
             *
             * The path and HTTP method used to login are configurable
             * using
             *
             *  angular.module('myModule', ['Devise']).
             *  config(function(AuthProvider) {
             *      AuthProvider.registerPath('path/on/server.json');
             *      AuthProvider.registerMethod('GET');
             *  });
             *
             * @param {Object} [creds] A hash of user credentials.
             * @param {Object} [config] Optional, additional config which
             *                  will be added to http config for underlying
             *                  $http.
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            register: function(creds, config) {
                creds = creds || {};
                return $http(httpConfig('register', creds, config))
                    .then(service.parse)
                    .then(save)
                    .then(broadcast('new-registration'));
            },

            /**
             * A function to send the reset password instructions to the
             * user email.
             * By default, `sendResetPasswordInstructions` will POST to '/users/password.json'.
             *
             * The path and HTTP method used to send instructions are configurable
             * using
             *
             *  angular.module('myModule', ['Devise']).
             *  config(function(AuthProvider) {
             *      AuthProvider.sendResetPasswordInstructionsPath('path/on/server.json');
             *      AuthProvider.sendResetPasswordInstructionsMethod('POST');
             *  });
             *
             * @param {Object} [creds] A hash containing user email.
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            sendResetPasswordInstructions: function(creds) {
                creds = creds || {};
                return $http(httpConfig('sendResetPasswordInstructions', creds))
                    .then(service.parse)
                    .then(broadcast('send-reset-password-instructions-successfully'));
            },

            /**
             * A reset function to reset user password.
             * By default, `resetPassword` will PUT to '/users/password.json'.
             *
             * The path and HTTP method used to reset password are configurable
             * using
             *
             *  angular.module('myModule', ['Devise']).
             *  config(function(AuthProvider) {
             *      AuthProvider.resetPasswordPath('path/on/server.json');
             *      AuthProvider.resetPasswordMethod('POST');
             *  });
             *
             * @param {Object} [creds] A hash containing password, password_confirmation and reset_password_token.
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            resetPassword: function(creds) {
                creds = creds || {};
                return $http(httpConfig('resetPassword', creds))
                    .then(service.parse)
                    .then(save)
                    .then(broadcast('reset-password-successfully'));
            },

            /**
             * A helper function that will return a promise with the currentUser.
             * Three different outcomes can happen:
             *  1. Auth has authenticated a user, and will resolve with it
             *  2. Auth has not authenticated a user but the server has an
             *      authenticated session, Auth will attempt to retrieve that
             *      session and resolve with its user.
             *  3. Neither Auth nor the server has an authenticated session,
             *      and will reject with an unauthenticated error.
             *
             * @returns {Promise} A $http promise that will be resolved or
             *                  rejected by the server.
             */
            currentUser: function() {
                if (service.isAuthenticated()) {
                    return $q.when(service._currentUser);
                }
                if(service._promise === null){
                    service._promise = service.login();
                }
                return service._promise;
            },

            /**
             * A helper function to determine if a currentUser is present.
             *
             * @returns Boolean
             */
            isAuthenticated: function(){
                return !!service._currentUser;
            }
        };

        return service;
    }];
});

})(angular);


text:
/*
 * (c)2017-2021, Flagship Biosciences, Inc., written by Cris Luengo.
 * (c)2022, Cris Luengo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "pydip.h"
#include "diplib/histogram.h"
#include "diplib/distribution.h"
#include "diplib/lookup_table.h"

namespace pybind11 {
namespace detail {

// Cast Python string to dip::Histogram::Configuration::Mode
template<>
class type_caster< dip::Histogram::Configuration::Mode > {
   public:
      using type = dip::Histogram::Configuration::Mode;
      bool load( handle src, bool ) {
         if( !src ) {
            return false;
         }
         if( PYBIND11_BYTES_CHECK( src.ptr() ) || PyUnicode_Check( src.ptr() )) {
            auto mode = src.cast< dip::String >();
            if( mode == "COMPUTE_BINSIZE" ) { value = dip::Histogram::Configuration::Mode::COMPUTE_BINSIZE; }
            else if( mode == "COMPUTE_BINS" ) { value = dip::Histogram::Configuration::Mode::COMPUTE_BINS; }
            else if( mode == "COMPUTE_LOWER" ) { value = dip::Histogram::Configuration::Mode::COMPUTE_LOWER; }
            else if( mode == "COMPUTE_UPPER" ) { value = dip::Histogram::Configuration::Mode::COMPUTE_UPPER; }
            else { return false; }
            return true;
         }
         return false;
      }
      static handle cast( dip::Histogram::Configuration::Mode const& src, return_value_policy, handle ) {
         switch( src ) {
            case dip::Histogram::Configuration::Mode::COMPUTE_BINSIZE:
               return py::cast( "COMPUTE_BINSIZE" ).release();
            case dip::Histogram::Configuration::Mode::COMPUTE_BINS:
               return py::cast( "COMPUTE_BINS" ).release();
            case dip::Histogram::Configuration::Mode::COMPUTE_LOWER:
               return py::cast( "COMPUTE_LOWER" ).release();
            case dip::Histogram::Configuration::Mode::COMPUTE_UPPER:
               return py::cast( "COMPUTE_UPPER" ).release();
         }
         return py::cast( "Unrecognized configuration mode!?" ).release();
      }
   PYBIND11_TYPE_CASTER( type, _( "Mode" ));
};

} // namespace detail
} // namespace pybind11

namespace {

char const* Format( bool v ) {
   return v ? "%" : "";
}

dip::String ConfigRepr( dip::Histogram::Configuration const& s ) {
   std::ostringstream os;
   os << "<Histogram.Configuration, ";
   switch( s.mode ) {
      case dip::Histogram::Configuration::Mode::COMPUTE_BINSIZE:
         os << '[' << s.lowerBound << Format(s.lowerIsPercentile)
            << ',' << s.upperBound << Format(s.upperIsPercentile)
            << "], " << s.nBins << " bins";
         break;
      case dip::Histogram::Configuration::Mode::COMPUTE_BINS:
         os << '[' << s.lowerBound << Format(s.lowerIsPercentile)
            << ',' << s.upperBound << Format(s.upperIsPercentile)
            << "], bin width " << s.binSize;
         break;
      case dip::Histogram::Configuration::Mode::COMPUTE_LOWER:
         os << "[?," << s.upperBound << Format(s.upperIsPercentile)
            << "], " << s.nBins << " bins of width " << s.binSize;
         break;
      case dip::Histogram::Configuration::Mode::COMPUTE_UPPER:
         os << '[' << s.lowerBound << Format(s.lowerIsPercentile)
            << ",?], " << s.nBins << " bins of width " << s.binSize;
         break;
   }
   os << '>';
   return os.str();
}

} // namespace

void init_histogram( py::module& m ) {

   // diplib/histogram.h
   auto hist = py::class_< dip::Histogram >( m, "Histogram", "Computes and holds histograms." );

   auto conf = py::class_< dip::Histogram::Configuration >( hist, "Configuration", "Configuration information for how the histogram is computed." );
   conf.def_readwrite( "lowerBound", &dip::Histogram::Configuration::lowerBound, "Lower bound for this dimension, corresponds to the lower bound of the first bin." );
   conf.def_readwrite( "upperBound", &dip::Histogram::Configuration::upperBound, "Upper bound for this dimension, corresponds to the upper bound of the last bin." );
   conf.def_readwrite( "nBins", &dip::Histogram::Configuration::nBins, "Number of bins for this dimension." );
   conf.def_readwrite( "binSize", &dip::Histogram::Configuration::binSize, "Size of each bin for this dimension." );
   conf.def_readwrite( "mode", &dip::Histogram::Configuration::mode, "The given value is ignored and replaced by the computed value." );
   conf.def_readwrite( "lowerIsPercentile", &dip::Histogram::Configuration::lowerIsPercentile, "If set, `lowerBound` is replaced by the given percentile pixel value." );
   conf.def_readwrite( "upperIsPercentile", &dip::Histogram::Configuration::upperIsPercentile, "If set, `upperBound` is replaced by the given percentile pixel value." );
   conf.def_readwrite( "excludeOutOfBoundValues", &dip::Histogram::Configuration::excludeOutOfBoundValues, "If set, pixels outside of the histogram bounds are not counted." );
   conf.def( py::init<>() );
   conf.def( py::init< dip::dfloat, dip::dfloat, dip::dfloat >(), "lowerBound"_a, "upperBound"_a, "binSize"_a );
   conf.def( py::init< dip::dfloat, dip::dfloat, dip::uint >(), "lowerBound"_a, "upperBound"_a, "nBins"_a = 256 );
   conf.def( py::init< dip::dfloat, dip::uint, dip::dfloat >(), "lowerBound"_a, "nBins"_a, "binSize"_a );
   conf.def( py::init< dip::DataType >(), "dataType"_a );
   conf.def( "__repr__", &ConfigRepr );

   hist.def( py::init< dip::Image const&, dip::Image const&, dip::Histogram::ConfigurationArray >(),
             "input"_a, "mask"_a = dip::Image{}, "configuration"_a = dip::Histogram::ConfigurationArray{} );
   hist.def( py::init( []( dip::Image const& input, dip::Image const& mask, dip::FloatArray const& bounds, dip::uint nBins, bool boundsArePercentile ) {
                DIP_THROW_IF( bounds.size() != 2, dip::E::ARRAY_PARAMETER_WRONG_LENGTH );
                dip::Histogram::Configuration config( bounds[ 0 ], bounds[ 1 ], nBins );
                if( boundsArePercentile ) {
                   config.lowerIsPercentile = config.upperIsPercentile = boundsArePercentile;
                }
                return dip::Histogram( input, mask, config );
             } ),
             "input"_a, "mask"_a = dip::Image{}, "bounds"_a = dip::FloatArray{ 0, 255 }, "nBins"_a = 256, "boundsArePercentile"_a = false );
   hist.def( py::init< dip::Image const&, dip::Image const&, dip::Image const&, dip::Histogram::ConfigurationArray >(),
             "input1"_a, "input2"_a, "mask"_a = dip::Image{}, "configuration"_a = dip::Histogram::ConfigurationArray{} );
   hist.def( py::init( []( dip::Image const& input1, dip::Image const& input2, dip::Image const& mask,
                           dip::FloatArray const& bounds1, dip::FloatArray const& bounds2, dip::uint nBins1, dip::uint nBins2, bool boundsArePercentile ) {
                DIP_THROW_IF( bounds1.size() != 2, dip::E::ARRAY_PARAMETER_WRONG_LENGTH );
                DIP_THROW_IF( bounds2.size() != 2, dip::E::ARRAY_PARAMETER_WRONG_LENGTH );
                dip::Histogram::ConfigurationArray config{{ bounds1[ 0 ], bounds1[ 1 ], nBins1 },
                                                          { bounds2[ 0 ], bounds2[ 1 ], nBins2 }};
                if( boundsArePercentile ) {
                   config[0].lowerIsPercentile = config[0].upperIsPercentile = boundsArePercentile;
                   config[1].lowerIsPercentile = config[1].upperIsPercentile = boundsArePercentile;
                }
                return dip::Histogram( input1, input2, mask, config );
             } ),
             "input1"_a, "input2"_a, "mask"_a = dip::Image{}, "bounds1"_a = dip::FloatArray{ 0, 255 }, "bounds2"_a = dip::FloatArray{ 0, 100 },
             "nBins1"_a = 256, "nBins2"_a = 256, "boundsArePercentile"_a = false );
   hist.def( py::init< dip::Histogram::ConfigurationArray >(), "configuration"_a );
   hist.def( "__repr__", []( dip::Histogram const& self ) {
                if( !self.IsInitialized() ) {
                   return std::string{ "<Uninitialized histogram>" };
                }
                std::ostringstream os;
                os << "<Histogram, sizes " << self.GetImage().Sizes() << '>';
                return os.str();
             } );
   hist.def( "__str__", []( dip::Histogram const& self ) { std::ostringstream os; os << self; return os.str(); } );
   hist.def( "IsInitialized", &dip::Histogram::IsInitialized );
   hist.def( "Copy", &dip::Histogram::Copy );
   hist.def( "ReverseLookup", py::overload_cast< dip::Image const&, dip::BooleanArray const& >( &dip::Histogram::ReverseLookup ),
             "input"_a, "excludeOutOfBoundValues"_a = dip::BooleanArray{ false } );
   hist.def( py::self += py::self );
   hist.def( py::self + py::self );
   hist.def( py::self -= py::self );
   hist.def( py::self - py::self );
   hist.def( "Dimensionality", &dip::Histogram::Dimensionality );
   hist.def( "Bins", &dip::Histogram::Bins, "dim"_a = 0 );
   hist.def( "BinSize", &dip::Histogram::BinSize, "dim"_a = 0 );
   hist.def( "LowerBound", &dip::Histogram::LowerBound, "dim"_a = 0 );
   hist.def( "UpperBound", &dip::Histogram::UpperBound, "dim"_a = 0 );
   hist.def( "BinBoundaries", &dip::Histogram::BinBoundaries, "dim"_a = 0 );
   hist.def( "BinCenters", &dip::Histogram::BinCenters, "dim"_a = 0 );
   hist.def( "BinCenter", &dip::Histogram::BinCenter, "bin"_a, "dim"_a = 0 );
   hist.def( "Bin", py::overload_cast< dip::dfloat >( &dip::Histogram::Bin, py::const_ ), "value"_a );
   hist.def( "Bin", py::overload_cast< dip::dfloat, dip::dfloat >( &dip::Histogram::Bin, py::const_ ), "x_value"_a, "y_value"_a );
   hist.def( "Bin", py::overload_cast< dip::dfloat, dip::dfloat, dip::dfloat >( &dip::Histogram::Bin, py::const_ ), "x_value"_a, "y_value"_a, "z_value"_a );
   hist.def( "Bin", py::overload_cast< dip::FloatArray const& >( &dip::Histogram::Bin, py::const_ ), "value"_a );
   hist.def( "__getitem__", []( dip::Histogram const& self, dip::uint x ) -> dip::Histogram::CountType { return self.At( x ); } );
   hist.def( "__getitem__", []( dip::Histogram const& self, dip::uint x, dip::uint y ) -> dip::Histogram::CountType { return self.At( x, y ); } );
   hist.def( "__getitem__", []( dip::Histogram const& self, dip::uint x, dip::uint y, dip::uint z ) -> dip::Histogram::CountType { return self.At( x, y, z ); } );
   hist.def( "__getitem__", []( dip::Histogram const& self, dip::UnsignedArray const& bin ) -> dip::Histogram::CountType { return self.At( bin ); } );
   hist.def( "GetImage", &dip::Histogram::GetImage );
   hist.def( "Count", &dip::Histogram::Count );
   hist.def( "Cumulative", &dip::Histogram::Cumulative );
   hist.def( "GetMarginal", &dip::Histogram::GetMarginal, "dim"_a );
   hist.def( "Smooth", py::overload_cast< dip::FloatArray >( &dip::Histogram::Smooth ), "sigma"_a = dip::FloatArray{ 1 });

   m.def( "CumulativeHistogram", &dip::CumulativeHistogram, "in"_a );
   m.def( "Smooth", py::overload_cast< dip::Histogram const&, dip::FloatArray const& >( &dip::Smooth ),
          "in"_a, "sigma"_a = dip::FloatArray{ 1 } );
   m.def( "Mean", py::overload_cast< dip::Histogram const& >( &dip::Mean ), "in"_a );
   m.def( "Covariance", py::overload_cast< dip::Histogram const& >( &dip::Covariance ), "in"_a );
   m.def( "MarginalPercentile", &dip::MarginalPercentile, "in"_a, "percentile"_a = 50 );
   m.def( "MarginalMedian", &dip::MarginalMedian, "in"_a );
   m.def( "Mode", py::overload_cast< dip::Histogram const& >( &dip::Mode ), "in"_a );
   m.def( "PearsonCorrelation", py::overload_cast< dip::Histogram const& >( &dip::PearsonCorrelation ), "in"_a );
   m.def( "Regression", py::overload_cast< dip::Histogram const& >( &dip::Regression ), "in"_a );
   m.def( "MutualInformation", py::overload_cast< dip::Histogram const& >( &dip::MutualInformation ), "in"_a );
   m.def( "Entropy", py::overload_cast< dip::Histogram const& >( &dip::Entropy ), "in"_a );

   m.def( "IsodataThreshold", py::overload_cast< dip::Histogram const&, dip::uint >( &dip::IsodataThreshold ),
          "in"_a, "nThresholds"_a = 1 );
   m.def( "OtsuThreshold", py::overload_cast< dip::Histogram const& >( &dip::OtsuThreshold ), "in"_a );
   m.def( "MinimumErrorThreshold", py::overload_cast< dip::Histogram const& >( &dip::MinimumErrorThreshold ), "in"_a );
   m.def( "GaussianMixtureModelThreshold", py::overload_cast< dip::Histogram const&, dip::uint >( &dip::GaussianMixtureModelThreshold ),
          "in"_a, "nThresholds"_a = 1 );
   m.def( "TriangleThreshold", py::overload_cast< dip::Histogram const&, dip::dfloat >( &dip::TriangleThreshold ), "in"_a, "sigma"_a = 4.0 );
   m.def( "BackgroundThreshold", py::overload_cast< dip::Histogram const&, dip::dfloat, dip::dfloat >( &dip::BackgroundThreshold ),
          "in"_a, "distance"_a = 2.0, "sigma"_a = 4.0 );
   m.def( "KMeansClustering", py::overload_cast< dip::Histogram const&, dip::uint >( &dip::KMeansClustering ),
          "in"_a, "nClusters"_a = 2 );
   m.def( "MinimumVariancePartitioning", py::overload_cast< dip::Histogram const&, dip::uint >( &dip::MinimumVariancePartitioning ),
          "in"_a, "nClusters"_a = 2 );
   m.def( "EqualizationLookupTable", &dip::EqualizationLookupTable, "in"_a );
   m.def( "MatchingLookupTable", &dip::MatchingLookupTable, "in"_a, "example"_a );

   m.def( "PerObjectHistogram", &dip::PerObjectHistogram, "grey"_a, "label"_a, "mask"_a = dip::Image{},
          "configuration"_a = dip::Histogram::Configuration{}, "mode"_a = dip::S::FRACTION, "background"_a = dip::S::EXCLUDE );

   auto regParams = py::class_< dip::RegressionParameters >( m, "RegressionParameters", "Regression parameters." );
   regParams.def( "__repr__", []( dip::RegressionParameters const& s ) {
                     std::ostringstream os;
                     os << "<RegressionParameters: intercept=" << s.intercept << ", slope=" << s.slope << '>';
                     return os.str();
                  } );
   regParams.def_readonly( "intercept", &dip::RegressionParameters::intercept );
   regParams.def_readonly( "slope", &dip::RegressionParameters::slope );

   // These next two functions are the old implementation of `dip.Histogram`, which we keep
   // here for backwards compatibility. Setting `dip.Histogram = dip.Histogram_old` in Python
   // will allow old programs that use these functions to continue working.
   m.def( "Histogram_old", []( dip::Image const& input, dip::Image const& mask, dip::uint nBins ) {
             dip::Histogram::Configuration config( input.DataType() );
             config.nBins = nBins;
             config.mode = dip::Histogram::Configuration::Mode::COMPUTE_BINSIZE;
             dip::Histogram histogram( input, mask, config );
             dip::Image im = histogram.GetImage();
             std::vector< dip::FloatArray > bins( histogram.Dimensionality() );
             for( dip::uint ii = 0; ii < bins.size(); ++ii ) {
                bins[ ii ] = histogram.BinCenters( ii );
             }
             return py::make_tuple( im, bins ).release();
          }, "input"_a, "mask"_a = dip::Image{}, "nBins"_a = 256,
          "This function exists for backwards compatibility. It takes an image `input`,\n"
          "and optional `mask`, and computes a histogram with `nBins` bins. The output is\n"
          "a tuple with an image containing the bins, and a list of lists containing the\n"
          "bin centers.\n\n"
          "Use `dip.Histogram = dip.Histogram_old` to allow an older program to run\n"
          "without modification." );
   m.def( "Histogram_old", []( dip::Image const& input1, dip::Image const& input2, dip::Image const& mask ) {
             dip::Histogram histogram( input1, input2, mask );
             dip::Image im = histogram.GetImage();
             std::vector< dip::FloatArray > bins( 2 );
             bins[ 0 ] = histogram.BinCenters( 0 );
             bins[ 1 ] = histogram.BinCenters( 1 );
             return py::make_tuple( im, bins ).release();
          }, "input1"_a, "input2"_a, "mask"_a = dip::Image{},
          "Overload that takes two scalar images and outputs a 2D histogram." );

   // diplib/lookup_table.h
   auto lut = py::class_< dip::LookupTable >( m, "LookupTable", "Encapsulates the concept of the look-up table (LUT)." );
   lut.def( py::init< dip::Image, dip::FloatArray >(), "values"_a, "index"_a = dip::FloatArray{} );
   lut.def( "__repr__", []( dip::LookupTable const& self ) {
               std::ostringstream os;
               os << "<LookupTable, " << self.DataType();
               if( self.HasIndex() ) {
                  os << ", with index";
               }
               os << '>';
               return os.str();
            } );
   lut.def( "HasIndex", &dip::LookupTable::HasIndex );
   lut.def( "DataType", &dip::LookupTable::DataType );
   lut.def( "SetOutOfBoundsValue", py::overload_cast< dip::dfloat >( &dip::LookupTable::SetOutOfBoundsValue ), "value"_a );
   lut.def( "SetOutOfBoundsValue", py::overload_cast< dip::dfloat, dip::dfloat >( &dip::LookupTable::SetOutOfBoundsValue ), "lowerValue"_a, "upperValue"_a );
   lut.def( "KeepInputValueOnOutOfBounds", &dip::LookupTable::KeepInputValueOnOutOfBounds );
   lut.def( "ClampOutOfBoundsValues", &dip::LookupTable::ClampOutOfBoundsValues );
   lut.def( "Apply", py::overload_cast< dip::Image const&, dip::String const& >( &dip::LookupTable::Apply, py::const_ ), "in"_a, "interpolation"_a = dip::S::LINEAR );
   lut.def( "Apply", py::overload_cast< dip::dfloat, dip::String const& >( &dip::LookupTable::Apply, py::const_ ), "value"_a, "interpolation"_a = dip::S::LINEAR );
   lut.def( "Convert", &dip::LookupTable::Convert, "dataType"_a );

   // This next function is the old implementation of `dip.LookupTable`, which we keep
   // here for backwards compatibility. Setting `dip.LookupTable = dip.LookupTable_old` in Python
   // will allow old programs that use this function to continue working.
   m.def( "LookupTable_old", []( dip::Image const& in, dip::Image const& lut, dip::FloatArray const& index,
                                 dip::String const& interpolation, dip::String const& mode,
                                 dip::dfloat lowerValue, dip::dfloat upperValue ) {
             dip::LookupTable lookupTable( lut, index );
             if( mode == "clamp" ) {
                lookupTable.ClampOutOfBoundsValues(); // is the default...
             } else if( mode == "values" ) {
                lookupTable.SetOutOfBoundsValue( lowerValue, upperValue );
             } else if( mode == "keep" ) {
                lookupTable.KeepInputValueOnOutOfBounds();
             } else {
                DIP_THROW_INVALID_FLAG( mode );
             }
             return lookupTable.Apply( in, interpolation );
          }, "in"_a, "lut"_a, "index"_a = dip::FloatArray{}, "interpolation"_a = dip::S::LINEAR, "mode"_a = "clamp", "lowerValue"_a = 0.0, "upperValue"_a = 0.0,
          "This function exists for backwards compatibility. It takes an image `lut`, and\n"
          "optional `index`, that are converted to a `dip::LookupTable` object, parameters\n"
          "are set, and the lookup table is applied to `in`, returning the result.\n\n"
          "Use `dip.LookupTable = dip.LookupTable_old` to allow an older program to run\n"
          "without modification." );

}