text:
\documentclass[onecolumn]{article}

\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{verbatim}
\usepackage{microtype}
\usepackage{booktabs}
\usepackage{hyperref}
\usepackage[margin=3cm]{geometry}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{hyperref}
\usepackage{booktabs}

\newcommand{\E}[1]{\ensuremath{\times 10^{#1}}}
\newcommand{\D}[2]{\ensuremath{\frac{\partial #1}{\partial #2}}}
\newcommand{\de}{\ensuremath{\mathrm{d}}}
\newcommand{\dee}{\ensuremath{\ \mathrm{d}}}
\newcommand{\vv}{\ensuremath{\mathbf{}}}

\title{\texttt{StarStruc.jl}: Stellar structure in Julia}
\author{Asher Wasserman}
\date{}

\begin{document}

\maketitle

\section{Introduction}

This document presents a description of a static stellar structure model implemented in \texttt{Julia}, a high-performance dynamical programming language.  The accompanying code can be found at \url{https://github.com/adwasser/StarStruc.jl}.  For carefully considered initial guesses as to the boundary values, the code should converge on a structure model on the order of a few minutes.  For arbitrary initial guesses, the code will likely crash and burn.

\section{Physics}

Stars are fearsome beasts, so we tame them by introducing some simplifying assumptions.  We model stars as non-rotating, time-independent, uniform composition, spherically symmetric cows.  Such domesticated animals still can pose numerical dangers to reckless star-cow wranglers, however.

% Stellar Structure and Evolution, Kippenhahn, Weigert, and Weiss, 2012.

\subsection{Structure equations}

We can concisely write the equations of stellar structure as
\begin{align}
  \D{r}{m} &= \frac{1}{4\pi r^2 \rho} \label{eq:drdm} \\
  \D{\ell}{m} &= \epsilon_n  \label{eq:dldm} \\
  \D{P}{m} &= -\frac{Gm}{4\pi r^4} \label{eq:dPdm} \\
  \D{T}{m} &= -\frac{GmT}{4\pi r^4P} \nabla \label{eq:dTdm}
\end{align}
where $r(m)$ is the radius, $\ell(m)$ is the luminosity, $P(m)$ is the pressure, and $T(m)$ is the temperature.  Our goal is to solve for these four structure function for a specified total mass, $M$, and composition, parameterized as hydrogen mass fraction, $X$, and helium mass fraction $Y$.  What is then left is to specify the equation of state, $\rho(P, T)$, the energy generation per unit mass $\epsilon_n$, the temperature gradient, $\nabla = \partial\log T / \partial\log P$, and the opacity, $\kappa(\rho, T)$.

We assume that the star is a fully ionized ideal gas, so its equation of state is
\begin{equation}
  P(\rho, T) = \frac{\rho}{\mu m_H} kT + \frac{a_\text{rad}}{3} T^4
\end{equation}
where
\begin{equation}
  \mu = \frac{1}{1 + 3X + Y/2}
\end{equation}
is the dimensionless mean molecular weight.  The term on the right accounts for pressure due to radiation and is generally small compared to the gas pressure.

For simplicity, we model energy transport such that convection efficiently transports any energy beyond the adiabatic limit, and so
\begin{align} \nabla = \frac{T}{P}\D{T}{P} =
  \begin{cases}
    \nabla_\text{ad} & \nabla_\text{rad} \ge \nabla_\text{ad} \\
    \nabla_\text{rad} & \nabla_\text{rad} < \nabla_\text{ad}
  \end{cases}
\end{align}
For our assumed ideal gas, $\nabla_\text{ad} = 0.4$, and for a diffusive radiative transport model,
\begin{equation}
  \nabla_\text{rad} = \frac{3}{16\pi a c G}\frac{\kappa \ell P}{m T^4}
\end{equation}

We only model hydrogen burning for energy generation.  Hydrogen burning occurs through the proton-proton chain and the CNO cycle, both of which have their own temperature dependencies.  In the weak electron shielding approximation, we have
\begin{align}
  \epsilon_\text{pp} &= 2.5\E{4} \psi g_\text{11} \rho X_1^2 T_9^{-2/3} \exp\left(-\frac{3.381}{T_9^{1/3}}\right) \text{ erg s}^{-1}\text{ g}^{-1} \\
  \epsilon_\text{CNO} &= 8.24\E{25} g_{14,1} X_\text{CNO} X_1 \rho T_9^{-2/3} \exp\left(-15.231 T_9^{-1/3} - \left(\frac{T_9}{0.8}\right)^2\right) \text{ erg s}^{-1}\text{ g}^{-1} \nonumber
\end{align}
where $T_9 = 10^{-9} \times (T / K)$. Here, $\psi$ accounts for the different branches of the proton-proton chain, and is generally between 1 and 1.5. The polynomial terms $g_{11}$ and $g_{14, 1}$ are given by
\begin{align}
  g_{11} &= 1 + 3.82 T_9 + 1.51 T_9^2 + 0.144 T_9^3 - 0.0114 T_9^4 \\
  g_{14, 1} &= 1 - 2.00 T_9 + 3.41 T_9^2 - 2.43 T_9^3 \nonumber
\end{align}
For the CNO mass fraction, $X_\text{CNO}$, we assume that carbon, nitrogen, and oxygen make up 70\% of the metal mass fraction.

The last missing piece for completely specifying the derivatives is a relevant opacity model for stellar matter.  Here we use the OPAL opacity tables, taken from \url{http://opalopacity.llnl.gov/}, and interpolate between values of $\rho$ and $T$.

\subsection{Boundary conditions}
With all of the above, we have four coupled first-order differential equations.  To solve for our four structure profiles, we need to impose some physically meaningful boundary conditions.  Starting from a mass shell very close to the center, $m_c$, we can use the linearizations of equations \ref{eq:drdm} and \ref{eq:dldm} to get
\begin{align}
  r_c &= \left(\frac{3}{4\pi \rho_c}\right)^{1/3} m_c^{1/3} \\
  \ell_c &= \epsilon_n m_c \nonumber
\end{align}

At the surface, we define our photosphere to be at the radius, $R_s$, where we have an optical depth of $2 / 3$.  Then from hydrostatic equilibrium and the definition of the effective temperature, we have
\begin{align}
  P_s &= \frac{GM}{R_s^2}\frac{2}{3}\frac{1}{\kappa} \\
  L_s &= 4\pi R_s^2 \sigma T_s^4 \nonumber
\end{align}

Since we only have four boundary condition equations with eight boundary values, we will have to make educated guesses for the other four, and evaluate how well we do in creating the four profiles.  For our purposes, we will propose the boundary values of $R_s$, $L_s$, $P_c$, and $T_c$, then use the relations above to create the full set of boundary values.

\section{Numerics}

We follow the strategy of shooting to a fixed point to solve the boundary value problem posed by the section above.  We choose a fixed mass shell at some fraction of the total mass.  We then iteratively propose a new set of boundary values, $\vec{y} = (R_s, L_s, P_c, T_c)$, and use these along with our boundary conditions to integrate the structure equations both outward from the center and inward from the surface, both ending at the fixed point.  We implement a fourth-order Runge-Kutta method for performing these integrations.

We define the mismatch function as
\begin{equation}
  \vec{f}\left(\vec{y}) = (r_\text{in}(m_f) - r_\text{out}(m_f), \ \ell_\text{in}(m_f) - \ell_\text{out}(m_f), \  P_\text{in}(m_f) - P_\text{out}(m_f), \ T_\text{in}(m_f) - T_\text{out}(m_f)\right)
\end{equation}
The mismatch function thus maps the proposed boundary values, $\vec{y}$, to the set of difference between the inward and outward integrations at the fixed point, $m_f$.  Finding a solution to the boundary value problem amounts to finding the zero of the mismatch function.

We approach this task by using a modified Newton-Raphson descent method.  We look at the linearization of $\vec{f}$ about $y$,
\begin{equation}
  \vec{f}(\vec{y} + \delta\vec{y}) \sim \vec{f}(\vec{y}) + J \delta\vec{y}
\end{equation}
Here, $J$ is the Jacobian of $\vec{f}$, defined as
\begin{equation}
  J =
  \begin{pmatrix}
    \D{f_1}{y_1} & \ldots & \D{f_1}{y_n} \\
    \vdots & \ddots & \vdots \\
    \D{f_n}{y_1} & \ldots & \D{f_n}{y_n}
  \end{pmatrix}
\end{equation}

We approximate the Jacobian through the finite difference method.  For each proposed boundary value, $y_i$, we can perturb the initial proposed vector to $\vec{y}_{\Delta_i} = \vec{y} + \Delta y_i \hat{i}$, where $\Delta$ is some small fraction.  The $i$-th column of $J$ is then given by
\begin{equation}
  \vec{J_i} =  \frac{\vec{y}_{\Delta_i} - \vec{y}}{\Delta y_i}
\end{equation}

If we wish to find the zero of $\vec{f}$, we need to choose the step $\delta \vec{y}$ such that $f(\vec{y} + \delta\vec{y}) \rightarrow 0$.  This leads to the proposed step
\begin{equation}
  \delta\vec{y} = -J^{-1}\vec{f}(\vec{y})
\end{equation}
Our next proposed set of boundary values is then given just by $\vec{y} + \delta\vec{y}$.  However, given that we have used only the linear term in the Taylor expansion of $\vec{f}$, this method will only work if we start very close to the true value of $\vec{y}$.  In practice, we will start with some poor guess for $\vec{y}$ for which the Newton-Raphson step will push us too far, leading to wild oscillations.  In order to create a chance for convergence, we down-weight the step $\delta\vec{y}$ by an amount such that $\max_i |\delta y_i / y_i| < 0.1$, and only allow for the full step once all changes are within 10\% of their previous value.

\section{Results}

We tuned the basic algorithm described above to successfully converge for a 4 $M_\odot$ solar metallicity star.  The initial guesses for the boundary values came from \texttt{MESA} through the MESA-Web interface at \url{http://mesa-web.asu.edu/}.  These initial guesses are compared to the converged solution in Table~\ref{tab:results}.  The central temperatures and pressures match quite well, which largely explains the rapid convergence.  The radius converges to a value within a third of the input value, but the luminosity settles on a value close to twice that of the initial guess.

\begin{table}[h]
  \centering
  \begin{tabular}{lllll}
    Value & $R_s$ & $L_s$ & $\log_{10} P_c$ & $\log_{10} T_c$ \\
    \toprule
    Units & $R_\odot$ & $L_\odot$ & dyne cm$^{-2}$ & K \\
    \midrule
    \texttt{StarStruc} & 4.47 & 657.43 & 16.94 & 7.41 \\
    \texttt{MESA} & 3.39 & 318.24 & 16.86 & 7.43 \\
    \bottomrule
  \end{tabular}
  \caption{Comparison of model boundary values with inputs from \texttt{MESA}.}
  \label{tab:results}
\end{table}

\begin{figure}[h]
  \centering
  \includegraphics[width=0.9\linewidth]{mstar4.png}
  \caption{Structure profiles for 4 $M_\odot$ solar metallicity test case.}
\end{figure}

\section{Discussion}

The test case runs in less than two minutes on an Intel 2.6 GHz CPU, with a memory usage of 1.24 Gb.  This is a significant advantage compared to other stellar structure codes written in python, for which each iteration of the Newton-Raphson steps could take around a minute.  The code could be significantly sped up by parallelizing the set of integrations for each computation of the Jacobian, and it is clear that the code would benefit from a more careful treatment of space utilization.

Julia is a different beast than python.  While there are a number of third party numeric libraries out there already for Julia, the community has not yet converged on a unified scientific stack in the same way that python has unified behind numpy and scipy.  I ended up implementing my own Runge-Kutta integrator and my own Newton-Raphson zero finding code, almost directly out of Numerical Recipes, which served my purposes well enough.  Having come from a background in mostly python, learning Julia brought a number of challenges, from relatively minor ones like its one-based array indexing, to trickier ones like the shift from object-oriented programming to a more functional programming style.  My personal verdict is that Julia shows much promise for developing tools to tackle numerically challenging problems, but it is not going to replace python as my general purpose scripting language anytime in the near future.

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


text:
#ifndef GCC_REGRENAME_H
#define GCC_REGRENAME_H

/* We keep linked lists of DU_HEAD structures, each of which describes
   a chain of occurrences of a reg.  */
struct du_head
{
  /* The next chain.  */
  struct du_head *next_chain;
  /* The first and last elements of this chain.  */
  struct du_chain *first, *last;
  /* Describes the register being tracked.  */
  unsigned regno;
  int nregs;

  /* A unique id to be used as an index into the conflicts bitmaps.  */
  unsigned id;
  /* A bitmap to record conflicts with other chains.  */
  bitmap_head conflicts;
  /* Conflicts with untracked hard registers.  */
  HARD_REG_SET hard_conflicts;

  /* Nonzero if the chain crosses a call.  */
  unsigned int need_caller_save_reg:1;
  /* Nonzero if the register is used in a way that prevents renaming,
     such as the SET_DEST of a CALL_INSN or an asm operand that used
     to be a hard register.  */
  unsigned int cannot_rename:1;
};

typedef struct du_head *du_head_p;

/* This struct describes a single occurrence of a register.  */
struct du_chain
{
  /* Links to the next occurrence of the register.  */
  struct du_chain *next_use;

  /* The insn where the register appears.  */
  rtx insn;
  /* The location inside the insn.  */
  rtx *loc;
  /* The register class required by the insn at this location.  */
  ENUM_BITFIELD(reg_class) cl : 16;
};

/* This struct describes data gathered during regrename_analyze about
   a single operand of an insn.  */
typedef struct
{
  /* The number of chains recorded for this operand.  */
  int n_chains;
  /* Holds either the chain for the operand itself, or for the registers in
     a memory operand.  */
  struct du_chain *chains[MAX_REGS_PER_ADDRESS];
  struct du_head *heads[MAX_REGS_PER_ADDRESS];
} operand_rr_info;

/* A struct to hold a vector of operand_rr_info structures describing the
   operands of an insn.  */
typedef struct
{
  operand_rr_info *op_info;
} insn_rr_info;

extern vec<insn_rr_info> insn_rr;

extern void regrename_init (bool);
extern void regrename_finish (void);
extern void regrename_analyze (bitmap);
extern du_head_p regrename_chain_from_id (unsigned int);
extern int find_best_rename_reg (du_head_p, enum reg_class, HARD_REG_SET *,
				 int);
extern void regrename_do_replace (du_head_p, int);

#endif

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.season.scut">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:name=".MApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
        <activity android:name=".RegisterActivity"></activity>
        <activity android:name=".CaseActivity"></activity>
        <activity android:name=".NewCaseActivity"></activity>
        <activity android:name=".NotifyActivity"></activity>
    </application>

</manifest>


text:
NPNetscapeFuncs* g_browser = NULL;

namespace {

NPError NPP_ClientNew(NPMIMEType plugin_type, NPP instance, uint16_t mode,
                int16_t argc, char* argn[], char* argv[], NPSavedData* saved) {
  if (instance == NULL)
    return NPERR_INVALID_INSTANCE_ERROR;

  ClientPlugin* plugin_impl = new ClientPlugin(mode);
  plugin_impl->Initialize(GetModuleHandle(NULL), instance, plugin_type, argc,
                          argn, argv);
  instance->pdata = reinterpret_cast<void*>(plugin_impl);
  return NPERR_NO_ERROR;
}

NPError NPP_ClientDestroy(NPP instance, NPSavedData** save) {
  ClientPlugin* plugin_impl = reinterpret_cast<ClientPlugin*>(instance->pdata);

  if (plugin_impl) {
    plugin_impl->Shutdown();
    delete plugin_impl;
  }

  return NPERR_NO_ERROR;
}

NPError NPP_ClientSetWindow(NPP instance, NPWindow* window_info) {
  if (instance == NULL)
    return NPERR_INVALID_INSTANCE_ERROR;

  if (window_info == NULL)
    return NPERR_GENERIC_ERROR;

  ClientPlugin* plugin_impl = reinterpret_cast<ClientPlugin*>(instance->pdata);

  if (plugin_impl == NULL)
    return NPERR_GENERIC_ERROR;

  HWND window_handle = reinterpret_cast<HWND>(window_info->window);
  if (!plugin_impl->SetWindow(window_handle)) {
    delete plugin_impl;
    return NPERR_GENERIC_ERROR;
  }

  return NPERR_NO_ERROR;
}

}  // namespace

NPError API_CALL NP_ClientGetEntryPoints(NPPluginFuncs* pFuncs) {
  pFuncs->newp = NPP_ClientNew;
  pFuncs->destroy = NPP_ClientDestroy;
  pFuncs->setwindow = NPP_ClientSetWindow;
  return NPERR_NO_ERROR;
}

NPError API_CALL NP_ClientInitialize(NPNetscapeFuncs* pFuncs) {
  g_browser = pFuncs;
  return NPERR_NO_ERROR;
}

NPError API_CALL NP_ClientShutdown(void) {
  g_browser = NULL;
  return NPERR_NO_ERROR;
}

// ClientPlugin Implementation

ClientPlugin::ClientPlugin(int16 mode)
  : mode_(mode) {
}

ClientPlugin::~ClientPlugin() {
}

bool ClientPlugin::Initialize(HINSTANCE module_handle, NPP instance,
                              NPMIMEType mime_type, int16 argc, char* argn[],
                              char* argv[]) {
  RefreshDisplay();
  return true;
}

bool ClientPlugin::SetWindow(HWND parent_window) {
  if (!::IsWindow(parent_window)) {
    // No window created yet. Ignore this call.
    if (!IsWindow())
      return true;
    // Parent window has been destroyed.
    Shutdown();
    return true;
  }

  RECT parent_rect;

  if (IsWindow()) {
    ::GetClientRect(parent_window, &parent_rect);
    SetWindowPos(NULL, &parent_rect, SWP_SHOWWINDOW);
    return true;
  }
  // First time in -- no window created by plugin yet.
  ::GetClientRect(parent_window, &parent_rect);
  Create(parent_window, parent_rect, NULL, WS_CHILD | WS_BORDER);

  UpdateWindow();
  ShowWindow(SW_SHOW);

  return true;
}

void ClientPlugin::Shutdown() {
  if (IsWindow()) {
    DestroyWindow();
  }
}

LRESULT ClientPlugin::OnPaint(UINT message, WPARAM wparam, LPARAM lparam,
                              BOOL& handled) {
  PAINTSTRUCT paint_struct;
  BeginPaint(&paint_struct);
  Paint(paint_struct.hdc);
  EndPaint(&paint_struct);
  return 0;
}

// PrintClient is necessary to support off-screen rendering.
LRESULT ClientPlugin::OnPrintClient(UINT message, WPARAM wparam, LPARAM lparam,
                                    BOOL& handled) {
  Paint(reinterpret_cast<HDC>(wparam));
  return 0;
}

LRESULT ClientPlugin::OnEraseBackGround(UINT message, WPARAM wparam,
                                        LPARAM lparam, BOOL& handled) {
  HDC paint_device_context = reinterpret_cast<HDC>(wparam);
  RECT erase_rect;
  GetClipBox(paint_device_context, &erase_rect);
  HBRUSH brush = CreateSolidBrush(RGB(0, 255, 0));
  FillRect(paint_device_context, &erase_rect, brush);
  DeleteObject(brush);
  return 1;
}

LRESULT ClientPlugin::OnLButtonDown(UINT message, WPARAM wparam, LPARAM lparam,
                                    BOOL& handled) {
  MessageBox(L"You clicked on the client plugin!", L"Client Plugin", MB_OK);
  return 0;
}

void ClientPlugin::RefreshDisplay() {
  if (!IsWindow())
    return;

  InvalidateRect(NULL, TRUE);
  UpdateWindow();
}

void ClientPlugin::Paint(HDC hdc) {
  static LPCWSTR text = L"Left click in the green area for a message box!";

  RECT client_rect;
  GetClientRect(&client_rect);

  int old_mode = SetBkMode(hdc, TRANSPARENT);
  COLORREF old_color = SetTextColor(hdc, RGB(0, 0, 255));

  RECT text_rect = client_rect;
  DrawText(hdc, text, -1, &text_rect, DT_CENTER | DT_CALCRECT);

  client_rect.top = ((client_rect.bottom - client_rect.top)
      - (text_rect.bottom - text_rect.top)) / 2;
  DrawText(hdc, text, -1, &client_rect, DT_CENTER);

  SetBkMode(hdc, old_mode);
  SetTextColor(hdc, old_color);
}

#endif  // OS_WIN


text:
namespace xls {
namespace {

using status_testing::StatusIs;

class BigIntTest : public ::testing::Test {
 protected:
  BigInt MakeBigInt(int64_t value) {
    return BigInt::MakeSigned(SBits(value, 64));
  }

  BigInt MakeBigInt(std::string_view hex_string) {
    std::pair<bool, Bits> sign_magnitude =
        GetSignAndMagnitude(hex_string).value();
    if (sign_magnitude.first) {
      // Negative number (leading '-').
      return BigInt::Negate(BigInt::MakeUnsigned(sign_magnitude.second));
    }
    return BigInt::MakeUnsigned(sign_magnitude.second);
  }
};

TEST_F(BigIntTest, EqualityOperator) {
  auto one = BigInt::MakeUnsigned(UBits(1, 64));
  auto two = BigInt::MakeUnsigned(UBits(2, 64));
  EXPECT_TRUE((one == one));
  EXPECT_FALSE((one == two));
  EXPECT_FALSE((one != one));
  EXPECT_TRUE((one != two));
}

TEST_F(BigIntTest, CopyConstructor) {
  auto original = BigInt::MakeUnsigned(UBits(1, 64));
  auto copy = BigInt(original);

  EXPECT_EQ(original, BigInt::MakeUnsigned(UBits(1, 64)));
  EXPECT_EQ(original, copy);
}

TEST_F(BigIntTest, MoveConstructor) {
  auto original = BigInt::MakeUnsigned(UBits(1, 64));
  auto moved = BigInt(std::move(original));

  EXPECT_EQ(moved, BigInt::MakeUnsigned(UBits(1, 64)));
}

TEST_F(BigIntTest, CopyAssignment) {
  auto original = BigInt::MakeUnsigned(UBits(1, 64));
  auto copy = BigInt();
  copy = original;

  EXPECT_EQ(original, BigInt::MakeUnsigned(UBits(1, 64)));
  EXPECT_EQ(original, copy);
}

// This is a regression test for https://github.com/google/xls/issues/759
// `operator=(BigInt&& other)` used to leak memory
TEST_F(BigIntTest, CopyAssignNoLeak) {
  {
    BigInt x = BigInt::Exp2(1);

    // tests operator=(BigInt&& other)
    x = x / x;

    EXPECT_EQ(x, BigInt::One());
  }
  {
    BigInt x = BigInt::Exp2(1);
    BigInt one = x / x;

    // tests operator=(const BigInt& other)
    x = one;

    EXPECT_EQ(x, BigInt::One());
    EXPECT_EQ(one, BigInt::One());
  }
}

TEST_F(BigIntTest, MoveAssignment) {
  auto original = BigInt::MakeUnsigned(UBits(1, 64));
  auto moved = BigInt();
  moved = std::move(original);

  EXPECT_EQ(moved, BigInt::MakeUnsigned(UBits(1, 64)));
}

TEST_F(BigIntTest, MakeUnsigned) {
  BigInt zero = BigInt::MakeUnsigned(UBits(0, 0));
  EXPECT_EQ(zero.UnsignedBitCount(), 0);
  EXPECT_EQ(zero.ToUnsignedBits(), UBits(0, 0));

  // Round-trip Bits values through BigInt and verify value and bit-width (which
  // should be the minimum to hold the value).
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(1, 64)).ToUnsignedBits(), UBits(1, 1));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(2, 64)).ToUnsignedBits(), UBits(2, 2));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(3, 64)).ToUnsignedBits(), UBits(3, 2));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(4, 64)).ToUnsignedBits(), UBits(4, 3));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(5, 64)).ToUnsignedBits(), UBits(5, 3));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(6, 64)).ToUnsignedBits(), UBits(6, 3));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(7, 64)).ToUnsignedBits(), UBits(7, 3));
  EXPECT_EQ(BigInt::MakeUnsigned(UBits(8, 64)).ToUnsignedBits(), UBits(8, 4));

  EXPECT_EQ(BigInt::MakeUnsigned(UBits(1234567, 64)).ToUnsignedBits(),
            UBits(1234567, 21));

  std::string wide_input = "0xabcd_abcd_1234_1234_aaaa_bbbb_cccc_dddd";
  XLS_ASSERT_OK_AND_ASSIGN(Bits wide_bits, ParseNumber(wide_input));
  EXPECT_EQ(BigInt::MakeUnsigned(wide_bits).ToUnsignedBits().ToString(
                FormatPreference::kHex),
            wide_input);
}

