text:
class BasicCategorySerializer < ApplicationSerializer

  attributes :id,
             :name,
             :color,
             :text_color,
             :slug,
             :topic_count,
             :post_count,
             :position,
             :description,
             :description_text,
             :topic_url,
             :read_restricted,
             :permission,
             :parent_category_id,
             :notification_level,
             :logo_url,
             :background_url,
             :can_edit,
             :topic_template,
             :has_children,
             :contains_messages

  def include_parent_category_id?
    parent_category_id
  end

  def description
    object.uncategorized? ? SiteSetting.uncategorized_description : object.description
  end

  def can_edit
    true
  end

  def include_can_edit?
    scope && scope.can_edit?(object)
  end

  def notification_level
    object.notification_level || CategoryUser.where(user: object.user, category: object).first.try(:notification_level)
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace MailLink
{
    public enum LogLevel { Fatal, Error, Warning, Informational, Verbose };
    public enum ServerType { SMTP, POP3, IMAP }

    [Serializable] [XmlRoot]
    public class Config
    {
        [XmlElement]
        public Setting Settings { get; set; }

        [XmlElement]
        public Default Defaults { get; set; }

        [XmlArrayItem(ElementName = "Server", Type = typeof(Server))]
        public List<Server> Servers { get; set; }

        //public Config Config { get; protected set; }

        public Config()
        {
            Defaults = new Default();
            Settings = new Setting();
            Servers = new List<Server>();

            //Initialize();
        }

        /// <summary>
        /// Creates a new config object populated with sample data.
        /// </summary>
        private void Create()
        {
            // Initialize Settings.
            Settings.TickInterval = 15; // Fifteen Seconds
            Settings.TockInterval = 60; // One Minute
            Settings.MaxMailboxThreads = 5;
            Settings.MaxQueueThreads = 2;

            // Initialize Defaults.
            Defaults.LogLevel = LogLevel.Verbose;
            Defaults.PollInterval = 60; // One Minute
            Defaults.Pop3Port = 110;
            Defaults.Pop3EncriptedPort = 995;
            Defaults.ImapPort = 143;
            Defaults.ImapEncriptedPort = 993;
            Defaults.SmtpPort = 25;
            Defaults.SmtpEncriptedPort = 587;
            Defaults.KeepMessages = true;
            Defaults.DaysToKeep = 14;

            Servers = new List<Server>()
            {
                new Server()
                {
                    Type = ServerType.SMTP,
                    Alias = "CSSOK",
                    Domain = "cssokc-ms1.coreslab.local",
                    Port = 25,
                    RequireSSL = false,
                    RequireAuth = false
                },
                new Server()
                {
                    Type = ServerType.POP3,
                    Alias = "Coreslab",
                    Domain = "mail.coreslab.com",
                    Port = 110,
                    RequireSSL = false,
                    RequireAuth = true
                },
                new Server()
                {
                    Type = ServerType.SMTP,
                    Alias = "TWFM",
                    Domain = "twfm.net.mail.eo.outlook.com",
                    Port = 25,
                    RequireSSL = false,
                    RequireAuth = false
                },
                new Server()
                {
                    Type = ServerType.POP3,
                    Alias = "TWFM",
                    Domain = "outlook.office365.com",
                    Port = 995,
                    RequireSSL = true,
                    RequireAuth = true
                },
                new Server()
                {
                    Type = ServerType.POP3,
                    Alias = "IT1",
                    Domain = "outlook.office365.com",
                    Port = 995,
                    RequireSSL = true,
                    RequireAuth = true
                }
            };
        }

        public void Serialize()
        {
            if (!Directory.Exists(@"c:\ProgramData\MailLink"))
            {
                Directory.CreateDirectory(@"c:\ProgramData\MailLink");
            }

            string configFile = @"c:\ProgramData\MailLink\config.xml";
            using (FileStream fs = new FileStream(configFile, FileMode.OpenOrCreate))
            {

                XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add("", "");
                XmlSerializer xml = new XmlSerializer(typeof(Config));

                xml.Serialize(fs, this, xmlns);
                fs.Close();
            }
        }

        public static Config Deserialize()
        {
            string configFile = @"c:\ProgramData\MailLink\config.xml";

            if (!File.Exists(configFile))
            {
                Config c = new Config();
                c.Create();
                c.Serialize();
                return c;
            }
            else
            {
                using (FileStream fs = new FileStream(configFile, FileMode.Open))
                {
                    XmlSerializer xml = new XmlSerializer(typeof(Config));

                    Config config = (Config)xml.Deserialize(fs);

                    fs.Close();
                    return config;
                }
            }
        }
    }

    public class Default
    {
        [XmlElement]
        public LogLevel LogLevel { get; set; }
        public int PollInterval { get; set; }
        public int Pop3Port { get; set; }
        public int Pop3EncriptedPort { get; set; }
        public int ImapPort { get; set; }
        public int ImapEncriptedPort { get; set; }
        public int SmtpPort { get; set; }
        public int SmtpEncriptedPort { get; set; }
        public bool KeepMessages { get; set; }
        public int DaysToKeep { get; set; }

        public Default()
        {

        }
    }

    public class Setting
    {
        [XmlElement]
        public int TickInterval { get; set; }
        public int TockInterval { get; set; }
        public int MaxMailboxThreads { get; set; }
        public int MaxQueueThreads { get; set; }

        public Setting()
        {

        }
    }

    public class Server
    {
        [XmlAttribute]
        public ServerType Type { get; set; }
        public string Alias { get; set; }

        [XmlElement]
        public string Domain { get; set; }
        public int Port { get; set; }
        public bool RequireSSL { get; set; }
        public bool RequireAuth { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        //TODO: Encript Password

        public Server()
        {
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
                   "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<!-- lifted from mdoc+troff by doclifter -->
<refentry id='skogpasswdmangui1'>
<!-- Copyright (c) 2013, Oskar Skog <oskar.skog.finland@gmail.com>
All rights reserved. -->

<!-- Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: -->

<!-- 1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. -->

<!-- 2.  Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution. -->

<!-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. -->

<refmeta>
<refentrytitle>PASSWDMANGUI</refentrytitle>
<manvolnum>1</manvolnum>
</refmeta>

<refnamediv id='purpose'>
<refname> skogpasswdmangui </refname>
<refpurpose> Graphical user interface for skogpasswdman </refpurpose>
</refnamediv>
<!-- body begins here -->

<refsect1 id='the_change_metadata_and_update_button'><title>The change meta-data and update button</title>
<itemizedlist remap='Bl -bullet' mark='bullet'>
<listitem>
<para>If the password was created with the
"Add existing"
button: use the
"change meta-data & update"
button.</para>
</listitem>
<listitem>
<para>If the password was created with the
"Create new"
button: use the
"update"
button.</para>
</listitem>
<listitem>
<para>If the minimal required length for the password or the maximal allowed length
or the allowable characters have changed: use the
"change meta-data & update"
button.</para>
</listitem>
</itemizedlist>
</refsect1>

<refsect1 id='difference_between_add_existing_and_crea'><title>Difference between Add existing and Create new</title>
<para>Click on those buttons and see what happens.
They are not dangerous.</para>
</refsect1>

<refsect1 id='undo_redo'><title>Undo Redo</title>
<para>The
"Undo"
and
"Redo"
buttons undoes/redoes the LATEST change in the password tab or the
fake-password tab, independent of which tab you're currently in.</para>
</refsect1>

<refsect1 id='fakepasswordshoney_pots'><title>fake-passwords/honey pots</title>
<para>The fake-passwords/honey pots are intended to be used as traps to catch
crackers.
The
"pick"
buttons picks a random fake-password, independent of what you have selected.
You should add fake-passwords such as
"password"
and
"drowssap".</para>
</refsect1>

<refsect1 id='author'><title>AUTHOR</title>
<para>Written by
Oskar Skog (oskar.skog.finland@gmail.com).</para>

<para>Please send patches, questions, bug reports and wish-lists.</para>
</refsect1>
</refentry>


text:
package net.ruippeixotog.scalascraper.browser

import java.io.File

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.Uri
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives.{post => httpPost, _}
import org.specs2.mutable.Specification

import net.ruippeixotog.scalascraper.SocksTestHelper
import net.ruippeixotog.scalascraper.model._

class BrowserSpec extends Specification with BrowserHelper with TestServer with SocksTestHelper {

  val html = """

        <title>Test Page</title>

        this is some text with many styles

            1

            2

            3

            4

            5

    """

  // format: OFF
  lazy val testService = {
    get {
      path("hello") { serveHtml(html) } ~
      path("encoding" / Segment) { charset =>
        respondWithHeader(`Content-Encoding`.parseFromValueString(charset).right.get) {
          serveResource(s"encoding-${charset.toLowerCase}.html", charset)
        }
      } ~
      path("agent") {
        headerValueByName("User-Agent") { userAgent =>
          serveText(userAgent)
        }
      } ~
      path("redirect") { redirect(Uri(testServerUri("redirected")) , Found) } ~
      path("redirected") { serveText("redirected") } ~
      path("setcookieA") {
        setCookie(HttpCookie("a", "4")) { serveText("cookie set") }
      } ~
      path("setcookieB") {
        setCookie(HttpCookie("b", "5")) { serveText("cookie set") }
      } ~
      path("cookies") {
        optionalHeaderValuePF({ case Cookie(cookies) => cookies }) { cookies =>
          val str = cookies.getOrElse(Nil).sortBy(_.name).map { c => s"${c.name}=${c.value}" }.mkString(";")
          serveText(str)
        }
      }
    } ~
    httpPost {
      path("form") {
        formFieldSeq { fields =>
          val dataHtml = fields.map { case (k, vs) => s"""$vs""" }.mkString
          serveText(dataHtml)
        }
      }
    }
  }
  // format: ON

  "A Browser" should {

    usingBrowsers(JsoupBrowser(), HtmlUnitBrowser()) { browser =>
      "do GET requests and parse correctly the returned HTML" in {
        val body = browser.get(testServerUri("hello")).body

        body.tagName mustEqual "body"
        body.children.size mustEqual 4

        val div = body.children.head
        div.tagName mustEqual "div"
        div.attr("id") mustEqual "a1"
        div.children.size mustEqual 2
      }

      "do GET requests and parse correctly the returned HTML with different charsets" in {
        val testPhrase = "El veloz murciélago hindú comía feliz cardillo y kiwi. " +
          "La cigüeña tocaba el saxofón detrás del palenque de paja."

        def getText(doc: Document) = doc.root.select("#a").head.text

        getText(browser.get(testServerUri("encoding/UTF-8"))) mustEqual testPhrase
        getText(browser.get(testServerUri("encoding/ISO-8859-1"))) mustEqual testPhrase
        getText(browser.get(testServerUri("encoding/UTF-16BE"))) mustEqual testPhrase
      }

      "do POST requests and parse correctly the returned HTML" in {
        val params = Map("a" -> "1", "b" -> "bbb", "c1" -> "data")
        val doc = browser.post(testServerUri("form"), params)

        doc.root.select("#a").head.text mustEqual "1"
        doc.root.select("#b").head.text mustEqual "bbb"
        doc.root.select("#c1").head.text mustEqual "data"
      }

      "parse correctly HTML from a string" in {
        val body = browser.parseString(html).body

        body.tagName mustEqual "body"
        body.children.size mustEqual 4

        val div = body.children.head
        div.tagName mustEqual "div"
        div.attr("id") mustEqual "a1"
        div.children.size mustEqual 2
      }

      "parse correctly HTML from a file" in {
        val file = new File(getClass.getResource("/test.html").toURI)
        val body = browser.parseFile(file).body

        body.tagName mustEqual "body"
        body.children.size mustEqual 1

        val div = body.children.head
        div.tagName mustEqual "div"
        div.attr("id") mustEqual "a1"
        div.children.size mustEqual 2
      }

      "parse correctly HTML from a resource" in {
        val body = browser.parseResource("/test.html").body

        body.tagName mustEqual "body"
        body.children.size mustEqual 1

        val div = body.children.head
        div.tagName mustEqual "div"
        div.attr("id") mustEqual "a1"
        div.children.size mustEqual 2
      }

      "parse correctly HTML from files with different charsets" in {
        val testPhrase = "El veloz murciélago hindú comía feliz cardillo y kiwi. " +
          "La cigüeña tocaba el saxofón detrás del palenque de paja."

        def getText(doc: Document) = doc.root.select("#a").head.text

        getText(browser.parseResource("/encoding-utf-8.html")) mustEqual testPhrase
        getText(browser.parseResource("/encoding-utf-8.html", "ISO-8859-1")) must not(beEqualTo(testPhrase))

        getText(browser.parseResource("/encoding-iso-8859-1.html")) must not(beEqualTo(testPhrase))
        getText(browser.parseResource("/encoding-iso-8859-1.html", "ISO-8859-1")) mustEqual testPhrase

        getText(browser.parseResource("/encoding-utf-16be.html")) must throwAn[
          Exception
        ] // file is not valid HTML in UTF-8
        getText(browser.parseResource("/encoding-utf-16be.html", "UTF-16BE")) mustEqual testPhrase
      }

      "do requests with the same user agent as returned by userAgent" in {
        val doc = browser.get(testServerUri("agent"))
        doc.body.text mustEqual browser.userAgent
      }

      "follow redirects" in {
        val doc = browser.get(testServerUri("redirect"))
        doc.location mustEqual testServerUri("redirected")
        doc.body.text mustEqual "redirected"
      }

      "keep and use cookies between requests" in {
        browser.cookies(testServerUri("")) mustEqual Map.empty

        browser.get(testServerUri("setcookieA"))
        val doc = browser.get(testServerUri("cookies"))
        doc.body.text mustEqual "a=4"

        browser.cookies(testServerUri("setcookieA")) mustEqual Map("a" -> "4")
        browser.cookies(testServerUri("")) mustEqual Map("a" -> "4")

        browser.get(testServerUri("setcookieB"))
        val doc2 = browser.get(testServerUri("cookies"))
        doc2.body.text mustEqual "a=4;b=5"

        browser.cookies(testServerUri("")) mustEqual Map("a" -> "4", "b" -> "5")

        browser.clearCookies()
        val doc3 = browser.get(testServerUri("cookies"))
        doc3.body.text mustEqual ""

        browser.cookies(testServerUri("")) mustEqual Map.empty
      }

      "return Document implementations" in {

        "with a correct location method" in {
          val doc = browser.get(testServerUri("hello"))

          doc.location mustEqual testServerUri("hello")
        }

        "with correct title, head and body methods" in {
          val doc = browser.get(testServerUri("hello"))

          doc.title mustEqual "Test Page"
          doc.head.attr("id") mustEqual "hid"
          doc.body.attr("id") mustEqual "bid"
        }

        "with a correct toHtml method" in {
          val doc = browser.get(testServerUri("hello"))
          val docStr = doc.toHtml

          browser.parseString(docStr).toHtml mustEqual docStr
        }
      }

      "return Element implementations" should {

        "with correct parent and children methods" in {
          val doc = browser.parseString(html)

          val body = doc.body
          body.parent must beSome[Element].which { p => p.tagName mustEqual "html" }
          body.children.map(_.tagName) mustEqual Iterable("div", "span", "span", "div")

          val table = doc.root.select("table").head
          table.parent must beSome[Element].which { p => p.attr("id") mustEqual "a1" }
          table.children must beEmpty
        }

        "with correct attr, hasAttr and attrs methods" in {
          val doc = browser.parseString(html)

          val body = doc.body
          body.attrs mustEqual Map("id" -> "bid", "data-a" -> "a", "data-b" -> "b")
          body.hasAttr("id") must beTrue
          body.attr("id") mustEqual "bid"
          body.hasAttr("data-b") must beTrue
          body.attr("data-b") mustEqual "b"
          body.hasAttr("data-c") must beFalse
          body.attr("data-c") must throwA[NoSuchElementException]
        }

        "with correct innerHtml and outerHtml methods" in {
          val doc = browser.parseString(html)

          val textNode = doc.root.select("#t").head
          textNode.innerHtml mustEqual "this is some text with many styles"
          textNode.outerHtml mustEqual "this is some text with many styles"
        }

        "with correct siblings methods" in {
          val doc = browser.parseString(html)

          val middleDiv = doc.root.select("#sibling3").head
          val Seq(sibling1, sibling2, sibling4, sibling5) = middleDiv.siblings.toList
          sibling1.attr("id") mustEqual "sibling1"
          sibling2.attr("id") mustEqual "sibling2"
          sibling4.attr("id") mustEqual "sibling4"
          sibling5.attr("id") mustEqual "sibling5"
        }

        "with correct childNodes and siblingNodes methods" in {
          val doc = browser.parseString(html)

          val textNode = doc.root.select("#t").head
          val Seq(b, i) = textNode.select("b, i").toSeq

          textNode.children mustEqual Seq(b, i)
          textNode.childNodes mustEqual Seq(
            TextNode("this is "),
            ElementNode(b),
            TextNode(" text with "),
            ElementNode(i),
            TextNode(" styles")
          )

          b.siblings mustEqual Seq(i)
          b.siblingNodes mustEqual Seq(
            TextNode("this is "),
            TextNode(" text with "),
            ElementNode(i),
            TextNode(" styles")
          )
        }
      }

      "make requests through a SOCKS server if configured" in skipIfProxyUnavailable {
        val proxy = Proxy(socksProxyHost, socksProxyPort, Proxy.SOCKS)
        val proxiedBrowser = browser.withProxy(proxy)

        val proxyIP = proxiedBrowser.get("http://ipv4.icanhazip.com").body.text
        val myIP = browser.get("http://ipv4.icanhazip.com").body.text
        proxyIP !=== myIP
      }
    }
  }
}


text:
#include "btTypedConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btSerializer.h"

#define DEFAULT_DEBUGDRAW_SIZE btScalar(0.05f)

btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA)
	: btTypedObject(type),
	  m_userConstraintType(-1),
	  m_userConstraintPtr((void*)-1),
	  m_breakingImpulseThreshold(SIMD_INFINITY),
	  m_isEnabled(true),
	  m_needsFeedback(false),
	  m_overrideNumSolverIterations(-1),
	  m_rbA(rbA),
	  m_rbB(getFixedBody()),
	  m_appliedImpulse(btScalar(0.)),
	  m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE),
	  m_jointFeedback(0)
{
}

btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA, btRigidBody& rbB)
	: btTypedObject(type),
	  m_userConstraintType(-1),
	  m_userConstraintPtr((void*)-1),
	  m_breakingImpulseThreshold(SIMD_INFINITY),
	  m_isEnabled(true),
	  m_needsFeedback(false),
	  m_overrideNumSolverIterations(-1),
	  m_rbA(rbA),
	  m_rbB(rbB),
	  m_appliedImpulse(btScalar(0.)),
	  m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE),
	  m_jointFeedback(0)
{
}

