text:
\documentstyle[11pt]{article}
\input{format}
\input{pars_defn}
\begin{document}
\begin{center}
{\large \bf IDA --- A Tcl Imaging and Data Analysis extension} \\
\vspace{0.5cm}
{\large \bf Version 0.5 12 April 1995} \\
\vspace{0.5cm}
{\large Paul Alexander, Cavendish Laboratory, Cambridge, UK}\\
\end{center}

\section{Introduction}

{\bf IDA} is an image/data processing and analysis language based
on Tcl (Ousterhout 1994).  The language is implemented as a Tcl
extension and may be used with other extensions.  It provides the
tools necessary for image/data analysis, but not for display although
{\it hooks} are provided within the Tcl {\bf pgplot} extension to provide
display functions.

This version provides support for {\em images} alone ---
in this context we consider an image to be a set of gridded data values
represented by a contnuous 4D volume.  Each element in this volume is referred
to as a pixel (for 3D data the term voxel is often used).  At each pixel
we may have a vector of data values --- therefore 5-dimensional data
may be handled.  A normal representation would be to map the 4 dimensions
of the data volume onto three spatial and one time dimension and to hold in
the vector any number of {\em physical} quantities.  These may be for example
density, pressure, temperature in a fluid-dynamical simulation, red, green
and blue for a true-colour image or components of one or more complex
quantities.  Future versions will include support for a second data format
where the data consist of a vector of values on discrete points in an
N-dimensional space and may include connectivities between the data ---
such a format is more appropriate for representing say the output of N-body
simulations or molecular data.

The internal representation is as a 5-dimension array of
4-byte floating point values; this is a necessary representation for the ---
{\bf IDA} can also be used to analyse images more usually
represented with less precision although at a cost in terms of memory usage
and for some operations processing time (but not all).
Fixing on one data type greatly simplifies
the implementation and is aimed at providing functionality rather than
the greatest efficiency.
\footnote{
It is the author's view that the power of
modern workstations is so great that many issues which were until
recently of concern --- memory usage, floating-point performance etc. ---
are no-longer overiding considerations in the design of
data-processing software.  Of much greater improtance is the time required
for scientists to implement relatively efficient, and accurate code.
}

The remainder of this section introduces a number of terms and concepts used
throughout the package.

\subsection{Image identifiers -- imId}

All commands acting on images take an image identifier --- in the
documentation this is abreviated to {\bf imId}.  Commands will also
return an {\bf imId} if they modify an image.
In the current implementation of the package {\bf imId}s are simply
an integer  value, in a future release this will change to be an integer
prefixed by a short string (probably {\it img}) to make the behaviour consistent
with other Tcl extensions.  You should not therefore {\it rely} on
{\bf imId}s being integers.

\subsection{Data formats}
At present three image formats are supported and
identified via a numerical {\it type}:
\begin{npars}
\item MRAO map format.
\item DDF format --- this stands for {\it Directory Data Format} and is
a very flexible format supported by the {\bf IDA} extension.  It is the
prefered format for {\bf IDA} images.
\item FITS --- Flexible image transport.
\end{npars}

Note that in the current release of the {\bf IDA} little
attention is paid to image headers beyond those items needed to read and
write data.  You should not therefore use the current implemntation to
convert between image formats and only DDF format has been tested to
any extent.  In future versions of the package there will be proper
support for image headers and for image conversion.

\subsection{Sub images}
Various commands take as some of their optional arguments a subimage.
A sub-image specifies a contiguous region of the image, for example
a range of values from a 1D image or a rectangular region in a 2D image.
To specify the subimage you must indicate the bouding pixel in each dimension;
a standard notation, common to all imaging commands, exists to specify the
subimage by specify options in the standard Tcl manner:
\begin{verbatim}
   -x1 Ix1 -x2 Ix2
   -y1 Iy1 -y2 Iy2
   -z1 Iz1 -z2 Iz2
   -t1 It1 -t2 It2
   -v1 Iv1 -v2 Iv2
\end{verbatim}
throughout this text the term {\bf subimage} will refer to a region of the
image specified using the above notation for a sub-image.
Any optional parameters which are not supplied default to the full extent of the
image.  It is legal to specify a subimage which extends beyond the
boundary of the image --- only those pixels which are within the image
will be used in processing.

\subsection{Blanking}
All imaging commands support the concept of a {\it blank} pixel.  This is
a pixel which has been set to a particular value to indicate that it does
not contain a physically realistic number.  The value is usually chosen to
be completely out of the bounds of physically sensible values (usually
a very large negative value such as 1.0E-30).  Commands exist to blank
and un-blank regions of images.  The blanking value is usually set in the
image header or definition record for an image stored on disc.

\subsection{Normalization}
Imaging commands which sum the image make use of a normalization parameter.
The normalization parameter is usually defined in the
image header or definition record for an image stored on disc.

\section{Commands to perform basic functions on images}

\subsection{The img\_image command}
The {\bf img\_image} command is used to provide low-level access to images
and to perform image I/O.  The synopsis for the command is:
\begin{verbatim}
   img_image option ?parameters?
\end{verbatim}
Table 1 provides a summary of the available options.
\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
read ?-file {\bf file}? ?-type {\bf type}? &
\begin{minipage}[t]{11.0cm}
Read a data file from {\bf file}.  The format of the data is specified
by the parameter {\bf type} and has one of the values listed in Section 1.2.
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
write ?-imid {\bf I}? ?-file {\bf file}? ?-type {\bf type}?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Read a data file from {\bf file}.  The format of the data is specified
by the parameter {\bf type} and has one of the values listed in Section 1.2.
\end{minipage} \\
& \\
destroy {\bf imId} & destroy the data structure associated wtih {\bf imId}\\
& \\
create {\bf defn} &
\begin{minipage}[t]{11.0cm}
create a new image with dimensions given by {\bf defn} which is a
normal Tcl array which should have all the elements required for a
definition record.  One method of ensuring this would be to read the
definition record from another {\bf imId} and modify it.
\end{minipage} \\
& \\
collapse {\bf imId} &
\begin{minipage}[t]{11.0cm}
reduce dimansionality of {\bf imId} by collapsing any dimension of unity.
This option sets range on dimensions of unity to 1.
\end{minipage} \\
& \\
next & return next free image ID {\bf imId}\\
& \\
exists {\bf imId} &
\begin{minipage}[t]{11.0cm}
check whether {\bf imId} is valid and exists.  The command returns a
boolean indicating true (1) if {\bf imId} exists.
\end{minipage} \\
& \\
max & return maximum number of images that may be allocated.\\
& \\
defget {\bf imId} {\bf defn} &
\begin{minipage}[t]{11.0cm}
get the definition record, returned in array {\bf defn}
\end{minipage} \\
& \\
defset {\bf imId} {\bf defn} &
\begin{minipage}[t]{11.0cm}
set the definition record for {\bf imId} from the array {\bf defn}.
\end{minipage} \\
& \\
defread {\bf file} {\bf defn} &
\begin{minipage}[t]{11.0cm}
read the definition record for file {\bf file};
the definition record is returned in array {\bf defn}.
\end{minipage} \\
& \\
defputs {\bf imId} & display the definition record for {\bf imId} on stdout\\
& \\
& \\ \hline
\end{tabular}
\caption{Options and return values for the {\bf img\_image} command.}
\end{table}
The most important use for the {\bf img\_image} command is to perform
I/O for images.
An example illustrates the use of the {\bf img\_image} command to
read in data and display it using the {\bf pgplot} extension which
defines a new command {\bf pg}.
\begin{verbatim}
   set n [img_image read -file ex1.dat -type 1]
   pg stream open 1 /xwindow
   set st [img_anal $n statistics]
   pg image $n [lindex $st 0] [lindex $st 1]
\end{verbatim}
In this example the {\bf img\_anal} command (Section 2.2) is used to annalyse
the image and obtain statistics which are needed for {\bf pg image} ---
this command takes arguments which are the
minimum and maximum of the range to display.

\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
\begin{minipage}[t]{4.0cm}
\flushleft
statistics
?-gate $g$? ?-agate $ag$?
?-min $m1$? ?-max $m2$?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
obtain statistics for an image. Only pixels satisfying:
\[
val > g  \; \&\&  \; abs( val ) > ag \; \&\&  \; m1 \le val \le m2
\]
are analysed in the specified subimage.
A list of \{max min mean sd min-pixel max-pixel\}
is returned.  The defaults are such as to analyse all pixels in the
image.
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
\flushleft
maxmin
?-gate $g$? ?-agate $ag$?
?-min $m1$? ?-max $m2$?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
obtain the maximum and minimum for an image. Only pixels satisfying:
\[
val > g  \; \&\&  \; abs( val ) > ag \; \&\&  \; m1 \le val \le m2
\]
are analysed in the specified subimage.
A list of \{max min min-pixel max-pixel\}
is returned.  The defaults are such as to analyse all pixels in the
image.
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
\flushleft
sum
?-gate $g$? ?-agate $ag$?
?-min $m1$? ?-max $m2$?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
obtain the sum of pixel intensities for an image. Only pixels satisfying:
\[
val > g  \; \&\&  \; abs( val ) > ag \; \&\&  \; m1 \le val \le m2
\]
are summed.  The sum of pixel intensities satisfying the above
constraints and within the specified subimage is returned scaled by the
normalization parameter.
The defaults are such as to analyse all pixels in the image.
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
\flushleft
histogram ?-ndata {\bf ndata}?
?-low {\bf low}? ?-high {\bf high}?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Extract a 1D image which is a histogram of image data in the specified
sub-image of the image. The command returns the imId of the new image
which has xdim = {\bf ndata} and vdim=2; the first vector argument is
the value for the bin,
the second is the number of pixels within the bin.  This format is appropriate
for display using the {\bf pg} extension. The default for {\bf ndata}
is 100 and {\bf low/high} default to the min/max on the image.
\end{minipage} \\
& \\
& \\ \hline
\end{tabular}
\caption{The {\bf img\_anal} command for basic image analysis.
The first argument to
{\bf img\_anal} must be a valid {\bf imId} and the second one of the above
options.  All the options take as an additional argument a {\bf subimage}
specification to limit the analysis to a specified sub-region of the
image.  The {\bf subimage} specification should occur after all
compulsary arrguments.}
\end{table}

