text:
%% bare_jrnl_compsoc.tex
%% V1.3
%% 2007/01/11
%% by Michael Shell
%% See:
%% http://www.michaelshell.org/
%% for current contact information.
%%
%% This is a skeleton file demonstrating the use of IEEEtran.cls
%% (requires IEEEtran.cls version 1.7 or later) with an IEEE Computer
%% Society journal paper.
%%
%% Support sites:
%% http://www.michaelshell.org/tex/ieeetran/
%% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/
%% and
%% http://www.ieee.org/

%%*************************************************************************
%% Legal Notice:
%% This code is offered as-is without any warranty either expressed or
%% implied; without even the implied warranty of MERCHANTABILITY or
%% FITNESS FOR A PARTICULAR PURPOSE!
%% User assumes all risk.
%% In no event shall IEEE or any contributor to this code be liable for
%% any damages or losses, including, but not limited to, incidental,
%% consequential, or any other damages, resulting from the use or misuse
%% of any information contained here.
%%
%% All comments are the opinions of their respective authors and are not
%% necessarily endorsed by the IEEE.
%%
%% This work is distributed under the LaTeX Project Public License (LPPL)
%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used,
%% distributed and modified. A copy of the LPPL, version 1.3, is included
%% in the base LaTeX documentation of all distributions of LaTeX released
%% 2003/12/01 or later.
%% Retain all contribution notices and credits.
%% ** Modified files should be clearly indicated as such, including  **
%% ** renaming them and changing author support contact information. **
%%
%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex,
%%                    bare_conf.tex, bare_jrnl.tex, bare_jrnl_compsoc.tex
%%*************************************************************************

% *** Authors should verify (and, if needed, correct) their LaTeX system  ***
% *** with the testflow diagnostic prior to trusting their LaTeX platform ***
% *** with production work. IEEE's font choices can trigger bugs that do  ***
% *** not appear when using other class files.                            ***
% The testflow support page is at:
% http://www.michaelshell.org/tex/testflow/

% Note that the a4paper option is mainly intended so that authors in
% countries using A4 can easily print to A4 and see how their papers will
% look in print - the typesetting of the document will not typically be
% affected with changes in paper size (but the bottom and side margins will).
% Use the testflow package mentioned above to verify correct handling of
% both paper sizes by the user's LaTeX system.
%
% Also note that the "draftcls" or "draftclsnofoot", not "draft", option
% should be used if it is desired that the figures are to be displayed in
% draft mode.
%
% The Computer Society usually requires 12pt for submissions.
%
\documentclass[12pt,journal,compsoc]{IEEEtran}
%
% If IEEEtran.cls has not been installed into the LaTeX system files,
% manually specify the path to it like:
% \documentclass[12pt,journal,compsoc]{../sty/IEEEtran}

% Some very useful LaTeX packages include:
% (uncomment the ones you want to load)

% *** MISC UTILITY PACKAGES ***
%
%\usepackage{ifpdf}
% Heiko Oberdiek's ifpdf.sty is very useful if you need conditional
% compilation based on whether the output is pdf or dvi.
% usage:
% \ifpdf
%   % pdf code
% \else
%   % dvi code
% \fi
% The latest version of ifpdf.sty can be obtained from:
% http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/
% Also, note that IEEEtran.cls V1.7 and later provides a builtin
% \ifCLASSINFOpdf conditional that works the same way.
% When switching from latex to pdflatex and vice-versa, the compiler may
% have to be run twice to clear warning/error messages.

% *** CITATION PACKAGES ***
%
\ifCLASSOPTIONcompsoc
  % IEEE Computer Society needs nocompress option
  % requires cite.sty v4.0 or later (November 2003)
  % \usepackage[nocompress]{cite}
\else
  % normal IEEE
  % \usepackage{cite}
\fi
% cite.sty was written by Donald Arseneau
% V1.6 and later of IEEEtran pre-defines the format of the cite.sty package
% \cite{} output to follow that of IEEE. Loading the cite package will
% result in citation numbers being automatically sorted and properly
% "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using
% cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's
% \cite will automatically add leading space, if needed. Use cite.sty's
% noadjust option (cite.sty V3.8 and later) if you want to turn this off.
% cite.sty is already installed on most LaTeX systems. Be sure and use
% version 4.0 (2003-05-27) and later if using hyperref.sty. cite.sty does
% not currently provide for hyperlinked citations.
% The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/cite/
% The documentation is contained in the cite.sty file itself.
%
% Note that some packages require special options to format as the Computer
% Society requires. In particular, Computer Society  papers do not use
% compressed citation ranges as is done in typical IEEE papers
% (e.g., [1]-[4]). Instead, they list every citation separately in order
% (e.g., [1], [2], [3], [4]). To get the latter we need to load the cite
% package with the nocompress option which is supported by cite.sty v4.0
% and later. Note also the use of a CLASSOPTION conditional provided by
% IEEEtran.cls V1.7 and later.

% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
  % \usepackage[pdftex]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../pdf/}{../jpeg/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.pdf,.jpeg,.png}
\else
  % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
  % will default to the driver specified in the system graphics.cfg if no
  % driver is specified.
  % \usepackage[dvips]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../eps/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.eps}
\fi
% graphicx was written by David Carlisle and Sebastian Rahtz. It is
% required if you want graphics, photos, etc. graphicx.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/graphics/
% Another good source of documentation is "Using Imported Graphics in
% LaTeX2e" by Keith Reckdahl which can be found as epslatex.ps or
% epslatex.pdf at: http://www.ctan.org/tex-archive/info/
%
% latex, and pdflatex in dvi mode, support graphics in encapsulated
% postscript (.eps) format. pdflatex in pdf mode supports graphics
% in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure
% that all non-photo figures use a vector format (.eps, .pdf, .mps) and
% not a bitmapped formats (.jpeg, .png). IEEE frowns on bitmapped formats
% which can result in "jaggedy"/blurry rendering of lines and letters as
% well as large increases in file sizes.
%
% You can find documentation about the pdfTeX application at:
% http://www.tug.org/applications/pdftex

% *** MATH PACKAGES ***
%
%\usepackage[cmex10]{amsmath}
% A popular package from the American Mathematical Society that provides
% many useful and powerful commands for dealing with mathematics. If using
% it, be sure to load this package with the cmex10 option to ensure that
% only type 1 fonts will utilized at all point sizes. Without this option,
% it is possible that some math symbols, particularly those within
% footnotes, will be rendered in bitmap form which will result in a
% document that can not be IEEE Xplore compliant!
%
% Also, note that the amsmath package sets \interdisplaylinepenalty to 10000
% thus preventing page breaks from occurring within multiline equations. Use:
%\interdisplaylinepenalty=2500
% after loading amsmath to restore such page breaks as IEEEtran.cls normally
% does. amsmath.sty is already installed on most LaTeX systems. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/amslatex/math/

% *** SPECIALIZED LIST PACKAGES ***
%
%\usepackage{algorithmic}
% algorithmic.sty was written by Peter Williams and Rogerio Brito.
% This package provides an algorithmic environment fo describing algorithms.
% You can use the algorithmic environment in-text or within a figure
% environment to provide for a floating algorithm. Do NOT use the algorithm
% floating environment provided by algorithm.sty (by the same authors) or
% algorithm2e.sty (by Christophe Fiorio) as IEEE does not use dedicated
% algorithm float types and packages that provide these will not provide
% correct IEEE style captions. The latest version and documentation of
% algorithmic.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithms/
% There is also a support site at:
% http://algorithms.berlios.de/index.html
% Also of interest may be the (relatively newer and more customizable)
% algorithmicx.sty package by Szasz Janos:
% http://www.ctan.org/tex-archive/macros/latex/contrib/algorithmicx/

% *** ALIGNMENT PACKAGES ***
%
%\usepackage{array}
% Frank Mittelbach's and David Carlisle's array.sty patches and improves
% the standard LaTeX2e array and tabular environments to provide better
% appearance and additional user controls. As the default LaTeX2e table
% generation code is lacking to the point of almost being broken with
% respect to the quality of the end results, all users are strongly
% advised to use an enhanced (at the very least that provided by array.sty)
% set of table tools. array.sty is already installed on most systems. The
% latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/required/tools/

%\usepackage{mdwmath}
%\usepackage{mdwtab}
% Also highly recommended is Mark Wooding's extremely powerful MDW tools,
% especially mdwmath.sty and mdwtab.sty which are used to format equations
% and tables, respectively. The MDWtools set is already installed on most
% LaTeX systems. The lastest version and documentation is available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/mdwtools/

% IEEEtran contains the IEEEeqnarray family of commands that can be used to
% generate multiline equations as well as matrices, tables, etc., of high
% quality.

%\usepackage{eqparbox}
% Also of notable interest is Scott Pakin's eqparbox package for creating
% (automatically sized) equal width boxes - aka "natural width parboxes".
% Available at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/eqparbox/

% *** SUBFIGURE PACKAGES ***
%\ifCLASSOPTIONcompsoc
%\usepackage[tight,normalsize,sf,SF]{subfigure}
%\else
%\usepackage[tight,footnotesize]{subfigure}
%\fi
% subfigure.sty was written by Steven Douglas Cochran. This package makes it
% easy to put subfigures in your figures. e.g., "Figure 1a and 1b". For IEEE
% work, it is a good idea to load it with the tight package option to reduce
% the amount of white space around the subfigures. Computer Society papers
% use a larger font and \sffamily font for their captions, hence the
% additional options needed under compsoc mode. subfigure.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:
% http://www.ctan.org/tex-archive/obsolete/macros/latex/contrib/subfigure/
% subfigure.sty has been superceeded by subfig.sty.

%\ifCLASSOPTIONcompsoc
%  \usepackage[caption=false]{caption}
%  \usepackage[font=normalsize,labelfont=sf,textfont=sf]{subfig}
%\else
%  \usepackage[caption=false]{caption}
%  \usepackage[font=footnotesize]{subfig}
%\fi
% subfig.sty, also written by Steven Douglas Cochran, is the modern
% replacement for subfigure.sty. However, subfig.sty requires and
% automatically loads Axel Sommerfeldt's caption.sty which will override
% IEEEtran.cls handling of captions and this will result in nonIEEE style
% figure/table captions. To prevent this problem, be sure and preload
% caption.sty with its "caption=false" package option. This is will preserve
% IEEEtran.cls handing of captions. Version 1.3 (2005/06/28) and later
% (recommended due to many improvements over 1.2) of subfig.sty supports
% the caption=false option directly:
%\ifCLASSOPTIONcompsoc
%  \usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig}
%\else
%  \usepackage[caption=false,font=footnotesize]{subfig}
%\fi
%
% The latest version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/subfig/
% The latest version and documentation of caption.sty can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/caption/