TEST_F(BigIntTest, MakeSigned) {
  BigInt zero = BigInt::MakeSigned(UBits(0, 0));
  EXPECT_EQ(zero.SignedBitCount(), 0);
  EXPECT_EQ(zero.ToSignedBits(), UBits(0, 0));

  // Round-trip a signed Bits values through BigInt and verify value and
  // bit-width (which should be the minimum to hold the value in twos-complement
  // representation).
  EXPECT_EQ(BigInt::MakeSigned(SBits(0, 1)).ToSignedBits(), SBits(0, 0));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 2)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 3)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 4)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 5)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 6)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 7)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 8)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(1, 64)).ToSignedBits(), SBits(1, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(2, 64)).ToSignedBits(), SBits(2, 3));
  EXPECT_EQ(BigInt::MakeSigned(SBits(3, 64)).ToSignedBits(), SBits(3, 3));
  EXPECT_EQ(BigInt::MakeSigned(SBits(4, 64)).ToSignedBits(), SBits(4, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(5, 64)).ToSignedBits(), SBits(5, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(6, 64)).ToSignedBits(), SBits(6, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(7, 64)).ToSignedBits(), SBits(7, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(8, 64)).ToSignedBits(), SBits(8, 5));
  EXPECT_EQ(BigInt::MakeSigned(SBits(127, 8)).ToSignedBits(), SBits(127, 8));

  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 1)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 2)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 3)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 4)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 5)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 6)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 7)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 8)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-1, 64)).ToSignedBits(), SBits(-1, 1));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-2, 64)).ToSignedBits(), SBits(-2, 2));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-3, 64)).ToSignedBits(), SBits(-3, 3));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-4, 64)).ToSignedBits(), SBits(-4, 3));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-5, 64)).ToSignedBits(), SBits(-5, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-6, 64)).ToSignedBits(), SBits(-6, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-7, 64)).ToSignedBits(), SBits(-7, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-8, 64)).ToSignedBits(), SBits(-8, 4));
  EXPECT_EQ(BigInt::MakeSigned(SBits(-128, 8)).ToSignedBits(), SBits(-128, 8));

  EXPECT_EQ(BigInt::MakeSigned(UBits(1234567, 64)).ToSignedBits(),
            UBits(1234567, 22));

  std::string wide_input = "0xabcd_abcd_1234_1234_aaaa_bbbb_cccc_dddd";
  XLS_ASSERT_OK_AND_ASSIGN(Bits wide_bits, ParseNumber(wide_input));
  EXPECT_EQ(BigInt::MakeSigned(wide_bits).ToSignedBits().ToString(
                FormatPreference::kHex),
            wide_input);
}