\subsection{Image analysis with img\_anal}

Analysis of images is performed using the {\bf img\_anal} command.
The synopsis for the command is:
\begin{verbatim}
   img_anal imId option ?parameters? ?subimage?
\end{verbatim}
Options for the command are listed in Table 2.  For all forms of the command
you may specify a {\bf subimage} (see section 1.2) which should appear
after all compulsary arguments; only pixels within the specified subimage
are analysed.
The following example illustrates how the output of the {\bf statistics}
option can be used to implement an algorithm which attempts an
analysis of noise in an image by assuming highly discrepant points are in
fact true signal.
\begin{verbatim}
   proc img_noise { imId nSD} {
    # determine mean and SD of image data
      set st [img_anal $imId statistics]
    # discard points more than nSD standard deviations from the mean
    # and recalculate the statistcis for the image.
    # Iterate three times
      for {set n 0} {$n < 3} {incr n} {
         set min [expr [lindex $st 2] - $nSD * [lindex $st 3]]
         set max [expr [lindex $st 2] + $nSD * [lindex $st 3]]
         set st [img_anal $imId statistics -min $min -max $max]
      }
      return [lindex $st 3]
   }
\end{verbatim}

\subsection{Modifying images with img\_apply}

The command {\bf img\_apply} takes an image and modifies it according to
a series of options which are applied sequentially to the image.  The
first agument to the command must be an {\bf imId} and subsequent arguments
are modifier options which themselves may take additional arguments as
either parameter values of other {\bf imId}s of other images.  The range
of options available with the {\bf img\_apply} command is given in
Tables 3 and 4.
\begin{verbatim}
   img_apply imId ?subimage? ?option ?parameter?? ?option ?parameter?? ...
\end{verbatim}
A {\bf subimage} may be specified which limits the command to operate on the
specified subimage --- the subimage may be specified anywhere on the
command line provided it does not break up an option which has to be followed
by a specified set of parameters; for clarity it is recommended that the
sub-image specification follows directly after {\bf imId}.
\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
= {\bf imId1} &
\begin{minipage}[t]{11.0cm}
set {\bf imId} equal to {\bf imId1}; the operation is applied
only to the {\bf subimage} common to both images.
\end{minipage} \\
& \\
== {\bf imId1} &
\begin{minipage}[t]{11.0cm}
set {\bf imId} equal to {\bf imId1}; the operation is applied
to the {\bf subimage} of {\bf imId}.  Values are taken sequentially
from {\bf imId1} such that the first pixel in
the subimage of {\bf imId} is set equal to the first value of {\bf imId1}.
\end{minipage} \\
& \\
+=, -=, *=, /=, {\bf imId1} &
\begin{minipage}[t]{11.0cm}
As for ``='' except:
\newline
{\bf imId} = {\bf imId} {\bf op} {\bf imId1}, where {\bf op} is +, -, *, / for
addition subtraction multiplication and division respectivley.
\end{minipage} \\
& \\
+==, -==, *==, /==, imId1 &
\begin{minipage}[t]{11.0cm}
As for ``=='' except:
\newline
{\bf imId} == {\bf imId} {\bf op} {\bf imId1}, where {\bf op} is +, -, *, / for
addition subtraction multiplication and division respectivley.
\end{minipage} \\
& \\
atan2 {\bf imId1} {\bf imId2} & set {\bf imId} = atan2( {\bf imId1}, {\bf imId2} ) \\
& \\
& \\ \hline
\end{tabular}
\caption{Options for the img\_apply command which combine images.
The first argument to img\_apply must be a valid {\bf imId} and subsequent
arguments are options as specified in this and the next table applied
sequentially.}
\end{table}

\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
\begin{minipage}[t]{4.0cm}
log, ln, log10, exp, sqrt
sin, cos, tan, asin, acos, atan
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Apply specified function to imId:
\newline
set {\bf imId} = func( {\bf imId} )
\end{minipage} \\
& \\
10 & set {\bf imId} = 10**{\bf imId} \\
& \\
raise {\bf x} & raise {\bf x} to power {\bf imId};
set {\bf imId} = {\bf x}**{\bf imId} \\
& \\
pow {\bf x} & raise {\bf imId} to power {\bf x}; set {\bf imId} = {\bf imId}**{\bf x}\\
& \\
scale {\bf x} & scale {\bf imId} by {\bf x}; set {\bf imId} = {\bf x} * {\bf imId}\\
& \\
offset {\bf x} & offset {\bf imId} by {\bf x}; set {\bf imId} = {\bf imId} + {\bf x}\\
& \\
binary {\bf x} & force {\bf imId} to be a binary image:\\
& if {\bf imId} $<$ {\bf x} then set {\bf imId} = 0.0, else set {\bf imId} = 1.0 \\
& \\
set {\bf x} & set {\bf imId} to the value {\bf x} \\
& \\
pass {\bf x1} {\bf x2} {\bf xI} & pass only values in interval {\bf x1} to {\bf x2}:\\
& if  {\bf imId} $<$ {\bf x1} or {\bf imId} $>$ {\bf x2} then set {\bf imId} = {\bf xI} \\
& \\
range {\bf x1} {\bf x2} {\bf op} {\bf xI} &
\begin{minipage}[t]{11.0cm}
For values in the interval {\bf x1} to {\bf x2} apply the specified operation.
{\bf op} should be one of =, +, $-$, * or /. Then:
\newline
if {\bf x1} $<$ {\bf imId} $<$ {\bf x2}  then set {\bf imId} = {\bf imId} {\bf op } {\bf xI}
\end{minipage} \\
& \\
quantize {\bf x1} {\bf x2} {\bf xI} & quantize image to values are multiples of\\
& {\bf xI} in the range {\bf x1} to {\bf x2}\\
& \\
blank & set image to blank values\\
& \\
unblank {\bf x} & set all blank pixels to value {\bf x}\\
& \\
inv & invert the image; {\bf imId} = 1.0/{\bf imId}\\
& \\
& \\ \hline
\end{tabular}
\caption{The img\_apply command for modifying
images.  The first argument to
img\_apply must be a valid {\bf imId} and subsequent arguments are options
as specified in this table applied sequentially.}
\end{table}

For example the following command averages four images:
\begin{verbatim}
   img_apply 0 += 1 += 2 += 3 scale 0.25
\end{verbatim}

In the following example we quantizes an image into a set of integer levels
and then displays each level in turn.  To do this a temporary copy of the
image is taken so that this can be used as work space:
\begin{verbatim}
   # quantize the image --- note the variable img1 just contains the the imId 0
   set img1 [img_apply 0 quantize 0.0 100.0 1.0]

   # make a copy for use as workspace
   set img2 [img_geom $img1 subimage]

   # loop and display all level using the img_display procedure
   # note how img2 is constantly reset to img1
   for {set n 0} {$n < 100} {incr n} {
      set m [expr $n + 1]
      img_apply $img2 = $img1 pass ${n}.0 ${m}.5
      img_display $img2
   }
   img_image destroy $img2
\end{verbatim}
This loop in this example could have been written very compactly as:
\begin{verbatim}
   for {set n 0; set m 1} {$n < 100} {incr n; incr m} {
      img_display [img_apply $img2 = $img1 pass ${n}.0 ${m}.5]
   }
\end{verbatim}
Note that at the end of the operation we destroy the temporary image
{\bf img2} --- in a long program without carefully destroying intermediate
images the memory usage will rise quickly and you will eventually use up all
the available image descriptors.

\subsection{Geometrical transformations with img\_geom}

The {\bf img\_geom} command is used to perform geometrical transformations
on images.  Some of the operations result in new images others are
performed ``in place'' --- if the operation is stricly reversible then the
latter method is usually followed.

Table 5 lists the options to the {\bf img\_geom} command --- the first
argument to {\bf img\_geom} is the {\bf imId} of the image to transform
the second is the tranformation option as listed in Table 5.

\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
subimage {\bf subimage} &
\begin{minipage}[t]{11.0cm}
Extract a subimage for {\bf imId}.  The format of a subimage is described in
section 1.3.  A new image is created by this command and the {\bf imId} of the
new image is returned.
\end{minipage} \\
& \\
project axis &
\begin{minipage}[t]{11.0cm}
Project the image along the specified axis.  The {\bf axis} argument
should be one of {\bf x, y, z, t} or {\bf v}.  This reduces the
dimensionality of the image by one.  The projection is accomplished
by summing all pixels to be projected onto a given direction.  If
any data selection is required (gating of the data for example) this
should have already been performed.
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
\flushleft
bshift
?-dx {\bf x}?
?-dy {\bf y}?
?-dz {\bf z}?
?-dt {\bf t}?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Perform a barrel shift on the image with pixel offsets given
x, y, z, t.  The defaults for the pixel offsets are 0 in all directions.
A barrel shift shifts the image by an integer number of pixels in all
dimensions and is performed using ``periodic boundary conditions'' so that
pixels projected outside the image will be wrapped back onto the opposite
side of the image.
\end{minipage} \\
& \\
flip axis &
\begin{minipage}[t]{11.0cm}
Flip the image in the direction specified by axis.
The {\bf axis} argument should be one of {\bf x, y, z, t}.
\end{minipage} \\
& \\
transpose axis-list &
\begin{minipage}[t]{11.0cm}
Transpose the axes of the image.  The new order of the axes
should be listed after the transpose option.  For example the
following will transpose the x and y axes for an X-dimensional image:
\begin{verbatim}
   img_geom 0 transpose y x
\end{verbatim}
\end{minipage} \\
& \\
\begin{minipage}[t]{4.0cm}
\flushleft
slice {\bf subimage}
\newline
?-ndata {\bf ndata}?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Extract a slice from the image.  The subimage format is used to
specify the extent of the slice which is taken from (x1, y1, z1, t1, v1)
to (x2, y2, z2, t2, v2).  The data are sampled along this slice to
give {\bf ndata} points.  The slice is returned as a 1D image with
vdim set to 2; the first vector argument is the length along the slice,
the second is the interpolated image value.  This format is appropriate
for display using the {\bf pg} extension.  {\bf ndata} defaults to 100.
\end{minipage} \\
& \\
& \\ \hline
\end{tabular}
\caption{The img\_geom command for performing geometrical
transformations to images.  The first argument to the command is
the {\bf imId} of the image to transform, the second is the option
as listed in this table.}
\end{table}