btScalar btTypedConstraint::getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact)
{
	if (lowLim > uppLim)
	{
		return btScalar(1.0f);
	}
	else if (lowLim == uppLim)
	{
		return btScalar(0.0f);
	}
	btScalar lim_fact = btScalar(1.0f);
	btScalar delta_max = vel / timeFact;
	if (delta_max < btScalar(0.0f))
	{
		if ((pos >= lowLim) && (pos < (lowLim - delta_max)))
		{
			lim_fact = (lowLim - pos) / delta_max;
		}
		else if (pos < lowLim)
		{
			lim_fact = btScalar(0.0f);
		}
		else
		{
			lim_fact = btScalar(1.0f);
		}
	}
	else if (delta_max > btScalar(0.0f))
	{
		if ((pos <= uppLim) && (pos > (uppLim - delta_max)))
		{
			lim_fact = (uppLim - pos) / delta_max;
		}
		else if (pos > uppLim)
		{
			lim_fact = btScalar(0.0f);
		}
		else
		{
			lim_fact = btScalar(1.0f);
		}
	}
	else
	{
		lim_fact = btScalar(0.0f);
	}
	return lim_fact;
}

///fills the dataBuffer and returns the struct name (and 0 on failure)
const char* btTypedConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
{
	btTypedConstraintData2* tcd = (btTypedConstraintData2*)dataBuffer;

	tcd->m_rbA = (btRigidBodyData*)serializer->getUniquePointer(&m_rbA);
	tcd->m_rbB = (btRigidBodyData*)serializer->getUniquePointer(&m_rbB);
	char* name = (char*)serializer->findNameForPointer(this);
	tcd->m_name = (char*)serializer->getUniquePointer(name);
	if (tcd->m_name)
	{
		serializer->serializeName(name);
	}

	tcd->m_objectType = m_objectType;
	tcd->m_needsFeedback = m_needsFeedback;
	tcd->m_overrideNumSolverIterations = m_overrideNumSolverIterations;
	tcd->m_breakingImpulseThreshold = m_breakingImpulseThreshold;
	tcd->m_isEnabled = m_isEnabled ? 1 : 0;

	tcd->m_userConstraintId = m_userConstraintId;
	tcd->m_userConstraintType = m_userConstraintType;

	tcd->m_appliedImpulse = m_appliedImpulse;
	tcd->m_dbgDrawSize = m_dbgDrawSize;

	tcd->m_disableCollisionsBetweenLinkedBodies = false;

	int i;
	for (i = 0; i < m_rbA.getNumConstraintRefs(); i++)
		if (m_rbA.getConstraintRef(i) == this)
			tcd->m_disableCollisionsBetweenLinkedBodies = true;
	for (i = 0; i < m_rbB.getNumConstraintRefs(); i++)
		if (m_rbB.getConstraintRef(i) == this)
			tcd->m_disableCollisionsBetweenLinkedBodies = true;

	return btTypedConstraintDataName;
}

btRigidBody& btTypedConstraint::getFixedBody()
{
	static btRigidBody s_fixed(0, 0, 0);
	s_fixed.setMassProps(btScalar(0.), btVector3(btScalar(0.), btScalar(0.), btScalar(0.)));
	return s_fixed;
}

void btAngularLimit::set(btScalar low, btScalar high, btScalar _softness, btScalar _biasFactor, btScalar _relaxationFactor)
{
	m_halfRange = (high - low) / 2.0f;
	m_center = btNormalizeAngle(low + m_halfRange);
	m_softness = _softness;
	m_biasFactor = _biasFactor;
	m_relaxationFactor = _relaxationFactor;
}

void btAngularLimit::test(const btScalar angle)
{
	m_correction = 0.0f;
	m_sign = 0.0f;
	m_solveLimit = false;

	if (m_halfRange >= 0.0f)
	{
		btScalar deviation = btNormalizeAngle(angle - m_center);
		if (deviation < -m_halfRange)
		{
			m_solveLimit = true;
			m_correction = -(deviation + m_halfRange);
			m_sign = +1.0f;
		}
		else if (deviation > m_halfRange)
		{
			m_solveLimit = true;
			m_correction = m_halfRange - deviation;
			m_sign = -1.0f;
		}
	}
}

btScalar btAngularLimit::getError() const
{
	return m_correction * m_sign;
}

void btAngularLimit::fit(btScalar& angle) const
{
	if (m_halfRange > 0.0f)
	{
		btScalar relativeAngle = btNormalizeAngle(angle - m_center);
		if (!btEqual(relativeAngle, m_halfRange))
		{
			if (relativeAngle > 0.0f)
			{
				angle = getHigh();
			}
			else
			{
				angle = getLow();
			}
		}
	}
}

