text:
\hypertarget{classBuffer}{
\section{Buffer Class Reference}
\label{classBuffer}\index{Buffer@{Buffer}}
}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classBuffer_a7fa5687eb5aeee187cf30d3d89f98751}{Buffer} (uint8\_\-t $\ast$buffer, uint32\_\-t size)
\begin{DoxyCompactList}\small\item\em Constructor. \item\end{DoxyCompactList}\item
\hypertarget{classBuffer_a59b8743e4a5f731bdd0c4185c9ef263b}{
virtual \hyperlink{classBuffer_a59b8743e4a5f731bdd0c4185c9ef263b}{$\sim$Buffer} ()}
\label{classBuffer_a59b8743e4a5f731bdd0c4185c9ef263b}

\begin{DoxyCompactList}\small\item\em Destructor. \item\end{DoxyCompactList}\item
uint32\_\-t \hyperlink{classBuffer_a61907c35a945626945f77752ec9eaa80}{size} ()
\begin{DoxyCompactList}\small\item\em Method to get the buffer size. \item\end{DoxyCompactList}\item
int8\_\-t \hyperlink{classBuffer_a32f8331e3bce9db17da619458b424d7e}{getChar} ()
\begin{DoxyCompactList}\small\item\em Method to get a char from the buffer. After calling this method, the position in the buffer is increased by one byte. \item\end{DoxyCompactList}\item
int8\_\-t \hyperlink{classBuffer_aaa0175c5b1b72ced0b8edffa157110a5}{getChar} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a char from the the position passed to the function. After calling this method, the position in the buffer is increased by one byte. \item\end{DoxyCompactList}\item
uint8\_\-t \hyperlink{classBuffer_ab2d089a99d5bceb23d07d00bf745119a}{getUChar} ()
\begin{DoxyCompactList}\small\item\em Method to get an unsigned char from the buffer. After calling this method, the position in the buffer is increased by one byte. \item\end{DoxyCompactList}\item
uint8\_\-t \hyperlink{classBuffer_ac9e1313de63fd9815b38ace7bddc22d8}{getUChar} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an unsigned char from the the position passed to the function. After calling this method, the position in the buffer is increased by one byte. \item\end{DoxyCompactList}\item
int16\_\-t \hyperlink{classBuffer_a6c22f064293935062f5b61c1d924132d}{getShort} ()
\begin{DoxyCompactList}\small\item\em Method to get a short from the buffer. After calling this method, the position in the buffer is increased by two bytes. \item\end{DoxyCompactList}\item
int16\_\-t \hyperlink{classBuffer_a7eb9d5449cf6553dca6808775d7f5583}{getShort} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a short from the the position passed to the function. After calling this method, the position in the buffer is increased by two bytes. \item\end{DoxyCompactList}\item
uint16\_\-t \hyperlink{classBuffer_aafccc403480bca311e3837a691e696b4}{getUShort} ()
\begin{DoxyCompactList}\small\item\em Method to get an unsigned short from the buffer. After calling this method, the position in the buffer is increased by two bytes. \item\end{DoxyCompactList}\item
uint16\_\-t \hyperlink{classBuffer_a7951a4bc4a72c3af88c829903949d8c7}{getUShort} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an unsigned short from the the position passed to the function. After calling this method, the position in the buffer is increased by two bytes. \item\end{DoxyCompactList}\item
int32\_\-t \hyperlink{classBuffer_a7210e64bc79fe779306f0ba8f6d27ec0}{getInt} ()
\begin{DoxyCompactList}\small\item\em Method to get an integer from the buffer. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
int32\_\-t \hyperlink{classBuffer_af5a294ff99464564ef35bf5ab6b93cf3}{getInt} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an integer from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
uint32\_\-t \hyperlink{classBuffer_ad604cb82913c0453caa1f1ccad9ce860}{getUInt} ()
\begin{DoxyCompactList}\small\item\em Method to get an unsigned integer from the buffer. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
uint32\_\-t \hyperlink{classBuffer_aa05686a1ed29f3d32414d5a518033201}{getUInt} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an unsigned integer from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
float \hyperlink{classBuffer_a129bc6d11c9125c1d29c8894880e8605}{getFloat} ()
\begin{DoxyCompactList}\small\item\em Method to get a float from the buffer. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
float \hyperlink{classBuffer_a9f76bac5c7796adf6713c7cd0f561e43}{getFloat} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a float from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
double \hyperlink{classBuffer_a8a373ecd5d76516f8d3569c44adf3381}{getDouble} ()
\begin{DoxyCompactList}\small\item\em Method to get a double from the buffer. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\item
double \hyperlink{classBuffer_a091a79452a41a318824896d65dc2978a}{getDouble} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a double from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\item
long \hyperlink{classBuffer_a629d217da34e85943eb002910d2bb336}{getLong} ()
\begin{DoxyCompactList}\small\item\em Method to get a long from the buffer. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
long \hyperlink{classBuffer_a16bcd3bdb5ca1b9a12ca1dc76cf5f28b}{getLong} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a long from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
unsigned long \hyperlink{classBuffer_a7145a0142c6dc0c31e1cac08d4f49435}{getULong} ()
\begin{DoxyCompactList}\small\item\em Method to get an unsigned long from the buffer. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
unsigned long \hyperlink{classBuffer_a70db4c2d0ad70f73ed930a0581dbb1e4}{getULong} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an unsigned long from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes. \item\end{DoxyCompactList}\item
int64\_\-t \hyperlink{classBuffer_a515cf0ba59f1970b039362ef22cdcf6c}{getLongLong} ()
\begin{DoxyCompactList}\small\item\em Method to get a long long from the buffer. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\item
int64\_\-t \hyperlink{classBuffer_a5a6117d58e6abb0c7ea50d2c302a4d59}{getLongLong} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get a long long from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\item
uint64\_\-t \hyperlink{classBuffer_a569f8603324b4db03f4461932f7537cb}{getULongLong} ()
\begin{DoxyCompactList}\small\item\em Method to get an unsigned long long from the buffer. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\item
uint64\_\-t \hyperlink{classBuffer_af73ab97665bd53f27bd142234b2ee749}{getULongLong} (uint32\_\-t index)
\begin{DoxyCompactList}\small\item\em Method to get an unsigned long long from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes. \item\end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Private Member Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{classBuffer_a5c61830f4da68ec0052c027ef920efd0}{
{\footnotesize template$<$typename T $>$ }\\T {\bfseries read} ()}
\label{classBuffer_a5c61830f4da68ec0052c027ef920efd0}

\item
\hypertarget{classBuffer_aff15b0854a1abcb0763abfd910d78fde}{
{\footnotesize template$<$typename T $>$ }\\T {\bfseries read} (uint32\_\-t pos)}
\label{classBuffer_aff15b0854a1abcb0763abfd910d78fde}

\end{DoxyCompactItemize}
\subsection*{Private Attributes}
\begin{DoxyCompactItemize}
\item
\hypertarget{classBuffer_a54b634b41801d4c40fd7c503394f5f3a}{
std::vector$<$ uint8\_\-t $>$ \hyperlink{classBuffer_a54b634b41801d4c40fd7c503394f5f3a}{buffer\_\-}}
\label{classBuffer_a54b634b41801d4c40fd7c503394f5f3a}

\begin{DoxyCompactList}\small\item\em \hyperlink{classBuffer}{Buffer} data. \item\end{DoxyCompactList}\item
\hypertarget{classBuffer_a2cd7df689455fe31350a2af8e0c1f4ae}{
uint32\_\-t \hyperlink{classBuffer_a2cd7df689455fe31350a2af8e0c1f4ae}{position\_\-}}
\label{classBuffer_a2cd7df689455fe31350a2af8e0c1f4ae}

\begin{DoxyCompactList}\small\item\em Current index in the buffer. \item\end{DoxyCompactList}\item
\hypertarget{classBuffer_a7b5cbacdb5bac0aa0639f240dca3788b}{
uint32\_\-t \hyperlink{classBuffer_a7b5cbacdb5bac0aa0639f240dca3788b}{size\_\-}}
\label{classBuffer_a7b5cbacdb5bac0aa0639f240dca3788b}