\begin{table}
\begin{tabular}{|l||l|}
\hline
& \\
{\bf Options} & {\bf Notes} \\
& \\ \hline
\begin{minipage}[t]{4.0cm}
\flushleft
transform
\newline
?-matrix \{{\bf matrix-elements}\}?
\newline
?-vector \{{\bf vector-elements}\}?
\newline
?-cvector \{{\bf cvector-elements}\}?
\newline
?-m11 {\bf m11}? ... ?-m44 {\bf m44}?
\end{minipage} &
\begin{minipage}[t]{11.0cm}
Apply a generalised linear transform to the image.  The transform
is specified in terms of a matrix and vector whose elements may be
real, floating-point, values.  The transformation is applied to determine
the mapping of the pixels of the new output image (the {\bf imId} of which is
returned by this command) to those of the original image.  The number
of elements supplied for the matrix must correspond to a square matrix
and should form a propoer Tcl list.  The corresponding matrix is taken
as the upper left sub-matrix of the full 4D tranformation matrix.
If the matrix is $M$, the vector $V$ and the c-vector $C$, then
pixels in the output image $po$ to the input image $pi$ are related by:
\[
po = V \; + M.(pi \; - \; C) \; + C
\]
therefore $V$ provides a linear translation and $M$ a general tranformation
about a point $C$.
\end{minipage} \\
& \\
& \\ \hline
\end{tabular}
\caption{The img\_geom command for performing generalised
transformations to images.  The first argument to the command is
the {\bf imId} of the image to transform, the second is the option
as listed in this table.}
\end{table}

\end{document}


text:
var fs = require('fs');
var html = fs.readFileSync('tests/samples/tests/1m.html', "utf8");
var ContextParser = require("context-parser").Parser;

var contextualize = function(n){
    var theParser = new ContextParser();
    try {
        theParser.contextualize(html);
    } catch (e) {
        console.log(e)
    }
    if ( theParser.state !== 1 ) {
        throw "Incorrect state.";
    }
};

module.exports = function() {
    contextualize();
};

redpajama_set_name: RedPajamaGithub


text:
namespace ginseng::util::image
{
    class Image : virtual public Root<Image>
    {
    public:
        struct Size : public Root<Size>
        {
            Size(size_t width, size_t height);

            virtual std::string to_string() const override;

            size_t width, height;
        };

        struct Position : public Root<Position>
        {
            Position(size_t x, size_t y);

            virtual std::string to_string() const override;

            size_t x, y;
        };

        virtual Size get_size() const = 0;

        Size size() const;

        virtual void resize(const Size &) = 0;

        void resize(size_t width, size_t height);

        virtual void draw_text(const Position &left_up_corner, const std::string &text) = 0;

        void draw_text(size_t x, size_t y, const std::string &text);

        virtual const Color::RGBA &get_pixel(const Position &) const = 0;

        const Color::RGBA &get_pixel(size_t x, size_t y) const;

        const Color::RGBA &pixel(const Position &) const;

        virtual Color::RGBA &pixel(const Position &) = 0;

        Color::RGBA &pixel(size_t x, size_t y);
    };
}

#endif // GINSENGPROJECT_UTIL_IMAGE_IMAGE_H


text:
require_relative 'spec_helper'

module Selenium
  module WebDriver
    describe Options do
      not_compliant_on browser: [:marionette, :ie, :edge] do
        describe 'logs' do
          compliant_on driver: :remote do
            it 'can fetch remote log types' do
              expect(driver.manage.logs.available_types).to include(:server, :client)
            end
          end

          # Phantomjs Returns har instead of driver
          not_compliant_on browser: :phantomjs do
            it 'can fetch available log types' do
              expect(driver.manage.logs.available_types).to include(:browser, :driver)
            end
          end

          # All other browsers show empty
          compliant_on browser: :firefox do
            it 'can get the browser log' do
              driver.navigate.to url_for('simpleTest.html')

              entries = driver.manage.logs.get(:browser)
              expect(entries).not_to be_empty
              expect(entries.first).to be_kind_of(LogEntry)
            end
          end

          # Phantomjs Returns har instead of driver
          not_compliant_on browser: :phantomjs do
            it 'can get the driver log' do
              driver.navigate.to url_for('simpleTest.html')

              entries = driver.manage.logs.get(:driver)
              expect(entries).not_to be_empty
              expect(entries.first).to be_kind_of(LogEntry)
            end
          end
        end
      end

      not_compliant_on browser: :phantomjs do
        describe 'cookie management' do
          it 'should get all' do
            driver.navigate.to url_for('xhtmlTest.html')
            driver.manage.add_cookie name: 'foo', value: 'bar'

            cookies = driver.manage.all_cookies

            expect(cookies.size).to eq(1)
            expect(cookies.first[:name]).to eq('foo')
            expect(cookies.first[:value]).to eq('bar')
          end

          # Edge BUG - https://connect.microsoft.com/IE/feedbackdetail/view/1864122
          not_compliant_on browser: :edge do
            it 'should delete one' do
              driver.navigate.to url_for('xhtmlTest.html')
              driver.manage.add_cookie name: 'foo', value: 'bar'

              driver.manage.delete_cookie('foo')
            end
          end

          # This is not a w3c supported spec
          not_compliant_on browser: :edge do
            it 'should delete all' do
              driver.navigate.to url_for('xhtmlTest.html')

              driver.manage.add_cookie name: 'foo', value: 'bar'
              driver.manage.delete_all_cookies
              expect(driver.manage.all_cookies).to be_empty
            end
          end

          # Marionette BUG - https://bugzilla.mozilla.org/show_bug.cgi?id=1256007
          not_compliant_on browser: [:android, :iphone, :safari, :marionette] do
            it 'should use DateTime for expires' do
              driver.navigate.to url_for('xhtmlTest.html')

              expected = DateTime.new(2039)
              driver.manage.add_cookie name: 'foo',
                                       value: 'bar',
                                       expires: expected

              actual = driver.manage.cookie_named('foo')[:expires]
              expect(actual).to be_kind_of(DateTime)
              expect(actual).to eq(expected)
            end
          end
        end
      end
    end
  end # WebDriver
end # Selenium


text:
package com.intellij.internal.statistic;

import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.internal.statistic.persistence.ApplicationStatisticsPersistence;
import com.intellij.internal.statistic.persistence.CollectedUsages;
import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent;
import com.intellij.internal.statistic.utils.StatisticsUtilKt;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.util.containers.ObjectIntHashMap;
import org.jetbrains.annotations.NotNull;

import java.util.Set;

// Collects(summarizes) project-level usages.
// Statistics is regularly sent  with some period of time (see com.intellij.internal.statistic.configurable.SendPeriod).
// In this period the user can open/close N projects which are not available at the "special send statistics" time.
// AbstractProjectsUsagesCollector persists the statistics data from opened/closed projects
// and summarizes collected results when data are requested.
//
// Example for groupId="my-team-lead-wants-something":
// 1. project A:  key_1= a1, key_2=b1, key_3=c1  // this project was opened and closed (not available just now)
// 2. project B:  key_1= a2, key_2=b2            // this project was opened and closed (not available just now)
// 3. project C:  key_1= a3, key_4=c3            // this project is open just now
// if "send statistics" action is invoked this UsageCollector returns :
// groupId="my-team-lead-wants-something":  key_1=(a1+a2+a3), key_2=(b1+b2), key_3=c1, key_4=c3
//
public abstract class AbstractProjectsUsagesCollector extends UsagesCollector {

  @NotNull
  public abstract Set<UsageDescriptor> getProjectUsages(@NotNull Project project) throws CollectUsagesException;

  private static final Logger LOG = Logger.getInstance(AbstractProjectsUsagesCollector.class);

  // Achtung!!! don't invoke this method directly even you can.
  void persistProjectUsages(@NotNull Project project) {
    try {
      persistProjectUsages(project, new CollectedUsages(getProjectUsages(project), System.currentTimeMillis()));
    }
    catch (Exception e) {
      LOG.info(e);
    }
  }

  private void persistProjectUsages(@NotNull Project project, @NotNull CollectedUsages usages) {
    persistProjectUsages(project, usages, ApplicationStatisticsPersistenceComponent.getInstance());
  }

  private void persistProjectUsages(@NotNull Project project,
                                   @NotNull CollectedUsages usages,
                                   @NotNull ApplicationStatisticsPersistence persistence) {
    persistence.persistUsages(getGroupId(), project, usages);
  }

  @NotNull
  private Set<UsageDescriptor> getApplicationUsages() {
    return mergeUsagesPostProcess(getApplicationUsages(ApplicationStatisticsPersistenceComponent.getInstance()));
  }

  @NotNull
  @Deprecated
  // this method should be overridden only in exceptional cases.
  // you have summarized usages from all opened/closed projects here.
  // do you want to add/merge something? Don't do it!!!
  protected Set<UsageDescriptor> mergeUsagesPostProcess(@NotNull Set<UsageDescriptor> usagesFromAllProjects) {
    return usagesFromAllProjects;
  }

  @NotNull
  private Set<UsageDescriptor> getApplicationUsages(@NotNull ApplicationStatisticsPersistence persistence) {
    ObjectIntHashMap<String> result = new ObjectIntHashMap<>();
    long lastTimeSent = UsageStatisticsPersistenceComponent.getInstance().getLastTimeSent();
    for (CollectedUsages usageDescriptors : persistence.getApplicationData(getGroupId()).values()) {
      if (!usageDescriptors.usages.isEmpty() && usageDescriptors.collectionTime > lastTimeSent) {
        result.ensureCapacity(usageDescriptors.usages.size());
        for (UsageDescriptor usageDescriptor : usageDescriptors.usages) {
          String key = usageDescriptor.getKey();
          result.put(key, result.get(key, 0) + usageDescriptor.getValue());
        }
      }
    }
    return StatisticsUtilKt.toUsageDescriptors(result);
  }