btScalar btAngularLimit::getLow() const
{
	return btNormalizeAngle(m_center - m_halfRange);
}

btScalar btAngularLimit::getHigh() const
{
	return btNormalizeAngle(m_center + m_halfRange);
}


text:
/**
 * App ID for the skill
 */
var APP_ID = 'amzn1.echo-sdk-ams.app.3dde646d-d3b0-4f82-b459-d0d5f94e29ef';

/**
 * The AlexaSkill prototype and helper functions
 */
var AlexaSkill = require('./AlexaSkill');

var http = require('http');

/**
 * CanIGiveMyDog is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var CanIGiveMyDog = function () {
    AlexaSkill.call(this, APP_ID);
};

// Extend AlexaSkill
CanIGiveMyDog.prototype = Object.create(AlexaSkill.prototype);
CanIGiveMyDog.prototype.constructor = CanIGiveMyDog;

CanIGiveMyDog.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
    console.log("CanIGiveMyDog onSessionStarted requestId: " + sessionStartedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any initialization logic goes here
};

CanIGiveMyDog.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
    console.log("CanIGiveMyDog onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    var speechOutput = "What would you like to give your dog?";
    var repromptText = "You can say an apple";
    response.ask(speechOutput, repromptText);
};

CanIGiveMyDog.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {
    console.log("CanIGiveMyDog onSessionEnded requestId: " + sessionEndedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any cleanup logic goes here
};

CanIGiveMyDog.prototype.intentHandlers = {
    // register custom intent handlers
    "CanIGiveMyDogIntent": function (intent, session, response) {
      var food = intent.slots.Food.value.toLowerCase();

      console.log("The food was: ", food);

      http.get('http://canigivemydog-api.herokuapp.com?q=' + food, function(res) {
        var reply = '';

        res.on('data', function(data) {
          reply += data;
        })

        res.on('end', function() {
          console.log("The resp was: ", reply);
          var answer = JSON.parse(reply);

          response.tell(answer.error ? "Sorry, food not found. Try asking again a different way" : answer.question + answer.answer);
        });
      });

        // response.tellWithCard("Hello World!", "Greeter", "Hello World!");
    },
    "AMAZON.HelpIntent": function (intent, session, response) {
        response.ask("You can say an apple", "You can say an apple");
    }
};

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the CanIGiveMyDog skill.
    var canIGiveMyDog = new CanIGiveMyDog();
    canIGiveMyDog.execute(event, context);
};


text:
package io.apiman.plugins.transformation_policy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import io.apiman.plugins.transformation_policy.backend.ConsumeJsonBackEndApi;
import io.apiman.plugins.transformation_policy.backend.ConsumeXmlBackEndApi;
import io.apiman.plugins.transformation_policy.backend.ProduceComplexJsonBackEndApi;
import io.apiman.plugins.transformation_policy.backend.ProduceEchoXmlResponseBackend;
import io.apiman.plugins.transformation_policy.backend.ProduceJsonBackEndApi;
import io.apiman.plugins.transformation_policy.backend.ProduceXmlBackEndApi;
import io.apiman.test.policies.ApimanPolicyTest;
import io.apiman.test.policies.BackEndApi;
import io.apiman.test.policies.Configuration;
import io.apiman.test.policies.PolicyTestRequest;
import io.apiman.test.policies.PolicyTestRequestType;
import io.apiman.test.policies.PolicyTestResponse;
import io.apiman.test.policies.TestingPolicy;

import org.junit.Test;

@SuppressWarnings("nls")
@TestingPolicy(TransformationPolicy.class)
public class TransformationPolicyTest extends ApimanPolicyTest {

    @Test
    @Configuration("{\"clientFormat\": \"XML\", \"serverFormat\": \"JSON\"}")
    @BackEndApi(ProduceJsonBackEndApi.class)
    public void transformServerJsonResponseToXml() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        String expectedResponse = "<name>apiman</name>";
        assertEquals("application/xml", response.header("Content-Type"));
        assertNull(response.header("Content-Length"));
        assertEquals(expectedResponse, response.body());
    }

    @Test
    @Configuration("{\"clientFormat\": \"XML\", \"serverFormat\": \"JSON\"}")
    @BackEndApi(ConsumeJsonBackEndApi.class)
    public void transformClientXmlRequesttToJson() throws Throwable {
        String xml = "test";
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.POST, "/some/resource");
        request.header("Content-Type", "application/xml");
        request.header("Content-Length", String.valueOf(xml.getBytes("UTF-8").length));
        request.body(xml);

        send(request);
    }

    @Test
    @Configuration("{\"clientFormat\": \"JSON\", \"serverFormat\": \"XML\"}")
    @BackEndApi(ProduceXmlBackEndApi.class)
    public void transformServerXmlResponseToJson() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        String expectedResponse = "{\"name\":\"apiman\"}";
        assertEquals("application/json", response.header("Content-Type"));
        assertNull(response.header("Content-Length"));
        assertEquals(expectedResponse, response.body());
    }

    @Test
    @Configuration("{\"clientFormat\": \"JSON\", \"serverFormat\": \"XML\"}")
    @BackEndApi(ConsumeXmlBackEndApi.class)
    public void transformClientJsonRequestToXml() throws Throwable {
        String json = "{\"name\":\"apiman\"}";
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.POST, "/some/resource");
        request.header("Content-Type", "application/json");
        request.header("Content-Length", String.valueOf(json.getBytes("UTF-8").length));
        request.body(json);

        send(request);
    }

    @Test
    @Configuration("{\"clientFormat\": \"JSON\", \"serverFormat\": \"JSON\"}")
    @BackEndApi(ProduceJsonBackEndApi.class)
    public void keepServerJsonResponseAsJson() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        String expectedResponse = "{\"name\":\"apiman\"}";
        assertEquals("application/json", response.header("Content-Type"));
        assertEquals(String.valueOf(expectedResponse.getBytes("UTF-8").length), response.header("Content-Length"));
        assertEquals(expectedResponse, response.body());
    }

    @Test
    @Configuration("{\"clientFormat\": \"XML\", \"serverFormat\": \"XML\"}")
    @BackEndApi(ProduceXmlBackEndApi.class)
    public void keepServerXmlResponseAsXml() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        String expectedResponse = "<name>apiman</name>";
        assertEquals("application/xml", response.header("Content-Type"));
        assertEquals(String.valueOf(expectedResponse.getBytes("UTF-8").length), response.header("Content-Length"));
        assertEquals(expectedResponse, response.body());
    }

    @Test
    @Configuration("{\"clientFormat\": \"JSON\", \"serverFormat\": \"XML\"}")
    @BackEndApi(ProduceEchoXmlResponseBackend.class)
    public void transformServerEchoXmlResponseToJson() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        assertEquals("application/json", response.header("Content-Type"));
        assertNull(response.header("Content-Length"));
        assertTrue(response.body().startsWith("{\"echoResponse\":"));
    }

    @Test
    @Configuration("{\"clientFormat\": \"XML\", \"serverFormat\": \"JSON\"}")
    @BackEndApi(ProduceComplexJsonBackEndApi.class)
    public void transformComplexServerJsonResponseToXml() throws Throwable {
        PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, "/some/resource");

        PolicyTestResponse response = send(request);

        String expectedResponse = "<root><property-1>value-1</property-1><array-1>10</array-1><array-1>5</array-1><array-1>3</array-1><array-1>12</array-1><property-2>value-2</property-2><object-1><p1>v1</p1><p2>v2</p2></object-1></root>";
        assertEquals("application/xml", response.header("Content-Type"));
        assertNull(response.header("Content-Length"));
        assertEquals(expectedResponse, response.body());
    }

}


text:
require 'test_helper'

class CoreExtTest < ActiveSupport::TestCase
  def test_to_strung_prepend_word
    assert_equal "SUPER hello world", "hello world".to_strung
  end
end


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.maven.model.impl;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.FileCollectionFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.*;
import org.jetbrains.jps.builders.storage.BuildDataPaths;
import org.jetbrains.jps.cmdline.ProjectDescriptor;
import org.jetbrains.jps.incremental.CompileContext;
import org.jetbrains.jps.indices.IgnoredFileIndex;
import org.jetbrains.jps.indices.ModuleExcludeIndex;
import org.jetbrains.jps.maven.model.JpsMavenExtensionService;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.util.JpsPathUtil;

import java.io.File;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author Eugene Zhuravlev
 */
public final class MavenResourcesTarget extends ModuleBasedTarget<MavenResourceRootDescriptor> {
  MavenResourcesTarget(final MavenResourcesTargetType type, @NotNull JpsModule module) {
    super(type, module);
  }

  @Override
  public String getId() {
    return myModule.getName();
  }

  @Override
  public Collection<BuildTarget<?>> computeDependencies(BuildTargetRegistry targetRegistry, TargetOutputIndex outputIndex) {
    return Collections.emptyList();
  }

  @Override
  public boolean isCompiledBeforeModuleLevelBuilders() {
    return true;
  }

  @NotNull
  @Override
  public List<MavenResourceRootDescriptor> computeRootDescriptors(JpsModel model, ModuleExcludeIndex index, IgnoredFileIndex ignoredFileIndex, BuildDataPaths dataPaths) {
    // todo: should we honor ignored and excluded roots here?
    final List<MavenResourceRootDescriptor> result = new ArrayList<>();

    MavenModuleResourceConfiguration moduleConfig = getModuleResourcesConfiguration(dataPaths);
    if (moduleConfig == null) return Collections.emptyList();

    int i = 0;

    for (ResourceRootConfiguration resource : getRootConfigurations(moduleConfig)) {
      result.add(new MavenResourceRootDescriptor(this, resource, i++, moduleConfig.overwrite));
    }
    return result;
  }

  private Collection<ResourceRootConfiguration> getRootConfigurations(@Nullable MavenModuleResourceConfiguration moduleConfig) {
    if (moduleConfig != null) {
      return isTests() ? moduleConfig.testResources : moduleConfig.resources;
    }
    return Collections.emptyList();
  }

  @Nullable
  public MavenModuleResourceConfiguration getModuleResourcesConfiguration(BuildDataPaths dataPaths) {
    final MavenProjectConfiguration projectConfig = JpsMavenExtensionService.getInstance().getMavenProjectConfiguration(dataPaths);
    if (projectConfig == null) return null;
    return projectConfig.moduleConfigurations.get(myModule.getName());
  }

  @Override
  public boolean isTests() {
    return ((MavenResourcesTargetType)getTargetType()).isTests();
  }

  @Nullable
  @Override
  public MavenResourceRootDescriptor findRootDescriptor(String rootId, BuildRootIndex rootIndex) {
    for (MavenResourceRootDescriptor descriptor : rootIndex.getTargetRoots(this, null)) {
      if (descriptor.getRootId().equals(rootId)) {
        return descriptor;
      }
    }
    return null;
  }

  @NotNull
  @Override
  public String getPresentableName() {
    return getTargetType().getTypeId() + ":" + myModule.getName();
  }

  @NotNull
  @Override
  public Collection<File> getOutputRoots(CompileContext context) {
    MavenModuleResourceConfiguration configuration =
      getModuleResourcesConfiguration(context.getProjectDescriptor().dataManager.getDataPaths());
    if (configuration == null) return Collections.emptyList();

    Set<File> result = FileCollectionFactory.createCanonicalFileSet();
    final File moduleOutput = getModuleOutputDir();
    for (ResourceRootConfiguration resConfig : getRootConfigurations(configuration)) {
      final File output = getOutputDir(moduleOutput, resConfig, configuration.outputDirectory);
      if (output != null) {
        result.add(output);
      }
    }
    return result;
  }

