text:
\documentclass[12pt]{article}
%\documentclass[12pt,preprint]{aastex}
%\usepackage{smsections}
\usepackage{graphicx}
\usepackage{amssymb}

\textwidth = 6.5 in
\textheight = 9 in
\oddsidemargin = 0.0 in
\evensidemargin = 0.0 in
\topmargin = -.3in
\headheight = 1ex
\headsep = 4ex
\parskip = 0.2in
\parindent = 0.0in
\title{Simple Lenses and Telescopes}
\begin{document}

\vspace*{-.8in}
\markright{\tiny \rm PS12000 W2009 V1.0}
\leftline{\tiny PS12000 W2009 V1.0}
\vspace{.5in}

\centerline{\large\bf Morphological types, spectra of galaxies,}
\centerline{\large\bf  and the Hubble expansion law.}
\vspace{.3in}

\begin{quote}
{\it "The history of astronomy is a history of receding horizons."}  --- Edwin Hubble
\end{quote}

\section{Introduction}
\pagestyle{myheadings}
\thispagestyle{plain}

In 1920s the University of Chicago alumnus Edwin Hubble\footnote{You can find detailed information
about life and work of Edwin Hubble on this website: {\tt http://www.time.com/time/time100/scientist/profile/hubble.html}} (Ph.D., 1917) solved four fundamental questions in astronomy and cosmology\footnote{See essay by Hubble's student, Alan Sandage at\\ {\tt http://antwrp.gsfc.nasa.gov/diamond$\_$jubilee/d$\_$1996/sandage$\_$hubble.html}}:
\begin{itemize}
\item 1922-1926. Hubble proposed a classification system for nebulae,
both galactic (which we still call ``nebulae'') and extragalactic
(which we know call ``galaxies''). The classification system of
galaxies has become known as the Hubble morphological sequence of galaxy types.
\item In 1924 Hubble decisively showed that spiral ``nebulae'' (or galaxies) are
huge ``island universes'' of stars similar to our own Milky Way,
with his discovery of Cepheids in nearby galaxies NGC 6822, M33 and M31
(The Andromeda galaxy) which allowed to measure distances to them.

\item Having established the fact that galaxies are distant stellar systems
like the Milky Way, Hubble used their distribution in various areas on the sky
to show that the overall distribution of galaxies in space on large scales is
quite homogeneous. This was a crucial fact as it justified the cosmological
principle of homogeneity and isotropy used to obtain dynamical models of
expanding universe from the Einstein's equations of general relativity.

\item In 1929 Hubble with a lot of technical help from his assistant Milton Humason has discovered
linear relation between redshift of lines in galaxy spectra and their distance from the Milky Way:
{\it the more distant a galaxy, the greater its
redshift.}
 This discovery lead to the notion of
the expanding universe and is the most fundamental discovery and observational fact that we know
about our observable Universe.
\end{itemize}
In this lab we will redo (in a simplified way) the Hubble's analysis
that resulted in the first, third, and fourth of these fundamental
discoveries using modern tools. The lab has four parts. In the first
part you will explore the morphological types of galaxies and the
overall shapes and features of their spectra, including the features
in the spectra called ``spectral lines.''  In the second part, you will
count galaxies in randomly chosen patches of the sky to see how homogeneous
their distribution over the sky really is. In the third part, you
will measure the wavelengths of spectral lines in real galaxy
spectra. To determine galaxy redshifts you will compare the measured
redshifted galaxy lines to the laboratory measurements of the line
wavelength on Earth.  Finally, using the apparent brightnesses of the
brightest cluster galaxies as proxy for their distances you will plot
your measured redshifts and distance against one another to produce
the Hubble law, which you will use to measure the Hubble constant.

\section*{Morphological types of galaxies}

Hubble classified galaxies into a sequence, now called {\it the tuning-fork Hubble diagram} (due
to the its ressemblance of a tuning fork viewed horizontally) based on their
visual appearance: shape, smoothness, and presence of features such as bars and spiral arms. All this
collectively is called ``galaxy morphology'' and classification scheme is called ``morphological
classification.'' Hubble has conjectured
that the sequence represented the path of galaxy evolution. Although this was not confirmed
by further observations, the classification is still widely used by astronomers.

Hubble's classification contains many sub-classes of galaxies\footnote{See the diagram at\\{\tt http://cas.sdss.org/dr3/en/proj/advanced/galaxies/tuningfork.asp}}, but the two main
classes of galaxies are the elliptical and spiral galaxies. Ellipticals tend to be
smooth in their light distribution and roundish in their appearance.
Spiral galaxies tend to have features such as bars and spiral arms.

To familiarize yourself with main morphological types of galaxies, go to the Galaxy Zoo website
at \texttt{http://www.galaxyzoo.org/Tutorial.aspx} and review Part 1 of that page.

{\bf Lab tasks.}
{\it
\begin{itemize}
\item What are the typical colors of elliptical and spiral galaxies? Discuss why these classes
of galaxies tend to have the colors they have from what you know about colors of stars.
\item Sketch six examples of the ellipticals and six examples of spiral galaxies in your lab report indicating their
type (spiral or ellipticals) and providing your best guess for their sub-type according to the
Hubble's classification (e.g., E3, Sc, SBb, etc.). It may be useful to review this portion
of the Galaxy Zoo's website:\\ {\tt http://beta.galaxyzoo.org/howtotakepart.aspx} (see also
the corresponding chapter of your textbook).
\end{itemize}
}

If you are curious and have time, explore the Galaxy Zoo website and help scientists
in their exploration of galaxies by performing some simple classifications in their Galaxy Analysis
section.

\section*{Homogeneity of galaxy distribution on the sky}

Start Google Earth and click on the ``Saturn'' icon on the top
bar which switches to the Sky portion of Google Earth\footnote{Google Sky is an extension of Google
Earth software into the sky (the simple version of which, Google Maps,
you probably have used to get directions, view a map, etc.).  See the
description of Google Sky that will be distributed to you, as well
as video introduction to Google Sky at {\tt
earth.google.com/sky/skyedu.html}} on the lab computer (or on your
laptop after you install Google Sky and download the SDSS Galaxy Query
kml plugin from the directory showed to you by TA and activate the
\texttt{SDSS Galaxy Photometric Layer} by clicking on it, make sure
the \texttt{SDSS Galaxy Spectroscopic Layer} is turned off (by
unchecking it). Load the kml file {\tt Hubble$\_$lab$\_$random$\_$SDSS$\_$fields.kml}.

Find the corresponding folder in the {\tt Places} window on the left
hand side of the Sky window and click on $+$ to see the folder
contends ({\tt field 1, field 2, ..., field 10}).  These are ten
random locations in the area of sky covered by the Sloan Digital Sky
Survey away from the plane of the Milky Way and in the areas devoid of
very big bright galaxies and stars (which can block a significant part
of the field of view).

Click on the {\tt field 1} field and the Sky
will take you to the first field down to the zoom level at which the
field has some approximately 5 minutes of arc size (verify that
the label in the lower right hand
corner of the Sky window shows number close to $0^{\circ}05'$). Please do not zoom
in or zoom out after that. If you do or if you decided to choose your own random field (feel
free to do so),
please zoom again to the point when the label is as close to $0^{\circ}05'$
as possible. This is because we want to compare counts of galaxies
within the same area of the sky in different places, which requires
that the size of the patch we use is the same (5 arcminutes in our
case). Also do not resize the Google Earth window as you count galaxies
in different fields, your counts may be affected if you resize the window.

Once the Sky finishes its zoom, wait until the SDSS Galaxy Query layer
identifies galaxies brighter than apparent magnitude in $r$ band of $m_r=21$ in the SDSS catalog.
Once the layer queries the SDSS database over the internet, the galaxies
in the field will be marked by circles. Count the number of marked
galaxies in the field and then click on {\tt field 2} and repeat the exercise.

For this part of the lab we need to discuss a little bit of statistics.
As you know, statistics is a big part of analysis of data in various
fields: physics, biology, economics, etc. The statistics of counts
of relatively small random samples of objects is typically governed
by what is called the Poisson distribution. For example, if galaxies
were distributed completely uniformly on the sky, we would expect that
the probability to find a given number of galaxies in a field of a given
size is given by the Poisson distribution. The key feature of this
distribution is that if the average number of galaxies per field of
a given area is $\bar{N}$, the typical variation from field to field
should be $\sqrt{\bar{N}}$.

{\bf Lab tasks.}
{\it
\begin{itemize}
\item Count the number of galaxies brighter than $m_r=21$ (the galaxies
marked by circles) and record the number for each field.
\item Calculate the average number of galaxies per field using counts from all
ten fields. You can choose more fields of your own within the areas
covered by the SDSS survey, just make sure that they
are all 5 arcminutes on a side.
\item Compare counts in each field to the average and expected variation from field
to field. Does it look like the distribution of galaxy counts in these fields
is close to the Poisson distribution (i.e. distribution of galaxies on the sky
is uniform)?
\end{itemize}
}

\section*{Galaxy Spectra}

In Google Sky activate \texttt{SDSS Galaxy Spectroscopic Layer},
make sure the \texttt{SDSS Galaxy Photometric Layer} is turned off. On the lowest zoom,
find the strips of sky that were observed by the SDSS. Now zoom in and
look for some cool nearby (i.e., bright) galaxies that have spectra available
(circled in brown). Remember, circles are only placed around the
brightest galaxies in your field of view, so if you'd like to check
whether SDSS has a dim galaxy's spectrum, just zoom in on that galaxy
until it is alone or is one of the brightest galaxies.  Find a few
disk/spiral galaxies, and a few elliptical galaxies.  You can
mark galaxies and go back to them later with the \texttt{placemark
tool} (thumbtack in the top toolbar). To view their spectra click on
the desired circled galaxies, and follow the link at the bottom of the
popup bubble.

{\bf Lab tasks.}
{\it \begin{itemize}
\item  Review the spectra of six elliptical and six
spiral galaxies, observe general pattern and similarities in spectra of galaxies of either class.
\item What is the relationship between the morphological class of a galaxy and its spectrum?
 Sketch a typical spectrum characteristic for elliptical and spiral galaxies.
\item Discuss the main differences in the spectra of elliptical and spiral galaxies and give your
explanation for the origin of these differences.
\end{itemize}
}

\section*{Measuring Redshifts}

The gas and stars in all galaxies are made of basically the
same stuff -- the same elements and molecules -- they are just often at different density
and temperature, with different
abundances from galaxy to galaxy. For example, oxygen we breathe here on Earth is still oxygen in a
distant galaxy, so we can use its properties measured in a lab on Earth to figure out
in what state it is in an observed galaxy. Since each chemical element has a
specific atomic structure, it has a fingerprint of light emission or
absorption that it plants in the spectra of galaxies in the form of emission or absorption spectral lines.
The lines of some chemical species or ions are particularly
prominent.

 Now that you know what galaxy spectra look like, we will use them to measure
shifts of spectral lines with respect to their laboratory wavelengths. Because these shifts in most galaxies tend
to be towards longer wavelengths corresponding to redder color, they are called redshifts. You
can find laboratory values for spectral features of elements in the
table below (the wavelengths are given in units of {\AA}ngstr\"oms: $1$\AA=$10^{-8}$~cm, named after the Swedish
physicist Anders {\AA}ngstr\"om, one of the founders of the field of atomic spectroscopy)

%http://skyserver.sdss.org/en/proj/advanced/hubble/redshifts.asp#ex16 ::
\begin{center}
% use packages: array
\begin{tabular}{lc}
\hline
Element-Transition & Laboratory wavelength (\AA) \\
\hline
\textbf{Hydrogen:} & \\
H$\alpha$ & 6563 \\
H$\beta$  & 4861 \\
H$\gamma$  & 4341 \\
H$\delta$  & 4102\\
\hline
\textbf{Heavy elements (metals):} & \\
Mg & 5150 \\
Na  & 5892 \\
\hline
%what other elements?
\end{tabular}
\end{center}

Different lines in the spectrum of a given element are indicated in
greek, and roman numerals mark different ionization states, which have
their own distinct spectral fingerprint.

You will measure the redshifts of a set of some of the brightest
galaxies in the universe, which are found in clusters.
Load file {\tt Hubble$\_$lab$\_$BCGs.kml} into Google Sky and click
on $+$ in front of the folder with the same name in the left window to see
the list of the brightest cluster galaxies from the list in the Table given
at the end of this document. Click on the first object in the list and Sky
will take you to the field showing this object. Activate the SDSS Galaxy Spectroscopy
Layer (and switch off the SDSS Galaxy Photometric Layer), the brightest galaxy
should be marked by a circle after the Sky queries the SDSS spectroscopic database.
Click on the brightest galaxy in the cluster marked by circle and
follow the link to its spectrum in a bubble that pops up.
Determine the redshift of each galaxy by comparing the measured
wavelength of spectral features (absorption or emission lines) with
the wavelength given in the table above as follows

$$ z={\lambda_{\rm obs}\over\lambda_{\rm lab}}-1$$

Where $\lambda_{\rm obs}$ is the measured wavelength of the spectral
feature and $\lambda_{\rm lab}$ is the wavelength from the ``lab''
measurement from the table.

{\it
{\bf Lab tasks.}
\begin{itemize}
\item For each galaxy use two strong absorption lines of magnesium and sodium, labeled Mg and Na.
Estimate the wavelength of the lines
following the corresponding vertical dotted line to the horizonthal $x$-axis
and reading off the wavelength number as accurately as you can.
Please, indicate the lines you used
and provide the actual calculations of redshifts using these lines in your
lab report.

\item Each line gives an independent estimate of redshift. Make
sure that they are consistent (close to each other; for example 0.171 and 0.175 are
close but 0.05 and 0.20 are not) and then calculate the average number using
the two measurements and record this number to the table below.
 The difference between redshifts from individual lines
and the average gives you a rough measure of the error of your redshift
estimate, which results from the visual estimate of the observed wavelength
$\lambda_{\rm obs}$ from the spectrum. Indicate this error along with the average number.

\item Click on the galaxy, and a popup bubble should appear containing measurements of light from the galaxy.
 Record the galaxies apparent brightness in the $r$ band (e.g., $r=13.6062$) to the table below.
The $r$ band is a range of wavelengths in the red part of the spectrum. $r$ band brightness is measured by using
a special filter that filters out light from other wavelengths.

\item Describe the visual appearance of the brightest cluster galaxies and their spectra
and interpret their color and spectra in terms of their stellar populations.
Do the brightest galaxies vary much in color or shape?
\end{itemize}
}

\section{Making a Hubble Diagram}

The Hubble's law of expansion relates redshift $z=\Delta\lambda/\lambda$ to the distance
between a galaxy and us via a linear relation. The relation is commonly
expressed in terms of the indicative velocity of recession by analogy with the Doppler wavelength
shift we encounter every day in a sound of an ambulance or a passing train,
\begin{equation}
V=cz=c\Delta\lambda/\lambda,
\label{eq:redshift}
\end{equation}
where $c=3\times 10^5$ km/s is the speed of light. The redshifts measured
for distant galaxies, however, do not actually reflect their physical motion
in space but rather expansion of the space itself, in which galaxies are markers of the expanding 'net'.
Nevertheless, the language of velocities is usually adopted for historical reasons and convenience. In these
terms, the recession law is
\begin{equation}
V=H_0d,
\label{eq:hubble}
\end{equation}

where $d$ is the distance to the galaxy and $H_0$ is the constant of
proportionality called the Hubble constant. Since $V$ is commonly measured in
kilometers per second, (km/s) and $d$ is commonly measured in megaparsecs,
(Mpc), the units of $H_0$ must be km/s/Mpc (note that this is equivalent to
units of inverse time). If we know the value of $H_0$ and we have measured the
value of $V$ from the shift of spectral lines, we can use the above formula to
compute the distance. Thus, our perceived scale of the universe depends on the
value of $H_0$.

Conversely, if we assume that expansion of space have been the same in the past (i.e., the same $V$),
we can calculate the time it took since the moment when distances between Milky Way
and a galaxy was zero (the moment of the Big Bang) to the present time when the distance is some value $d$:
$t=d/V$. Given the Hubble law $V=H_0d$, we can rewrite this as $t=d/V=1/H_0$,
which means that the inverse of the Hubble constant gives us an estimate of the time
elapsed since the Big Bang or the age of the Universe. This is a rough estimate
because modern observations show that $V$ and the Hubble constant are not constant
in time. This estimate however is within a factor of two of the exact age.

In this part of the lab we will work with data that will allow us to verify the
linear relation between redshift and distance, and to determine the value of
$H_0$. We need some way to measure distances independently of the redshift. We
will use the inverse-square law, where the measured brightness of the whole galaxy
can be related to its distance:
\begin{equation}
f = {L\over 4\pi d^2},
\label{eq:flux}
\end{equation}
where $L$ is the luminosity and is measured in erg/s, $d$ is
the distance measured in cm, and $f$ is apparent brightness,
or flux, $f$, measured in erg/s/cm$^2$.

Different galaxies naturally have different
intrinsic brightnesses (called luminosities in the following). However, Hubble
and others showed that a recognizable class of galaxy, namely the brightest
elliptical galaxies (typically residing in the centers of groups and
clusters of galaxies), has a small range of luminosity. Such
'first-ranked' galaxies then serve as good ``standard candles'' (objects
with known intrinsic brightness).

It is often useful to express a physical relation directly in terms of
``observables'' --- quantities we can actually measure in
observations. Equation~\ref{eq:hubble}, called the Hubble law of
recession, contains the apparent recessional velocity $V$, which is
not directly observable, and the distance $d$, which is also not
directly observable.  However, Equations~\ref{eq:redshift} and
\ref{eq:flux} show how to relate these quantities to the redshift $z$
and to the flux $f$ which are directly observable. Write down the
equation that is equivalent to Equation~\ref{eq:hubble} that is
expressed as far as possible in terms of ``observables.''  Your
formula should contain both $L$  and $H_0$. This tells you that an
uncertainty in the value of $H_0$ (the scale of the universe) is
equivalent to an uncertainty in the characteristic luminosities of
galaxies and vice versa.

There is one more formula that is needed. Astronomers like to express
measurements of the flux in terms of magnitudes (see Chapter 1 in the
``Universe'' textbook).  The relation between the magnitude $m$ and
the flux expressed in cgs units is
\begin{equation}
m=-48.60-2.5\log_{10}(f)
\label{eq:mag}
\end{equation}

The numerical factor 48.60 is an arbitrary zero point to the magnitude scale set
by historical precedent. It makes the star Vega ($\alpha$ Lyr) have a magnitude
of 0.0 at a wavelength of 5500~{\AA}. Vega is also used as the zero point for
the B, V, R, I filter system magnitudes. For our purposes,
the constant factor is not important.

In the last section you compiled a table of redshifts $z$ and apparent
magnitudes for brightest cluster galaxies. We will use the symbol $m_r$ for
r-band magnitudes to avoid confusion. It is useful to extend the Hubble diagram
to very low redshift to increase the lever arm over which we measure $H_0$.
However, measuring very small redshifts using visual estimates of wavelength used
for the BCGs is tough due to the errors of redshift estimates. Therefore,
we will rely, as is often done in science, on previous accurate measurement
done by other people for the brighest cluster galaxy NGC 4472 in the nearby Virgo cluster:
$m_r$ = 9.97 and $z = 0.004$.

 To determine the value of the Hubble constant, $H_0$, we require that one
of the galaxies has a distance that is measured in some fashion that is
independent of the measurement of its redshift (otherwise the argument would be
circular). Such distance measurement is done using distance estimators
from the previous rung of the ``distance ladder'' (e.g., Cepheid stars).
This is an arduous task, and its description will not be attempted
here. The most recent measurements of the distance to NGC 4472
(the point that should be in the lower left-hand comer of your plot) is 18.2 Mpc.
Given the distance to NGC 4472 and its $r-$band magnitude ($m_r=9.97$),
you can calculate distances to any other BCG galaxy as (make sure you understand
where this relation comes from; you can derive it from equations given above):
\begin{equation}
d_{\rm BCG}=18.2\times 10^{0.2(m_r-9.97)}{\ \rm Mpc}.
\label{eq:dist}
\end{equation}
Using distance measured in such way and the redshift you measured
for a galaxy, you can can estimate value of $H_0$ for each of the BCGs.

{\bf Lab tasks.}
{\it
\begin{enumerate}
\item Make a plot of the data in the accompanying table, plus NGC 4472, that has
log$_{10}z$ on the x-axis and $m_r$ on the y-axis (note that numerically
larger values of $m_r$ correspond to fainter fluxes, {\it i.e.} greater
distances). This plot is called the Hubble diagram.
From the definition of magnitude in Equation~\ref{eq:mag}, a
difference in flux $f$ of a factor of 100 is equivalent to the difference of 5 magnitudes,
which is what is expected for a difference in
distance of a factor of 10 by the inverse-square law. Since we are claiming that distance is proportional
to redshift, 5 magnitudes should also correspond to a factor of 10 in redshift.
Draw two straight lines through the data points which you think best fit the data
by eye, one {\em
including} and one {\em excluding} NGC 4472. What is the slope = $\Delta
y/\Delta x$ that you expect if the universe is expanding uniformly? Is that what
you have measured? \label{item:first}

\item Estimate $H_0$ for a dozen BCG galaxies using redshifts you measured and
distances calculated using equation~(\ref{eq:dist}). Average the values to get
an average estimate of $H_0$.
What is the derived value for the Hubble constant $H_0$? What is the limit for
the age of the universe that this value implies?

\item Hand in your plot with the value of the Hubble constant clearly indicated.
Include a written discussion of the following questions: Why don't the points
fall on precisely a straight line (give at least two possible reasons)?
Estimate the rough estimate of time elapsed since the Big Bang using the
value of the Hubble constant you measured ($t=1/H_0$).
\end{enumerate}
}

%\newpage

%http://umsdss.physics.lsa.umich.edu/catalogs/maxbcg_public_catalog.dat
%$RA,DEC,z,bcgspecz,BCG_rlum,BCG_ilum,rlum_mem,ilum_mem,ngals,ngals_r200$
%$239.58334,27.233419,0.102650,0.0907943,8.67289,10.7264,274.706,343.396,95,188$
%$126.37104,47.133478,0.135050,0.128977,19.0209,24.4289,152.746,192.101,68,99$

%http://xxx.lanl.gov/pdf/astro-ph/0403354v1

\begin{center}
% use packages: array
\begin{tabular}{|c|c|c|c|c|}
\hline
Name & R.A. & dec & z & $m_r$ \\ \hline
RXCJ0747.0+4131 & 116.7537 & 41.5314 &{\hspace{1cm}} &{\ \ \ \ \ \ \ \ \ \ }\\ \hline  %& 0.0280 \\%13.61
%RXCJ0758.4+3747 & 119.6172 & 37.7888 &{\ \ \ \ \ }&\\ \hline  %& 0.0410 \\ %************%
RXCJ0810.3+4216 & 122.5942 & 42.2669 &{\ \ \ \ \ }&\\ \hline %& 0.0640 \\ %********%
%RXCJ0041.8-0918 & 10.4587 & -9.3019  &{\ \ \ \ \ }&\\ \hline  %& 0.0520 \\%
RXCJ0809.6+3455 & 122.4177 & 34.9262 &{\ \ \ \ \  }&\\ \hline % & 0.0800 \\ %*******%
RXCJ0800.9+3602 & 120.2445 & 36.0469  &{\ \ \ \ \  }&\\ \hline % & 0.2880 \\%
%RXCJ0114.9+0022 & 18.7350 & 0.3746   & &\\  %& 0.0470 \\%this is off center!%
%RXCJ0119.6+1453 & 19.9072 & 14.8931  & &\\ %& 0.1290 \\%also hard to tell%
%RXCJ0137.2-0912 & 24.3140 & -9.2028   %& 0.0390 \\ too hard to tell%
%RXCJ0152.7+0100 & 28.1762 & 1.0126   & &\\ \hline  %& 0.2270 \\%
RXCJ0736.4+3925 & 114.1540 & 39.4229  & &\\ \hline  % 114.1040 & 39.4329  %& 0.1170 \\%
%RXCJ0753.3+2922 & 118.3291 & 29.3741 & 0.0620 \\ too hard to tell%
%%%%%%
%not in DR5? RXCJ0821.8+0112 & 125.4655 & 1.2116 & 0.0820 &  \\ \hline%
RXCJ0822.1+4705 & 125.5417 & 47.0995 & &\\ \hline  % 0.1300 & 15.52\\ \hline%15.52
%RXCJ0824.0+0326 & 126.0209 & 3.4383 & 0.3470 & 18.35\\ \hline %BCG location?
RXCJ0825.4+4707 & 126.3652 & 47.1196 & &\\ \hline  % 0.1260 & 14.71\\ \hline %***
RXCJ0828.1+4445 & 127.0278 & 44.7634 & &\\ \hline  % 0.1450 & 15.71\\ \hline %nicenodata
RXCJ0842.9+3621 & 130.7401 & 36.3625 & &\\ \hline  % 0.2820 & 16.79\\ \hline %
%RXCJ0845.3+4430 & 131.3434 & 44.5115 & &\\ \hline  % 0.0540 & 14.82\\ \hline% weak
%RXCJ0850.1+3603 & 132.5499 & 36.0614 & &\\ \hline  % 0.3730 & 18.57\\ \hline%
RXCJ0913.7+4056 & 138.4411 & 40.9339 & &\\ \hline  % 0.4420 & 18.14\\ \hline% crazy high z
RXCJ0913.7+4742 & 138.4446 & 47.7021 & &\\ \hline  % 0.0510 & 14.52\\ \hline%  ***
RXCJ0917.8+5143 & 139.4637 & 51.7223 & &\\ \hline  % 0.2170 & 16.73\\ \hline% * super rich but only 3 specs
RXCJ0943.0+4700 & 145.7600 & 47.0038 & &\\ \hline  % 0.4060 & 19.00\\ \hline%
%RXCJ0947.1+5428 & 146.7862 & 54.4754 & &\\ \hline  % 0.0460 & 14.17\\ \hline%
RXCJ0952.8+5153 & 148.2009 & 51.8888 & &\\ \hline  % 0.2140 & 16.56\\ \hline%
RXCJ0953.6+0142 & 148.4231 & 1.7118  & &\\ \hline  % 0.0980 & 14.82\\ \hline%
RXCJ1000.5+4409 & 150.1260 & 44.1550 & &\\ \hline  % 0.1540 & 17.15\\ \hline%
%RXCJ1013.7-0006 & 153.4368 & -0.1085 & &\\ \hline  % 0.0930 & 14.76\\ \hline%** but no bcg
%*RXCJ1017.5+5933 & 154.3960 & 59.5577 & &\\ \hline  % 0.2850& 17.76\\ \hline%corrected z ** but no bcg
%RXCJ1022.5+5006 & 155.6283 & 50.1030 & &\\ \hline  % 0.1580 & 15.51\\ \hline%
%RXCJ1023.6+0411 & 155.9125 & 4.1873 & &\\ \hline  % 0.2850  & 17.17\\ \hline%
%RXCJ1023.6+4908 & 155.9212 & 49.1349 & &\\ \hline  % 0.1440 & 15.45\\ \hline%***
RXCJ1053.7+5452 & 163.4349 & 54.8726 & &\\ \hline  % 0.0750 & 15.24\\ \hline%
RXCJ1058.4+5647 & 164.6097 & 56.7922 & &\\ \hline  % 0.1360 & 15.48\\       %***
\hline
\end{tabular}
\end{center}

%\includegraphics[width=7in]{g0312-220.pdf}
%\newpage
%\includegraphics[width=7in]{g0312-255.pdf}
%\newpage
%\includegraphics[width=7in]{g0312-529.pdf}
%\newpage
%\includegraphics[width=7in,trim=1.in 0.in 0.3in 0.2in]{Template_spect2.pdf}
%\newpage
%\begin{center}
%
%\includegraphics[width=5.5in,trim=2.8in 0in -2.in 2.3in]{data.pdf}\\

%\end{center}

\end{document}


text:
require 'notification_hub/channels/webhook/base'

module NotificationHub
	module Channels
		module Webhook
	    class Httparty < Base
		    @gateway_code = :httparty

	      def initialize(configuration)
	      	super
	      end

	      class << self
					def send_message(event_code, data, options)
						event = event_code.split(".")

						begin
							json_string = ActionController::Base.new.
								render_to_string("#{gateway_options[:template_path]}/#{event[0]}/#{event[1]}", locals: data)
							json_object = JSON.parse(json_string)
							json_object[:event] = event_code
							json_object[:timestamp] = Time.zone.now

							response = HTTParty.post(options[:webhook_url], {
						    :body => json_object.to_json,
						    :headers => { 'Content-Type' => 'application/json' },
						    :timeout => gateway_options[:timeout_time]
						  })

						  raise "Webhook::Httparty Error: #{response.body}" if response.code != 200
						rescue => exception
						  raise "Webhook::Httparty Error Error: #{exception.message}"
						end
					end
				end
			end
	  end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import Vue from 'vue'
import Vuex from 'vuex'
import mousePos from './modules/mouse-pos'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    mousePos
  },
  strict: debug
})


text:
#ifndef ANDROID_MEDIARECORDER_H
#define ANDROID_MEDIARECORDER_H

#include <utils/Log.h>
#include <utils/threads.h>
#include <utils/List.h>
#include <utils/Errors.h>
#include <media/IMediaRecorderClient.h>
#include <media/IMediaDeathNotifier.h>

namespace android {

class Surface;
class IMediaRecorder;
class ICamera;

typedef void (*media_completion_f)(status_t status, void *cookie);

/* Do not change these values without updating their counterparts
 * in media/java/android/media/MediaRecorder.java!
 */
enum audio_source {
    AUDIO_SOURCE_DEFAULT = 0,
    AUDIO_SOURCE_MIC = 1,
    AUDIO_SOURCE_VOICE_UPLINK = 2,
    AUDIO_SOURCE_VOICE_DOWNLINK = 3,
    AUDIO_SOURCE_VOICE_CALL = 4,
    AUDIO_SOURCE_CAMCORDER = 5,
    AUDIO_SOURCE_VOICE_RECOGNITION = 6,
    AUDIO_SOURCE_VOICE_COMMUNICATION = 7,
    AUDIO_SOURCE_MAX = AUDIO_SOURCE_VOICE_COMMUNICATION,

    AUDIO_SOURCE_LIST_END  // must be last - used to validate audio source type
};

enum video_source {
    VIDEO_SOURCE_DEFAULT = 0,
    VIDEO_SOURCE_CAMERA = 1,

    VIDEO_SOURCE_LIST_END  // must be last - used to validate audio source type
};

//Please update media/java/android/media/MediaRecorder.java if the following is updated.
enum output_format {
    OUTPUT_FORMAT_DEFAULT = 0,
    OUTPUT_FORMAT_THREE_GPP = 1,
    OUTPUT_FORMAT_MPEG_4 = 2,

    OUTPUT_FORMAT_AUDIO_ONLY_START = 3, // Used in validating the output format.  Should be the
                                        //  at the start of the audio only output formats.

    /* These are audio only file formats */
    OUTPUT_FORMAT_RAW_AMR = 3, //to be backward compatible
    OUTPUT_FORMAT_AMR_NB = 3,
    OUTPUT_FORMAT_AMR_WB = 4,
    OUTPUT_FORMAT_AAC_ADIF = 5,
    OUTPUT_FORMAT_AAC_ADTS = 6,

    /* Stream over a socket, limited to a single stream */
    OUTPUT_FORMAT_RTP_AVP = 7,

    /* H.264/AAC data encapsulated in MPEG2/TS */
    OUTPUT_FORMAT_MPEG2TS = 8,

    OUTPUT_FORMAT_LIST_END // must be last - used to validate format type
};

enum audio_encoder {
    AUDIO_ENCODER_DEFAULT = 0,
    AUDIO_ENCODER_AMR_NB = 1,
    AUDIO_ENCODER_AMR_WB = 2,
    AUDIO_ENCODER_AAC = 3,
    AUDIO_ENCODER_AAC_PLUS = 4,
    AUDIO_ENCODER_EAAC_PLUS = 5,

    AUDIO_ENCODER_LIST_END // must be the last - used to validate the audio encoder type
};

enum video_encoder {
    VIDEO_ENCODER_DEFAULT = 0,
    VIDEO_ENCODER_H263 = 1,
    VIDEO_ENCODER_H264 = 2,
    VIDEO_ENCODER_MPEG_4_SP = 3,

    VIDEO_ENCODER_LIST_END // must be the last - used to validate the video encoder type
};

/*
 * The state machine of the media_recorder uses a set of different state names.
 * The mapping between the media_recorder and the pvauthorengine is shown below:
 *
 *    mediarecorder                        pvauthorengine
 * ----------------------------------------------------------------
 *    MEDIA_RECORDER_ERROR                 ERROR
 *    MEDIA_RECORDER_IDLE                  IDLE
 *    MEDIA_RECORDER_INITIALIZED           OPENED
 *    MEDIA_RECORDER_DATASOURCE_CONFIGURED
 *    MEDIA_RECORDER_PREPARED              INITIALIZED
 *    MEDIA_RECORDER_RECORDING             RECORDING
 */
enum media_recorder_states {
    MEDIA_RECORDER_ERROR                 =      0,
    MEDIA_RECORDER_IDLE                  = 1 << 0,
    MEDIA_RECORDER_INITIALIZED           = 1 << 1,
    MEDIA_RECORDER_DATASOURCE_CONFIGURED = 1 << 2,
    MEDIA_RECORDER_PREPARED              = 1 << 3,
    MEDIA_RECORDER_RECORDING             = 1 << 4,
};

// The "msg" code passed to the listener in notify.
enum media_recorder_event_type {
    MEDIA_RECORDER_EVENT_ERROR                    = 1,
    MEDIA_RECORDER_EVENT_INFO                     = 2
};

enum media_recorder_error_type {
    MEDIA_RECORDER_ERROR_UNKNOWN                  = 1
};

// The codes are distributed as follow:
//   0xx: Reserved
//   8xx: General info/warning
//
enum media_recorder_info_type {
    MEDIA_RECORDER_INFO_UNKNOWN                   = 1,
    MEDIA_RECORDER_INFO_MAX_DURATION_REACHED      = 800,
    MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED      = 801,
    MEDIA_RECORDER_INFO_COMPLETION_STATUS         = 802,
    MEDIA_RECORDER_INFO_PROGRESS_FRAME_STATUS     = 803,
    MEDIA_RECORDER_INFO_PROGRESS_TIME_STATUS      = 804,
};

// ----------------------------------------------------------------------------
// ref-counted object for callbacks
class MediaRecorderListener: virtual public RefBase
{
public:
    virtual void notify(int msg, int ext1, int ext2) = 0;
};

class MediaRecorder : public BnMediaRecorderClient,
                      public virtual IMediaDeathNotifier
{
public:
    MediaRecorder();
    ~MediaRecorder();

    void        died();
    status_t    initCheck();
    status_t    setCamera(const sp<ICamera>& camera);
    status_t    setPreviewSurface(const sp<Surface>& surface);
    status_t    setVideoSource(int vs);
    status_t    setAudioSource(int as);
    status_t    setOutputFormat(int of);
    status_t    setVideoEncoder(int ve);
    status_t    setAudioEncoder(int ae);
    status_t    setOutputFile(const char* path);
    status_t    setOutputFile(int fd, int64_t offset, int64_t length);
    status_t    setVideoSize(int width, int height);
    status_t    setVideoFrameRate(int frames_per_second);
    status_t    setParameters(const String8& params);
    status_t    setListener(const sp<MediaRecorderListener>& listener);
    status_t    prepare();
    status_t    getMaxAmplitude(int* max);
    status_t    start();
    status_t    stop();
    status_t    reset();
    status_t    init();
    status_t    close();
    status_t    release();
    void        notify(int msg, int ext1, int ext2);

private:
    void                    doCleanUp();
    status_t                doReset();

    sp<IMediaRecorder>          mMediaRecorder;
    sp<MediaRecorderListener>   mListener;
    media_recorder_states       mCurrentState;
    bool                        mIsAudioSourceSet;
    bool                        mIsVideoSourceSet;
    bool                        mIsAudioEncoderSet;
    bool                        mIsVideoEncoderSet;
    bool                        mIsOutputFileSet;
    Mutex                       mLock;
    Mutex                       mNotifyLock;
};

};  // namespace android

#endif // ANDROID_MEDIARECORDER_H


text:
echo
bin/gpm install admin
echo
echo installing gantry
bin/gpm install gantry5
echo -e "\e[92minstalling themes"
bin/gpm install g5_hydrogen
echo
bin/gpm install g5_helium
echo
bin/gpm install optimus
echo
bin/gpm install shoppingcart
echo
bin/gpm install shoppingcart-paypal
echo
bin/gpm install adminidenticons
echo
bin/gpm install login-oauth
echo
echo -e "\e[32mYou can add more plugins at the end of this script ..."
echo -e "\e[31mBye \e[5mBye \e[39m;) !"
echo


text:
require 'spec_helper'

describe 'AcademicCard' do
  let(:attrs) { {} }
  subject(:academic_card) { create :academic_card, attrs }

  # Associations
  it { should belong_to :school }
  it { should have_and_belong_to_many :academic_programs }

  # Fields
  it { should have_field(:title).of_type String }
  it { should have_field(:description).of_type String }

  # Validations
  it { should validate_presence_of :title }
end


text:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Sheep.VHall.Core.Util;

namespace Sheep.VHall.Core.Config
{
    internal class XmlConfigurator
    {
        internal static T Configure<T>() where T : class
        {
            var builder = new ConfigurationBuilder();
            string vhallPath = Path.Combine(AppContext.BaseDirectory, "config.ini");
            builder.AddIniFile(vhallPath);

            var live = builder.Build().GetValue<VHallBaseConfig>("vhall");
            string path = Path.Combine(AppContext.BaseDirectory, live.Path, typeof(T).Name, ".xml");

            return XmlHandle.XmlDeserializeFromFile<T>(path);
        }

    }
}


text:
package tests.javax_servlet_http.HttpServletResponseWrapper;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *	A Test for setStatus(int) method
 */

public class HttpServletResponseWrapperSetStatusTestServlet extends HttpServlet {

    public void service ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {

        response.setStatus( HttpServletResponse.SC_OK );
    }
}


text:
Poltergeist.InvalidSelector = (function (_super) {
  __extends(InvalidSelector, _super);

  function InvalidSelector(method, selector) {
    this.method = method;
    this.selector = selector;
  }

  InvalidSelector.prototype.name = "Poltergeist.InvalidSelector";

  InvalidSelector.prototype.args = function () {
    return [this.method, this.selector];
  };

  return InvalidSelector;

})(Poltergeist.Error);


text:
package org.lion.together.di.modules;

import org.lion.together.presenter.GistPresenter;
import org.lion.together.presenter.GistPresenterImpl;
import org.lion.together.ui.GistView;

import dagger.Module;
import dagger.Provides;

/**
 * Created by lion on 2016-11-17
 */
@Module
public class GistModule {
    private GistView gistView;

    public GistModule(GistView gistView) {
        this.gistView = gistView;
    }

    @Provides
    public GistPresenter provideGistPresenter() {
        return new GistPresenterImpl(gistView);
    }
}


text:
package org.kie.workbench.common.dmn.client.editors.expressions.types.context;

import org.junit.Test;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ContextUIModelMapperHelper.ContextSection;

import static org.junit.Assert.assertEquals;
import static org.kie.workbench.common.dmn.client.editors.expressions.types.context.ContextUIModelMapperHelper.getSection;

public class ContextUIModelMapperHelperTest {

    @Test
    public void testGetSectionNone() {
        assertEquals(ContextSection.NONE,
                     getSection(ContextUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT +
                                        ContextUIModelMapperHelper.NAME_COLUMN_COUNT +
                                        ContextUIModelMapperHelper.EXPRESSION_COLUMN_COUNT + 1));
    }

    @Test
    public void testGetSectionRowNumberColumn() {
        assertEquals(ContextSection.ROW_INDEX,
                     getSection(0));
    }

    @Test
    public void testGetSectionNameColumn() {
        assertEquals(ContextSection.NAME,
                     getSection(ContextUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT));
    }

    @Test
    public void testGetSectionExpressionColumn() {
        assertEquals(ContextSection.EXPRESSION,
                     getSection(ContextUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT +
                                        ContextUIModelMapperHelper.NAME_COLUMN_COUNT));
    }
}


text:
from google.cloud import orgpolicy_v2

async def sample_delete_policy():
    # Create a client
    client = orgpolicy_v2.OrgPolicyAsyncClient()

    # Initialize request argument(s)
    request = orgpolicy_v2.DeletePolicyRequest(
        name="name_value",
    )

    # Make the request
    await client.delete_policy(request=request)

# [END orgpolicy_v2_generated_OrgPolicy_DeletePolicy_async]


text:
class IKMap
{
public:
	IKString GetPath();

	IKMap();
	virtual ~IKMap();
	IKString Lookup ( IKString key );
	bool Write ( IKString filename );
	bool Write ();
	bool Read ( IKString filename );
	void RemoveAll ();
	bool Remove ( IKString key );
	bool Add ( IKString key, IKString value );
	int	Count();
	bool GetNthPair(int n, IKString &key, IKString &value);
	IKMap & operator = ( const IKMap &rhs );
	IKMap ( const IKMap& src);  //  copy ctor
	void ModifyKey ( IKString oldKey, IKString newKey );

private:
	int Find ( IKString key );

	class pair
	{
	public:
		pair (){key=TEXT(""), value=TEXT("");}
		~pair (){key=TEXT(""), value=TEXT("");}

		pair ( const pair& src)
		{
			key = src.key;
			value = src.value;
		}

		pair & operator = ( const pair &rhs )
		{
			key = rhs.key;
			value = rhs.value;

			return *this;
		}

		IKString key;
		IKString value;
	};

#if IKMAP_DYNAMIC
	pair *m_pairs;
	void Allocate (int n);
	//void Free();
	int m_size;
#else
	pair m_pairs[MAP_MAX_STRINGS];
#endif
	int m_nPairs;

	IKString m_path;
};

#endif // !defined(AFX_IKMAP_H__87C62D2C_22DB_4636_A522_DF3FA5DF90F6__INCLUDED_)


text:
import os
import getopt
import commands
import sys
import matplotlib.pyplot as plt
try:
    import nibabel
except ImportError:
    print '--- nibabel not installed! Exit program. ---'
    sys.exit(2)
try:
    import numpy as np
except ImportError:
    print '--- numpy not installed! Exit program. ---'
    sys.exit(2)

#=======================================================================================================================
# main
#=======================================================================================================================
def main():

    # get path of the toolbox
    status, path_sct = commands.getstatusoutput('echo $SCT_DIR')

    #loading files
    fname_template_vertebral_level  = path_sct+'/data/template/MNI-Poly-AMU_level.nii.gz'
    fname_template_vertebral_cord = path_sct+'/data/template/MNI-Poly-AMU_cord.nii.gz'

    vertebral_level_file = nibabel.load(fname_template_vertebral_level)
    vertebral_cord_file = nibabel.load(fname_template_vertebral_cord)

    vertebral_level_image = vertebral_level_file.get_data()
    vertebral_cord_image = vertebral_cord_file.get_data()

    hdr_vertebral_level=vertebral_level_file.get_header()
    hdr_vertebral_cord=vertebral_cord_file.get_header()

    z_size_vertebral_level=hdr_vertebral_level['pixdim'][3]
    z_size_vertebral_cord=hdr_vertebral_cord['pixdim'][3]

    #finding the centers of the vertebral levels
    vertebral_levels = find_mid_point_vertebral_level(vertebral_level_image)

    # Mean and Variance of Vertebral centers (Data from the graph)
    vertebral_Mu = np.zeros(len(vertebral_levels))
    vertebral_Sigma = np.zeros(len(vertebral_levels))

    vertebral_Mu[0], vertebral_Sigma[0] = 0, 0
    vertebral_Mu[1], vertebral_Sigma[1] = 0, 0
    vertebral_Mu[2], vertebral_Sigma[2] =  69.99, 4.58
    vertebral_Mu[3], vertebral_Sigma[3] =  86.11, 5.35
    vertebral_Mu[4], vertebral_Sigma[4] = 101.16, 6.33
    vertebral_Mu[5], vertebral_Sigma[5] = 115.54, 7.15
    vertebral_Mu[6], vertebral_Sigma[6] = 130.08, 8.25
    vertebral_Mu[7], vertebral_Sigma[7] = 0, 0
    vertebral_Mu[8], vertebral_Sigma[8] = 0, 0
    vertebral_Mu[9], vertebral_Sigma[9] = 0, 0
    vertebral_Mu[10], vertebral_Sigma[10] = 0, 0
    vertebral_Mu[11], vertebral_Sigma[11] = 0, 0
    vertebral_Mu[12], vertebral_Sigma[12] = 0, 0

    # Mean and Variance of Spinal centers (Data from the graph)
    spinal_Mu = np.zeros(len(vertebral_levels))
    spinal_Sigma = np.zeros(len(vertebral_levels))

    spinal_Mu[0], spinal_Sigma[0] = 0, 0
    spinal_Mu[1], spinal_Sigma[1] = 0, 0
    spinal_Mu[2], spinal_Sigma[2] =  51.46, 3.15
    spinal_Mu[3], spinal_Sigma[3] =  65.68, 3.96
    spinal_Mu[4], spinal_Sigma[4] =  81.08, 5.15
    spinal_Mu[5], spinal_Sigma[5] =  95.39, 5.68
    spinal_Mu[6], spinal_Sigma[6] = 109.33, 6.05
    spinal_Mu[7], spinal_Sigma[7] = 122.77, 7.03
    spinal_Mu[8], spinal_Sigma[8] = 0, 0
    spinal_Mu[9], spinal_Sigma[9] = 0, 0
    spinal_Mu[10], spinal_Sigma[10] = 0, 0
    spinal_Mu[11], spinal_Sigma[11] = 0, 0
    spinal_Mu[12], spinal_Sigma[12] = 0, 0

    #==================================================================================
    #Extrapolating unknown Means and Variances from the given data

    #Finding the distance between the known Spinal centers and Vertebral centers from the given data
    spinal_vertebral_dist=np.zeros(5)
    for i in range(5):
        spinal_vertebral_dist[i]=(vertebral_Mu[i+2] - spinal_Mu[i+2])

    #Linear fit of the distances between Vertebral and Spinal centers
    popt_spinal_vertebral = np.polyfit(np.arange(3,8),spinal_vertebral_dist,1)
    P_fit_spinal_vertebral_dist = np.poly1d(popt_spinal_vertebral)

    plt.plot(np.arange(0,15),P_fit_spinal_vertebral_dist(np.arange(0,15)),marker='+')
    plt.plot(np.arange(3,8),spinal_vertebral_dist,marker='o',linestyle='None')
    plt.title('Spinal-Vertebral distances')
    plt.show()

    conversion_factor=np.zeros(4)
    for i in range(2,6,1):
        conversion_factor[i-2]=(vertebral_levels[i]-vertebral_levels[i+1])/(vertebral_Mu[i+1]-vertebral_Mu[i])
    average_conversion_factor=np.mean(conversion_factor)

    delta_vertebral_levels = np.zeros(len(vertebral_levels)-1)
    for i in range(len(vertebral_levels)-1):
        delta_vertebral_levels[i] = (vertebral_levels[i] - vertebral_levels[i+1])/average_conversion_factor

    vertebral_Mu[0] = vertebral_Mu[1] - delta_vertebral_levels[0]
    vertebral_Mu[1] = vertebral_Mu[2] - delta_vertebral_levels[1]
    vertebral_Mu[7] = vertebral_Mu[6] + delta_vertebral_levels[6]
    vertebral_Mu[8] = vertebral_Mu[7] + delta_vertebral_levels[7]
    vertebral_Mu[9] = vertebral_Mu[8] + delta_vertebral_levels[8]
    vertebral_Mu[10] = vertebral_Mu[9] + delta_vertebral_levels[9]
    vertebral_Mu[11] = vertebral_Mu[10] + delta_vertebral_levels[10]
    vertebral_Mu[12] = vertebral_Mu[11] + delta_vertebral_levels[11]

    spinal_Mu[0] = vertebral_Mu[0] - P_fit_spinal_vertebral_dist(1)
    spinal_Mu[1] = vertebral_Mu[1] - P_fit_spinal_vertebral_dist(2)
    spinal_Mu[8] = vertebral_Mu[8] - P_fit_spinal_vertebral_dist(9)
    spinal_Mu[9] = vertebral_Mu[9] - P_fit_spinal_vertebral_dist(10)
    spinal_Mu[10] = vertebral_Mu[10] - P_fit_spinal_vertebral_dist(11)
    spinal_Mu[11] = vertebral_Mu[11] - P_fit_spinal_vertebral_dist(12)
    spinal_Mu[12] = vertebral_Mu[12] - P_fit_spinal_vertebral_dist(13)

    #Linear Fit of the known Vertebral variances to find the unkown variances
    popt_vertebral_sigma = np.polyfit(np.arange(3,8),vertebral_Sigma[2:7],1)
    P_fit_vertebral_sigma = np.poly1d(popt_vertebral_sigma)
    plt.plot(np.arange(0,14),P_fit_vertebral_sigma(np.arange(0,14)),marker='+')
    plt.title('Vertebral_sigma')
    plt.plot(np.arange(3,8),vertebral_Sigma[2:7],marker='o',linestyle='None')
    plt.show()

    #Linear Fit of the known Spinal variances to find the unknown variances
    popt_spinal_sigma = np.polyfit(np.arange(3,9),spinal_Sigma[2:8],1)
    P_fit_spinal_sigma = np.poly1d(popt_spinal_sigma)
    plt.plot(np.arange(0,14),P_fit_spinal_sigma(np.arange(0,14)),marker='+')
    plt.title('Spinal_sigma')
    plt.plot(np.arange(3,9),spinal_Sigma[2:8],marker='o',linestyle='None')
    plt.show()

    vertebral_Sigma[1]=P_fit_vertebral_sigma(0)
    vertebral_Sigma[0]=P_fit_vertebral_sigma(1)
    vertebral_Sigma[7]=P_fit_vertebral_sigma(8)
    vertebral_Sigma[8]=P_fit_vertebral_sigma(9)
    vertebral_Sigma[9]=P_fit_vertebral_sigma(10)
    vertebral_Sigma[10]=P_fit_vertebral_sigma(11)
    vertebral_Sigma[11]=P_fit_vertebral_sigma(12)
    vertebral_Sigma[12]=P_fit_vertebral_sigma(13)

    spinal_Sigma[1]=P_fit_spinal_sigma(2)
    spinal_Sigma[0]=P_fit_spinal_sigma(1)
    spinal_Sigma[8]=P_fit_spinal_sigma(9)
    spinal_Sigma[9]=P_fit_spinal_sigma(10)
    spinal_Sigma[10]=P_fit_spinal_sigma(11)
    spinal_Sigma[11]=P_fit_spinal_sigma(12)
    spinal_Sigma[12]=P_fit_spinal_sigma(13)

    for i in range(len(vertebral_levels)):
        y = gaussian(np.arange(0,500,0.1),spinal_Mu[i],spinal_Sigma[i])
        plt.plot(np.arange(0,500,0.1),y)
    plt.title('Mean Distance from the PMJ to the centre of each Nerve Rootlet Segment')
    plt.show()

    #Finding the distance between the Spinal and Vertebral centers in the image
    spinal_vertebral_distances=np.zeros(len(vertebral_levels))
    for i in range(len(vertebral_levels)):
        spinal_vertebral_distances[i]=round((vertebral_Mu[i] - spinal_Mu[i])*average_conversion_factor)

    spinal_levels = np.zeros(len(vertebral_levels))
    for i in range(len(vertebral_levels)):
        spinal_levels[i] = int(vertebral_levels[i] + spinal_vertebral_distances[i])

    #Creating Templates for each Spinal level
    k = 0
    X,Y,Z = np.where(vertebral_cord_image>0)
    for i in spinal_levels[:]:
        template_spinal_image = vertebral_cord_image.copy()
        count = 0

        for j in range(np.amax(Z),np.amin(Z)-1,-1):
            x,y = np.where(vertebral_cord_image[:,:,j]>0)
            diff = (i - j)/average_conversion_factor
            value = gaussian((spinal_Mu[k]+diff),spinal_Mu[k],spinal_Sigma[k])
            template_spinal_image[x,y,j] = value
        k = k+1

        # Write NIFTI volumes
        hdr_vertebral_cord.set_data_dtype('uint8') # set imagetype to uint8
        print '\nWrite NIFTI volumes...'
        img = nibabel.Nifti1Image(template_spinal_image, None, hdr_vertebral_cord)
        if k<=8:
            file_name = 'spinal_level_C'+str(k)+'.nii.gz'
        else:
            file_name = 'spinal_level_T'+str(k-8)+'.nii.gz'
        nibabel.save(img,file_name)
        print '.. File created:' + file_name

#==================================================================================
def find_mid_point_vertebral_level(data):

    vertebral_levels = np.zeros(int(np.amax(data)))
    for i in range((int(np.amin(data))+1),(int(np.amax(data))+1)):

        #finding the co-ordinates of voxels in each level
        x,y,z = np.where(data==i)
        z = np.sort(z)
        vertebral_levels[i-1] = np.amin(z) + round((np.amax(z)-np.amin(z))/2)
    return vertebral_levels

#==================================================================================
def gaussian(x, mu, sig):
    return (np.exp(-((x - mu)*(x - mu))/(2*sig*sig)))/(np.sqrt(2*(np.pi)*sig*sig))

#=======================================================================================================================
# Start program
#=======================================================================================================================
if __name__ == "__main__":
    # call main function
    main()


text:
package com.open.project.utils;

import android.content.Context;
import android.database.DataSetObservable;
import android.database.DataSetObserver;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.WrapperListAdapter;

import java.util.ArrayList;

/**
 * A {@link com.project.project.utils.GridView} that supports adding header rows and footer rows in a very
 * similar way to {@link android.widget.ListView}. See
 * {@link HeaderFooterGridView#addHeaderView(android.view.View, Object, boolean)} and
 * {@link HeaderFooterGridView#addFooterView(android.view.View, Object, boolean)}.
 *

 * This source code is based from
 * http://grepcode.com/file/repository.grepcode.com
 * /java/ext/com.google.android/android
 * -apps/4.4_r1/com/android/photos/views/HeaderGridView.java
 */
public class GridView extends android.widget.GridView
{
	private static final String TAG = "HeaderFooterGridView";
	private ArrayList<FixedViewInfo> mHeaderViewInfos = new ArrayList<FixedViewInfo>();
	private ArrayList<FixedViewInfo> mFooterViewInfos = new ArrayList<FixedViewInfo>();
	private int mRequestedNumColumns;
	private int mNumColmuns = 1;

	public GridView(Context context)
	{
		super(context);
		initHeaderGridView();
	}

	public GridView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initHeaderGridView();
	}

	public GridView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initHeaderGridView();
	}

	private void initHeaderGridView()
	{
		super.setClipChildren(false);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		if (mRequestedNumColumns != AUTO_FIT)
		{
			mNumColmuns = mRequestedNumColumns;
		}
		if (mNumColmuns <= 0)
		{
			mNumColmuns = 1;
		}

		ListAdapter adapter = getAdapter();
		if (adapter != null && adapter instanceof HeaderFooterViewGridAdapter)
		{
			((HeaderFooterViewGridAdapter) adapter).setNumColumns(getNumColumns());
		}
	}

	@Override
	public void setClipChildren(boolean clipChildren)
	{
		// Ignore, since the header rows depend on not being clipped
	}

	/**
	 * Add a fixed view to appear at the top of the grid. If addHeaderView is
	 * called more than once, the views will appear in the order they were
	 * added. Views added using this call can take focus if they want.
	 *

	 * NOTE: Call this before calling setAdapter. This is so
	 * HeaderFooterGridView can wrap the supplied cursor with one that will also
	 * account for header views.
	 *
	 * @param v            The view to add.
	 * @param data         Data to associate with this view
	 * @param isSelectable whether the item is selectable
	 */
	public void addHeaderView(View v, Object data, boolean isSelectable)
	{
		ListAdapter adapter = getAdapter();

		if (adapter != null && !(adapter instanceof HeaderFooterViewGridAdapter))
		{
			throw new IllegalStateException(
					"Cannot add header view to grid -- setAdapter has already been called.");
		}

		FixedViewInfo info = new FixedViewInfo();
		FrameLayout fl = new FullWidthFixedViewLayout(getContext());
		fl.addView(v);
		info.view = v;
		info.viewContainer = fl;
		info.data = data;
		info.isSelectable = isSelectable;
		mHeaderViewInfos.add(info);

		// in the case of re-adding a header view, or adding one later on,
		// we need to notify the observer
		if (adapter != null)
		{
			((HeaderFooterViewGridAdapter) adapter).notifyDataSetChanged();
		}
	}

	/**
	 * Add a fixed view to appear at the top of the grid. If addHeaderView is
	 * called more than once, the views will appear in the order they were
	 * added. Views added using this call can take focus if they want.
	 *

	 * NOTE: Call this before calling setAdapter. This is so
	 * HeaderFooterGridView can wrap the supplied cursor with one that will also
	 * account for header views.
	 *
	 * @param v The view to add.
	 */
	public void addHeaderView(View v)
	{
		addHeaderView(v, null, true);
	}

	/**
	 * Add a fixed view to appear at the bottom of the grid. If addFooterView is
	 * called more than once, the views will appear in the order they were
	 * added. Views added using this call can take focus if they want.
	 *

	 * NOTE: Call this before calling setAdapter. This is so
	 * HeaderFooterGridView can wrap the supplied cursor with one that will also
	 * account for header views.
	 *
	 * @param v            The view to add.
	 * @param data         Data to associate with this view
	 * @param isSelectable whether the item is selectable
	 */
	public void addFooterView(View v, Object data, boolean isSelectable)
	{
		ListAdapter adapter = getAdapter();

		if (adapter != null && !(adapter instanceof HeaderFooterViewGridAdapter))
		{
			throw new IllegalStateException(
					"Cannot add footer view to grid -- setAdapter has already been called.");
		}

		FixedViewInfo info = new FixedViewInfo();
		FrameLayout fl = new FullWidthFixedViewLayout(getContext());
		fl.addView(v);
		info.view = v;
		info.viewContainer = fl;
		info.data = data;
		info.isSelectable = isSelectable;
		mFooterViewInfos.add(info);

		// in the case of re-adding a header view, or adding one later on,
		// we need to notify the observer
		if (adapter != null)
		{
			((HeaderFooterViewGridAdapter) adapter).notifyDataSetChanged();
		}
	}

	/**
	 * Add a fixed view to appear at the bottom of the grid. If addFooterView is
	 * called more than once, the views will appear in the order they were
	 * added. Views added using this call can take focus if they want.
	 *

	 * NOTE: Call this before calling setAdapter. This is so
	 * HeaderFooterGridView can wrap the supplied cursor with one that will also
	 * account for header views.
	 *
	 * @param v The view to add.
	 */
	public void addFooterView(View v)
	{
		addFooterView(v, null, true);
	}

	public int getHeaderViewCount()
	{
		return mHeaderViewInfos.size();
	}

	public int getFooterViewCount()
	{
		return mFooterViewInfos.size();
	}

	/**
	 * Removes a previously-added header view.
	 *
	 * @param v The view to remove
	 * @return true if the view was removed, false if the view was not a header
	 * view
	 */
	public boolean removeHeaderView(View v)
	{
		if (mHeaderViewInfos.size() > 0)
		{
			boolean result = false;
			ListAdapter adapter = getAdapter();
			if (adapter != null && ((HeaderFooterViewGridAdapter) adapter).removeHeader(v))
			{
				result = true;
			}
			removeFixedViewInfo(v, mHeaderViewInfos);
			return result;
		}
		return false;
	}

	/**
	 * Removes a previously-added footer view.
	 *
	 * @param v The view to remove
	 * @return true if the view was removed, false if the view was not a footer
	 * view
	 */
	public boolean removeFooterView(View v)
	{
		if (mFooterViewInfos.size() > 0)
		{
			boolean result = false;
			ListAdapter adapter = getAdapter();
			if (adapter != null && ((HeaderFooterViewGridAdapter) adapter).removeFooter(v))
			{
				result = true;
			}
			removeFixedViewInfo(v, mFooterViewInfos);
			return result;
		}
		return false;
	}

	private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where)
	{
		int len = where.size();
		for (int i = 0; i < len; ++i)
		{
			FixedViewInfo info = where.get(i);
			if (info.view == v)
			{
				where.remove(i);
				break;
			}
		}
	}

	@Override
	public void setAdapter(ListAdapter adapter)
	{
		if (mHeaderViewInfos.size() > 0 || mFooterViewInfos.size() > 0)
		{
			HeaderFooterViewGridAdapter hadapter = new HeaderFooterViewGridAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
			int numColumns = getNumColumns();
			if (numColumns > 1)
			{
				hadapter.setNumColumns(numColumns);
			}
			super.setAdapter(hadapter);
		}
		else
		{
			super.setAdapter(adapter);
		}
	}

	@Override
	public int getNumColumns()
	{
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
		{
			return super.getNumColumns();
		}

		// Return value for less than Honeycomb.
		return mNumColmuns;
	}

	@Override
	public void setNumColumns(int numColumns)
	{
		super.setNumColumns(numColumns);
		// Store specified value for less than Honeycomb.
		mRequestedNumColumns = numColumns;
	}

	/**
	 * A class that represents a fixed view in a list, for example a header at
	 * the top or a footer at the bottom.
	 */
	private static class FixedViewInfo
	{
		/**
		 * The view to add to the grid
		 */
		public View view;
		public ViewGroup viewContainer;
		/**
		 * The data backing the view. This is returned from
		 * {@link android.widget.ListAdapter#getItem(int)}.
		 */
		public Object data;
		/**
		 * true if the fixed view should be selectable in the grid
		 */
		public boolean isSelectable;
	}

	/**
	 * ListAdapter used when a HeaderFooterGridView has header views. This
	 * ListAdapter wraps another one and also keeps track of the header views
	 * and their associated data objects.
	 *

	 * This is intended as a base class; you will probably not need to use this
	 * class directly in your own code.
	 */
	private static class HeaderFooterViewGridAdapter implements WrapperListAdapter, Filterable
	{

		// This is used to notify the container of updates relating to number of
		// columns
		// or headers changing, which changes the number of placeholders needed
		private final DataSetObservable mDataSetObservable = new DataSetObservable();

		private final ListAdapter mAdapter;
		private final boolean mIsFilterable;
		// This ArrayList is assumed to NOT be null.
		ArrayList<FixedViewInfo> mHeaderViewInfos;

		ArrayList<FixedViewInfo> mFooterViewInfos;

		boolean mAreAllFixedViewsSelectable;
		private int mNumColumns = 1;

		public HeaderFooterViewGridAdapter(ArrayList<FixedViewInfo> headerViewInfos, ArrayList<FixedViewInfo> footerViewInfos, ListAdapter adapter)
		{
			mAdapter = adapter;
			mIsFilterable = adapter instanceof Filterable;

			if (headerViewInfos == null)
			{
				throw new IllegalArgumentException("headerViewInfos cannot be null");
			}
			if (footerViewInfos == null)
			{
				throw new IllegalArgumentException("footerViewInfos cannot be null");
			}
			mHeaderViewInfos = headerViewInfos;
			mFooterViewInfos = footerViewInfos;

			mAreAllFixedViewsSelectable = (areAllListInfosSelectable(mHeaderViewInfos) && areAllListInfosSelectable(mFooterViewInfos));
		}

		public int getHeadersCount()
		{
			return mHeaderViewInfos.size();
		}

		public int getFootersCount()
		{
			return mFooterViewInfos.size();
		}

		@Override
		public boolean isEmpty()
		{
			return (mAdapter == null || mAdapter.isEmpty()) && getHeadersCount() == 0 && getFootersCount() == 0;
		}

		public void setNumColumns(int numColumns)
		{
			if (numColumns < 1)
			{
				throw new IllegalArgumentException("Number of columns must be 1 or more");
			}
			if (mNumColumns != numColumns)
			{
				mNumColumns = numColumns;
				notifyDataSetChanged();
			}
		}

		private boolean areAllListInfosSelectable(ArrayList<FixedViewInfo> infos)
		{
			if (infos != null)
			{
				for (FixedViewInfo info : infos)
				{
					if (!info.isSelectable)
					{
						return false;
					}
				}
			}
			return true;
		}

		public boolean removeHeader(View v)
		{
			for (int i = 0; i < mHeaderViewInfos.size(); i++)
			{
				FixedViewInfo info = mHeaderViewInfos.get(i);
				if (info.view == v)
				{
					mHeaderViewInfos.remove(i);

					mAreAllFixedViewsSelectable = (areAllListInfosSelectable(mHeaderViewInfos) && areAllListInfosSelectable(mFooterViewInfos));

					mDataSetObservable.notifyChanged();
					return true;
				}
			}

			return false;
		}

		public boolean removeFooter(View v)
		{
			for (int i = 0; i < mFooterViewInfos.size(); i++)
			{
				FixedViewInfo info = mFooterViewInfos.get(i);
				if (info.view == v)
				{
					mFooterViewInfos.remove(i);

					mAreAllFixedViewsSelectable = (areAllListInfosSelectable(mHeaderViewInfos) && areAllListInfosSelectable(mFooterViewInfos));

					mDataSetObservable.notifyChanged();
					return true;
				}
			}

			return false;
		}

		@Override
		public int getCount()
		{
			if (mAdapter != null)
			{
				final int lastRowItemCount = (mAdapter.getCount() % mNumColumns);
				final int emptyItemCount = ((lastRowItemCount == 0) ? 0 : mNumColumns - lastRowItemCount);
				return (getHeadersCount() * mNumColumns) + mAdapter.getCount() + emptyItemCount + (getFootersCount() * mNumColumns);
			}
			else
			{
				return (getHeadersCount() * mNumColumns) + (getFootersCount() * mNumColumns);
			}
		}

		@Override
		public boolean areAllItemsEnabled()
		{
			if (mAdapter != null)
			{
				return mAreAllFixedViewsSelectable && mAdapter.areAllItemsEnabled();
			}
			else
			{
				return true;
			}
		}

		@Override
		public boolean isEnabled(int position)
		{
			// Header (negative positions will throw an
			// ArrayIndexOutOfBoundsException)
			int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders)
			{
				return (position % mNumColumns == 0)
						&& mHeaderViewInfos.get(position / mNumColumns).isSelectable;
			}

			// Adapter
			if (position < numHeadersAndPlaceholders + mAdapter.getCount())
			{
				final int adjPosition = position - numHeadersAndPlaceholders;
				int adapterCount = 0;
				if (mAdapter != null)
				{
					adapterCount = mAdapter.getCount();
					if (adjPosition < adapterCount)
					{
						return mAdapter.isEnabled(adjPosition);
					}
				}
			}

			// Empty item
			final int lastRowItemCount = (mAdapter.getCount() % mNumColumns);
			final int emptyItemCount = ((lastRowItemCount == 0) ? 0 : mNumColumns - lastRowItemCount);
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount)
			{
				return false;
			}

			// Footer
			int numFootersAndPlaceholders = getFootersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount + numFootersAndPlaceholders)
			{
				return (position % mNumColumns == 0)
						&& mFooterViewInfos.get((position - numHeadersAndPlaceholders - mAdapter.getCount() - emptyItemCount) / mNumColumns).isSelectable;
			}

			throw new ArrayIndexOutOfBoundsException(position);
		}

		@Override
		public Object getItem(int position)
		{
			// Header (negative positions will throw an
			// ArrayIndexOutOfBoundsException)
			int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders)
			{
				if (position % mNumColumns == 0)
				{
					return mHeaderViewInfos.get(position / mNumColumns).data;
				}
				return null;
			}

			// Adapter
			if (position < numHeadersAndPlaceholders + mAdapter.getCount())
			{
				final int adjPosition = position - numHeadersAndPlaceholders;
				int adapterCount = 0;
				if (mAdapter != null)
				{
					adapterCount = mAdapter.getCount();
					if (adjPosition < adapterCount)
					{
						return mAdapter.getItem(adjPosition);
					}
				}
			}

			// Empty item
			final int lastRowItemCount = (mAdapter.getCount() % mNumColumns);
			final int emptyItemCount = ((lastRowItemCount == 0) ? 0 : mNumColumns - lastRowItemCount);
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount)
			{
				return null;
			}

			// Footer
			int numFootersAndPlaceholders = getFootersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount + numFootersAndPlaceholders)
			{
				if (position % mNumColumns == 0)
				{
					return mFooterViewInfos.get((position - numHeadersAndPlaceholders - mAdapter.getCount() - emptyItemCount) / mNumColumns).data;
				}
			}

			throw new ArrayIndexOutOfBoundsException(position);
		}

		@Override
		public long getItemId(int position)
		{
			int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
			if (mAdapter != null)
			{
				if (position >= numHeadersAndPlaceholders && position < numHeadersAndPlaceholders + mAdapter.getCount())
				{
					int adjPosition = position - numHeadersAndPlaceholders;
					int adapterCount = mAdapter.getCount();
					if (adjPosition < adapterCount)
					{
						return mAdapter.getItemId(adjPosition);
					}
				}
			}
			return -1;
		}

		@Override
		public boolean hasStableIds()
		{
			if (mAdapter != null)
			{
				return mAdapter.hasStableIds();
			}
			return false;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// Header (negative positions will throw an
			// ArrayIndexOutOfBoundsException)
			int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders)
			{
				View headerViewContainer = mHeaderViewInfos
						.get(position / mNumColumns).viewContainer;
				if (position % mNumColumns == 0)
				{
					return headerViewContainer;
				}
				else
				{
					convertView = new View(parent.getContext());
					// We need to do this because GridView uses the height of
					// the last item
					// in a row to determine the height for the entire row.
					convertView.setVisibility(View.INVISIBLE);
					convertView.setMinimumHeight(headerViewContainer.getHeight());
					return convertView;
				}
			}

			// Adapter
			if (position < numHeadersAndPlaceholders + mAdapter.getCount())
			{
				final int adjPosition = position - numHeadersAndPlaceholders;
				int adapterCount = 0;
				if (mAdapter != null)
				{
					adapterCount = mAdapter.getCount();
					if (adjPosition < adapterCount)
					{
						return mAdapter.getView(adjPosition, convertView, parent);
					}
				}
			}

			// Empty item
			final int lastRowItemCount = (mAdapter.getCount() % mNumColumns);
			final int emptyItemCount = ((lastRowItemCount == 0) ? 0 : mNumColumns - lastRowItemCount);
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount)
			{
				// We need to do this because GridView uses the height of the
				// last item
				// in a row to determine the height for the entire row.
				// TODO Current implementation may not be enough in the case of
				// 3 or more column. May need to be careful on the INVISIBLE
				// View height.
				convertView = mAdapter.getView(mAdapter.getCount() - 1, convertView, parent);
				convertView.setVisibility(View.INVISIBLE);
				return convertView;
			}

			// Footer
			int numFootersAndPlaceholders = getFootersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders + mAdapter.getCount() + emptyItemCount + numFootersAndPlaceholders)
			{
				View footerViewContainer = mFooterViewInfos
						.get((position - numHeadersAndPlaceholders - mAdapter.getCount() - emptyItemCount) / mNumColumns).viewContainer;
				if (position % mNumColumns == 0)
				{
					footerViewContainer.setPadding(0, 130, 0, 0);
					return footerViewContainer;
				}
				else
				{
					convertView = new View(parent.getContext());
					// We need to do this because GridView uses the height of
					// the last item
					// in a row to determine the height for the entire row.
					convertView.setVisibility(View.INVISIBLE);
					convertView.setMinimumHeight(footerViewContainer.getHeight());
					return convertView;
				}
			}

			throw new ArrayIndexOutOfBoundsException(position);
		}

		@Override
		public int getItemViewType(int position)
		{
			int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
			if (position < numHeadersAndPlaceholders && (position % mNumColumns != 0))
			{
				// Placeholders get the last view type number
				return mAdapter != null ? mAdapter.getViewTypeCount() : 1;
			}
			if (mAdapter != null && position >= numHeadersAndPlaceholders && position < numHeadersAndPlaceholders + mAdapter.getCount())
			{
				int adjPosition = position - numHeadersAndPlaceholders;
				int adapterCount = mAdapter.getCount();
				if (adjPosition < adapterCount)
				{
					return mAdapter.getItemViewType(adjPosition);
				}
			}
			int numFootersAndPlaceholders = getFootersCount() * mNumColumns;
			if (mAdapter != null && position < numHeadersAndPlaceholders + mAdapter.getCount() + numFootersAndPlaceholders)
			{
				return mAdapter != null ? mAdapter.getViewTypeCount() : 1;
			}

			return AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER;
		}

		@Override
		public int getViewTypeCount()
		{
			if (mAdapter != null)
			{
				return mAdapter.getViewTypeCount() + 1;
			}
			return 2;
		}

		@Override
		public void registerDataSetObserver(DataSetObserver observer)
		{
			mDataSetObservable.registerObserver(observer);
			if (mAdapter != null)
			{
				mAdapter.registerDataSetObserver(observer);
			}
		}

		@Override
		public void unregisterDataSetObserver(DataSetObserver observer)
		{
			mDataSetObservable.unregisterObserver(observer);
			if (mAdapter != null)
			{
				mAdapter.unregisterDataSetObserver(observer);
			}
		}

		@Override
		public Filter getFilter()
		{
			if (mIsFilterable)
			{
				return ((Filterable) mAdapter).getFilter();
			}
			return null;
		}

		@Override
		public ListAdapter getWrappedAdapter()
		{
			return mAdapter;
		}

		public void notifyDataSetChanged()
		{
			mDataSetObservable.notifyChanged();
		}
	}

	private class FullWidthFixedViewLayout extends FrameLayout
	{
		public FullWidthFixedViewLayout(Context context)
		{
			super(context);
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
		{
			int targetWidth = GridView.this.getMeasuredWidth()
					- GridView.this.getPaddingLeft()
					- GridView.this.getPaddingRight();
			widthMeasureSpec = MeasureSpec.makeMeasureSpec(targetWidth,
                    MeasureSpec.getMode(widthMeasureSpec));
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}
}


text:
[Spring Social] is an extension of the [Spring Framework] that helps you connect your applications with Software-as-a-Service (SaaS) providers such as Facebook and Twitter.

## Features

- An extensible service provider framework that greatly simplifies the process of connecting local user accounts to hosted provider accounts.

- A connect controller that handles the authorization flow between your Java/Spring web application, a service provider, and your users.

- Java bindings to popular service provider APIs such as Facebook, Twitter, LinkedIn, TripIt, and GitHub.

- A sign-in controller that enables users to authenticate with your application by signing in through a service provider.

- Much more...

## Download Artifacts

See [downloading Spring artifacts] for Maven repository information. Unable to use Maven or other transitive dependency management tools? See [building a distribution with dependencies].

### Dependencies

```xml
<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-core</artifactId>
    <version>${org.springframework.social-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-web</artifactId>
    <version>${org.springframework.social-version}</version>
</dependency>
```

### Repositories

```xml
<repository>
    <id>spring-repo</id>
    <name>Spring Repository</name>
    <url>http://repo.spring.io/release</url>
</repository>

<repository>
    <id>spring-milestone</id>
    <name>Spring Milestone Repository</name>
    <url>http://repo.spring.io/milestone</url>
</repository>

<repository>
    <id>spring-snapshot</id>
    <name>Spring Snapshot Repository</name>
    <url>http://repo.spring.io/snapshot</url>
</repository>
```

## Spring Social Modules

The core [Spring Social] project does not contain provider modules. Each of the provider modules is in its own project. This enables those modules to progress and release on a separate schedule than Spring Social and be able to react more quickly to changes in the provider's API without the need to wait for a Spring Social release. The SaaS provider-specific projects can be cloned from the following GitHub URLs:

- Twitter: [GitHub][twitter-gh] | [Reference][twitter-ref] | [API][twitter-api]

- Facebook: [GitHub][facebook-gh] | [Reference][facebook-ref] | [API][facebook-api]

- LinkedIn: [GitHub][linkedin-gh] | [Reference][linkedin-ref] | [API][linkedin-api]

- TripIt: [GitHub][tripit-gh]

- GitHub: [GitHub][github-gh]

## Documentation

See the current [Javadoc] and [reference docs]. To get up and running quickly using the project, see the [Quick Start] guide.

## Sample Applications

Several example projects are available in the [samples repository].

## Issue Tracking

Report issues via the [Spring Social JIRA]. While JIRA is preferred, [GitHub issues] are also welcome. Understand our issue management process by reading about [the lifecycle of an issue].

## Build from Source

1. Clone the repository from GitHub:

    ```sh
    $ git clone https://github.com/spring-projects/spring-social.git
    ```

2. Navigate into the cloned repository directory:

    ```sh
    $ cd spring-social
    ```

3. The project uses [Gradle] to build:

    ```sh
    $ ./gradlew build
    ```

4. Install jars into your local Maven cache (optional)

    ```sh
    $ ./gradlew install
    ```

## Import Source into your IDE

### Eclipse

1. To generate Eclipse metadata (.classpath and .project files):

    ```sh
    $ ./gradlew eclipse
    ```

2. Once complete, you may then import the projects into Eclipse as usual:

   ```
   File -> Import -> Existing projects into workspace
   ```

> **Note**: [Spring Tool Suite][sts] has built in support for [Gradle], and you can simply import as Gradle projects.

### IDEA

Generate IDEA metadata (.iml and .ipr files):

```sh
$ ./gradlew idea
```

## Contributing

[Pull requests] are welcome. See the [contributor guidelines] for details.

## License

[Spring Social] is released under version 2.0 of the [Apache License].

[Spring Social]: http://projects.spring.io/spring-social
[Spring Framework]: http://projects.spring.io/spring-framework
[downloading Spring artifacts]: https://github.com/spring-projects/spring-framework/wiki/Downloading-Spring-artifacts
[building a distribution with dependencies]: https://github.com/spring-projects/spring-framework/wiki/Building-a-distribution-with-dependencies
[twitter-gh]: https://github.com/spring-projects/spring-social-twitter
[twitter-ref]: http://docs.spring.io/spring-social-twitter/docs/current/reference/htmlsingle/
[twitter-api]: http://docs.spring.io/spring-social-twitter/docs/current/apidocs/
[facebook-gh]: https://github.com/spring-projects/spring-social-facebook
[facebook-ref]: http://docs.spring.io/spring-social-facebook/docs/current/reference/htmlsingle/
[facebook-api]: http://docs.spring.io/spring-social-facebook/docs/current/apidocs/
[linkedin-gh]: https://github.com/spring-projects/spring-social-linkedin
[linkedin-ref]: http://docs.spring.io/spring-social-linkedin/docs/1.0.x/reference/htmlsingle/
[linkedin-api]: http://docs.spring.io/spring-social-linkedin/docs/1.0.x/api/
[tripit-gh]: https://github.com/spring-projects/spring-social-tripit
[github-gh]: https://github.com/spring-projects/spring-social-github
[Javadoc]: http://docs.spring.io/spring-social/docs/current/apidocs/
[reference docs]: http://docs.spring.io/spring-social/docs/current-SNAPSHOT/reference/htmlsingle/
[samples repository]: https://github.com/spring-projects/spring-social-samples
[Quick Start]: https://github.com/spring-projects/spring-social/wiki/Quick-Start
[Spring Social JIRA]: http://jira.springsource.org/browse/SOCIAL
[GitHub issues]: https://github.com/spring-projects/spring-social/issues
[the lifecycle of an issue]: https://github.com/spring-projects/spring-framework/wiki/The-Lifecycle-of-an-Issue
[Gradle]: http://gradle.org
[sts]: https://spring.io/tools
[Pull requests]: http://help.github.com/send-pull-requests
[contributor guidelines]: https://github.com/spring-projects/spring-framework/blob/master/CONTRIBUTING.md
[Apache License]: http://www.apache.org/licenses/LICENSE-2.0


text:
require File.dirname(__FILE__) + '/../test_helper.rb'

module ActsAsAuthenticTest
  class MagicColumnsTest < ActiveSupport::TestCase
    def test_validates_numericality_of_login_count
      u = User.new
      u.login_count = -1
      assert !u.valid?
      assert u.errors[:login_count].size > 0

      u.login_count = 0
      assert !u.valid?
      assert u.errors[:login_count].size == 0
    end

    def test_validates_numericality_of_failed_login_count
      u = User.new
      u.failed_login_count = -1
      assert !u.valid?
      assert u.errors[:failed_login_count].size > 0

      u.failed_login_count = 0
      assert !u.valid?
      assert u.errors[:failed_login_count].size == 0
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://localhost/mytofah/index.php/user

	 *	- or -
	 * 		http://localhost/mytofah/index.php/user/index

	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://localhost/mytofah/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/login/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */

	function __construct()// no spaces around parenthesis in function declarations
	{
		parent::__construct();
		$this->load->library('session');
		$info=$this->session->all_userdata();
		$this->load->model('model');

	}
	function checkvalid_username()
	{
		$user_name= $this->model->get_row('user_registration_table',array('username'=>$_REQUEST['name']));
		if(!empty($user_name))
		{
			echo 1;
		}
		else
		{
			echo 0;
		}

	}

	function checkvalid_email()
	{
		$email= $this->model->get_row('user_registration_table',array('email'=>$_REQUEST['email']));
		if(!empty($email))
		{
			echo 1;
		}
		else
		{
			echo 0;
		}

	}

 function login_email()
 {
	$email= $this->model->getcheck_emaillogin($_REQUEST['email']);
		if(!empty($email))
		{
			echo 1;
		}
		else
		{
			echo 0;
		}
 }

 function login_pass()
 {
	$email= $this->model->getcheck_passlogin($_REQUEST['email'],$_REQUEST['pass']);

		if(!empty($email))
		{
			echo 1;
		}
		else
		{
			echo 0;
		}
  }

  function logincheck()
{
     $error="";

         if(isset($_REQUEST['Email']))
         {
             $useremail=$_REQUEST['Email'];
			 $pass=$_REQUEST['Pass'];
             $data['login']=$this->model->get_login_data($useremail,$pass);
             if(count($data['login'])!=0)
             {
                 $userid=$data['login']->pk_user_id;

                $logininfo= array('session_id'=>session_id(),'useremail'=>$useremail,'user_id'=>$userid,'logged_in'=>TRUE,'login_times'=>$data['login']->no_of_times,'Item'=>'');

                $this->session->set_userdata($logininfo);

                $info = $this->session->all_userdata();

                /*$data=array('session_id'=>$info['session_id'],'ip_address'=>$_SERVER['REMOTE_ADDR'],
                'user_agent'=>$this->input->user_agent(),'last_activity'=>$info['__ci_last_regenerate'],'user_id'=>$info['user_id'],'siterole_id'=>$info['siterole_id']);

                $data['session']=$this->model->insert_data('usersessiontable',$data);*/
                $error='';
                echo "1";

             }
             else
             {
                 echo 0;
             }

         }

}

public function item_info(){
   if(isset($_REQUEST['itemset']))
       {
               $info=$this->session->all_userdata();
			   $count = $info['count'];
			   $i=1;
			   if($info['Item'] !=''){
			   foreach($info['Item'] as $item){

		          $iteminfo[$i]['itemname']=$item['itemname'];
                  $iteminfo[$i]['cost']=$item['cost'];
                  $iteminfo[$i]['weburl']=$item['weburl'];
                  $iteminfo[$i]['item_specification']=$item['item_specification'];
				  $i++;
		       }
			  }
			   $count++;
			   $iteminfo[$count]['itemname']=$_REQUEST['itemname'];
               $iteminfo[$count]['cost']=$_REQUEST['cost'];
               $iteminfo[$count]['weburl']=$_REQUEST['weburl'];
               $iteminfo[$count]['item_specification']=$_REQUEST['item_specification'];
			   $item = array('Item'=>$iteminfo,'count'=> $count);
               $this->session->set_userdata($item);
			   $info=$this->session->all_userdata();
			   echo 1;

       }
}

function personal_info()
{
       if(isset($_REQUEST['name']))
       {
               $personalinfo['your_name']=$_REQUEST['name'];
               $personalinfo['spouse_name']=$_REQUEST['spouse_name'];
               $personalinfo['wedding_date']=$_REQUEST['wedding_date'];
               $personalinfo['email']=$_REQUEST['email'];
               $personalinfo['venue']=$_REQUEST['venue'];
               $personalinfo['phone']=$_REQUEST['contact_no'];
               $personalinfo['couple_summary']=$_REQUEST['summary'];
			   $personalinfo['days']=$_REQUEST['days'];
			   $personalinfo['count'] = 0;
			   $personalinfo['Item'] = '';
               $this->session->set_userdata($personalinfo);
			   $info=$this->session->all_userdata();

       }
}

 function insert_registrydata()
    {
        if(isset($_REQUEST['regitration']))
        {
            $info=$this->session->all_userdata();

                  $insert['your_name']=$info['your_name'];
                  $insert['spouse_name']=$info['spouse_name'];
                  $insert['wedding_date']=date('Y-m-d',strtotime($info['wedding_date']));
                  $insert['venue']=$info['venue'];
                  $insert['email']=$info['email'];
                  $insert['phone']=$info['phone'];
                  $insert['couple_summary']=$info['couple_summary'];
                  $insert['fk_user_id']=$info['user_id'];
                  $insert['no_of_days']=$info['days'];
                  $this->db->insert('wedding_page_table',$insert);
                  $pageid=$this->db->insert_id();
             if($info['Item'] !=''){
               foreach($info['Item'] as $item)
               {

                  $insertitem['item_name']=$item['itemname'];
                  $insertitem['approx_cost']=$item['cost'];
                  $insertitem['web_url']=$item['weburl'];
                  $insertitem['item_specification']=$item['item_specification'];
                  $insertitem['fk_user_id']=$info['user_id'];
                  $insertitem['fk_wedding_page_id']=$pageid;
                  $this->db->insert('wishlist_item_table',$insertitem);
               }
             }
                  $Newinfo = array('login_times'=>1);
				  $this->session->set_userdata($Newinfo);
                  $update['no_of_times']=1;
                  $this->model->update('user_registration_table',$update,array('pk_user_id'=>$info['user_id']));
				  echo 1;

        }
    }

}


