text:
/**
 * @file
 * @author Brad Hayes <hayesbh@gmail.com>
 * @version 0.1
 *
 * @section DESCRIPTION
 *
 * Definitions of certain fixed-type actions are placed here
 *
 **/

#include <string>
#include "QLearner/Action.h"

const std::string Primitives::Action::NO_ACTION = "NO_ACTION";
const std::string Primitives::Action::INTERPOLATE = "INTERPOLATE";


text:
package mini.configuration;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.jooq.SQLDialect;
import org.jooq.util.jaxb.Configuration;
import org.jooq.util.jaxb.Database;
import org.jooq.util.jaxb.Generate;
import org.jooq.util.jaxb.Generator;
import org.jooq.util.jaxb.Jdbc;
import org.jooq.util.jaxb.Logging;
import org.jooq.util.jaxb.Target;

/** Settings for the database. */
@AutoValue
public abstract class DatabaseSettings {

  private static final int DEFAULT_POSTGRES_PORT = 5432;
  private static final int DEFAULT_CONNECTION_POOL_SIZE = 20;

  @JsonCreator()
  static DatabaseSettings create(
    @JsonProperty("username") String username,
    @JsonProperty("password") String password,
    @JsonProperty("host") String host,
    @JsonProperty("name") String name,
    @JsonProperty("port") int port,
    @JsonProperty("connectionPoolSize") int connectionPoolSize
  ) {
    return new AutoValue_DatabaseSettings(
      username,
      password,
      name,
      host,
      port == 0 ? DEFAULT_POSTGRES_PORT : port,
      connectionPoolSize  == 0 ? DEFAULT_CONNECTION_POOL_SIZE : connectionPoolSize
    );
  }

  public abstract String getUsername();

  public abstract String getPassword();

  public abstract String getName();

  public abstract String getHost();

  public abstract int getPort();

  public abstract int getConnectionPoolSize();

  public final String getDriver() {
    return "org.postgresql.Driver";
  }

  /** Returns a jdbc compliant connection string.
   *  @return a jdbc compliant connection string
   */
  public final String getUrl() {
    return String.format(
      "jdbc:postgresql://%s:%d/%s",
      getHost(),
      getPort(),
      getName()
     );
  }

  /** Returns the dialect in use.
   *  @return the dialect in use.
   */
  public final SQLDialect getDialect() {
    return SQLDialect.POSTGRES;
  }

  /** Returns a jooq configuration object. Used by build script to generate jooq classes.
   *  @return a jooq configuration object.
   */
  public static Configuration getJooqConfiguration(
    DatabaseSettings db,
    String packageName,
    String outputDir
  ) {
    return new Configuration()
      .withLogging(Logging.TRACE)
      .withJdbc(new Jdbc()
        .withDriver(db.getDriver())
        .withUrl(db.getUrl())
        .withUser(db.getUsername())
        .withPassword(db.getPassword()))
      .withGenerator(new Generator()
        .withGenerate(new Generate()
          .withRecords(true))
        .withDatabase(new Database()
          .withInputSchema("mini"))
        .withTarget(new Target()
          .withPackageName(packageName)
          .withDirectory(outputDir))
      );
  }
}

redpajama_set_name: RedPajamaGithub


text:
%%%%%%%% ICML 2019 EXAMPLE LATEX SUBMISSION FILE %%%%%%%%%%%%%%%%%

\documentclass{article}

% Recommended, but optional, packages for figures and better typesetting:
\usepackage{microtype}
\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{booktabs} % for professional tables

% hyperref makes hyperlinks in the resulting PDF.
% If your build breaks (sometimes temporarily if a hyperlink spans a page)
% please comment out the following usepackage line and replace
% \usepackage{icml2019} with \usepackage[nohyperref]{icml2019} above.
\usepackage{hyperref}

% Attempt to make hyperref and algorithmic work together better:
\newcommand{\theHalgorithm}{\arabic{algorithm}}

% Use the following line for the initial blind version submitted for review:
% \usepackage{icml2019}

% If accepted, instead use the following line for the camera-ready submission:
\usepackage[accepted]{icml2019}

% The \icmltitle you define below is probably too long as a header.
% Therefore, a short form for the running title is supplied here:
\icmltitlerunning{Submission and Formatting Instructions for ICML 2019}

\input{../bsuite_preamble}

\begin{document}

\twocolumn[
\icmltitle{Submission and Formatting Instructions for \\
           International Conference on Machine Learning (ICML 2019)}

% It is OKAY to include author information, even for blind
% submissions: the style file will automatically remove it for you
% unless you've provided the [accepted] option to the icml2019
% package.

% List of affiliations: The first argument should be a (short)
% identifier you will use later to specify author affiliations
% Academic affiliations should list Department, University, City, Region, Country
% Industry affiliations should list Company, City, Region, Country

% You can specify symbols, otherwise they are numbered in order.
% Ideally, you should not use this facility. Affiliations will be numbered
% in order of appearance and this is the preferred way.
\icmlsetsymbol{equal}{*}

\begin{icmlauthorlist}
\icmlauthor{Aeiau Zzzz}{equal,to}
\icmlauthor{Bauiu C.~Yyyy}{equal,to,goo}
\icmlauthor{Cieua Vvvvv}{goo}
\icmlauthor{Iaesut Saoeu}{ed}
\icmlauthor{Fiuea Rrrr}{to}
\icmlauthor{Tateu H.~Yasehe}{ed,to,goo}
\icmlauthor{Aaoeu Iasoh}{goo}
\icmlauthor{Buiui Eueu}{ed}
\icmlauthor{Aeuia Zzzz}{ed}
\icmlauthor{Bieea C.~Yyyy}{to,goo}
\icmlauthor{Teoau Xxxx}{ed}
\icmlauthor{Eee Pppp}{ed}
\end{icmlauthorlist}

\icmlaffiliation{to}{Department of Computation, University of Torontoland, Torontoland, Canada}
\icmlaffiliation{goo}{Googol ShallowMind, New London, Michigan, USA}
\icmlaffiliation{ed}{School of Computation, University of Edenborrow, Edenborrow, United Kingdom}

\icmlcorrespondingauthor{Cieua Vvvvv}{c.vvvvv@googol.com}
\icmlcorrespondingauthor{Eee Pppp}{ep@eden.co.uk}

% You may provide any keywords that you
% find helpful for describing your paper; these are used to populate
% the "keywords" metadata in the PDF but will not be shown in the document
\icmlkeywords{Machine Learning, ICML}

\vskip 0.3in
]