  @Nullable
  public File getModuleOutputDir() {
    return JpsJavaExtensionService.getInstance().getOutputDirectory(myModule, isTests());
  }

  @Nullable
  public static File getOutputDir(@Nullable File moduleOutput, ResourceRootConfiguration config, @Nullable String outputDirectory) {
    if(outputDirectory != null) {
      moduleOutput = JpsPathUtil.urlToFile(outputDirectory);
    }

    if (moduleOutput == null) {
      return null;
    }
    String targetPath = config.targetPath;
    if (StringUtil.isEmptyOrSpaces(targetPath)) {
      return moduleOutput;
    }
    final File targetPathFile = new File(targetPath);
    final File outputFile = targetPathFile.isAbsolute() ? targetPathFile : new File(moduleOutput, targetPath);
    return new File(FileUtil.toCanonicalPath(outputFile.getPath()));
  }

  @Override
  public void writeConfiguration(ProjectDescriptor pd, PrintWriter out) {
    final BuildDataPaths dataPaths = pd.getTargetsState().getDataPaths();
    final MavenModuleResourceConfiguration configuration = getModuleResourcesConfiguration(dataPaths);
    if (configuration != null) {
      out.write(Integer.toHexString(configuration.computeConfigurationHash(isTests())));
    }
  }
}


text:
#include "btBatchedConstraints.h"

#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btMinMax.h"
#include "LinearMath/btStackAlloc.h"
#include "LinearMath/btQuickprof.h"

#include <string.h> //for memset

const int kNoMerge = -1;

bool btBatchedConstraints::s_debugDrawBatches = false;

struct btBatchedConstraintInfo
{
    int constraintIndex;
    int numConstraintRows;
    int bodyIds[2];
};

struct btBatchInfo
{
    int numConstraints;
    int mergeIndex;

    btBatchInfo() : numConstraints(0), mergeIndex(kNoMerge) {}
};

bool btBatchedConstraints::validate(btConstraintArray* constraints, const btAlignedObjectArray<btSolverBody>& bodies) const
{
    //
    // validate: for debugging only. Verify coloring of bodies, that no body is touched by more than one batch in any given phase
    //
    int errors = 0;
    const int kUnassignedBatch = -1;

    btAlignedObjectArray<int> bodyBatchId;
    for (int iPhase = 0; iPhase < m_phases.size(); ++iPhase)
    {
        bodyBatchId.resizeNoInitialize(0);
        bodyBatchId.resize( bodies.size(), kUnassignedBatch );
        const Range& phase = m_phases[iPhase];
        for (int iBatch = phase.begin; iBatch < phase.end; ++iBatch)
        {
            const Range& batch = m_batches[iBatch];
            for (int iiCons = batch.begin; iiCons < batch.end; ++iiCons)
            {
                int iCons = m_constraintIndices[iiCons];
                const btSolverConstraint& cons = constraints->at(iCons);
                const btSolverBody& bodyA = bodies[cons.m_solverBodyIdA];
                const btSolverBody& bodyB = bodies[cons.m_solverBodyIdB];
                if (! bodyA.internalGetInvMass().isZero())
                {
                    int thisBodyBatchId = bodyBatchId[cons.m_solverBodyIdA];
                    if (thisBodyBatchId == kUnassignedBatch)
                    {
                        bodyBatchId[cons.m_solverBodyIdA] = iBatch;
                    }
                    else if (thisBodyBatchId != iBatch)
                    {
                        btAssert( !"dynamic body is used in 2 different batches in the same phase" );
                        errors++;
                    }
                }
                if (! bodyB.internalGetInvMass().isZero())
                {
                    int thisBodyBatchId = bodyBatchId[cons.m_solverBodyIdB];
                    if (thisBodyBatchId == kUnassignedBatch)
                    {
                        bodyBatchId[cons.m_solverBodyIdB] = iBatch;
                    }
                    else if (thisBodyBatchId != iBatch)
                    {
                        btAssert( !"dynamic body is used in 2 different batches in the same phase" );
                        errors++;
                    }
                }
            }
        }
    }
    return errors == 0;
}

static void debugDrawSingleBatch( const btBatchedConstraints* bc,
    btConstraintArray* constraints,
    const btAlignedObjectArray<btSolverBody>& bodies,
    int iBatch,
    const btVector3& color,
    const btVector3& offset
    )
{
    if (bc && bc->m_debugDrawer && iBatch < bc->m_batches.size())
    {
        const btBatchedConstraints::Range& b = bc->m_batches[iBatch];
        for (int iiCon = b.begin; iiCon < b.end; ++iiCon)
        {
            int iCon = bc->m_constraintIndices[iiCon];
            const btSolverConstraint& con = constraints->at(iCon);
            int iBody0 = con.m_solverBodyIdA;
            int iBody1 = con.m_solverBodyIdB;
            btVector3 pos0 = bodies[iBody0].getWorldTransform().getOrigin() + offset;
            btVector3 pos1 = bodies[iBody1].getWorldTransform().getOrigin() + offset;
            bc->m_debugDrawer->drawLine(pos0, pos1, color);
        }
    }
}

static void debugDrawPhase( const btBatchedConstraints* bc,
    btConstraintArray* constraints,
    const btAlignedObjectArray<btSolverBody>& bodies,
    int iPhase,
    const btVector3& color0,
    const btVector3& color1,
    const btVector3& offset
    )
{
    BT_PROFILE( "debugDrawPhase" );
    if ( bc && bc->m_debugDrawer && iPhase < bc->m_phases.size() )
    {
        const btBatchedConstraints::Range& phase = bc->m_phases[iPhase];
        for (int iBatch = phase.begin; iBatch < phase.end; ++iBatch)
        {
            float tt = float(iBatch - phase.begin) / float(btMax(1, phase.end - phase.begin - 1));
            btVector3 col = lerp(color0, color1, tt);
            debugDrawSingleBatch(bc, constraints, bodies, iBatch, col, offset);
        }
    }
}

static void debugDrawAllBatches( const btBatchedConstraints* bc,
    btConstraintArray* constraints,
    const btAlignedObjectArray<btSolverBody>& bodies
    )
{
    BT_PROFILE( "debugDrawAllBatches" );
    if ( bc && bc->m_debugDrawer && bc->m_phases.size() > 0 )
    {
        btVector3 bboxMin(BT_LARGE_FLOAT, BT_LARGE_FLOAT, BT_LARGE_FLOAT);
        btVector3 bboxMax = -bboxMin;
        for (int iBody = 0; iBody < bodies.size(); ++iBody)
        {
            const btVector3& pos = bodies[iBody].getWorldTransform().getOrigin();
            bboxMin.setMin(pos);
            bboxMax.setMax(pos);
        }
        btVector3 bboxExtent = bboxMax - bboxMin;
        btVector3 offsetBase = btVector3( 0, bboxExtent.y()*1.1f, 0 );
        btVector3 offsetStep = btVector3( 0, 0, bboxExtent.z()*1.1f );
        int numPhases = bc->m_phases.size();
        for (int iPhase = 0; iPhase < numPhases; ++iPhase)
        {
            float b = float(iPhase)/float(numPhases-1);
            btVector3 color0 = btVector3(1,0,b);
            btVector3 color1 = btVector3(0,1,b);
            btVector3 offset = offsetBase + offsetStep*(float(iPhase) - float(numPhases-1)*0.5);
            debugDrawPhase(bc, constraints, bodies, iPhase, color0, color1, offset);
        }
    }
}

static void initBatchedBodyDynamicFlags(btAlignedObjectArray<bool>* outBodyDynamicFlags, const btAlignedObjectArray<btSolverBody>& bodies)
{
    BT_PROFILE("initBatchedBodyDynamicFlags");
    btAlignedObjectArray<bool>& bodyDynamicFlags = *outBodyDynamicFlags;
    bodyDynamicFlags.resizeNoInitialize(bodies.size());
    for (int i = 0; i < bodies.size(); ++i)
    {
        const btSolverBody& body = bodies[ i ];
        bodyDynamicFlags[i] = ( body.internalGetInvMass().x() > btScalar( 0 ) );
    }
}

static int runLengthEncodeConstraintInfo(btBatchedConstraintInfo* outConInfos, int numConstraints)
{
    BT_PROFILE("runLengthEncodeConstraintInfo");
    // detect and run-length encode constraint rows that repeat the same bodies
    int iDest = 0;
    int iSrc = 0;
    while (iSrc < numConstraints)
    {
        const btBatchedConstraintInfo& srcConInfo = outConInfos[iSrc];
        btBatchedConstraintInfo& conInfo = outConInfos[iDest];
        conInfo.constraintIndex = iSrc;
        conInfo.bodyIds[0] = srcConInfo.bodyIds[0];
        conInfo.bodyIds[1] = srcConInfo.bodyIds[1];
        while (iSrc < numConstraints && outConInfos[iSrc].bodyIds[0] == srcConInfo.bodyIds[0] && outConInfos[iSrc].bodyIds[1] == srcConInfo.bodyIds[1])
        {
            ++iSrc;
        }
        conInfo.numConstraintRows = iSrc - conInfo.constraintIndex;
        ++iDest;
    }
    return iDest;
}

struct ReadSolverConstraintsLoop : public btIParallelForBody
{
    btBatchedConstraintInfo* m_outConInfos;
    btConstraintArray* m_constraints;

    ReadSolverConstraintsLoop( btBatchedConstraintInfo* outConInfos, btConstraintArray* constraints )
    {
        m_outConInfos = outConInfos;
        m_constraints = constraints;
    }
    void forLoop( int iBegin, int iEnd ) const BT_OVERRIDE
    {
        for (int i = iBegin; i < iEnd; ++i)
        {
            btBatchedConstraintInfo& conInfo = m_outConInfos[i];
            const btSolverConstraint& con = m_constraints->at( i );
            conInfo.bodyIds[0] = con.m_solverBodyIdA;
            conInfo.bodyIds[1] = con.m_solverBodyIdB;
            conInfo.constraintIndex = i;
            conInfo.numConstraintRows = 1;
        }
    }
};

static int initBatchedConstraintInfo(btBatchedConstraintInfo* outConInfos, btConstraintArray* constraints)
{
    BT_PROFILE("initBatchedConstraintInfo");
    int numConstraints = constraints->size();
    bool inParallel = true;
    if (inParallel)
    {
        ReadSolverConstraintsLoop loop(outConInfos, constraints);
        int grainSize = 1200;
        btParallelFor(0, numConstraints, grainSize, loop);
    }
    else
    {
        for (int i = 0; i < numConstraints; ++i)
        {
            btBatchedConstraintInfo& conInfo = outConInfos[i];
            const btSolverConstraint& con = constraints->at( i );
            conInfo.bodyIds[0] = con.m_solverBodyIdA;
            conInfo.bodyIds[1] = con.m_solverBodyIdB;
            conInfo.constraintIndex = i;
            conInfo.numConstraintRows = 1;
        }
    }
    bool useRunLengthEncoding = true;
    if (useRunLengthEncoding)
    {
        numConstraints = runLengthEncodeConstraintInfo(outConInfos, numConstraints);
    }
    return numConstraints;
}

static void expandConstraintRowsInPlace(int* constraintBatchIds, const btBatchedConstraintInfo* conInfos, int numConstraints, int numConstraintRows)
{
    BT_PROFILE("expandConstraintRowsInPlace");
    if (numConstraintRows > numConstraints)
    {
        // we walk the array in reverse to avoid overwriteing
        for (int iCon = numConstraints - 1; iCon >= 0; --iCon)
        {
            const btBatchedConstraintInfo& conInfo = conInfos[iCon];
            int iBatch = constraintBatchIds[iCon];
            for (int i = conInfo.numConstraintRows - 1; i >= 0; --i)
            {
                int iDest = conInfo.constraintIndex + i;
                btAssert(iDest >= iCon);
                btAssert(iDest >= 0 && iDest < numConstraintRows);
                constraintBatchIds[iDest] = iBatch;
            }
        }
    }
}