TEST_F(BigIntTest, Zero) {
  BigInt zero = BigInt::Zero();
  EXPECT_EQ(zero.UnsignedBitCount(), 0);
  EXPECT_EQ(zero.ToUnsignedBits(), UBits(0, 0));
}

TEST_F(BigIntTest, One) {
  BigInt one = BigInt::One();
  EXPECT_EQ(one.UnsignedBitCount(), 1);
  EXPECT_EQ(one.ToUnsignedBits(), UBits(1, 1));
}

TEST_F(BigIntTest, ToSignedBitsWithBitCount) {
  XLS_ASSERT_OK_AND_ASSIGN(
      auto small_positive,
      BigInt::MakeSigned(SBits(42, 64)).ToSignedBitsWithBitCount(32));
  EXPECT_EQ(small_positive, SBits(42, 32));

  EXPECT_THAT(BigInt::MakeSigned(SBits(3e9, 64)).ToSignedBitsWithBitCount(32),
              StatusIs(absl::StatusCode::kInvalidArgument));

  XLS_ASSERT_OK_AND_ASSIGN(
      auto small_negative,
      BigInt::MakeSigned(SBits(-42, 64)).ToSignedBitsWithBitCount(32));
  EXPECT_EQ(small_negative, SBits(-42, 32));

  EXPECT_THAT(BigInt::MakeSigned(SBits(-3e9, 64)).ToSignedBitsWithBitCount(32),
              StatusIs(absl::StatusCode::kInvalidArgument));
}

TEST_F(BigIntTest, ToUnsignedBitsWithBitCount) {
  XLS_ASSERT_OK_AND_ASSIGN(
      auto small_positive,
      BigInt::MakeUnsigned(UBits(42, 64)).ToUnsignedBitsWithBitCount(32));
  EXPECT_EQ(small_positive, UBits(42, 32));

  EXPECT_THAT(
      BigInt::MakeUnsigned(UBits(6e9, 64)).ToUnsignedBitsWithBitCount(32),
      StatusIs(absl::StatusCode::kInvalidArgument));
}

TEST_F(BigIntTest, SignedBitCount) {
  EXPECT_EQ(MakeBigInt(0).SignedBitCount(), 0);
  EXPECT_EQ(MakeBigInt(-1).SignedBitCount(), 1);
  EXPECT_EQ(MakeBigInt(-2).SignedBitCount(), 2);
  EXPECT_EQ(MakeBigInt(-3).SignedBitCount(), 3);
  EXPECT_EQ(MakeBigInt(-4).SignedBitCount(), 3);
  EXPECT_EQ(MakeBigInt(1).SignedBitCount(), 2);
  EXPECT_EQ(MakeBigInt(127).SignedBitCount(), 8);
  EXPECT_EQ(MakeBigInt(128).SignedBitCount(), 9);
  EXPECT_EQ(MakeBigInt(-128).SignedBitCount(), 8);
  EXPECT_EQ(MakeBigInt(-129).SignedBitCount(), 9);
}

TEST_F(BigIntTest, UnignedBitCount) {
  EXPECT_EQ(MakeBigInt(0).UnsignedBitCount(), 0);
  EXPECT_EQ(MakeBigInt(1).UnsignedBitCount(), 1);
  EXPECT_EQ(MakeBigInt(127).UnsignedBitCount(), 7);
  EXPECT_EQ(MakeBigInt(128).UnsignedBitCount(), 8);
  EXPECT_EQ(MakeBigInt(129).UnsignedBitCount(), 8);
}

TEST_F(BigIntTest, Add) {
  EXPECT_EQ(BigInt::Add(MakeBigInt(0), MakeBigInt(0)), MakeBigInt(0));
  EXPECT_EQ(BigInt::Add(MakeBigInt(42), MakeBigInt(123)), MakeBigInt(165));
  EXPECT_EQ(
      BigInt::Add(MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
                  MakeBigInt("0x1")),
      MakeBigInt("0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000"));
  EXPECT_EQ(
      BigInt::Add(
          MakeBigInt("0xabcd_ffff_1234_aaaa_0101_3333_4444_1328_abcd_0042"),
          MakeBigInt("0xffff_1234_aaaa_0101_3333_4444_1328_abcd_0042_0033")),
      MakeBigInt("0x1_abcd_1233_bcde_abab_3434_7777_576c_bef5_ac0f_0075"));
}

TEST_F(BigIntTest, Sub) {
  EXPECT_EQ(BigInt::Sub(MakeBigInt(42), MakeBigInt(123)), MakeBigInt(-81));
  EXPECT_EQ(
      BigInt::Sub(
          MakeBigInt("0xabcd_ffff_1234_aaaa_0101_3333_4444_1328_abcd_0042"),
          MakeBigInt("0xffff_1234_aaaa_0101_3333_4444_1328_abcd_0042_0033")),
      MakeBigInt("-0x5431_1235_9875_5657_3232_1110_cee4_98a4_5474_fff1"));
}

TEST_F(BigIntTest, Exp2) {
  constexpr int many_bits = 33;
  EXPECT_EQ(BigInt::Exp2(0), BigInt::One());
  EXPECT_EQ(BigInt::Exp2(1), BigInt::MakeUnsigned(UBits(2, many_bits)));
  EXPECT_EQ(BigInt::Exp2(2), BigInt::MakeUnsigned(UBits(4, many_bits)));
  EXPECT_EQ(BigInt::Exp2(32),
            BigInt::MakeUnsigned(UBits(4294967296ul, many_bits)));
}

TEST_F(BigIntTest, Negate) {
  EXPECT_EQ(BigInt::Negate(MakeBigInt(0)), MakeBigInt(0));
  EXPECT_EQ(BigInt::Negate(MakeBigInt(123456)), MakeBigInt(-123456));
  EXPECT_EQ(BigInt::Negate(
                MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff")),
            MakeBigInt("-0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"));
}

TEST_F(BigIntTest, Absolute) {
  EXPECT_EQ(BigInt::Absolute(MakeBigInt(0)), MakeBigInt(0));

  EXPECT_EQ(BigInt::Absolute(MakeBigInt(-1)), MakeBigInt(1));
  EXPECT_EQ(BigInt::Absolute(MakeBigInt(1)), MakeBigInt(1));

  EXPECT_EQ(BigInt::Absolute(MakeBigInt(-37)), MakeBigInt(37));
  EXPECT_EQ(BigInt::Absolute(MakeBigInt(37)), MakeBigInt(37));

  EXPECT_EQ(BigInt::Absolute(MakeBigInt(-9223372036854775807ll)),
            MakeBigInt(9223372036854775807ll));
  EXPECT_EQ(BigInt::Absolute(MakeBigInt(9223372036854775807ll)),
            MakeBigInt(9223372036854775807ll));
}

TEST_F(BigIntTest, Multiply) {
  EXPECT_EQ(BigInt::Mul(MakeBigInt(0), MakeBigInt(0)), MakeBigInt(0));
  EXPECT_EQ(BigInt::Mul(MakeBigInt(123456), MakeBigInt(0)), MakeBigInt(0));
  EXPECT_EQ(BigInt::Mul(MakeBigInt(123456), MakeBigInt(1)), MakeBigInt(123456));

  EXPECT_EQ(BigInt::Mul(MakeBigInt(1000), MakeBigInt(42)), MakeBigInt(42000));
  EXPECT_EQ(BigInt::Mul(MakeBigInt(-1000), MakeBigInt(42)), MakeBigInt(-42000));
  EXPECT_EQ(BigInt::Mul(MakeBigInt(-1000), MakeBigInt(-42)), MakeBigInt(42000));

  EXPECT_EQ(
      BigInt::Mul(MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
                  MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff")),
      MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe_0000_0000_"
                 "0000_0000_0000_0000_0000_0000_0001"));
}

TEST_F(BigIntTest, Divide) {
  EXPECT_EQ(BigInt::Div(MakeBigInt(0), MakeBigInt(10)), MakeBigInt(0));

  // Rounding should match C semantics.
  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(2)), MakeBigInt(10 / 2));
  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(3)), MakeBigInt(10 / 3));
  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(4)), MakeBigInt(10 / 4));

  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(2)), MakeBigInt(-10 / 2));
  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(3)), MakeBigInt(-10 / 3));
  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(4)), MakeBigInt(-10 / 4));

  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(-2)), MakeBigInt(10 / -2));
  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(-3)), MakeBigInt(10 / -3));
  EXPECT_EQ(BigInt::Div(MakeBigInt(10), MakeBigInt(-4)), MakeBigInt(10 / -4));

  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(-2)), MakeBigInt(-10 / -2));
  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(-3)), MakeBigInt(-10 / -3));
  EXPECT_EQ(BigInt::Div(MakeBigInt(-10), MakeBigInt(-4)), MakeBigInt(-10 / -4));

  EXPECT_EQ(
      BigInt::Div(
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff")),
      MakeBigInt(1));

  EXPECT_EQ(
      BigInt::Div(
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
          MakeBigInt("0xffff_ffff")),
      MakeBigInt("0x1_0000_0001_0000_0001_0000_0001_0000_0001"));
}