  @Override
  @NotNull
  public final Set<UsageDescriptor> getUsages() throws CollectUsagesException {
    return getApplicationUsages();
  }
}


text:
package org.apache.spark.sql.execution

import org.apache.hadoop.fs.Path

import org.apache.spark.SparkConf
import org.apache.spark.sql.QueryTest
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSQLContext

/**
 * Suite that tests the redaction of DataSourceScanExec
 */
class DataSourceScanExecRedactionSuite extends QueryTest with SharedSQLContext {

  override protected def sparkConf: SparkConf = super.sparkConf
    .set("spark.redaction.string.regex", "file:/[\\w_]+")

  test("treeString is redacted") {
    withTempDir { dir =>
      val basePath = dir.getCanonicalPath
      spark.range(0, 10).toDF("a").write.parquet(new Path(basePath, "foo=1").toString)
      val df = spark.read.parquet(basePath)

      val rootPath = df.queryExecution.sparkPlan.find(_.isInstanceOf[FileSourceScanExec]).get
        .asInstanceOf[FileSourceScanExec].relation.location.rootPaths.head
      assert(rootPath.toString.contains(dir.toURI.getPath.stripSuffix("/")))

      assert(!df.queryExecution.sparkPlan.treeString(verbose = true).contains(rootPath.getName))
      assert(!df.queryExecution.executedPlan.treeString(verbose = true).contains(rootPath.getName))
      assert(!df.queryExecution.toString.contains(rootPath.getName))
      assert(!df.queryExecution.simpleString.contains(rootPath.getName))

      val replacement = "*********"
      assert(df.queryExecution.sparkPlan.treeString(verbose = true).contains(replacement))
      assert(df.queryExecution.executedPlan.treeString(verbose = true).contains(replacement))
      assert(df.queryExecution.toString.contains(replacement))
      assert(df.queryExecution.simpleString.contains(replacement))
    }
  }

  private def isIncluded(queryExecution: QueryExecution, msg: String): Boolean = {
    queryExecution.toString.contains(msg) ||
    queryExecution.simpleString.contains(msg) ||
    queryExecution.stringWithStats.contains(msg)
  }

  test("explain is redacted using SQLConf") {
    withTempDir { dir =>
      val basePath = dir.getCanonicalPath
      spark.range(0, 10).toDF("a").write.parquet(new Path(basePath, "foo=1").toString)
      val df = spark.read.parquet(basePath)
      val replacement = "*********"

      // Respect SparkConf and replace file:/
      assert(isIncluded(df.queryExecution, replacement))

      assert(isIncluded(df.queryExecution, "FileScan"))
      assert(!isIncluded(df.queryExecution, "file:/"))

      withSQLConf(SQLConf.SQL_STRING_REDACTION_PATTERN.key -> "(?i)FileScan") {
        // Respect SQLConf and replace FileScan
        assert(isIncluded(df.queryExecution, replacement))

        assert(!isIncluded(df.queryExecution, "FileScan"))
        assert(isIncluded(df.queryExecution, "file:/"))
      }
    }
  }

  test("FileSourceScanExec metadata") {
    withTempPath { path =>
      val dir = path.getCanonicalPath
      spark.range(0, 10).write.parquet(dir)
      val df = spark.read.parquet(dir)

      assert(isIncluded(df.queryExecution, "Format"))
      assert(isIncluded(df.queryExecution, "ReadSchema"))
      assert(isIncluded(df.queryExecution, "Batched"))
      assert(isIncluded(df.queryExecution, "PartitionFilters"))
      assert(isIncluded(df.queryExecution, "PushedFilters"))
      assert(isIncluded(df.queryExecution, "DataFilters"))
      assert(isIncluded(df.queryExecution, "Location"))
    }
  }

}


text:
<?php
namespace TYPO3\CMS\Fluid\Core\Parser\SyntaxTree;

/*                                                                        *
 * This script is backported from the TYPO3 Flow package "TYPO3.Fluid".   *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 *  of the License, or (at your option) any later version.                *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * A node which is used inside boolean arguments
 */
class BooleanNode extends \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
{
    /**
     * List of comparators which are supported in the boolean expression language.
     *
     * Make sure that if one string is contained in one another, the longer
     * string is listed BEFORE the shorter one.
     * Example: put ">=" before ">"
     *
     * @var array
     */
    protected static $comparators = ['==', '!=', '%', '>=', '>', '<=', '<'];