static void expandConstraintRows(int* destConstraintBatchIds, const int* srcConstraintBatchIds, const btBatchedConstraintInfo* conInfos, int numConstraints, int numConstraintRows)
{
    BT_PROFILE("expandConstraintRows");
    for ( int iCon = 0; iCon < numConstraints; ++iCon )
    {
        const btBatchedConstraintInfo& conInfo = conInfos[ iCon ];
        int iBatch = srcConstraintBatchIds[ iCon ];
        for ( int i = 0; i < conInfo.numConstraintRows; ++i )
        {
            int iDest = conInfo.constraintIndex + i;
            btAssert( iDest >= iCon );
            btAssert( iDest >= 0 && iDest < numConstraintRows );
            destConstraintBatchIds[ iDest ] = iBatch;
        }
    }
}

struct ExpandConstraintRowsLoop : public btIParallelForBody
{
    int* m_destConstraintBatchIds;
    const int* m_srcConstraintBatchIds;
    const btBatchedConstraintInfo* m_conInfos;
    int m_numConstraintRows;

    ExpandConstraintRowsLoop( int* destConstraintBatchIds, const int* srcConstraintBatchIds, const btBatchedConstraintInfo* conInfos, int numConstraintRows)
    {
        m_destConstraintBatchIds = destConstraintBatchIds;
        m_srcConstraintBatchIds = srcConstraintBatchIds;
        m_conInfos = conInfos;
        m_numConstraintRows = numConstraintRows;
    }
    void forLoop( int iBegin, int iEnd ) const BT_OVERRIDE
    {
        expandConstraintRows(m_destConstraintBatchIds, m_srcConstraintBatchIds + iBegin, m_conInfos + iBegin, iEnd - iBegin, m_numConstraintRows);
    }
};

static void expandConstraintRowsMt(int* destConstraintBatchIds, const int* srcConstraintBatchIds, const btBatchedConstraintInfo* conInfos, int numConstraints, int numConstraintRows)
{
    BT_PROFILE("expandConstraintRowsMt");
    ExpandConstraintRowsLoop loop(destConstraintBatchIds, srcConstraintBatchIds, conInfos, numConstraintRows);
    int grainSize = 600;
    btParallelFor(0, numConstraints, grainSize, loop);
}

static void initBatchedConstraintInfoArray(btAlignedObjectArray<btBatchedConstraintInfo>* outConInfos, btConstraintArray* constraints)
{
    BT_PROFILE("initBatchedConstraintInfoArray");
    btAlignedObjectArray<btBatchedConstraintInfo>& conInfos = *outConInfos;
    int numConstraints = constraints->size();
    conInfos.resizeNoInitialize(numConstraints);

    int newSize = initBatchedConstraintInfo(&outConInfos->at(0), constraints);
    conInfos.resizeNoInitialize(newSize);
}

static void mergeSmallBatches(btBatchInfo* batches, int iBeginBatch, int iEndBatch, int minBatchSize, int maxBatchSize)
{
    BT_PROFILE("mergeSmallBatches");
    for ( int iBatch = iEndBatch - 1; iBatch >= iBeginBatch; --iBatch )
    {
        btBatchInfo& batch = batches[ iBatch ];
        if ( batch.mergeIndex == kNoMerge && batch.numConstraints > 0 && batch.numConstraints < minBatchSize )
        {
            for ( int iDestBatch = iBatch - 1; iDestBatch >= iBeginBatch; --iDestBatch )
            {
                btBatchInfo& destBatch = batches[ iDestBatch ];
                if ( destBatch.mergeIndex == kNoMerge && ( destBatch.numConstraints + batch.numConstraints ) < maxBatchSize )
                {
                    destBatch.numConstraints += batch.numConstraints;
                    batch.numConstraints = 0;
                    batch.mergeIndex = iDestBatch;
                    break;
                }
            }
        }
    }
    // flatten mergeIndexes
    // e.g. in case where A was merged into B and then B was merged into C, we need A to point to C instead of B
    // Note: loop goes forward through batches because batches always merge from higher indexes to lower,
    //     so by going from low to high it reduces the amount of trail-following
    for ( int iBatch = iBeginBatch; iBatch < iEndBatch; ++iBatch )
    {
        btBatchInfo& batch = batches[ iBatch ];
        if ( batch.mergeIndex != kNoMerge )
        {
            int iMergeDest = batches[ batch.mergeIndex ].mergeIndex;
            // follow trail of merges to the end
            while ( iMergeDest != kNoMerge )
            {
                int iNext = batches[ iMergeDest ].mergeIndex;
                if ( iNext == kNoMerge )
                {
                    batch.mergeIndex = iMergeDest;
                    break;
                }
                iMergeDest = iNext;
            }
        }
    }
}

static void updateConstraintBatchIdsForMerges(int* constraintBatchIds, int numConstraints, const btBatchInfo* batches, int numBatches)
{
    BT_PROFILE("updateConstraintBatchIdsForMerges");
    // update batchIds to account for merges
    for (int i = 0; i < numConstraints; ++i)
    {
        int iBatch = constraintBatchIds[i];
        btAssert(iBatch < numBatches);
        // if this constraint references a batch that was merged into another batch
        if (batches[iBatch].mergeIndex != kNoMerge)
        {
            // update batchId
            constraintBatchIds[i] = batches[iBatch].mergeIndex;
        }
    }
}

struct UpdateConstraintBatchIdsForMergesLoop : public btIParallelForBody
{
    int* m_constraintBatchIds;
    const btBatchInfo* m_batches;
    int m_numBatches;

    UpdateConstraintBatchIdsForMergesLoop( int* constraintBatchIds, const btBatchInfo* batches, int numBatches )
    {
        m_constraintBatchIds = constraintBatchIds;
        m_batches = batches;
        m_numBatches = numBatches;
    }
    void forLoop( int iBegin, int iEnd ) const BT_OVERRIDE
    {
        BT_PROFILE( "UpdateConstraintBatchIdsForMergesLoop" );
        updateConstraintBatchIdsForMerges( m_constraintBatchIds + iBegin, iEnd - iBegin, m_batches, m_numBatches );
    }
};

static void updateConstraintBatchIdsForMergesMt(int* constraintBatchIds, int numConstraints, const btBatchInfo* batches, int numBatches)
{
    BT_PROFILE( "updateConstraintBatchIdsForMergesMt" );
    UpdateConstraintBatchIdsForMergesLoop loop(constraintBatchIds, batches, numBatches);
    int grainSize = 800;
    btParallelFor(0, numConstraints, grainSize, loop);
}

inline bool BatchCompare(const btBatchedConstraints::Range& a, const btBatchedConstraints::Range& b)
{
    int lenA = a.end - a.begin;
    int lenB = b.end - b.begin;
    return lenA > lenB;
}

static void writeOutConstraintIndicesForRangeOfBatches(btBatchedConstraints* bc,
    const int* constraintBatchIds,
    int numConstraints,
    int* constraintIdPerBatch,
    int batchBegin,
    int batchEnd
    )
{
    BT_PROFILE("writeOutConstraintIndicesForRangeOfBatches");
    for ( int iCon = 0; iCon < numConstraints; ++iCon )
    {
        int iBatch = constraintBatchIds[ iCon ];
        if (iBatch >= batchBegin && iBatch < batchEnd)
        {
            int iDestCon = constraintIdPerBatch[ iBatch ];
            constraintIdPerBatch[ iBatch ] = iDestCon + 1;
            bc->m_constraintIndices[ iDestCon ] = iCon;
        }
    }
}

struct WriteOutConstraintIndicesLoop : public btIParallelForBody
{
    btBatchedConstraints* m_batchedConstraints;
    const int* m_constraintBatchIds;
    int m_numConstraints;
    int* m_constraintIdPerBatch;
    int m_maxNumBatchesPerPhase;

    WriteOutConstraintIndicesLoop( btBatchedConstraints* bc, const int* constraintBatchIds, int numConstraints, int* constraintIdPerBatch, int maxNumBatchesPerPhase )
    {
        m_batchedConstraints = bc;
        m_constraintBatchIds = constraintBatchIds;
        m_numConstraints = numConstraints;
        m_constraintIdPerBatch = constraintIdPerBatch;
        m_maxNumBatchesPerPhase = maxNumBatchesPerPhase;
    }
    void forLoop( int iBegin, int iEnd ) const BT_OVERRIDE
    {
        BT_PROFILE( "WriteOutConstraintIndicesLoop" );
        int batchBegin = iBegin * m_maxNumBatchesPerPhase;
        int batchEnd = iEnd * m_maxNumBatchesPerPhase;
        writeOutConstraintIndicesForRangeOfBatches(m_batchedConstraints,
            m_constraintBatchIds,
            m_numConstraints,
            m_constraintIdPerBatch,
            batchBegin,
            batchEnd
        );
    }
};

static void writeOutConstraintIndicesMt(btBatchedConstraints* bc,
    const int* constraintBatchIds,
    int numConstraints,
    int* constraintIdPerBatch,
    int maxNumBatchesPerPhase,
    int numPhases
    )
{
    BT_PROFILE("writeOutConstraintIndicesMt");
    bool inParallel = true;
    if (inParallel)
    {
        WriteOutConstraintIndicesLoop loop( bc, constraintBatchIds, numConstraints, constraintIdPerBatch, maxNumBatchesPerPhase );
        btParallelFor( 0, numPhases, 1, loop );
    }
    else
    {
        for ( int iCon = 0; iCon < numConstraints; ++iCon )
        {
            int iBatch = constraintBatchIds[ iCon ];
            int iDestCon = constraintIdPerBatch[ iBatch ];
            constraintIdPerBatch[ iBatch ] = iDestCon + 1;
            bc->m_constraintIndices[ iDestCon ] = iCon;
        }
    }
}

static void writeGrainSizes(btBatchedConstraints* bc)
{
    typedef btBatchedConstraints::Range Range;
    int numPhases = bc->m_phases.size();
    bc->m_phaseGrainSize.resizeNoInitialize(numPhases);
    int numThreads = btGetTaskScheduler()->getNumThreads();
    for (int iPhase = 0; iPhase < numPhases; ++iPhase)
    {
        const Range& phase = bc->m_phases[ iPhase ];
        int numBatches = phase.end - phase.begin;
        float grainSize = floor((0.25f*numBatches / float(numThreads)) + 0.0f);
        bc->m_phaseGrainSize[ iPhase ] = btMax(1, int(grainSize));
    }
}