text:
from .elementfinder import ElementFinder

class TableElementFinder(object):

    def __init__(self, element_finder=None):
        if not element_finder:
            element_finder = ElementFinder()
        self._element_finder = element_finder

        self._locator_suffixes = {
            ('css', 'default'): [''],
            ('css', 'content'): [''],
            ('css', 'header'): [' th'],
            ('css', 'footer'): [' tfoot td'],
            ('css', 'row'): [' tr:nth-child(%s)'],
            ('css', 'col'): [' tr td:nth-child(%s)', ' tr th:nth-child(%s)'],

            ('jquery', 'default'): [''],
            ('jquery', 'content'): [''],
            ('jquery', 'header'): [' th'],
            ('jquery', 'footer'): [' tfoot td'],
            ('jquery', 'row'): [' tr:nth-child(%s)'],
            ('jquery', 'col'): [' tr td:nth-child(%s)', ' tr th:nth-child(%s)'],

            ('sizzle', 'default'): [''],
            ('sizzle', 'content'): [''],
            ('sizzle', 'header'): [' th'],
            ('sizzle', 'footer'): [' tfoot td'],
            ('sizzle', 'row'): [' tr:nth-child(%s)'],
            ('sizzle', 'col'): [' tr td:nth-child(%s)', ' tr th:nth-child(%s)'],

            ('xpath', 'default'): [''],
            ('xpath', 'content'): ['//*'],
            ('xpath', 'header'): ['//th'],
            ('xpath', 'footer'): ['//tfoot//td'],
            ('xpath', 'row'): ['//tr[%s]//*'],
            ('xpath', 'col'): ['//tr//*[self::td or self::th][%s]']
        };

    def find(self, browser, table_locator):
        locators = self._parse_table_locator(table_locator, 'default')
        return self._search_in_locators(browser, locators, None)

    def find_by_content(self, browser, table_locator, content):
        locators = self._parse_table_locator(table_locator, 'content')
        return self._search_in_locators(browser, locators, content)

    def find_by_header(self, browser, table_locator, content):
        locators = self._parse_table_locator(table_locator, 'header')
        return self._search_in_locators(browser, locators, content)

    def find_by_footer(self, browser, table_locator, content):
        locators = self._parse_table_locator(table_locator, 'footer')
        return self._search_in_locators(browser, locators, content)

    def find_by_row(self, browser, table_locator, col, content):
        locators = self._parse_table_locator(table_locator, 'row')
        locators = [locator % str(col) for locator in locators]
        return self._search_in_locators(browser, locators, content)

    def find_by_col(self, browser, table_locator, col, content):
        locators = self._parse_table_locator(table_locator, 'col')
        locators = [locator % str(col) for locator in locators]
        return self._search_in_locators(browser, locators, content)

    def _parse_table_locator(self, table_locator, location_method):
        if table_locator.startswith('xpath='):
            table_locator_type = 'xpath'
        elif table_locator.startswith('jquery=') or table_locator.startswith('sizzle='):
            table_locator_type = 'sizzle'
        else:
            if not table_locator.startswith('css='):
                table_locator = "css=table#%s" % table_locator
            table_locator_type = 'css'

        locator_suffixes = self._locator_suffixes[(table_locator_type, location_method)]

        return map(
            lambda locator_suffix: table_locator + locator_suffix,
            locator_suffixes)

    def _search_in_locators(self, browser, locators, content):
        for locator in locators:
            elements = self._element_finder.find(browser, locator)
            for element in elements:
                if content is None: return element
                element_text = element.text
                if element_text and content in element_text:
                    return element
        return None