TEST_F(BigIntTest, Modulus) {
  EXPECT_EQ(BigInt::Mod(MakeBigInt(0), MakeBigInt(10)), MakeBigInt(0));

  // Result should match C semantics.
  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(2)), MakeBigInt(10 % 2));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(3)), MakeBigInt(10 % 3));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(4)), MakeBigInt(10 % 4));

  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(2)), MakeBigInt(-10 % 2));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(3)), MakeBigInt(-10 % 3));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(4)), MakeBigInt(-10 % 4));

  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(-2)), MakeBigInt(10 % -2));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(-3)), MakeBigInt(10 % -3));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(10), MakeBigInt(-4)), MakeBigInt(10 % -4));

  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(-2)), MakeBigInt(-10 % -2));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(-3)), MakeBigInt(-10 % -3));
  EXPECT_EQ(BigInt::Mod(MakeBigInt(-10), MakeBigInt(-4)), MakeBigInt(-10 % -4));

  EXPECT_EQ(
      BigInt::Mod(
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff")),
      MakeBigInt(0));

  EXPECT_EQ(
      BigInt::Mod(
          MakeBigInt("0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"),
          MakeBigInt("0xfff_ffff")),
      MakeBigInt("0xf_ffff"));
}

TEST_F(BigIntTest, LessThan) {
  EXPECT_TRUE(BigInt::LessThan(MakeBigInt(2), MakeBigInt(10)));
  EXPECT_FALSE(BigInt::LessThan(MakeBigInt(10), MakeBigInt(10)));
  EXPECT_FALSE(BigInt::LessThan(MakeBigInt(12), MakeBigInt(10)));

  EXPECT_TRUE(MakeBigInt(2) < MakeBigInt(10));
  EXPECT_FALSE(MakeBigInt(10) < MakeBigInt(10));
  EXPECT_FALSE(MakeBigInt(12) < MakeBigInt(10));
}

TEST_F(BigIntTest, GreaterThan) {
  EXPECT_FALSE(BigInt::GreaterThan(MakeBigInt(2), MakeBigInt(10)));
  EXPECT_FALSE(BigInt::GreaterThan(MakeBigInt(10), MakeBigInt(10)));
  EXPECT_TRUE(BigInt::GreaterThan(MakeBigInt(12), MakeBigInt(10)));

  EXPECT_FALSE(MakeBigInt(2) > MakeBigInt(10));
  EXPECT_FALSE(MakeBigInt(10) > MakeBigInt(10));
  EXPECT_TRUE(MakeBigInt(12) > MakeBigInt(10));
}

TEST_F(BigIntTest, LessThanEqual) {
  EXPECT_TRUE(MakeBigInt(2) <= MakeBigInt(10));
  EXPECT_TRUE(MakeBigInt(10) <= MakeBigInt(10));
  EXPECT_FALSE(MakeBigInt(12) <= MakeBigInt(10));
}

TEST_F(BigIntTest, GreaterThanEqual) {
  EXPECT_FALSE(MakeBigInt(2) >= MakeBigInt(10));
  EXPECT_TRUE(MakeBigInt(10) >= MakeBigInt(10));
  EXPECT_TRUE(MakeBigInt(12) >= MakeBigInt(10));
}

TEST_F(BigIntTest, IsEven) {
  EXPECT_TRUE(BigInt::IsEven(MakeBigInt(-4)));
  EXPECT_FALSE(BigInt::IsEven(MakeBigInt(-3)));
  EXPECT_TRUE(BigInt::IsEven(MakeBigInt(-2)));
  EXPECT_FALSE(BigInt::IsEven(MakeBigInt(-1)));
  EXPECT_TRUE(BigInt::IsEven(MakeBigInt(0)));
  EXPECT_FALSE(BigInt::IsEven(MakeBigInt(1)));
  EXPECT_TRUE(BigInt::IsEven(MakeBigInt(2)));
  EXPECT_FALSE(BigInt::IsEven(MakeBigInt(3)));
  EXPECT_TRUE(BigInt::IsEven(MakeBigInt(4)));
}

TEST_F(BigIntTest, IsPowerOfTwo) {
  EXPECT_FALSE(BigInt::IsPowerOfTwo(MakeBigInt(-2)));
  EXPECT_FALSE(BigInt::IsPowerOfTwo(MakeBigInt(-1)));
  EXPECT_FALSE(BigInt::IsPowerOfTwo(MakeBigInt(0)));

  EXPECT_FALSE(BigInt::IsPowerOfTwo(BigInt::Exp2(129) - BigInt::One()));
  EXPECT_FALSE(BigInt::IsPowerOfTwo(BigInt::Exp2(129) + BigInt::One()));

  EXPECT_TRUE(BigInt::IsPowerOfTwo(MakeBigInt(1)));
  EXPECT_TRUE(BigInt::IsPowerOfTwo(MakeBigInt(2)));
  EXPECT_TRUE(BigInt::IsPowerOfTwo(MakeBigInt(4)));
  EXPECT_TRUE(BigInt::IsPowerOfTwo(BigInt::Exp2(129)));
}

TEST_F(BigIntTest, CeilingLog2) {
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(0)),
            std::numeric_limits<int64_t>::min());

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(1)), 0);

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(2)), 1);

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(3)), 2);
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(4)), 2);

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(5)), 3);
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(6)), 3);
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(7)), 3);
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(8)), 3);

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(9)), 4);
  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(15)), 4);

  EXPECT_EQ(BigInt::CeilingLog2(MakeBigInt(4611686018427387903ul)), 62);
  EXPECT_EQ(BigInt::CeilingLog2(BigInt::Exp2(62) - BigInt::One()), 62);

  EXPECT_EQ(BigInt::CeilingLog2(BigInt::Exp2(128)), 128);
  EXPECT_EQ(BigInt::CeilingLog2(BigInt::Exp2(128) - BigInt::One()), 128);

  EXPECT_EQ(BigInt::CeilingLog2(BigInt::Exp2(128) + BigInt::One()), 129);
  EXPECT_EQ(BigInt::CeilingLog2(BigInt::Exp2(129)), 129);
}

TEST_F(BigIntTest, FactorizePowerOfTwo) {
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(0));
    EXPECT_EQ(odd, MakeBigInt(0));
    EXPECT_EQ(exponent, 0);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(1));
    EXPECT_EQ(odd, MakeBigInt(1));
    EXPECT_EQ(exponent, 0);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(2));
    EXPECT_EQ(odd, MakeBigInt(1));
    EXPECT_EQ(exponent, 1);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(3));
    EXPECT_EQ(odd, MakeBigInt(3));
    EXPECT_EQ(exponent, 0);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(4));
    EXPECT_EQ(odd, MakeBigInt(1));
    EXPECT_EQ(exponent, 2);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(6));
    EXPECT_EQ(odd, MakeBigInt(3));
    EXPECT_EQ(exponent, 1);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(40));
    EXPECT_EQ(odd, MakeBigInt(5));
    EXPECT_EQ(exponent, 3);
  }
  {
    auto [odd, exponent] =
        BigInt::FactorizePowerOfTwo(MakeBigInt(7) * BigInt::Exp2(129));
    EXPECT_EQ(odd, MakeBigInt(7));
    EXPECT_EQ(exponent, 129);
  }

  // negative
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(-1));
    EXPECT_EQ(odd, MakeBigInt(-1));
    EXPECT_EQ(exponent, 0);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(-2));
    EXPECT_EQ(odd, MakeBigInt(-1));
    EXPECT_EQ(exponent, 1);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(-3));
    EXPECT_EQ(odd, MakeBigInt(-3));
    EXPECT_EQ(exponent, 0);
  }
  {
    auto [odd, exponent] = BigInt::FactorizePowerOfTwo(MakeBigInt(-4));
    EXPECT_EQ(odd, MakeBigInt(-1));
    EXPECT_EQ(exponent, 2);
  }
}

}  // namespace
}  // namespace xls


text:
package com.proofpoint.audit.testing;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.auto.value.AutoValue;
import com.proofpoint.audit.AuditLogger;
import com.proofpoint.tracetoken.TraceToken;

import javax.annotation.Nullable;
import java.io.IOException;

import static com.proofpoint.audit.testing.TestingAuditLogger.AuditWrapper.auditWrapper;
import static com.proofpoint.tracetoken.TraceTokenManager.getCurrentTraceToken;
import static java.util.Objects.requireNonNull;