static void writeOutBatches(btBatchedConstraints* bc,
    const int* constraintBatchIds,
    int numConstraints,
    const btBatchInfo* batches,
    int* batchWork,
    int maxNumBatchesPerPhase,
    int numPhases
)
{
    BT_PROFILE("writeOutBatches");
    typedef btBatchedConstraints::Range Range;
    bc->m_constraintIndices.reserve( numConstraints );
    bc->m_batches.resizeNoInitialize( 0 );
    bc->m_phases.resizeNoInitialize( 0 );

    //int maxNumBatches = numPhases * maxNumBatchesPerPhase;
    {
        int* constraintIdPerBatch = batchWork;  // for each batch, keep an index into the next available slot in the m_constraintIndices array
        int iConstraint = 0;
        for (int iPhase = 0; iPhase < numPhases; ++iPhase)
        {
            int curPhaseBegin = bc->m_batches.size();
            int iBegin = iPhase * maxNumBatchesPerPhase;
            int iEnd = iBegin + maxNumBatchesPerPhase;
            for ( int i = iBegin; i < iEnd; ++i )
            {
                const btBatchInfo& batch = batches[ i ];
                int curBatchBegin = iConstraint;
                constraintIdPerBatch[ i ] = curBatchBegin;  // record the start of each batch in m_constraintIndices array
                int numConstraints = batch.numConstraints;
                iConstraint += numConstraints;
                if ( numConstraints > 0 )
                {
                    bc->m_batches.push_back( Range( curBatchBegin, iConstraint ) );
                }
            }
            // if any batches were emitted this phase,
            if ( bc->m_batches.size() > curPhaseBegin )
            {
                // output phase
                bc->m_phases.push_back( Range( curPhaseBegin, bc->m_batches.size() ) );
            }
        }

        btAssert(iConstraint == numConstraints);
        bc->m_constraintIndices.resizeNoInitialize( numConstraints );
        writeOutConstraintIndicesMt( bc, constraintBatchIds, numConstraints, constraintIdPerBatch, maxNumBatchesPerPhase, numPhases );
    }
    // for each phase
    for (int iPhase = 0; iPhase < bc->m_phases.size(); ++iPhase)
    {
        // sort the batches from largest to smallest (can be helpful to some task schedulers)
        const Range& curBatches = bc->m_phases[iPhase];
        bc->m_batches.quickSortInternal(BatchCompare, curBatches.begin, curBatches.end-1);
    }
    bc->m_phaseOrder.resize(bc->m_phases.size());
    for (int i = 0; i < bc->m_phases.size(); ++i)
    {
        bc->m_phaseOrder[i] = i;
    }
    writeGrainSizes(bc);
}

//
// PreallocatedMemoryHelper -- helper object for allocating a number of chunks of memory in a single contiguous block.
//                             It is generally more efficient to do a single larger allocation than many smaller allocations.
//
// Example Usage:
//
//  btVector3* bodyPositions = NULL;
//  btBatchedConstraintInfo* conInfos = NULL;
//  {
//    PreallocatedMemoryHelper<8> memHelper;
//    memHelper.addChunk( (void**) &bodyPositions, sizeof( btVector3 ) * bodies.size() );
//    memHelper.addChunk( (void**) &conInfos, sizeof( btBatchedConstraintInfo ) * numConstraints );
//    void* memPtr = malloc( memHelper.getSizeToAllocate() );  // allocate the memory
//    memHelper.setChunkPointers( memPtr );  // update pointers to chunks
//  }
template <int N>
class PreallocatedMemoryHelper
{
    struct Chunk
    {
        void** ptr;
        size_t size;
    };
    Chunk m_chunks[N];
    int m_numChunks;
public:
    PreallocatedMemoryHelper() {m_numChunks=0;}
    void addChunk( void** ptr, size_t sz )
    {
        btAssert( m_numChunks < N );
        if ( m_numChunks < N )
        {
            Chunk& chunk = m_chunks[ m_numChunks ];
            chunk.ptr = ptr;
            chunk.size = sz;
            m_numChunks++;
        }
    }
    size_t getSizeToAllocate() const
    {
        size_t totalSize = 0;
        for (int i = 0; i < m_numChunks; ++i)
        {
            totalSize += m_chunks[i].size;
        }
        return totalSize;
    }
    void setChunkPointers(void* mem) const
    {
        size_t totalSize = 0;
        for (int i = 0; i < m_numChunks; ++i)
        {
            const Chunk& chunk = m_chunks[ i ];
            char* chunkPtr = static_cast<char*>(mem) + totalSize;
            *chunk.ptr = chunkPtr;
            totalSize += chunk.size;
        }
    }
};

static btVector3 findMaxDynamicConstraintExtent(
    btVector3* bodyPositions,
    bool* bodyDynamicFlags,
    btBatchedConstraintInfo* conInfos,
    int numConstraints,
    int numBodies
    )
{
    BT_PROFILE("findMaxDynamicConstraintExtent");
    btVector3 consExtent = btVector3(1,1,1) * 0.001;
    for (int iCon = 0; iCon < numConstraints; ++iCon)
    {
        const btBatchedConstraintInfo& con = conInfos[ iCon ];
        int iBody0 = con.bodyIds[0];
        int iBody1 = con.bodyIds[1];
        btAssert(iBody0 >= 0 && iBody0 < numBodies);
        btAssert(iBody1 >= 0 && iBody1 < numBodies);
        // is it a dynamic constraint?
        if (bodyDynamicFlags[iBody0] && bodyDynamicFlags[iBody1])
        {
            btVector3 delta = bodyPositions[iBody1] - bodyPositions[iBody0];
            consExtent.setMax(delta.absolute());
        }
    }
    return consExtent;
}

struct btIntVec3
{
    int m_ints[ 3 ];

    SIMD_FORCE_INLINE const int& operator[](int i) const {return m_ints[i];}
    SIMD_FORCE_INLINE int&       operator[](int i)       {return m_ints[i];}
};

struct AssignConstraintsToGridBatchesParams
{
    bool* bodyDynamicFlags;
    btIntVec3* bodyGridCoords;
    int numBodies;
    btBatchedConstraintInfo* conInfos;
    int* constraintBatchIds;
    btIntVec3 gridChunkDim;
    int maxNumBatchesPerPhase;
    int numPhases;
    int phaseMask;

    AssignConstraintsToGridBatchesParams()
    {
        memset(this, 0, sizeof(*this));
    }
};

static void assignConstraintsToGridBatches(const AssignConstraintsToGridBatchesParams& params, int iConBegin, int iConEnd)
{
    BT_PROFILE("assignConstraintsToGridBatches");
    // (can be done in parallel)
    for ( int iCon = iConBegin; iCon < iConEnd; ++iCon )
    {
        const btBatchedConstraintInfo& con = params.conInfos[ iCon ];
        int iBody0 = con.bodyIds[ 0 ];
        int iBody1 = con.bodyIds[ 1 ];
        int iPhase = iCon; //iBody0; // pseudorandom choice to distribute evenly amongst phases
        iPhase &= params.phaseMask;
        int gridCoord[ 3 ];
        // is it a dynamic constraint?
        if ( params.bodyDynamicFlags[ iBody0 ] && params.bodyDynamicFlags[ iBody1 ] )
        {
            const btIntVec3& body0Coords = params.bodyGridCoords[iBody0];
            const btIntVec3& body1Coords = params.bodyGridCoords[iBody1];
            // for each dimension x,y,z,
            for (int i = 0; i < 3; ++i)
            {
                int coordMin = btMin(body0Coords.m_ints[i], body1Coords.m_ints[i]);
                int coordMax = btMax(body0Coords.m_ints[i], body1Coords.m_ints[i]);
                if (coordMin != coordMax)
                {
                    btAssert( coordMax == coordMin + 1 );
                    if ((coordMin&1) == 0)
                    {
                        iPhase &= ~(1 << i); // force bit off
                    }
                    else
                    {
                        iPhase |= (1 << i); // force bit on
                        iPhase &= params.phaseMask;
                    }
                }
                gridCoord[ i ] = coordMin;
            }
        }
        else
        {
            if ( !params.bodyDynamicFlags[ iBody0 ] )
            {
                iBody0 = con.bodyIds[ 1 ];
            }
            btAssert(params.bodyDynamicFlags[ iBody0 ]);
            const btIntVec3& body0Coords = params.bodyGridCoords[iBody0];
            // for each dimension x,y,z,
            for ( int i = 0; i < 3; ++i )
            {
                gridCoord[ i ] = body0Coords.m_ints[ i ];
            }
        }
        // calculate chunk coordinates
        int chunkCoord[ 3 ];
        btIntVec3 gridChunkDim = params.gridChunkDim;
        // for each dimension x,y,z,
        for ( int i = 0; i < 3; ++i )
        {
            int coordOffset = ( iPhase >> i ) & 1;
            chunkCoord[ i ] = (gridCoord[ i ] - coordOffset)/2;
            btClamp( chunkCoord[ i ], 0, gridChunkDim[ i ] - 1);
            btAssert( chunkCoord[ i ] < gridChunkDim[ i ] );
        }
        int iBatch = iPhase * params.maxNumBatchesPerPhase + chunkCoord[ 0 ] + chunkCoord[ 1 ] * gridChunkDim[ 0 ] + chunkCoord[ 2 ] * gridChunkDim[ 0 ] * gridChunkDim[ 1 ];
        btAssert(iBatch >= 0 && iBatch < params.maxNumBatchesPerPhase*params.numPhases);
        params.constraintBatchIds[ iCon ] = iBatch;
    }
}

struct AssignConstraintsToGridBatchesLoop : public btIParallelForBody
{
    const AssignConstraintsToGridBatchesParams* m_params;

    AssignConstraintsToGridBatchesLoop( const AssignConstraintsToGridBatchesParams& params )
    {
        m_params = &params;
    }
    void forLoop( int iBegin, int iEnd ) const BT_OVERRIDE
    {
        assignConstraintsToGridBatches(*m_params, iBegin, iEnd);
    }
};