\begin{DoxyCompactList}\small\item\em \hyperlink{classBuffer}{Buffer} size. \item\end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Constructor \& Destructor Documentation}
\hypertarget{classBuffer_a7fa5687eb5aeee187cf30d3d89f98751}{
\index{Buffer@{Buffer}!Buffer@{Buffer}}
\index{Buffer@{Buffer}!Buffer@{Buffer}}
\subsubsection[{Buffer}]{\setlength{\rightskip}{0pt plus 5cm}Buffer::Buffer (
\begin{DoxyParamCaption}
\item[{uint8\_\-t $\ast$}]{buffer, }
\item[{uint32\_\-t}]{size}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a7fa5687eb5aeee187cf30d3d89f98751}

Constructor.

\begin{DoxyParams}{Parameters}
{\em buffer} & \\
\hline
{\em size} & \\
\hline
\end{DoxyParams}

\subsection{Member Function Documentation}
\hypertarget{classBuffer_a32f8331e3bce9db17da619458b424d7e}{
\index{Buffer@{Buffer}!getChar@{getChar}}
\index{getChar@{getChar}!Buffer@{Buffer}}
\subsubsection[{getChar}]{\setlength{\rightskip}{0pt plus 5cm}int8\_\-t Buffer::getChar (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a32f8331e3bce9db17da619458b424d7e}

Method to get a char from the buffer. After calling this method, the position in the buffer is increased by one byte.

\begin{DoxyReturn}{Returns}
Data with a size of int8 (equivalent to char)
\end{DoxyReturn}
\hypertarget{classBuffer_aaa0175c5b1b72ced0b8edffa157110a5}{
\index{Buffer@{Buffer}!getChar@{getChar}}
\index{getChar@{getChar}!Buffer@{Buffer}}
\subsubsection[{getChar}]{\setlength{\rightskip}{0pt plus 5cm}int8\_\-t Buffer::getChar (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_aaa0175c5b1b72ced0b8edffa157110a5}

Method to get a char from the the position passed to the function. After calling this method, the position in the buffer is increased by one byte.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of int8 (equivalent to char)
\end{DoxyReturn}
\hypertarget{classBuffer_a8a373ecd5d76516f8d3569c44adf3381}{
\index{Buffer@{Buffer}!getDouble@{getDouble}}
\index{getDouble@{getDouble}!Buffer@{Buffer}}
\subsubsection[{getDouble}]{\setlength{\rightskip}{0pt plus 5cm}double Buffer::getDouble (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a8a373ecd5d76516f8d3569c44adf3381}

Method to get a double from the buffer. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyReturn}{Returns}
Data with a size of double.
\end{DoxyReturn}
\hypertarget{classBuffer_a091a79452a41a318824896d65dc2978a}{
\index{Buffer@{Buffer}!getDouble@{getDouble}}
\index{getDouble@{getDouble}!Buffer@{Buffer}}
\subsubsection[{getDouble}]{\setlength{\rightskip}{0pt plus 5cm}double Buffer::getDouble (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a091a79452a41a318824896d65dc2978a}

Method to get a double from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of double.
\end{DoxyReturn}
\hypertarget{classBuffer_a129bc6d11c9125c1d29c8894880e8605}{
\index{Buffer@{Buffer}!getFloat@{getFloat}}
\index{getFloat@{getFloat}!Buffer@{Buffer}}
\subsubsection[{getFloat}]{\setlength{\rightskip}{0pt plus 5cm}float Buffer::getFloat (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a129bc6d11c9125c1d29c8894880e8605}

Method to get a float from the buffer. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyReturn}{Returns}
Data with a size of float.
\end{DoxyReturn}
\hypertarget{classBuffer_a9f76bac5c7796adf6713c7cd0f561e43}{
\index{Buffer@{Buffer}!getFloat@{getFloat}}
\index{getFloat@{getFloat}!Buffer@{Buffer}}
\subsubsection[{getFloat}]{\setlength{\rightskip}{0pt plus 5cm}float Buffer::getFloat (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a9f76bac5c7796adf6713c7cd0f561e43}

Method to get a float from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of float.
\end{DoxyReturn}
\hypertarget{classBuffer_a7210e64bc79fe779306f0ba8f6d27ec0}{
\index{Buffer@{Buffer}!getInt@{getInt}}
\index{getInt@{getInt}!Buffer@{Buffer}}
\subsubsection[{getInt}]{\setlength{\rightskip}{0pt plus 5cm}int32\_\-t Buffer::getInt (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a7210e64bc79fe779306f0ba8f6d27ec0}

Method to get an integer from the buffer. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyReturn}{Returns}
Data with a size of int32 (equivalent to int)
\end{DoxyReturn}
\hypertarget{classBuffer_af5a294ff99464564ef35bf5ab6b93cf3}{
\index{Buffer@{Buffer}!getInt@{getInt}}
\index{getInt@{getInt}!Buffer@{Buffer}}
\subsubsection[{getInt}]{\setlength{\rightskip}{0pt plus 5cm}int32\_\-t Buffer::getInt (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_af5a294ff99464564ef35bf5ab6b93cf3}

Method to get an integer from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of int32 (equivalent to int)
\end{DoxyReturn}
\hypertarget{classBuffer_a629d217da34e85943eb002910d2bb336}{
\index{Buffer@{Buffer}!getLong@{getLong}}
\index{getLong@{getLong}!Buffer@{Buffer}}
\subsubsection[{getLong}]{\setlength{\rightskip}{0pt plus 5cm}long Buffer::getLong (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a629d217da34e85943eb002910d2bb336}

Method to get a long from the buffer. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyReturn}{Returns}
Data with a size of long.
\end{DoxyReturn}
\hypertarget{classBuffer_a16bcd3bdb5ca1b9a12ca1dc76cf5f28b}{
\index{Buffer@{Buffer}!getLong@{getLong}}
\index{getLong@{getLong}!Buffer@{Buffer}}
\subsubsection[{getLong}]{\setlength{\rightskip}{0pt plus 5cm}long Buffer::getLong (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a16bcd3bdb5ca1b9a12ca1dc76cf5f28b}

Method to get a long from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of long.
\end{DoxyReturn}
\hypertarget{classBuffer_a515cf0ba59f1970b039362ef22cdcf6c}{
\index{Buffer@{Buffer}!getLongLong@{getLongLong}}
\index{getLongLong@{getLongLong}!Buffer@{Buffer}}
\subsubsection[{getLongLong}]{\setlength{\rightskip}{0pt plus 5cm}int64\_\-t Buffer::getLongLong (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a515cf0ba59f1970b039362ef22cdcf6c}

Method to get a long long from the buffer. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyReturn}{Returns}
Data with a size of long long.
\end{DoxyReturn}
\hypertarget{classBuffer_a5a6117d58e6abb0c7ea50d2c302a4d59}{
\index{Buffer@{Buffer}!getLongLong@{getLongLong}}
\index{getLongLong@{getLongLong}!Buffer@{Buffer}}
\subsubsection[{getLongLong}]{\setlength{\rightskip}{0pt plus 5cm}int64\_\-t Buffer::getLongLong (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a5a6117d58e6abb0c7ea50d2c302a4d59}

Method to get a long long from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of long long.
\end{DoxyReturn}
\hypertarget{classBuffer_a6c22f064293935062f5b61c1d924132d}{
\index{Buffer@{Buffer}!getShort@{getShort}}
\index{getShort@{getShort}!Buffer@{Buffer}}
\subsubsection[{getShort}]{\setlength{\rightskip}{0pt plus 5cm}int16\_\-t Buffer::getShort (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a6c22f064293935062f5b61c1d924132d}

Method to get a short from the buffer. After calling this method, the position in the buffer is increased by two bytes.

\begin{DoxyReturn}{Returns}
Data with a size of int16 (equivalent to short)
\end{DoxyReturn}
\hypertarget{classBuffer_a7eb9d5449cf6553dca6808775d7f5583}{
\index{Buffer@{Buffer}!getShort@{getShort}}
\index{getShort@{getShort}!Buffer@{Buffer}}
\subsubsection[{getShort}]{\setlength{\rightskip}{0pt plus 5cm}int16\_\-t Buffer::getShort (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a7eb9d5449cf6553dca6808775d7f5583}

Method to get a short from the the position passed to the function. After calling this method, the position in the buffer is increased by two bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of int16 (equivalent to short)
\end{DoxyReturn}
\hypertarget{classBuffer_ac9e1313de63fd9815b38ace7bddc22d8}{
\index{Buffer@{Buffer}!getUChar@{getUChar}}
\index{getUChar@{getUChar}!Buffer@{Buffer}}
\subsubsection[{getUChar}]{\setlength{\rightskip}{0pt plus 5cm}uint8\_\-t Buffer::getUChar (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_ac9e1313de63fd9815b38ace7bddc22d8}

Method to get an unsigned char from the the position passed to the function. After calling this method, the position in the buffer is increased by one byte.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of unsigned int8 (equivalent to unsigned char)
\end{DoxyReturn}
\hypertarget{classBuffer_ab2d089a99d5bceb23d07d00bf745119a}{
\index{Buffer@{Buffer}!getUChar@{getUChar}}
\index{getUChar@{getUChar}!Buffer@{Buffer}}
\subsubsection[{getUChar}]{\setlength{\rightskip}{0pt plus 5cm}uint8\_\-t Buffer::getUChar (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_ab2d089a99d5bceb23d07d00bf745119a}

Method to get an unsigned char from the buffer. After calling this method, the position in the buffer is increased by one byte.

\begin{DoxyReturn}{Returns}
Data with a size of unsigned int8 (equivalent to unsigned char)
\end{DoxyReturn}
\hypertarget{classBuffer_ad604cb82913c0453caa1f1ccad9ce860}{
\index{Buffer@{Buffer}!getUInt@{getUInt}}
\index{getUInt@{getUInt}!Buffer@{Buffer}}
\subsubsection[{getUInt}]{\setlength{\rightskip}{0pt plus 5cm}uint32\_\-t Buffer::getUInt (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_ad604cb82913c0453caa1f1ccad9ce860}

Method to get an unsigned integer from the buffer. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyReturn}{Returns}
Data with a size of unsigned int32 (equivalent to unsigned int)
\end{DoxyReturn}
\hypertarget{classBuffer_aa05686a1ed29f3d32414d5a518033201}{
\index{Buffer@{Buffer}!getUInt@{getUInt}}
\index{getUInt@{getUInt}!Buffer@{Buffer}}
\subsubsection[{getUInt}]{\setlength{\rightskip}{0pt plus 5cm}uint32\_\-t Buffer::getUInt (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_aa05686a1ed29f3d32414d5a518033201}

Method to get an unsigned integer from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of unsigned int32 (equivalent to unsigned int)
\end{DoxyReturn}
\hypertarget{classBuffer_a7145a0142c6dc0c31e1cac08d4f49435}{
\index{Buffer@{Buffer}!getULong@{getULong}}
\index{getULong@{getULong}!Buffer@{Buffer}}
\subsubsection[{getULong}]{\setlength{\rightskip}{0pt plus 5cm}unsigned long Buffer::getULong (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a7145a0142c6dc0c31e1cac08d4f49435}

Method to get an unsigned long from the buffer. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyReturn}{Returns}
Data with a size of unsigned long.
\end{DoxyReturn}
\hypertarget{classBuffer_a70db4c2d0ad70f73ed930a0581dbb1e4}{
\index{Buffer@{Buffer}!getULong@{getULong}}
\index{getULong@{getULong}!Buffer@{Buffer}}
\subsubsection[{getULong}]{\setlength{\rightskip}{0pt plus 5cm}unsigned long Buffer::getULong (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a70db4c2d0ad70f73ed930a0581dbb1e4}

Method to get an unsigned long from the the position passed to the function. After calling this method, the position in the buffer is increased by four bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of unsigned long.
\end{DoxyReturn}
\hypertarget{classBuffer_af73ab97665bd53f27bd142234b2ee749}{
\index{Buffer@{Buffer}!getULongLong@{getULongLong}}
\index{getULongLong@{getULongLong}!Buffer@{Buffer}}
\subsubsection[{getULongLong}]{\setlength{\rightskip}{0pt plus 5cm}uint64\_\-t Buffer::getULongLong (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_af73ab97665bd53f27bd142234b2ee749}

Method to get an unsigned long long from the the position passed to the function. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of long long.
\end{DoxyReturn}
\hypertarget{classBuffer_a569f8603324b4db03f4461932f7537cb}{
\index{Buffer@{Buffer}!getULongLong@{getULongLong}}
\index{getULongLong@{getULongLong}!Buffer@{Buffer}}
\subsubsection[{getULongLong}]{\setlength{\rightskip}{0pt plus 5cm}uint64\_\-t Buffer::getULongLong (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a569f8603324b4db03f4461932f7537cb}

Method to get an unsigned long long from the buffer. After calling this method, the position in the buffer is increased by eight bytes.

\begin{DoxyReturn}{Returns}
Data with a size of long long.
\end{DoxyReturn}
\hypertarget{classBuffer_aafccc403480bca311e3837a691e696b4}{
\index{Buffer@{Buffer}!getUShort@{getUShort}}
\index{getUShort@{getUShort}!Buffer@{Buffer}}
\subsubsection[{getUShort}]{\setlength{\rightskip}{0pt plus 5cm}uint16\_\-t Buffer::getUShort (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_aafccc403480bca311e3837a691e696b4}

Method to get an unsigned short from the buffer. After calling this method, the position in the buffer is increased by two bytes.

\begin{DoxyReturn}{Returns}
Data with a size of unsigned int16 (equivalent to unsigned short)
\end{DoxyReturn}
\hypertarget{classBuffer_a7951a4bc4a72c3af88c829903949d8c7}{
\index{Buffer@{Buffer}!getUShort@{getUShort}}
\index{getUShort@{getUShort}!Buffer@{Buffer}}
\subsubsection[{getUShort}]{\setlength{\rightskip}{0pt plus 5cm}uint16\_\-t Buffer::getUShort (
\begin{DoxyParamCaption}
\item[{uint32\_\-t}]{index}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a7951a4bc4a72c3af88c829903949d8c7}

Method to get an unsigned short from the the position passed to the function. After calling this method, the position in the buffer is increased by two bytes.

\begin{DoxyParams}{Parameters}
{\em index} & position from which the data will be read.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
Data with a size of unsigned int16 (equivalent to unsigned short)
\end{DoxyReturn}
\hypertarget{classBuffer_a61907c35a945626945f77752ec9eaa80}{
\index{Buffer@{Buffer}!size@{size}}
\index{size@{size}!Buffer@{Buffer}}
\subsubsection[{size}]{\setlength{\rightskip}{0pt plus 5cm}uint32\_\-t Buffer::size (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}
\label{classBuffer_a61907c35a945626945f77752ec9eaa80}

Method to get the buffer size.

\begin{DoxyReturn}{Returns}
\hyperlink{classBuffer}{Buffer} size.
\end{DoxyReturn}

The documentation for this class was generated from the following files:\begin{DoxyCompactItemize}
\item
\hyperlink{Buffer_8h}{Buffer.h}\item
Buffer.cpp\end{DoxyCompactItemize}


text:
#include "util/sampling/uniform_sampler.h"

#include "mock_sampler.h"

namespace veles {
namespace util {

TEST(UniformSampler, testGetData) {
  auto data = prepare_data(100);
  UniformSampler sampler(data);
  sampler.setSampleSize(20);
  ASSERT_EQ(20u, sampler.getSampleSize());
  auto sample = sampler.data();
  char prev = sample[0], curr = sample[1];
  size_t i = 2;
  do {
    ASSERT_LT(prev, data[99]);
    ASSERT_LE(curr, data[99]);
    ASSERT_LT(prev, curr);
    prev = curr;
    curr = sample[i];
    ASSERT_EQ(curr, sampler[i]);
    i += 1;
  } while (i < 20);
}

TEST(UniformSampler, testOffsets) {
  auto data = prepare_data(100);
  UniformSampler sampler(data);
  sampler.setSampleSize(20);
  ASSERT_EQ(20u, sampler.getSampleSize());
  ASSERT_EQ(0u, sampler.getFileOffset(0));
  size_t prev = 0;
  ASSERT_EQ(0u, sampler.getSampleOffset(0));
  for (size_t i = 1; i < 20; ++i) {
    size_t curr = sampler.getFileOffset(i);
    ASSERT_LT(prev, curr);
    ASSERT_LE(curr, 99u);
    ASSERT_EQ(i, sampler.getSampleOffset(curr));
    // ISampler interface doesn't require this condition to be true for
    // any value. However this should be true for UniformSampler
    // implementation, except for first and last byte in sample (which have
    // values defined by getFileOffset() interface)
    if (curr < 19) {
      ASSERT_EQ(data[static_cast<int>(curr)], sampler[i]);
    }
  }
  prev = 0;
  for (size_t i = 0; i < 99; ++i) {
    size_t curr = sampler.getSampleOffset(i);
    ASSERT_GE(curr, 0u);
    ASSERT_LE(curr, 99u);
    ASSERT_LE(prev, curr);
    prev = curr;
  }
}

}  // namespace util
}  // namespace veles

redpajama_set_name: RedPajamaGithub


text:
`./build-myriad.sh` will run the gradle scripts from the root myriad folder and compile all necessary libraries.

## Running the Resource Manager Docker

```bash
docker run --name='myriad-resourcemanager' -t \
  -v /path/to/yarn-site.xml:/myriad-conf/yarn-site.xml \
  -v /path/to/myriad-config-default.yml:/myriad-conf/myriad-config-default.yml \
  -e HADOOP_NAMENODE="10.100.3.237:9000" \
  mesos/myriad-resourcemanager
  ```

### Available Environment Variables
You can also pass in custom values via docker run for the following env vars:
* HADOOP_HOME
* HADOOP_USER
* HADOOP_GROUP

#Configuration Guide#

In order for the ResourceManager to operate correctly, you will need to provide 2 configuration files:

* [myriad-config-default.yml](https://github.com/mesos/myriad/blob/phase1/myriad-scheduler/src/main/resources/myriad-config-default.yml)
* modified [yarn-site.xml](https://github.com/mesos/myriad/blob/phase1/docs/myriad-dev.md)

If you already had a working Vagrant instance, you will need to run `vagrant reload` in order to allow zookeeper and hdfs port-forwarding.

Still having problems connecting to Zookeeper? Be sure that your zkServer and MesosMaster values are correct in the [myriad-config-default.yml](https://github.com/mesos/myriad/blob/phase1/myriad-scheduler/src/main/resources/myriad-config-default.yml) file.


text:
package com.ibm.xsp.theme.bootstrap.renderkit.html.extlib.outline.tree;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import com.ibm.commons.util.StringUtil;
import com.ibm.xsp.extlib.tree.ITreeNode;
import com.ibm.xsp.extlib.util.ExtLibUtil;
import com.ibm.xsp.renderkit.html_basic.HtmlRendererUtil;
import com.ibm.xsp.renderkit.html_extended.RenderUtil;
import com.ibm.xsp.util.JSUtil;

import com.ibm.xsp.theme.bootstrap.renderkit.html.extlib.util.NavButtonRenderer;

public class DropDownButtonRenderer extends NavButtonRenderer {

    private static final long serialVersionUID = 1L;

    protected static final int PROP_DROPDOWN_BUTTON_CLASS       = 0;

    public DropDownButtonRenderer() {
    }

    @Override
    protected Object getProperty(int prop) {
        switch(prop) {
            case PROP_DROPDOWN_BUTTON_CLASS:   return "btn btn-default"; // $NON-NLS-1$
        }
        return null;
    }

    @Override
	protected boolean buttonGroup() {
        return false;
    }

    @Override
    protected void startRenderContainer(FacesContext context, ResponseWriter writer, TreeContextImpl tree) throws IOException {
        int depth = tree.getDepth();
        if(depth==1) {
            writer.startElement("div",null); // $NON-NLS-1$
            writer.writeAttribute("class", "btn-group", null); // $NON-NLS-1$ $NON-NLS-2$
        } else {
            super.startRenderContainer(context, writer, tree);
        }
    }

    @Override
    protected void endRenderContainer(FacesContext context, ResponseWriter writer, TreeContextImpl tree) throws IOException {
        int depth = tree.getDepth();
        if(depth==1) {
            writer.endElement("div"); // $NON-NLS-1$
            writer.write('\n');
        } else {
            super.endRenderContainer(context, writer, tree);
        }
    }

    @Override
    protected void renderEntryNode(FacesContext context, ResponseWriter writer, TreeContextImpl tree) throws IOException {
        int depth = tree.getDepth();
        if(depth==2) {
            boolean enabled = tree.getNode().isEnabled();
            boolean selected = tree.getNode().isSelected();
            renderPopupButton(context, writer, tree, enabled, selected);
        } else {
            super.renderEntryNode(context, writer, tree);
        }
    }

    @Override
    protected String getItemTag() {
        return "li"; // $NON-NLS-1$
    }
    @Override
    protected String getItemStyleClass(TreeContextImpl tree, boolean enabled, boolean selected) {
        if(tree.getDepth()==2) {
            return "btn-group"; // $NON-NLS-1$
        }
        return super.getItemStyleClass(tree, enabled, selected);
    }

    protected void renderPopupButton(FacesContext context, ResponseWriter writer, TreeContextImpl tree, boolean enabled, boolean selected) throws IOException {
        boolean popup = tree.getNode().getType()==ITreeNode.NODE_CONTAINER;

        writer.startElement("div",null); //$NON-NLS-1$
        writer.writeAttribute("class", "btn-group", null); // $NON-NLS-1$ $NON-NLS-2$

        writer.startElement("button",null); //$NON-NLS-1$
        writer.writeAttribute("type", "button", null); // $NON-NLS-1$ $NON-NLS-2$

        String style = tree.getNode().getStyle();
        if(StringUtil.isNotEmpty(style)) {
            writer.writeAttribute("style", style, "style"); // $NON-NLS-1$ $NON-NLS-2$
        }

        String styleClass = ExtLibUtil.concatStyleClasses(tree.getNode().getStyleClass(),(String)getProperty(PROP_DROPDOWN_BUTTON_CLASS));

        if(popup) {
            // A popup button requires an id
            String clientId = tree.getClientId(context,"ab",1); // $NON-NLS-1$
            if(StringUtil.isNotEmpty(clientId)) {
                writer.writeAttribute("id", clientId, null); // $NON-NLS-1$
            }
            styleClass = ExtLibUtil.concatStyleClasses(styleClass, "dropdown-toggle"); //$NON-NLS-1$
            writer.writeAttribute("data-toggle","dropdown",null); // $NON-NLS-1$ $NON-NLS-2$
        }
        if(StringUtil.isNotEmpty(styleClass)) {
            writer.writeAttribute("class", styleClass, "class"); // $NON-NLS-1$ $NON-NLS-2$
        }

        String image = tree.getNode().getImage();
        boolean hasImage = StringUtil.isNotEmpty(image);
        if(hasImage) {
            writer.startElement("img",null); // $NON-NLS-1$
            if(StringUtil.isNotEmpty(image)) {
                image = HtmlRendererUtil.getImageURL(context, image);
                writer.writeAttribute("src",image,null); // $NON-NLS-1$
                String imageAlt = tree.getNode().getImageAlt();
                if (StringUtil.isNotEmpty(imageAlt)) {
                    writer.writeAttribute("alt",imageAlt,null); // $NON-NLS-1$
                }
                String imageHeight = tree.getNode().getImageHeight();
                if (StringUtil.isNotEmpty(imageHeight)) {
                    writer.writeAttribute("height",imageHeight,null); // $NON-NLS-1$
                }
                String imageWidth = tree.getNode().getImageWidth();
                if (StringUtil.isNotEmpty(imageWidth)) {
                    writer.writeAttribute("width",imageWidth,null); // $NON-NLS-1$
                }
            }
            writer.endElement("img"); // $NON-NLS-1$
        }

        // Add the action if necessary
        if(!popup && enabled) {
            String href = tree.getNode().getHref();
            String onclick = findNodeOnClick(tree);
            if (StringUtil.isNotEmpty(onclick)) {
                writer.writeAttribute("onclick", onclick, null); // $NON-NLS-1$
            } else if (StringUtil.isNotEmpty(href)) {
                StringBuilder b = new StringBuilder();
                b.append("window.location.href='"); // $NON-NLS-1$
                JSUtil.appendJavaScriptString(b,RenderUtil.formatLinkRef(context,href));
                b.append("'");
                writer.writeAttribute("onclick", b.toString(), null); // $NON-NLS-1$
            }
        }

        // Render the text
        String label = tree.getNode().getLabel();
        if(StringUtil.isNotEmpty(label)) {
            writer.writeText(label, "label"); // $NON-NLS-1$
        }

        if(popup) {
            writePopupImage(context, writer, tree);
        }

        writer.endElement("button");//$NON-NLS-1$
        JSUtil.writeln(writer);

        // Render the children
        renderChildren(context, writer, tree);

        writer.endElement("div");//$NON-NLS-1$
        JSUtil.writeln(writer);
    }

    @Override
    protected void renderEntryItemLinkAttributes(FacesContext context, ResponseWriter writer, TreeContextImpl tree, boolean enabled, boolean selected) throws IOException {
        String clazz = null;
        String styleClass = tree.getNode().getStyleClass();
        if(StringUtil.isNotEmpty(styleClass)) {
            clazz = ExtLibUtil.concatStyleClasses(clazz, styleClass);
        }

        String itemStyle = tree.getNode().getStyle();
        if(StringUtil.isNotEmpty(itemStyle)) {
            writer.writeAttribute("style",itemStyle,null); // $NON-NLS-1$
        }

        if(tree.getNode().getType()==ITreeNode.NODE_CONTAINER) {
            clazz = ExtLibUtil.concatStyleClasses(clazz, "dropdown-toggle");// $NON-NLS-1$
            writer.writeAttribute("data-toggle","dropdown",null); // $NON-NLS-1$ $NON-NLS-2$
            writer.writeAttribute("href", "#",  null); // $NON-NLS-1$ $NON-NLS-2$
        }

        if(StringUtil.isNotEmpty(clazz)) {
            writer.writeAttribute("class",clazz,null); // $NON-NLS-1$
        }
    }
}


text:
"""This module implements some common and new sparse training algorithms."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import re

import six

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.tpu.ops import tpu_ops
from tensorflow.python.training import learning_rate_decay
from tensorflow.python.training import optimizer as tf_optimizer
from tensorflow.python.training import training_util

def extract_number(token):
  """Strips the number from the end of the token if it exists.

  Args:
    token: str, s or s_d where d is a number: a float or int. `foo_.5`,
      `foo_foo.5`, `foo_0.5`, `foo_4` are all valid strings.

  Returns:
    float, d if exists otherwise 1.
  """
  regexp = re.compile(r'.*_(\d*\.?\d*)$')
  if regexp.search(token):
    return float(regexp.search(token).group(1))
  else:
    return 1.

class SparseSETOptimizerBase(tf_optimizer.Optimizer):
  """Implementation of dynamic sparsity optimizers.

  Implementation of SET.
  See https://www.nature.com/articles/s41467-018-04316-3
  This optimizer wraps a regular optimizer and performs updates on the masks
  according to schedule given.

  Attributes:
    optimizer: tf.train.Optimizer
    begin_step: int, first iteration where masks are updated.
    end_step: int, iteration after which no mask is updated.
    frequency: int, of mask update operations.
    drop_fraction: float, of connections to drop during each update.
    drop_fraction_anneal: str or None, if supplied used to anneal the drop
      fraction.
    use_locking: bool, passed to the super.
    grow_init: str, name of the method used to initialize new connections.
    name: bool, passed to the super.
    use_stateless: bool, if True stateless operations are used. This is
      important for multi-worker jobs not to diverge.
    stateless_seed_offset: int, added to the seed of stateless operations. Use
      this to create randomness without divergence across workers.
  """

  def __init__(self,
               optimizer,
               begin_step,
               end_step,
               frequency,
               drop_fraction=0.1,
               drop_fraction_anneal='constant',
               use_locking=False,
               grow_init='zeros',
               name='SparseSETOptimizer',
               use_stateless=True,
               stateless_seed_offset=0):
    super(SparseSETOptimizerBase, self).__init__(use_locking, name)
    self._optimizer = optimizer
    self._grow_init = grow_init
    self._drop_fraction_anneal = drop_fraction_anneal
    self._drop_fraction_initial_value = ops.convert_to_tensor(
        float(drop_fraction),
        name='%s_drop_fraction' % self._drop_fraction_anneal)
    self._begin_step = ops.convert_to_tensor(begin_step, name='begin_step')
    self._end_step = ops.convert_to_tensor(end_step, name='end_step')
    self._frequency = ops.convert_to_tensor(frequency, name='frequency')
    self._frequency_val = frequency
    self._use_stateless = use_stateless
    self._stateless_seed_offset = stateless_seed_offset

  def compute_gradients(self, loss, **kwargs):
    """Wraps the compute gradient of passed optimizer."""
    result = self._optimizer.compute_gradients(loss, **kwargs)
    return result

  def apply_gradients(self, grads_and_vars, global_step=None, name=None):
    """Wraps the original apply_gradient of the optimizer.

    Args:
      grads_and_vars: List of (gradient, variable) pairs as returned by
        `compute_gradients()`.
      global_step: Optional `Variable` to increment by one after the variables
        have been updated.
      name: Optional name for the returned operation.  Default to the name
        passed to the `Optimizer` constructor.

    Returns:
      An `Operation` that applies the specified gradients. If `global_step`
      was not None, that operation also increments `global_step`.
    """
    pre_op = self._before_apply_gradients(grads_and_vars)
    with ops.control_dependencies([pre_op]):
      optimizer_update = self._optimizer.apply_gradients(
          grads_and_vars, global_step=global_step, name=name)
    # We get the default one after calling the super.apply_gradient(), since
    # we want to preserve original behavior of the optimizer: don't increment
    # anything if no global_step is passed. But we need the global step for
    # the mask_update.
    global_step = (
        global_step if global_step is not None else
        training_util.get_or_create_global_step())
    self._global_step = global_step
    with ops.control_dependencies([optimizer_update]):
      return self.cond_mask_update_op(global_step, control_flow_ops.no_op)

  def _before_apply_gradients(self, grads_and_vars):
    """Called before applying gradients."""
    return control_flow_ops.no_op('before_apply_grad')

  def cond_mask_update_op(self, global_step, false_branch):
    """Creates the conditional mask update operation.

    All masks are updated when it is an update iteration
    (checked by self.is_mask_update_iter()).
    Arguments:
      global_step: tf.Variable, current training iteration.
      false_branch: function, called when it is not a mask update iteration.

    Returns:
      conditional update operation
    """
    # Initializing to -freq so that last_update_step+freq=0. This enables early
    # mask_updates.
    last_update_step = variable_scope.get_variable(
        'last_mask_update_step', [],
        initializer=init_ops.constant_initializer(
            -self._frequency_val, dtype=global_step.dtype),
        trainable=False,
        dtype=global_step.dtype)

    def mask_update_op():
      update_ops = []
      for mask, weights in zip(self.get_masks(), self.get_weights()):
        update_ops.append(self.generic_mask_update(mask, weights))

      with ops.control_dependencies(update_ops):
        assign_op = state_ops.assign(
            last_update_step, global_step, name='last_mask_update_step_assign')
        with ops.control_dependencies([assign_op]):
          return control_flow_ops.no_op('mask_update')

    maybe_update = control_flow_ops.cond(
        self.is_mask_update_iter(global_step, last_update_step), mask_update_op,
        false_branch)
    return maybe_update

  def get_weights(self):
    raise NotImplementedError

  def get_masks(self):
    raise NotImplementedError

  def get_masked_weights(self):
    raise NotImplementedError

  def is_mask_update_iter(self, global_step, last_update_step):
    """Function for checking if the current step is a mask update step.

    It also creates the drop_fraction op and assigns it to the self object.

    Args:
      global_step: tf.Variable(int), current training step.
      last_update_step: tf.Variable(int), holding the last iteration the mask is
        updated. Used to determine whether current iteration is a mask update
        step.

    Returns:
      bool, whether the current iteration is a mask_update step.
    """
    gs_dtype = global_step.dtype
    self._begin_step = math_ops.cast(self._begin_step, gs_dtype)
    self._end_step = math_ops.cast(self._end_step, gs_dtype)
    self._frequency = math_ops.cast(self._frequency, gs_dtype)
    is_step_within_update_range = math_ops.logical_and(
        math_ops.greater_equal(global_step, self._begin_step),
        math_ops.logical_or(
            math_ops.less_equal(global_step, self._end_step),
            # If _end_step is negative, we never stop updating the mask.
            # In other words we update the mask with given frequency until the
            # training ends.
            math_ops.less(self._end_step, 0)))
    is_update_step = math_ops.less_equal(
        math_ops.add(last_update_step, self._frequency), global_step)
    is_mask_update_iter_op = math_ops.logical_and(is_step_within_update_range,
                                                  is_update_step)
    self.drop_fraction = self.get_drop_fraction(global_step,
                                                is_mask_update_iter_op)
    return is_mask_update_iter_op

  def get_drop_fraction(self, global_step, is_mask_update_iter_op):
    """Returns a constant or annealing drop_fraction op."""
    if self._drop_fraction_anneal == 'constant':
      drop_frac = self._drop_fraction_initial_value
    elif self._drop_fraction_anneal == 'cosine':
      decay_steps = self._end_step - self._begin_step
      drop_frac = learning_rate_decay.cosine_decay(
          self._drop_fraction_initial_value,
          global_step,
          decay_steps,
          name='cosine_drop_fraction')
    elif self._drop_fraction_anneal.startswith('exponential'):
      exponent = extract_number(self._drop_fraction_anneal)
      div_dtype = self._drop_fraction_initial_value.dtype
      power = math_ops.divide(
          math_ops.cast(global_step - self._begin_step, div_dtype),
          math_ops.cast(self._end_step - self._begin_step, div_dtype),
      )
      drop_frac = math_ops.multiply(
          self._drop_fraction_initial_value,
          math_ops.pow(1 - power, exponent),
          name='%s_drop_fraction' % self._drop_fraction_anneal)
    else:
      raise ValueError('drop_fraction_anneal: %s is not valid' %
                       self._drop_fraction_anneal)
    return array_ops.where(is_mask_update_iter_op, drop_frac,
                           array_ops.zeros_like(drop_frac))

  def generic_mask_update(self, mask, weights, noise_std=1e-5):
    """True branch of the condition, updates the mask."""
    # Ensure that the weights are masked.
    masked_weights = mask * weights
    score_drop = math_ops.abs(masked_weights)
    # Add noise for slight bit of randomness.
    score_drop += self._random_normal(
        score_drop.shape,
        stddev=noise_std,
        dtype=score_drop.dtype,
        seed=(hash(weights.name + 'drop')))
    # Randomly revive n_prune many connections from non-existing connections.
    score_grow = self._random_uniform(
        weights.shape, seed=hash(weights.name + 'grow'))
    return self._get_update_op(score_drop, score_grow, mask, weights)

  def _get_update_op(self,
                     score_drop,
                     score_grow,
                     mask,
                     weights,
                     reinit_when_same=False):
    """Prunes+grows connections, all tensors same shape."""
    old_dtype = mask.dtype
    mask_casted = math_ops.cast(mask, dtypes.float32)
    n_total = array_ops.size(score_drop)
    n_ones = math_ops.cast(math_ops.reduce_sum(mask_casted), dtype=dtypes.int32)
    n_prune = math_ops.cast(
        math_ops.cast(n_ones, dtype=dtypes.float32) * self.drop_fraction,
        dtypes.int32)
    n_keep = n_ones - n_prune

    # Sort the entire array since the k needs to be constant for TPU.
    _, sorted_indices = nn_ops.top_k(
        array_ops.reshape(score_drop, [-1]), k=n_total)
    sorted_indices_ex = array_ops.expand_dims(sorted_indices, 1)
    # We will have zeros after having `n_keep` many ones.
    new_values = array_ops.where(
        math_ops.range(n_total) < n_keep,
        array_ops.ones_like(sorted_indices, dtype=mask_casted.dtype),
        array_ops.zeros_like(sorted_indices, dtype=mask_casted.dtype))
    mask1 = array_ops.scatter_nd(sorted_indices_ex, new_values,
                                 new_values.shape)
    # Flatten the scores
    score_grow = array_ops.reshape(score_grow, [-1])
    # Set scores of the enabled connections(ones) to min(s) - 1, so that they
    # have the lowest scores.
    score_grow_lifted = array_ops.where(
        math_ops.equal(mask1, 1),
        array_ops.ones_like(mask1) * (math_ops.reduce_min(score_grow) - 1),
        score_grow)
    _, sorted_indices = nn_ops.top_k(score_grow_lifted, k=n_total)
    sorted_indices_ex = array_ops.expand_dims(sorted_indices, 1)
    new_values = array_ops.where(
        math_ops.range(n_total) < n_prune,
        array_ops.ones_like(sorted_indices, dtype=mask_casted.dtype),
        array_ops.zeros_like(sorted_indices, dtype=mask_casted.dtype))
    mask2 = array_ops.scatter_nd(sorted_indices_ex, new_values,
                                 new_values.shape)
    # Ensure masks are disjoint.
    assert_op = control_flow_ops.Assert(
        math_ops.equal(math_ops.reduce_sum(mask1 * mask2), 0.), [mask1, mask2])

    with ops.control_dependencies([assert_op]):
      # Let's set the weights of the growed connections.
      mask2_reshaped = array_ops.reshape(mask2, mask.shape)
    # Set the values of the new connections.
    grow_tensor = self.get_grow_tensor(weights, self._grow_init)
    if reinit_when_same:
      # If dropped and grown, we re-initialize.
      new_connections = math_ops.equal(mask2_reshaped, 1)
    else:
      new_connections = math_ops.logical_and(
          math_ops.equal(mask2_reshaped, 1), math_ops.equal(mask_casted, 0))
    new_weights = array_ops.where(new_connections, grow_tensor, weights)
    weights_update = state_ops.assign(weights, new_weights)
    # Ensure there is no momentum value for new connections
    reset_op = self.reset_momentum(weights, new_connections)

    with ops.control_dependencies([weights_update, reset_op]):
      mask_combined = array_ops.reshape(mask1 + mask2, mask.shape)
    mask_combined = math_ops.cast(mask_combined, dtype=old_dtype)
    new_mask = state_ops.assign(mask, mask_combined)
    return new_mask

  def reset_momentum(self, weights, new_connections):
    reset_ops = []
    for s_name in self._optimizer.get_slot_names():
      # Momentum variable for example, we reset the aggregated values to zero.
      optim_var = self._optimizer.get_slot(weights, s_name)
      new_values = array_ops.where(new_connections,
                                   array_ops.zeros_like(optim_var), optim_var)
      reset_ops.append(state_ops.assign(optim_var, new_values))
    return control_flow_ops.group(reset_ops)

  def get_grow_tensor(self, weights, method):
    """Different ways to initialize new connections.

    Args:
      weights: tf.Tensor or Variable.
      method: str, available options: 'zeros', 'random_normal', 'random_uniform'
        and 'initial_value'

    Returns:
      tf.Tensor same shape and type as weights.

    Raises:
      ValueError, when the method is not valid.
    """
    if not isinstance(method, six.string_types):
      raise ValueError('Grow-Init: %s is not a string' % method)

    if method == 'zeros':
      grow_tensor = array_ops.zeros_like(weights, dtype=weights.dtype)
    elif method.startswith('initial_dist'):
      original_shape = weights.initial_value.shape
      divisor = extract_number(method)
      grow_tensor = array_ops.reshape(
          random_ops.random_shuffle(
              array_ops.reshape(weights.initial_value, [-1])),
          original_shape) / divisor
    elif method.startswith('random_normal'):
      stddev = math_ops.reduce_std(weights)
      divisor = extract_number(method)
      grow_tensor = self._random_normal(
          weights.shape,
          stddev=stddev,
          dtype=weights.dtype,
          seed=hash(weights.name + 'grow_init_n')) / divisor
    elif method.startswith('random_uniform'):
      mean = math_ops.reduce_mean(math_ops.abs(weights))
      divisor = extract_number(method)
      grow_tensor = self._random_uniform(
          weights.shape,
          minval=-mean,
          maxval=mean,
          dtype=weights.dtype,
          seed=hash(weights.name + 'grow_init_u')) / divisor
    else:
      raise ValueError('Grow-Init: %s is not a valid option.' % method)
    return grow_tensor

  def _random_uniform(self, *args, **kwargs):
    if self._use_stateless:
      c_seed = self._stateless_seed_offset + kwargs['seed']
      kwargs['seed'] = math_ops.cast(
          array_ops.stack([c_seed, self._global_step]), dtypes.int32)
      return stateless_random_ops.stateless_random_uniform(*args, **kwargs)
    else:
      return random_ops.random_uniform(*args, **kwargs)

  def _random_normal(self, *args, **kwargs):
    if self._use_stateless:
      c_seed = self._stateless_seed_offset + kwargs['seed']
      kwargs['seed'] = math_ops.cast(
          array_ops.stack([c_seed, self._global_step]), dtypes.int32)
      return stateless_random_ops.stateless_random_normal(*args, **kwargs)
    else:
      return random_ops.random_normal(*args, **kwargs)

class SparseRigLOptimizerBase(SparseSETOptimizerBase):
  """Sparse optimizer that grows connections with the pre-removal gradients.

  Attributes:
    optimizer: tf.train.Optimizer
    begin_step: int, first iteration where masks are updated.
    end_step: int, iteration after which no mask is updated.
    frequency: int, of mask update operations.
    drop_fraction: float, of connections to drop during each update.
    drop_fraction_anneal: str or None, if supplied used to anneal the drop
      fraction.
    use_locking: bool, passed to the super.
    grow_init: str, name of the method used to initialize new connections.
    init_avg_scale: float, used to scale the gradient when initializing the,
      momentum values of new connections. We hope this will improve training,
      compare to starting from 0 for the new connections. Set this to something
      between 0 and 1 / (1 - momentum). This is because in the current
      implementation of MomentumOptimizer, aggregated values converge to 1 / (1
      - momentum) with constant gradients.
    use_tpu: bool, if true the masked_gradients are aggregated.
    name: bool, passed to the super.
  """

  def __init__(self,
               optimizer,
               begin_step,
               end_step,
               frequency,
               drop_fraction=0.1,
               drop_fraction_anneal='constant',
               use_locking=False,
               grow_init='zeros',
               initial_acc_scale=0.,
               use_tpu=False,
               name='SparseRigLOptimizer',
               stateless_seed_offset=0):
    super(SparseRigLOptimizerBase, self).__init__(
        optimizer,
        begin_step,
        end_step,
        frequency,
        drop_fraction=drop_fraction,
        drop_fraction_anneal=drop_fraction_anneal,
        grow_init=grow_init,
        use_locking=use_locking,
        name='SparseRigLOptimizer',
        stateless_seed_offset=stateless_seed_offset)
    self._initial_acc_scale = initial_acc_scale
    self._use_tpu = use_tpu

  def set_masked_grads(self, grads, weights):
    if self._use_tpu:
      grads = [tpu_ops.cross_replica_sum(g) for g in grads]
    self._masked_grads = grads
    # Using names since better to hash.
    self._weight2masked_grads = {w.name: m for w, m in zip(weights, grads)}

  def compute_gradients(self, loss, **kwargs):
    """Wraps the compute gradient of passed optimizer."""
    grads_and_vars = self._optimizer.compute_gradients(loss, **kwargs)
    masked_grads_vars = self._optimizer.compute_gradients(
        loss, var_list=self.get_masked_weights())
    masked_grads = [g for g, _ in masked_grads_vars]
    self.set_masked_grads(masked_grads, self.get_weights())
    return grads_and_vars

  def apply_gradients(self, grads_and_vars, global_step=None, name=None):
    """Wraps the original apply_gradient of the optimizer.

    Args:
      grads_and_vars: List of (gradient, variable) pairs as returned by
        `compute_gradients()`.
      global_step: Optional `Variable` to increment by one after the variables
        have been updated.
      name: Optional name for the returned operation.  Default to the name
        passed to the `Optimizer` constructor.

    Returns:
      An `Operation` that applies the specified gradients. If `global_step`
      was not None, that operation also increments `global_step`.
    """
    pre_op = self._before_apply_gradients(grads_and_vars)
    with ops.control_dependencies([pre_op]):
      # Call this to create slots.
      _ = self._optimizer.apply_gradients(
          grads_and_vars, global_step=global_step, name=name)

      def apply_gradient_op():
        optimizer_update = self._optimizer.apply_gradients(
            grads_and_vars, global_step=global_step, name=name)
        return optimizer_update

      # We get the default one after calling the super.apply_gradient(), since
      # we want to preserve original behavior of the optimizer: don't increment
      # anything if no global_step is passed. But we need the global step for
      # the mask_update.
      global_step = (
          global_step if global_step is not None else
          training_util.get_or_create_global_step())
      self._global_step = global_step
      return self.cond_mask_update_op(global_step, apply_gradient_op)

  def generic_mask_update(self, mask, weights, noise_std=1e-5):
    """True branch of the condition, updates the mask."""
    # Ensure that the weights are masked.
    casted_mask = math_ops.cast(mask, dtype=dtypes.float32)
    masked_weights = casted_mask * weights
    score_drop = math_ops.abs(masked_weights)
    # Add noise for slight bit of randomness.
    score_drop += self._random_normal(
        score_drop.shape,
        stddev=noise_std,
        dtype=score_drop.dtype,
        seed=hash(weights.name + 'drop'))
    # Revive n_prune many connections using gradient.
    score_grow = math_ops.abs(self._weight2masked_grads[weights.name])
    with ops.control_dependencies([score_grow]):
      return self._get_update_op(score_drop, score_grow, mask, weights)

  def get_grow_tensor(self, weights, method):
    """Returns initialization for grown weights."""
    if method.startswith('grad_scale'):
      masked_grad = self._weight2masked_grads[weights.name]
      divisor = extract_number(method)
      grow_tensor = masked_grad / divisor
    elif method.startswith('grad_sign'):
      masked_grad_sign = math_ops.sign(self._weight2masked_grads[weights.name])
      divisor = extract_number(method)
      grow_tensor = masked_grad_sign / divisor
    else:
      grow_tensor = super(SparseRigLOptimizerBase,
                          self).get_grow_tensor(weights, method)
    return grow_tensor

  def reset_momentum(self, weights, new_connections):
    reset_ops = []
    for s_name in self._optimizer.get_slot_names():
      # Momentum variable for example, we reset the aggregated values to zero.
      optim_var = self._optimizer.get_slot(weights, s_name)
      accum_grad = (
          self._weight2masked_grads[weights.name] * self._initial_acc_scale)
      new_values = array_ops.where(new_connections, accum_grad, optim_var)
      reset_ops.append(state_ops.assign(optim_var, new_values))
    return control_flow_ops.group(reset_ops)


text:
module JacintheManagement
  # Open a logger
  # @param [String] name of log file
  def self.open_log(name = 'jacman.log')
    Dir.chdir(Core::DATADIR)
    log_dir = File.join(Core::DATADIR, 'jacman_logs')
    Utils.make_dir_if_necessary(log_dir, 0773)
    log_file = File.expand_path(name, log_dir)
    @logger = Logger.new(log_file, 'monthly')
    @logger.level = Logger::INFO
  end

  # Log the text (cleaned from HTML decoration)
  # @param [String] text to be logged
  def self.log(text)
    log_text = text.gsub(/<[^>]*>/, '').sub(/-+ /, '--').force_encoding('utf-8')
    @logger.info { log_text } unless log_text.empty?
  end

  # Log the erro message and backtrace
  # @param [Exception] error
  def self.err(error)
    @logger.error(error.message)
    @logger.error(error.backtrace.join("\n"))
  end
end


text:
from __future__ import absolute_import, unicode_literals

from .collection import *
from .collection_meta import *


text:
<?php

namespace Telegram\Bot;

use Telegram\Bot\Exceptions\TelegramSDKException;

/**
 * Class TelegramRequest.
 *
 * Builds Telegram Bot API Request Entity.
 */
class TelegramRequest
{
    /**
     * @var string|null The bot access token to use for this request.
     */
    protected $accessToken;

    /**
     * @var string The HTTP method for this request.
     */
    protected $method;

    /**
     * @var string The API endpoint for this request.
     */
    protected $endpoint;

    /**
     * @var array The headers to send with this request.
     */
    protected $headers = [];

    /**
     * @var array The parameters to send with this request.
     */
    protected $params = [];

    /**
     * @var array The files to send with this request.
     */
    protected $files = [];

    /**
     * Indicates if the request to Telegram will be asynchronous (non-blocking).
     *
     * @var bool
     */
    protected $isAsyncRequest = false;

    /**
     * Timeout of the request in seconds.
     *
     * @var int
     */
    protected $timeOut = 30;

    /**
     * Connection timeout of the request in seconds.
     *
     * @var int
     */
    protected $connectTimeOut = 10;

    /**
     * Creates a new Request entity.
     *
     * @param string|null $accessToken
     * @param string|null $method
     * @param string|null $endpoint
     * @param array|null  $params
     * @param bool        $isAsyncRequest
     * @param int         $timeOut
     * @param int         $connectTimeOut
     */
    public function __construct(
        $accessToken = null,
        $method = null,
        $endpoint = null,
        array $params = [],
        $isAsyncRequest = false,
        $timeOut = 60,
        $connectTimeOut = 10
    ) {
        $this->setAccessToken($accessToken);
        $this->setMethod($method);
        $this->setEndpoint($endpoint);
        $this->setParams($params);
        $this->setAsyncRequest($isAsyncRequest);
        $this->setTimeOut($timeOut);
        $this->setConnectTimeOut($connectTimeOut);
    }

    /**
     * Set the bot access token for this request.
     *
     * @param string
     *
     * @return TelegramRequest
     */
    public function setAccessToken($accessToken)
    {
        $this->accessToken = $accessToken;

        return $this;
    }

    /**
     * Return the bot access token for this request.
     *
     * @return string|null
     */
    public function getAccessToken()
    {
        return $this->accessToken;
    }

    /**
     * Validate that bot access token exists for this request.
     *
     * @throws TelegramSDKException
     */
    public function validateAccessToken()
    {
        $accessToken = $this->getAccessToken();
        if ($accessToken === null) {
            throw new TelegramSDKException('You must provide your bot access token to make any API requests.');
        }
    }

    /**
     * Set the HTTP method for this request.
     *
     * @param string
     *
     * @return TelegramRequest
     */
    public function setMethod($method)
    {
        $this->method = strtoupper($method);

        return $this;
    }

    /**
     * Return the HTTP method for this request.
     *
     * @return string
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * Validate that the HTTP method is set.
     *
     * @throws TelegramSDKException
     */
    public function validateMethod()
    {
        if (!$this->method) {
            throw new TelegramSDKException('HTTP method not specified.');
        }

        if (!in_array($this->method, ['GET', 'POST'])) {
            throw new TelegramSDKException('Invalid HTTP method specified.');
        }
    }

    /**
     * Set the endpoint for this request.
     *
     * @param string $endpoint
     *
     * @return TelegramRequest
     */
    public function setEndpoint($endpoint)
    {
        $this->endpoint = $endpoint;

        return $this;
    }

    /**
     * Return the API Endpoint for this request.
     *
     * @return string
     */
    public function getEndpoint()
    {
        return $this->endpoint;
    }

    /**
     * Set the params for this request.
     *
     * @param array $params
     *
     * @return TelegramRequest
     */
    public function setParams(array $params = [])
    {
        $this->params = array_merge($this->params, $params);

        return $this;
    }

    /**
     * Return the params for this request.
     *
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Set the headers for this request.
     *
     * @param array $headers
     *
     * @return TelegramRequest
     */
    public function setHeaders(array $headers)
    {
        $this->headers = array_merge($this->headers, $headers);

        return $this;
    }

    /**
     * Return the headers for this request.
     *
     * @return array
     */
    public function getHeaders()
    {
        $headers = $this->getDefaultHeaders();

        return array_merge($this->headers, $headers);
    }

    /**
     * Make this request asynchronous (non-blocking).
     *
     * @param $isAsyncRequest
     *
     * @return TelegramRequest
     */
    public function setAsyncRequest($isAsyncRequest)
    {
        $this->isAsyncRequest = $isAsyncRequest;

        return $this;
    }

    /**
     * Check if this is an asynchronous request (non-blocking).
     *
     * @return bool
     */
    public function isAsyncRequest()
    {
        return $this->isAsyncRequest;
    }

    /**
     * Only return params on POST requests.
     *
     * @return array
     */
    public function getPostParams()
    {
        if ($this->getMethod() === 'POST') {
            return $this->getParams();
        }

        return [];
    }

    /**
     * The default headers used with every request.
     *
     * @return array
     */
    public function getDefaultHeaders()
    {
        return [
            'User-Agent' => 'Telegram Bot PHP SDK v'.Api::VERSION.' - (https://github.com/irazasyed/telegram-bot-sdk)',
        ];
    }

    /**
     * @return int
     */
    public function getTimeOut()
    {
        return $this->timeOut;
    }

    /**
     * @param int $timeOut
     *
     * @return $this
     */
    public function setTimeOut($timeOut)
    {
        $this->timeOut = $timeOut;

        return $this;
    }

    /**
     * @return int
     */
    public function getConnectTimeOut()
    {
        return $this->connectTimeOut;
    }

    /**
     * @param int $connectTimeOut
     *
     * @return $this
     */
    public function setConnectTimeOut($connectTimeOut)
    {
        $this->connectTimeOut = $connectTimeOut;

        return $this;
    }
}


text:
package com.google.appengine.api.memcache.transcoders;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;

abstract class SpyMemcachedBaseTest extends BaseTest  {

  protected static final int DEFAULT_EXP = 0;

  protected InetSocketAddress serverAddress;
  protected String version;
  protected boolean isAscii;

  protected MemcachedClient client;

  protected SpyMemcachedBaseTest(String server, int port, String version, boolean isAscii) {
    this.serverAddress = new InetSocketAddress(server, port);
    this.version = version;
    this.isAscii = isAscii;
  }

  protected void setUp() throws Exception {
    ConnectionFactoryBuilder cfb = new ConnectionFactoryBuilder();
    cfb.setTranscoder(new SpymemcachedSerializingTranscoder());
    cfb.setProtocol(isAscii ? Protocol.TEXT : Protocol.BINARY);
    ArrayList<InetSocketAddress> servers = new ArrayList<>();
    servers.add(serverAddress);
    client = new MemcachedClient(cfb.build(), servers);
  }

  protected void tearDown() throws Exception {
    client.shutdown();
  }

  protected void expectTrue(boolean condition, String template, Object... values) {
    result.append(isAscii ? "ascii " : "binary ");
    super.expectTrue(condition, template, values);
  }

  protected String setRandom(Object value) throws Exception {
    String key = randomKey();
    client.set(key, DEFAULT_EXP, value);
    return key;
  }

  protected String setByKey(String key) throws Exception {
    String value = randomValue();
    client.set(key, DEFAULT_EXP, value);
    return value;
  }
}


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __DISCOVER_FUNCTIONS_H
#define __DISCOVER_FUNCTIONS_H

/* Includes ------------------------------------------------------------------*/
#include "stm8l15x.h"

#define STR_VERSION     tab[1] = 'V';tab[2] = '1'|DOT; tab[3] = '2'|DOT; tab[4] = '4'

/*#define STATE_VREF			0
#define STATE_ICC_RUN 	1
#define STATE_LPR_LCD 	2
#define STATE_LPR 			3
#define STATE_HALT 			4
#define I2C_READ	 			5
*/
#define MAX_STATE 			6

typedef enum { 	STATE_CHECKNDEFMESSAGE =	0,
								STATE_VREF	,
								STATE_TEMPMEAS
						} DemoState;

/* Theorically BandGAP 1.224volt */
#define VREF 		1.224L

/* UNCOMMENT the line below for use the VREFINT_Factory_CONV value*/
/* else we use the typical value defined in the datasheet (see Vdd_appli function in the file discover_functions.c) */

// #define VREFINT_FACTORY_CONV 1

/*
	ADC Converter
	LSBIdeal = VREF/4096 or VDA/4096
*/
#define ADC_CONV 	4096

/*
 VDD Factory for VREFINT measurement
*/
#define VDD_FACTORY 3.0L

/* The VREFINT_Factory_CONV byte represents the LSB of the VREFINT 12-bit ADC conversion result. The MSB have a fixed value: 0x6 */

#define VREFINT_Factory_CONV_ADDRESS ((uint8_t*)0x4910)

/*
	* The Typical value is 1.224
	* Min value 1.202
	* Max value	1.242
	* The value VREF is 0x668 to 0x69f
	*
*/
#define VREFINT_Factory_CONV_MSB 0x600 /* Le value MSB always 0x600 */
#define VREFINT_Factory_CONV_MIN 0x60 /* Low byte min */
#define VREFINT_Factory_CONV_MAX 0xA0 /* Low byte max */

#define MAX_CURRENT 	9999

/* AUTO TEST VALUE */
/*
#define VCC_MIN 	2915 // nominal Vcc/Vdd is 2.99V, allow 2.5% lower - Vref can be ~2% lower than 1.225
#define VCC_MAX 	3100
#define ICC_RUN_MIN 	1000
#define ICC_RUN_MAX 	1600 // typical ICC_RUN is ~1.3mA, allow ~15% bigger
#define ICC_HALT_MIN 	300
#define ICC_HALT_MAX 	800 // typical ICC_HALT is 0.35uA, allow 800 nA instead 1000  this low value is for select the best circuits
#define ICC_LP_MIN 	2500
#define ICC_LP_MAX 	4060 // typical ICC_LP is ~2.9uA, allow ~40% bigger
#define LSE_DELAY 	2000
*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
int _fctcpy(char name);
void convert_into_char(uint16_t number, uint16_t *p_tab);
//void LPR_init(void);
//void Halt_Init(void);
uint16_t Vref_measure(void);
//void Icc_measure(void);
//float Icc_measure_RUN(void);
//float Icc_measure_HALT(void);
//float Icc_measure_LPR(void);
//void Icc_measure_LPR_LCD(void);
//void auto_test(void);
//void Bias_measurement(void);
//void test_vdd(void);
//void test_icc_Run(void);
//void test_icc_LP(void);
//void test_icc_HALT(void);
//void display_MuAmp (uint16_t);
void FLASH_ProgramBias(uint8_t) ;
float Vdd_appli(void);

void	Display_Ram( void );

#endif /* __DISCOVER_FUNCTIONS_H*/

/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}

module Data.Git.Commit where

import           Bindings.Libgit2
import qualified Data.ByteString as BS
import           Data.ByteString.Unsafe
import           Data.Git.Common
import           Data.Git.Internal
import           Data.Git.Tree
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified Data.Text.ICU.Convert as U
import           Foreign.Marshal.Array
import qualified Prelude

default (Text)

data Commit = Commit { _commitInfo      :: Base Commit
                     , _commitAuthor    :: Signature
                     , _commitCommitter :: Signature
                     , _commitLog       :: Text
                     , _commitEncoding  :: Prelude.String
                     , _commitTree      :: ObjRef Tree
                     , _commitParents   :: [ObjRef Commit]
                     -- , _commitObj       :: ObjPtr C'git_commit
                     }

makeClassy ''Commit

instance Show Commit where
  show x = case x^.commitInfo.gitId of
    Pending _ -> "Commit"
    Stored y  -> "Commit#" ++ show y

instance Updatable Commit where
  getId x        = x^.commitInfo.gitId
  objectRepo x   = x^.commitInfo.gitRepo
  objectPtr x    = x^.commitInfo.gitObj
  update         = writeCommit Nothing
  lookupFunction = lookupCommit

newCommitBase :: Commit -> Base Commit
newCommitBase t =
  newBase (t^.commitInfo.gitRepo)
          (Pending (doWriteCommit Nothing >=> return . snd)) Nothing

-- | Create a new, empty commit.
--
--   Since empty commits cannot exist in Git, attempting to write out an empty
--   commit is a no-op.
createCommit :: Repository -> Commit
createCommit repo =
  Commit { _commitInfo     =
            newBase repo (Pending (doWriteCommit Nothing >=> return . snd))
                    Nothing
         , _commitAuthor    = createSignature
         , _commitCommitter = createSignature
         , _commitTree      = ObjRef (createTree repo)
         , _commitParents   = []
         , _commitLog       = T.empty
         , _commitEncoding  = "" }

lookupCommit :: Oid -> Repository -> IO (Maybe Commit)
lookupCommit oid repo =
  lookupObject' oid repo c'git_commit_lookup c'git_commit_lookup_prefix $
    \coid obj _ ->
      withForeignPtr obj $ \cobj -> do
        let c = castPtr cobj

        enc   <- c'git_commit_message_encoding c
        encs  <- if enc == nullPtr
                then return "UTF-8"
                else peekCString enc
        conv  <- U.open encs (Just False)

        msg   <- c'git_commit_message c   >>= BS.packCString
        auth  <- c'git_commit_author c    >>= packSignature conv
        comm  <- c'git_commit_committer c >>= packSignature conv
        toid  <- c'git_commit_tree_oid c  >>= wrapOidPtr

        pn    <- c'git_commit_parentcount c
        poids <- traverse wrapOidPtr =<<
                (sequence $
                 zipWith ($) (replicate (fromIntegral (toInteger pn))
                                        (c'git_commit_parent_oid c)) [0..pn])

        return Commit { _commitInfo      = newBase repo (Stored coid) (Just obj)
                      , _commitAuthor    = auth
                      , _commitCommitter = comm
                      , _commitTree      = toid
                      , _commitParents   = poids
                      , _commitLog       = U.toUnicode conv msg
                      , _commitEncoding  = encs }

withGitCommit :: Updatable b
              => ObjRef Commit -> b -> (Ptr C'git_commit -> IO a) -> IO a
withGitCommit cref obj f = do
  c' <- loadObject cref obj
  case c' of
    Nothing -> error "Cannot find Git commit in repository"
    Just co ->
      case co^.commitInfo.gitObj of
        Nothing  -> error "Cannot find Git commit id"
        Just co' -> withForeignPtr co' (f . castPtr)

-- | Write out a commit to its repository.  If it has already been written,
--   nothing will happen.
writeCommit :: Maybe Text -> Commit -> IO Commit
writeCommit _ c@(Commit { _commitInfo = Base { _gitId = Stored _ } }) =
  return c
writeCommit ref c = fst <$> doWriteCommit ref c

doWriteCommit :: Maybe Text -> Commit -> IO (Commit, COid)
doWriteCommit ref c = do
  coid <- withForeignPtr repo $ \repoPtr -> do
    coid <- mallocForeignPtr
    withForeignPtr coid $ \coid' -> do
      conv <- U.open (c^.commitEncoding) (Just True)
      BS.useAsCString (U.fromUnicode conv (c^.commitLog)) $ \message ->
        withRef ref $ \update_ref ->
          withSignature conv (c^.commitAuthor) $ \author ->
            withSignature conv (c^.commitCommitter) $ \committer ->
              withEncStr (c^.commitEncoding) $ \message_encoding ->
                withGitTree (c^.commitTree) c $ \commit_tree -> do
                  parentPtrs <- getCommitParentPtrs c
                  flip finally (freeCommits parentPtrs) $ do
                    parents <- newArray parentPtrs
                    r <- c'git_commit_create coid' repoPtr
                         update_ref author committer
                         message_encoding message commit_tree
                         (fromIntegral (length (c^.commitParents)))
                         parents
                    when (r < 0) $ throwIO CommitCreateFailed
                    return coid

  return (commitInfo.gitId .~ Stored (COid coid) $ c, COid coid)

  where
    repo = fromMaybe (error "Repository invalid")
                     (c^.commitInfo.gitRepo.repoObj)

    withRef refName =
      if isJust refName
      then unsafeUseAsCString (E.encodeUtf8 (fromJust refName))
      else flip ($) nullPtr

    withEncStr enc =
      if null enc
      then flip ($) nullPtr
      else withCString enc

    freeCommits = traverse c'git_commit_free

getCommitParents :: Commit -> IO [Commit]
getCommitParents c =
  traverse (\p -> do parent <- loadObject p c
                     case parent of
                       Nothing -> error "Cannot find Git commit"
                       Just p' -> return p')
           (c^.commitParents)

getCommitParentPtrs :: Commit -> IO [Ptr C'git_commit]
getCommitParentPtrs c =
  withForeignPtr (repositoryPtr (objectRepo c)) $ \repoPtr ->
    for (c^.commitParents) $ \p -> do
      Oid (COid oid) <- case p of
        IdRef coid -> return $ Oid coid
        ObjRef x   -> objectId x

      withForeignPtr oid $ \commit_id ->
        alloca $ \ptr -> do
          r <- c'git_commit_lookup ptr repoPtr commit_id
          when (r < 0) $ throwIO CommitLookupFailed
          peek ptr

-- Commit.hs


text:
require_relative 'spec_base'
require_relative 'fixtures/references'

describe 'An entity with references' do

  let (:a_shipment) {
    Shipment.build do |s|
      s.name = 'A referenced shipment'

      s.make_container do |c|
        c.kind = 'Large'
        c.make_package { |p| p.contents = 'Widgets'}
        c.make_package { |p| p.contents = 'Doohickeys'}
      end

      s.make_container do |c|
        c.kind = 'Small'
        c.make_package { |p| p.contents = 'Thingamabobs'}
        c.make_package { |p| p.contents = 'Stuff'}
      end
    end
  }

  let (:a_location) {
    Location.build { |l| l.name = 'tumbolia' }
  }

  let (:a_shipyard) { Shipyard.build do |s|
    s.name = 'The shipyard'
    s.location = a_location
    a_shipment.containers.each { |c| s.add_container(c) }
  end
  }

  before(:all) do
    transaction = UnitOfWork::Transaction.new(EntityMapper::Sequel)
    transaction.register_new(a_shipment)
    transaction.register_new(a_location)
    transaction.commit
  end

  it 'should have the correct attribute descriptors' do
    Shipyard.attribute_descriptors[:containers].class.should eq(BasicAttributes::ImmutableMultiReference)
    Shipyard.attribute_descriptors[:location].class.should eq(BasicAttributes::ImmutableReference)
  end

  it 'should have the correct methods' do
    a_shipyard.respond_to?(:location).should be_true
    a_shipyard.respond_to?(:containers).should be_true
    a_shipyard.respond_to?(:location=).should be_true
    a_shipyard.respond_to?(:'add_container').should be_true
  end

  it 'should create the correct tables' do
    shipyard_schema = $database.schema(:shipyards)
    shipyard_schema[0][0].should eq(:id)
    shipyard_schema[1][0].should eq(:active)
    shipyard_schema[2][0].should eq(:name)
    shipyard_schema[3][0].should eq(:location_id)

    container_schema = $database.schema(:shipyards_containers)
    container_schema[0][0].should eq(:id)
    container_schema[1][0].should eq(:shipyard_id)
    container_schema[2][0].should eq(:container_id)
  end

  it 'should save to and load from the database' do
    transaction = UnitOfWork::Transaction.new(EntityMapper::Sequel)
    transaction.register_new(a_shipyard)
    transaction.commit

    shipyard_row = $database[:shipyards].where(:id => 1).first
    shipyard_row[:name].should eq(a_shipyard.name)
    shipyard_row[:location_id].should eq(a_shipyard.location.id)

    shipyard_containers = $database[:shipyards_containers].where(:shipyard_id => 1)
    matched_containers = shipyard_containers.zip(a_shipyard.containers)
    matched_containers.length.should eq(a_shipyard.containers.length)
    matched_containers.each { |match| match[0][:container_id].should eq(match[1].id) }

    fetched_shipyard = Shipyard.fetch_by_id(1)
    fetched_shipyard.name.should eq(a_shipyard.name)

    fetched_shipyard.location.id.should eq(a_shipyard.location.id)

    matched_containers = fetched_shipyard.containers.zip(a_shipyard.containers)
    matched_containers.length.should eq(a_shipyard.containers.length)
    matched_containers.each { |match| match[0].id.should eq(match[1].id) }
  end

  it 'should serialize correctly to a Hash' do
    serialized = EntitySerializer.to_nested_hash(a_shipyard)

    serialized[:name].should eq('The shipyard')
    serialized[:location].should eq(Association::ImmutableEntityReference.new(a_location.id, Location))

    serialized[:containers].each_with_index do |c, i|
      c.should eq(Association::ImmutableEntityReference.new(a_shipment.containers[i].id, Container))
    end
  end
end