public class TestingAuditLogger<T>
        implements AuditLogger<T>
{
    private final String type;
    private final ObjectMapper objectMapper;
    private final TestingAuditLog auditLog;

    TestingAuditLogger(Class<T> recordClass, ObjectMapper objectMapper, TestingAuditLog auditLog)
    {
        type = recordClass.getCanonicalName();
        this.objectMapper = requireNonNull(objectMapper, "objectMapper is null");
        this.auditLog = requireNonNull(auditLog, "auditLog is null");
    }

    @Override
    public void audit(T record)
    {
        Object value;
        try {
            String json = objectMapper.writeValueAsString(auditWrapper(type, record));
            value = objectMapper.readValue(json, Object.class);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }

        auditLog.add(value);
    }

    @AutoValue
    abstract static class AuditWrapper
    {
        // "time" is intentionally omitted

        @JsonProperty
        public abstract String getType();

        @Nullable
        @JsonProperty
        public abstract TraceToken getTraceToken();

        @JsonUnwrapped
        public abstract Object getObject();

        public static TestingAuditLogger.AuditWrapper auditWrapper(String type, Object object) {
            return new AutoValue_TestingAuditLogger_AuditWrapper(type, getCurrentTraceToken(), object);
        }
    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;

namespace HOLMS.Types.Supply.RPC {
  public static partial class PricingOverrideSvc
  {
    static readonly string __ServiceName = "holms.types.supply.rpc.PricingOverrideSvc";

    static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.PricingDetailsRequest> __Marshaller_PricingDetailsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.PricingDetailsRequest.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.PricingDetailsResponse> __Marshaller_PricingDetailsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.PricingDetailsResponse.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.PricingUpdateRequest> __Marshaller_PricingUpdateRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.PricingUpdateRequest.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.PricingUpdateResponse> __Marshaller_PricingUpdateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.PricingUpdateResponse.Parser.ParseFrom);

    static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.PricingDetailsRequest, global::HOLMS.Types.Supply.RPC.PricingDetailsResponse> __Method_AllForDates = new grpc::Method<global::HOLMS.Types.Supply.RPC.PricingDetailsRequest, global::HOLMS.Types.Supply.RPC.PricingDetailsResponse>(
        grpc::MethodType.Unary,
        __ServiceName,
        "AllForDates",
        __Marshaller_PricingDetailsRequest,
        __Marshaller_PricingDetailsResponse);

    static readonly grpc::Method<global::HOLMS.Types.Supply.RPC.PricingUpdateRequest, global::HOLMS.Types.Supply.RPC.PricingUpdateResponse> __Method_InsertOrUpdatePrices = new grpc::Method<global::HOLMS.Types.Supply.RPC.PricingUpdateRequest, global::HOLMS.Types.Supply.RPC.PricingUpdateResponse>(
        grpc::MethodType.Unary,
        __ServiceName,
        "InsertOrUpdatePrices",
        __Marshaller_PricingUpdateRequest,
        __Marshaller_PricingUpdateResponse);

    /// Service descriptor
    public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
    {
      get { return global::HOLMS.Types.Supply.RPC.PricingOverrideSvcReflection.Descriptor.Services[0]; }
    }

    /// Base class for server-side implementations of PricingOverrideSvc
    public abstract partial class PricingOverrideSvcBase
    {
      public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.PricingDetailsResponse> AllForDates(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

      public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.PricingUpdateResponse> InsertOrUpdatePrices(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

    }

    /// Client for PricingOverrideSvc
    public partial class PricingOverrideSvcClient : grpc::ClientBase<PricingOverrideSvcClient>
    {
      /// Creates a new client for PricingOverrideSvc
      /// <param name="channel">The channel to use to make remote calls.</param>
      public PricingOverrideSvcClient(grpc::Channel channel) : base(channel)
      {
      }
      /// Creates a new client for PricingOverrideSvc that uses a custom <c>CallInvoker</c>.
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public PricingOverrideSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
      {
      }
      /// Protected parameterless constructor to allow creation of test doubles.
      protected PricingOverrideSvcClient() : base()
      {
      }
      /// Protected constructor to allow creation of configured clients.
      /// <param name="configuration">The client configuration.</param>
      protected PricingOverrideSvcClient(ClientBaseConfiguration configuration) : base(configuration)
      {
      }

      public virtual global::HOLMS.Types.Supply.RPC.PricingDetailsResponse AllForDates(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return AllForDates(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual global::HOLMS.Types.Supply.RPC.PricingDetailsResponse AllForDates(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_AllForDates, null, options, request);
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.PricingDetailsResponse> AllForDatesAsync(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return AllForDatesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.PricingDetailsResponse> AllForDatesAsync(global::HOLMS.Types.Supply.RPC.PricingDetailsRequest request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_AllForDates, null, options, request);
      }
      public virtual global::HOLMS.Types.Supply.RPC.PricingUpdateResponse InsertOrUpdatePrices(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return InsertOrUpdatePrices(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual global::HOLMS.Types.Supply.RPC.PricingUpdateResponse InsertOrUpdatePrices(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_InsertOrUpdatePrices, null, options, request);
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.PricingUpdateResponse> InsertOrUpdatePricesAsync(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return InsertOrUpdatePricesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.PricingUpdateResponse> InsertOrUpdatePricesAsync(global::HOLMS.Types.Supply.RPC.PricingUpdateRequest request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_InsertOrUpdatePrices, null, options, request);
      }
      /// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
      protected override PricingOverrideSvcClient NewInstance(ClientBaseConfiguration configuration)
      {
        return new PricingOverrideSvcClient(configuration);
      }
    }

    /// Creates service definition that can be registered with a server
    /// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
    public static grpc::ServerServiceDefinition BindService(PricingOverrideSvcBase serviceImpl)
    {
      return grpc::ServerServiceDefinition.CreateBuilder()
          .AddMethod(__Method_AllForDates, serviceImpl.AllForDates)
          .AddMethod(__Method_InsertOrUpdatePrices, serviceImpl.InsertOrUpdatePrices).Build();
    }

  }
}
#endregion


text:
package org.apache.wicket.markup.html.header.threelayers;

/**
 * @author dashorst
 */
public class MeldingPage extends AbstractMeldingPage
{
	/** For serialization. */
	private static final long serialVersionUID = 1L;

	/**
	 * Construct.
	 */
	public MeldingPage()
	{
	}
}


text:
#import <XCTest/XCTest.h>
#import "IRErrorProvider.h"

@interface IRErrorProviderSpec : XCTestCase

@end

@implementation IRErrorProviderSpec

- (void)setUp {
    [super setUp];
}

- (void)tearDown {
    [super tearDown];
}

- (void)testGeneratingAGenericError {
    NSError *error = [IRErrorProvider genericError];
    XCTAssertEqualObjects(error.userInfo[NSLocalizedDescriptionKey],@"An Error has occurred");
}

- (void)testReturningAnErrorWithACustomMessage {
    NSError *error = [IRErrorProvider errorWithMessage:@"my-message" errorCode:1000];
    XCTAssertEqualObjects(error.userInfo[NSLocalizedDescriptionKey],@"my-message");
    XCTAssertEqual(error.code,1000);
}

@end


text:
"""
Created on Feb 15, 2018

@author: Tyranic-Moron
"""
from twisted.plugin import IPlugin
from pymoronbot.moduleinterface import IModule
from pymoronbot.modules.commandinterface import BotCommand
from zope.interface import implementer

import datetime
import re
import os
from collections import OrderedDict

from croniter import croniter
from twisted.internet import task
from twisted.internet import reactor
# from pytimeparse.timeparse import timeparse
from ruamel.yaml import YAML, yaml_object
from six import iteritems

from pymoronbot.message import IRCMessage
from pymoronbot.response import IRCResponse, ResponseType
from pymoronbot.channel import IRCChannel
# from pymoronbot.utils import string

yaml = YAML()

@yaml_object(yaml)
class Task(object):
    yaml_tag = u'!Task'

    def __init__(self, type, timeStr, command, params, user, channel, bot):
        """
        @param type: str
        @param timeStr: str
        @param command: str
        @param params: list[str]
        @param user: str
        @param channel: str
        @param bot: MoronBot
        """
        self.type = type
        self.timeStr = timeStr
        self.commandStr = command
        self.params = params
        self.user = user
        self.channel = channel
        self.task = None

        # these will be set by self.reInit()
        self.bot = None
        self.command = None
        self.cron = None
        self.nextTime = None
        self.cronStr = None

        self.reInit(bot)

    def reInit(self, bot):
        self.bot = bot
        triggers = bot.moduleHandler.mappedTriggers
        self.command = triggers[self.commandStr].execute

        self.cronStr = {
            'cron': self.timeStr
        }[self.type]

        self.cron = croniter(self.cronStr, datetime.datetime.utcnow())
        self.nextTime = self.cron.get_next(datetime.datetime)

    def start(self):
        delta = self.nextTime - datetime.datetime.utcnow()
        seconds = delta.total_seconds()
        self.task = task.deferLater(reactor, seconds, self.activate)
        self.task.addCallback(self.cycle)

    def activate(self):
        commandStr = u'{}{} {}'.format(self.bot.commandChar, self.commandStr,
                                       u' '.join(self.params))
        message = IRCMessage('PRIVMSG', self.user, IRCChannel(self.channel),
                             commandStr,
                             self.bot)

        return self.command(message)

    def cycle(self, response):
        self.bot.sendResponse(response)
        if self.type in ['cron']:
            self.nextTime = self.cron.get_next(datetime.datetime)
            self.start()

    def stop(self):
        if self.task:
            self.task.cancel()

    @classmethod
    def to_yaml(cls, representer, node):
        # trim out complex objects and things we can recreate
        skip = ['bot', 'task', 'command', 'cron', 'nextTime']
        cleanedTask = dict((k, v)
                           for (k, v) in node.__dict__.items()
                           if k not in skip)
        return representer.represent_mapping(cls.yaml_tag, cleanedTask)

@implementer(IPlugin, IModule)
class Schedule(BotCommand):
    def triggers(self):
        return ['schedule']

    def _cron(self, message):
        """cron <min> <hour> <day> <month> <day of week> <task name> <command> (<params>)
        - schedules a repeating task using cron syntax https://crontab.guru/"""
        if len(message.ParameterList) < 7:
            return IRCResponse(ResponseType.Say,
                               u'{}'.format(re.sub(r"\s+", u" ",
                                                   self._cron.__doc__)),
                               message.ReplyTo)

        taskName = message.ParameterList[6]
        if taskName in self.schedule:
            response = u'There is already a scheduled task called {!r}'.format(taskName)
            return IRCResponse(ResponseType.Say, response, message.ReplyTo)

        command = message.ParameterList[7].lower()
        if command not in self.bot.moduleHandler.mappedTriggers:
            return IRCResponse(ResponseType.Say,
                               u'{!r} is not a recognized command'.format(command),
                               message.ReplyTo)

        params = message.ParameterList[8:]

        cronStr = u' '.join(message.ParameterList[1:6])

        self.schedule[taskName] = Task('cron', cronStr, command, params,
                                       message.User.String,
                                       message.Channel.Name,
                                       self.bot)
        self.schedule[taskName].start()

        self._saveSchedule()

        return IRCResponse(ResponseType.Say,
                           u'Task {!r} created! Next execution: {}'
                           .format(taskName, self.schedule[taskName].nextTime),
                           message.ReplyTo)

    def _list(self, message):
        """list - lists scheduled task titles with their next execution time.
        * after the time indicates a repeating task"""
        taskList = [u'{} ({}){}'.format(n, t.nextTime, '*' if t.type in ['cron'] else '')
                    for n, t in iteritems(self.schedule)]
        tasks = u'Scheduled Tasks: ' + u', '.join(taskList)
        return IRCResponse(ResponseType.Say, tasks, message.ReplyTo)

    def _show(self, message):
        """show <task name> - gives you detailed information
        for the named task"""
        if len(message.ParameterList) < 2:
            return IRCResponse(ResponseType.Say,
                               u'Show which task?',
                               message.ReplyTo)

        taskName = message.ParameterList[1]

        if taskName not in self.schedule:
            return IRCResponse(ResponseType.Say,
                               u'Task {!r} is unknown'.format(taskName),
                               message.ReplyTo)

        t = self.schedule[taskName]
        return IRCResponse(ResponseType.Say,
                           u'{} {} {} {} | {}'
                           .format(t.type, t.timeStr, t.commandStr,
                                   u' '.join(t.params), t.nextTime),
                           message.ReplyTo)

    def _stop(self, message):
        """stop <task name> - stops the named task"""
        if len(message.ParameterList) < 2:
            return IRCResponse(ResponseType.Say,
                               u'Stop which task?',
                               message.ReplyTo)

        taskName = message.ParameterList[1]

        if taskName not in self.schedule:
            return IRCResponse(ResponseType.Say,
                               u'Task {!r} is unknown'.format(taskName),
                               message.ReplyTo)

        self.schedule[taskName].stop()
        del self.schedule[taskName]

        self._saveSchedule()

        return IRCResponse(ResponseType.Say,
                           u'Task {!r} stopped'.format(taskName),
                           message.ReplyTo)

    subCommands = OrderedDict([
        (u'cron', _cron),
        (u'list', _list),
        (u'show', _show),
        (u'stop', _stop),
    ])

    def help(self, query):
        """
        @type query: list[str]
        @rtype str
        """
        if len(query) > 1:
            subCommand = query[1].lower()
            if subCommand in self.subCommands:
                sub = re.sub(r"\s+", u" ",
                             self.subCommands[subCommand].__doc__)
                return u'{1}schedule {0}'.format(sub, self.bot.commandChar)
            else:
                return self._unrecognizedSubCommand(subCommand)
        else:
            return self._helpText()

    def _unrecognizedSubCommand(self, subCommand):
        return (u"unrecognized sub-command '{}', "
                u"available sub-commands for schedule are: {}"
                .format(subCommand, u', '.join(self.subCommands.keys())))

    def _helpText(self):
        return (u"{1}schedule ({0}) - manages scheduled tasks. "
                u"Use '{1}help schedule <sub-command> for sub-command help."
                .format(u'/'.join(self.subCommands.keys()),
                        self.bot.commandChar))

    def _saveSchedule(self):
        path = os.path.join(self.bot.dataPath, 'schedule.yaml')
        with open(path, 'w') as file:
            yaml.dump(self.schedule, file)

    def onLoad(self):
        # load schedule from data file
        try:
            path = os.path.join(self.bot.dataPath, 'schedule.yaml')
            with open(path, 'r') as file:
                self.schedule = yaml.load(file)

            if not self.schedule:
                self.schedule = {}

            # start them all going
            for _, t in iteritems(self.schedule):
                t.reInit(self.bot)
                t.start()
        except FileNotFoundError:
            self.schedule = {}

    def onUnload(self):
        # cancel everything
        for _, t in iteritems(self.schedule):
            t.stop()

    def execute(self, message):
        """
        @type message: IRCMessage
        """
        if len(message.ParameterList) > 0:
            subCommand = message.ParameterList[0].lower()
            if subCommand not in self.subCommands:
                return IRCResponse(ResponseType.Say,
                                   self._unrecognizedSubCommand(subCommand),
                                   message.ReplyTo)
            return self.subCommands[subCommand](self, message)
        else:
            return IRCResponse(ResponseType.Say,
                               self._helpText(),
                               message.ReplyTo)

schedule = Schedule()


text:
package org.apache.lucene.facet;

import java.util.Random;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.facet.FacetsCollector.MatchingDocs;
import org.apache.lucene.facet.taxonomy.FastTaxonomyFacetCounts;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiCollector;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;

public class TestRandomSamplingFacetsCollector extends FacetTestCase {

  public void testRandomSampling() throws Exception {
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();

    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    FacetsConfig config = new FacetsConfig();

    int numDocs = atLeast(10000);
    for (int i = 0; i < numDocs; i++) {
      Document doc = new Document();
      doc.add(new StringField("EvenOdd", (i % 2 == 0) ? "even" : "odd", Store.NO));
      doc.add(new FacetField("iMod10", String.valueOf(i % 10)));
      writer.addDocument(config.build(taxoWriter, doc));
    }
    Random random = random();

    // NRT open
    IndexSearcher searcher = newSearcher(writer.getReader());
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
    IOUtils.close(writer, taxoWriter);

    // Test empty results
    RandomSamplingFacetsCollector collectRandomZeroResults = new RandomSamplingFacetsCollector(numDocs / 10, random.nextLong());

    // There should be no divisions by zero
    searcher.search(new TermQuery(new Term("EvenOdd", "NeverMatches")), collectRandomZeroResults);

    // There should be no divisions by zero and no null result
    assertNotNull(collectRandomZeroResults.getMatchingDocs());

    // There should be no results at all
    for (MatchingDocs doc : collectRandomZeroResults.getMatchingDocs()) {
      assertEquals(0, doc.totalHits);
    }

    // Now start searching and retrieve results.

    // Use a query to select half of the documents.
    TermQuery query = new TermQuery(new Term("EvenOdd", "even"));

    // there will be 5 facet values (0, 2, 4, 6 and 8), as only the even (i %
    // 10) are hits.
    // there is a REAL small chance that one of the 5 values will be missed when
    // sampling.
    // but is that 0.8 (chance not to take a value) ^ 2000 * 5 (any can be
    // missing) ~ 10^-193
    // so that is probably not going to happen.
    int maxNumChildren = 5;

    RandomSamplingFacetsCollector random100Percent = new RandomSamplingFacetsCollector(numDocs, random.nextLong()); // no sampling
    RandomSamplingFacetsCollector random10Percent = new RandomSamplingFacetsCollector(numDocs / 10, random.nextLong()); // 10 % of total docs, 20% of the hits

    FacetsCollector fc = new FacetsCollector();

    searcher.search(query, MultiCollector.wrap(fc, random100Percent, random10Percent));

    FastTaxonomyFacetCounts random10FacetCounts = new FastTaxonomyFacetCounts(taxoReader, config, random10Percent);
    FastTaxonomyFacetCounts random100FacetCounts = new FastTaxonomyFacetCounts(taxoReader, config, random100Percent);
    FastTaxonomyFacetCounts exactFacetCounts = new FastTaxonomyFacetCounts(taxoReader, config, fc);

    FacetResult random10Result = random10Percent.amortizeFacetCounts(random10FacetCounts.getTopChildren(10, "iMod10"), config, searcher);
    FacetResult random100Result = random100FacetCounts.getTopChildren(10, "iMod10");
    FacetResult exactResult = exactFacetCounts.getTopChildren(10, "iMod10");

    assertEquals(random100Result, exactResult);

    // we should have five children, but there is a small chance we have less.
    // (see above).
    assertTrue(random10Result.childCount <= maxNumChildren);
    // there should be one child at least.
    assertTrue(random10Result.childCount >= 1);

    // now calculate some statistics to determine if the sampled result is 'ok'.
    // because random sampling is used, the results will vary each time.
    int sum = 0;
    for (LabelAndValue lav : random10Result.labelValues) {
      sum += lav.value.intValue();
    }
    float mu = (float) sum / (float) maxNumChildren;

    float variance = 0;
    for (LabelAndValue lav : random10Result.labelValues) {
      variance += Math.pow((mu - lav.value.intValue()), 2);
    }
    variance = variance / maxNumChildren;
    float sigma = (float) Math.sqrt(variance);

    // we query only half the documents and have 5 categories. The average
    // number of docs in a category will thus be the total divided by 5*2
    float targetMu = numDocs / (5.0f * 2.0f);

    // the average should be in the range and the standard deviation should not
    // be too great
    assertTrue(sigma < 200);
    assertTrue(targetMu - 3 * sigma < mu && mu < targetMu + 3 * sigma);

    IOUtils.close(searcher.getIndexReader(), taxoReader, dir, taxoDir);
  }

}


text:
$:.push File.dirname(__FILE__) + '/..'

require 'test_helper'
require 'thrift'
require 'thrift_test'

$protocolType = "binary"
$host = "localhost"
$port = 9090
$transport = "buffered"
ARGV.each do|a|
  if a == "--help"
    puts "Allowed options:"
    puts "\t -h [ --help ] \t produce help message"
    puts "\t--host arg (=localhost) \t Host to connect"
    puts "\t--port arg (=9090) \t Port number to listen"
    puts "\t--protocol arg (=binary) \t protocol: binary, accel"
    puts "\t--transport arg (=buffered) transport: buffered, framed, http"
    exit
  elsif a.start_with?("--host")
    $host = a.split("=")[1]
  elsif a.start_with?("--protocol")
    $protocolType = a.split("=")[1]
  elsif a.start_with?("--transport")
    $transport = a.split("=")[1]
  elsif a.start_with?("--port")
    $port = a.split("=")[1].to_i
  end
end
ARGV=[]

class SimpleClientTest < Test::Unit::TestCase
  def setup
    unless @socket
      @socket   = Thrift::Socket.new($host, $port)
      if $transport == "buffered"
        transportFactory = Thrift::BufferedTransport.new(@socket)
      elsif $transport == "framed"
        transportFactory = Thrift::FramedTransport.new(@socket)
      else
        raise 'Unknown transport type'
      end

      if $protocolType == "binary"
        @protocol = Thrift::BinaryProtocol.new(transportFactory)
      elsif $protocolType == "compact"
        @protocol = Thrift::CompactProtocol.new(transportFactory)
      elsif $protocolType == "json"
        @protocol = Thrift::JsonProtocol.new(transportFactory)
      elsif $protocolType == "accel"
        @protocol = Thrift::BinaryProtocolAccelerated.new(transportFactory)
      else
        raise 'Unknown protocol type'
      end
      @client   = Thrift::Test::ThriftTest::Client.new(@protocol)
      @socket.open
    end
  end

  def teardown
    @socket.close
  end

  def test_void
    p 'test_void'
    @client.testVoid()
  end

  def test_string
    p 'test_string'
    test_string =
      'quote: \" backslash:' +
      ' forwardslash-escaped: \/ ' +
      ' backspace: \b formfeed: \f newline: \n return: \r tab: ' +
      ' now-all-of-them-together: "\\\/\b\n\r\t' +
      ' now-a-bunch-of-junk: !@#$%&()(&%$#{}{}<><><' +
      ' char-to-test-json-parsing: ]] \"]] \\" }}}{ [[[ '

    result_string = @client.testString(test_string)
    assert_equal(test_string, result_string.force_encoding(Encoding::UTF_8))
  end

  def test_bool
    p 'test_bool'
    assert_equal(@client.testBool(true), true)
    assert_equal(@client.testBool(false), false)
  end

  def test_byte
    p 'test_byte'
    val = 120
    assert_equal(@client.testByte(val), val)
    assert_equal(@client.testByte(-val), -val)
  end

  def test_i32
    p 'test_i32'
    val = 2000000032
    assert_equal(@client.testI32(val), val)
    assert_equal(@client.testI32(-val), -val)
  end

  def test_i64
    p 'test_i64'
    val = 9000000000000000064
    assert_equal(@client.testI64(val), val)
    assert_equal(@client.testI64(-val), -val)
  end

  def test_double
    p 'test_double'
    val = 3.14159265358979323846
    assert_equal(@client.testDouble(val), val)
    assert_equal(@client.testDouble(-val), -val)
    assert_kind_of(Float, @client.testDouble(val))
  end

  def test_binary
    p 'test_binary'
    val = (0...256).reverse_each.to_a
    ret = @client.testBinary(val.pack('C*'))
    assert_equal(val, ret.bytes.to_a)
  end

  def test_map
    p 'test_map'
    val = {1 => 1, 2 => 2, 3 => 3}
    assert_equal(@client.testMap(val), val)
    assert_kind_of(Hash, @client.testMap(val))
  end

  def test_string_map
    p 'test_string_map'
    val = {'a' => '2', 'b' => 'blah', 'some' => 'thing'}
    ret = @client.testStringMap(val)
    assert_equal(val, ret)
    assert_kind_of(Hash, ret)
  end

  def test_list
    p 'test_list'
    val = [1,2,3,4,5]
    assert_equal(@client.testList(val), val)
    assert_kind_of(Array, @client.testList(val))
  end

  def test_enum
    p 'test_enum'
    val = Thrift::Test::Numberz::SIX
    ret = @client.testEnum(val)

    assert_equal(ret, 6)
    assert_kind_of(Fixnum, ret)
  end

  def test_typedef
    p 'test_typedef'
    #UserId  testTypedef(1: UserId thing),
    assert_equal(@client.testTypedef(309858235082523), 309858235082523)
    assert_kind_of(Fixnum, @client.testTypedef(309858235082523))
    true
  end

  def test_set
    p 'test_set'
    val = Set.new([1,2,3])
    assert_equal(@client.testSet(val), val)
    assert_kind_of(Set, @client.testSet(val))
  end

  def get_struct
    Thrift::Test::Xtruct.new({'string_thing' => 'hi!', 'i32_thing' => 4 })
  end

  def test_struct
    p 'test_struct'
    ret = @client.testStruct(get_struct)

    # TODO: not sure what unspecified "default" requiredness values should be
    assert(ret.byte_thing == nil || ret.byte_thing == 0)
    assert(ret.i64_thing == nil || ret.i64_thing == 0)

    assert_equal(ret.string_thing, 'hi!')
    assert_equal(ret.i32_thing, 4)
    assert_kind_of(Thrift::Test::Xtruct, ret)
  end

  def test_nest
    p 'test_nest'
    struct2 = Thrift::Test::Xtruct2.new({'struct_thing' => get_struct, 'i32_thing' => 10})

    ret = @client.testNest(struct2)

    # TODO: not sure what unspecified "default" requiredness values should be
    assert(ret.struct_thing.byte_thing == nil || ret.struct_thing.byte_thing == 0)
    assert(ret.struct_thing.i64_thing == nil || ret.struct_thing.i64_thing == 0)

    assert_equal(ret.struct_thing.string_thing, 'hi!')
    assert_equal(ret.struct_thing.i32_thing, 4)
    assert_equal(ret.i32_thing, 10)

    assert_kind_of(Thrift::Test::Xtruct, ret.struct_thing)
    assert_kind_of(Thrift::Test::Xtruct2, ret)
  end

  def test_insanity
    p 'test_insanity'
    insane = Thrift::Test::Insanity.new({
      'userMap' => {
        Thrift::Test::Numberz::FIVE => 5,
        Thrift::Test::Numberz::EIGHT => 8,
      },
      'xtructs' => [
        Thrift::Test::Xtruct.new({
          'string_thing' => 'Goodbye4',
          'byte_thing' => 4,
          'i32_thing' => 4,
          'i64_thing' => 4,
        }),
        Thrift::Test::Xtruct.new({
          'string_thing' => 'Hello2',
          'byte_thing' => 2,
          'i32_thing' => 2,
          'i64_thing' => 2,
        })
      ]
    })

    ret = @client.testInsanity(insane)

    assert_equal(insane, ret[1][2])
    assert_equal(insane, ret[1][3])

    assert(ret[2][6].userMap == nil || ret[2][6].userMap.length == 0)
    assert(ret[2][6].xtructs == nil || ret[2][6].xtructs.length == 0)
  end

  def test_map_map
    p 'test_map_map'
    ret = @client.testMapMap(4)
    assert_kind_of(Hash, ret)
    expected = {
      -4 => {
        -4 => -4,
        -3 => -3,
        -2 => -2,
        -1 => -1,
      },
      4 => {
        4 => 4,
        3 => 3,
        2 => 2,
        1 => 1,
      }
    }
    assert_equal(expected, ret)
  end

  def test_multi
    p 'test_multi'
    ret = @client.testMulti(42, 4242, 424242, {1 => 'blah', 2 => 'thing'}, Thrift::Test::Numberz::EIGHT, 24)
    expected = Thrift::Test::Xtruct.new({
      :string_thing => 'Hello2',
      :byte_thing =>   42,
      :i32_thing =>    4242,
      :i64_thing =>    424242
    })
    assert_equal(expected, ret)
  end

  def test_exception
    p 'test_exception'
    assert_raise Thrift::Test::Xception do
      @client.testException('Xception')
    end
    begin
      @client.testException('TException')
    rescue => e
      assert e.class.ancestors.include?(Thrift::Exception)
    end
    assert_nothing_raised do
      @client.testException('test')
    end
  end

  def test_multi_exception
    p 'test_multi_exception'
    assert_raise Thrift::Test::Xception do
      @client.testMultiException("Xception", "test 1")
    end
    assert_raise Thrift::Test::Xception2 do
      @client.testMultiException("Xception2", "test 2")
    end
    assert_equal( @client.testMultiException("Success", "test 3").string_thing, "test 3")
  end

  def test_oneway
    p 'test_oneway'
    time1 = Time.now.to_f
    @client.testOneway(1)
    time2 = Time.now.to_f
    assert_operator (time2-time1), :<, 0.1
  end

end


text:
{% extends "webintents/layouts/base.html" %}
{% block title %}Web Intents FAQ{% endblock %}
{% block headline %}Web Intents FAQ{% endblock %}
{% block head %}

    Page:
    Table of Contents
    Questions

{% endblock %}
{% block content %}

Table of Contents

Why not just use navigator.registerProtocolHandler?

Why not just use navigator.registerContentHandler?

Why not just improve both navigator.registerContentHandler
      and navigator.registerProtocolHandler?

Why do we need a new tag? And why can't you use create an new registerIntentHandler() API

Why not simply use a manifest file to register intents

Why is there no inline-in-page disposition?

Why is there no background disposition

How well does Web Intents work with offline apps?

Why can I only transter 5MB of data?

Which browsers will support it?

Why is Action a URL?

What are Type strings going to be? How will they be matched?

Questions

Why not just use navigator.registerProtocolHandler?

registerProtocolHandler is designed to handle cases where there is a
       specific type of application that needs to be launched, commonly via
       an anchor or form, for instance "mailto://". When a user launches a
       link with mailto defined it will open the registered native
       application or web application.

We don't think this goes quite far enough, the protocol handlers
       have no concept of what data will be presented to the launched
       application; what happens when the opened application can't handle
       the data? how do you send an image to an app? There is no way to
       communicate data back to the calling application. Web Intents solves
       both of these problems.

Web Intents uses a filter mechanism to let applications register
       the commands that they wish to handle and also the data-types that
       they can support.

Why not just use navigator.registerContentHandler?

The answer is very similar to the problems that
       navigator.registerProtocolHandler suffers from. It's primary usecase
       is for registering the browser as a handler for a type of file data,
       it doesn't provide context as to the action's it can perform on
       those files.

Why not just improve both navigator.registerContentHandler
    and navigator.registerProtocolHandler?

Why do we need a new tag? And why can't you use create an new registerIntentHandler() API

We can easily index the intentions of services and provide a list of possible apps for the users to use;

It is declarative;

It can be validated;

Less developer API surface area;

Copy and Pastability.  It is very easy for developers to start handling intents without any code

Why not simply use a manifest file to register intents?

It is another file to manage and deploy - our experience with AppCache and the deployment issues irk us.

It hasn't got the copy and paste-ability that a plain tag has.

It is another request for the UA to make:

Management issues: if the manifest 404's do we uninstall intents, if the manifest changes do we uninstall/install etc.

Increased latency and load on the server

Syntax, should it be text like AppCache? should it be XML? should it be JSON?

We would also have to spec out the format of the file and the exact parsing semantics

It is another dialect for developers to learn - The chrome manifest are simple, but we have had to build tools (appmator.appspot.com) to help developers because it was too much to grok the spec.

Add a new rel type to the html spec.

Other app manifests formats - there isn't consensus about the manifest formats for apps and this would lead us to not have one solid place to put it, and even then it might take longer to get this standardised.

Why is there no inline-in-page disposition?

We want to provide a picker and application context to the user that is not spoofable by a malicious page.
    An in-page in-line solution would look and feel very similar to an iframe and thus could be spoofable.  It would be
    nearly impossible to provide an interface that could not be spoofed by a site.

Why is there no background disposition?

      The user experience of having services that are invisible adds greater complexity to the user-agent and the user experience.

How well does Web Intents work with offline apps?

Very well. Web Intents is designed to be an entirely clientside discovery and communication channel.

The native implementation requires no 3rd party scripts or hosting.  It is built in as a function of the User Agent.

The Javascript shim is hosted on webintents.org and is built to work with AppCache,
        so as long as you have a browser that supports AppCache then Web Intents will work offline.

Why can I only transfer 5MB of data?

This is an artifact of localStorage limits in Chrome, it only affects the use of the Javascript shim, not the native implementation.

Which browsers will support it?

We are working with browser vendors to build Web Intents natively in to their browsers.  In the meantime, we have an
    API compatible Javascript Shim with support for  IE8, IE9, Opera, Safari, Firefox 3+ and Chrome 3+.

Why is Action a URL?

       The action in the intent tag is a URL to facilitate the following cases:

Namespacing;

Versioning;

Documentation

       Throughout the Android intent eco-system you see regular use of com.domain.intentname for custom intents. Looking at Android (not the external apps), every intent is already in a namespace, the documentation suggests that everyone prefix it with their package name, therefore "android.intent.action.SEND" is different "com.example.intent.SEND". Given that they are namespaced to a physical location on an Android device (the package) translating this to the web, is through URL's.

What are Type strings going to be? How will they be matched?

        Type strings are a filter used by the User agent to resolve the list of services that are known to be able to handle a particular type of data.  For example, there is no point in listing a service that can only edit images at the start of an activity to edit audio.

        Type strings are based on a MIME-type style syntax and can be resolved either via a full string match or via a simple wildcard system.

        Wildcard types can be specified both in the intent tag and at the time of "startActivity".

Registering at the intent level allows an app to specify a selection of datatypes that it can support. Applications can choose to handle a very specific type: image/png; a range of types: image/* - every image, or any type of data "*"

Client apps can invoke an intent by saying the type of data the expect to send to the app, or recieve from the app. The app can support a vvery specific type: image/png; a range of types: image/* - every image, or any type of data "*"

Intent type resolution matrix

            <intent>

            text/uri-list
            image/jpg
            image/png
            image/*
            *

          startActivity
          text/uri-list
          Yes

          Yes

          image/jpg

          Yes

          Yes
          Yes

          image/png

          Yes
          Yes
          Yes

          image/*

          Yes
          Yes
          Yes
          Yes

          *
          Yes
          Yes
          Yes
          Yes
          Yes

{% endblock %}


text:
module.exports = bin

var npm = require("./npm.js")

bin.usage = "npm bin\nnpm bin -g\n(just prints the bin folder)"

function bin (args, silent, cb) {
  if (typeof cb !== "function") cb = silent, silent = false
  var b = npm.bin
    , PATH = (process.env.PATH || "").split(":")

  if (!silent) console.log(b)
  process.nextTick(cb.bind(this, null, b))

  if (npm.config.get("global") && PATH.indexOf(b) === -1) {
    npm.config.get("logstream").write("(not in PATH env variable)\n")
  }
}


text:
package io.indexr.query.expr.predicate;

import com.google.common.collect.Lists;

import java.util.List;

import io.indexr.query.expr.Expression;
import io.indexr.query.row.InternalRow;
import io.indexr.query.types.DataType;

public class EqualTo extends BinaryPredicate {
    public EqualTo(Expression left, Expression right) {
        super(left, right);
    }

    @Override
    public boolean evalBoolean(InternalRow input) {
        if (left.dataType() == DataType.StringType) {
            return left.evalString(input).equals(right.evalString(input));
        } else {
            return left.evalUniformVal(input) == right.evalUniformVal(input);
        }
    }

    @Override
    public Expression withNewChildren(List<Expression> newChildren) {
        assert newChildren.size() == 2;
        return new EqualTo(newChildren.get(0), newChildren.get(1));
    }

    @Override
    public List<Object> args() {return Lists.newArrayList(left, right);}
}


text:
import re
from typing import Optional, Union

from autobahn.util import public
from autobahn.wamp.types import RegisterOptions, SubscribeOptions

__all__ = (
    'Pattern',
    'register',
    'subscribe',
    'error',
    'convert_starred_uri'
)

def convert_starred_uri(uri: str):
    """
    Convert a starred URI to a standard WAMP URI and a detected matching
    policy. A starred URI is one that may contain the character '*' used
    to mark URI wildcard components or URI prefixes. Starred URIs are
    more comfortable / intuitive to use at the user/API level, but need
    to be converted for use on the wire (WAMP protocol level).

    This function takes a possibly starred URI, detects the matching policy
    implied by stars, and returns a pair (uri, match) with any stars
    removed from the URI and the detected matching policy.

    An URI like 'com.example.topic1' (without any stars in it) is
    detected as an exact-matching URI.

    An URI like 'com.example.*' (with exactly one star at the very end)
    is detected as a prefix-matching URI on 'com.example.'.

    An URI like 'com.*.foobar.*' (with more than one star anywhere) is
    detected as a wildcard-matching URI on 'com..foobar.' (in this example,
    there are two wildcard URI components).

    Note that an URI like 'com.example.*' is always detected as
    a prefix-matching URI 'com.example.'. You cannot express a wildcard-matching
    URI 'com.example.' using the starred URI notation! A wildcard matching on
    'com.example.' is different from prefix-matching on 'com.example.' (which
    matches a strict superset of the former!). This is one reason we don't use
    starred URIs for WAMP at the protocol level.
    """
    assert(type(uri) == str)

    cnt_stars = uri.count('*')

    if cnt_stars == 0:
        match = 'exact'

    elif cnt_stars == 1 and uri[-1] == '*':
        match = 'prefix'
        uri = uri[:-1]

    else:
        match = 'wildcard'
        uri = uri.replace('*', '')

    return uri, match

@public
class Pattern(object):
    """
    A WAMP URI Pattern.

    .. todo::

       * suffix matches
       * args + kwargs
       * uuid converter
       * multiple URI patterns per decorated object
       * classes: Pattern, EndpointPattern, ..
    """

    URI_TARGET_ENDPOINT = 1
    URI_TARGET_HANDLER = 2
    URI_TARGET_EXCEPTION = 3

    URI_TYPE_EXACT = 1
    URI_TYPE_PREFIX = 2
    URI_TYPE_WILDCARD = 3

    _URI_COMPONENT = re.compile(r"^[a-z0-9][a-z0-9_\-]*$")
    """
    Compiled regular expression for a WAMP URI component.
    """

    _URI_NAMED_COMPONENT = re.compile(r"^<([a-z][a-z0-9_]*)>$")
    """
    Compiled regular expression for a named WAMP URI component.

    .. note::
        This pattern is stricter than a general WAMP URI component since a valid Python identifier is required.
    """

    _URI_NAMED_CONVERTED_COMPONENT = re.compile(r"^<([a-z][a-z0-9_]*):([a-z]*)>$")
    """
    Compiled regular expression for a named and type-converted WAMP URI component.

    .. note::
        This pattern is stricter than a general WAMP URI component since a valid Python identifier is required.
    """

    def __init__(self, uri: str, target: int, options: Optional[Union[SubscribeOptions, RegisterOptions]] = None,
                 check_types: Optional[bool] = None):
        """

        :param uri: The URI or URI pattern, e.g. ``"com.myapp.product.<product:int>.update"``.
        :type uri: str

        :param target: The target for this pattern: a procedure endpoint (a callable),
           an event handler (a callable) or an exception (a class).
        :type target: callable or obj

        :param options: An optional options object
        :type options: None or RegisterOptions or SubscribeOptions

        :param check_types: Enable automatic type checking against (Python 3.5+) type hints
            specified on the ``endpoint`` callable. Types are checked at run-time on each
            invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
            is forwarded to the callee code in ``onUserError`` override method of
            :class:`autobahn.wamp.protocol.ApplicationSession`. An error
            of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
            returned to the caller (via the router).
        :type check_types: bool

        """
        assert (type(uri) == str)
        assert (len(uri) > 0)
        assert (target in [Pattern.URI_TARGET_ENDPOINT,
                           Pattern.URI_TARGET_HANDLER,
                           Pattern.URI_TARGET_EXCEPTION])
        if target == Pattern.URI_TARGET_ENDPOINT:
            assert (options is None or type(options) == RegisterOptions)
        elif target == Pattern.URI_TARGET_HANDLER:
            assert (options is None or type(options) == SubscribeOptions)
        else:
            options = None

        components = uri.split('.')

        _URI_COMP_CHARS = r'[^\s\.#]+'
        # _URI_COMP_CHARS = r'[\da-z_]+'
        # _URI_COMP_CHARS = r'[a-z0-9][a-z0-9_\-]*'

        pl = []
        nc = {}
        group_count = 0
        for i in range(len(components)):
            component = components[i]

            match = Pattern._URI_NAMED_CONVERTED_COMPONENT.match(component)
            if match:
                name, comp_type = match.groups()
                if comp_type not in ['str', 'string', 'int', 'suffix']:
                    raise TypeError("invalid URI")

                if comp_type == 'suffix' and i != len(components) - 1:
                    raise TypeError("invalid URI")

                if name in nc:
                    raise TypeError("invalid URI")

                if comp_type in ['str', 'string', 'suffix']:
                    nc[name] = str
                elif comp_type == 'int':
                    nc[name] = int
                else:
                    # should not arrive here
                    raise TypeError("logic error")

                pl.append("(?P<{}>{})".format(name, _URI_COMP_CHARS))
                group_count += 1
                continue

            match = Pattern._URI_NAMED_COMPONENT.match(component)
            if match:
                name = match.groups()[0]
                if name in nc:
                    raise TypeError("invalid URI")

                nc[name] = str
                pl.append("(?P<{}>{})".format(name, _URI_COMP_CHARS))
                group_count += 1
                continue

            match = Pattern._URI_COMPONENT.match(component)
            if match:
                pl.append(component)
                continue

            if component == '':
                group_count += 1
                pl.append(r"({})".format(_URI_COMP_CHARS))
                nc[group_count] = str
                continue

            raise TypeError("invalid URI")

        if nc:
            # URI pattern
            self._type = Pattern.URI_TYPE_WILDCARD
            p = "^" + r"\.".join(pl) + "$"
            self._pattern = re.compile(p)
            self._names = nc
        else:
            # exact URI
            self._type = Pattern.URI_TYPE_EXACT
            self._pattern = None
            self._names = None
        self._uri = uri
        self._target = target
        self._options = options
        self._check_types = check_types

    @public
    @property
    def options(self):
        """
        Returns the Options instance (if present) for this pattern.

        :return: None or the Options instance
        :rtype: None or RegisterOptions or SubscribeOptions
        """
        return self._options

    @public
    @property
    def uri_type(self):
        """
        Returns the URI type of this pattern

        :return:
        :rtype: Pattern.URI_TYPE_EXACT, Pattern.URI_TYPE_PREFIX or Pattern.URI_TYPE_WILDCARD
        """
        return self._type

    @public
    def uri(self):
        """
        Returns the original URI (pattern) for this pattern.

        :returns: The URI (pattern), e.g. ``"com.myapp.product.<product:int>.update"``.
        :rtype: str
        """
        return self._uri

    def match(self, uri):
        """
        Match the given (fully qualified) URI according to this pattern
        and return extracted args and kwargs.

        :param uri: The URI to match, e.g. ``"com.myapp.product.123456.update"``.
        :type uri: str

        :returns: A tuple ``(args, kwargs)``
        :rtype: tuple
        """
        args = []
        kwargs = {}
        if self._type == Pattern.URI_TYPE_EXACT:
            return args, kwargs
        elif self._type == Pattern.URI_TYPE_WILDCARD:
            match = self._pattern.match(uri)
            if match:
                for key in self._names:
                    val = match.group(key)
                    val = self._names[key](val)
                    kwargs[key] = val
                return args, kwargs
            else:
                raise ValueError('no match')

    @public
    def is_endpoint(self):
        """
        Check if this pattern is for a procedure endpoint.

        :returns: ``True``, iff this pattern is for a procedure endpoint.
        :rtype: bool
        """
        return self._target == Pattern.URI_TARGET_ENDPOINT

    @public
    def is_handler(self):
        """
        Check if this pattern is for an event handler.

        :returns: ``True``, iff this pattern is for an event handler.
        :rtype: bool
        """
        return self._target == Pattern.URI_TARGET_HANDLER

    @public
    def is_exception(self):
        """
        Check if this pattern is for an exception.

        :returns: ``True``, iff this pattern is for an exception.
        :rtype: bool
        """
        return self._target == Pattern.URI_TARGET_EXCEPTION

@public
def register(uri: Optional[str], options: Optional[RegisterOptions] = None, check_types: Optional[bool] = None):
    """
    Decorator for WAMP procedure endpoints.

    :param uri:
    :type uri: str

    :param options:
    :type options: None or RegisterOptions

    :param check_types: Enable automatic type checking against (Python 3.5+) type hints
        specified on the ``endpoint`` callable. Types are checked at run-time on each
        invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
        is forwarded to the callee code in ``onUserError`` override method of
        :class:`autobahn.wamp.protocol.ApplicationSession`. An error
        of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
        returned to the caller (via the router).
    :type check_types: bool
    """
    def decorate(f):
        assert(callable(f))
        if uri is None:
            real_uri = '{}'.format(f.__name__)
        else:
            real_uri = uri
        if not hasattr(f, '_wampuris'):
            f._wampuris = []
        f._wampuris.append(Pattern(real_uri, Pattern.URI_TARGET_ENDPOINT, options, check_types))
        return f
    return decorate

@public
def subscribe(uri: Optional[str], options: Optional[SubscribeOptions] = None, check_types: Optional[bool] = None):
    """
    Decorator for WAMP event handlers.

    :param uri:
    :type uri: str

    :param options:
    :type options: None or SubscribeOptions

    :param check_types: Enable automatic type checking against (Python 3.5+) type hints
        specified on the ``endpoint`` callable. Types are checked at run-time on each
        invocation of the ``endpoint`` callable. When a type mismatch occurs, the error
        is forwarded to the callee code in ``onUserError`` override method of
        :class:`autobahn.wamp.protocol.ApplicationSession`. An error
        of type :class:`autobahn.wamp.exception.TypeCheckError` is also raised and
        returned to the caller (via the router).
    :type check_types: bool
    """
    def decorate(f):
        assert(callable(f))
        if not hasattr(f, '_wampuris'):
            f._wampuris = []
        f._wampuris.append(Pattern(uri, Pattern.URI_TARGET_HANDLER, options, check_types))
        return f
    return decorate

@public
def error(uri: str):
    """
    Decorator for WAMP error classes.
    """
    def decorate(cls):
        assert(issubclass(cls, Exception))
        if not hasattr(cls, '_wampuris'):
            cls._wampuris = []
        cls._wampuris.append(Pattern(uri, Pattern.URI_TARGET_EXCEPTION))
        return cls
    return decorate


text:
require 'spec_helper'
describe Regimen do
  let(:regimen) { FactoryGirl.create(:regimen) }

  it "Enforces uniqueness of names" do
    expect {Regimen.create!(name: regimen.name, device: regimen.device)}.to raise_error(ActiveRecord::RecordInvalid)
  end

end


text:
#ifndef LOCATION_IMP_H
#define LOCATION_IMP_H

#include <Object.h>
#include <org/w3c/dom/html/Location.h>

#include "url/URL.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

class WindowProxy;
typedef std::shared_ptr<WindowProxy> WindowProxyPtr;

class LocationImp : public ObjectMixin<LocationImp>
{
    WindowProxyPtr window;
    URL url;

public:
    LocationImp(const WindowProxyPtr& window, const std::u16string& url);
    LocationImp(const LocationImp& other) = default;

    // Location
    virtual std::u16string getHref();
    virtual void setHref(const std::u16string& href);
    virtual void assign(const std::u16string& url);
    virtual void replace(const std::u16string& url);
    virtual void reload();
    virtual std::u16string getProtocol();
    virtual void setProtocol(const std::u16string& protocol);
    virtual std::u16string getHost();
    virtual void setHost(const std::u16string& host);
    virtual std::u16string getHostname();
    virtual void setHostname(const std::u16string& hostname);
    virtual std::u16string getPort();
    virtual void setPort(const std::u16string& port);
    virtual std::u16string getPathname();
    virtual void setPathname(const std::u16string& pathname);
    virtual std::u16string getSearch();
    virtual void setSearch(const std::u16string& search);
    virtual std::u16string getHash();
    virtual void setHash(const std::u16string& hash);
    virtual std::u16string resolveURL(const std::u16string& url);
    // Object
    virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv)
    {
        return html::Location::dispatch(this, selector, id, argc, argv);
    }
    static const char* const getMetaData()
    {
        return html::Location::getMetaData();
    }
};

}}}}  // org::w3c::dom::bootstrap

#endif  // LOCATION_IMP_H


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="fr_FR">
<context>
    <name>Game</name>
    <message>
        <location filename="../assets/Game.qml" line="14"/>
        <source>GAME OVER!</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/Game.qml" line="30"/>
        <source>Submit Score</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/Game.qml" line="41"/>
        <source>Score</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>main</name>
    <message>
        <location filename="../assets/main.qml" line="113"/>
        <source>Welcome</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../assets/main.qml" line="34"/>
        <source>Cascades Scoreloop Sample</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>