text:
#include <aws/appsync/model/RelationalDatabaseSourceType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace AppSync
  {
    namespace Model
    {
      namespace RelationalDatabaseSourceTypeMapper
      {

        static const int RDS_HTTP_ENDPOINT_HASH = HashingUtils::HashString("RDS_HTTP_ENDPOINT");

        RelationalDatabaseSourceType GetRelationalDatabaseSourceTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == RDS_HTTP_ENDPOINT_HASH)
          {
            return RelationalDatabaseSourceType::RDS_HTTP_ENDPOINT;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<RelationalDatabaseSourceType>(hashCode);
          }

          return RelationalDatabaseSourceType::NOT_SET;
        }

        Aws::String GetNameForRelationalDatabaseSourceType(RelationalDatabaseSourceType enumValue)
        {
          switch(enumValue)
          {
          case RelationalDatabaseSourceType::RDS_HTTP_ENDPOINT:
            return "RDS_HTTP_ENDPOINT";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace RelationalDatabaseSourceTypeMapper
    } // namespace Model
  } // namespace AppSync
} // namespace Aws


text:
<?php

/**
 * Client for sending requests to InkRouter
 *
 * @author Kirill Gusakov
 */
class InkRouter_Client_RestClient implements InkRouter_Client_ClientInterface
{