% this must go after the closing bracket ] following \twocolumn[ ...

% This command actually creates the footnote in the first column
% listing the affiliations and the copyright notice.
% The command takes one argument, which is text to display at the start of the footnote.
% The \icmlEqualContribution command is standard text for equal contribution.
% Remove it (just {}) if you do not need this facility.

%\printAffiliationsAndNotice{}  % leave blank if no need to mention equal contribution
\printAffiliationsAndNotice{\icmlEqualContribution} % otherwise use the standard text.

\begin{abstract}
This document provides a basic paper template and submission guidelines.
Abstracts must be a single paragraph, ideally between 4--6 sentences long.
Gross violations will trigger corrections at the camera-ready phase.
\end{abstract}

\section{Electronic Submission}
\label{submission}

Submission to ICML 2019 will be entirely electronic, via a web site
(not email). Information about the submission process and \LaTeX\ templates
are available on the conference web site at:
\begin{center}
\textbf{\texttt{http://icml.cc/}}
\end{center}

The guidelines below will be enforced for initial submissions and
camera-ready copies. Here is a brief summary:
\begin{itemize}
\item Submissions must be in PDF\@.
\item Submitted papers can be up to eight pages long, not including references, and up to twelve pages when references and acknowledgments are included. Any paper exceeding this length will automatically be rejected.
\item \textbf{Do not include author information or acknowledgements} in your
    initial submission.
\item Your paper should be in \textbf{10 point Times font}.
\item Make sure your PDF file only uses Type-1 fonts.
\item Place figure captions \emph{under} the figure (and omit titles from inside
    the graphic file itself). Place table captions \emph{over} the table.
\item References must include page numbers whenever possible and be as complete
    as possible. Place multiple citations in chronological order.
\item Do not alter the style template; in particular, do not compress the paper
    format by reducing the vertical spaces.
\item Keep your abstract brief and self-contained, one paragraph and roughly
    4--6 sentences. Gross violations will require correction at the
    camera-ready phase. The title should have content words capitalized.
\end{itemize}

\subsection{Submitting Papers}

\textbf{Paper Deadline:} The deadline for paper submission that is
advertised on the conference website is strict. If your full,
anonymized, submission does not reach us on time, it will not be
considered for publication.

\textbf{Anonymous Submission:} ICML uses double-blind review: no identifying
author information may appear on the title page or in the paper
itself. Section~\ref{author info} gives further details.

\textbf{Simultaneous Submission:} ICML will not accept any paper which,
at the time of submission, is under review for another conference or
has already been published. This policy also applies to papers that
overlap substantially in technical content with conference papers
under review or previously published. ICML submissions must not be
submitted to other conferences during ICML's review period. Authors
may submit to ICML substantially different versions of journal papers
that are currently under review by the journal, but not yet accepted
at the time of submission. Informal publications, such as technical
reports or papers in workshop proceedings which do not appear in
print, do not fall under these restrictions.

\medskip

Authors must provide their manuscripts in \textbf{PDF} format.
Furthermore, please make sure that files contain only embedded Type-1 fonts
(e.g.,~using the program \texttt{pdffonts} in linux or using
File/DocumentProperties/Fonts in Acrobat). Other fonts (like Type-3)
might come from graphics files imported into the document.

Authors using \textbf{Word} must convert their document to PDF\@. Most
of the latest versions of Word have the facility to do this
automatically. Submissions will not be accepted in Word format or any
format other than PDF\@. Really. We're not joking. Don't send Word.

Those who use \textbf{\LaTeX} should avoid including Type-3 fonts.
Those using \texttt{latex} and \texttt{dvips} may need the following
two commands:

{\footnotesize
\begin{verbatim}
dvips -Ppdf -tletter -G0 -o paper.ps paper.dvi
ps2pdf paper.ps
\end{verbatim}}
It is a zero following the ``-G'', which tells dvips to use
the config.pdf file. Newer \TeX\ distributions don't always need this
option.

Using \texttt{pdflatex} rather than \texttt{latex}, often gives better
results. This program avoids the Type-3 font problem, and supports more
advanced features in the \texttt{microtype} package.

\textbf{Graphics files} should be a reasonable size, and included from
an appropriate format. Use vector formats (.eps/.pdf) for plots,
lossless bitmap formats (.png) for raster graphics with sharp lines, and
jpeg for photo-like images.

The style file uses the \texttt{hyperref} package to make clickable
links in documents. If this causes problems for you, add
\texttt{nohyperref} as one of the options to the \texttt{icml2019}
usepackage statement.

\subsection{Submitting Final Camera-Ready Copy}

The final versions of papers accepted for publication should follow the
same format and naming convention as initial submissions, except that
author information (names and affiliations) should be given. See
Section~\ref{final author} for formatting instructions.

The footnote, ``Preliminary work. Under review by the International
Conference on Machine Learning (ICML). Do not distribute.'' must be
modified to ``\textit{Proceedings of the
$\mathit{36}^{th}$ International Conference on Machine Learning},
Long Beach, USA, 2019.
Copyright 2019 by the author(s).''

For those using the \textbf{\LaTeX} style file, this change (and others) is
handled automatically by simply changing
$\mathtt{\backslash usepackage\{icml2019\}}$ to
$$\mathtt{\backslash usepackage[accepted]\{icml2019\}}$$
Authors using \textbf{Word} must edit the
footnote on the first page of the document themselves.

Camera-ready copies should have the title of the paper as running head
on each page except the first one. The running title consists of a
single line centered above a horizontal rule which is $1$~point thick.
The running head should be centered, bold and in $9$~point type. The
rule should be $10$~points above the main text. For those using the
\textbf{\LaTeX} style file, the original title is automatically set as running
head using the \texttt{fancyhdr} package which is included in the ICML
2019 style file package. In case that the original title exceeds the
size restrictions, a shorter form can be supplied by using

\verb|\icmltitlerunning{...}|

just before $\mathtt{\backslash begin\{document\}}$.
Authors using \textbf{Word} must edit the header of the document themselves.

\section{Format of the Paper}

All submissions must follow the specified format.

\subsection{Length and Dimensions}

Submitted papers can be up to eight pages long, not including references, and up to twelve pages when references and acknowledgments are included.
Acknowledgements should be limited to grants and people who contributed to the paper.
Any submission that exceeds
this page limit, or that diverges significantly from the specified format,
will be rejected without review.

The text of the paper should be formatted in two columns, with an
overall width of 6.75~inches, height of 9.0~inches, and 0.25~inches
between the columns. The left margin should be 0.75~inches and the top
margin 1.0~inch (2.54~cm). The right and bottom margins will depend on
whether you print on US letter or A4 paper, but all final versions
must be produced for US letter size.

The paper body should be set in 10~point type with a vertical spacing
of 11~points. Please use Times typeface throughout the text.

\subsection{Title}

The paper title should be set in 14~point bold type and centered
between two horizontal rules that are 1~point thick, with 1.0~inch
between the top rule and the top edge of the page. Capitalize the
first letter of content words and put the rest of the title in lower
case.

\subsection{Author Information for Submission}
\label{author info}

ICML uses double-blind review, so author information must not appear. If
you are using \LaTeX\/ and the \texttt{icml2019.sty} file, use
\verb+\icmlauthor{...}+ to specify authors and \verb+\icmlaffiliation{...}+ to specify affiliations. (Read the TeX code used to produce this document for an example usage.) The author information
will not be printed unless \texttt{accepted} is passed as an argument to the
style file.
Submissions that include the author information will not
be reviewed.

\subsubsection{Self-Citations}

If you are citing published papers for which you are an author, refer
to yourself in the third person. In particular, do not use phrases
that reveal your identity (e.g., ``in previous work \cite{langley00}, we
have shown \ldots'').

Do not anonymize citations in the reference section. The only exception are manuscripts that are
not yet published (e.g., under submission). If you choose to refer to
such unpublished manuscripts \cite{anonymous}, anonymized copies have
to be submitted
as Supplementary Material via CMT\@. However, keep in mind that an ICML
paper should be self contained and should contain sufficient detail
for the reviewers to evaluate the work. In particular, reviewers are
not required to look at the Supplementary Material when writing their
review.

\subsubsection{Camera-Ready Author Information}
\label{final author}

If a paper is accepted, a final camera-ready copy must be prepared.
%
For camera-ready papers, author information should start 0.3~inches below the
bottom rule surrounding the title. The authors' names should appear in 10~point
bold type, in a row, separated by white space, and centered. Author names should
not be broken across lines. Unbolded superscripted numbers, starting 1, should
be used to refer to affiliations.

Affiliations should be numbered in the order of appearance. A single footnote
block of text should be used to list all the affiliations. (Academic
affiliations should list Department, University, City, State/Region, Country.
Similarly for industrial affiliations.)

Each distinct affiliations should be listed once. If an author has multiple
affiliations, multiple superscripts should be placed after the name, separated
by thin spaces. If the authors would like to highlight equal contribution by
multiple first authors, those authors should have an asterisk placed after their
name in superscript, and the term ``\textsuperscript{*}Equal contribution"
should be placed in the footnote block ahead of the list of affiliations. A
list of corresponding authors and their emails (in the format Full Name
\textless{}email@domain.com\textgreater{}) can follow the list of affiliations.
Ideally only one or two names should be listed.

A sample file with author names is included in the ICML2019 style file
package. Turn on the \texttt{[accepted]} option to the stylefile to
see the names rendered. All of the guidelines above are implemented
by the \LaTeX\ style file.

\subsection{Abstract}

The paper abstract should begin in the left column, 0.4~inches below the final
address. The heading `Abstract' should be centered, bold, and in 11~point type.
The abstract body should use 10~point type, with a vertical spacing of
11~points, and should be indented 0.25~inches more than normal on left-hand and
right-hand margins. Insert 0.4~inches of blank space after the body. Keep your
abstract brief and self-contained, limiting it to one paragraph and roughly 4--6
sentences. Gross violations will require correction at the camera-ready phase.

\subsection{Partitioning the Text}

You should organize your paper into sections and paragraphs to help
readers place a structure on the material and understand its
contributions.

\subsubsection{Sections and Subsections}

Section headings should be numbered, flush left, and set in 11~pt bold
type with the content words capitalized. Leave 0.25~inches of space
before the heading and 0.15~inches after the heading.

Similarly, subsection headings should be numbered, flush left, and set
in 10~pt bold type with the content words capitalized. Leave
0.2~inches of space before the heading and 0.13~inches afterward.

Finally, subsubsection headings should be numbered, flush left, and
set in 10~pt small caps with the content words capitalized. Leave
0.18~inches of space before the heading and 0.1~inches after the
heading.

Please use no more than three levels of headings.

\subsubsection{Paragraphs and Footnotes}

Within each section or subsection, you should further partition the
paper into paragraphs. Do not indent the first line of a given
paragraph, but insert a blank line between succeeding ones.

You can use footnotes\footnote{Footnotes
should be complete sentences.} to provide readers with additional
information about a topic without interrupting the flow of the paper.
Indicate footnotes with a number in the text where the point is most
relevant. Place the footnote in 9~point type at the bottom of the
column in which it appears. Precede the first footnote in a column
with a horizontal rule of 0.8~inches.\footnote{Multiple footnotes can
appear in each column, in the same order as they appear in the text,
but spread them across columns and pages if possible.}

\begin{figure}[ht]
\vskip 0.2in
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{icml_numpapers}}
\caption{Historical locations and number of accepted papers for International
Machine Learning Conferences (ICML 1993 -- ICML 2008) and International
Workshops on Machine Learning (ML 1988 -- ML 1992). At the time this figure was
produced, the number of accepted papers for ICML 2008 was unknown and instead
estimated.}
\label{icml-historical}
\end{center}
\vskip -0.2in
\end{figure}

\subsection{Figures}

You may want to include figures in the paper to illustrate
your approach and results. Such artwork should be centered,
legible, and separated from the text. Lines should be dark and at
least 0.5~points thick for purposes of reproduction, and text should
not appear on a gray background.

Label all distinct components of each figure. If the figure takes the
form of a graph, then give a name for each axis and include a legend
that briefly describes each curve. Do not include a title inside the
figure; instead, the caption should serve this function.

Number figures sequentially, placing the figure number and caption
\emph{after} the graphics, with at least 0.1~inches of space before
the caption and 0.1~inches after it, as in
Figure~\ref{icml-historical}. The figure caption should be set in
9~point type and centered unless it runs two or more lines, in which
case it should be flush left. You may float figures to the top or
bottom of a column, and you may set wide figures across both columns
(use the environment \texttt{figure*} in \LaTeX). Always place
two-column figures at the top or bottom of the page.

\subsection{Algorithms}

If you are using \LaTeX, please use the ``algorithm'' and ``algorithmic''
environments to format pseudocode. These require
the corresponding stylefiles, algorithm.sty and
algorithmic.sty, which are supplied with this package.
Algorithm~\ref{alg:example} shows an example.

\begin{algorithm}[tb]
   \caption{Bubble Sort}
   \label{alg:example}
\begin{algorithmic}
   \STATE {\bfseries Input:} data $x_i$, size $m$
   \REPEAT
   \STATE Initialize $noChange = true$.
   \FOR{$i=1$ {\bfseries to} $m-1$}
   \IF{$x_i > x_{i+1}$}
   \STATE Swap $x_i$ and $x_{i+1}$
   \STATE $noChange = false$
   \ENDIF
   \ENDFOR
   \UNTIL{$noChange$ is $true$}
\end{algorithmic}
\end{algorithm}

\subsection{Tables}

You may also want to include tables that summarize material. Like
figures, these should be centered, legible, and numbered consecutively.
However, place the title \emph{above} the table with at least
0.1~inches of space before the title and the same after it, as in
Table~\ref{sample-table}. The table title should be set in 9~point
type and centered unless it runs two or more lines, in which case it
should be flush left.

% Note use of \abovespace and \belowspace to get reasonable spacing
% above and below tabular lines.

\begin{table}[t]
\caption{Classification accuracies for naive Bayes and flexible
Bayes on various data sets.}
\label{sample-table}
\vskip 0.15in
\begin{center}
\begin{small}
\begin{sc}
\begin{tabular}{lcccr}
\toprule
Data set & Naive & Flexible & Better? \\
\midrule
Breast    & 95.9$\pm$ 0.2& 96.7$\pm$ 0.2& $\surd$ \\
Cleveland & 83.3$\pm$ 0.6& 80.0$\pm$ 0.6& $\times$\\
Glass2    & 61.9$\pm$ 1.4& 83.8$\pm$ 0.7& $\surd$ \\
Credit    & 74.8$\pm$ 0.5& 78.3$\pm$ 0.6&         \\
Horse     & 73.3$\pm$ 0.9& 69.7$\pm$ 1.0& $\times$\\
Meta      & 67.1$\pm$ 0.6& 76.5$\pm$ 0.5& $\surd$ \\
Pima      & 75.1$\pm$ 0.6& 73.9$\pm$ 0.5&         \\
Vehicle   & 44.9$\pm$ 0.6& 61.5$\pm$ 0.4& $\surd$ \\
\bottomrule
\end{tabular}
\end{sc}
\end{small}
\end{center}
\vskip -0.1in
\end{table}

Tables contain textual material, whereas figures contain graphical material.
Specify the contents of each row and column in the table's topmost
row. Again, you may float tables to a column's top or bottom, and set
wide tables across both columns. Place two-column tables at the
top or bottom of the page.

\subsection{Citations and References}

Please use APA reference format regardless of your formatter
or word processor. If you rely on the \LaTeX\/ bibliographic
facility, use \texttt{natbib.sty} and \texttt{icml2019.bst}
included in the style-file package to obtain this format.

Citations within the text should include the authors' last names and
year. If the authors' names are included in the sentence, place only
the year in parentheses, for example when referencing Arthur Samuel's
pioneering work \yrcite{Samuel59}. Otherwise place the entire
reference in parentheses with the authors and year separated by a
comma \cite{Samuel59}. List multiple references separated by
semicolons \cite{kearns89,Samuel59,mitchell80}. Use the `et~al.'
construct only for citations with three or more authors or after
listing all authors to a publication in an earlier reference \cite{MachineLearningI}.

Authors should cite their own work in the third person
in the initial version of their paper submitted for blind review.
Please refer to Section~\ref{author info} for detailed instructions on how to
cite your own papers.

Use an unnumbered first-level section heading for the references, and use a
hanging indent style, with the first line of the reference flush against the
left margin and subsequent lines indented by 10 points. The references at the
end of this document give examples for journal articles \cite{Samuel59},
conference publications \cite{langley00}, book chapters \cite{Newell81}, books
\cite{DudaHart2nd}, edited volumes \cite{MachineLearningI}, technical reports
\cite{mitchell80}, and dissertations \cite{kearns89}.

Alphabetize references by the surnames of the first authors, with
single author entries preceding multiple author entries. Order
references for the same authors by year of publication, with the
earliest first. Make sure that each reference includes all relevant
information (e.g., page numbers).

Please put some effort into making references complete, presentable, and
consistent. If using bibtex, please protect capital letters of names and
abbreviations in titles, for example, use \{B\}ayesian or \{L\}ipschitz
in your .bib file.

\subsection{Software and Data}

We strongly encourage the publication of software and data with the
camera-ready version of the paper whenever appropriate. This can be
done by including a URL in the camera-ready copy. However, do not
include URLs that reveal your institution or identity in your
submission for review. Instead, provide an anonymous URL or upload
the material as ``Supplementary Material'' into the CMT reviewing
system. Note that reviewers are not required to look at this material
when writing their review.

% Acknowledgements should only appear in the accepted version.
\section*{Acknowledgements}

\textbf{Do not} include acknowledgements in the initial version of
the paper submitted for blind review.

If a paper is accepted, the final camera-ready version can (and
probably should) include acknowledgements. In this case, please
place such acknowledgements in an unnumbered section at the
end of the paper. Typically, this will include thanks to reviewers
who gave useful comments, to colleagues who contributed to the ideas,
and to funding agencies and corporate sponsors that provided financial
support.

% In the unusual situation where you want a paper to appear in the
% references without citing it in the main text, use \nocite
\nocite{langley00}

\bibliography{example_paper}
\bibliographystyle{icml2019}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DELETE THIS PART. DO NOT PLACE CONTENT AFTER THE REFERENCES!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\appendix
\section{Do \emph{not} have an appendix here}

\textbf{\emph{Do not put content after the references.}}
%
Put anything that you might normally include after the references in a separate
supplementary file.

We recommend that you build supplementary material in a separate document.
If you must create one PDF and cut it up, please be careful to use a tool that
doesn't alter the margins, and that doesn't aggressively rewrite the PDF file.
pdftk usually works fine.

\textbf{Please do not use Apple's preview to cut off supplementary material.} In
previous years it has altered margins, and created headaches at the camera-ready
stage.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{../bsuite_appendix}

\end{document}

% This document was modified from the file originally made available by
% Pat Langley and Andrea Danyluk for ICML-2K. This version was created
% by Iain Murray in 2018, and modified by Alexandre Bouchard in
% 2019. Previous contributors include Dan Roy, Lise Getoor and Tobias
% Scheffer, which was slightly modified from the 2010 version by
% Thorsten Joachims & Johannes Fuernkranz, slightly modified from the
% 2009 version by Kiri Wagstaff and Sam Roweis's 2008 version, which is
% slightly modified from Prasad Tadepalli's 2007 version which is a
% lightly changed version of the previous year's version by Andrew
% Moore, which was in turn edited from those of Kristian Kersting and
% Codrina Lauth. Alex Smola contributed to the algorithmic style files.


text:
// Copyright (C) 2019 MapRoulette contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.maproulette.models

import org.joda.time.DateTime

/**
  * @author cuthbertm
  */
case class Lock(lockedTime: Option[DateTime], itemType: Int, itemId: Long, userId: Long)

object Lock {
  def emptyLock: Lock = Lock(None, -1, -1, -1)
}


text:
<?php
declare(strict_types=1);

namespace Ytake\LaravelAspect;

use Ytake\LaravelAspect\Annotation;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;

use function count;
use function array_merge;

/**
 * Class AnnotationConfiguration
 */
class AnnotationConfiguration
{
    /** @var array */
    protected $configuration = [];

    /** @var array */
    protected $customAnnotations = [];

    /** @var string[] */
    private $annotations = [
        Annotation\Cacheable::class,
        Annotation\CacheEvict::class,
        Annotation\CachePut::class,
        Annotation\EagerQueue::class,
        Annotation\LazyQueue::class,
        Annotation\LogExceptions::class,
        Annotation\Loggable::class,
        Annotation\MessageDriven::class,
        Annotation\PostConstruct::class,
        Annotation\QueryLog::class,
        Annotation\RetryOnFailure::class,
        Annotation\Transactional::class,
    ];

    /**
     * @param array $configuration
     * @param array $customAnnotations
     */
    public function __construct(array $configuration, array $customAnnotations = [])
    {
        $this->configuration = $configuration;
        $this->customAnnotations = $customAnnotations;
        $this->registerAnnotations();
    }

    /**
     * Add a new annotation to the globally ignored annotation names with regard to exception handling.
     */
    public function ignoredAnnotations(): void
    {
        if (isset($this->configuration['ignores'])) {
            $ignores = $this->configuration['ignores'];
            if (count($ignores)) {
                foreach ($ignores as $ignore) {
                    AnnotationReader::addGlobalIgnoredName($ignore);
                }
            }
        }
    }

    protected function registerAnnotations(): void
    {
        $this->annotations = array_merge(
            $this->annotations,
            $this->customAnnotations
        );
        if (isset($this->configuration['custom'])) {
            $this->annotations = array_merge(
                $this->annotations,
                $this->configuration['custom']
            );
        }
        foreach ($this->annotations as $annotation) {
            AnnotationRegistry::loadAnnotationClass($annotation);
        }
    }
}


text:
package org.camunda.bpm.engine.impl.interceptor;

/**
 * @author Tom Baeyens
 */
public interface SessionFactory {

  Class<?> getSessionType();

  Session openSession();

}


text:
namespace Rhino.Etl.Tests
{
    using System;
    using System.Collections.Generic;
    using MbUnit.Framework;
    using Fibonacci.Output;

    [TestFixture]
    public class OutputCommandFixture : BaseFibonacciTest
    {
        [Test]
        public void CanInsertToDatabaseFromInMemoryCollection()
        {
            OutputFibonacciToDatabase fibonaci = new OutputFibonacciToDatabase(25, Should.WorkFine);
            fibonaci.Execute();

            Assert25ThFibonacci();
        }

        [Test]
        public void WillRaiseRowProcessedEvent()
        {
            int rowsProcessed = 0;

            using (OutputFibonacciToDatabase fibonaci = new OutputFibonacciToDatabase(1, Should.WorkFine))
            {
                fibonaci.OutputOperation.OnRowProcessed += delegate { rowsProcessed++; };
                fibonaci.Execute();
            }

            Assert.AreEqual(1, rowsProcessed);
        }

        [Test]
        public void WillRaiseRowProcessedEventUntilItThrows()
        {
            int rowsProcessed = 0;

            using (OutputFibonacciToDatabase fibonaci = new OutputFibonacciToDatabase(25, Should.Throw))
            {
                fibonaci.OutputOperation.OnRowProcessed += delegate { rowsProcessed++; };
                fibonaci.Execute();

                Assert.AreEqual(fibonaci.ThrowingOperation.RowsAfterWhichToThrow, rowsProcessed);
            }
        }

        [Test]
        public void WillRaiseFinishedProcessingEventOnce()
        {
            int finished = 0;

            using (OutputFibonacciToDatabase fibonaci = new OutputFibonacciToDatabase(1, Should.WorkFine))
            {
                fibonaci.OutputOperation.OnFinishedProcessing += delegate { finished++; };
                fibonaci.Execute();
            }

            Assert.AreEqual(1, finished);
        }

        [Test]
        public void WhenErrorIsThrownWillRollbackTransaction()
        {
            OutputFibonacciToDatabase fibonaci = new OutputFibonacciToDatabase(25, Should.Throw);
            fibonaci.Execute();
            Assert.AreEqual(1, new List<Exception>(fibonaci.GetAllErrors()).Count);
            AssertFibonacciTableEmpty();
        }
    }
}


text:
export default function styles(
  theme,
  { withTab, withAppBar } = { withTab: false, withAppBar: true }
) {
  const { breakpoints } = theme;
  const tabHeight = withTab ? 48 : 0;
  const bottomNavigationHeight = 56;
  return {
    slideHeight: {
      height: `calc(100vh - ${tabHeight + (withAppBar ? 56 : 0) + bottomNavigationHeight}px)`,
      [`${breakpoints.up('xs')} and (orientation: landscape)`]: {
        height: `calc(100vh - ${tabHeight + (withAppBar ? 48 : 0) + bottomNavigationHeight}px)`,
      },
      [`${breakpoints.up('sm')}`]: {
        height: `calc(100vh - ${tabHeight + (withAppBar ? 64 : 0)}px)`,
      },
    },
  };
}


text:
package com.qxcmp.web.view.modules.table;

import com.qxcmp.web.view.support.Color;
import com.qxcmp.web.view.support.ColumnCount;
import com.qxcmp.web.view.support.Device;
import com.qxcmp.web.view.support.Size;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

/**
 * 数据表格抽象类
 *
 * @author Aaric
 */
@Getter
@Setter
public abstract class AbstractTable extends AbstractTableComponent {

    /**
     * 显示指定列的数量
     *

     * 每一列都为等宽
     */
    protected ColumnCount columnCount = ColumnCount.NONE;
    /**
     * 表头
     */
    private AbstractTableHeader header;
    /**
     * 表格内容
     */
    private AbstractTableBody body;
    /**
     * 表尾
     */
    private AbstractTableFooter footer;
    /**
     * 是否禁用掉过滤器
     */
    private boolean disableFilter;
    /**
     * 是否在单元格之间显示分隔符
     */
    private boolean celled;
    /**
     * 是否为基本表格
     *

     * 该属性为移除表头和表尾的背景色
     */
    private boolean basic;
    /**
     * 是否为纯净表格
     *

     * 该属性在基本表格的基础上再移除表格的外边框
     */
    private boolean veryBasic;
    /**
     * 是否为单行模式
     *

     * 该模式下的单元格不会换行,始终保持单行
     */
    private boolean singleLine;
    /**
     * 是否为固定表格
     *

     * 该属性将会使用 table-layout: fixed 作为数据表格布局
     *

     * 如果和单行模式结合使用,显示不下的数据将以...表示
     */
    private boolean fixed;
    /**
     * 自动堆叠的设备类型
     *

     * 数据表格默认不开启自动堆叠,如需要指定自动堆叠,使用此属性
     */
    private Device stackDevice = Device.NONE;
    /**
     * 是否开始行高亮
     */
    private boolean selectable;
    /**
     * 是否显示单双行的条纹
     */
    private boolean striped;
    /**
     * 是否翻转颜色
     */
    private boolean inverted;
    /**
     * 是否为崩塌
     *

     * 该属性会让单元格只占用实际宽度
     */
    private boolean collapsing;
    /**
     * 是否增加单元格的内边距
     */
    private boolean padded;
    /**
     * 是否更多的增加单元格的内边距
     */
    private boolean veryPadded;
    /**
     * 是否减少单元格的内边距
     */
    private boolean compact;
    /**
     * 是否更多的减少单元格的内边距
     */
    private boolean veryCompact;
    /**
     * 颜色
     */
    private Color color = Color.NONE;

    /**
     * 大小
     */
    private Size size = Size.NONE;

    @Override
    public String getClassPrefix() {
        return "ui";
    }

    @Override
    public String getClassContent() {
        final StringBuilder stringBuilder = new StringBuilder();

        if (celled) {
            stringBuilder.append(" celled");
        }

        if (basic) {
            stringBuilder.append(" basic");
        } else if (veryBasic) {
            stringBuilder.append(" very basic");
        }

        if (singleLine) {
            stringBuilder.append(" single line");
        }

        if (fixed) {
            stringBuilder.append(" fixed");
        }

        if (StringUtils.isNotBlank(stackDevice.toString())) {
            stringBuilder.append(" ").append(stackDevice).append(" stackable");
        } else {
            stringBuilder.append(" unstackable");
        }

        if (selectable) {
            stringBuilder.append(" selectable");
        }

        if (striped) {
            stringBuilder.append(" striped");
        }

        if (inverted) {
            stringBuilder.append(" inverted");
        }

        if (collapsing) {
            stringBuilder.append(" collapsing");
        }

        if (padded) {
            stringBuilder.append(" padded");
        } else if (veryPadded) {
            stringBuilder.append(" very padded");
        }

        if (compact) {
            stringBuilder.append(" compact");
        } else if (veryCompact) {
            stringBuilder.append(" very compact");
        }

        return stringBuilder.append(columnCount).append(color).append(size).toString();
    }

    @Override
    public String getClassSuffix() {
        return "table";
    }

    public AbstractTable setHeader(AbstractTableHeader header) {
        this.header = header;
        return this;
    }

    public AbstractTable setBody(AbstractTableBody body) {
        this.body = body;
        return this;
    }

    public AbstractTable setFooter(AbstractTableFooter footer) {
        this.footer = footer;
        return this;
    }

    public AbstractTable setCelled() {
        setCelled(true);
        return this;
    }

    public AbstractTable setBasic() {
        setBasic(true);
        return this;
    }

    public AbstractTable setVeryBasic() {
        setVeryBasic(true);
        return this;
    }

    public AbstractTable setSingleLine() {
        setSingleLine(true);
        return this;
    }

    public AbstractTable setFixed() {
        setFixed(true);
        return this;
    }

    public AbstractTable setStackDevice(Device device) {
        this.stackDevice = device;
        return this;
    }

    public AbstractTable setSelectable() {
        setSelectable(true);
        return this;
    }

    public AbstractTable setStriped() {
        setStriped(true);
        return this;
    }

    public AbstractTable setInverted() {
        setInverted(true);
        return this;
    }

    public AbstractTable setCollapsing() {
        setCollapsing(true);
        return this;
    }

    public AbstractTable setPadded() {
        setPadded(true);
        return this;
    }

    public AbstractTable setVeryPadded() {
        setVeryPadded(true);
        return this;
    }

    public AbstractTable setCompact() {
        setCompact(true);
        return this;
    }

    public AbstractTable setVeryCompact() {
        setVeryCompact(true);
        return this;
    }

    public AbstractTable setColumnCount(ColumnCount columnCount) {
        this.columnCount = columnCount;
        return this;
    }

    public AbstractTable setColor(Color color) {
        this.color = color;
        return this;
    }

    public AbstractTable setSize(Size size) {
        this.size = size;
        return this;
    }
}


text:
@javax.xml.bind.annotation.XmlSchema(namespace = KimApiConstants.Namespaces.KIM_NAMESPACE_2_0, elementFormDefault = XmlNsForm.QUALIFIED)
package org.kuali.rice.kim.api.identity.phone;

import org.kuali.rice.kim.api.KimApiConstants;

import javax.xml.bind.annotation.XmlNsForm;


text:
<?php
/**
 * Created by PhpStorm.
 * User: yiqing
 * Date: 2016/6/1
 * Time: 18:47
 */

namespace my\test\widgets;

use yii\base\Widget;

class HelloTheme extends Widget
{

    public function run()
    {
       return $this->render('hello') ;
    }
}


text:
<?php

namespace FluentDOM\Exceptions {

  use FluentDOM\Exception;

  class InvalidSource extends \InvalidArgumentException implements Exception {

    /**
     * @param mixed $source
     * @param string $contentType
     */
    public function __construct($source, $contentType) {
      parent::__construct(
        sprintf(
          'Can not load %s as "%s".',
          (is_object($source) ? get_class($source) : gettype($source)),
          $contentType
        )
      );
    }
  }
}


text:
package org.n0pe.asadmin;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import junit.framework.TestCase;

public class ExternalProcessTest
        extends TestCase
{

    public void testEnvVars()
    {
        Map<String, String> env = new LinkedHashMap<String, String>();
        env.put( "JAVA_HOME", "/home/paul/opt/jdk" );
        env.put( "JAVA_HOME_WITH_SPACES", "/home/paul/with spaces/opt/jdk" );
        String[] envStrings = AsAdmin.buildEnvironmentStrings( env );
        assertEquals( "[JAVA_HOME=/home/paul/opt/jdk, JAVA_HOME_WITH_SPACES=\"/home/paul/with spaces/opt/jdk\"]", Arrays.toString( envStrings ) );

        env.put( "WRONG NAME", "useless" );
        try {
            AsAdmin.buildEnvironmentStrings( env );
            fail( "Environment variable with spaces in name are illegal" );
        } catch ( IllegalArgumentException ex ) {
            // expected
        }
    }

}


text:
package ipv6

import (
	"syscall"
	"unsafe"

	"golang.org/x/net/internal/iana"
)

func marshalTrafficClass(b []byte, cm *ControlMessage) []byte {
	m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
	m.Level = iana.ProtocolIPv6
	m.Type = sysIPV6_TCLASS
	m.SetLen(syscall.CmsgLen(4))
	if cm != nil {
		data := b[syscall.CmsgLen(0):]
		nativeEndian.PutUint32(data[:4], uint32(cm.TrafficClass))
	}
	return b[syscall.CmsgSpace(4):]
}

func parseTrafficClass(cm *ControlMessage, b []byte) {
	cm.TrafficClass = int(nativeEndian.Uint32(b[:4]))
}

func marshalHopLimit(b []byte, cm *ControlMessage) []byte {
	m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
	m.Level = iana.ProtocolIPv6
	m.Type = sysIPV6_HOPLIMIT
	m.SetLen(syscall.CmsgLen(4))
	if cm != nil {
		data := b[syscall.CmsgLen(0):]
		nativeEndian.PutUint32(data[:4], uint32(cm.HopLimit))
	}
	return b[syscall.CmsgSpace(4):]
}

func parseHopLimit(cm *ControlMessage, b []byte) {
	cm.HopLimit = int(nativeEndian.Uint32(b[:4]))
}

func marshalPacketInfo(b []byte, cm *ControlMessage) []byte {
	m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
	m.Level = iana.ProtocolIPv6
	m.Type = sysIPV6_PKTINFO
	m.SetLen(syscall.CmsgLen(sizeofInet6Pktinfo))
	if cm != nil {
		pi := (*inet6Pktinfo)(unsafe.Pointer(&b[syscall.CmsgLen(0)]))
		if ip := cm.Src.To16(); ip != nil && ip.To4() == nil {
			copy(pi.Addr[:], ip)
		}
		if cm.IfIndex > 0 {
			pi.setIfindex(cm.IfIndex)
		}
	}
	return b[syscall.CmsgSpace(sizeofInet6Pktinfo):]
}

func parsePacketInfo(cm *ControlMessage, b []byte) {
	pi := (*inet6Pktinfo)(unsafe.Pointer(&b[0]))
	cm.Dst = pi.Addr[:]
	cm.IfIndex = int(pi.Ifindex)
}

func marshalNextHop(b []byte, cm *ControlMessage) []byte {
	m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
	m.Level = iana.ProtocolIPv6
	m.Type = sysIPV6_NEXTHOP
	m.SetLen(syscall.CmsgLen(sizeofSockaddrInet6))
	if cm != nil {
		sa := (*sockaddrInet6)(unsafe.Pointer(&b[syscall.CmsgLen(0)]))
		sa.setSockaddr(cm.NextHop, cm.IfIndex)
	}
	return b[syscall.CmsgSpace(sizeofSockaddrInet6):]
}

func parseNextHop(cm *ControlMessage, b []byte) {
}

func marshalPathMTU(b []byte, cm *ControlMessage) []byte {
	m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
	m.Level = iana.ProtocolIPv6
	m.Type = sysIPV6_PATHMTU
	m.SetLen(syscall.CmsgLen(sizeofIPv6Mtuinfo))
	return b[syscall.CmsgSpace(sizeofIPv6Mtuinfo):]
}

func parsePathMTU(cm *ControlMessage, b []byte) {
	mi := (*ipv6Mtuinfo)(unsafe.Pointer(&b[0]))
	cm.Dst = mi.Addr.Addr[:]
	cm.IfIndex = int(mi.Addr.Scope_id)
	cm.MTU = int(mi.Mtu)
}


text:
package org.apache.hadoop.hbase.regionserver.compactions;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.regionserver.StoreFileWriter;
import org.apache.hadoop.hbase.regionserver.throttle.NoLimitThroughputController;
import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController;
import org.apache.hadoop.hbase.security.User;

import org.apache.hadoop.hbase.shaded.com.google.common.collect.Lists;

/**
 * Compact passed set of files. Create an instance and then call
 * {@link #compact(CompactionRequest, ThroughputController, User)}
 */
@InterfaceAudience.Private
public class DefaultCompactor extends Compactor<StoreFileWriter> {
  private static final Log LOG = LogFactory.getLog(DefaultCompactor.class);

  public DefaultCompactor(final Configuration conf, final Store store) {
    super(conf, store);
  }

  private final CellSinkFactory<StoreFileWriter> writerFactory =
      new CellSinkFactory<StoreFileWriter>() {
        @Override
        public StoreFileWriter createWriter(InternalScanner scanner,
            org.apache.hadoop.hbase.regionserver.compactions.Compactor.FileDetails fd,
            boolean shouldDropBehind) throws IOException {
          return createTmpWriter(fd, shouldDropBehind);
        }
      };

  /**
   * Do a minor/major compaction on an explicit set of storefiles from a Store.
   */
  public List<Path> compact(final CompactionRequest request,
      ThroughputController throughputController, User user) throws IOException {
    return compact(request, defaultScannerFactory, writerFactory, throughputController, user);
  }

  /**
   * Compact a list of files for testing. Creates a fake {@link CompactionRequest} to pass to
   * {@link #compact(CompactionRequest, ThroughputController, User)};
   * @param filesToCompact the files to compact. These are used as the compactionSelection for the
   *          generated {@link CompactionRequest}.
   * @param isMajor true to major compact (prune all deletes, max versions, etc)
   * @return Product of compaction or an empty list if all cells expired or deleted and nothing \
   *         made it through the compaction.
   * @throws IOException
   */
  public List<Path> compactForTesting(final Collection<StoreFile> filesToCompact, boolean isMajor)
      throws IOException {
    CompactionRequest cr = new CompactionRequest(filesToCompact);
    cr.setIsMajor(isMajor, isMajor);
    return compact(cr, NoLimitThroughputController.INSTANCE, null);
  }

  @Override
  protected List<Path> commitWriter(StoreFileWriter writer, FileDetails fd,
      CompactionRequest request) throws IOException {
    List<Path> newFiles = Lists.newArrayList(writer.getPath());
    writer.appendMetadata(fd.maxSeqId, request.isAllFiles());
    writer.close();
    return newFiles;
  }

  @Override
  protected void abortWriter(StoreFileWriter writer) throws IOException {
    Path leftoverFile = writer.getPath();
    try {
      writer.close();
    } catch (IOException e) {
      LOG.warn("Failed to close the writer after an unfinished compaction.", e);
    }
    try {
      store.getFileSystem().delete(leftoverFile, false);
    } catch (IOException e) {
      LOG.warn(
        "Failed to delete the leftover file " + leftoverFile + " after an unfinished compaction.",
        e);
    }
  }
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.math;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor;
import org.elasticsearch.xpack.ql.expression.gen.processor.Processor;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation;
import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation;

import java.io.IOException;
import java.util.function.BiFunction;

/**
 * Binary math operations. Sister class to {@link MathOperation}.
 */
public class BinaryMathProcessor extends FunctionalEnumBinaryProcessor<Number, Number, Number, BinaryMathOperation> {

    public enum BinaryMathOperation implements BiFunction<Number, Number, Number> {

        ATAN2((l, r) -> Math.atan2(l.doubleValue(), r.doubleValue())),
        MOD(Arithmetics::mod),
        POWER((l, r) -> Math.pow(l.doubleValue(), r.doubleValue()));

        private final BiFunction<Number, Number, Number> process;

        BinaryMathOperation(BiFunction<Number, Number, Number> process) {
            this.process = process;
        }

        @Override
        public final Number apply(Number left, Number right) {
            if (left == null || right == null) {
                return null;
            }
            return process.apply(left, right);
        }
    }

    public static final String NAME = "mb";

    public BinaryMathProcessor(Processor left, Processor right, BinaryMathOperation operation) {
        super(left, right, operation);
    }

    public BinaryMathProcessor(StreamInput in) throws IOException {
        super(in, i -> i.readEnum(BinaryMathOperation.class));
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    @Override
    protected void checkParameter(Object param) {
        if (!(param instanceof Number)) {
            throw new SqlIllegalArgumentException("A number is required; received [{}]", param);
        }
    }
}


text:
import { Users, Roles, Documents } from '../models';
import {
  passwordHash,
  authenticateUser,
  catchError,
  returnValidationErrors,
  isRegisteredUser,
  pagination,
  verifyPassword,
} from '../helpers/utils';

/**
 * @description creates a user
 * @function createUser
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object
 */
const createUser = (req, res) => {
  req.checkBody('fullname', 'Full name cannot be empty').notEmpty();
  req.checkBody('email', 'Email cannot be empty').notEmpty();
  req.checkBody('email', 'Enter a valid email address').isEmail();
  req.checkBody('password', 'Password cannot be empty').notEmpty();

  returnValidationErrors(req, res);

  /** check if provided email already exists in user database */
  isRegisteredUser(req.body.email, 'email')
  .then((registeredUser) => {
    if (registeredUser) {
      return res.status(409).send({
        message: 'an account with this email already exists',
      });
    }
    if (!registeredUser) {
      return Users.create({
        fullname: req.body.fullname,
        password: passwordHash(req.body.password),
        email: req.body.email,
        roleId: 2,
      });
    }
  })
  .then(newUser => res.status(201).send({
    user: {
      userId: newUser.userId,
      fullname: newUser.fullname,
      email: newUser.email,
      roleId: newUser.roleId,
      created: newUser.createdAt,
    },
  }))
  .catch(() => catchError(res));
};

/**
 * @description authenticates user and generates token
 * @function loginUser
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object containing access token
 */
const loginUser = (req, res) => {
  req.checkBody('email', 'Email cannot be empty').notEmpty();
  req.checkBody('email', 'Enter a valid email address').isEmail();
  req.checkBody('password', 'Password cannot be empty').notEmpty();

  returnValidationErrors(req, res);

  Users.findOne({
    where: { email: req.body.email },
  })
  .then((user) => {
    if (!user) {
      return res.status(401).send({
        message: 'This email is not associated with any account',
      });
    }

    const token = authenticateUser(req.body.password, user);

    if (token) {
      return res.status(200).send({
        accessToken: token,
      });
    }
    return res.status(401).send({
      message: 'Authentication failed. Password is incorrect',
    });
  })
  .catch(() => catchError(res));
};

/**
 * @description view all user details
 * @function viewUser
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object of all users
 */
const viewUser = (req, res) => {
  /** set default values for offset and limit */
  let offset = 0;
  let limit = 20;
  if (req.query.limit || req.query.offset) {
    req.checkQuery('limit', 'Limit must be an integer and greater than 0').isInt({ gt: 0 });
    req.checkQuery('offset', 'Offset must be an integer greater or equal to 0').isInt({ gt: -1 });

    returnValidationErrors(req, res);

    /** convert limit and offset to number in base 10 */
    limit = parseInt(req.query.limit, 10);
    offset = parseInt(req.query.offset, 10);
  }

  Users.findAndCount({
    include: [
      {
        model: Roles,
        required: true,
        attributes: { exclude: ['createdAt', 'updatedAt'] },
      }
    ],
    offset,
    limit,
    attributes: { exclude: ['email', 'password', 'updatedAt', 'roleId'] },
  })
  .then(users => res.status(200).send({
    pagination: pagination(limit, offset, users.count),
    users: users.rows.filter(user => user.userId !== 1),
  }))
  .catch(() => catchError(res));
};

/**
 * @description gets user details using id
 * @function getUserById
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object of matching user
 */
const getUserById = (req, res) => {
  req.checkParams('id', 'No user id supplied').notEmpty();
  req.checkParams('id', 'Only integers are allowed as user id').isInt();

  returnValidationErrors(req, res);

  Users.findOne({
    where: { userId: req.params.id },
    include: [
      {
        model: Roles,
        required: true,
        attributes: { exclude: ['createdAt', 'updatedAt'] },
      }
    ],
    attributes: { exclude: ['password', 'roleId'] },
  })
  .then((user) => {
    if (!user) {
      return res.status(404).send({
        message: 'This user does not exist or has been previously deleted',
      });
    }

    return res.status(200).send({
      user,
    });
  })
  .catch(() => catchError(res));
};

/**
 * @description updates user details
 * @function updateUser
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object containing updated user details
 */
const updateUser = (req, res) => {
  req.checkParams('id', 'No user id supplied').notEmpty();
  req.checkParams('id', 'Only integers are allowed as user id').isInt();
  req.checkBody('email', 'Email cannot be empty').notEmpty();
  req.checkBody('email', 'Enter a valid email address').isEmail();
  req.checkBody('password', 'Password cannot be empty').notEmpty();
  req.checkBody('oldPassword', 'Enter your current password to confirm password change').notEmpty();

  returnValidationErrors(req, res);

  Users.findOne({
    where: { userId: req.params.id },
    plain: true
  })
  .then((user) => {
    user.get({ plain: true });

    if (req.body.password && !verifyPassword(req.body.oldPassword, user.password)) {
      return res.status(403).send({
        message: 'Password confirmation failed. Enter your current password to confirm password change'
      });
    }

    const password = req.body.password ? passwordHash(req.body.password) : user.password;

    return user.update({
      password,
      fullname: req.body.fullname || user.fullname,
      email: req.body.email || user.email,
      roleId: user.roleId,
    });
  })
  .then(updatedUser => res.status(200).send({
    user: {
      userId: updatedUser.userId,
      fullname: updatedUser.fullname,
      email: updatedUser.email,
    },
  }))
  .catch(() => catchError(res));
};

/**
 * @description deletes user
 * @function deleteUser
 * @param {object} req request object
 * @param {object} res response object
 * @returns {void}
 */
const deleteUser = (req, res) => {
  req.checkParams('id', 'No user id supplied').notEmpty();
  req.checkParams('id', 'Only integers are allowed as user id').isInt();

  returnValidationErrors(req, res);

  if (parseInt(req.params.id, 10) === 1) {
    return res.status(403).send({
      message: 'You cannot delete this user',
    });
  }

  Users.findOne({
    where: { userId: req.params.id },
  })
  .then((user) => {
    if (!user) {
      return res.status(404).send({
        message: 'This user does not exist or has been previously deleted',
      });
    }

    return user.destroy();
  })
  .then(() => res.status(200).json({
    message: 'User was successfully deleted',
  }))
  .catch(() => catchError(res));
};

/**
 * @description gets all documents belonging a particular user
 * @function getUserDocuments
 * @param {object} req request object
 * @param {object} res response object
 * @returns {object} response object containing doccuments
 */
const getUserDocuments = (req, res) => {
  req.checkParams('id', 'No user id supplied').notEmpty();
  req.checkParams('id', 'Only integers are allowed as user id').isInt();

  returnValidationErrors(req, res);
  Users.findOne({
    where: { userId: req.params.id },
  })
  .then((user) => {
    if (!user) {
      return res.status(404).send({
        message: 'This user does not exist or has been previously deleted',
      });
    }

    return Documents.findAll({
      where: {
        userId: req.params.id,
      },
      attributes: { exclude: ['content', 'userId'] },
    });
  })
  .then((documents) => {
    if (documents.length === 0) {
      return res.status(404).send({
        message: 'No document associated with this user',
      });
    }
    return res.status(200).send({
      documents,
    });
  })
  .catch(() => catchError(res));
};

export default {
  createUser,
  viewUser,
  getUserById,
  updateUser,
  deleteUser,
  loginUser,
  getUserDocuments,
};


text:
namespace rime {

void ModuleManager::Register(const string& name,
                              RimeModule* module) {
  map_[name] = module;
}

RimeModule* ModuleManager::Find(const string& name) {
  ModuleMap::const_iterator it = map_.find(name);
  if (it != map_.end()) {
    return it->second;
  }
  return NULL;
}

void ModuleManager::LoadModule(RimeModule* module) {
  if (!module ||
      loaded_.find(module) != loaded_.end()) {
    return;
  }
  DLOG(INFO) << "loading module: " << module;
  loaded_.insert(module);
  if (module->initialize != NULL) {
    module->initialize();
  }
  else {
    LOG(WARNING) << "missing initialize() function in module: " << module;
  }
}

void ModuleManager::UnloadModules() {
  for (auto module : loaded_) {
    if (module->finalize != NULL) {
      module->finalize();
    }
  }
  loaded_.clear();
}

ModuleManager& ModuleManager::instance() {
  static the<ModuleManager> s_instance;
  if (!s_instance) {
    s_instance.reset(new ModuleManager);
  }
  return *s_instance;
}

}  // namespace rime


text:
import {firstValueFrom, lastValueFrom, NEVER, of} from 'rxjs';

import {initTestEnvironment} from '../testing';

import {cacheLatest, StorageCache} from './cache';

initTestEnvironment();

class MapStorage implements Storage {
  private readonly map = new Map<string, string>();

  get length(): number {
    return this.map.size;
  }

  clear(): void {
    this.map.clear();
  }

  getItem(key: string): string|null {
    return this.map.get(key) ?? null;
  }

  key(index: number): string|null {
    return Array.from(this.map.keys())[index];
  }

  removeItem(key: string): void {
    this.map.delete(key);
  }

  setItem(key: string, value: string): void {
    this.map.set(key, value);
  }
}

describe('cache', () => {
  it('writes emitted values to storage', async () => {
    const storage = new StorageCache<number>(new MapStorage());
    const observable = of(1, 2, 3).pipe(cacheLatest('foo', storage));
    await lastValueFrom(observable);
    expect(storage.getItem('foo')).toBeTruthy();
  });

  it('emits the stored value', async () => {
    const storage = new StorageCache<number>(new MapStorage());
    of(3).pipe(cacheLatest('foo', storage)).subscribe();

    const cachedValue =
        await firstValueFrom(NEVER.pipe(cacheLatest<number>('foo', storage)));
    expect(cachedValue).toEqual(3);
  });

  it('correctly retains JSON-like data', async () => {
    const storage = new StorageCache<{}>(new MapStorage());
    of({a: 42, b: 'foo', c: {d: [true]}})
        .pipe(cacheLatest('foo', storage))
        .subscribe();

    const cachedValue =
        await firstValueFrom(NEVER.pipe(cacheLatest<{}>('foo', storage)));
    expect(cachedValue).toEqual({a: 42, b: 'foo', c: {d: [true]}});
  });

  it('passes through original data', async () => {
    const storage = new StorageCache<number>(new MapStorage());
    const original$ = of(42).pipe(cacheLatest('foo', storage));
    const originalValue = await lastValueFrom(original$);
    expect(originalValue).toEqual(42);

    const cached$ = of(99).pipe(cacheLatest<number>('foo', storage));
    const cachedValue = await firstValueFrom(cached$);
    expect(cachedValue).toEqual(42);

    const newValue = await lastValueFrom(cached$);
    expect(newValue).toEqual(99);
  });
});


text:
package rx.internal.operators;

import rx.*;
import rx.exceptions.Exceptions;
import rx.functions.Action0;

/**
 * Call an Action0 when the subscription happens to the source.
 *
 * @param <T> the value type
 */
public final class SingleDoOnSubscribe<T> implements Single.OnSubscribe<T> {

    final Single.OnSubscribe<T> source;

    final Action0 onSubscribe;

    public SingleDoOnSubscribe(Single.OnSubscribe<T> source, Action0 onSubscribe) {
        this.source = source;
        this.onSubscribe = onSubscribe;
    }

    @Override
    public void call(SingleSubscriber<? super T> t) {

        try {
            onSubscribe.call();
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            t.onError(ex);
            return;
        }

        source.call(t);
    }
}


text:
package com.zaxxer.hikari.pool;

import static com.zaxxer.hikari.util.UtilityElf.createInstance;

import java.lang.management.ManagementFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.util.DefaultThreadFactory;
import com.zaxxer.hikari.util.DriverDataSource;
import com.zaxxer.hikari.util.PropertyElf;
import com.zaxxer.hikari.util.UtilityElf;

abstract class PoolBase
{
   protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
   protected final HikariConfig config;
   protected long connectionTimeout;

   private static final String[] RESET_STATES = {"readOnly", "autoCommit", "isolation", "catalog", "netTimeout"};
   private static final int UNINITIALIZED = -1;
   private static final int TRUE = 1;
   private static final int FALSE = 0;

   private int networkTimeout;
   private int transactionIsolation;
   private int isNetworkTimeoutSupported;
   private int isQueryTimeoutSupported;
   private Executor netTimeoutExecutor;
   private DataSource dataSource;

   // private final HikariPool hikariPool;
   private final String poolName;
   private final String catalog;
   private final boolean isReadOnly;
   private final boolean isAutoCommit;
   private final boolean isUseJdbc4Validation;
   private final boolean isIsolateInternalQueries;
   private final AtomicReference<Throwable> lastConnectionFailure;

   private volatile boolean isValidChecked;

   public PoolBase(final HikariConfig config)
   {
      this.config = config;

      this.networkTimeout = -1;
      this.catalog = config.getCatalog();
      this.isReadOnly = config.isReadOnly();
      this.isAutoCommit = config.isAutoCommit();
      this.transactionIsolation = UtilityElf.getTransactionIsolation(config.getTransactionIsolation());

      this.isQueryTimeoutSupported = UNINITIALIZED;
      this.isNetworkTimeoutSupported = UNINITIALIZED;
      this.isUseJdbc4Validation = config.getConnectionTestQuery() == null;
      this.isIsolateInternalQueries = config.isIsolateInternalQueries();

      this.poolName = config.getPoolName();
      this.connectionTimeout = config.getConnectionTimeout();
      this.lastConnectionFailure = new AtomicReference<>();

      initializeDataSource();
   }

   public String getPoolName()
   {
      return poolName;
   }

   abstract void releaseConnection(final PoolEntry poolEntry);

   // ***********************************************************************
   //                           JDBC methods
   // ***********************************************************************

   public void quietlyCloseConnection(final Connection connection, final String closureReason)
   {
      try {
         if (connection == null || connection.isClosed()) {
            return;
         }

         LOGGER.debug("{} - Closing connection {}: {}", poolName, connection, closureReason);
         try {
            setNetworkTimeout(connection, TimeUnit.SECONDS.toMillis(15));
         }
         finally {
            // continue with the close even if setNetworkTimeout() throws (due to driver poorly behaving drivers)
            connection.close();
         }
      }
      catch (Throwable e) {
         LOGGER.debug("{} - Closing connection {} failed", poolName, connection, e);
      }
   }

   public boolean isConnectionAlive(final Connection connection)
   {
      try {
         final long validationTimeout = config.getValidationTimeout();

         if (isUseJdbc4Validation) {
            return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(validationTimeout));
         }

         final int originalTimeout = getAndSetNetworkTimeout(connection, validationTimeout);

         try (Statement statement = connection.createStatement()) {
            if (isNetworkTimeoutSupported != TRUE) {
               setQueryTimeout(statement, (int) TimeUnit.MILLISECONDS.toSeconds(validationTimeout));
            }

            statement.execute(config.getConnectionTestQuery());
         }

         if (isIsolateInternalQueries && !isAutoCommit) {
            connection.rollback();
         }

         setNetworkTimeout(connection, originalTimeout);

         return true;
      }
      catch (SQLException e) {
         lastConnectionFailure.set(e);
         LOGGER.warn("{} - Connection {} failed alive test with exception {}", poolName, connection, e.getMessage());
         return false;
      }
   }

   public DataSource getUnwrappedDataSource()
   {
      return dataSource;
   }

   public Throwable getLastConnectionFailure()
   {
      return lastConnectionFailure.getAndSet(null);
   }

   // ***********************************************************************
   //                         PoolEntry methods
   // ***********************************************************************

   public PoolEntry newPoolEntry() throws Exception
   {
      return new PoolEntry(newConnection(), this);
   }

   public void resetConnectionState(final Connection connection, final ProxyConnection proxyConnection, final int dirtyBits) throws SQLException
   {
      int resetBits = 0;

      if ((dirtyBits & 0b00001) != 0 && proxyConnection.getReadOnlyState() != isReadOnly) {
         connection.setReadOnly(isReadOnly);
         resetBits |= 0b00001;
      }

      if ((dirtyBits & 0b00010) != 0 && proxyConnection.getAutoCommitState() != isAutoCommit) {
         connection.setAutoCommit(isAutoCommit);
         resetBits |= 0b00010;
      }

      if ((dirtyBits & 0b00100) != 0 && proxyConnection.getTransactionIsolationState() != transactionIsolation) {
         connection.setTransactionIsolation(transactionIsolation);
         resetBits |= 0b00100;
      }

      if ((dirtyBits & 0b01000) != 0) {
         final String currentCatalog = proxyConnection.getCatalogState();
         if ((currentCatalog != null && !currentCatalog.equals(catalog)) || (currentCatalog == null && catalog != null)) {
            connection.setCatalog(catalog);
            resetBits |= 0b01000;
         }
      }

      if ((dirtyBits & 0b10000) != 0 && proxyConnection.getNetworkTimeoutState() != networkTimeout) {
         setNetworkTimeout(connection, networkTimeout);
         resetBits |= 0b10000;
      }

      if (LOGGER.isDebugEnabled()) {
         LOGGER.debug("{} - Reset ({}) on connection {}", poolName, resetBits != 0 ? stringFromResetBits(resetBits) : "nothing", connection);
      }
   }

   // ***********************************************************************
   //                       PoolMediator methods
   // ***********************************************************************

   /**
    * Register MBeans for HikariConfig and HikariPool.
    *
    * @param pool a HikariPool instance
    */
   public void registerMBeans(final HikariPool hikariPool)
   {
      if (!config.isRegisterMbeans()) {
         return;
      }

      try {
         final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

         final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
         final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
         if (!mBeanServer.isRegistered(beanConfigName)) {
            mBeanServer.registerMBean(config, beanConfigName);
            mBeanServer.registerMBean(hikariPool, beanPoolName);
         }
         else {
            LOGGER.error("{} - You cannot use the same pool name for separate pool instances.", poolName);
         }
      }
      catch (Exception e) {
         LOGGER.warn("{} - Unable to register management beans.", poolName, e);
      }
   }

   /**
    * Unregister MBeans for HikariConfig and HikariPool.
    */
   public void unregisterMBeans()
   {
      if (!config.isRegisterMbeans()) {
         return;
      }

      try {
         final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

         final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
         final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
         if (mBeanServer.isRegistered(beanConfigName)) {
            mBeanServer.unregisterMBean(beanConfigName);
            mBeanServer.unregisterMBean(beanPoolName);
         }
      }
      catch (Exception e) {
         LOGGER.warn("{} - Unable to unregister management beans.", poolName, e);
      }
   }

   public void shutdownNetworkTimeoutExecutor()
   {
      if (netTimeoutExecutor != null && netTimeoutExecutor instanceof ThreadPoolExecutor) {
         ((ThreadPoolExecutor) netTimeoutExecutor).shutdownNow();
      }
   }

   // ***********************************************************************
   //                          Private methods
   // ***********************************************************************

   /**
    * Create/initialize the underlying DataSource.
    *
    * @return a DataSource instance
    */
   private void initializeDataSource()
   {
      final String jdbcUrl = config.getJdbcUrl();
      final String username = config.getUsername();
      final String password = config.getPassword();
      final String dsClassName = config.getDataSourceClassName();
      final String driverClassName = config.getDriverClassName();
      final Properties dataSourceProperties = config.getDataSourceProperties();

      DataSource dataSource = config.getDataSource();
      if (dsClassName != null && dataSource == null) {
         dataSource = createInstance(dsClassName, DataSource.class);
         PropertyElf.setTargetFromProperties(dataSource, dataSourceProperties);
      }
      else if (jdbcUrl != null && dataSource == null) {
         dataSource = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
      }

      if (dataSource != null) {
         setLoginTimeout(dataSource, connectionTimeout);
         createNetworkTimeoutExecutor(dataSource, dsClassName, jdbcUrl);
      }

      this.dataSource = dataSource;
   }

   private Connection newConnection() throws Exception
   {
      Connection connection = null;
      try {
         String username = config.getUsername();
         String password = config.getPassword();

         connection = (username == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);
         setupConnection(connection);
         lastConnectionFailure.set(null);
         return connection;
      }
      catch (Exception e) {
         lastConnectionFailure.set(e);
         quietlyCloseConnection(connection, "(exception during connection creation)");
         throw e;
      }
   }

   /**
    * Setup a connection initial state.
    *
    * @param connection a Connection
    * @throws SQLException thrown from driver
    */
   private void setupConnection(final Connection connection) throws SQLException
   {
      networkTimeout = getAndSetNetworkTimeout(connection, connectionTimeout);

      checkValidationMode(connection);

      connection.setAutoCommit(isAutoCommit);
      connection.setReadOnly(isReadOnly);

      final int defaultLevel = connection.getTransactionIsolation();
      transactionIsolation = (transactionIsolation < 0 || defaultLevel == Connection.TRANSACTION_NONE)
                           ? defaultLevel
                           : transactionIsolation;
      if (transactionIsolation != defaultLevel) {
         connection.setTransactionIsolation(transactionIsolation);
      }

      if (catalog != null) {
         connection.setCatalog(catalog);
      }

      executeSql(connection, config.getConnectionInitSql(), !isAutoCommit, false);

      setNetworkTimeout(connection, networkTimeout);
   }

   /**
    * Execute isValid() or connection test query.
    *
    * @param connection a Connection to check
    */
   private void checkValidationMode(final Connection connection) throws SQLException
   {
      if (!isValidChecked) {
         if (isUseJdbc4Validation) {
            try {
               connection.isValid(1);
            }
            catch (Throwable e) {
               LOGGER.debug("{} - Connection.isValid() is not supported, configure connection test query. ({})", poolName, e.getMessage());
               throw e;
            }
         }
         else {
            try {
               executeSql(connection, config.getConnectionTestQuery(), false, isIsolateInternalQueries && !isAutoCommit);
            }
            catch (Throwable e) {
               LOGGER.debug("{} - Exception during executing connection test query. ({})", poolName, e.getMessage());
               throw e;
            }
         }
         isValidChecked = true;
      }
   }

   /**
    * Set the query timeout, if it is supported by the driver.
    *
    * @param statement a statement to set the query timeout on
    * @param timeoutSec the number of seconds before timeout
    */
   private void setQueryTimeout(final Statement statement, final int timeoutSec)
   {
      if (isQueryTimeoutSupported != FALSE) {
         try {
            statement.setQueryTimeout(timeoutSec);
            isQueryTimeoutSupported = TRUE;
         }
         catch (Throwable e) {
            if (isQueryTimeoutSupported == UNINITIALIZED) {
               isQueryTimeoutSupported = FALSE;
               LOGGER.debug("{} - Statement.setQueryTimeout() is not supported ({})", poolName, e.getMessage());
            }
         }
      }
   }

   /**
    * Set the network timeout, if isUseNetworkTimeout is true and the
    * driver supports it.  Return the pre-existing value of the network timeout.
    *
    * @param connection the connection to set the network timeout on
    * @param timeoutMs the number of milliseconds before timeout
    * @return the pre-existing network timeout value
    */
   private int getAndSetNetworkTimeout(final Connection connection, final long timeoutMs)
   {
      if (isNetworkTimeoutSupported != FALSE) {
         try {
            final int originalTimeout = connection.getNetworkTimeout();
            connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
            isNetworkTimeoutSupported = TRUE;
            return originalTimeout;
         }
         catch (Throwable e) {
            if (isNetworkTimeoutSupported == UNINITIALIZED) {
               isNetworkTimeoutSupported = FALSE;
               LOGGER.debug("{} - Connection.setNetworkTimeout() is not supported ({})", poolName, e.getMessage());
            }
         }
      }

      return 0;
   }

   /**
    * Set the network timeout, if isUseNetworkTimeout is true and the
    * driver supports it.
    *
    * @param connection the connection to set the network timeout on
    * @param timeoutMs the number of milliseconds before timeout
    * @throws SQLException throw if the connection.setNetworkTimeout() call throws
    */
   private void setNetworkTimeout(final Connection connection, final long timeoutMs) throws SQLException
   {
      if (isNetworkTimeoutSupported == TRUE) {
         connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
      }
   }

   /**
    * Execute the user-specified init SQL.
    *
    * @param connection the connection to initialize
    * @param sql the SQL to execute
    * @param isAutoCommit whether to commit the SQL after execution or not
    * @throws SQLException throws if the init SQL execution fails
    */
   private void executeSql(final Connection connection, final String sql, final boolean isCommit, final boolean isRollback) throws SQLException
   {
      if (sql != null) {
         try (Statement statement = connection.createStatement()) {

            statement.execute(sql);

            if (isCommit) {
               connection.commit();
            }
            else if (isRollback) {
               connection.rollback();
            }
         }
      }
   }

   private void createNetworkTimeoutExecutor(final DataSource dataSource, final String dsClassName, final String jdbcUrl)
   {
      // Temporary hack for MySQL issue: http://bugs.mysql.com/bug.php?id=75615
      if ((dsClassName != null && dsClassName.contains("Mysql")) ||
          (jdbcUrl != null && jdbcUrl.contains("mysql")) ||
          (dataSource != null && dataSource.getClass().getName().contains("Mysql"))) {
         netTimeoutExecutor = new SynchronousExecutor();
      }
      else {
         ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory("Hikari JDBC-timeout executor", true);
         ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(threadFactory);
         executor.allowCoreThreadTimeOut(true);
         executor.setKeepAliveTime(15, TimeUnit.SECONDS);
         netTimeoutExecutor = executor;
      }
   }

   private static class SynchronousExecutor implements Executor
   {
      /** {@inheritDoc} */
      @Override
      public void execute(Runnable command)
      {
         try {
            command.run();
         }
         catch (Throwable t) {
            LoggerFactory.getLogger(PoolBase.class).debug("Exception executing {}", command, t);
         }
      }
   }

   /**
    * Set the loginTimeout on the specified DataSource.
    *
    * @param dataSource the DataSource
    * @param connectionTimeout the timeout in milliseconds
    */
   private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout)
   {
      if (connectionTimeout != Integer.MAX_VALUE) {
         try {
            dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout)));
         }
         catch (SQLException e) {
            LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e);
         }
      }
   }

   /**
    * This will create a string for debug logging. Given a set of "reset bits", this
    * method will return a concatenated string, for example:
    *
    * Input : 0b00110
    * Output: "autoCommit, isolation"
    *
    * @param bits a set of "reset bits"
    * @return a string of which states were reset
    */
   private String stringFromResetBits(final int bits)
   {
      final StringBuilder sb = new StringBuilder();
      for (int ndx = 0; ndx < RESET_STATES.length; ndx++) {
         if ( (bits & (0b1 << ndx)) != 0) {
            sb.append(RESET_STATES[ndx]).append(", ");
         }
      }

      sb.setLength(sb.length() - 2);  // trim trailing comma
      return sb.toString();
   }
}