//
// setupSpatialGridBatchesMt -- generate batches using a uniform 3D grid
//
/*

Bodies are treated as 3D points at their center of mass. We only consider dynamic bodies at this stage,
because only dynamic bodies are mutated when a constraint is solved, thus subject to race conditions.

1. Compute a bounding box around all dynamic bodies
2. Compute the maximum extent of all dynamic constraints. Each dynamic constraint is treated as a line segment, and we need the size of
   box that will fully enclose any single dynamic constraint

3. Establish the cell size of our grid, the cell size in each dimension must be at least as large as the dynamic constraints max-extent,
   so that no dynamic constraint can span more than 2 cells of our grid on any axis of the grid. The cell size should be adjusted
   larger in order to keep the total number of cells from being excessively high

Key idea: Given that each constraint spans 1 or 2 grid cells in each dimension, we can handle all constraints by processing
          in chunks of 2x2x2 cells with 8 different 1-cell offsets ((0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0)...).
          For each of the 8 offsets, we create a phase, and for each 2x2x2 chunk with dynamic constraints becomes a batch in that phase.

4. Once the grid is established, we can calculate for each constraint which phase and batch it belongs in.

5. Do a merge small batches on the batches of each phase separately, to try to even out the sizes of batches

Optionally, we can "collapse" one dimension of our 3D grid to turn it into a 2D grid, which reduces the number of phases
to 4. With fewer phases, there are more constraints per phase and this makes it easier to create batches of a useful size.
*/
//
static void setupSpatialGridBatchesMt(
    btBatchedConstraints* batchedConstraints,
    btAlignedObjectArray<char>* scratchMemory,
    btConstraintArray* constraints,
    const btAlignedObjectArray<btSolverBody>& bodies,
    int minBatchSize,
    int maxBatchSize,
    bool use2DGrid
)
{
    BT_PROFILE("setupSpatialGridBatchesMt");
    const int numPhases = 8;
    int numConstraints = constraints->size();
    int numConstraintRows = constraints->size();

    const int maxGridChunkCount = 128;
    int allocNumBatchesPerPhase = maxGridChunkCount;
    int minNumBatchesPerPhase = 16;
    int allocNumBatches = allocNumBatchesPerPhase * numPhases;

    btVector3* bodyPositions = NULL;
    bool* bodyDynamicFlags = NULL;
    btIntVec3* bodyGridCoords = NULL;
    btBatchInfo* batches = NULL;
    int* batchWork = NULL;
    btBatchedConstraintInfo* conInfos = NULL;
    int* constraintBatchIds = NULL;
    int* constraintRowBatchIds = NULL;
    {
        PreallocatedMemoryHelper<10> memHelper;
        memHelper.addChunk( (void**) &bodyPositions, sizeof( btVector3 ) * bodies.size() );
        memHelper.addChunk( (void**) &bodyDynamicFlags, sizeof( bool ) * bodies.size() );
        memHelper.addChunk( (void**) &bodyGridCoords, sizeof( btIntVec3 ) * bodies.size() );
        memHelper.addChunk( (void**) &batches, sizeof( btBatchInfo )* allocNumBatches );
        memHelper.addChunk( (void**) &batchWork, sizeof( int )* allocNumBatches );
        memHelper.addChunk( (void**) &conInfos, sizeof( btBatchedConstraintInfo ) * numConstraints );
        memHelper.addChunk( (void**) &constraintBatchIds, sizeof( int ) * numConstraints );
        memHelper.addChunk( (void**) &constraintRowBatchIds, sizeof( int ) * numConstraintRows );
        size_t scratchSize = memHelper.getSizeToAllocate();
        // if we need to reallocate
        if (scratchMemory->capacity() < scratchSize)
        {
            // allocate 6.25% extra to avoid repeated reallocs
            scratchMemory->reserve( scratchSize + scratchSize/16 );
        }
        scratchMemory->resizeNoInitialize( scratchSize );
        char* memPtr = &scratchMemory->at(0);
        memHelper.setChunkPointers( memPtr );
    }

    numConstraints = initBatchedConstraintInfo(conInfos, constraints);

    // compute bounding box around all dynamic bodies
    // (could be done in parallel)
    btVector3 bboxMin(BT_LARGE_FLOAT, BT_LARGE_FLOAT, BT_LARGE_FLOAT);
    btVector3 bboxMax = -bboxMin;
    //int dynamicBodyCount = 0;
    for (int i = 0; i < bodies.size(); ++i)
    {
        const btSolverBody& body = bodies[i];
        btVector3 bodyPos = body.getWorldTransform().getOrigin();
        bool isDynamic = ( body.internalGetInvMass().x() > btScalar( 0 ) );
        bodyPositions[i] = bodyPos;
        bodyDynamicFlags[i] = isDynamic;
        if (isDynamic)
        {
            //dynamicBodyCount++;
            bboxMin.setMin(bodyPos);
            bboxMax.setMax(bodyPos);
        }
    }

    // find max extent of all dynamic constraints
    // (could be done in parallel)
    btVector3 consExtent = findMaxDynamicConstraintExtent(bodyPositions, bodyDynamicFlags, conInfos, numConstraints, bodies.size());

    btVector3 gridExtent = bboxMax - bboxMin;

    btVector3 gridCellSize = consExtent;
    int gridDim[3];
    gridDim[ 0 ] = int( 1.0 + gridExtent.x() / gridCellSize.x() );
    gridDim[ 1 ] = int( 1.0 + gridExtent.y() / gridCellSize.y() );
    gridDim[ 2 ] = int( 1.0 + gridExtent.z() / gridCellSize.z() );

    // if we can collapse an axis, it will cut our number of phases in half which could be more efficient
    int phaseMask = 7;
    bool collapseAxis = use2DGrid;
    if ( collapseAxis )
    {
        // pick the smallest axis to collapse, leaving us with the greatest number of cells in our grid
        int iAxisToCollapse = 0;
        int axisDim = gridDim[iAxisToCollapse];
        //for each dimension
        for ( int i = 0; i < 3; ++i )
        {
            if (gridDim[i] < axisDim)
            {
                iAxisToCollapse = i;
                axisDim = gridDim[i];
            }
        }
        // collapse it
        gridCellSize[iAxisToCollapse] = gridExtent[iAxisToCollapse] * 2.0f;
        phaseMask &= ~(1 << iAxisToCollapse);
    }

    int numGridChunks = 0;
    btIntVec3 gridChunkDim;  // each chunk is 2x2x2 group of cells
    while (true)
    {
        gridDim[0] = int( 1.0 + gridExtent.x() / gridCellSize.x() );
        gridDim[1] = int( 1.0 + gridExtent.y() / gridCellSize.y() );
        gridDim[2] = int( 1.0 + gridExtent.z() / gridCellSize.z() );
        gridChunkDim[ 0 ] = btMax( 1, ( gridDim[ 0 ] + 0 ) / 2 );
        gridChunkDim[ 1 ] = btMax( 1, ( gridDim[ 1 ] + 0 ) / 2 );
        gridChunkDim[ 2 ] = btMax( 1, ( gridDim[ 2 ] + 0 ) / 2 );
        numGridChunks = gridChunkDim[ 0 ] * gridChunkDim[ 1 ] * gridChunkDim[ 2 ];
        float nChunks = float(gridChunkDim[0]) * float(gridChunkDim[1]) * float(gridChunkDim[2]);  // suceptible to integer overflow
        if ( numGridChunks <= maxGridChunkCount && nChunks <= maxGridChunkCount )
        {
            break;
        }
        gridCellSize *= 1.25; // should roughly cut numCells in half
    }
    btAssert(numGridChunks <= maxGridChunkCount );
    int maxNumBatchesPerPhase = numGridChunks;

    // for each dynamic body, compute grid coords
    btVector3 invGridCellSize = btVector3(1,1,1)/gridCellSize;
    // (can be done in parallel)
    for (int iBody = 0; iBody < bodies.size(); ++iBody)
    {
        btIntVec3& coords = bodyGridCoords[iBody];
        if (bodyDynamicFlags[iBody])
        {
            btVector3 v = ( bodyPositions[ iBody ] - bboxMin )*invGridCellSize;
            coords.m_ints[0] = int(v.x());
            coords.m_ints[1] = int(v.y());
            coords.m_ints[2] = int(v.z());
            btAssert(coords.m_ints[0] >= 0 && coords.m_ints[0] < gridDim[0]);
            btAssert(coords.m_ints[1] >= 0 && coords.m_ints[1] < gridDim[1]);
            btAssert(coords.m_ints[2] >= 0 && coords.m_ints[2] < gridDim[2]);
        }
        else
        {
            coords.m_ints[0] = -1;
            coords.m_ints[1] = -1;
            coords.m_ints[2] = -1;
        }
    }

    for (int iPhase = 0; iPhase < numPhases; ++iPhase)
    {
        int batchBegin = iPhase * maxNumBatchesPerPhase;
        int batchEnd = batchBegin + maxNumBatchesPerPhase;
        for ( int iBatch = batchBegin; iBatch < batchEnd; ++iBatch )
        {
            btBatchInfo& batch = batches[ iBatch ];
            batch = btBatchInfo();
        }
    }

    {
        AssignConstraintsToGridBatchesParams params;
        params.bodyDynamicFlags = bodyDynamicFlags;
        params.bodyGridCoords = bodyGridCoords;
        params.numBodies = bodies.size();
        params.conInfos = conInfos;
        params.constraintBatchIds = constraintBatchIds;
        params.gridChunkDim = gridChunkDim;
        params.maxNumBatchesPerPhase = maxNumBatchesPerPhase;
        params.numPhases = numPhases;
        params.phaseMask = phaseMask;
        bool inParallel = true;
        if (inParallel)
        {
            AssignConstraintsToGridBatchesLoop loop(params);
            int grainSize = 250;
            btParallelFor(0, numConstraints, grainSize, loop);
        }
        else
        {
            assignConstraintsToGridBatches( params, 0, numConstraints );
        }
    }
    for ( int iCon = 0; iCon < numConstraints; ++iCon )
    {
        const btBatchedConstraintInfo& con = conInfos[ iCon ];
        int iBatch = constraintBatchIds[ iCon ];
        btBatchInfo& batch = batches[iBatch];
        batch.numConstraints += con.numConstraintRows;
    }

    for (int iPhase = 0; iPhase < numPhases; ++iPhase)
    {
        // if phase is legit,
        if (iPhase == (iPhase&phaseMask))
        {
            int iBeginBatch = iPhase * maxNumBatchesPerPhase;
            int iEndBatch = iBeginBatch + maxNumBatchesPerPhase;
            mergeSmallBatches( batches, iBeginBatch, iEndBatch, minBatchSize, maxBatchSize );
        }
    }
    // all constraints have been assigned a batchId
    updateConstraintBatchIdsForMergesMt(constraintBatchIds, numConstraints, batches, maxNumBatchesPerPhase*numPhases);

    if (numConstraintRows > numConstraints)
    {
        expandConstraintRowsMt(&constraintRowBatchIds[0], &constraintBatchIds[0], &conInfos[0], numConstraints, numConstraintRows);
    }
    else
    {
        constraintRowBatchIds = constraintBatchIds;
    }

    writeOutBatches(batchedConstraints, constraintRowBatchIds, numConstraintRows, batches, batchWork, maxNumBatchesPerPhase, numPhases);
    btAssert(batchedConstraints->validate(constraints, bodies));
}

static void setupSingleBatch(
    btBatchedConstraints* bc,
    int numConstraints
)
{
    BT_PROFILE("setupSingleBatch");
    typedef btBatchedConstraints::Range Range;

    bc->m_constraintIndices.resize( numConstraints );
    for ( int i = 0; i < numConstraints; ++i )
    {
        bc->m_constraintIndices[ i ] = i;
    }

    bc->m_batches.resizeNoInitialize( 0 );
    bc->m_phases.resizeNoInitialize( 0 );
    bc->m_phaseOrder.resizeNoInitialize( 0 );
    bc->m_phaseGrainSize.resizeNoInitialize( 0 );

    if (numConstraints > 0)
    {
        bc->m_batches.push_back( Range( 0, numConstraints ) );
        bc->m_phases.push_back( Range( 0, 1 ) );
        bc->m_phaseOrder.push_back(0);
        bc->m_phaseGrainSize.push_back(1);
    }
}

void btBatchedConstraints::setup(
    btConstraintArray* constraints,
    const btAlignedObjectArray<btSolverBody>& bodies,
    BatchingMethod batchingMethod,
    int minBatchSize,
    int maxBatchSize,
    btAlignedObjectArray<char>* scratchMemory
    )
{
    if (constraints->size() >= minBatchSize*4)
    {
        bool use2DGrid = batchingMethod == BATCHING_METHOD_SPATIAL_GRID_2D;
        setupSpatialGridBatchesMt( this, scratchMemory, constraints, bodies, minBatchSize, maxBatchSize, use2DGrid );
        if (s_debugDrawBatches)
        {
            debugDrawAllBatches( this, constraints, bodies );
        }
    }
    else
    {
        setupSingleBatch( this, constraints->size() );
    }
}