    private static $CREATE_PATH = 'orders/%s';
    private static $UPDATE_PATH = 'orders/%s/%s';
    private static $CANCEL_PATH = 'orders/%s/%s';
    private static $HOLD_PATH = 'orders/hold/%s/%s';
    private static $REMOVE_HOLD_PATH = 'orders/remove_hold/%s/%s';

    /**
     * @var string
     */
    private $baseUrl;

    /**
     * Id associated with a certain print customer
     *
     * @var string
     */
    private $printCustomerId;

    /**
     * Key that is used by print customer for accessing InkRouter
     *
     * @var string
     */
    private $secretKey;

    /**
     *
     * @param string $baseUrl
     * @param string $printCustomerId
     * @param string $secretKey
     */
    public function __construct($baseUrl, $printCustomerId, $secretKey)
    {
        $this->baseUrl = $baseUrl;
        $this->printCustomerId = $printCustomerId;
        $this->secretKey = $secretKey;
    }

    /**
     * @param int $timestamp
     * @param InkRouter_Models_OrderInfo $orderInfo
     * @return mixed
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     */
    public function createOrder($timestamp, InkRouter_Models_OrderInfo $orderInfo)
    {
        return $this->sendRequest(sprintf($this->baseUrl . self::$CREATE_PATH, $timestamp), 'POST',
            array('Content-Type: application/xml'), $orderInfo->pack());
    }