text:
<?php

namespace spec\Phorm\Element;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ContentSpec extends ObjectBehavior {
	function it_is_initializable() {
		$this->shouldHaveType('Phorm\Element\Content');
	}

	function it_has_content() {
		$this->setContent('test');
		$this->getContent()->shouldReturn('test');
	}

	function it_is_chainable() {
		$this->setContent('test')->shouldHaveType('Phorm\Element\Content');
	}
}


text:
package v2ch02.objectStream;

import java.io.*;

/**
 * @version 1.10 17 Aug 1998
 * @author Cay Horstmann
 */
class ObjectStreamTest
{
   public static void main(String[] args) throws IOException, ClassNotFoundException
   {
      Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      carl.setSecretary(harry);
      Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
      tony.setSecretary(harry);

      Employee[] staff = new Employee[3];

      staff[0] = carl;
      staff[1] = harry;
      staff[2] = tony;

      // save all employee records to the file employee.dat
      try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat")))
      {
         out.writeObject(staff);
      }

      try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat")))
      {
         // retrieve all records into a new array

         Employee[] newStaff = (Employee[]) in.readObject();

         // raise secretary's salary
         newStaff[1].raiseSalary(10);

         // print the newly read employee records
         for (Employee e : newStaff)
            System.out.println(e);
      }
   }
}