% *** FLOAT PACKAGES ***
%
%\usepackage{fixltx2e}
% fixltx2e, the successor to the earlier fix2col.sty, was written by
% Frank Mittelbach and David Carlisle. This package corrects a few problems
% in the LaTeX2e kernel, the most notable of which is that in current
% LaTeX2e releases, the ordering of single and double column floats is not
% guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a
% single column figure to be placed prior to an earlier double column
% figure. The latest version and documentation can be found at:
% http://www.ctan.org/tex-archive/macros/latex/base/

%\usepackage{stfloats}
% stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e
% the ability to do double column floats at the bottom of the page as well
% as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in
% LaTeX2e). It also provides a command:
%\fnbelowfloat
% to enable the placement of footnotes below bottom floats (the standard
% LaTeX2e kernel puts them above bottom floats). This is an invasive package
% which rewrites many portions of the LaTeX2e float routines. It may not work
% with other packages that modify the LaTeX2e float routines. The latest
% version and documentation can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/sttools/
% Documentation is contained in the stfloats.sty comments as well as in the
% presfull.pdf file. Do not use the stfloats baselinefloat ability as IEEE
% does not allow \baselineskip to stretch. Authors submitting work to the
% IEEE should note that IEEE rarely uses double column equations and
% that authors should try to avoid such use. Do not be tempted to use the
% cuted.sty or midfloat.sty packages (also by Sigitas Tolusis) as IEEE does
% not format its papers in such ways.