    /**
     * @param int $orderId
     * @param int $timestamp
     * @param InkRouter_Models_OrderInfo $orderInfo
     * @return mixed
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     */
    public function updateOrder($orderId, $timestamp, InkRouter_Models_OrderInfo $orderInfo)
    {
        return $this->sendRequest(sprintf($this->baseUrl . self::$UPDATE_PATH, $orderId, $timestamp), 'PUT',
            array('Content-Type: application/xml'), $orderInfo->pack());
    }

    /**
     * @param int $orderId
     * @param int $timestamp
     * @return mixed
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     */
    public function placeOnHold($orderId, $timestamp)
    {
        return $this->sendRequest(sprintf($this->baseUrl . self::$HOLD_PATH, $orderId, $timestamp), 'PUT',
            array('Content-Type: text/plain'), '');
    }

    /**
     * @param int $orderId
     * @param int $timestamp
     * @return mixed
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     */
    public function removeHold($orderId, $timestamp)
    {
        return $this->sendRequest(sprintf($this->baseUrl . self::$REMOVE_HOLD_PATH, $orderId, $timestamp), 'PUT',
            array('Content-Type: text/plain'), '');
    }

    /**
     * @param int $orderId
     * @param int $timestamp
     * @return mixed
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     */
    public function cancelOrder($orderId, $timestamp)
    {
        return $this->sendRequest(sprintf($this->baseUrl . self::$CANCEL_PATH, $orderId, $timestamp), 'DELETE',
            array('Content-Type: text/plain'), '');
    }