text:
"use strict";
exports.__esModule = true;
var net = require("net");
var index_1 = require("./index");
var ON = 0x23;
var OFF = 0x24;
var PERSIST = 0x31;
var MODE_CUSTOM = 0x60;
var MODE_NORM1 = 0x61;
var MODE_NORM2 = 0x62;
var cmdGetState = makeCommand([0x81, 0x8a, 0x8b]);
var cmdGetTimers = makeCommand([0x22, 0x2a, 0x2b, 0x0f]);
var cmdOn = makeCommand([0x71, ON, 0x0f]);
var cmdOff = makeCommand([0x71, OFF, 0x0f]);
function byte(num) { return num & 0xff; }
function checksum(arr) { return byte(arr.reduce(function (acc, num) { return acc + num; }, 0)); }
function makeCommand(arr) {
    arr.push(checksum(arr));
    return Buffer.from(arr);
}
function bufstr(command) {
    return command.toJSON().data.map(function (value) { return (value < 16 ? "0" : "") + value.toString(16); }).join(",");
}
function sendCommandRaw(socket, command, keepalive) {
    if (keepalive === void 0) { keepalive = false; }
    return new Promise(function (resolve, reject) {
        if (keepalive) {
            socket.write(command, function (err) {
                if (err) {
                    return reject(err);
                }
                index_1.log.debug("   Sent: " + bufstr(command));
                resolve("write[" + bufstr(command) + "]");
            });
        }
        else {
            socket.end(command, function (err) {
                if (err) {
                    return reject(err);
                }
                index_1.log.debug("   Sent: " + bufstr(command));
                resolve("end[" + bufstr(command) + "]");
            });
        }
    });
}
function warmCommand(level) {
    return makeCommand([PERSIST, 0, 0, 0, level <= 1 ? Math.floor(level * 255) : level, 0x0f, 0x0f]);
}
function colorCommand(r, g, b) {
    return makeCommand([PERSIST, byte(r), byte(g), byte(b), 0x00, 0xf0, 0x0f]);
}
function padnum(num, radix) {
    if (radix === void 0) { radix = 10; }
    return num < radix ? "0" + num.toString(radix) : num.toString(radix);
}
var Color = (function () {
    function Color(red, green, blue) {
        this.red = red;
        this.green = green;
        this.blue = blue;
        if (red < 0) {
            this.red = 0;
        }
        else if (red > 255) {
            this.red = 255;
        }
        if (green < 0) {
            this.green = 0;
        }
        else if (green > 255) {
            this.green = 255;
        }
        if (blue < 0) {
            this.blue = 0;
        }
        else if (blue > 255) {
            this.blue = 255;
        }
    }
    Color.prototype.brightness = function () {
        var nr = this.red / 255;
        var ng = this.green / 255;
        var nb = this.blue / 255;
        return Math.sqrt((0.299 * nr * nr) + (0.587 * ng * ng) + (0.114 * nb * nb));
    };
    Color.prototype.darker = function (percent) {
        return new Color(this.red * (1 - percent), this.green * (1 - percent), this.blue * (1 - percent));
    };
    Color.prototype.lighter = function (percent) {
        var rAugment = (255 - this.red) * percent;
        var gAugment = (255 - this.green) * percent;
        var bAugment = (255 - this.blue) * percent;
        return new Color(this.red + rAugment, this.green + gAugment, this.blue + bAugment);
    };
    Color.prototype.toString = function () {
        return "#" + padnum(this.red, 16) + padnum(this.green, 16) + padnum(this.blue, 16);
    };
    return Color;
}());
exports.Color = Color;
var PresetPatterns;
(function (PresetPatterns) {
    PresetPatterns[PresetPatterns["SevenColorCrossFade"] = 37] = "SevenColorCrossFade";
    PresetPatterns[PresetPatterns["RedGradualChange"] = 38] = "RedGradualChange";
    PresetPatterns[PresetPatterns["GreenGradualChange"] = 39] = "GreenGradualChange";
    PresetPatterns[PresetPatterns["BlueGradualChange"] = 40] = "BlueGradualChange";
    PresetPatterns[PresetPatterns["YellowGradualChange"] = 41] = "YellowGradualChange";
    PresetPatterns[PresetPatterns["CyanGradualChange"] = 42] = "CyanGradualChange";
    PresetPatterns[PresetPatterns["PurpleGradualChange"] = 43] = "PurpleGradualChange";
    PresetPatterns[PresetPatterns["WhiteGradualChange"] = 44] = "WhiteGradualChange";
    PresetPatterns[PresetPatterns["RedGreenCrossFade"] = 45] = "RedGreenCrossFade";
    PresetPatterns[PresetPatterns["RedBlueCrossFade"] = 46] = "RedBlueCrossFade";
    PresetPatterns[PresetPatterns["GreenBlueCrossFade"] = 47] = "GreenBlueCrossFade";
    PresetPatterns[PresetPatterns["SevenColorStrobeFlash"] = 48] = "SevenColorStrobeFlash";
    PresetPatterns[PresetPatterns["RedStrobeFlash"] = 49] = "RedStrobeFlash";
    PresetPatterns[PresetPatterns["GreenStrobeFlash"] = 50] = "GreenStrobeFlash";
    PresetPatterns[PresetPatterns["BlueStobeFlash"] = 51] = "BlueStobeFlash";
    PresetPatterns[PresetPatterns["YellowStrobeFlash"] = 52] = "YellowStrobeFlash";
    PresetPatterns[PresetPatterns["CyanStrobeFlash"] = 53] = "CyanStrobeFlash";
    PresetPatterns[PresetPatterns["PurpleStrobeFlash"] = 54] = "PurpleStrobeFlash";
    PresetPatterns[PresetPatterns["WhiteStrobeFlash"] = 55] = "WhiteStrobeFlash";
    PresetPatterns[PresetPatterns["SevenColorJumping"] = 56] = "SevenColorJumping";
})(PresetPatterns = exports.PresetPatterns || (exports.PresetPatterns = {}));
var FluxBulbState = (function () {
    function FluxBulbState(status) {
        this.on = status[2] === ON;
        var pattern = status[3];
        var level = status[9];
        this.mode = "unknown";
        this.determineMode(pattern, level);
        switch (this.mode) {
            case "ww":
                this.brightness = level / 255;
                break;
            case "color":
                this.color = new Color(status[6], status[7], status[8]);
                this.brightness = this.color.brightness();
                break;
        }
    }
    FluxBulbState.prototype.determineMode = function (pattern, level) {
        if (pattern === MODE_NORM1 || pattern === MODE_NORM2) {
            this.mode = level === 0 ? "color" : "ww";
        }
        else if (pattern === MODE_CUSTOM) {
            this.mode = "custom";
        }
        else if (this.isPresetPattern(pattern)) {
            this.mode = "preset";
            this.pattern = PresetPatterns[pattern];
        }
    };
    FluxBulbState.prototype.isPresetPattern = function (pattern) { return pattern >= 0x25 && pattern <= 0x38; };
    FluxBulbState.prototype.toString = function () {
        var str = "FluxBulbState(on=" + this.on + ",mode=" + this.mode;
        if (this.mode === "color") {
            str += ",brightness=" + Math.round(this.brightness * 100) + "%,color=" + this.color.toString() + ")";
        }
        else if (this.mode === "ww") {
            str += ",brightness=" + Math.round(this.brightness * 100) + "%)";
        }
        else if (this.mode === "preset") {
            str += ",pattern=" + this.pattern + ")";
        }
        else {
            str += ")";
        }
        return str;
    };
    return FluxBulbState;
}());
exports.FluxBulbState = FluxBulbState;
var defaultPort = 5577;
var defaultOptions = {
    timeout: 5000
};
var FluxBulb = (function () {
    function FluxBulb(host, port, options) {
        if (port === void 0) { port = defaultPort; }
        this.host = host;
        this.port = port || defaultPort;
        this.opts = options || defaultOptions;
    }
    FluxBulb.prototype.connect = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var sock = net.connect(_this.port, _this.host, function () {
                resolve(sock);
            });
            sock.on("error", function (err) { reject(err); });
            sock.setTimeout(_this.opts.timeout, function () { reject("Timeout Error"); });
        });
    };
    FluxBulb.prototype.sendCommand = function (cmd) {
        return this.connect().then(function (sock) {
            sendCommandRaw(sock, cmd, false);
        });
    };
    FluxBulb.prototype.getState = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.connect().then(function (sock) {
                sock.once("data", function (stateData) {
                    sock.destroy();
                    resolve(new FluxBulbState(stateData));
                });
                sendCommandRaw(sock, cmdGetState, true);
            });
        });
    };
    FluxBulb.prototype.turn = function (on) { this.sendCommand(on ? cmdOn : cmdOff); };
    FluxBulb.prototype.turnOn = function () { this.turn(true); };
    FluxBulb.prototype.turnOff = function () { this.turn(false); };
    FluxBulb.prototype.setWarm = function (level) {
        this.sendCommand(warmCommand(level));
    };
    FluxBulb.prototype.setColor = function (color) {
        this.setRGB(color.red, color.green, color.blue);
    };
    FluxBulb.prototype.setRGB = function (r, g, b) {
        this.sendCommand(colorCommand(r, g, b));
    };
    FluxBulb.prototype.darken = function (percent) {
        var _this = this;
        this.getState().then(function (state) {
            if (state.mode === "ww") {
                _this.setWarm(Math.max(0, state.brightness * (1 - percent)));
            }
            else if (state.mode === "color") {
                _this.setColor(state.color.darker(percent));
            }
        });
    };
    FluxBulb.prototype.brighten = function (percent) {
        var _this = this;
        this.getState().then(function (state) {
            if (state.mode === "ww") {
                _this.setWarm(Math.min(1, state.brightness * (1 + percent)));
            }
            else if (state.mode === "color") {
                _this.setColor(state.color.lighter(percent));
            }
        });
    };
    return FluxBulb;
}());
exports.FluxBulb = FluxBulb;


text:
import CurrentTrack from './CurrentTrack'

export default CurrentTrack