    /**
     * A regular expression which checks the text nodes of a boolean expression.
     * Used to define how the regular expression language should look like.
     *
     * @var string
     */
    protected static $booleanExpressionTextNodeCheckerRegularExpression = '/
		^                 # Start with first input symbol
		(?:               # start repeat
			COMPARATORS   # We allow all comparators
			|\s*          # Arbitary spaces
			|-?           # Numbers, possibly with the "minus" symbol in front.
				[0-9]+    # some digits
				(?:       # and optionally a dot, followed by some more digits
					\\.
					[0-9]+
				)?
			|\'[^\'\\\\]* # single quoted string literals with possibly escaped single quotes
				(?:
					\\\\.      # escaped character
					[^\'\\\\]* # unrolled loop following Jeffrey E.F. Friedl
				)*\'
			|"[^"\\\\]*   # double quoted string literals with possibly escaped double quotes
				(?:
					\\\\.     # escaped character
					[^"\\\\]* # unrolled loop following Jeffrey E.F. Friedl
				)*"
		)*
		$/x';

    /**
     * Left side of the comparison
     *
     * @var \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     */
    protected $leftSide;

    /**
     * Right side of the comparison
     *
     * @var \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     */
    protected $rightSide;

    /**
     * The comparator. One element of self::$comparators. If NULL,
     * no comparator was found, and self::$syntaxTreeNode should
     * instead be evaluated.
     *
     * @var string
     */
    protected $comparator;

    /**
     * If no comparator was found, the syntax tree node should be
     * converted to boolean.
     *
     * @var \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     */
    protected $syntaxTreeNode;

    /**
     * Constructor. Parses the syntax tree node and fills $this->leftSide, $this->rightSide,
     * $this->comparator and $this->syntaxTreeNode.
     *
     * @param \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode $syntaxTreeNode
     * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
     */
    public function __construct(\TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode $syntaxTreeNode)
    {
        $childNodes = $syntaxTreeNode->getChildNodes();
        if (count($childNodes) > 3) {
            throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('A boolean expression has more than three parts.', 1244201848);
        } elseif (count($childNodes) === 0) {
            // In this case, we do not have child nodes; i.e. the current SyntaxTreeNode
            // is a text node with a literal comparison like "1 == 1"
            $childNodes = [$syntaxTreeNode];
        }

        $this->leftSide = new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\RootNode();
        $this->rightSide = new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\RootNode();
        $this->comparator = null;
        foreach ($childNodes as $childNode) {
            if ($childNode instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\TextNode && !preg_match(str_replace('COMPARATORS', implode('|', self::$comparators), self::$booleanExpressionTextNodeCheckerRegularExpression), $childNode->getText())) {
                // $childNode is text node, and no comparator found.
                $this->comparator = null;
                // skip loop and fall back to classical to boolean conversion.
                break;
            }

            if ($this->comparator !== null) {
                // comparator already set, we are evaluating the right side of the comparator
                $this->rightSide->addChildNode($childNode);
            } elseif ($childNode instanceof \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\TextNode
                && ($this->comparator = $this->getComparatorFromString($childNode->getText()))) {
                // comparator in current string segment
                $explodedString = explode($this->comparator, $childNode->getText());
                if (isset($explodedString[0]) && trim($explodedString[0]) !== '') {
                    $value = trim($explodedString[0]);
                    if (is_numeric($value)) {
                        $this->leftSide->addChildNode(new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NumericNode($value));
                    } else {
                        $this->leftSide->addChildNode(new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\TextNode(preg_replace('/(^[\'"]|[\'"]$)/', '', $value)));
                    }
                }
                if (isset($explodedString[1]) && trim($explodedString[1]) !== '') {
                    $value = trim($explodedString[1]);
                    if (is_numeric($value)) {
                        $this->rightSide->addChildNode(new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\NumericNode($value));
                    } else {
                        $this->rightSide->addChildNode(new \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\TextNode(preg_replace('/(^[\'"]|[\'"]$)/', '', $value)));
                    }
                }
            } else {
                // comparator not found yet, on the left side of the comparator
                $this->leftSide->addChildNode($childNode);
            }
        }

        if ($this->comparator === null) {
            // No Comparator found, we need to evaluate the given syntax tree node manually
            $this->syntaxTreeNode = $syntaxTreeNode;
        }
    }

    /**
     * @return string
     * @internal
     */
    public function getComparator()
    {
        return $this->comparator;
    }

    /**
     * @return \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     * @internal
     */
    public function getSyntaxTreeNode()
    {
        return $this->syntaxTreeNode;
    }

    /**
     * @return \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     * @internal
     */
    public function getLeftSide()
    {
        return $this->leftSide;
    }

    /**
     * @return \TYPO3\CMS\Fluid\Core\Parser\SyntaxTree\AbstractNode
     * @internal
     */
    public function getRightSide()
    {
        return $this->rightSide;
    }

    /**
     * @param \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext
     * @return bool the boolean value
     */
    public function evaluate(\TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext)
    {
        if ($this->comparator !== null) {
            return self::evaluateComparator($this->comparator, $this->leftSide->evaluate($renderingContext), $this->rightSide->evaluate($renderingContext));
        } else {
            $value = $this->syntaxTreeNode->evaluate($renderingContext);
            return self::convertToBoolean($value);
        }
    }

    /**
     * Do the actual comparison. Compares $leftSide and $rightSide with $comparator and emits a boolean value.
     *
     * Some special rules apply:
     * - The == and != operators are comparing the Object Identity using === and !==, when one of the two
     *   operands are objects.
     * - For arithmetic comparisons (%, >, >=, <, <=), some special rules apply:
     *   - arrays are only comparable with arrays, else the comparison yields FALSE
     *   - objects are only comparable with objects, else the comparison yields FALSE
     *   - the comparison is FALSE when two types are not comparable according to the table
     *     "Comparison with various types" on http://php.net/manual/en/language.operators.comparison.php
     *
     * This function must be static public, as it is also directly called from cached templates.
     *
     * @param string $comparator
     * @param mixed $evaluatedLeftSide
     * @param mixed $evaluatedRightSide
     * @return bool TRUE if comparison of left and right side using the comparator emit TRUE, false otherwise
     * @throws \TYPO3\CMS\Fluid\Core\Parser\Exception
     */
    public static function evaluateComparator($comparator, $evaluatedLeftSide, $evaluatedRightSide)
    {
        switch ($comparator) {
            case '==':
                if (is_object($evaluatedLeftSide) || is_object($evaluatedRightSide)) {
                    return $evaluatedLeftSide === $evaluatedRightSide;
                } else {
                    return $evaluatedLeftSide == $evaluatedRightSide;
                }
            case '!=':
                if (is_object($evaluatedLeftSide) || is_object($evaluatedRightSide)) {
                    return $evaluatedLeftSide !== $evaluatedRightSide;
                } else {
                    return $evaluatedLeftSide != $evaluatedRightSide;
                }
            case '%':
                if (!self::isComparable($evaluatedLeftSide, $evaluatedRightSide)) {
                    return false;
                }
                return (bool)((int)$evaluatedLeftSide % (int)$evaluatedRightSide);
            case '>':
                if (!self::isComparable($evaluatedLeftSide, $evaluatedRightSide)) {
                    return false;
                }
                return $evaluatedLeftSide > $evaluatedRightSide;
            case '>=':
                if (!self::isComparable($evaluatedLeftSide, $evaluatedRightSide)) {
                    return false;
                }
                return $evaluatedLeftSide >= $evaluatedRightSide;
            case '<':
                if (!self::isComparable($evaluatedLeftSide, $evaluatedRightSide)) {
                    return false;
                }
                return $evaluatedLeftSide < $evaluatedRightSide;
            case '<=':
                if (!self::isComparable($evaluatedLeftSide, $evaluatedRightSide)) {
                    return false;
                }
                return $evaluatedLeftSide <= $evaluatedRightSide;
            default:
                throw new \TYPO3\CMS\Fluid\Core\Parser\Exception('Comparator "' . $comparator . '" is not implemented.', 1244234398);
        }
    }

    /**
     * Checks whether two operands are comparable (based on their types). This implements
     * the "Comparison with various types" table from http://php.net/manual/en/language.operators.comparison.php,
     * only leaving out "array" with "anything" and "object" with anything; as we specify
     * that arrays and objects are incomparable with anything else than their type.
     *
     * @param mixed $evaluatedLeftSide
     * @param mixed $evaluatedRightSide
     * @return bool TRUE if the operands can be compared using arithmetic operators, FALSE otherwise.
     */
    protected static function isComparable($evaluatedLeftSide, $evaluatedRightSide)
    {
        if ((is_null($evaluatedLeftSide) || is_string($evaluatedLeftSide))
            && is_string($evaluatedRightSide)) {
            return true;
        }
        if (is_bool($evaluatedLeftSide) || is_null($evaluatedLeftSide)) {
            return true;
        }
        if (is_object($evaluatedLeftSide) && is_object($evaluatedRightSide)) {
            return true;
        }
        if ((is_string($evaluatedLeftSide) || is_resource($evaluatedLeftSide) || is_numeric($evaluatedLeftSide))
            && (is_string($evaluatedRightSide) || is_resource($evaluatedRightSide) || is_numeric($evaluatedRightSide))) {
            return true;
        }
        if (is_array($evaluatedLeftSide) && is_array($evaluatedRightSide)) {
            return true;
        }
        return false;
    }

    /**
     * Determine if there is a comparator inside $string, and if yes, returns it.
     *
     * @param string $string string to check for a comparator inside
     * @return string The comparator or NULL if none found.
     */
    protected function getComparatorFromString($string)
    {
        foreach (self::$comparators as $comparator) {
            if (strpos($string, $comparator) !== false) {
                return $comparator;
            }
        }
        return null;
    }

    /**
     * Convert argument strings to their equivalents. Needed to handle strings with a boolean meaning.
     *
     * Must be public and static as it is used from inside cached templates.
     *
     * @param mixed $value Value to be converted to boolean
     * @return bool
     */
    public static function convertToBoolean($value)
    {
        if (is_bool($value)) {
            return $value;
        }

        if (is_int($value) || is_float($value)) {
            return !empty($value);
        }

        if (is_numeric($value)) {
            return $value != 0;
        }

        if (is_string($value)) {
            return !empty($value) && strtolower($value) !== 'false';
        }
        if (is_array($value) || (is_object($value) && $value instanceof \Countable)) {
            return (bool)count($value);
        }
        if (is_object($value)) {
            return true;
        }

        return false;
    }
}


text:
module Distribution.Simple.Program.Strip (stripLib, stripExe)
       where

import Prelude ()
import Distribution.Compat.Prelude

import Distribution.Simple.Program
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Verbosity
import Distribution.Version

import System.FilePath             (takeBaseName)

runStrip :: Verbosity -> ProgramDb -> FilePath -> [String] -> IO ()
runStrip verbosity progDb path args =
  case lookupProgram stripProgram progDb of
    Just strip -> runProgram verbosity strip (path:args)
    Nothing    -> unless (buildOS == Windows) $
                  -- Don't bother warning on windows, we don't expect them to
                  -- have the strip program anyway.
                  warn verbosity $ "Unable to strip executable or library '"
                                   ++ (takeBaseName path)
                                   ++ "' (missing the 'strip' program)"

stripExe :: Verbosity -> Platform -> ProgramDb -> FilePath -> IO ()
stripExe verbosity (Platform _arch os) progdb path =
  runStrip verbosity progdb path args
  where
    args = case os of
       OSX -> ["-x"] -- By default, stripping the ghc binary on at least
                     -- some OS X installations causes:
                     --     HSbase-3.0.o: unknown symbol `_environ'"
                     -- The -x flag fixes that.
       _   -> []

stripLib :: Verbosity -> Platform -> ProgramDb -> FilePath -> IO ()
stripLib verbosity (Platform arch os) progdb path = do
  case os of
    OSX -> -- '--strip-unneeded' is not supported on OS X, iOS, AIX, or
           -- Solaris. See #1630.
           return ()
    IOS -> return ()
    AIX -> return ()
    Solaris -> return ()
    Windows -> -- Stripping triggers a bug in 'strip.exe' for
               -- libraries with lots identically named modules. See
               -- #1784.
               return()
    Linux | arch == I386 ->
      -- Versions of 'strip' on 32-bit Linux older than 2.18 are
      -- broken. See #2339.
      let okVersion = orLaterVersion (Version [2,18] [])
      in case programVersion =<< lookupProgram stripProgram progdb of
          Just v | withinRange v okVersion ->
            runStrip verbosity progdb path args
          _ -> warn verbosity $ "Unable to strip library '"
                                ++ (takeBaseName path)
                                ++ "' (version of 'strip' too old; "
                                ++ "requires >= 2.18 on 32-bit Linux)"
    _   -> runStrip verbosity progdb path args
  where
    args = ["--strip-unneeded"]


text:
@implementation EEEBeacon

- (void)fire
{
    [self.delegate beaconDidFire:self];
}

@end


text:
using System;

namespace Whitelog.Core.Configuration.Fluent.StringLayout
{
    public class StringOutputer : IStringOutputer
    {
        private IStringLayoutBuilder m_layoutBuilder;
        private Action<IStringAppenderBuilder> m_addLogger;
        private ExecutionMode m_executionMode;

        public StringOutputer(IStringLayoutBuilder layoutBuilder,Action<IStringAppenderBuilder> addLogger,ExecutionMode executionMode)
        {
            m_executionMode = executionMode;
            m_addLogger = addLogger;
            m_layoutBuilder = layoutBuilder;
        }

        public ExecutionMode ExecutionMode { get { return m_executionMode; } }
        IStringLayoutBuilder IStringOutputer.Source { get { return m_layoutBuilder; } }

        public void AddLogger(IStringAppenderBuilder logger)
        {
            m_addLogger.Invoke(logger);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Ilwis-Objects: Ilwis::DomainMerger Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Ilwis-Objects
    1.0

GIS and Remote Sensing framework for data access and processing

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Enumerations Pages

Ilwis

DomainMerger

Public Member Functions |
Protected Attributes |
List of all members

Ilwis::DomainMerger Class Referenceabstract

#include <domainmerger.h>

Inheritance diagram for Ilwis::DomainMerger:

  <map id="Ilwis::DomainMerger_map" name="Ilwis::DomainMerger_map">
<area href="class_ilwis_1_1_item_domain_merger_indexed_items.html" alt="Ilwis::ItemDomainMergerIndexedItems" shape="rect" coords="0,56,220,80"/>
<area href="class_ilwis_1_1_item_domain_merger_named_items.html" alt="Ilwis::ItemDomainMergerNamedItems" shape="rect" coords="230,56,450,80"/>
<area href="class_ilwis_1_1_numeric_domain_merger.html" alt="Ilwis::NumericDomainMerger" shape="rect" coords="460,56,680,80"/>
</map>

Public Member Functions

 	DomainMerger ()

 	DomainMerger (const IDomain &dom1, const IDomain &dom2)

IDomain 	mergeDomains (const IDomain &dom1, const IDomain &dom2)

std::map< quint32, quint32 > 	renumberer () const

virtual bool 	merge ()=0

IDomain 	mergedDomain () const

Protected Attributes

IDomain 	_domain1

IDomain 	_domain2

IDomain 	_mergedDomain

std::map< quint32, quint32 > 	_renumber

Detailed Description

The DomainMerger class merges domains, when possible

Constructor & Destructor Documentation

          DomainMerger::DomainMerger
          (
          	)

Constructor for an empty DomainMerger

          DomainMerger::DomainMerger
          (
          const IDomain &
          dom1,

          const IDomain &
          dom2

          )

Creates a DomainMerger from 2 IDomain 's

 Does not yet do the actual merging

 the domains may not be null

Parameters

dom1	an IDomain you want merged

dom2	an IDomain you want merged

Member Function Documentation

          virtual bool Ilwis::DomainMerger::merge
          (
          	)

pure virtual

merges the 2 domains, which have been specified in the constructor

 requires the 2 domains to be compatible. the actual merging details are in the relevant subclasses

Returns

true when the merging was succesfull

          IDomain DomainMerger::mergedDomain
          (
          	)
           const

Query for the merged domain in this DomainMerger

 based on the 2 domains specified in the constructor

 only works after the domains have been merged, if the domains have not yet been merged this will return null

Returns

the result of the merging

          IDomain DomainMerger::mergeDomains
          (
          const IDomain &
          dom1,

          const IDomain &
          dom2

          )

Merges the domains and returns the result

 for a merge to work the domains must be valid and must have the same valuetypes

the merged domain will be saved in this domainmerger

 which means if you want to acces an already merged domain again you should use mergedDomain() instead of this

Parameters

dom1	first domain to be merged

dom2	second domain to be merged

Returns

the result of the merge, can be null if the domains are not compatible

          std::map< quint32, quint32 > DomainMerger::renumberer
          (
          	)
           const

Query for the renumberer

 the renumberer is the map that is used to renumber the elements in the 2 soon to be merged domains

Returns

the renumberer (a map<quint32,quint32>)

The documentation for this class was generated from the following files:

ilwisobjects/domain/domainmerger.h

ilwisobjects/domain/domainmerger.cpp

<address class="footer">
Generated on Fri Mar 28 2014 13:51:04 for Ilwis-Objects by

 1.8.3.1
</address>


text:
/**
 * @fileoverview Extern definitions for types missing in the Closure externs,
 * but used in TypeScript platform `.d.ts`.
 * @externs
 */

/** @typedef {!IArrayLike} */
var ArrayLike;

/** @typedef {!HTMLCollection} */
var HTMLCollectionOf;

/** @typedef {!HTMLTableCellElement} */
var HTMLTableDataCellElement;

/**
 * Does not have an equivalent in Closure's externs.
 * @typedef {!HTMLTableCellElement}
 */
var HTMLTableHeaderCellElement;

/**
 * Closure's NodeList is parameterized itself, there is no NodeListOf.
 * @typedef {!NodeList}
 */
var NodeListOf;

/**
 * Closure models this as a plain Array.
 * @typedef {Array<string>|null}
 */
var RegExpExecArray;


text:
package io.apiman.gateway.engine.impl;

import io.apiman.gateway.engine.async.AsyncResultImpl;
import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.components.ISharedStateComponent;

import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

/**
 * An in-memory only implementation of the shared state component.  This
 * implementation is generally used for testing and embedded situations.
 * It does not work in a cluster and is not persistent across server
 * restarts.
 *
 * @author eric.wittmann@redhat.com
 */
public class InMemorySharedStateComponent implements ISharedStateComponent {

    private Map<QName, Object> sharedState = new HashMap<>();

    /**
     * Constructor.
     */
    public InMemorySharedStateComponent() {
    }

    /**
     * @see io.apiman.gateway.engine.components.ISharedStateComponent#getProperty(java.lang.String, java.lang.String, java.lang.Object, io.apiman.gateway.engine.async.IAsyncResultHandler)
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> void getProperty(String namespace, String propertyName, T defaultValue,
            IAsyncResultHandler<T> handler) {
        T value = null;
        synchronized (sharedState) {
            QName key = new QName(namespace, propertyName);
            value = (T) sharedState.get(key);
        }
        if (value == null) {
            value = defaultValue;
        }
        handler.handle(AsyncResultImpl.create(value));
    }

    /**
     * @see io.apiman.gateway.engine.components.ISharedStateComponent#setProperty(java.lang.String, java.lang.String, java.lang.Object, io.apiman.gateway.engine.async.IAsyncResultHandler)
     */
    @Override
    public <T> void setProperty(String namespace, String propertyName, T value, IAsyncResultHandler<Void> handler) {
        QName key = new QName(namespace, propertyName);
        synchronized (sharedState) {
            sharedState.put(key, value);
        }
        handler.handle(AsyncResultImpl.create((Void) null));
    }

    /**
     * @see io.apiman.gateway.engine.components.ISharedStateComponent#clearProperty(java.lang.String, java.lang.String, io.apiman.gateway.engine.async.IAsyncResultHandler)
     */
    @Override
    public <T> void clearProperty(String namespace, String propertyName, IAsyncResultHandler<Void> handler) {
        QName key = new QName(namespace, propertyName);
        synchronized (sharedState) {
            sharedState.remove(key);
        }
        handler.handle(AsyncResultImpl.create((Void) null));
    }

}


text:
from __future__ import absolute_import, division, print_function

# Import standard modules
from abc import ABCMeta, abstractmethod, abstractproperty

# Import the relevant PTS classes and modules
from ..basics.configurable import OldConfigurable
from ..tools.logging import log

# -----------------------------------------------------------------

class Plotter(OldConfigurable):

    """
    This class ...
    """

    __metaclass__ = ABCMeta

    # -----------------------------------------------------------------

    def __init__(self):

        """
        The constructor ...
        :return:
        """

        # Call the constructor of the base class
        super(Plotter, self).__init__(None, "core")

        # -- Attributes --

        # The table containing the input data
        self.table = None

        # The data structure to contain the input information in plottable format
        self.data = []

        # The path to the output directory
        self.output_path = None

    # -----------------------------------------------------------------

    @staticmethod
    @abstractproperty
    def default_input():

        """
        This function ...
        :return:
        """

        return ""

    # -----------------------------------------------------------------

    def run(self, table, output_path):

        """
        This function should be called to invoke the plotting routine ...
        :param table:
        :param output_path:
        :return:
        """

        # 1. Call the setup function
        self.setup(table, output_path)

        # 2. Prepare the input data into plottable format
        self.prepare_data()

        # 3. Create the plots
        self.plot()

    # -----------------------------------------------------------------

    def setup(self, table, output_path):

        """
        This function ...
        :param table:
        :param output_path:
        :return:
        """

        # Call the setup of the base class
        super(Plotter, self).setup()

        # Inform the user
        log.info("Reading input data...")

        # Set the input table
        self.table = table

        # Set the path to the output directory
        self.output_path = output_path

    # -----------------------------------------------------------------

    @abstractmethod
    def prepare_data(self):

        """
        This function ...
        :return:
        """

        return

    # -----------------------------------------------------------------

    @abstractmethod
    def plot(self):

        """
        This function ...
        :param path:
        :return:
        """

        return

# -----------------------------------------------------------------


text:
package agent

import (
	"errors"
	"net"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"github.com/doubledutch/quantum"
	"github.com/doubledutch/quantum/inmemory"
)

var (
	// ErrUnexpectedError describes the error when a job panics
	ErrUnexpectedError = errors.New("Job exited with unexpected error")
)

// Config encapsulates configuration for an agent
type Config struct {
	*quantum.ConnConfig

	Port string

	Registry    quantum.Registry
	Registrator quantum.Registrator
}

// Agent routes job requests to jobs, and runs the jobs with the request
type Agent struct {
	*quantum.ConnConfig

	port  string
	done  chan struct{}
	sigCh chan os.Signal

	quantum.Registry
	registrator quantum.Registrator
}

// New creates a new Agent with the specified port
func New(config *Config) quantum.Agent {
	if config == nil {
		config = new(Config)
	}

	if config.ConnConfig == nil {
		config.ConnConfig = quantum.DefaultConnConfig()
	}

	if config.Registry == nil {
		config.Registry = inmemory.NewRegistry(config.Lager)
	}

	if config.Registrator == nil {
		config.Registrator = inmemory.NewRegistrator()
	}

	if config.Timeout == 0 {
		config.Timeout = 100 * time.Millisecond
	}

	return &Agent{
		ConnConfig: config.ConnConfig,

		Registry:    config.Registry,
		registrator: config.Registrator,

		port:  config.Port,
		done:  make(chan struct{}),
		sigCh: make(chan os.Signal, 1),
	}
}

// Accept accepts on a specified net.Listener
func (a *Agent) Accept(ln net.Listener) error {
	netConn, err := ln.Accept()
	if err != nil {
		return err
	}

	conn, err := NewConn(netConn, a.ConnConfig)
	if err != nil {
		a.Lager.Errorf("Error creating agent conn: %s", err)
		return err
	}

	go conn.Serve(a)
	return nil
}

// IsShutdown returns a chan that determines whether we're shutdown
func (a *Agent) IsShutdown() chan struct{} {
	return a.done
}

// Close shutdowns an agent
func (a *Agent) Close() error {
	// Deregister services
	return a.registrator.Deregister()
}

// Start starts the agent by setting up the signal listener and listening on port.
func (a *Agent) Start() error {
	// Listen for signals, wire up done

	signal.Notify(a.sigCh,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT,
		syscall.SIGKILL)
	defer close(a.sigCh)

	// TODO: We should also notify any running jobs
	// Or, we can start a goroutine to update each connection when this happens?
	go func() {
		sig := <-a.sigCh
		// If sig is nil, channel was closed
		if sig != nil {
			close(a.done)
		}
	}()

	a.Lager.Debugf("Registering")
	if err := a.registrator.Register(NewPort(a.port).Int(), a); err != nil {
		a.Lager.Errorf("Failed to announce services: %s\n", err)
		return err
	}

	// Blocks
	a.Lager.Debugf("ListenAndServe block")
	return quantum.ListenAndServe(a, a.port, a.Lager)
}

// Port holds a port in the form :XXXX
type Port struct {
	Value string
}

// NewPort returns a Port
func NewPort(s string) Port {
	return Port{Value: s}
}

// Int returns a int representation of Port
func (p Port) Int() int {
	number := p.Value[1:] // ignore : at [0]

	i, err := strconv.Atoi(number)
	if err != nil {
		return -1
	}
	return i
}


text:
perlex
======

Perl Exercises


text:
var ComputeRequest = require("../../../xflow/interface/request.js").ComputeRequest;
var GL = require("../../webgl/constants.js");
var Configuration = require("../../renderer/scene/configuration.js");
var ConfigurableGLStates = require("../render-interface.js").ConfigurableGLStates;

var configurableGLStates = [];
for (var i = 0; i < ConfigurableGLStates.length; i++) {
    configurableGLStates.push("gl-" + ConfigurableGLStates[i]);
}

/**
 * A configuration connects a model (material, light, camera) with a data node containing
 * the parameters for the model
 * The Configuration is immutable
 * The GLConfiguration class also contains gl state entries that are specific to WebGL
 *
 * @param model The model (e.g. identified by an URN)
 * @param {Xflow.DataNode} dataNode  The parameters of this model instance
 * @param {{}} opt
 * @constructor
 */
var GLConfiguration = function(model, dataNode, opt) {
    Configuration.call(this, model, dataNode, opt);

    /**
     * Contains the WebGL state overrides that this material requests.
     * @type {{}}
     */
    this.states = {};

    createStateRequest(this);
};

function createStateRequest(conf) {
    var request = new ComputeRequest(conf.dataNode, configurableGLStates, updateStates.bind(window, conf));
    updateStates(conf, request);
}

function updateStates(conf, request, data) {
    var state = {};
    var result = request.getResult();
    var stateNames = result.outputNames;
    for (var i=0; i < stateNames.length; i++) {
        var name = stateNames[i];
        name = name.substr(3, name.length);
        var vals = result.getOutputData(stateNames[i]).getValue();
        if (vals.length == 1) {
            vals = vals[0].split(" ");
        }
        var parsed = parseGLValues(vals);
        if (parsed) {
            state[name] = parsed;
        } else {
            XML3D.debug.logError("The arguments '"+vals+"' for 'gl-"+name+"' in material '#"+conf.name+"' are not valid.");
        }
    }
    conf.states = state;
}

function parseGLValues(vals) {
    var parsed = [];
    for (var j=0; j<vals.length; j++) {
        var val = vals[j];
        if (GL[val] !== undefined) {
            parsed.push(GL[val]);
        } else if (typeof val == typeof "") {
            if (GL[val.toUpperCase()]) {
                parsed.push(GL[val.toUpperCase()]);
            } else if (val.toLowerCase() == "true") {
                parsed.push(true);
            } else if (val.toLowerCase() == "false") {
                parsed.push(false);
            } else if (!isNaN(+val)) {
                parsed.push(+val);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    return parsed;
}

module.exports = GLConfiguration;


text:
'use strict';

const webpack = require('webpack');

module.exports = new webpack.DefinePlugin({
    'process.env': {
        'NODE_ENV': JSON.stringify('development')
    }
});


text:
package lincs_gse92742_v0

import (
	"strings"

	"github.com/jtolds/golincs/mmm"
	"github.com/jtolds/golincs/web/dbs"
)

func (ds *Dataset) search(h *mmm.Handle, keyword string,
	filter dbs.SampleFilter, offset, limit int, tags bool) (rv []scoredSample,
	err error) {
	rows, err := ds.tx.Query(
		"SELECT s.id FROM signatures s, sig sig WHERE s.sig_id = sig.sig_id AND "+
			"instr(lower(sig.pert_iname), ?)", strings.ToLower(keyword))
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	skipped := 0
	for rows.Next() {
		var mmm_id mmm.Ident
		err = rows.Scan(&mmm_id)
		if err != nil {
			return nil, err
		}

		s, found, err := ds.load(h, mmm_id, tags)
		if err != nil {
			return nil, err
		}
		if !found {
			continue
		}

		if filter != nil && !filter(s) {
			continue
		}

		if skipped < offset {
			skipped++
			continue
		}

		rv = append(rv, scoredSample{idx: -1, score: 0, Sample: s})
		if len(rv) >= limit {
			return rv, nil
		}
	}

	return rv, nil
}

func (ds *Dataset) SearchGeneSigs(keyword string, offset, limit int) (
	[]dbs.ScoredGeneSig, error) {
	rv, err := ds.search(ds.genesigs, keyword, nil, offset, limit, false)
	return scoredSamplesToScoredGeneSigs(rv), err
}

func (ds *Dataset) SearchSamples(keyword string, filter dbs.SampleFilter,
	offset, limit int) ([]dbs.ScoredSample, error) {
	rv, err := ds.search(ds.samples, keyword, filter, offset, limit, true)
	return scoredSamplesToScoredSamples(rv), err
}


text:
package eu.sdi4apps.openapi.servlets;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import eu.sdi4apps.routing.types.NodeResponse;
import eu.sdi4apps.routing.types.RoutingOperations;
import eu.sdi4apps.openapi.types.Response;
import eu.sdi4apps.openapi.utils.Cors;
import eu.sdi4apps.routing.RouteCalculator;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author runarbe
 */
@WebServlet(name = "routing", urlPatterns = {"/routing"})
public class Routing extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param hReq servlet request
     * @param hResp servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest hReq, HttpServletResponse hResp)
            throws ServletException, IOException, SQLException, ClassNotFoundException {

        hResp = Cors.EnableCors(hResp);

        PrintWriter out = hResp.getWriter();

        Response r = Response.Error(null);

        try {

            String action = hReq.getParameter("action");

            switch (action) {
                case RoutingOperations.NEARESTNODE:
                    double lat = Double.parseDouble(hReq.getParameter("lat"));
                    double lon = Double.parseDouble(hReq.getParameter("lon"));
                    int radius = Integer.parseInt(hReq.getParameter("radius"));
                    r = RouteCalculator.GetNodeByLonLat(lon, lat, radius);
                    break;
                case RoutingOperations.SHORTESTPATH:
                    int from = Integer.parseInt(hReq.getParameter("from"));
                    int to = Integer.parseInt(hReq.getParameter("to"));
                    r = RouteCalculator.GetShortestRoute(from, to);
                    break;
                case RoutingOperations.OPTIMALROUTE:
                    r = RouteCalculator.GetOptimalRoute(hReq);
                    break;
                case RoutingOperations.REACHABLEAREA:
                    r = RouteCalculator.GetReachableArea(hReq);
                    break;
                default:
                    r.unsupportedAction(action);
                    break;
            }
        } catch (Exception e) {
            r.addMessage(e.toString());
        } finally {
            out.println(r.asJson());
            out.close();
        }

    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
            Logger.getLogger(Routing.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Routing.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
            Logger.getLogger(Routing.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Routing.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
Minimal example to create a function webshop for small stores like a local pizza shop.

## Installation

All dependencies of python are in requirements.txt. The easiest is to add them to a virtualenv

        virtualenv p
        source p/bin/activate
        pip install -r requirements.txt

All security related must be defined in a file or at command line. Please note, to run it behind a firewall [ngrok](http://ngrok.com) or similar is needed. In this example you should change that to your session.

        mcash_secret = '...'
        mcash_token = '...'
        mcash_user = '...'
        mcash_merchant = '...'
        mcash_endpoint = 'https://mcashtestbed.appspot.com/merchant/v1/'
        mcash_callback_uri = 'https://438e7e13.ngrok.com'

To run the code all you need is to specify the config

        ./src/webapp.py --config=local.config

## Try it out

I used curl to test. The first step is to get the product list. In this example lagano is our pizzeria.

        curl -D - http://localhost:8888/api/products/lagano/
            {"pizzas": [{"price": 45, "id": 1, "name": "Pizza lagano"}, {"price": 50, "id": 2, "name": "Pizza vegan"}, {"price": 55, "id": 3, "name": "Pizza of the house"}], "toppings": [{"price": 1, "id": 1, "name": "garlic"}, {"price": 5, "id": 2, "name": "extra cheese"}, {"price": 2, "id": 3, "name": "pepperoni"}], "sizes": [{"price": -5, "id": 28, "name": "28 cm"}, {"price": 0, "id": 32, "name": "32 cm"}, {"price": 5, "id": 36, "name": "36 cm"}]}

To place an order select a pizza and a size and add toppings if you like. POST it to get the order.

        echo '[{"id": 1, "size": 28}, {"id": 2, "size": 36, "toppings": [{"id": 1}, {"id": 2}]}]' > order

        curl -d @order -H 'Content-Type: application/vnd.api+json' -H 'Accept: application/vnd.api+json' http://localhost:8888/api/products/lagano/
            {"poll_uri": "https://18b290ee.ngrok.com/api/poll/7596db1185191baa87a983951ee5e764/", "qrcode_url": "https://api.mca.sh/shortlink/v1/qr_image/---0/7596db1185191baa87a983951ee5e764", "amount": 101, "id": "7596db1185191baa87a983951ee5e764"}

When placing an order the server returns the long poll URI to call, a QR code to display, final amount and an id. Use that to scan the code and authorize the payment.

Long poll returns to a POST with a JSON:

        {"result": true}


text:
// NOLINT(legal/copyright)
/******************************************************************************

    some description...

    libraries used:
        ~ slight_ButtonInput
            written by stefan krueger (s-light),
                git@s-light.eu, http://s-light.eu, https://github.com/s-light/
            license: MIT

    written by stefan krueger (s-light),
        git@s-light.eu, http://s-light.eu, https://github.com/s-light/

******************************************************************************/
/******************************************************************************
The MIT License (MIT)

Copyright (c) 2019 Stefan Krüger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

// include Core Arduino functionality
#include <Arduino.h>

#include <slight_ButtonInput.h>

// include own headerfile
// NOLINTNEXTLINE(build/include)
#include "./myinput.h"

// this polluts the global namespace..
// using namespace std::placeholders;  // for `_1`
// so we use std::placeholders::_1

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// functions

// MyInput::MyInput(Stream &out): out(out) {
MyInput::MyInput() {
    ready = false;
}

MyInput::~MyInput() {
    end();
}

void MyInput::begin(Stream &out) {
    // clean up..
    end();
    // start up...
    if (ready == false) {
        // setup
        out.println("MyInput begin:");

        pinMode(mybutton.pin, INPUT_PULLUP);
        mybutton.begin();
        mybutton.flag_filter_multi_click_events = true;

        out.println("done:");
        // enable
        ready = true;
    }
}

void MyInput::end() {
    if (ready) {
        // nothing to do..
    }
}

void MyInput::update() {
    if (ready) {
        mybutton.update();
        if (state != state_last) {
            state_last = state;
            Serial.println("State changed!");
        }
    }
}

// ------------------------------------------
// slight_ButtonInput things

boolean MyInput::mybutton_get_input(slight_ButtonInput *instance) {
    // read input + invert: button closes to GND.
    return !digitalRead((*instance).pin);
}

void MyInput::mybutton_event(slight_ButtonInput *instance) {
    Serial.print(F("instance:"));
    Serial.print((*instance).id);
    Serial.print(F(" - event: "));
    (*instance).printEventLast(Serial);
    Serial.println();

    // react on event
    switch ((*instance).getEventLast()) {
        case slight_ButtonInput::event_down : {
            // Serial.println(F("down"));
        } break;
        case slight_ButtonInput::event_holddown : {
            Serial.print(F("duration active: "));
            Serial.println((*instance).getDurationActive());
        } break;
        case slight_ButtonInput::event_up : {
            // Serial.println(F("up"));
        } break;
        case slight_ButtonInput::event_click : {
            // Serial.println(F("click"));
            state += 1;
        } break;
        case slight_ButtonInput::event_click_long : {
            Serial.print(F("click long "));
            Serial.println((*instance).getDurationActive());
        } break;
        case slight_ButtonInput::event_click_double : {
            // Serial.println(F("click double"));
        } break;
        case slight_ButtonInput::event_click_triple : {
            // Serial.println(F("click triple"));
        } break;
        case slight_ButtonInput::event_click_multi : {
            Serial.print(F("click multi - count: "));
            Serial.println((*instance).getClickCount());
        } break;
    }  // end switch
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// THE END
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


text:
    font-family: DejaVu Sans Mono, monospace;
    font-size: 13px;
    border: 1px solid #333;
    background-color: #000;
    padding: 4px;
    color: #fff;
}
#runtime_infos, #filesystem_panel {
    float: left;
    width: 250px;
    margin-bottom: 7px;
    margin-right: 7px;
    padding-bottom: 7px;
}
#log {
    height: 100px;
    width: 550px;
}
#serial {
    margin: 0px;
}
#serial:focus {
    outline: 1px solid rgb(229, 151, 0);
}
#screen {
    white-space: pre;
    position: relative;
    font-family: Liberation Mono, DejaVu Sans Mono, Courier New, monospace;
    font-weight: bold;
    font-size: 15px;
    line-height: normal;
}
#screen, #vga {
    border: 1px solid #555;
    border-width: 2px 1px;
    display: none;
    -webkit-transform-origin: top left;
    -moz-transform-origin: top left;
}
#vga {
    image-rendering: -moz-crisp-edges;
    image-rendering: -webkit-optimize-contrast;

    image-rendering: -o-crisp-edges;
    image-rendering: optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor;

    background-color: #000;
}
body {
    background-color: #111;
    color: #fff;
    line-height: 1.5;
    padding: 10px;
    font-family: sans-serif;
}
a {
    color: wheat;
}
.phone_keyboard {
    width: 0;
    height: 0;
    resize: none;
    border: 0;
    padding: 0;
}
h4 {
    margin: 0px 0px 20px 0px;
}
#start_emulation {
    padding: 6px 18px;
    font-size: 16px;
    font-weight: bold;
}
#setup_error {
    color: red;
    font-weight: bold;
    background-color: #222;
    padding: 8px 18px;
}
#config_link {
    font-weight: bold;
    background-color: #222;
    padding: 8px 18px;
}
#screen_container {
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
}
a img {
    margin: 10px;
}
.screenshots a {
    text-decoration: none;
}


text:
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { TranslateService } from '@ngx-translate/core';

import { ResumeService } from './resume.service';
import { MenuDirective } from './menu.directive';
import { ModalsComponent } from '../modals-component/modals.component';

// interface
interface DateLiteral {
    today?: string;
    month: string;
    months: string;
    year: string;
    years: string;
}

@Component({
    selector: 'my-resume',
    templateUrl: 'resume.component.html',
    styleUrls: ['resume.component.scss']
})

export class ResumeComponent implements OnInit, AfterViewInit {

    @ViewChild(MenuDirective) menu: MenuDirective;
    @ViewChild(ModalsComponent) modal: ModalsComponent;

    private subscription: Subscription;

    private datesLiterals: DateLiteral = {
        month: '',
        months: '',
        year: '',
        years: ''
    };

    private modalData: string;

    public dotsCollection: Object[];
    public cvData: any;
    public currentYear: number;

    public currentSection = '';

    public phoneDivOpened = false;

    constructor(private _resumeService: ResumeService, public _translate: TranslateService) {
        _translate.addLangs(['en', 'es']);
        _translate.setDefaultLang('en');

        const browserLang = _translate.getBrowserLang();
        _translate.use(browserLang.match(/en|es/) ? browserLang : 'en');

        this.subscription = this._resumeService.scrollEv$.subscribe(
            (section: string) => {
                this.currentSection = section;
            }
        );
    }

    getCurrentYear(): void {
        const currentDate = new Date();
        this.currentYear = currentDate.getFullYear();
    };

    private openAlertModal(size?: string): void {
        let modalData: Object;
        this._translate.get('loadingError').subscribe((literal: string) => {
            modalData = {
                type: 'danger',
                title: 'Error',
                bodyText: literal
            };
            this.modal.showAlertModal(modalData);
        });
    }

    getData(): void {
        this.modal.showLoadingModal();
        this._resumeService.getData().subscribe(
            data => {   // the first argument is a function which runs on success
                        this.cvData = data.data;

                        this._translate.get('dates').subscribe((literals: DateLiteral) => {
                            this.datesLiterals = literals;
                        });

                        this.modal.hideLoadingModal();
            },
            err => {    // the second argument is a function which runs on error
                        console.error(err);
                        this.modal.hideLoadingModal();
                        this.openAlertModal();

            },
            () => console.log('loading data: done')     // the third argument is a function which runs on completion
        );
    }

    changeLanguage(language: string): void {

        if (this._translate.currentLang === language) {
            return;
        }

        this._translate.use(language).subscribe(
            data => {
                this.getData();
            },
            err => {
                console.error(err);
            }
        );
    }

    showPhones(): void {
        this.phoneDivOpened = !this.phoneDivOpened;
    }

    onModalOutput(value): void {
        this.modalData = value;
    }

    changeSection(value: string): void {
        this.menu.changeSection(value);
    }

    toggleMobileMenu(): void {
        this.menu.toggleMobileMenu();
    }

    private getCookie(c_name: string) {
        let c_value = document.cookie;
        let c_start = c_value.indexOf(' ' + c_name + '=');
        let c_end;

        if (c_start === -1) {
            c_start = c_value.indexOf(c_name + '=');
        }
        if (c_start === -1) {
            c_value = null;
        } else {
            c_start = c_value.indexOf('=', c_start) + 1;
            c_end = c_value.indexOf(';', c_start);

            if (c_end === -1) {
                c_end = c_value.length;
            }
            c_value = decodeURI(c_value.substring(c_start, c_end));
        }
        return c_value;
    }

    private setCookie(c_name, value, exdays): void {
        const exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        const c_value = encodeURI(value) + ((exdays === null) ? '' : '; expires=' + exdate.toUTCString());
        document.cookie = c_name + '=' + c_value;
    }

    private showCookieAlert(): void {
        if (this.getCookie('mariogonzalezduarte-web-aviso-cookies') === '1') {
            jQuery('#warning-cookies').hide();
        }
    }

    acceptCookie(): void {
        this.setCookie('mariogonzalezduarte-web-aviso-cookies', '1', 365);
        jQuery('#warning-cookies').slideToggle('slow');
    }

    ngAfterViewInit() {
        this.getData();
    }

    ngOnInit() {
        this.showCookieAlert();
        this.getCurrentYear();
        this.dotsCollection = this._resumeService.getDotsCollection();
    }

    showFormContact(): void {
        this.modal.showModal('contactModal');
    }

    calculatePeriod(dateFrom: string, dateTo: string): string {
        let period = '',
            months = 0,
            years = 0,
            txtMonth = '',
            txtYear = '';

        const currentDate: Date = new Date(),
              currentDateFormated: string = currentDate.getDate() + '/' + (currentDate.getMonth() + 1) + '/' + currentDate.getFullYear(),
              dateF: any = dateFrom.split('/'),
              dateT: any = dateTo ? dateTo.split('/') : currentDateFormated.split('/'),
              fDate1: any = Date.UTC(dateF[2], dateF[1] - 1, dateF[0]),
              fDate2: any = Date.UTC(dateT[2], dateT[1] - 1, dateT[0]),
              dif: any = fDate2 - fDate1,
              days: number = Math.floor(dif / (1000 * 60 * 60 * 24));

        months = Math.ceil(days / 30);
        period = months > 1 ? '(' + months + ' LIT_MONTHS)' : '(' + months + ' LIT_MONTH)';

        if (months >= 12) {
            years = Math.floor(months / 12);

            if (months % 12 === 0) {
                period = years > 1 ? '(' + years + ' LIT_YEARS)' : '(' + years + ' LIT_YEAR)';
            } else {
                txtYear = years !== 1 ? ' LIT_YEARS' : ' LIT_YEAR';
                txtMonth = months % 12 !== 1 ? ' LIT_MONTHS' : ' LIT_MONTH';
                period = '(' + years + txtYear + ', ' + (months % 12) + txtMonth + ')';
            }
        }

        period = period.replace(/LIT_YEARS/,  this.datesLiterals.years)
                       .replace(/LIT_YEAR/,   this.datesLiterals.year)
                       .replace(/LIT_MONTHS/, this.datesLiterals.months)
                       .replace(/LIT_MONTH/,  this.datesLiterals.month);

        return period;
    }

}