    /**
     * @throws InkRouter_Exceptions_InkRouterNotAvailableException|InkRouter_Exceptions_AuthenticationException|InkRouter_Exceptions_ProcessingException|InkRouter_Exceptions_RejectionException
     **/
    private function sendRequest($url, $httpMethod, $headers, $body = null) {
        $curlResource = curl_init();
        if ($body !== null) {
            switch ($httpMethod) {
                case 'POST':
                    curl_setopt($curlResource, CURLOPT_POSTFIELDS, $body);
                    break;
                case 'PUT':
                    $fp = fopen('php://temp/maxmemory:256000', 'w');
                    fwrite($fp, $body);
                    fseek($fp, 0);
                    curl_setopt($curlResource, CURLOPT_BINARYTRANSFER, true);
                    curl_setopt($curlResource, CURLOPT_PUT, true);
                    curl_setopt($curlResource, CURLOPT_INFILE, $fp);
                    curl_setopt($curlResource, CURLOPT_INFILESIZE, strlen($body));
                    break;
                case 'DELETE':
                    curl_setopt($curlResource, CURLOPT_CUSTOMREQUEST, 'DELETE');
                    break;
            }
        }
        curl_setopt($curlResource, CURLOPT_URL, $url);
        curl_setopt($curlResource, CURLOPT_HTTPHEADER,
            array_merge($headers, array('Authorization: Basic ' . base64_encode("{$this->printCustomerId}:{$this->secretKey}"))));
        curl_setopt($curlResource, CURLOPT_RETURNTRANSFER, true);
        $responseMessage = curl_exec($curlResource);
        if ($responseMessage === false) {
            throw new InkRouter_Exceptions_InkRouterNotAvailableException();
        }

        $statusCode = curl_getinfo($curlResource, CURLINFO_HTTP_CODE);
        switch ($statusCode) {
            case 201:
                return $responseMessage;
            case 200:
                return $responseMessage;
            case 401:
                throw new InkRouter_Exceptions_AuthenticationException($responseMessage);
            case 500:
                throw new InkRouter_Exceptions_ProcessingException($responseMessage);
            case 409:
                throw new InkRouter_Exceptions_RejectionException($responseMessage);
            default:
                throw new InkRouter_Exceptions_ProcessingException('Unknown error occured');
        }
    }
}


text:
import { IDisposable } from 'xterm';

/**
 * Adds a disposabe listener to a node in the DOM, returning the disposable.
 * @param type The event type.
 * @param handler The handler for the listener.
 */
export function addDisposableListener(
  node: Element | Window | Document,
  type: string,
  handler: (e: any) => void,
  useCapture?: boolean
): IDisposable {
  node.addEventListener(type, handler, useCapture);
  return {
    dispose: () => {
      if (!handler) {
        // Already disposed
        return;
      }
      node.removeEventListener(type, handler, useCapture);
      node = null;
      handler = null;
    }
  };
}