text:
namespace settings {

StartupPagesHandler::StartupPagesHandler(content::WebUI* webui)
    : startup_custom_pages_table_model_(Profile::FromWebUI(webui)) {
}

StartupPagesHandler::~StartupPagesHandler() {
}

void StartupPagesHandler::RegisterMessages() {
  if (Profile::FromWebUI(web_ui())->IsOffTheRecord())
    return;

  web_ui()->RegisterMessageCallback(
      "addStartupPage",
      base::BindRepeating(&StartupPagesHandler::HandleAddStartupPage,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "editStartupPage",
      base::BindRepeating(&StartupPagesHandler::HandleEditStartupPage,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "onStartupPrefsPageLoad",
      base::BindRepeating(&StartupPagesHandler::HandleOnStartupPrefsPageLoad,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "removeStartupPage",
      base::BindRepeating(&StartupPagesHandler::HandleRemoveStartupPage,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "setStartupPagesToCurrentPages",
      base::BindRepeating(
          &StartupPagesHandler::HandleSetStartupPagesToCurrentPages,
          base::Unretained(this)));
}

void StartupPagesHandler::OnJavascriptAllowed() {
  startup_custom_pages_table_model_.SetObserver(this);

  PrefService* prefService = Profile::FromWebUI(web_ui())->GetPrefs();
  SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefService);
  startup_custom_pages_table_model_.SetURLs(pref.urls);

  if (pref.urls.empty())
    pref.type = SessionStartupPref::DEFAULT;

  pref_change_registrar_.Init(prefService);
  pref_change_registrar_.Add(
      prefs::kURLsToRestoreOnStartup,
      base::BindRepeating(&StartupPagesHandler::UpdateStartupPages,
                          base::Unretained(this)));
}

void StartupPagesHandler::OnJavascriptDisallowed() {
  startup_custom_pages_table_model_.SetObserver(nullptr);
  pref_change_registrar_.RemoveAll();
}

void StartupPagesHandler::OnModelChanged() {
  base::ListValue startup_pages;
  int page_count = startup_custom_pages_table_model_.RowCount();
  std::vector<GURL> urls = startup_custom_pages_table_model_.GetURLs();
  for (int i = 0; i < page_count; ++i) {
    std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
    entry->SetStringKey("title",
                        startup_custom_pages_table_model_.GetText(i, 0));
    entry->SetStringKey("url", urls[i].spec());
    entry->SetStringKey("tooltip",
                        startup_custom_pages_table_model_.GetTooltip(i));
    entry->SetIntKey("modelIndex", i);
    startup_pages.Append(std::move(entry));
  }

  FireWebUIListener("update-startup-pages", startup_pages);
}

void StartupPagesHandler::OnItemsChanged(int start, int length) {
  OnModelChanged();
}

void StartupPagesHandler::OnItemsAdded(int start, int length) {
  OnModelChanged();
}

void StartupPagesHandler::OnItemsRemoved(int start, int length) {
  OnModelChanged();
}

void StartupPagesHandler::HandleAddStartupPage(const base::Value::List& args) {
  CHECK_EQ(2U, args.size());
  const base::Value& callback_id = args[0];

  if (!args[1].is_string()) {
    NOTREACHED();
    return;
  }

  std::string url_string = args[1].GetString();

  GURL url;
  if (!settings_utils::FixupAndValidateStartupPage(url_string, &url)) {
    ResolveJavascriptCallback(callback_id, base::Value(false));
    return;
  }

  startup_custom_pages_table_model_.Add(
      startup_custom_pages_table_model_.RowCount(), url);
  SaveStartupPagesPref();
  ResolveJavascriptCallback(callback_id, base::Value(true));
}

void StartupPagesHandler::HandleEditStartupPage(const base::Value::List& args) {
  CHECK_EQ(args.size(), 3U);
  const base::Value& callback_id = args[0];
  int index = args[1].GetInt();

  if (index < 0 || index >= startup_custom_pages_table_model_.RowCount()) {
    RejectJavascriptCallback(callback_id, base::Value());
    NOTREACHED();
    return;
  }

  std::string url_string = args[2].GetString();

  GURL fixed_url;
  if (settings_utils::FixupAndValidateStartupPage(url_string, &fixed_url)) {
    std::vector<GURL> urls = startup_custom_pages_table_model_.GetURLs();
    urls[index] = fixed_url;
    startup_custom_pages_table_model_.SetURLs(urls);
    SaveStartupPagesPref();
    ResolveJavascriptCallback(callback_id, base::Value(true));
  } else {
    ResolveJavascriptCallback(callback_id, base::Value(false));
  }
}

void StartupPagesHandler::HandleOnStartupPrefsPageLoad(
    const base::Value::List& args) {
  AllowJavascript();
}

void StartupPagesHandler::HandleRemoveStartupPage(
    const base::Value::List& args) {
  CHECK_EQ(args.size(), 1u);
  if (!args[0].is_int()) {
    NOTREACHED();
    return;
  }
  int selected_index = args[0].GetInt();

  if (selected_index < 0 ||
      selected_index >= startup_custom_pages_table_model_.RowCount()) {
    NOTREACHED();
    return;
  }

  startup_custom_pages_table_model_.Remove(selected_index);
  SaveStartupPagesPref();
}

void StartupPagesHandler::HandleSetStartupPagesToCurrentPages(
    const base::Value::List& args) {
  startup_custom_pages_table_model_.SetToCurrentlyOpenPages(
      web_ui()->GetWebContents());
  SaveStartupPagesPref();
}

void StartupPagesHandler::SaveStartupPagesPref() {
  PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();

  SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);
  pref.urls = startup_custom_pages_table_model_.GetURLs();

  if (pref.urls.empty())
    pref.type = SessionStartupPref::DEFAULT;

  SessionStartupPref::SetStartupPref(prefs, pref);
}

void StartupPagesHandler::UpdateStartupPages() {
  const SessionStartupPref startup_pref = SessionStartupPref::GetStartupPref(
      Profile::FromWebUI(web_ui())->GetPrefs());
  startup_custom_pages_table_model_.SetURLs(startup_pref.urls);
  // The change will go to the JS code in the
  // StartupPagesHandler::OnModelChanged() method.
}

}  // namespace settings


text:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Test.EntityFramework;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IServiceCollection services = new ServiceCollection();
            var constr = "server=localhost;userid=root;pwd=Pw@123456;port=3306;database=test;sslmode=none;";
            services.AddDbContext<MyDbContext>(options => options.UseMySql(constr, b => b.MigrationsAssembly("Test")));

            services.AddTimedTask().AddEntityFrameworkTimedTask<MyDbContext>();

            //构建容器
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            serviceProvider.UseTimedTask();

            Console.ReadLine();
        }
    }
}


text:
/*
 * Licensed under the Apache License,Version2.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.
 */

/**
 * Licensed under the Apache License,Version2.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.
 */

package de.datenhahn.vaadin.componentrenderer.grid.header;

/**
 * Typed lambda-compatible interface to generate html grid headers.
 *
 * @author Jonas Hahn (jonas.hahn@datenhahn.de)
 */
public interface HtmlHeaderGenerator extends HeaderGenerator<String> {

    @Override
    String getHeader(Object propertyId);
}


text:
package cssminify

import (
	"os"
	"path/filepath"
	"regexp"
)

func Files() []string {
	files := make([]string, 0)
	filepath.Walk(".",
		func(root string, info os.FileInfo, err error) error {
			matched, _ := regexp.MatchString(".css$", root)
			if matched {
				files = append(files, root)
			}
			return err
		})
	return files
}


text:
module Company
  module Mapping

#CompanyMapper given a corpus of documents (that contains company names) can map a new document with an existing one
#if one exists
    class CompanyMapper

      def initialize(corpus)
        @corpus = corpus
        @tfidf = TFIDF.new(@corpus)
        @tfidf.calculate
      end

      #maps a given company to a company exists to the given corpus. If the maximum name similarity found exceeds the given
      # threshold then the company's id is returned as a match
      def map(company, threshold)
        if (company.is_a? String)
          content = company
          company = TextDocument.new
          company.contents = content
          company.id = "new_comp"
        end

        @tfidf.calculate_tfidf_weights_of_new_document(company)

        maxSim = 0.0
        mapped_company = ""
        @corpus.each do |d|
          similarity = @tfidf.similarity(d.id, company.id)
          next unless maxSim < similarity
          maxSim = similarity
          mapped_company = d.id
          break if maxSim == 1
        end

        return unless maxSim > threshold
        mapped_company.to_s.sub(/\_.*/, "").to_i
      end
    end
  end
end


text:
class RatingsController < ApplicationController
  def index
    @rater = respond_to?(:current_rater) ? current_rater : params[:rating][:rater_type].constantize.find_by_id(params[:rating][:rater_id])
    @rating = @rater.rate(params[:rating])
    respond_to do |format|
      if (@rating.new_record? ? @rating.save : @rating.update_attribute(:score, params[:rating][:score]))
        format.js { render :inline => "#{20 * @rating.score}"}
      else
        format.js { render :inline => "null"}
      end
    end
  end
end


text:
layout: page
title: "Steven Earl Frost"
comments: true
description: "blanks"
keywords: "Steven Earl Frost,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Media, Communication and Information

**Classes taught**: MDST 4331, MDST 4871

#### MDST 4331: Gender, Race, Class, and Sexuality in Popular Culture

**Terms taught**: Spring 2017

**Instructor rating**: 4.0

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.43

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.6

**Standard deviation in workload** (raw): 0.0

#### MDST 4871: Special Topics

**Terms taught**: Spring 2017

**Instructor rating**: 5.0

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.83

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.5

**Standard deviation in workload** (raw): 0.0


text:
package com.episode6.hackit.mockspresso.easymock.powermock;

import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.powermock.api.easymock.annotation.MockNice;
import org.powermock.api.easymock.annotation.MockStrict;

import static org.fest.assertions.api.Assertions.assertThat;

/**
 * Tests {@link EasyPowerMockFieldPreparer}
 */
@RunWith(JUnit4.class)
public class EasyPowerMockFieldPreparerTest {

  private EasyPowerMockFieldPreparer mFieldPreparer;

  @Mock Runnable mMockRunnable;
  @org.powermock.api.easymock.annotation.Mock Runnable mMockRunnable2;
  @MockStrict Runnable mStrictRunnable;
  @MockNice Runnable mNiceRunnable;

  @Before
  public void setup() {
    mFieldPreparer = new EasyPowerMockFieldPreparer();
  }

  @Test
  public void testMocksOnThisClass() {
    mFieldPreparer.prepareFields(this);

    assertThat(mMockRunnable)
        .isNotNull()
        .is(Conditions.mockCondition());
    assertThat(mMockRunnable2)
        .isNotNull()
        .is(Conditions.mockCondition());
    assertThat(mStrictRunnable)
        .isNotNull()
        .is(Conditions.mockCondition());
    assertThat(mNiceRunnable)
        .isNotNull()
        .is(Conditions.mockCondition());
  }
}


text:
struct ServicesOptimize : public testing::Test {
  ServicesOptimize()
      : init(init_ss), parameter(parameter_ss), model(context, 0, &model_ss) {}

  std::stringstream init_ss, parameter_ss, model_ss;
  stan::test::unit::instrumented_logger logger;
  stan::callbacks::stream_writer init;
  stan::test::unit::values_writer parameter;
  stan::io::empty_var_context context;
  stan_model model;
};

TEST_F(ServicesOptimize, rosenbrock) {
  unsigned int seed = 0;
  unsigned int chain = 1;
  double init_radius = 0;

  bool save_iterations = true;
  int refresh = 0;
  stan::test::unit::instrumented_interrupt interrupt;

  int return_code = stan::services::optimize::lbfgs(
      model, context, seed, chain, init_radius, 5, 0.001, 1e-12, 10000, 1e-8,
      10000000, 1e-8, 2000, save_iterations, refresh, interrupt, logger, init,
      parameter);

  EXPECT_EQ(logger.call_count(), logger.call_count_info())
      << "all output to info";
  EXPECT_EQ(1, logger.find("Initial log joint probability = -1"));
  EXPECT_EQ(1, logger.find("Optimization terminated normally: "));
  EXPECT_EQ(1, logger.find("  Convergence detected: relative gradient "
                           "magnitude is below tolerance"));

  EXPECT_EQ("0,0\n", init_ss.str());

  ASSERT_EQ(3, parameter.names_.size());
  EXPECT_EQ("lp__", parameter.names_[0]);
  EXPECT_EQ("x", parameter.names_[1]);
  EXPECT_EQ("y", parameter.names_[2]);

  EXPECT_EQ(23, parameter.states_.size());
  EXPECT_FLOAT_EQ(0, parameter.states_.front()[1])
      << "initial value should be (0, 0)";
  EXPECT_FLOAT_EQ(0, parameter.states_.front()[2])
      << "initial value should be (0, 0)";
  EXPECT_FLOAT_EQ(0.99998301, parameter.states_.back()[1])
      << "optimal value should be (1, 1)";
  EXPECT_FLOAT_EQ(0.99996597, parameter.states_.back()[2])
      << "optimal value should be (1, 1)";
  EXPECT_FLOAT_EQ(return_code, 0);
  EXPECT_EQ(22, interrupt.call_count());
}