%\ifCLASSOPTIONcaptionsoff
%  \usepackage[nomarkers]{endfloat}
% \let\MYoriglatexcaption\caption
% \renewcommand{\caption}[2][\relax]{\MYoriglatexcaption[#2]{#2}}
%\fi
% endfloat.sty was written by James Darrell McCauley and Jeff Goldberg.
% This package may be useful when used in conjunction with IEEEtran.cls'
% captionsoff option. Some IEEE journals/societies require that submissions
% have lists of figures/tables at the end of the paper and that
% figures/tables without any captions are placed on a page by themselves at
% the end of the document. If needed, the draftcls IEEEtran class option or
% \CLASSINPUTbaselinestretch interface can be used to increase the line
% spacing as well. Be sure and use the nomarkers option of endfloat to
% prevent endfloat from "marking" where the figures would have been placed
% in the text. The two hack lines of code above are a slight modification of
% that suggested by in the endfloat docs (section 8.3.1) to ensure that
% the full captions always appear in the list of figures/tables - even if
% the user used the short optional argument of \caption[]{}.
% IEEE papers do not typically make use of \caption[]'s optional argument,
% so this should not be an issue. A similar trick can be used to disable
% captions of packages such as subfig.sty that lack options to turn off
% the subcaptions:
% For subfig.sty:
% \let\MYorigsubfloat\subfloat
% \renewcommand{\subfloat}[2][\relax]{\MYorigsubfloat[]{#2}}
% For subfigure.sty:
% \let\MYorigsubfigure\subfigure
% \renewcommand{\subfigure}[2][\relax]{\MYorigsubfigure[]{#2}}
% However, the above trick will not work if both optional arguments of
% the \subfloat/subfig command are used. Furthermore, there needs to be a
% description of each subfigure *somewhere* and endfloat does not add
% subfigure captions to its list of figures. Thus, the best approach is to
% avoid the use of subfigure captions (many IEEE journals avoid them anyway)
% and instead reference/explain all the subfigures within the main caption.
% The latest version of endfloat.sty and its documentation can obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/endfloat/
%
% The IEEEtran \ifCLASSOPTIONcaptionsoff conditional can also be used
% later in the document, say, to conditionally put the References on a
% page by themselves.

% *** PDF, URL AND HYPERLINK PACKAGES ***
%
%\usepackage{url}
% url.sty was written by Donald Arseneau. It provides better support for
% handling and breaking URLs. url.sty is already installed on most LaTeX
% systems. The latest version can be obtained at:
% http://www.ctan.org/tex-archive/macros/latex/contrib/misc/
% Read the url.sty source comments for usage information. Basically,
% \url{my_url_here}.

% *** Do not adjust lengths that control margins, column widths, etc. ***
% *** Do not use packages that alter fonts (such as pslatex).         ***
% There should be no need to do such things with IEEEtran.cls V1.6 and later.
% (Unless specifically asked to do so by the journal or conference you plan
% to submit to, of course. )

% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}

\begin{document}
%
% paper title
% can use linebreaks \\ within to get better formatting as desired
\title{Bare Demo of IEEEtran.cls\\ for Computer Society Journals}
%
%
% author names and IEEE memberships
% note positions of commas and nonbreaking spaces ( ~ ) LaTeX will not break
% a structure at a ~ so this keeps an author's name from being broken across
% two lines.
% use \thanks{} to gain access to the first footnote area
% a separate \thanks must be used for each paragraph as LaTeX2e's \thanks
% was not built to handle multiple paragraphs
%
%
%\IEEEcompsocitemizethanks is a special \thanks that produces the bulleted
% lists the Computer Society journals use for "first footnote" author
% affiliations. Use \IEEEcompsocthanksitem which works much like \item
% for each affiliation group. When not in compsoc mode,
% \IEEEcompsocitemizethanks becomes like \thanks and
% \IEEEcompsocthanksitem becomes a line break with idention. This
% facilitates dual compilation, although admittedly the differences in the
% desired content of \author between the different types of papers makes a
% one-size-fits-all approach a daunting prospect. For instance, compsoc
% journal papers have the author affiliations above the "Manuscript
% received ..."  text while in non-compsoc journals this is reversed. Sigh.

\author{Michael~Shell,~\IEEEmembership{Member,~IEEE,}
        John~Doe,~\IEEEmembership{Fellow,~OSA,}
        and~Jane~Doe,~\IEEEmembership{Life~Fellow,~IEEE}% <-this % stops a space
\IEEEcompsocitemizethanks{\IEEEcompsocthanksitem M. Shell is with the Department
of Electrical and Computer Engineering, Georgia Institute of Technology, Atlanta,
GA, 30332.\protect\\
% note need leading \protect in front of \\ to get a newline within \thanks as
% \\ is fragile and will error, could use \hfil\break instead.
E-mail: see http://www.michaelshell.org/contact.html
\IEEEcompsocthanksitem J. Doe and J. Doe are with Anonymous University.}% <-this % stops a space
\thanks{Manuscript received April 19, 2005; revised January 11, 2007.}}

% note the % following the last \IEEEmembership and also \thanks -
% these prevent an unwanted space from occurring between the last author name
% and the end of the author line. i.e., if you had this:
%
% \author{....lastname \thanks{...} \thanks{...} }
%                     ^------------^------------^----Do not want these spaces!
%
% a space would be appended to the last name and could cause every name on that
% line to be shifted left slightly. This is one of those "LaTeX things". For
% instance, "\textbf{A} \textbf{B}" will typeset as "A B" not "AB". To get
% "AB" then you have to do: "\textbf{A}\textbf{B}"
% \thanks is no different in this regard, so shield the last } of each \thanks
% that ends a line with a % and do not let a space in before the next \thanks.
% Spaces after \IEEEmembership other than the last one are OK (and needed) as
% you are supposed to have spaces between the names. For what it is worth,
% this is a minor point as most people would not even notice if the said evil
% space somehow managed to creep in.

% The paper headers
\markboth{Journal of \LaTeX\ Class Files,~Vol.~6, No.~1, January~2007}%
{Shell \MakeLowercase{\textit{et al.}}: Bare Demo of IEEEtran.cls for Computer Society Journals}
% The only time the second header will appear is for the odd numbered pages
% after the title page when using the twoside option.
%
% *** Note that you probably will NOT want to include the author's ***
% *** name in the headers of peer review papers.                   ***
% You can use \ifCLASSOPTIONpeerreview for conditional compilation here if
% you desire.

% The publisher's ID mark at the bottom of the page is less important with
% Computer Society journal papers as those publications place the marks
% outside of the main text columns and, therefore, unlike regular IEEE
% journals, the available text space is not reduced by their presence.
% If you want to put a publisher's ID mark on the page you can do it like
% this:
%\IEEEpubid{0000--0000/00\$00.00~\copyright~2007 IEEE}
% or like this to get the Computer Society new two part style.
%\IEEEpubid{\makebox[\columnwidth]{\hfill 0000--0000/00/\$00.00~\copyright~2007 IEEE}%
%\hspace{\columnsep}\makebox[\columnwidth]{Published by the IEEE Computer Society\hfill}}
% Remember, if you use this you must call \IEEEpubidadjcol in the second
% column for its text to clear the IEEEpubid mark (Computer Society jorunal
% papers don't need this extra clearance.)

% use for special paper notices
%\IEEEspecialpapernotice{(Invited Paper)}

% for Computer Society papers, we must declare the abstract and index terms
% PRIOR to the title within the \IEEEcompsoctitleabstractindextext IEEEtran
% command as these need to go into the title area created by \maketitle.
\IEEEcompsoctitleabstractindextext{%
\begin{abstract}
%\boldmath
The abstract goes here.
\end{abstract}
% IEEEtran.cls defaults to using nonbold math in the Abstract.
% This preserves the distinction between vectors and scalars. However,
% if the journal you are submitting to favors bold math in the abstract,
% then you can use LaTeX's standard command \boldmath at the very start
% of the abstract to achieve this. Many IEEE journals frown on math
% in the abstract anyway. In particular, the Computer Society does
% not want either math or citations to appear in the abstract.

% Note that keywords are not normally used for peerreview papers.
\begin{IEEEkeywords}
Computer Society, IEEEtran, journal, \LaTeX, paper, template.
\end{IEEEkeywords}}

% make the title area
\maketitle

% To allow for easy dual compilation without having to reenter the
% abstract/keywords data, the \IEEEcompsoctitleabstractindextext text will
% not be used in maketitle, but will appear (i.e., to be "transported")
% here as \IEEEdisplaynotcompsoctitleabstractindextext when compsoc mode
% is not selected <OR> if conference mode is selected - because compsoc
% conference papers position the abstract like regular (non-compsoc)
% papers do!
\IEEEdisplaynotcompsoctitleabstractindextext
% \IEEEdisplaynotcompsoctitleabstractindextext has no effect when using
% compsoc under a non-conference mode.

% For peer review papers, you can put extra information on the cover
% page as needed:
% \ifCLASSOPTIONpeerreview
% \begin{center} \bfseries EDICS Category: 3-BBND \end{center}
% \fi
%
% For peerreview papers, this IEEEtran command inserts a page break and
% creates the second title. It will be ignored for other modes.
\IEEEpeerreviewmaketitle

\section{Introduction}
% Computer Society journal papers do something a tad strange with the very
% first section heading (almost always called "Introduction"). They place it
% ABOVE the main text! IEEEtran.cls currently does not do this for you.
% However, You can achieve this effect by making LaTeX jump through some
% hoops via something like:
%
%\ifCLASSOPTIONcompsoc
%  \noindent\raisebox{2\baselineskip}[0pt][0pt]%
%  {\parbox{\columnwidth}{\section{Introduction}\label{sec:introduction}%
%  \global\everypar=\everypar}}%
%  \vspace{-1\baselineskip}\vspace{-\parskip}\par
%\else
%  \section{Introduction}\label{sec:introduction}\par
%\fi
%
% Admittedly, this is a hack and may well be fragile, but seems to do the
% trick for me. Note the need to keep any \label that may be used right
% after \section in the above as the hack puts \section within a raised box.

% The very first letter is a 2 line initial drop letter followed
% by the rest of the first word in caps (small caps for compsoc).
%
% form to use if the first word consists of a single letter:
% \IEEEPARstart{A}{demo} file is ....
%
% form to use if you need the single drop letter followed by
% normal text (unknown if ever used by IEEE):
% \IEEEPARstart{A}{}demo file is ....
%
% Some journals put the first two words in caps:
% \IEEEPARstart{T}{his demo} file is ....
%
% Here we have the typical use of a "T" for an initial drop letter
% and "HIS" in caps to complete the first word.
\IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file''
for IEEE Computer Society journal papers produced under \LaTeX\ using
IEEEtran.cls version 1.7 and later.
% You must have at least 2 lines in the paragraph with the drop letter
% (should never be an issue)
I wish you the best of success.

\hfill mds

\hfill January 11, 2007

\subsection{Subsection Heading Here}
Subsection text here.

% needed in second column of first page if using \IEEEpubid
%\IEEEpubidadjcol

\subsubsection{Subsubsection Heading Here}
Subsubsection text here.

% An example of a floating figure using the graphicx package.
% Note that \label must occur AFTER (or within) \caption.
% For figures, \caption should occur after the \includegraphics.
% Note that IEEEtran v1.7 and later has special internal code that
% is designed to preserve the operation of \label within \caption
% even when the captionsoff option is in effect. However, because
% of issues like this, it may be the safest practice to put all your
% \label just after \caption rather than within \caption{}.
%
% Reminder: the "draftcls" or "draftclsnofoot", not "draft", class
% option should be used if it is desired that the figures are to be
% displayed while in draft mode.
%
%\begin{figure}[!t]
%\centering
%\includegraphics[width=2.5in]{myfigure}
% where an .eps filename suffix will be assumed under latex,
% and a .pdf suffix will be assumed for pdflatex; or what has been declared
% via \DeclareGraphicsExtensions.
%\caption{Simulation Results}
%\label{fig_sim}
%\end{figure}

% Note that IEEE typically puts floats only at the top, even when this
% results in a large percentage of a column being occupied by floats.
% However, the Computer Society has been known to put floats at the bottom.

% An example of a double column floating figure using two subfigures.
% (The subfig.sty package must be loaded for this to work.)
% The subfigure \label commands are set within each subfloat command, the
% \label for the overall figure must come after \caption.
% \hfil must be used as a separator to get equal spacing.
% The subfigure.sty package works much the same way, except \subfigure is
% used instead of \subfloat.
%
%\begin{figure*}[!t]
%\centerline{\subfloat[Case I]\includegraphics[width=2.5in]{subfigcase1}%
%\label{fig_first_case}}
%\hfil
%\subfloat[Case II]{\includegraphics[width=2.5in]{subfigcase2}%
%\label{fig_second_case}}}
%\caption{Simulation results}
%\label{fig_sim}
%\end{figure*}
%
% Note that often IEEE papers with subfigures do not employ subfigure
% captions (using the optional argument to \subfloat), but instead will
% reference/describe all of them (a), (b), etc., within the main caption.

% An example of a floating table. Note that, for IEEE style tables, the
% \caption command should come BEFORE the table. Table text will default to
% \footnotesize as IEEE normally uses this smaller font for tables.
% The \label must come after \caption as always.
%
%\begin{table}[!t]
%% increase table row spacing, adjust to taste
%\renewcommand{\arraystretch}{1.3}
% if using array.sty, it might be a good idea to tweak the value of
% \extrarowheight as needed to properly center the text within the cells
%\caption{An Example of a Table}
%\label{table_example}
%\centering
%% Some packages, such as MDW tools, offer better commands for making tables
%% than the plain LaTeX2e tabular which is used here.
%\begin{tabular}{|c||c|}
%\hline
%One & Two\\
%\hline
%Three & Four\\
%\hline
%\end{tabular}
%\end{table}

% Note that IEEE does not put floats in the very first column - or typically
% anywhere on the first page for that matter. Also, in-text middle ("here")
% positioning is not used. Most IEEE journals use top floats exclusively.
% However, Computer Society journals sometimes do use bottom floats - bear
% this in mind when choosing appropriate optional arguments for the
% figure/table environments.
% Note that, LaTeX2e, unlike IEEE journals, places footnotes above bottom
% floats. This can be corrected via the \fnbelowfloat command of the
% stfloats package.

\section{Conclusion}
The conclusion goes here.

% if have a single appendix:
%\appendix[Proof of the Zonklar Equations]
% or
%\appendix  % for no appendix heading
% do not use \section anymore after \appendix, only \section*
% is possibly needed

% use appendices with more than one appendix
% then use \section to start each appendix
% you must declare a \section before using any
% \subsection or using \label (\appendices by itself
% starts a section numbered zero.)
%

\appendices
\section{Proof of the First Zonklar Equation}
Appendix one text goes here.

% you can choose not to have a title for an appendix
% if you want by leaving the argument blank
\section{}
Appendix two text goes here.

% use section* for acknowledgement
\ifCLASSOPTIONcompsoc
  % The Computer Society usually uses the plural form
  \section*{Acknowledgments}
\else
  % regular IEEE prefers the singular form
  \section*{Acknowledgment}
\fi

The authors would like to thank...

% Can use something like this to put references on a page
% by themselves when using endfloat and the captionsoff option.
\ifCLASSOPTIONcaptionsoff
  \newpage
\fi

% trigger a \newpage just before the given reference
% number - used to balance the columns on the last page
% adjust value as needed - may need to be readjusted if
% the document is modified later
%\IEEEtriggeratref{8}
% The "triggered" command can be changed if desired:
%\IEEEtriggercmd{\enlargethispage{-5in}}

% references section

% can use a bibliography generated by BibTeX as a .bbl file
% BibTeX documentation can be easily obtained at:
% http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/
% The IEEEtran BibTeX style support page is at:
% http://www.michaelshell.org/tex/ieeetran/bibtex/
%\bibliographystyle{IEEEtran}
% argument is your BibTeX string definitions and bibliography database(s)
%\bibliography{IEEEabrv,../bib/paper}
%
% <OR> manually copy in the resultant .bbl file
% set second argument of \begin to the number of references
% (used to reserve space for the reference number labels box)
\begin{thebibliography}{1}

\bibitem{IEEEhowto:kopka}
H.~Kopka and P.~W. Daly, \emph{A Guide to \LaTeX}, 3rd~ed.\hskip 1em plus
  0.5em minus 0.4em\relax Harlow, England: Addison-Wesley, 1999.

\end{thebibliography}

% biography section
%
% If you have an EPS/PDF photo (graphicx package needed) extra braces are
% needed around the contents of the optional argument to biography to prevent
% the LaTeX parser from getting confused when it sees the complicated
% \includegraphics command within an optional argument. (You could create
% your own custom macro containing the \includegraphics command to make things
% simpler here.)
%\begin{biography}[{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{mshell}}]{Michael Shell}
% or if you just want to reserve a space for a photo:

\begin{IEEEbiography}{Michael Shell}
Biography text here.
\end{IEEEbiography}

% if you will not have a photo at all:
\begin{IEEEbiographynophoto}{John Doe}
Biography text here.
\end{IEEEbiographynophoto}

% insert where needed to balance the two columns on the last page with
% biographies
%\newpage

\begin{IEEEbiographynophoto}{Jane Doe}
Biography text here.
\end{IEEEbiographynophoto}

% You can push biographies down or up by placing
% a \vfill before or after them. The appropriate
% use of \vfill depends on what kind of text is
% on the last page and whether or not the columns
% are being equalized.

%\vfill

% Can be used to pull up biographies so that the bottom of the last one
% is flush with the other column.
%\enlargethispage{-5in}

% that's all folks
\end{document}


text:
// Simon says: A complete list of includes.
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
	// Initialize and declare variables.
    int* intData = NULL;
	int intScan = 0;
	int intSize = 0;

    // Open file, assign to fileHandle
	FILE* fileHandle = fopen("./Data1.txt", "r");
	{
		// Grab first value, which declares number of integers in file.
        fscanf(fileHandle, "%d", &intSize);

		// Establish array intData, setting to size of first value.
        intData = (int*) (malloc(sizeof(int) * intSize));

		// Fill array with values, reading over file.
        for (int intFor1 = 0; intFor1 < intSize; intFor1++) {
			fscanf(fileHandle, "%d", &intData[intFor1]);
		}
	}

    // Super important - close the file.
	fclose(fileHandle);

	// Run through the array, comparing to intScan (initially declared at 0), and tracking largest.
    for (int intFor1 = 0; intFor1 < intSize; intFor1++) {
        if (intData[intFor1] > intScan) {
            intScan = intData[intFor1];
        }
    }

    printf("The largest number in the file is %d.\n", intScan);

    // Free up the data in the array.
    free(intData);
}

redpajama_set_name: RedPajamaGithub


text:
import { Action } from '@ngrx/store'

import { suffixes } from './'

import { MonzoAccountResponse } from '../../../lib/monzo/Account'

const actionPrefix = '[Account]'

export const GET_ACCOUNT = `${actionPrefix} HTTP/Get`
export const GET_ACCOUNT_SUCCESS = `${GET_ACCOUNT} ${suffixes.success}`
export const GET_ACCOUNT_FAILED = `${GET_ACCOUNT} ${suffixes.failed}`
export const SET_ACCOUNT = `${actionPrefix} Set`
export const LOGOUT = `${actionPrefix} Logout`
export const LOGOUT_FAILED = `${actionPrefix} Logout ${suffixes.failed}`

export class SetAccountAction implements Action {
  readonly type = SET_ACCOUNT

  constructor(public payload: MonzoAccountResponse) {}
}

export class GetAccountAction implements Action {
  readonly type = GET_ACCOUNT
}
export class GetAccountFailedAction implements Action {
  readonly type = GET_ACCOUNT_FAILED
}

export class LogoutAction implements Action {
  readonly type = LOGOUT
}
export class LogoutFailedAction implements Action {
  readonly type = LOGOUT_FAILED
}

export type Actions = GetAccountAction | SetAccountAction


text:
<?php

namespace Gear\Modules\Users\Interfaces;

interface SessionInterface {}


text:
namespace ADNS
{

Mutex::Mutex()
{
    int ret = pthread_mutex_init(&m_mutex, nullptr);
    if( ret != 0 )
        throw std::system_error(ret, std::system_category(), "init mutex fail");
}

Mutex::~Mutex()
{
    int ret = pthread_mutex_destroy(&m_mutex);
    if( ret != 0 )
        throw std::system_error(ret, std::system_category(), "destroy mutex fail");
}

void Mutex::lock()
{
    int ret = pthread_mutex_lock(&m_mutex);
    if( ret != 0 )
        throw std::system_error(ret, std::system_category(), "lock mutex fail");
}

void Mutex::unlock()
{
    int ret = pthread_mutex_unlock(&m_mutex);

    if( ret != 0 )
        throw std::system_error(ret, std::system_category(), "unlock mutex fail");
}

}


text:
{% load crispy_forms_tags %}
{% load crispy_forms_field %}

                    Reservasjoner ({{ event.attendance_event.number_of_reserved_seats_taken }}/{{ event.attendance_event.number_of_reserved_seats }})

                                #
                                Navn
                                Notat
                                Allergier

                        {% for reservee in event.attendance_event.reservees_qs %}

                                {{ forloop.counter }}
                                {{ reservee.name }}
                                {{ reservee.note }}
                                {{ reservee.allergies }}

                        {% endfor %}

Det er ingen reserverte på dette arrangementet.


text:
@interface UIFont (Custom)

//设置字体名称
+ (void)setFontName:(NSString*)fontName;
//设置粗体字体名称
+ (void)setBoldFontName:(NSString*)boldFontName;

//使用默认字体
+ (UIFont *)getFontOfSize:(CGFloat)fontSize;
+ (UIFont *)getBoldFontOfSize:(CGFloat)fontSize;

@end


text: Fetches places from Google's API and inserts them into a database


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/gray_background">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="24dp"
        >
        <ve.com.abicelis.chefbuddy.views.FancyTitleTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dialog_add_recipe_ingredient_title"
            custom:default_padding="false"
            />

        <LinearLayout
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:orientation="vertical">

            <ve.com.abicelis.chefbuddy.views.FancyEditText
                android:id="@+id/dialog_add_recipe_ingredient_amount"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                custom:icon="@drawable/ic_amount"
                custom:hint="@string/dialog_add_recipe_ingredient_amount_hint"
                custom:maxLines="2"
                />
            <ve.com.abicelis.chefbuddy.views.FancySpinner
                android:id="@+id/dialog_add_recipe_ingredient_measurement"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                custom:icon="@drawable/ic_measurement_cup"

                />

            <ve.com.abicelis.chefbuddy.views.FancyAutoCompleteTextView
                android:id="@+id/dialog_add_recipe_ingredient_ingredient"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                custom:maxLines="1"
                custom:icon="@drawable/ic_food"
                custom:hint="@string/dialog_add_recipe_ingredient_ingredient_hint"
                />

        </LinearLayout>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="24dp"
        android:paddingStart="24dp"
        android:paddingBottom="8dp"
        android:paddingRight="8dp"
        android:paddingEnd="8dp"
        >
        <Button
            android:id="@+id/dialog_add_recipe_ingredient_ok"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dialog_done"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            style="?attr/borderlessButtonStyle"/>

        <Button
            android:id="@+id/dialog_add_recipe_ingredient_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:layout_marginEnd="8dp"
            android:layout_toStartOf="@id/dialog_add_recipe_ingredient_ok"
            android:layout_toLeftOf="@id/dialog_add_recipe_ingredient_ok"
            android:text="@string/dialog_cancel"
            style="?attr/borderlessButtonStyle"/>
    </RelativeLayout>

</LinearLayout>


text:
package com.miviclin.droidengine2d.gamestate;

import java.util.ArrayList;
import java.util.Stack;

import android.util.SparseArray;

import com.miviclin.droidengine2d.AbstractGame;
import com.miviclin.droidengine2d.graphics.Graphics;

/**
 * GameStateManager.
 *
 * @author Miguel Vicente Linares
 *
 */
public class GameStateManager {

	private SparseArray<GameState> gameStatesRegistry;
	private Stack<GameState> activeGameStates;
	private ArrayList<OnGameStateChangeListener> onGameStateChangeListeners;

	/**
	 * Constructor.
	 */
	public GameStateManager() {
		this(16);
	}

	/**
	 * Constructor.
	 *
	 * @param initialCapacity Initial capacity for GameStates. If this capacity is reached, the data structure that
	 *            holds the GameStates will be resized automatically.
	 */
	public GameStateManager(int initialCapacity) {
		this.gameStatesRegistry = new SparseArray<GameState>(initialCapacity);
		this.activeGameStates = new Stack<GameState>();
		this.onGameStateChangeListeners = new ArrayList<OnGameStateChangeListener>();
	}

	/**
	 * Registers a GameState in this GameStateManager using the specified gameStateId.

	 * If a GameState with the specified gameStateId was previously registered in this GameStateManager, it will be
	 * replaced by the new one.
	 *
	 * @param gameStateId Identifier of the GameState. It can be used to get the GameState from this GameStateManager
	 *            later.
	 * @param gameState GameState (can not be null).
	 */
	public void registerGameState(int gameStateId, GameState gameState) {
		registerGameState(gameStateId, gameState, false);
	}

	/**
	 * Registers a GameState in this GameStateManager using the specified gameStateId.

	 * If a GameState with the specified gameStateId was previously registered in this GameStateManager, it will be
	 * replaced by the new one.
	 *
	 * @param gameStateId Identifier of the GameState. It can be used to get the GameState from this GameStateManager
	 *            later.
	 * @param gameState GameState (can not be null).
	 * @param push true to push the GameState onto the stack of active GameStates of this GameStateManager.
	 */
	public void registerGameState(int gameStateId, GameState gameState, boolean push) {
		if (gameState == null) {
			throw new IllegalArgumentException("The GameState can not be null");
		}
		gameStatesRegistry.put(gameStateId, gameState);
		gameState.onRegister();
		if (push) {
			pushActiveGameState(gameStateId);
		}
	}

	/**
	 * Unregisters the specified GameState from this GameStateManager.

	 * If a GameState was registered with the specified gameStateId, {@link GameState#dispose()} is called on the
	 * GameState before it is removed from this GameStateManager.

	 * If the specified GameState is in the stack of active GameStates it should be removed from the stack first,
	 * otherwise an exception will be thrown.
	 *
	 * @param gameStateId Identifier of the GameState.
	 * @return Removed GameState or null
	 */
	public GameState unregisterGameState(int gameStateId) {
		GameState gameState = gameStatesRegistry.get(gameStateId);
		if (gameState == null) {
			return null;
		}
		int indexInStack = activeGameStates.search(gameState);
		if (indexInStack >= 0) {
			throw new IllegalStateException("The GameState registered with the gameStateId " + gameStateId + " is " +
					"currently in the stack of active GameStates. It should be removed from the stack of active " +
					"GameStates before unregistering it from this GameStateManager.");
		}
		gameState.dispose();
		gameStatesRegistry.remove(gameStateId);
		return gameState;
	}

	/**
	 * Returns the GameState registered with the specified gameStateId.
	 *
	 * @param gameStateId Identifier of the GameState.
	 * @return GameState or null
	 */
	public GameState getGameState(int gameStateId) {
		return gameStatesRegistry.get(gameStateId);
	}

	/**
	 * Replaces the GameState at the top of the stack of active GameStates of this GameStateManager with the specified
	 * GameState.

	 * The GameState must have been previously registered with the specified gameStateId.

	 * This method notifies every {@link OnGameStateChangeListener} registered in this GameStateManager that the
	 * GameState at the top of the stack of active GameStates has changed.
	 *
	 * @param gameStateId Identifier of the GameState we want to set as the active GameState.
	 */
	public void switchActiveGameState(int gameStateId) {
		GameState previousTopGameState = popActiveGameStateOffStack();
		GameState currentTopGameState = pushActiveGameStateOntoStack(gameStateId);
		dispatchOnGameStateChangeEvent(previousTopGameState, currentTopGameState);
	}

	/**
	 * Returns the GameState at the top of the stack of active GameStates of this GameStateManager.
	 *
	 * @return GameState or null
	 */
	public GameState peekActiveGameState() {
		if (activeGameStates.empty()) {
			return null;
		}
		return activeGameStates.peek();
	}

	/**
	 * Pushes the GameState onto the stack of active GameStates of this GameStateManager.

	 * The GameState must have been previously registered with the specified gameStateId.

	 * This method notifies every {@link OnGameStateChangeListener} registered in this GameStateManager that the
	 * GameState at the top of the stack of active GameStates has changed.
	 *
	 * @param gameStateId Identifier of the GameState we want to set as the active GameState.
	 */
	public void pushActiveGameState(int gameStateId) {
		GameState previousTopGameState = peekActiveGameState();
		GameState currentTopGameState = pushActiveGameStateOntoStack(gameStateId);
		dispatchOnGameStateChangeEvent(previousTopGameState, currentTopGameState);
	}

	/**
	 * Pushes the GameState onto the stack of active GameStates of this GameStateManager.

	 * The GameState must have been previously registered with the specified gameStateId.

	 * This method does not call {@link #dispatchOnGameStateChangeEvent(GameState, GameState)}.
	 *
	 * @param gameStateId Identifier of the GameState we want to set as the active GameState.
	 * @return The GameState pushed onto the stack of active GameStates
	 */
	private GameState pushActiveGameStateOntoStack(int gameStateId) {
		GameState gameState = gameStatesRegistry.get(gameStateId);
		if (gameState == null) {
			throw new GameStateNotRegisteredException(gameStateId);
		}
		activeGameStates.push(gameState);
		gameState.onActivation();
		return gameState;
	}

	/**
	 * Pops 1 GameState off the stack of active GameStates of this GameStateManager. Also calls
	 * {@link GameState#onDeactivation()} on the GameState popped off the stack.

	 * This method notifies every {@link OnGameStateChangeListener} registered in this GameStateManager that the
	 * GameState at the top of the stack of active GameStates has changed.
	 */
	public void popActiveGameState() {
		popActiveGameStates(1);
	}

	/**
	 * Pops the specified number of GameStates off the stack of active GameStates of this GameStateManager. Also calls
	 * {@link GameState#onDeactivation()} on all the GameStates popped off the stack.

	 * This method notifies every {@link OnGameStateChangeListener} registered in this GameStateManager that the
	 * GameState at the top of the stack of active GameStates has changed.
	 *
	 * @param numGameStatesToPop Number of GameStates that will be popped off the stack of active GameStates.
	 */
	public void popActiveGameStates(int numGameStatesToPop) {
		for (int i = 0; ((i < numGameStatesToPop) && !activeGameStates.empty()); i++) {
			GameState previousGameState = popActiveGameStateOffStack();
			GameState currentGameState = peekActiveGameState();
			dispatchOnGameStateChangeEvent(previousGameState, currentGameState);
		}
	}

	/**
	 * Pops all GameStates off the stack of active GameStates of this GameStateManager.

	 * This method notifies every {@link OnGameStateChangeListener} registered in this GameStateManager that the
	 * GameState at the top of the stack of active GameStates has changed.
	 *
	 * @see #popActiveGameStates(int)
	 */
	public void popAllActiveGameStates() {
		int numGameStatesToPop = activeGameStates.size();
		popActiveGameStates(numGameStatesToPop);
	}

	/**
	 * Pops 1 GameState off the stack of active GameStates of this GameStateManager. Also calls
	 * {@link GameState#onDeactivation()} on the GameState popped off the stack.

	 * This method does not call {@link #dispatchOnGameStateChangeEvent(GameState, GameState)}.
	 *
	 * @return The removed GameState or null
	 */
	private GameState popActiveGameStateOffStack() {
		GameState gameState = null;
		if (!activeGameStates.empty()) {
			gameState = activeGameStates.pop();
			gameState.onDeactivation();
		}
		return gameState;
	}

	/**
	 * Notifies all listeners that the GameState at the top of the stack of active GameStates has changed.
	 *
	 * @param previousGameState Previous GameState at the top of the stack or null if the stack was empty.
	 * @param currentGameState Current GameState at the top of the stack or null if the stack is empty.
	 */
	private void dispatchOnGameStateChangeEvent(GameState previousTopGameState, GameState currentTopGameState) {
		for (int i = 0; i < onGameStateChangeListeners.size(); i++) {
			onGameStateChangeListeners.get(i).onGameStateChange(previousTopGameState, currentTopGameState);
		}
	}

	/**
	 * Adds an OnGameStateChangeListener that will be notified when the active GameState of this GameStateManager
	 * changes.
	 *
	 * @param listener Listener to be added.
	 */
	public void addOnGameStateChangeListener(OnGameStateChangeListener listener) {
		onGameStateChangeListeners.add(listener);
	}

	/**
	 * Removes an OnGameStateChangeListener from the list of listeners. The removed listener will not be notified
	 * anymore when the active GameState of this GameStateManager changes.
	 *
	 * @param listener Listener to be removed.
	 */
	public void removeOnGameStateChangeListener(OnGameStateChangeListener listener) {
		onGameStateChangeListeners.remove(listener);
	}

	/**
	 * This method is called when the engine is paused, usually when the activity goes to background.

	 * Calls {@link GameState#onPause()} on all the active GameStates.
	 */
	public void pause() {
		for (int i = 0; i < activeGameStates.size(); i++) {
			activeGameStates.get(i).onPause();
		}
	}

	/**
	 * This method is called when the engine is resumed, usually when the activity comes to foreground.

	 * Calls {@link GameState#onResume()} on the active GameState.
	 */
	public void resume() {
		for (int i = 0; i < activeGameStates.size(); i++) {
			activeGameStates.get(i).onResume();
		}
	}

	/**
	 * Clears the stack of active GameStates calling {@link #popAllActiveGameStates()} and calls
	 * {@link GameState#dispose()} on all GameStates registered in this GameStateManager and removes them from the
	 * GameStateManager.

	 * This GameStateManager will be left empty.
	 */
	public void dispose() {
		popAllActiveGameStates();
		int numGameStates = gameStatesRegistry.size();
		for (int i = 0; i < numGameStates; i++) {
			GameState gameState = gameStatesRegistry.valueAt(i);
			if (gameState != null) {
				gameState.dispose();
			}
		}
		gameStatesRegistry.clear();
	}

	/**
	 * Calls {@link GameState#update(float)} on the GameState at the top of the stack of active GameStates.

	 * This method is called from {@link AbstractGame#update(float)}.
	 *
	 * @param delta Elapsed time, in milliseconds, since the last update.
	 */
	public void update(float delta) {
		GameState gameState = peekActiveGameState();
		if (gameState != null) {
			gameState.getGameStateInputManager().processInput();
			gameState.update(delta);
		}
	}

	/**
	 * Calls {@link GameState#draw(Graphics)} on all the GameStates in the stack of active GameStates.

	 * This method is called from {@link AbstractGame#draw(Graphics)}.

	 * This method is called from the redering thread after {@link GameStateManager#update(float)} has been executed in
	 * the game thread.
	 */
	public void draw(Graphics graphics) {
		for (int i = 0; i < activeGameStates.size(); i++) {
			GameState gameState = activeGameStates.get(i);
			gameState.draw(graphics);
		}
	}

}


text:
package com.alumnigroup.adapter;

import java.util.List;

import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;

import com.alumnigroup.app.R;
import com.alumnigroup.widget.XListView;
/**
 * 即将废弃 使用 FootOnPageChangelistener来替换
 * @author Jayin Ton
 *
 */
public class BaseOnPageChangeListener implements OnPageChangeListener {
	private List<View> btns;

	public BaseOnPageChangeListener(List<View> btns){
		this.btns = btns;

	}
	@Override
	public void onPageScrollStateChanged(int state) {

	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int positon) {
         for(View v : btns){
        	 v.setBackgroundResource(R.color.blue_nav_bg_nomal);
         }
         btns.get(positon).setBackgroundResource(R.color.blue_nav_bg_press);
	}

}


text:
using Base.Test
using Gumbo

include("basics.jl")
include("comparison.jl")
include("parsing.jl")
include("traversal.jl")


text:
using System;

namespace CircuitSimulation.Library.Data
{
    public class InputChangedData : EventData
    {
        public Guid InputId { get; set; }
        public SignalType NewSignal { get; set; }
    }
}


text:
namespace blink {

class LineLayoutBR : public LineLayoutText {
 public:
  explicit LineLayoutBR(LayoutBR* layoutBR) : LineLayoutText(layoutBR) {}

  explicit LineLayoutBR(const LineLayoutItem& item) : LineLayoutText(item) {
    SECURITY_DCHECK(!item || item.isBR());
  }

  explicit LineLayoutBR(std::nullptr_t) : LineLayoutText(nullptr) {}

  LineLayoutBR() {}

  int lineHeight(bool firstLine) const { return toBR()->lineHeight(firstLine); }

 private:
  LayoutBR* toBR() { return toLayoutBR(layoutObject()); }

  const LayoutBR* toBR() const { return toLayoutBR(layoutObject()); }
};

}  // namespace blink

#endif  // LineLayoutBR_h


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>StreamEventHandler (apache-cassandra API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.streaming

Interface StreamEventHandler

All Superinterfaces:

com.google.common.util.concurrent.FutureCallback<StreamState>

All Known Implementing Classes:

LocalSyncTask, SSTableLoader, StreamEventJMXNotifier, StreamingRepairTask, StreamStateStore

public interface StreamEventHandler
extends com.google.common.util.concurrent.FutureCallback<StreamState>

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
handleStreamEvent(StreamEvent event)

Callback for various streaming events.

Methods inherited from interface com.google.common.util.concurrent.FutureCallback

onFailure, onSuccess

Method Detail

handleStreamEvent

void handleStreamEvent(StreamEvent event)

Callback for various streaming events.

Parameters:

event - Stream event.

See Also:

StreamEvent.Type

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
<?php

/**
 * Task for resolving relative paths and setting absolute path in property value.
 *
 * This task was created to address a need for resolving absolute paths of files / directories.
 * In many cases a relative directory (e.g. "./build") is specified, but it needs to be treated
 * as an absolute path since other build files (e.g. in subdirs) should all be using the same
 * path -- and not treating it as a relative path to their own directory.
 *
 * <code>
 * <property name="relative_path" value="./dirname"/>
 * <resolvepath propertyName="absolute_path" file="${relative_path}"/>
 * <echo>Resolved [absolute] path: ${absolute_path}</echo>
 * </code>
 *
 * TODO:
 *      - Possibly integrate this with PackageAsPath, for handling/resolving dot-path paths.
 *
 * @author    Hans Lellelid <hans@xmpl.org>
 * @version   $Revision: 1.6 $
 * @package   phing.tasks.system
 */
class ResolvePathTask extends Task {

    /** Name of property to set. */
    private $propertyName;

    /** The [possibly] relative file/path that needs to be resolved. */
    private $file;

    /** Base directory used for resolution. */
    private $dir;

    /**
     * Set the name of the property to set.
     * @param string $v Property name
     * @return void
     */
    public function setPropertyName($v) {
        $this->propertyName = $v;
    }

    /**
     * Sets a base dir to use for resolution.
     * @param PhingFile $d
     */
    function setDir(PhingFile $d) {
        $this->dir = $d;
    }

    /**
     * Sets a path (file or directory) that we want to resolve.
     * This is the same as setFile() -- just more generic name so that it's
     * clear that you can also use it to set directory.
     * @param string $f
     * @see setFile()
     */
    function setPath($f) {
        $this->file = $f;
    }

    /**
     * Sets a file that we want to resolve.
     * @param string $f
     */
    function setFile($f) {
        $this->file = $f;
    }

    /**
     * Perform the resolution & set property.
     */
    public function main() {

        if (!$this->propertyName) {
            throw new BuildException("You must specify the propertyName attribute", $this->getLocation());
        }

        // Currently only files are supported
        if ($this->file === null) {
            throw new BuildException("You must specify a path to resolve", $this->getLocation());
        }

		$fs = FileSystem::getFileSystem();

        // if dir attribute was specified then we should
        // use that as basedir to which file was relative.
		// -- unless the file specified is an absolute path
        if ($this->dir !== null && !$fs->isAbsolute(new PhingFile($this->file))) {
            $resolved = new PhingFile($this->dir->getPath(), $this->file);
        } else {
            // otherwise just resolve it relative to project basedir
            $resolved = $this->project->resolveFile($this->file);
        }

        $this->log("Resolved " . $this->file . " to " . $resolved->getAbsolutePath(), Project::PROJECT_MSG_INFO);
        $this->project->setProperty($this->propertyName, $resolved->getAbsolutePath());
    }

}


text:
path: "/montreal-is-beautiful.html"
date: "2017-07-05T17:13:20+02:00"
title: "Montreal 😻 🇨🇦"
description: ""
thumbnail: ""
tags: ["travel", "photography"]
publish: true
---

About a week before the July 4th holiday weekend, Celeste (my girlfriend) and I were discussing last-minute travel plans. We looked at airbnb listings up along the Hudson river. A calming vacation into the less-urban, hilly areas north of NYC was enticing. However, it would almost certainly require renting a car and driving on busy roads, and that would significantly reduce the "calming" factor of the trip. Plus, most things around there seemed either booked or more expensive than we wanted, so we started looking further afield.

"Mexico City?" I suggested. Celeste is adventurous, but this was shut down pretty quickly. 😄 We didn't want to spend two days flying out of our four days off from work.

"Niagara Falls?" she suggested. I looked it up on Google Maps, and something caught my eye: Niagara Falls is about 7 hours away from NYC, and Montreal seemed to be about the same distance. I hadn't ever visited Montreal before, even though I have heard great things about it. Celeste was in the same position, so we agreed to give it a try.

We made a good choice! Montreal is beautiful, and we had so much fun that it's on our list of places we'd be seriously interested in moving to in the future (though, we should probably visit in the winter before we sign any leases or job offers).

_Celeste._

_Montreal's public housing has some fantastic murals._

_Montreal's residential areas are full of multi-story houses with external stairs leading up to each dwelling._

_Our airbnb was neat! We stayed with a small family, and they had an apartment full of character._

_The airbnb also had a lively and curious yellow cat. Amongst other things, he liked to play with water. I tried to turn on the faucet just a bit after taking this photo, and he simply licked and pawed at the small stream of water._

_There was also a brown cat, who was calmer but also very cute._

We lucked out, and ended up visiting during the week of Montreal's International Jazz Festival. So, the city was buzzing, and every evening there was something perfect to do. He's not pictured here, but the absolute highlight was seeing Colin Stetson, a phenomenal saxophone player. Not only does he play saxophone with circular breathing to achieve continuous harmonies; he also wears a mic on his neck to record his simultaneous throat singing, _and_ sometimes even puts a contact mic on his saxophone to amplify the keys to create a percussive rhythm. Take a minute to watch this:

_I took a lot of photos on this trip, including in crowds at the Jazz Fest. Sometimes, photos are still fun even when they're blurry._

_Sidewalk Chalk, a jazz & hip hop band, was another really fun group to see._

_A scene from the Montreal Metro, after a night of Jazz Fest._

One of my favorite parts of seeing a new city is experiencing the public transit. Now, I love NYC, and the MTA Subway is an amazing achievement of organization, technology, and sheer volume. Still, the Subway has a few ... discomforts: loud sounds, intense summer temperatures, and occasional overwhelming smells. Montreal has an underground train system that is a relatively large system, and our experience of it was really positive. It is definitely a newer train system, and it had some trains that felt futuristic – shiny, bright, and smooth-rolling (these trains don't run on traditional train tracks, but rather a system of huge rubber tires on concrete tracks, almost like high-speed, connected buses).

_Walking around a city is even better than taking transport – I love seeing the million everyday but spectacular sites of a city. Here is a dog, relaxing on the porch._

_A large and delicious crêpe._

I knew before we went that Montreal would have quite a bit of French culture and French speakers, though I had somehow imagined it would be a mostly-English city, with bilingual signage and many bilingual speakers. On the contrary, Montreal is a mostly-French city, with some English on its signage and many bilingual speakers. We encountered several people that spoke almost no English.

A frequent experience in Montreal was hearing someone speak French with complete fluency and a distinctly native-speaking French accent, then flip to English with the same fluency and a crisp North American accent that wouldn't stand out in the Midwest.

![Celeste enjoyed the delicious crepe](./images/2017-08-01_10.44.06.jpg)

_We both enjoyed the delicious crêpe._

_The Montreal Biosphère is an awesome geodesic dome, which we happened upon on a daytrip to see Habitat 67. It turns out, this dome was built along with Habitat 67 for a year when Montreal hosted both the Summer Olympics and a World's Fair._

We walked around Île Sainte-Hélène and across the Pont de la Concorde bridge, and enjoyed seeing others enjoying the picturesque Summer day.

We finally reached Habitat 67! This was an architectural model community originally built as affordable housing for the workers of the 67 World's Fair and Olympics, and today it's used as luxury condos. We were basically another set of tourists gazing at rich people's apartments, but it was still fun to see (from the sidewalk, as enforced by lawn signs and security guards in golf carts).

This was one of the main points of Montreal I had wanted to see, because in 1967 my Dad took a road trip as a teenager with his family from their home in Alberta to Montreal, for the World's Fair. When I learned this, I asked, "What do you remember?" expecting to hear something about gleaming structures or technology, and the one thing he remembered seeing was Habitat 67. It's definitely memorable, as some of the cubes in the concrete structure appear to be floating, almost weightless.

_Just including this because I look like I'm in a movie here._

Habitat 67 is actually a bit removed from the main city, so we had a long, hot walk to a bus stop, and were temporarily concerned that with the Canada Day weekend, buses might not come. Calling the bus tracker phone number was a bit cryptic, as again, things in Montreal are French-first. But, a bus eventually did come, and we rode back into the city.

The Montreal central library, officially called _Bibliothèque et Archives nationales du Québec_, is awesome! We really wanted to see it for longer than we did during it's shortened hours of the holiday weekend, but a quick run-through was exciting. We marveled at the comic book selection, the CD-listening chairs, and the gleaming newness of the place.

We also visited several bookstores around the city, as Celeste searched for the right book to read with her Mom in their French-language book club.

_I don't know what the story is here, but it looks like Québec has some special penalty rules in football._

[Oui Mai Nos](https://www.yelp.ca/biz/oui-mais-non-montr%C3%A9al) was a favorite Café near our airbnb. It had good coffee, plus a beautiful and eclectic interior that included a challenging-to-read but enticing menu.

_See anything surprising in the photo above? The grocer had his dog in his front pouch!_ 😄

We visited the Jean Talon Market on a rainy day, and it was a bustling marketplace in the best way. There were many grocers selling fresh produce, stacked neatly  with charming hand-written signs. The colors and sounds were vibrant, and it was all the more inviting with the light rain punctuating the areas around a between the covered spaces of the market.

In Montreal, like in most cities I know, it's illegal to publicly consume alcohol. _But_ Montreal has an exception, the [Picnic Law](http://ville.montreal.qc.ca/sel/sypre-consultation/afficherpdf?idDoc=122&typeDoc=1):

> Il est défendu de consommer des boissons alcooliques sur le domaine public, sauf:
> 1) dans un café-terrasse installé sur le domaine public où la vente de boissons alcooliques est autorisée par la loi;
> 2) **à l'occasion d'un repas pris en plein air dans la partie d'un parc** où la ville a installé des tables de pique-nique;
> 3) dans certaines circonstances ou à l'occasion d'événements, de fêtes ou de manifestations, suivant l'autorisation donnée par ordonnance.

Translated to English, the relevant part of that is: "It is forbidden to consume alcoholic beverages on the public domain, except ... (2) for an outdoor meal in the part of a park where the town has set up picnic tables."

So, we enjoyed a picnic in Mount Royal Park! We feasted on smoked salmon, bread, and a couple of local craft beers.

We then hiked up Mount Royal, which had trails that reminded me in many ways of hiking in the Black Hills of South Dakota, where I grew up.

Montreal is a city with so much to see, it's hard to show much of it in a single blog post. Hopefully, I'll get to make another trip someday in the near future!

---

......Aaand on the ride back to NYC, our bus broke down on the side of the highway in New Jersey. It was at least 90°F that day, and we were stuck without air conditioning for almost an hour. Worse, though, that morning there was a feature in the Montreal newspaper about a bus in Germany that had burst into flames, killing several passengers. 😔 Not surprisingly, then, everyone on the bus was a bit on edge when we learned that there was an electrical problem with the batteries, and even more so as we heard a roadside mechanic loudly banging around in the back of the bus. Another bus finally picked us up, but that was quite the way to end the trip!


text:
package knative

import (
	"context"

	"knative.dev/reconciler-test/pkg/environment"
)

type knativeNamespaceConfig struct{}

func WithKnativeNamespace(namespace string) environment.EnvOpts {
	return func(ctx context.Context, env environment.Environment) (context.Context, error) {
		return context.WithValue(ctx, knativeNamespaceConfig{}, namespace), nil
	}
}

func KnativeNamespaceFromContext(ctx context.Context) string {
	if e, ok := ctx.Value(knativeNamespaceConfig{}).(string); ok {
		return e
	}
	panic("no knative namespace found in the context, make sure you properly configured the env opts using WithKnativeNamespace")
}


text:
package org.lwjgl.stb;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 *
Layout

 *
 *

 * struct stb_vorbis_comment {
 *     char * vendor;
 *     int comment_list_length;
 *     char ** comment_list;
 * }

 */
@NativeType("struct stb_vorbis_comment")
public class STBVorbisComment extends Struct implements NativeResource {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        VENDOR,
        COMMENT_LIST_LENGTH,
        COMMENT_LIST;

    static {
        Layout layout = __struct(
            __member(POINTER_SIZE),
            __member(4),
            __member(POINTER_SIZE)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        VENDOR = layout.offsetof(0);
        COMMENT_LIST_LENGTH = layout.offsetof(1);
        COMMENT_LIST = layout.offsetof(2);
    }

    /**
     * Creates a {@code STBVorbisComment} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public STBVorbisComment(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@code vendor} field. */
    @NativeType("char *")
    public ByteBuffer vendor() { return nvendor(address()); }
    /** @return the null-terminated string pointed to by the {@code vendor} field. */
    @NativeType("char *")
    public String vendorString() { return nvendorString(address()); }
    /** @return the value of the {@code comment_list_length} field. */
    public int comment_list_length() { return ncomment_list_length(address()); }
    /** @return a {@link PointerBuffer} view of the data pointed to by the {@code comment_list} field. */
    @NativeType("char **")
    public PointerBuffer comment_list() { return ncomment_list(address()); }

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

    /** Returns a new {@code STBVorbisComment} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static STBVorbisComment malloc() {
        return wrap(STBVorbisComment.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code STBVorbisComment} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static STBVorbisComment calloc() {
        return wrap(STBVorbisComment.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code STBVorbisComment} instance allocated with {@link BufferUtils}. */
    public static STBVorbisComment create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(STBVorbisComment.class, memAddress(container), container);
    }

    /** Returns a new {@code STBVorbisComment} instance for the specified memory address. */
    public static STBVorbisComment create(long address) {
        return wrap(STBVorbisComment.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static STBVorbisComment createSafe(long address) {
        return address == NULL ? null : wrap(STBVorbisComment.class, address);
    }

    /**
     * Returns a new {@link STBVorbisComment.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link STBVorbisComment.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link STBVorbisComment.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link STBVorbisComment.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static STBVorbisComment.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

    /**
     * Returns a new {@code STBVorbisComment} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static STBVorbisComment malloc(MemoryStack stack) {
        return wrap(STBVorbisComment.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code STBVorbisComment} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static STBVorbisComment calloc(MemoryStack stack) {
        return wrap(STBVorbisComment.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link STBVorbisComment.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link STBVorbisComment.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static STBVorbisComment.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

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

    /** Unsafe version of {@link #vendor}. */
    public static ByteBuffer nvendor(long struct) { return memByteBufferNT1(memGetAddress(struct + STBVorbisComment.VENDOR)); }
    /** Unsafe version of {@link #vendorString}. */
    public static String nvendorString(long struct) { return memASCII(memGetAddress(struct + STBVorbisComment.VENDOR)); }
    /** Unsafe version of {@link #comment_list_length}. */
    public static int ncomment_list_length(long struct) { return UNSAFE.getInt(null, struct + STBVorbisComment.COMMENT_LIST_LENGTH); }
    /** Unsafe version of {@link #comment_list() comment_list}. */
    public static PointerBuffer ncomment_list(long struct) { return memPointerBuffer(memGetAddress(struct + STBVorbisComment.COMMENT_LIST), ncomment_list_length(struct)); }

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

    /** An array of {@link STBVorbisComment} structs. */
    public static class Buffer extends StructBuffer<STBVorbisComment, Buffer> implements NativeResource {

        private static final STBVorbisComment ELEMENT_FACTORY = STBVorbisComment.create(-1L);

        /**
         * Creates a new {@code STBVorbisComment.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link STBVorbisComment#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected STBVorbisComment getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@code vendor} field. */
        @NativeType("char *")
        public ByteBuffer vendor() { return STBVorbisComment.nvendor(address()); }
        /** @return the null-terminated string pointed to by the {@code vendor} field. */
        @NativeType("char *")
        public String vendorString() { return STBVorbisComment.nvendorString(address()); }
        /** @return the value of the {@code comment_list_length} field. */
        public int comment_list_length() { return STBVorbisComment.ncomment_list_length(address()); }
        /** @return a {@link PointerBuffer} view of the data pointed to by the {@code comment_list} field. */
        @NativeType("char **")
        public PointerBuffer comment_list() { return STBVorbisComment.ncomment_list(address()); }

    }

}


text:
{-# LANGUAGE RecordWildCards, LambdaCase #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE NamedFieldPuns    #-}

module WindowsInstaller
    ( main
    , writeInstallerNSIS
    , writeUninstallerNSIS
    ) where

import           Universum hiding (pass, writeFile, stdout, FilePath, die, view)

import qualified Data.List as L
import qualified Data.Text as T
import           Data.Yaml                 (decodeFileThrow)
import           Development.NSIS (Attrib (IconFile, IconIndex, RebootOK, Recursive, Required, StartOptions, Target),
                                   HKEY (HKLM), Level (Highest), Page (Directory, InstFiles), abort,
                                   constant, constantStr, createDirectory, createShortcut, delete,
                                   deleteRegKey, file, iff_, installDir, installDirRegKey,
                                   name, nsis, onPagePre, onError, outFile, page, readRegStr,
                                   requestExecutionLevel, rmdir, section, setOutPath, str,
                                   strLength, uninstall, unsafeInject, unsafeInjectGlobal,
                                   loadLanguage, sleep, (@=), detailPrint, (%<), (%&&),
                                   not_, mutableInt_, mutable_, while, false, true, strShow, (&),
                                   writeRegDWORD, writeRegStr, (%/=), fileExists)
import           Prelude ((!!))
import qualified System.IO as IO
import           Filesystem.Path (FilePath, (</>))
import           Filesystem.Path.CurrentOS (encodeString, fromText)
import           Turtle (Shell, Line, ExitCode (..), echo, proc, procs, inproc, shells, testfile, export, sed, strict, format, printf, fp, w, s, (%), need, writeTextFile, die, cp, rm)
import           Turtle.Pattern (text, plus, noneOf, star, dot)

import           Config
import           Types
import           Util

daedalusShortcut :: Text -> [Attrib]
daedalusShortcut installDir =
        [ Target "$INSTDIR\\cardano-launcher.exe"
        , IconFile $ fromString $ T.unpack $ "$INSTDIR\\" <> installDir <> ".exe"
        , StartOptions "SW_SHOWMINIMIZED"
        , IconIndex 0
        ]

-- See INNER blocks at http://nsis.sourceforge.net/Signing_an_Uninstaller
writeUninstallerNSIS :: Version -> InstallerConfig -> IO ()
writeUninstallerNSIS (Version fullVersion) installerConfig = do
    tempDir <- getTempDir
    IO.writeFile "uninstaller.nsi" $ nsis $ do
        _ <- constantStr "Version" (str $ T.unpack fullVersion)
        _ <- constantStr "InstallDir" (str $ T.unpack $ installDirectory installerConfig)
        _ <- constantStr "SpacedName" (str $ T.unpack $ spacedName installerConfig)
        unsafeInjectGlobal "Unicode true"

        loadLanguage "English"
        loadLanguage "Japanese"

        --mapM_ unsafeInjectGlobal
        --  [ "LangString UninstallName ${LANG_ENGLISH} \"Uninstaller\""
        --  , "LangString UninstallName ${LANG_JAPANESE} \"アンインストーラー\""
        --  ]

        name "$SpacedName Uninstaller $Version"
        -- TODO, the nsis library doesn't support translation vars
        -- name "$InstallDir $(UninstallName) $Version"
        --unsafeInjectGlobal $ T.unpack ( "Name \"" <> (installDirectory installerConfig) <> " $(UninstallName) " <> (fullVersion) <> "\"")
        outFile . str . encodeString $ tempDir </> "tempinstaller.exe"
        unsafeInjectGlobal "!addplugindir \"nsis_plugins\\liteFirewall\\bin\""
        unsafeInjectGlobal "SetCompress off"

        _ <- section "" [Required] $ do
            unsafeInject . T.unpack $ format ("WriteUninstaller \""%fp%"\"") ("c:\\uninstall.exe")

        uninstall $ do
            -- Remove registry keys
            deleteRegKey HKLM "Software/Microsoft/Windows/CurrentVersion/Uninstall/$SpacedName"
            deleteRegKey HKLM "Software/$SpacedName"
            rmdir [Recursive,RebootOK] "$INSTDIR"
            delete [] "$SMPROGRAMS/$SpacedName/*.*"
            delete [] "$DESKTOP\\$SpacedName.lnk"
            mapM_ unsafeInject
                [ "liteFirewall::RemoveRule \"$INSTDIR\\cardano-node.exe\" \"Cardano Node\""
                , "Pop $0"
                , "DetailPrint \"liteFirewall::RemoveRule: $0\""
                ]
            -- Note: we leave user data alone

-- See non-INNER blocks at http://nsis.sourceforge.net/Signing_an_Uninstaller
signUninstaller :: Options -> IO SigningResult
signUninstaller opts = do
    rawnsi <- readFile "uninstaller.nsi"
    putStr rawnsi
    IO.hFlush IO.stdout

    procs "C:\\Program Files (x86)\\NSIS\\makensis" ["uninstaller.nsi"] mempty
    tempDir <- getTempDir
    writeTextFile "runtempinstaller.bat" $ format (fp%" /S") (tempDir </> "tempinstaller.exe")
    -- in order to sign the uninstaller, we must first create a dummy nsis script that generates a stand-alone uninstaller at "install time"
    -- then "install" that dummy on the CI system, to create the uninstaller
    void $ proc "runtempinstaller.bat" [] mempty
    result <- signFile opts ("c:/uninstall.exe")
    tempDir <- getTempDir
    cp "c:/uninstall.exe" (tempDir </> "uninstall.exe")
    pure result

signFile :: Options -> FilePath -> IO SigningResult
signFile Options{..} filename = do
    exists   <- testfile filename
    mCertPass <- need "CERT_PASS"
    case (exists, mCertPass) of
      (True, Just certPass) -> do
        printf ("Signing "%fp%"\n") filename
        -- TODO: Double sign a file, SHA1 for vista/xp and SHA2 for windows 8 and on
        -- procs "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.1A\\Bin\\signtool.exe" ["sign", "/f", "C:\\iohk-windows-certificate.p12", "/p", toText pass, "/t", "http://timestamp.comodoca.com", "/v", toText filename] mempty
        exitcode <- proc "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.1A\\Bin\\signtool.exe" ["sign", "/f", "C:\\iohk-windows-certificate.p12", "/p", toText certPass, "/fd", "sha256", "/tr", "http://timestamp.comodoca.com/?td=sha256", "/td", "sha256", "/v", tt filename] mempty
        unless (exitcode == ExitSuccess) $ die "Signing failed"
        pure SignedOK
      (False, _) ->
        die $ format ("Unable to sign missing file '"%fp%"'\n") filename
      (_, Nothing) -> do
        echo "Not signing: CERT_PASS not specified."
        pure NotSigned

parseVersion :: Text -> [String]
parseVersion ver =
    case T.split (== '.') (toText ver) of
        v@[_, _, _, _] -> map toString v
        _              -> ["0", "0", "0", "0"]

writeInstallerNSIS :: FilePath -> Version -> InstallerConfig -> Options -> Cluster -> IO ()
writeInstallerNSIS outName (Version fullVersion') InstallerConfig{installDirectory,spacedName} Options{oBackend} clusterName = do
    tempDir <- getTempDir
    let fullVersion = T.unpack fullVersion'
        viProductVersion = L.intercalate "." $ parseVersion fullVersion'
    printf ("VIProductVersion: "%w%"\n") viProductVersion

    IO.writeFile "daedalus.nsi" $ nsis $ do
        _ <- constantStr "Version" (str fullVersion)
        _ <- constantStr "Cluster" (str $ lshow clusterName)
        _ <- constantStr "InstallDir" (str $ T.unpack installDirectory)
        _ <- constantStr "SpacedName" (str $ T.unpack spacedName)
        name "$SpacedName ($Version)"                  -- The name of the installer
        outFile $ str $ encodeString outName        -- Where to produce the installer
        unsafeInjectGlobal $ "!define MUI_ICON \"icons\\" ++ lshow clusterName ++ "\\" ++ lshow clusterName ++ ".ico\""
        unsafeInjectGlobal $ "!define MUI_HEADERIMAGE"
        unsafeInjectGlobal $ "!define MUI_HEADERIMAGE_BITMAP \"icons\\installBanner.bmp\""
        unsafeInjectGlobal $ "!define MUI_HEADERIMAGE_RIGHT"
        unsafeInjectGlobal $ "!include WinVer.nsh"
        unsafeInjectGlobal $ "VIProductVersion " <> viProductVersion
        unsafeInjectGlobal $ "VIAddVersionKey \"ProductVersion\" " <> fullVersion
        unsafeInjectGlobal "Unicode true"
        requestExecutionLevel Highest
        unsafeInjectGlobal "!addplugindir \"nsis_plugins\\liteFirewall\\bin\""

        installDir "$PROGRAMFILES64\\$SpacedName"                   -- Default installation directory...
        installDirRegKey HKLM "Software/$SpacedName" "Install_Dir"  -- ...except when already installed.

        loadLanguage "English"
        loadLanguage "Japanese"
        mapM_ unsafeInjectGlobal
          [ "LangString AlreadyRunning ${LANG_ENGLISH} \"is running. It needs to be fully shut down before running the installer!\""
          , "LangString AlreadyRunning ${LANG_JAPANESE} \"が起動中です。 インストーラーを実行する前に完全にシャットダウンする必要があります!\""
          , "LangString TooOld ${LANG_ENGLISH} \"This version of Windows is not supported. Windows 8.1 or above required.\""
          , "LangString TooOld ${LANG_JAPANESE} \"このWindowsバージョンはサポートされていません。Windows 8.1以降が必要です。\""
          ]

        mapM_ unsafeInject [
            "${IfNot} ${AtLeastWin8.1}"
          , "  MessageBox MB_OK \"$(TooOld)\""
          , "  Quit"
          , "${EndIf}"
          ]

        page Directory                   -- Pick where to install
        _ <- constant "INSTALLEDAT" $ readRegStr HKLM "Software/$SpacedName" "Install_Dir"
        onPagePre Directory (iff_ (strLength "$INSTALLEDAT" %/= 0) $ abort "")

        page InstFiles                   -- Give a progress bar while installing

        _ <- section "" [Required] $ do
                setOutPath "$INSTDIR"        -- Where to install files in this section
                unsafeInject "AllowSkipFiles off"
                writeRegStr HKLM "Software/$SpacedName" "Install_Dir" "$INSTDIR" -- Used by launcher batch script
                createDirectory "$APPDATA\\$InstallDir\\Secrets-1.0"
                createDirectory "$APPDATA\\$InstallDir\\Logs"
                createDirectory "$APPDATA\\$InstallDir\\Logs\\pub"

                -- XXX: sometimes during auto-update, it takes longer for Daedalus to exit,
                -- and cardano-launcher.exe's lockfile to be unlocked (deletable), so
                -- let's loop waiting for this to happen:
                let waitSeconds = 30
                lockfileCounter <- mutableInt_ 0
                lockfileDeleted <- mutable_ false
                while ((lockfileCounter %< waitSeconds) %&& (not_ lockfileDeleted)) $ do
                    detailPrint (
                        "Checking if Daedalus is not running ("
                        Development.NSIS.& strShow (lockfileCounter + 1)
                        Development.NSIS.& "/"
                        Development.NSIS.& strShow waitSeconds
                        Development.NSIS.& ")..."
                        )
                    lockfileDeleted @= true
                    onError (delete [] "$APPDATA\\$InstallDir\\daedalus_lockfile") $ do
                        lockfileDeleted @= false
                    iff_ (not_ lockfileDeleted) $ do
                        sleep 1000 -- milliseconds
                    lockfileCounter @= lockfileCounter + 1
                iff_ (not_ (lockfileDeleted)) $ do
                    unsafeInject $ T.unpack $ "Abort \"" <> installDirectory <> " $(AlreadyRunning)\""

                iff_ (fileExists "$APPDATA\\$InstallDir\\Wallet-1.0\\open\\*.*") $
                    rmdir [] "$APPDATA\\$InstallDir\\Wallet-1.0\\open"
                case oBackend of
                  Cardano _ -> do
                    file [] "cardano-node.exe"
                    file [] "cardano-wallet.exe"
                    file [] "cardano-address.exe"
                    file [] "cardano-cli.exe"
                    file [] "config.yaml"
                    file [] "topology.yaml"
                    file [] "genesis.json"
                    when (clusterName /= Selfnode) $ do
                      file [] "genesis-byron.json"
                      file [] "genesis-shelley.json"
                      file [] "genesis-alonzo.json"
                    file [] "libsodium-23.dll"
                    file [] "libsecp256k1-0.dll"
                    when (clusterName == Selfnode) $ do
                      file [] "signing.key"
                      file [] "delegation.cert"
                      file [] "local-cluster.exe"
                      file [] "libgmpxx-4.dll"
                      file [] "libwinpthread-1.dll"
                      file [] "mock-token-metadata-server.exe"
                      file [Recursive] "test\\"
                      file [] "token-metadata.json"
                file [] "cardano-launcher.exe"
                file [] "libffi-8.dll"
                file [] "libgmp-10.dll"
                --file [] "cardano-x509-certificates.exe"
                --file [] "log-config-prod.yaml"
                --file [] "wallet-topology.yaml"
                --file [] "configuration.yaml"
                --file [] "*genesis*.json"
                file [] "launcher-config.yaml"
                file [Recursive] "dlls\\"
                file [Recursive] "..\\release\\win32-x64\\$SpacedName-win32-x64\\"

                mapM_ unsafeInject
                    [ "liteFirewall::AddRule \"$INSTDIR\\cardano-node.exe\" \"Cardano Node\""
                    , "Pop $0"
                    , "DetailPrint \"liteFirewall::AddRule: $0\""
                    ]

                createShortcut "$DESKTOP\\$SpacedName.lnk" (daedalusShortcut spacedName)

                -- Uninstaller
                let
                    uninstallKey = "Software/Microsoft/Windows/CurrentVersion/Uninstall/$SpacedName"
                do
                    writeRegStr HKLM uninstallKey "InstallLocation" "$INSTDIR"
                    writeRegStr HKLM uninstallKey "Publisher" "IOHK"
                    writeRegStr HKLM uninstallKey "ProductVersion" (str fullVersion)
                    writeRegStr HKLM uninstallKey "VersionMajor" (str . (!! 0). parseVersion $ fullVersion')
                    writeRegStr HKLM uninstallKey "VersionMinor" (str . (!! 1). parseVersion $ fullVersion')
                    writeRegStr HKLM uninstallKey "DisplayName" "$SpacedName"
                    writeRegStr HKLM uninstallKey "DisplayVersion" (str fullVersion)
                    writeRegStr HKLM uninstallKey "UninstallString" "\"$INSTDIR/uninstall.exe\""
                    writeRegStr HKLM uninstallKey "QuietUninstallString" "\"$INSTDIR/uninstall.exe\" /S"
                    writeRegDWORD HKLM uninstallKey "NoModify" 1
                    writeRegDWORD HKLM uninstallKey "NoRepair" 1
                file [] $ (str . encodeString $ tempDir </> "uninstall.exe")

        -- this string never appears in the UI
        _ <- section "Start Menu Shortcuts" [] $ do
                createDirectory "$SMPROGRAMS/$SpacedName"
                createShortcut "$SMPROGRAMS/$SpacedName/Uninstall $SpacedName.lnk"
                    [Target "$INSTDIR/uninstall.exe", IconFile "$INSTDIR/uninstall.exe", IconIndex 0]
                createShortcut "$SMPROGRAMS/$SpacedName/$SpacedName.lnk" (daedalusShortcut installDirectory)
        return ()

lshow :: Show a => a -> String
lshow = T.unpack . lshowText

packageFrontend :: Cluster -> InstallerConfig -> IO ()
packageFrontend cluster installerConfig = do
    let
      icon = format ("installers/icons/"%s%"/"%s) (lshowText cluster) (lshowText cluster)
      installDir :: Text
      installDir = installDirectory installerConfig
      releaseDir :: Text
      releaseDir = "../release/win32-x64/" <> (installDirectory installerConfig) <> "-win32-x64"
    export "NODE_ENV" "production"
    rewritePackageJson "../package.json" installDir
    echo "running yarn"
    shells ("yarn run package --icon " <> icon) empty
    cp "../node_modules/ps-list/fastlist.exe" $ fromString $ T.unpack $ releaseDir <> "/resources/app/dist/main/fastlist.exe"

-- | The contract of `main` is not to produce unsigned installer binaries.
main :: Options -> IO ()
main opts@Options{..}  = do
    cp (fromText "launcher-config.yaml") (fromText "../launcher-config.yaml")

    installerConfig <- decodeFileThrow "installer-config.json"

    fullVersion <- getDaedalusVersion "../package.json"
    ver <- getCardanoVersion

    echo "Packaging frontend"
    exportBuildVars opts ver
    packageFrontend oCluster installerConfig

    let fullName = packageFileName Win64 oCluster fullVersion oBackend ver oBuildJob

    printf ("Building: "%fp%"\n") fullName

    echo "Adding permissions manifest to cardano-launcher.exe"
    procs "C:\\Program Files (x86)\\Windows Kits\\8.1\\bin\\x64\\mt.exe" ["-manifest", "cardano-launcher.exe.manifest", "-outputresource:cardano-launcher.exe;#1"] mempty

    signFile opts "cardano-launcher.exe"
    signFile opts "cardano-node.exe"

    echo "Writing uninstaller.nsi"
    writeUninstallerNSIS fullVersion installerConfig
    signUninstaller opts

    echo "Writing daedalus.nsi"
    writeInstallerNSIS fullName fullVersion installerConfig opts oCluster

    rawnsi <- readFile "daedalus.nsi"
    putStr rawnsi
    IO.hFlush IO.stdout

    windowsRemoveDirectoryRecursive $ T.unpack $ "../release/win32-x64/" <> (installDirectory installerConfig) <> "-win32-x64/resources/app/installers/.stack-work"

    echo "Generating NSIS installer"
    procs "C:\\Program Files (x86)\\NSIS\\makensis" ["daedalus.nsi", "-V4"] mempty

    signed <- signFile opts fullName
    case signed of
      SignedOK  -> pure ()
      NotSigned -> rm fullName

-- | Run cardano-node --version to get a version string.
-- Because this is Windows, all necessary DLLs for cardano-node.exe
-- need to be in the PATH.
getCardanoVersion :: IO Text
getCardanoVersion = withDir "DLLs" (grepCardanoVersion run)
  where
    run = inproc (tt prog) ["--version"] empty
    prog = ".." </> "cardano-node.exe"

grepCardanoVersion :: Shell Line -> IO Text
grepCardanoVersion = fmap T.stripEnd . strict . sed versionPattern
  where
    versionPattern = text "cardano-node-" *> plus (noneOf ", ") <* star dot

getTempDir :: MonadIO io => io FilePath
getTempDir = need "TEMP" >>= \case
  Just temp -> pure (fromText temp)
  Nothing -> die "Environment variable TEMP is not set."