text:
/////////////////////////////////////////////////////////////////////////////
// Name:        src/html/m_tables.cpp
// Purpose:     wxHtml module for tables
// Author:      Vaclav Slavik
// Copyright:   (c) 1999 Vaclav Slavik
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#include "wx/wxprec.h"

#if wxUSE_HTML && wxUSE_STREAMS

#ifndef WX_PRECOMP
    #include "wx/wxcrtvararg.h"
    #include "wx/brush.h"
#endif

#include "wx/html/forcelnk.h"
#include "wx/html/m_templ.h"

#include "wx/html/htmlcell.h"

FORCE_LINK_ME(m_tables)

#define TABLE_BORDER_CLR_1  wxColour(0xC5, 0xC2, 0xC5)
#define TABLE_BORDER_CLR_2  wxColour(0x62, 0x61, 0x62)

//-----------------------------------------------------------------------------
// wxHtmlTableCell
//-----------------------------------------------------------------------------

struct colStruct
{
    int width, units;
            // width of the column either in pixels or percents
            // ('width' is the number, 'units' determines its meaning)
    int minWidth, maxWidth;
            // minimal/maximal column width. This is needed by HTML 4.0
            // layout algorithm and can be determined by trying to
            // layout table cells with width=1 and width=infinity
    int leftpos, pixwidth, maxrealwidth;
            // temporary (depends on actual width of table)
};

enum cellState
{
    cellSpan,
    cellUsed,
    cellFree
};

struct cellStruct
{
    wxHtmlContainerCell *cont;
    int colspan, rowspan;
    int minheight, valign;
    cellState flag;
    bool nowrap;
};

class wxHtmlTableCell : public wxHtmlContainerCell
{
protected:
    /* These are real attributes: */

    // number of columns; rows
    int m_NumCols, m_NumRows, m_NumAllocatedRows;
    // array of column information
    colStruct *m_ColsInfo;
    // 2D array of all cells in the table : m_CellInfo[row][column]
    cellStruct **m_CellInfo;
    // spaces between cells
    int m_Spacing;
    // cells internal indentation
    int m_Padding;

private:
    /* ...and these are valid only when parsing the table: */

    // number of actual column (ranging from 0..m_NumCols)
    int m_ActualCol, m_ActualRow;

    // default values (for table and row):
    wxColour m_tBkg, m_rBkg;
    wxString m_tValign, m_rValign;

    double m_PixelScale;

public:
    wxHtmlTableCell(wxHtmlContainerCell *parent, const wxHtmlTag& tag, double pixel_scale = 1.0);
    virtual ~wxHtmlTableCell();

    virtual void RemoveExtraSpacing(bool top, bool bottom) wxOVERRIDE;

    virtual void Layout(int w) wxOVERRIDE;

    void AddRow(const wxHtmlTag& tag);
    void AddCell(wxHtmlContainerCell *cell, const wxHtmlTag& tag);

    const wxColour& GetRowDefaultBackgroundColour() const { return m_rBkg; }

private:
    // Reallocates memory to given number of cols/rows
    // and changes m_NumCols/m_NumRows value to reflect this change
    // NOTE! You CAN'T change m_NumCols/m_NumRows before calling this!!
    void ReallocCols(int cols);
    void ReallocRows(int rows);

    // Computes minimal and maximal widths of columns. Needs to be called
    // only once, before first Layout().
    void ComputeMinMaxWidths();

    wxDECLARE_NO_COPY_CLASS(wxHtmlTableCell);
};

wxHtmlTableCell::wxHtmlTableCell(wxHtmlContainerCell *parent, const wxHtmlTag& tag, double pixel_scale)
 : wxHtmlContainerCell(parent)
{
    m_PixelScale = pixel_scale;
    m_ColsInfo = NULL;
    m_NumCols = m_NumRows = m_NumAllocatedRows = 0;
    m_CellInfo = NULL;
    m_ActualCol = m_ActualRow = -1;

    /* scan params: */
    if (tag.GetParamAsColour(wxT("BGCOLOR"), &m_tBkg))
        SetBackgroundColour(m_tBkg);
    m_tValign = tag.GetParam(wxT("VALIGN"));
    if (!tag.GetParamAsInt(wxT("CELLSPACING"), &m_Spacing))
        m_Spacing = 2;
    if (!tag.GetParamAsInt(wxT("CELLPADDING"), &m_Padding))
        m_Padding = 3;
    m_Spacing = (int)(m_PixelScale * (double)m_Spacing);
    m_Padding = (int)(m_PixelScale * (double)m_Padding);

    if(tag.HasParam(wxT("BORDER")))
    {
        if(tag.GetParam("BORDER").IsEmpty())
            m_Border = 1;
        else
            tag.GetParamAsInt(wxT("BORDER"), &m_Border);
    }
    if (m_Border == 1)
        SetBorder(TABLE_BORDER_CLR_1, TABLE_BORDER_CLR_2, m_Border); // special case see wxHtmlContainerCell::Draw
    else if (m_Border> 0)
        SetBorder(TABLE_BORDER_CLR_1, TABLE_BORDER_CLR_2, (int)(m_PixelScale * (double)m_Border));
    else
        m_Border = 0;

}

wxHtmlTableCell::~wxHtmlTableCell()
{
    if (m_ColsInfo) free(m_ColsInfo);
    if (m_CellInfo)
    {
        for (int i = 0; i < m_NumRows; i++)
            free(m_CellInfo[i]);
        free(m_CellInfo);
    }
}

void wxHtmlTableCell::RemoveExtraSpacing(bool WXUNUSED(top),
                                         bool WXUNUSED(bottom))
{
    // Don't remove any spacing in the table -- it's always desirable,
    // because it's part of table's definition.
    // (If wxHtmlContainerCell::RemoveExtraSpacing() was applied to tables,
    // then upper left cell of a table would be positioned above other cells
    // if the table was the first element on the page.)
}

void wxHtmlTableCell::ReallocCols(int cols)
{
    int i,j;

    for (i = 0; i < m_NumRows; i++)
    {
        m_CellInfo[i] = (cellStruct*) realloc(m_CellInfo[i], sizeof(cellStruct) * cols);
        for (j = m_NumCols; j < cols; j++)
            m_CellInfo[i][j].flag = cellFree;
    }

    m_ColsInfo = (colStruct*) realloc(m_ColsInfo, sizeof(colStruct) * cols);
    for (j = m_NumCols; j < cols; j++)
    {
           m_ColsInfo[j].width = 0;
           m_ColsInfo[j].units = wxHTML_UNITS_PERCENT;
           m_ColsInfo[j].minWidth = m_ColsInfo[j].maxWidth = -1;
    }

    m_NumCols = cols;
}

void wxHtmlTableCell::ReallocRows(int rows)
{
    int alloc_rows;
    for (alloc_rows = m_NumAllocatedRows; alloc_rows < rows;)
    {
        if (alloc_rows < 4)
            alloc_rows = 4;
        else if (alloc_rows < 4096)
            alloc_rows <<= 1;
        else
            alloc_rows += 2048;
    }

    if (alloc_rows > m_NumAllocatedRows)
    {
        m_CellInfo = (cellStruct**) realloc(m_CellInfo, sizeof(cellStruct*) * alloc_rows);
        m_NumAllocatedRows = alloc_rows;
    }

    for (int row = m_NumRows; row < rows ; ++row)
    {
        if (m_NumCols == 0)
            m_CellInfo[row] = NULL;
        else
        {
            m_CellInfo[row] = (cellStruct*) malloc(sizeof(cellStruct) * m_NumCols);
            for (int col = 0; col < m_NumCols; col++)
                m_CellInfo[row][col].flag = cellFree;
        }
    }
    m_NumRows = rows;
}

void wxHtmlTableCell::AddRow(const wxHtmlTag& tag)
{
    m_ActualCol = -1;
    // VS: real allocation of row entry is done in AddCell in order
    //     to correctly handle empty rows (i.e. "

")
    //     m_ActualCol == -1 indicates that AddCell has to allocate new row.

    // scan params:
    m_rBkg = m_tBkg;
    tag.GetParamAsColour(wxT("BGCOLOR"), &m_rBkg);
    if (!tag.GetParamAsString(wxT("VALIGN"), &m_rValign))
        m_rValign = m_tValign;
}

void wxHtmlTableCell::AddCell(wxHtmlContainerCell *cell, const wxHtmlTag& tag)
{
    // Is this cell in new row?
    // VS: we can't do it in AddRow, see my comment there
    if (m_ActualCol == -1)
    {
        if (m_ActualRow + 1 > m_NumRows - 1)
            ReallocRows(m_ActualRow + 2);
        m_ActualRow++;
    }

    // cells & columns:
    do
    {
        m_ActualCol++;
    } while ((m_ActualCol < m_NumCols) &&
             (m_CellInfo[m_ActualRow][m_ActualCol].flag != cellFree));

    if (m_ActualCol > m_NumCols - 1)
        ReallocCols(m_ActualCol + 1);

    int r = m_ActualRow, c = m_ActualCol;

    m_CellInfo[r][c].cont = cell;
    m_CellInfo[r][c].colspan = 1;
    m_CellInfo[r][c].rowspan = 1;
    m_CellInfo[r][c].flag = cellUsed;
    m_CellInfo[r][c].minheight = 0;
    m_CellInfo[r][c].valign = wxHTML_ALIGN_TOP;

    /* scan for parameters: */

    // id:
    wxString idvalue;
    if (tag.GetParamAsString(wxT("ID"), &idvalue))
    {
        cell->SetId(idvalue);
    }

    // width:
    {
        int width = 0;
        bool wpercent = false;
        if (tag.GetParamAsIntOrPercent(wxT("WIDTH"), &width, wpercent))
        {
            if (wpercent)
            {
                m_ColsInfo[c].width = width;
                m_ColsInfo[c].units = wxHTML_UNITS_PERCENT;
            }
            else
            {
                m_ColsInfo[c].width = (int)(m_PixelScale * (double)width);
                m_ColsInfo[c].units = wxHTML_UNITS_PIXELS;
            }
        }
    }

    // spanning:
    {
        tag.GetParamAsInt(wxT("COLSPAN"), &m_CellInfo[r][c].colspan);
        tag.GetParamAsInt(wxT("ROWSPAN"), &m_CellInfo[r][c].rowspan);

        // VS: the standard says this about col/rowspan:
        //     "This attribute specifies the number of rows spanned by the
        //     current cell. The default value of this attribute is one ("1").
        //     The value zero ("0") means that the cell spans all rows from the
        //     current row to the last row of the table." All mainstream
        //     browsers act as if 0==1, though, and so does wxHTML.
        if (m_CellInfo[r][c].colspan < 1)
            m_CellInfo[r][c].colspan = 1;
        if (m_CellInfo[r][c].rowspan < 1)
            m_CellInfo[r][c].rowspan = 1;

        if ((m_CellInfo[r][c].colspan > 1) || (m_CellInfo[r][c].rowspan > 1))
        {
            int i, j;

            if (r + m_CellInfo[r][c].rowspan > m_NumRows)
                ReallocRows(r + m_CellInfo[r][c].rowspan);
            if (c + m_CellInfo[r][c].colspan > m_NumCols)
                ReallocCols(c + m_CellInfo[r][c].colspan);
            for (i = r; i < r + m_CellInfo[r][c].rowspan; i++)
                for (j = c; j < c + m_CellInfo[r][c].colspan; j++)
                    m_CellInfo[i][j].flag = cellSpan;
            m_CellInfo[r][c].flag = cellUsed;
        }
    }

    //background color:
    {
        wxColour bk = m_rBkg;
        tag.GetParamAsColour(wxT("BGCOLOR"), &bk);
        if (bk.IsOk())
            cell->SetBackgroundColour(bk);
    }
    if (m_Border > 0)
        cell->SetBorder(TABLE_BORDER_CLR_2, TABLE_BORDER_CLR_1);

    // vertical alignment:
    {
        wxString valign;
        if (!tag.GetParamAsString(wxT("VALIGN"), &valign))
            valign = m_tValign;
        valign.MakeUpper();
        if (valign == wxT("TOP"))
            m_CellInfo[r][c].valign = wxHTML_ALIGN_TOP;
        else if (valign == wxT("BOTTOM"))
            m_CellInfo[r][c].valign = wxHTML_ALIGN_BOTTOM;
        else m_CellInfo[r][c].valign = wxHTML_ALIGN_CENTER;
    }

    // nowrap
    m_CellInfo[r][c].nowrap = tag.HasParam(wxT("NOWRAP"));

    cell->SetIndent(m_Padding, wxHTML_INDENT_ALL, wxHTML_UNITS_PIXELS);
}

void wxHtmlTableCell::ComputeMinMaxWidths()
{
    if (m_NumCols == 0 || m_ColsInfo[0].minWidth != wxDefaultCoord) return;

    m_MaxTotalWidth = 0;
    int percentage = 0;
    for (int c = 0; c < m_NumCols; c++)
    {
        for (int r = 0; r < m_NumRows; r++)
        {
            cellStruct& cell = m_CellInfo[r][c];
            if (cell.flag == cellUsed)
            {
                cell.cont->Layout(2*m_Padding + 1);
                int maxWidth = cell.cont->GetMaxTotalWidth();
                int width = cell.nowrap?maxWidth:cell.cont->GetWidth();
                width -= (cell.colspan-1) * m_Spacing;
                maxWidth -= (cell.colspan-1) * m_Spacing;
                // HTML 4.0 says it is acceptable to distribute min/max
                width /= cell.colspan;
                maxWidth /= cell.colspan;
                for (int j = 0; j < cell.colspan; j++) {
                    if (width > m_ColsInfo[c+j].minWidth)
                        m_ColsInfo[c+j].minWidth = width;
                    if (maxWidth > m_ColsInfo[c+j].maxWidth)
                        m_ColsInfo[c+j].maxWidth = maxWidth;
                }
            }
        }
        // Calculate maximum table width, required for nested tables
        if (m_ColsInfo[c].units == wxHTML_UNITS_PIXELS)
            m_MaxTotalWidth += wxMax(m_ColsInfo[c].width, m_ColsInfo[c].minWidth);
        else if ((m_ColsInfo[c].units == wxHTML_UNITS_PERCENT) && (m_ColsInfo[c].width != 0))
            percentage += m_ColsInfo[c].width;
        else
            m_MaxTotalWidth += m_ColsInfo[c].maxWidth;
    }

    if (percentage >= 100)
    {
        // Table would have infinite length
        // Make it ridiculous large
        m_MaxTotalWidth = 0xFFFFFF;
    }
    else
        m_MaxTotalWidth = m_MaxTotalWidth * 100 / (100 - percentage);

    m_MaxTotalWidth += (m_NumCols + 1) * m_Spacing +  2 * m_Border;
}

void wxHtmlTableCell::Layout(int w)
{
    ComputeMinMaxWidths();

    wxHtmlCell::Layout(w);

    /*

    WIDTH ADJUSTING :

    */

    if (m_WidthFloatUnits == wxHTML_UNITS_PERCENT)
    {
        if (m_WidthFloat < 0)
        {
            if (m_WidthFloat < -100)
                m_WidthFloat = -100;
            m_Width = (100 + m_WidthFloat) * w / 100;
        }
        else
        {
            if (m_WidthFloat > 100)
                m_WidthFloat = 100;
            m_Width = m_WidthFloat * w / 100;
        }
    }
    else
    {
        if (m_WidthFloat < 0) m_Width = w + m_WidthFloat;
        else m_Width = m_WidthFloat;
    }

    /*

    LAYOUT :

    */

    /* 1.  setup columns widths:

           The algorithm tries to keep the table size less than w if possible.
       */
    {
        int wpix = m_Width - (m_NumCols + 1) * m_Spacing - 2 * m_Border;  // Available space for cell content
        int i, j;

        // 1a. setup fixed-width columns:
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].units == wxHTML_UNITS_PIXELS)
            {
                m_ColsInfo[i].pixwidth = wxMax(m_ColsInfo[i].width,
                                               m_ColsInfo[i].minWidth);
                wpix -= m_ColsInfo[i].pixwidth;
            }

        // 1b. Calculate maximum possible width if line wrapping would be disabled
        // Recalculate total width if m_WidthFloat is zero to keep tables as small
        // as possible.
        int maxWidth = 0;
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0)
            {
                maxWidth += m_ColsInfo[i].maxWidth;
            }

        if (!m_WidthFloat)
        {
            // Recalculate table width since no table width was initially given
            int newWidth = m_Width - wpix +  maxWidth;

            // Make sure that floating-width columns will have the right size.
            // Calculate sum of all floating-width columns
            int percentage = 0;
            for (i = 0; i < m_NumCols; i++)
                if ((m_ColsInfo[i].units == wxHTML_UNITS_PERCENT) && (m_ColsInfo[i].width != 0))
                    percentage += m_ColsInfo[i].width;

            if (percentage >= 100)
                newWidth = w;
            else
                newWidth = newWidth * 100 / (100 - percentage);

            newWidth = wxMin(newWidth, w - (m_NumCols + 1) * m_Spacing - 2 * m_Border);
            wpix -= m_Width - newWidth;
            m_Width = newWidth;
        }

        // 1c. setup floating-width columns:
        int wtemp = wpix;
        for (i = 0; i < m_NumCols; i++)
            if ((m_ColsInfo[i].units == wxHTML_UNITS_PERCENT) && (m_ColsInfo[i].width != 0))
            {
                m_ColsInfo[i].pixwidth = wxMin(m_ColsInfo[i].width, 100) * wpix / 100;

                // Make sure to leave enough space for the other columns
                int minRequired = m_Border;
                for (j = 0; j < m_NumCols; j++)
                {
                    if ((m_ColsInfo[j].units == wxHTML_UNITS_PERCENT && j > i) ||
                        !m_ColsInfo[j].width)
                        minRequired += m_ColsInfo[j].minWidth;
                }
                m_ColsInfo[i].pixwidth = wxMax(wxMin(wtemp - minRequired, m_ColsInfo[i].pixwidth), m_ColsInfo[i].minWidth);

                wtemp -= m_ColsInfo[i].pixwidth;
            }
       wpix = wtemp; // minimum cells width

        // 1d. setup default columns (no width specification supplied):
        // The algorithm assigns calculates the maximum possible width if line
        // wrapping would be disabled and assigns column width as a fraction
        // based upon the maximum width of a column
        // FIXME: I'm not sure if this algorithm is conform to HTML standard,
        //        though it seems to be much better than the old one

        for (i = j = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0) j++;
        if (wpix < m_Border)
            wpix = m_Border;

        // Assign widths
        for (i = 0; i < m_NumCols; i++)
            if (m_ColsInfo[i].width == 0)
            {
                // Assign with, make sure not to drop below minWidth
                if (maxWidth)
                    m_ColsInfo[i].pixwidth = (int)(wpix * (m_ColsInfo[i].maxWidth / (float)maxWidth) + 0.5f);
                else
                    m_ColsInfo[i].pixwidth = wpix / j;

                // Make sure to leave enough space for the other columns
                int minRequired = 0;
                int r;
                for (r = i + 1; r < m_NumCols; r++)
                {
                    if (!m_ColsInfo[r].width)
                        minRequired += m_ColsInfo[r].minWidth;
                }
                const int pixwidthPrev = m_ColsInfo[i].pixwidth;
                m_ColsInfo[i].pixwidth = wxMax(wxMin(wpix - minRequired, m_ColsInfo[i].pixwidth), m_ColsInfo[i].minWidth);

                if (maxWidth)
                {
                    if (m_ColsInfo[i].pixwidth > pixwidthPrev)
                    {
                        int diff = m_ColsInfo[i].pixwidth - pixwidthPrev;
                        maxWidth += diff - m_ColsInfo[i].maxWidth;
                    }
                    else
                        maxWidth -= m_ColsInfo[i].maxWidth;
                }
                wpix -= m_ColsInfo[i].pixwidth;
            }
    }

    /* 2.  compute positions of columns: */
    {
        int wpos = m_Spacing + m_Border;
        for (int i = 0; i < m_NumCols; i++)
        {
            m_ColsInfo[i].leftpos = wpos;
            wpos += m_ColsInfo[i].pixwidth + m_Spacing;
        }

        // add the remaining space to the last column
        if (m_NumCols > 0 && wpos < m_Width - m_Border)
            m_ColsInfo[m_NumCols-1].pixwidth += m_Width - wpos - m_Border;
    }

    /* 3.  sub-layout all cells: */
    {
        int *ypos = new int[m_NumRows + 1];

        int actcol, actrow;
        int fullwid;
        wxHtmlContainerCell *actcell;

        ypos[0] = m_Spacing + m_Border;
        for (actrow = 1; actrow <= m_NumRows; actrow++) ypos[actrow] = -1;
        for (actrow = 0; actrow < m_NumRows; actrow++)
        {
            if (ypos[actrow] == -1) ypos[actrow] = ypos[actrow-1];
            // 3a. sub-layout and detect max height:

            for (actcol = 0; actcol < m_NumCols; actcol++) {
                if (m_CellInfo[actrow][actcol].flag != cellUsed) continue;
                actcell = m_CellInfo[actrow][actcol].cont;
                fullwid = 0;
                for (int i = actcol; i < m_CellInfo[actrow][actcol].colspan + actcol; i++)
                    fullwid += m_ColsInfo[i].pixwidth;
                fullwid += (m_CellInfo[actrow][actcol].colspan - 1) * m_Spacing;
                actcell->SetMinHeight(m_CellInfo[actrow][actcol].minheight, m_CellInfo[actrow][actcol].valign);
                actcell->Layout(fullwid);

                if (ypos[actrow] + actcell->GetHeight() + m_CellInfo[actrow][actcol].rowspan * m_Spacing > ypos[actrow + m_CellInfo[actrow][actcol].rowspan])
                    ypos[actrow + m_CellInfo[actrow][actcol].rowspan] =
                            ypos[actrow] + actcell->GetHeight() + m_CellInfo[actrow][actcol].rowspan * m_Spacing;
            }
        }

        for (actrow = 0; actrow < m_NumRows; actrow++)
        {
            // 3b. place cells in row & let'em all have same height:

            for (actcol = 0; actcol < m_NumCols; actcol++)
            {
                if (m_CellInfo[actrow][actcol].flag != cellUsed) continue;
                actcell = m_CellInfo[actrow][actcol].cont;
                actcell->SetMinHeight(
                                 ypos[actrow + m_CellInfo[actrow][actcol].rowspan] - ypos[actrow] -  m_Spacing,
                                 m_CellInfo[actrow][actcol].valign);
                fullwid = 0;
                for (int i = actcol; i < m_CellInfo[actrow][actcol].colspan + actcol; i++)
                    fullwid += m_ColsInfo[i].pixwidth;
                fullwid += (m_CellInfo[actrow][actcol].colspan - 1) * m_Spacing;
                actcell->Layout(fullwid);
                actcell->SetPos(m_ColsInfo[actcol].leftpos, ypos[actrow]);
            }
        }
        m_Height = ypos[m_NumRows] + m_Border;
        delete[] ypos;
    }

    /* 4. adjust table's width if it was too small: */
    if (m_NumCols > 0)
    {
        int twidth = m_ColsInfo[m_NumCols-1].leftpos +
                     m_ColsInfo[m_NumCols-1].pixwidth + m_Spacing + m_Border;
        if (twidth > m_Width)
            m_Width = twidth;
    }
}

//-----------------------------------------------------------------------------
// The tables handler:
//-----------------------------------------------------------------------------

TAG_HANDLER_BEGIN(TABLE, "TABLE,TR,TD,TH")

    TAG_HANDLER_VARS
        wxHtmlTableCell* m_Table;
        wxString m_tAlign, m_rAlign;
        wxHtmlContainerCell *m_enclosingContainer;

        // Call ParseInner() preserving background colour and mode after any
        // changes done by it.
        void CallParseInnerWithBg(const wxHtmlTag& tag, const wxColour& colBg)
        {
            const wxColour oldbackclr = m_WParser->GetActualBackgroundColor();
            const int oldbackmode = m_WParser->GetActualBackgroundMode();
            if ( colBg.IsOk() )
            {
                m_WParser->SetActualBackgroundColor(colBg);
                m_WParser->SetActualBackgroundMode(wxBRUSHSTYLE_SOLID);
                m_WParser->GetContainer()->InsertCell(
                        new wxHtmlColourCell(colBg, wxHTML_CLR_BACKGROUND)
                    );
            }

            ParseInner(tag);

            if ( oldbackmode != m_WParser->GetActualBackgroundMode() ||
                    oldbackclr != m_WParser->GetActualBackgroundColor() )
            {
               m_WParser->SetActualBackgroundMode(oldbackmode);
               m_WParser->SetActualBackgroundColor(oldbackclr);
               m_WParser->GetContainer()->InsertCell(
                      new wxHtmlColourCell(oldbackclr,
                                        oldbackmode == wxBRUSHSTYLE_TRANSPARENT
                                            ? wxHTML_CLR_TRANSPARENT_BACKGROUND
                                            : wxHTML_CLR_BACKGROUND)
                );
            }
        }

    TAG_HANDLER_CONSTR(TABLE)
    {
        m_Table = NULL;
        m_enclosingContainer = NULL;
        m_tAlign.clear();
        m_rAlign.clear();
    }

    TAG_HANDLER_PROC(tag)
    {
        wxHtmlContainerCell *c;

        // new table started, backup upper-level table (if any) and create new:
        if (tag.GetName() == wxT("TABLE"))
        {
            wxHtmlTableCell *oldt = m_Table;

            wxHtmlContainerCell *oldEnclosing = m_enclosingContainer;
            m_enclosingContainer = c = m_WParser->OpenContainer();

            m_Table = new wxHtmlTableCell(c, tag, m_WParser->GetPixelScale());

            // width:
            {
                int width = 0;
                bool wpercent = false;
                if (tag.GetParamAsIntOrPercent(wxT("WIDTH"), &width, wpercent))
                {
                    if (wpercent)
                    {
                        m_Table->SetWidthFloat(width, wxHTML_UNITS_PERCENT);
                    }
                    else
                    {
                        m_Table->SetWidthFloat((int)(m_WParser->GetPixelScale() * width), wxHTML_UNITS_PIXELS);
                    }
                }
                else
                    m_Table->SetWidthFloat(0, wxHTML_UNITS_PIXELS);
            }
            int oldAlign = m_WParser->GetAlign();
            if (!tag.GetParamAsString(wxT("ALIGN"), &m_tAlign))
                m_tAlign.clear();

            CallParseInnerWithBg(tag, m_Table->GetBackgroundColour());

            m_WParser->SetAlign(oldAlign);
            m_WParser->SetContainer(m_enclosingContainer);
            m_WParser->CloseContainer();

            m_Table = oldt;
            m_enclosingContainer = oldEnclosing;

            return true; // ParseInner() called
        }

        else if (m_Table)
        {
            // new row in table
            if (tag.GetName() == wxT("TR"))
            {
                m_Table->AddRow(tag);
                if (!tag.GetParamAsString(wxT("ALIGN"), &m_rAlign))
                    m_rAlign = m_tAlign;
            }

            // new cell
            else
            {
                c = m_WParser->SetContainer(new wxHtmlContainerCell(m_Table));
                m_Table->AddCell(c, tag);

                m_WParser->OpenContainer();

                const bool isHeader = tag.GetName() == wxT("TH");

                wxString als;
                if (!tag.GetParamAsString(wxT("ALIGN"), &als))
                    als = m_rAlign;
                als.MakeUpper();

                if (als == wxT("RIGHT"))
                    m_WParser->SetAlign(wxHTML_ALIGN_RIGHT);
                else if (als == wxT("LEFT"))
                    m_WParser->SetAlign(wxHTML_ALIGN_LEFT);
                else if (als == wxT("CENTER"))
                    m_WParser->SetAlign(wxHTML_ALIGN_CENTER);
                else // use default alignment
                    m_WParser->SetAlign(isHeader ? wxHTML_ALIGN_CENTER
                                                 : wxHTML_ALIGN_LEFT);

                m_WParser->OpenContainer();

                // the header should be rendered in bold by default
                int boldOld = 0;
                if ( isHeader )
                {
                    boldOld = m_WParser->GetFontBold();
                    m_WParser->SetFontBold(true);
                    m_WParser->GetContainer()->InsertCell(
                        new wxHtmlFontCell(m_WParser->CreateCurrentFont()));
                }

                wxColour bgCol;
                if ( !tag.GetParamAsColour(wxT("BGCOLOR"), &bgCol) )
                    bgCol = m_Table->GetRowDefaultBackgroundColour();

                CallParseInnerWithBg(tag, bgCol);

                if ( isHeader )
                {
                    m_WParser->SetFontBold(boldOld);
                    m_WParser->GetContainer()->InsertCell(
                        new wxHtmlFontCell(m_WParser->CreateCurrentFont()));
                }

                // set the current container back to the enclosing one so that
                // text outside of  and  isn't included in any cell
                // (this happens often enough in practice because it's common
                // to use whitespace between 	 and the next ):
                m_WParser->SetContainer(m_enclosingContainer);

                return true; // ParseInner() called
            }
        }

        return false;
    }

TAG_HANDLER_END(TABLE)

TAGS_MODULE_BEGIN(Tables)

    TAGS_MODULE_ADD(TABLE)

TAGS_MODULE_END(Tables)

#endif


text:
Our CSS Flexbox-based framework, with graceful fallback to a % based grid. We use this framework on all our websites, and as such it does contain our base styling, however this is all located in variables.scss, so you can easily edit it for your own application if you wish to build from source. We use gulp, and a gulpfile is included with the project, but you may feel free to build it however you wish.

# Contributing
We would love for your help! Please submit all changes to the _develop_ branch.

# Building from Source
To build from source, simply install the required node modules and run gulp. You should then have an updated compiled.min.css, with full source maps.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.Serialization;

namespace Alphaleonis.Win32.Filesystem
{
   /// The requested operation could not be completed because the device was not ready.
   [Serializable]
   public class DeviceNotReadyException : System.IO.IOException
   {
      private static readonly int s_errorCode = Win32Errors.GetHrFromWin32Error(Win32Errors.ERROR_NOT_READY);

      /// Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.
      public DeviceNotReadyException()
         : base(Resources.Device_Not_Ready, s_errorCode)
      {
      }

      /// Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.
      /// <param name="message">The message.</param>
      public DeviceNotReadyException(string message)
         : base(message, s_errorCode)
      {
      }

      /// Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.
      /// <param name="message">The message.</param>
      /// <param name="innerException">The inner exception.</param>
      public DeviceNotReadyException(string message, Exception innerException)
         : base(message, innerException)
      {
      }

      /// Initializes a new instance of the <see cref="DeviceNotReadyException"/> class.
      /// <param name="info">The data for serializing or deserializing the object.</param>
      /// <param name="context">The source and destination for the object.</param>
      protected DeviceNotReadyException(SerializationInfo info, StreamingContext context)
         : base(info, context)
      {
      }
   }
}


text:
"""
Neural network layers involving the application of convolutional filters.
"""

import logging
from neon.backends.cpu import CPU
from neon.layers.layer import WeightLayer
from neon.util.param import opt_param, req_param

logger = logging.getLogger(__name__)

class ConvLayer(WeightLayer):

    """
    Convolutional layer.
    """

    def __init__(self, **kwargs):
        self.is_local = True
        super(ConvLayer, self).__init__(**kwargs)
        opt_param(self, ['local_conv'], False)

    def initialize(self, kwargs):
        super(ConvLayer, self).initialize(kwargs)
        self.initialize_local()
        if self.pad != 0 and isinstance(self.backend, CPU):
            raise NotImplementedError('pad != 0, for CPU backend in ConvLayer')

        opt_param(self, ['shared_bias'], True)
        if self.shared_bias:
            self.bias_shape = (self.nofm, 1)
            self.bias_expand = self.backend.empty((self.nout, 1),
                                                  dtype=self.weight_dtype)
        else:
            self.bias_shape = (self.nout, 1)

        self.allocate_output_bufs()
        self.allocate_param_bufs()

        opt_param(self, ['prodbuf', 'bpropbuf', 'updatebuf'], None)
        if isinstance(self.backend, CPU):
            self.prodbuf = self.backend.empty((self.nofm, self.batch_size))
            self.bpropbuf = self.backend.empty((self.fsize, self.batch_size))
            self.updatebuf = self.backend.empty(self.weights.shape)

        if self.backend.__module__ == 'neon.backends.gpu':
            self.conv_params = self.backend.ng.conv_layer(
                N=self.batch_size, C=self.nifm, K=self.nofm,
                D=1, H=self.ifmshape[0], W=self.ifmshape[1], T=1,
                R=self.fshape[0], S=self.fshape[1],
                pad_d=0, pad_h=self.pad, pad_w=self.pad,
                str_d=1, str_h=self.stride, str_w=self.stride,
                grid_P=0, grid_Q=0,
                dtype=self.weight_dtype)
            self.prodbuf = self.bpropbuf = self.updatebuf = self.conv_params

    def set_weight_shape(self):
        if hasattr(self, 'local_conv') and self.local_conv:
            weight_shape = (self.fsize * self.ofmsize, self.nofm)
        else:
            weight_shape = (self.fsize, self.nofm)
        opt_param(self, ['weight_shape'], weight_shape)

    def fprop(self, inputs):
        self.backend.fprop_conv(out=self.pre_act, inputs=inputs,
                                weights=self.weights, ofmshape=self.ofmshape,
                                ofmsize=self.ofmsize,
                                ofmlocs=self.ofmlocs, ifmshape=self.ifmshape,
                                links=self.links, nifm=self.nifm,
                                padding=self.negpad, stride=self.stride,
                                ngroups=1, fpropbuf=self.prodbuf,
                                local=self.local_conv)
        if self.use_biases is True:
            if self.shared_bias:
                self.pre_act = self.pre_act.reshape(
                    (self.nofm, self.ofmsize * self.batch_size))
                self.backend.add(self.pre_act, self.biases, out=self.pre_act)
                self.pre_act = self.pre_act.reshape(
                    (self.nofm * self.ofmsize, self.batch_size))
            else:
                self.backend.add(self.pre_act, self.biases, out=self.pre_act)

        if self.batch_norm:
            self.bn.fprop_func(self.backend, self.pre_act, self.pre_act)

        self.activation.fprop_func(self.backend, self.pre_act, self.output)

    def bprop(self, error):
        inputs = self.prev_layer.output
        self.activation.bprop_func(self.backend, self.pre_act, error,
                                   self.skip_act)

        upm = self.utemp if self.accumulate else self.updates
        u_idx = 0
        if self.batch_norm:
            self.bn.bprop_func(self.backend, self.pre_act, error,
                               self.skip_act)
            u_idx = 2

        if self.deltas is not None:
            self.backend.bprop_conv(out=self.deltas, weights=self.weights,
                                    deltas=error, ofmshape=self.ofmshape,
                                    ofmsize=self.ofmsize,
                                    ofmlocs=self.ofmlocs,
                                    ifmshape=self.ifmshape, links=self.links,
                                    padding=self.negpad, stride=self.stride,
                                    nifm=self.nifm, ngroups=1,
                                    bpropbuf=self.bpropbuf,
                                    local=self.local_conv)
        self.backend.update_conv(out=upm[u_idx], inputs=inputs,
                                 weights=self.weights, deltas=error,
                                 ofmshape=self.ofmshape,
                                 ofmsize=self.ofmsize,
                                 ofmlocs=self.ofmlocs,
                                 ifmshape=self.ifmshape, links=self.links,
                                 nifm=self.nifm, padding=self.negpad,
                                 stride=self.stride, ngroups=1,
                                 fwidth=self.fshape[-1],
                                 updatebuf=self.updatebuf,
                                 local=self.local_conv,
                                 layer=self)

        if self.use_biases is True:
            # We can't reshape the error buffer since it might be global buffer
            if self.shared_bias:
                self.backend.sum(error, axes=1, out=self.bias_expand)
                self.bias_expand = self.bias_expand.reshape(
                    (self.nofm, self.ofmsize))
                self.backend.sum(self.bias_expand, axes=1, out=upm[u_idx+1])
                self.bias_expand = self.bias_expand.reshape(
                    (self.nofm * self.ofmsize, 1))
            else:
                self.backend.sum(error, axes=1, out=upm[u_idx+1])

        if self.accumulate:
            self.backend.add(upm[u_idx], self.updates[u_idx],
                             out=self.updates[u_idx])
            if self.use_biases is True:
                self.backend.add(upm[1], self.updates[1], out=self.updates[1])

class SubConvLayer(ConvLayer):
    """
    Convolutional layer with workaround for modulo 16 number of filters
    """
    def __init__(self, **kwargs):
        super(SubConvLayer, self).__init__(**kwargs)
        req_param(self, ['endidx'])

    def initialize(self, kwargs):
        super(SubConvLayer, self).initialize(kwargs)
        self.rowendidx = self.endidx * self.ofmsize
        self.bigoutput = self.output
        self.suboutput = self.backend.zeros(
            (self.rowendidx, self.batch_size), self.output_dtype)

    def fprop(self, inputs):
        self.output = self.bigoutput
        super(SubConvLayer, self).fprop(inputs)
        self.suboutput.fill(0.0)
        self.suboutput[:] = self.output[:self.rowendidx, :]
        self.output = self.suboutput

    def bprop(self, error):
        inputs = self.prev_layer.output
        if self.activation is not None:
            self.backend.multiply(error, self.pre_act[:self.rowendidx],
                                  out=self.pre_act[:self.rowendidx])
        self.pre_act[self.rowendidx:] = 0.
        self.weights[self.endidx:] = 0.
        error = self.pre_act
        if self.deltas is not None:
            self.backend.bprop_conv(out=self.deltas, weights=self.weights,
                                    deltas=error, ofmshape=self.ofmshape,
                                    ofmsize=self.ofmsize,
                                    ofmlocs=self.ofmlocs,
                                    ifmshape=self.ifmshape, links=self.links,
                                    padding=self.pad, stride=self.stride,
                                    nifm=self.nifm, ngroups=1,
                                    bpropbuf=self.bpropbuf,
                                    local=self.local_conv)

        upm = self.utemp if self.accumulate else self.updates

        self.backend.update_conv(out=upm[0], inputs=inputs,
                                 weights=self.weights, deltas=error,
                                 ofmshape=self.ofmshape,
                                 ofmsize=self.ofmsize,
                                 ofmlocs=self.ofmlocs,
                                 ifmshape=self.ifmshape, links=self.links,
                                 nifm=self.nifm, padding=self.pad,
                                 stride=self.stride, ngroups=1,
                                 fwidth=self.fshape[-1],
                                 updatebuf=self.updatebuf,
                                 local=self.local_conv,
                                 layer=self)

        if self.use_biases is True:
            self.backend.sum(error, axes=1, out=upm[1])
        if self.accumulate:
            self.backend.add(upm[0], self.updates[0], out=self.updates[0])
            if self.use_biases is True:
                self.backend.add(upm[1], self.updates[1], out=self.updates[1])


text:
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const del = require('del');
const path = require('path');
const mkdirp = require('mkdirp');
const isparta = require('isparta');
const exec = require('child_process').exec;

const manifest = require('./package.json');
const config = manifest.nodeBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Send a notification when JSHint fails,
// so that you know your changes didn't build
function jshintNotify(file) {
  if (!file.jshint) {
    return;
  }
  return file.jshint.success ? false : 'JSHint failed';
}

function jscsNotify(file) {
  if (!file.jscs) {
    return;
  }
  return file.jscs.success ? false : 'JSCS failed';
}

function createLintTask(taskName, files) {
  gulp.task(taskName, function() {
    return gulp.src(files)
      .pipe($.plumber())
      .pipe($.eslint())
      .pipe($.eslint.format())
      .pipe($.eslint.failOnError())
      .pipe($.jscs())
      .pipe($.notify(jscsNotify));
  });
}

// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);

// Lint our test code
createLintTask('lint-test', ['test/**/*.js']);

// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function() {

  // Create our output directory
  mkdirp.sync(destinationFolder);
  return gulp.src('src/**/*.js')
    .pipe($.plumber())
    .pipe($.babel({
      blacklist: ['useStrict']
    }))
    .pipe(gulp.dest(destinationFolder));
});

function test() {
  return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {
      read: false
    })
    .pipe($.plumber())
    .pipe($.mocha({
      reporter: 'spec',
      globals: config.mochaGlobals,
      timeout: 10000
    }));
}

// Make babel preprocess the scripts the user tries to import from here on.
require('babel/register');

gulp.task('coverage', function(done) {
  gulp.src(['src/*.js'])
    .pipe($.plumber())
    .pipe($.istanbul({
      instrumenter: isparta.Instrumenter
    }))
    .pipe($.istanbul.hookRequire())
    .on('finish', function() {
      return test()
        .pipe($.istanbul.writeReports())
        .on('end', done);
    });
});

// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], test);

// Run the headless unit tests as you make changes.
gulp.task('watch', ['test'], function() {
  gulp.watch(['src/**/*', 'test/**/*', 'package.json', '**/.jshintrc', '.jscsrc'], ['test']);
});

// An alias of test
gulp.task('default', ['test']);


text:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class ZXPDFSearchResultPage, ZXPDFSearchWord;

@interface ZXPDFSearchResultDocument : NSManagedObject {
@private
}
@property (nonatomic, strong) NSNumber * indexed;
@property (nonatomic, strong) NSString * filePath;
@property (nonatomic, strong) NSNumber * completed;
@property (nonatomic, strong) NSSet* resultPages;
@property (nonatomic, strong) ZXPDFSearchWord * word;

@end


text:
 Home |
 Phones List Template|

Phone List from Controller

    Search: <input ng-model="vm.queryOn" class="form-control input-sm" placeholder="Search Value" />

    Sort By:
    <select class="form-control input-sm" ng-model="vm.orderBy" ng-options="orderByOption.id as orderByOption.desc for orderByOption in vm.orderByOptions">
        <option value="">Please select ....</option>
    </select>

        {{phone.name}}

{{phone.snippet}} | Age: {{phone.age}}


text:
#/**********************************************************\
#
# Auto-Generated Plugin Configuration file
# for Kinect JS
#
#\**********************************************************/

set(PLUGIN_NAME "KSenseJS")
set(PLUGIN_PREFIX "KJS")
set(COMPANY_NAME "UIUC")

# ActiveX constants:
set(FBTYPELIB_NAME KSenseJSLib)
set(FBTYPELIB_DESC "KSenseJS 1.0 Type Library")
set(IFBControl_DESC "KSenseJS Control Interface")
set(FBControl_DESC "KSenseJS Control Class")
set(IFBComJavascriptObject_DESC "KSenseJS IComJavascriptObject Interface")
set(FBComJavascriptObject_DESC "KSenseJS ComJavascriptObject Class")
set(IFBComEventSource_DESC "KSenseJS IFBComEventSource Interface")
set(AXVERSION_NUM "1")

# NOTE: THESE GUIDS *MUST* BE UNIQUE TO YOUR PLUGIN/ACTIVEX CONTROL!  YES, ALL OF THEM!
set(FBTYPELIB_GUID 47f44b67-b863-5079-981d-dd248e513795)
set(IFBControl_GUID d5561d14-c1b4-532b-bf7c-4743507eb0cc)
set(FBControl_GUID 08348fcc-f531-58a5-b3b8-58768a3af389)
set(IFBComJavascriptObject_GUID efbb62ff-ce03-5763-80f5-6551842775b8)
set(FBComJavascriptObject_GUID 5a3fc00d-369b-56b7-80d1-b46dff083ba9)
set(IFBComEventSource_GUID 1fe257a2-a740-5348-b4ee-3d6932060b10)

# these are the pieces that are relevant to using it from Javascript
set(ACTIVEX_PROGID "UIUC.KSenseJS")
set(MOZILLA_PLUGINID "uiuc.com/KSenseJS")

# strings
set(FBSTRING_CompanyName "UIUC")
set(FBSTRING_PluginDescription "Kinect JavaScript interface")
set(FBSTRING_PLUGIN_VERSION "1.0.0.0")
set(FBSTRING_LegalCopyright "Copyright 2012 UIUC")
set(FBSTRING_PluginFileName "np${PLUGIN_NAME}.dll")
set(FBSTRING_ProductName "KSense JS")
set(FBSTRING_FileExtents "")
set(FBSTRING_PluginName "KSense JS")
set(FBSTRING_MIMEType "application/x-ksensejs")

# Uncomment this next line if you're not planning on your plugin doing
# any drawing:

set (FB_GUI_DISABLED 1)

# Mac plugin settings. If your plugin does not draw, set these all to 0
set(FBMAC_USE_QUICKDRAW 0)
set(FBMAC_USE_CARBON 0)
set(FBMAC_USE_COCOA 0)
set(FBMAC_USE_COREGRAPHICS 0)
set(FBMAC_USE_COREANIMATION 0)
set(FBMAC_USE_INVALIDATINGCOREANIMATION 0)

# If you want to register per-machine on Windows, uncomment this line
#set (FB_ATLREG_MACHINEWIDE 1)

# Enable logging to JS console
add_firebreath_library(log4cplus)


text:
using System;
using System.Collections.Generic;
using System.Xml;
using TableauAPI.FilesLogging;
using TableauAPI.RESTHelpers;
using TableauAPI.ServerData;

namespace TableauAPI.RESTRequests
{
    /// <summary>
    /// Downloads the list of Workbooks from the server
    /// </summary>
    public class DownloadWorkbooksList : TableauServerSignedInRequestBase
    {
        private readonly TableauServerUrls _onlineUrls;
        private readonly string _userId;

        private List<SiteWorkbook> _workbooks;
        /// <summary>
        /// Workbooks we've parsed from server results
        /// </summary>
        public ICollection<SiteWorkbook> Workbooks
        {
            get
            {
                var wb = _workbooks;
                return wb?.AsReadOnly();
            }
        }

        /// <summary>
        /// Constructor: Call when we want to query the workbooks on behalf of the currently logged in user
        /// </summary>
        /// <param name="onlineUrls">Tableau Server Information</param>
        /// <param name="logInInfo">Tableau Sign In Information</param>
        public DownloadWorkbooksList(TableauServerUrls onlineUrls, TableauServerSignIn logInInfo)
            : base(logInInfo)
        {
            _onlineUrls = onlineUrls;
            _userId = logInInfo.UserId;
        }

        /// <summary>
        /// Constructor: Call when we want to query the Workbooks on behalf of an explicitly specified user
        /// </summary>
        /// <param name="onlineUrls">Tableau Server Information</param>
        /// <param name="logInInfo">Tableau Sign In Information</param>
        /// <param name="userId">User ID of person we are downloading on behalf of</param>
        public DownloadWorkbooksList(TableauServerUrls onlineUrls, TableauServerSignIn logInInfo, string userId) : base(logInInfo)
        {
            _onlineUrls = onlineUrls;
            _userId = userId;
        }

        /// <summary>
        /// Execute request for Workbook listings
        /// </summary>
        public void ExecuteRequest()
        {
            //Sanity check
            if(string.IsNullOrWhiteSpace(_userId))
            {
                OnlineSession.StatusLog.AddError("User ID required to query workbooks");
            }

            var onlineWorkbooks = new List<SiteWorkbook>();
            int numberPages = 1; //Start with 1 page (we will get an updated value from server)
            //Get subsequent pages
            for (int thisPage = 1; thisPage <= numberPages; thisPage++)
            {
                try
                {
                    _ExecuteRequest_ForPage(onlineWorkbooks, thisPage, out numberPages);
                }
                catch (Exception exPageRequest)
                {
                    StatusLog.AddError("Workbooks error during page request: " + exPageRequest.Message);
                }
            }

            _workbooks = onlineWorkbooks;
        }

        #region Private methods

        /// <summary>
        /// Get a page's worth of Workbook listings
        /// </summary>
        /// <param name="onlineWorkbooks"></param>
        /// <param name="pageToRequest">Page # we are requesting (1 based)</param>
        /// <param name="totalNumberPages">Total # of pages of data that Server can return us</param>
        private void _ExecuteRequest_ForPage(List<SiteWorkbook> onlineWorkbooks, int pageToRequest, out int totalNumberPages)
        {
            int pageSize = _onlineUrls.PageSize;
            //Create a web request, in including the users logged-in auth information in the request headers
            var urlQuery = _onlineUrls.Url_WorkbooksListForUser(OnlineSession, _userId, pageSize, pageToRequest);
            var webRequest = CreateLoggedInWebRequest(urlQuery);
            webRequest.Method = "GET";

            OnlineSession.StatusLog.AddStatus("Web request: " + urlQuery, -10);
            var response = GetWebResponseLogErrors(webRequest, "get workbooks list");
            var xmlDoc = GetWebResponseAsXml(response);

            //Get all the workbook nodes
            var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
            var workbooks = xmlDoc.SelectNodes("//iwsOnline:workbook", nsManager);

            //Get information for each of the data sources
            foreach (XmlNode itemXml in workbooks)
            {
                try
                {
                    var ds = new SiteWorkbook(itemXml);
                    onlineWorkbooks.Add(ds);
                }
                catch
                {
                    AppDiagnostics.Assert(false, "Workbook parse error");
                    OnlineSession.StatusLog.AddError("Error parsing workbook: " + itemXml.InnerXml);
                }
            } //end: foreach

            //-------------------------------------------------------------------
            //Get the updated page-count
            //-------------------------------------------------------------------
            totalNumberPages = DownloadPaginationHelper.GetNumberOfPagesFromPagination(
                xmlDoc.SelectSingleNode("//iwsOnline:pagination", nsManager),
                pageSize);
        }

        #endregion

    }
}


text:
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsFrameMessageManager_h__
#define nsFrameMessageManager_h__

#include "nsIFrameMessageManager.h"
#include "nsIObserver.h"
#include "nsCOMPtr.h"
#include "nsAutoPtr.h"
#include "nsCOMArray.h"
#include "nsTArray.h"
#include "nsIAtom.h"
#include "nsCycleCollectionParticipant.h"
#include "nsTArray.h"
#include "nsIPrincipal.h"
#include "nsIXPConnect.h"
#include "nsDataHashtable.h"
#include "mozilla/Services.h"
#include "nsIObserverService.h"
#include "nsThreadUtils.h"
#include "mozilla/Attributes.h"

namespace mozilla {
namespace dom {
class ContentParent;
}
}

class nsAXPCNativeCallContext;
struct JSContext;
struct JSObject;

struct nsMessageListenerInfo
{
  nsCOMPtr<nsIFrameMessageListener> mListener;
  nsCOMPtr<nsIAtom> mMessage;
};

typedef bool (*nsLoadScriptCallback)(void* aCallbackData, const nsAString& aURL);
typedef bool (*nsSyncMessageCallback)(void* aCallbackData,
                                      const nsAString& aMessage,
                                      const nsAString& aJSON,
                                      InfallibleTArray<nsString>* aJSONRetVal);
typedef bool (*nsAsyncMessageCallback)(void* aCallbackData,
                                       const nsAString& aMessage,
                                       const nsAString& aJSON);

class nsFrameMessageManager MOZ_FINAL : public nsIContentFrameMessageManager,
                                        public nsIChromeFrameMessageManager
{
public:
  nsFrameMessageManager(bool aChrome,
                        nsSyncMessageCallback aSyncCallback,
                        nsAsyncMessageCallback aAsyncCallback,
                        nsLoadScriptCallback aLoadScriptCallback,
                        void* aCallbackData,
                        nsFrameMessageManager* aParentManager,
                        JSContext* aContext,
                        bool aGlobal = false,
                        bool aProcessManager = false)
  : mChrome(aChrome), mGlobal(aGlobal), mIsProcessManager(aProcessManager),
    mHandlingMessage(false), mDisconnected(false), mParentManager(aParentManager),
    mSyncCallback(aSyncCallback), mAsyncCallback(aAsyncCallback),
    mLoadScriptCallback(aLoadScriptCallback), mCallbackData(aCallbackData),
    mContext(aContext)
  {
    NS_ASSERTION(mContext || (aChrome && !aParentManager) || aProcessManager,
                 "Should have mContext in non-global/non-process manager!");
    NS_ASSERTION(aChrome || !aParentManager, "Should not set parent manager!");
    // This is a bit hackish. When parent manager is global, we want
    // to attach the window message manager to it immediately.
    // Is it just the frame message manager which waits until the
    // content process is running.
    if (mParentManager && (mCallbackData || IsWindowLevel())) {
      mParentManager->AddChildManager(this);
    }
  }

  ~nsFrameMessageManager()
  {
    for (PRInt32 i = mChildManagers.Count(); i > 0; --i) {
      static_cast<nsFrameMessageManager*>(mChildManagers[i - 1])->
        Disconnect(false);
    }
    if (mIsProcessManager) {
      if (this == sParentProcessManager) {
        sParentProcessManager = nsnull;
      }
      if (this == sChildProcessManager) {
        sChildProcessManager = nsnull;
        delete sPendingSameProcessAsyncMessages;
        sPendingSameProcessAsyncMessages = nsnull;
      }
      if (this == sSameProcessParentManager) {
        sSameProcessParentManager = nsnull;
      }
    }
  }

  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsFrameMessageManager,
                                           nsIContentFrameMessageManager)
  NS_DECL_NSIFRAMEMESSAGEMANAGER
  NS_DECL_NSISYNCMESSAGESENDER
  NS_DECL_NSICONTENTFRAMEMESSAGEMANAGER
  NS_DECL_NSICHROMEFRAMEMESSAGEMANAGER
  NS_DECL_NSITREEITEMFRAMEMESSAGEMANAGER

  static nsFrameMessageManager*
  NewProcessMessageManager(mozilla::dom::ContentParent* aProcess);

  nsresult ReceiveMessage(nsISupports* aTarget, const nsAString& aMessage,
                          bool aSync, const nsAString& aJSON,
                          JSObject* aObjectsArray,
                          InfallibleTArray<nsString>* aJSONRetVal,
                          JSContext* aContext = nsnull);
  void AddChildManager(nsFrameMessageManager* aManager,
                       bool aLoadScripts = true);
  void RemoveChildManager(nsFrameMessageManager* aManager)
  {
    mChildManagers.RemoveObject(aManager);
  }

  void Disconnect(bool aRemoveFromParent = true);
  void SetCallbackData(void* aData, bool aLoadScripts = true);
  void* GetCallbackData() { return mCallbackData; }
  void GetParamsForMessage(const jsval& aObject,
                           JSContext* aCx,
                           nsAString& aJSON);
  nsresult SendAsyncMessageInternal(const nsAString& aMessage,
                                    const nsAString& aJSON);
  JSContext* GetJSContext() { return mContext; }
  void SetJSContext(JSContext* aCx) { mContext = aCx; }
  void RemoveFromParent();
  nsFrameMessageManager* GetParentManager() { return mParentManager; }
  void SetParentManager(nsFrameMessageManager* aParent)
  {
    NS_ASSERTION(!mParentManager, "We have parent manager already!");
    NS_ASSERTION(mChrome, "Should not set parent manager!");
    mParentManager = aParent;
  }
  bool IsGlobal() { return mGlobal; }
  bool IsWindowLevel() { return mParentManager && mParentManager->IsGlobal(); }

  static nsFrameMessageManager* GetParentProcessManager()
  {
    return sParentProcessManager;
  }
  static nsFrameMessageManager* GetChildProcessManager()
  {
    return sChildProcessManager;
  }
protected:
  friend class MMListenerRemover;
  nsTArray<nsMessageListenerInfo> mListeners;
  nsCOMArray<nsIContentFrameMessageManager> mChildManagers;
  bool mChrome;
  bool mGlobal;
  bool mIsProcessManager;
  bool mHandlingMessage;
  bool mDisconnected;
  nsFrameMessageManager* mParentManager;
  nsSyncMessageCallback mSyncCallback;
  nsAsyncMessageCallback mAsyncCallback;
  nsLoadScriptCallback mLoadScriptCallback;
  void* mCallbackData;
  JSContext* mContext;
  nsTArray<nsString> mPendingScripts;
public:
  static nsFrameMessageManager* sParentProcessManager;
  static nsFrameMessageManager* sChildProcessManager;
  static nsFrameMessageManager* sSameProcessParentManager;
  static nsTArray<nsCOMPtr<nsIRunnable> >* sPendingSameProcessAsyncMessages;
};

void
ContentScriptErrorReporter(JSContext* aCx,
                           const char* aMessage,
                           JSErrorReport* aReport);

class nsScriptCacheCleaner;

struct nsFrameJSScriptExecutorHolder
{
  nsFrameJSScriptExecutorHolder(JSScript* aScript) : mScript(aScript)
  { MOZ_COUNT_CTOR(nsFrameJSScriptExecutorHolder); }
  ~nsFrameJSScriptExecutorHolder()
  { MOZ_COUNT_DTOR(nsFrameJSScriptExecutorHolder); }
  JSScript* mScript;
};

class nsFrameScriptExecutor
{
public:
  static void Shutdown();
protected:
  friend class nsFrameScriptCx;
  nsFrameScriptExecutor() : mCx(nsnull), mCxStackRefCnt(0),
                            mDelayedCxDestroy(false)
  { MOZ_COUNT_CTOR(nsFrameScriptExecutor); }
  ~nsFrameScriptExecutor()
  { MOZ_COUNT_DTOR(nsFrameScriptExecutor); }
  void DidCreateCx();
  // Call this when you want to destroy mCx.
  void DestroyCx();
  void LoadFrameScriptInternal(const nsAString& aURL);
  bool InitTabChildGlobalInternal(nsISupports* aScope);
  static void Traverse(nsFrameScriptExecutor *tmp,
                       nsCycleCollectionTraversalCallback &cb);
  nsCOMPtr<nsIXPConnectJSObjectHolder> mGlobal;
  JSContext* mCx;
  PRUint32 mCxStackRefCnt;
  bool mDelayedCxDestroy;
  nsCOMPtr<nsIPrincipal> mPrincipal;
  static nsDataHashtable<nsStringHashKey, nsFrameJSScriptExecutorHolder*>* sCachedScripts;
  static nsRefPtr<nsScriptCacheCleaner> sScriptCacheCleaner;
};

class nsFrameScriptCx
{
public:
  nsFrameScriptCx(nsISupports* aOwner, nsFrameScriptExecutor* aExec)
  : mOwner(aOwner), mExec(aExec)
  {
    ++(mExec->mCxStackRefCnt);
  }
  ~nsFrameScriptCx()
  {
    if (--(mExec->mCxStackRefCnt) == 0 &&
        mExec->mDelayedCxDestroy) {
      mExec->DestroyCx();
    }
  }
  nsCOMPtr<nsISupports> mOwner;
  nsFrameScriptExecutor* mExec;
};

class nsScriptCacheCleaner MOZ_FINAL : public nsIObserver
{
  NS_DECL_ISUPPORTS

  nsScriptCacheCleaner()
  {
    nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService();
    if (obsSvc)
      obsSvc->AddObserver(this, "xpcom-shutdown", false);
  }

  NS_IMETHODIMP Observe(nsISupports *aSubject,
                        const char *aTopic,
                        const PRUnichar *aData)
  {
    nsFrameScriptExecutor::Shutdown();
    return NS_OK;
  }
};

#endif


text:
from selene.core.condition import Condition
from selene.core.entity import Browser, Element, Collection

class ElementCondition(Condition[Element]):
    pass

class CollectionCondition(Condition[Collection]):
    pass

class BrowserCondition(Condition[Browser]):
    pass


text:
/*! anotherbutton.css | MIT License */

:root {
  /* Colors form clrs.cc */
  --navy: #001F3F;
  --blue: #0074D9;
  --aqua: #7FDBFF;
  --teal: #39CCCC;
  --olive: #3D9970;
  --green: #2ECC40;
  --lime: #01FF70;
  --yellow: #FFDC00;
  --orange: #FF851B;
  --red: #FF4136;
  --fuchsia: #F012BE;
  --purple: #B10DC9;
  --maroon: #85144B;
  --white: #fff;
  --silver: #ddd;
  --gray: #aaa;
  --black: #111;

  --default-color: var(--gray);
  --default-hover-color: #777;
  --primary-color: var(--aqua);
  --primary-hover-color:  var(--blue);
  --disabled-color: var(--silver);
  --radius: 3px;
}

/* Default Button */
.btn {
  display: inline-block;
  box-sizing: border-box;

  margin-left: 0.1em;
  margin-right: 0.1em;
  margin-top: 0.2em;
  margin-bottom: 0.2em;

  padding-left: 1em;
  padding-right: 1em;
  padding-top: 0.7em;
  padding-bottom: 0.7em;

  color: #fff;
  line-height: 1;
  text-decoration: none;
  text-transform: uppercase;
  letter-spacing: 0.025em;
  background-color: var(--default-color);

  border: 2px solid transparent;
  border-radius: var(--radius);

  transition: background-color 0.2s ease-out;
}

.btn:hover,
.btn:focus {
  background-color: var(--default-hover-color);

  transition: background-color 0.3s ease-in;
}

.btn:active {

}

/* Primary buttons */
.btn--primary {
  background-color: var(--primary-color);
}

.btn--primary:hover,
.btn--primary:focus {
  background-color: var(--primary-hover-color);

  transition: background-color 0.3s ease-in;
}

/* Disabled buttons */
.btn[disabled],
.btn--disabled,
.btn--disabled:hover,
.btn--disabled:focus {
  background-color: var(--disabled-color);
  cursor: not-allowed;
}

/* Button size */
.btn--small {
  font-size: 0.7em;
  letter-spacing: 0.06em;
}

.btn--large {
  font-size: 1.3em;
  letter-spacing: 0.025em;
}

/* Ghost buttons */
.btn--ghost {
  background-color: transparent;
  transition: color 0.2s ease-out, border-color 0.2s ease-out;
}

.btn.btn--ghost {
  color: var(--default-color);
  border-color: var(--default-color);
}

.btn.btn--ghost:hover,
.btn.btn--ghost:focus {
  color: var(--default-hover-color);
  border-color: var(--default-hover-color);
  background-color: transparent;
  transition: color 0.2s ease-in, border-color 0.2s ease-in;
}

.btn--primary.btn--ghost {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.btn--primary.btn--ghost:hover,
.btn--primary.btn--ghost:focus {
  color: var(--primary-hover-color);
  border-color: var(--primary-hover-color);
  background-color: transparent;
  transition: color 0.2s ease-in, border-color 0.2s ease-in;
}


text:
template: post.html
title: GeoRocket 1.2.0
tags: [GeoRocket, Announcement]
description: GeoRocket version 1.2.0 has just been released
author: mkraemer
lead: A new stable version of GeoRocket has just been released
---

We're very happy to announce the next stable version of GeoRocket 1.2.0. We
worked hard to make this the best release available yet with a large number of
new features, fixes, and updates:

## New features

* We added a [new storage back-end]({{ site.url }}/docs/user-documentation/1.2.0/#config-backend-h2):
  The embedded database H2 stores geospatial data on your local hard drive but
  is much faster than the old [file system back-end]({{ site.url }}/docs/user-documentation/1.2.0/#config-backend-file). We made H2 the default
  back-end now. Note that in production environments, we still recommend using
  the [MongoDB back-end]({{ site.url }}/docs/user-documentation/1.2.0/#mongodb)
  as it allows for a more scalable cluster deployment.
* GeoRocket supports encrypted connections with [SSL/TLS]({{ site.url }}/docs/user-documentation/1.2.0/#http-interface-2) now. We also added
  support for the new [HTTP/2]({{ site.url }}/docs/user-documentation/1.2.0/#http-interface-2).
  This allows for a much faster client-server communication.
* We added support for [Cross-Origin Resource Sharing (CORS)]({{ site.url }}/docs/user-documentation/1.2.0/#http-interface-2).
  This allows web developers to query the GeoRocket HTTP interface from the
  browser with JavaScript.
* HTTP compression can now be [turned on and off]({{ site.url }}/docs/user-documentation/1.2.0/#http-interface-2).
* We improved the performance of the XML splitter.
* You can now search for `gmlId` specifically. In particular, we added support
  for indexing `gml:id` from GML 3.2.
* We upgraded the [embedded Elasticsearch]({{ site.url }}/docs/user-documentation/1.2.0/#indexer-elasticsearch)
  version to 5.6.5. You can still use your own external one if you like.
* The [default heap size]({{ site.url }}/docs/user-documentation/1.2.0/#configuration-6)
  of the embedded Elasticsearch was increased.
* GeoRocket now logs progress while importing and deleting chunks.
* Error messages from Elasticsearch are now forwarded to
  [GeoRocket's HTTP interface]({{ site.url }}/docs/user-documentation/1.2.0/#error-responses).
* GeoRocket prints a fancy banner 🤘 and its server version on startup.
* We improved compatibility with Java 9.

## Server API

* The sever API now allows [new HTTP endpoints]({{ site.url }}/docs/api/server/1.2.0/io/georocket/http/Endpoint.html) to be added.
* GeoRocket extensions can now [register verticles]({{ site.url }}/docs/api/server/1.2.0/io/georocket/ExtensionVerticle.html).
* We've added the possibility to [filter service instances]({{ site.url }}/docs/api/server/1.2.0/io/georocket/util/ServiceFilter.html).

## Bug fixes

* GeoRocket now correctly imports files with a UTF-8 BOM.
* GeoJSON files with UTF-8 characters are now correctly split.
* GeoRocket now handles empty tags and properties correctly.
* We made sure all results are returned when scrolling.
* We fixed a `StackOverflowError` that could happen when scrolling with a very
  large frame size.

## Internal changes

* We upgraded Vert.x to 3.5.1.
* Library dependencies have been updated.
* We upgraded the Gradle Wrapper to 4.8.1.
* We improved our integration tests and unit tests.
* We replaced `rx.Single<Void>` with `rx.Completable` where applicable.
* All Observables are now cold by default.
* We replaced Rx operators by transformers.
* It is now easier to build the Docker image.

## More information

The new version is recommended for all users. Try GeoRocket 1.2.0 while it's
still hot! 🔥

🚀 https://georocket.io/download

For a complete [list of features](https://georocket.io/features) visit our
[website](https://georocket.io). There you will also find the
[user documentation](https://georocket.io/docs/user-documentation)
and other information.

If you have questions, ideas or comments regarding GeoRocket or any of our other
services feel free to [contact us](http://www.igd.fraunhofer.de/en/competences/technologies/spatial-information-management).


text: export * from "./Profiler";


text:
Protocol
========

**Gretel** provides a command line tool for the recovery of haplotypes.
We recommend the following protocol.

Read Alignment
--------------

**Gretel** requires your reads to be aligned to a common reference. This is to
ensure that reads share a co-ordinate system, on which we can call for variants
and recover haplotypes. The reference itself is of little consequence, though
dropped reads will lead to evidence to be unavailable to Gretel.

Construction of a *de novo* consensus assembly for a metagenome is left as an exercise
for the reader. Align the reads to your assembly (`bowtie2`, `minimap2` etc.).
Sort and index the alignment BAM.

Variant Calling
---------------

**Gretel** is robust to sequencing error and misalignment noise, thus the
calling of variants need not be carefully conducted. Typically we have used `samtools`,
but for our own Gretel pipeline, we have aggressively called all heterogenous sites
in an alignment as a SNP using the `snpper` tool in our `gretel-test repository
<https://github.com/SamStudio8/gretel-test>`_.

For somewhat questionable reasoning, we currently require a compressed and indexed VCF: ::

    bgzip <my.vcf>
    tabix <my.vcf.gz>

Invocation of Gretel
--------------------
As described in the README, Gretel is invoked as follows: ::

    gretel <my.sort.bam> <my.vcf.gz> <contig> [-s 1startpos] [-e 1endpos] [--master master.fa] [-o output_dir]

You must provide your sorted BAM, compressed VCF, and the name of the contig on which
to recover haplotypes. Use `-s` and `-e` to specify the positions on the aligned reads between which
to recover haplotypes from your metagenome.

By default, Gretel will output a FASTA containing the recovered SNPs, in order, for each haplotype.
Providing an optional "master" FASTA sequence will permit Gretel to "fill in" the non-SNP positions
(*i.e.* the positions between `-s` and `-e` that do not appear in the VCF) with the nucleotide from
the pseudo-reference.

Gretel Outputs
--------------

out.fasta
~~~~~~~~~
A **FASTA** containing each of the recovered sequences, in the order they were found.
Each sequence is named `<iteration>__-<log10 likelihood>`. Sequences are not wrapped.

gretel.crumbs
~~~~~~~~~~~~~

Additionally, Gretel outputs a whimsically named *crumbs* file, containing some potentially
interesting metadata, as well as a record of each recovered haplotype.
The first row is a comment containing the following (in order):

* The number of SNPs across the region of interest
* The number of 'crumbs': paired observations added to the Hansel matrix
* The number of 'slices': reads with at least one observation added to the Hansel matrix
* The chosen value of `L` for the `L`'th order Markov chain

The rest of the file contains tab-delimited metadata for each recovered haplotype:

* The iteration number, starting from 0
* The number of times this haplotype was returned
* The *weighted* likelihood of the haplotype, given the Hansel matrix at the time the haplotype was recovered (comma-sep for each time the haplotype was returned)
* The *unweighted* likelihood of the haplotype, given the Hansel matrix at the time the reads were parsed (comma-sep for each time the haplotype was returned)
* The haplotype magnitude: total number of observations removed from the Hansel matrix by the reweighting mechanism

In practice, we rank with the **weighted** likelihoods to discern the haplotypes most likely to exist in the metagenome.
One may attempt to use the *unweighted* likelihoods as a means to compare the abundance, or read support, **between the returned haplotypes** (*i.e.* not necessarily the metagenome as a whole).


text:
/**
 * \file drm_atomic.h
 * Atomic operations used in the DRM which may or may not be provided by the OS.
 *
 * \author Eric Anholt <anholt@FreeBSD.org>
 */

/*-
 * Copyright 2004 Eric Anholt
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/* Many of these implementations are rather fake, but good enough. */

typedef u_int32_t atomic_t;

#if defined(__FreeBSD__)
#define atomic_set(p, v)	(*(p) = (v))
#define atomic_read(p)		(*(p))
#define atomic_inc(p)		atomic_add_int(p, 1)
#define atomic_dec(p)		atomic_subtract_int(p, 1)
#define atomic_add(n, p)	atomic_add_int(p, n)
#define atomic_sub(n, p)	atomic_subtract_int(p, n)

static __inline atomic_t
test_and_set_bit(int b, volatile void *p)
{
	int s = splhigh();
	unsigned int m = 1<<b;
	unsigned int r = *(volatile int *)p & m;
	*(volatile int *)p |= m;
	splx(s);
	return r;
}

static __inline void
clear_bit(int b, volatile void *p)
{
	atomic_clear_int(((volatile int *)p) + (b >> 5), 1 << (b & 0x1f));
}

static __inline void
set_bit(int b, volatile void *p)
{
	atomic_set_int(((volatile int *)p) + (b >> 5), 1 << (b & 0x1f));
}

static __inline int
test_bit(int b, volatile void *p)
{
	return ((volatile int *)p)[b >> 5] & (1 << (b & 0x1f));
}

#elif   defined(__NetBSD__)

#include <sys/atomic.h>

#define	atomic_set(p, v)		(*((volatile uint32_t *)p) = (v))
#define atomic_read(p)		(*(p))
#define atomic_inc(p)		atomic_inc_uint(p)
#define atomic_dec(p)		atomic_dec_uint(p)
#define atomic_add(n, p)	atomic_add_int(p, n)
#define atomic_sub(n, p)	atomic_add_int(p, -(n))

#define atomic_add_acq_int(p, v)	atomic_add(v, p)
#define atomic_subtract_acq_int(p, v)	atomic_sub(v, p)
#define	atomic_set_int(p, bits)		atomic_or_uint(p, bits)
#define	atomic_clear_int(p, bits)	atomic_and_uint(p, ~(bits))

#define	atomic_cmpset_int(p, o, n)					\
			((old == atomic_cas_uint(p, o, n)) ? 1 : 0)

#define	set_bit(b, p)							\
	atomic_set_int(((volatile uint32_t *)(volatile void *)p) + (b >> 5),\
			(1 << (b & 0x1f)))

#define	clear_bit(b, p)							\
	atomic_clear_int(((volatile uint32_t *)(volatile void *)p) + (b >> 5), \
			(1 << (b & 0x1f)))

#define	test_bit(b, p)							\
	(((volatile uint32_t *)(volatile void *)p)[b >> 5] & (1 << (b & 0x1f)))

static __inline uint32_t
test_and_set_bit(int b, volatile void *p)
{
	volatile uint32_t *val;
	uint32_t mask, old;

	val = (volatile uint32_t *)p;
	mask = 1 << b;

	do {
		old = *val;
		if ((old & mask) != 0)
			break;
	} while (atomic_cas_uint(val, old, old | mask) != old);

	return old & mask;
}

#endif
static __inline int
find_first_zero_bit(volatile void *p, int max_)
{
	int b;
	volatile int *ptr = (volatile int *)p;

	for (b = 0; b < max_; b += 32) {
		if (ptr[b >> 5] != ~0) {
			for (;;) {
				if ((ptr[b >> 5] & (1 << (b & 0x1f))) == 0)
					return b;
				b++;
			}
		}
	}
	return max_;
}


text:
package org.apache.falcon.oozie.process;

import org.apache.commons.lang3.StringUtils;
import org.apache.falcon.FalconException;
import org.apache.falcon.LifeCycle;
import org.apache.falcon.Tag;
import org.apache.falcon.entity.CatalogStorage;
import org.apache.falcon.entity.EntityUtil;
import org.apache.falcon.entity.FeedHelper;
import org.apache.falcon.entity.ProcessHelper;
import org.apache.falcon.entity.Storage;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.Frequency;
import org.apache.falcon.entity.v0.SchemaHelper;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.entity.v0.feed.Feed;
import org.apache.falcon.entity.v0.feed.LocationType;
import org.apache.falcon.entity.v0.process.Input;
import org.apache.falcon.entity.v0.process.Output;
import org.apache.falcon.entity.v0.process.Process;
import org.apache.falcon.entity.v0.process.Workflow;
import org.apache.falcon.expression.ExpressionHelper;
import org.apache.falcon.oozie.OozieCoordinatorBuilder;
import org.apache.falcon.oozie.OozieEntityBuilder;
import org.apache.falcon.oozie.OozieOrchestrationWorkflowBuilder;
import org.apache.falcon.oozie.coordinator.CONTROLS;
import org.apache.falcon.oozie.coordinator.COORDINATORAPP;
import org.apache.falcon.oozie.coordinator.DATAIN;
import org.apache.falcon.oozie.coordinator.DATAOUT;
import org.apache.falcon.oozie.coordinator.DATASETS;
import org.apache.falcon.oozie.coordinator.INPUTEVENTS;
import org.apache.falcon.oozie.coordinator.OUTPUTEVENTS;
import org.apache.falcon.oozie.coordinator.SYNCDATASET;
import org.apache.falcon.oozie.coordinator.WORKFLOW;
import org.apache.falcon.workflow.WorkflowExecutionArgs;
import org.apache.falcon.workflow.WorkflowExecutionContext;
import org.apache.hadoop.fs.Path;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * Builds oozie coordinator for process.
 */
public class ProcessExecutionCoordinatorBuilder extends OozieCoordinatorBuilder<Process> {
    private static final int THIRTY_MINUTES = 30 * 60 * 1000;

    public ProcessExecutionCoordinatorBuilder(Process entity) {
        super(entity, LifeCycle.EXECUTION);
    }

    @Override public List<Properties> buildCoords(Cluster cluster, Path buildPath) throws FalconException {
        String coordName = getEntityName();
        Path coordPath = getBuildPath(buildPath);
        copySharedLibs(cluster, new Path(coordPath, "lib"));

        COORDINATORAPP coord = new COORDINATORAPP();
        // coord attributes
        initializeCoordAttributes(cluster, coord, coordName);

        CONTROLS controls = initializeControls(); // controls
        coord.setControls(controls);

        // Configuration
        Properties props = createCoordDefaultConfiguration(cluster, coordName);

        initializeInputPaths(cluster, coord, props); // inputs
        initializeOutputPaths(cluster, coord, props);  // outputs

        Workflow processWorkflow = entity.getWorkflow();
        propagateUserWorkflowProperties(processWorkflow, props);

        // create parent wf
        Properties wfProps = OozieOrchestrationWorkflowBuilder.get(entity, cluster, Tag.DEFAULT).build(cluster,
            coordPath);

        WORKFLOW wf = new WORKFLOW();
        wf.setAppPath(getStoragePath(wfProps.getProperty(OozieEntityBuilder.ENTITY_PATH)));
        props.putAll(wfProps);
        wf.setConfiguration(getConfig(props));

        // set coord action to parent wf
        org.apache.falcon.oozie.coordinator.ACTION action = new org.apache.falcon.oozie.coordinator.ACTION();
        action.setWorkflow(wf);
        coord.setAction(action);

        Path marshalPath = marshal(cluster, coord, coordPath);
        return Arrays.asList(getProperties(marshalPath, coordName));
    }

    @Override
    protected WorkflowExecutionContext.EntityOperations getOperation() {
        return WorkflowExecutionContext.EntityOperations.GENERATE;
    }

    private void initializeCoordAttributes(Cluster cluster, COORDINATORAPP coord, String coordName) {
        coord.setName(coordName);
        org.apache.falcon.entity.v0.process.Cluster processCluster = ProcessHelper.getCluster(entity,
            cluster.getName());
        coord.setStart(SchemaHelper.formatDateUTC(processCluster.getValidity().getStart()));
        coord.setEnd(SchemaHelper.formatDateUTC(processCluster.getValidity().getEnd()));
        coord.setTimezone(entity.getTimezone().getID());
        coord.setFrequency("${coord:" + entity.getFrequency().toString() + "}");
    }

    private CONTROLS initializeControls()
        throws FalconException {
        CONTROLS controls = new CONTROLS();
        controls.setConcurrency(String.valueOf(entity.getParallel()));
        controls.setExecution(entity.getOrder().name());

        Frequency timeout = entity.getTimeout();
        long frequencyInMillis = ExpressionHelper.get().evaluate(entity.getFrequency().toString(), Long.class);
        long timeoutInMillis;
        if (timeout != null) {
            timeoutInMillis = ExpressionHelper.get().
                evaluate(entity.getTimeout().toString(), Long.class);
        } else {
            timeoutInMillis = frequencyInMillis * 6;
            if (timeoutInMillis < THIRTY_MINUTES) {
                timeoutInMillis = THIRTY_MINUTES;
            }
        }
        controls.setTimeout(String.valueOf(timeoutInMillis / (1000 * 60)));

        if (timeoutInMillis / frequencyInMillis * 2 > 0) {
            controls.setThrottle(String.valueOf(timeoutInMillis / frequencyInMillis * 2));
        }

        return controls;
    }

    private void initializeInputPaths(Cluster cluster, COORDINATORAPP coord, Properties props) throws FalconException {
        if (entity.getInputs() == null) {
            props.put(WorkflowExecutionArgs.INPUT_FEED_NAMES.getName(), "NONE");
            props.put(WorkflowExecutionArgs.INPUT_FEED_PATHS.getName(), IGNORE);
            props.put(WorkflowExecutionArgs.INPUT_NAMES.getName(), IGNORE);
            return;
        }

        List<String> inputFeeds = new ArrayList<String>();
        List<String> inputNames = new ArrayList<String>();
        List<String> inputPaths = new ArrayList<String>();
        List<String> inputFeedStorageTypes = new ArrayList<String>();
        for (Input input : entity.getInputs().getInputs()) {
            Feed feed = EntityUtil.getEntity(EntityType.FEED, input.getFeed());
            Storage storage = FeedHelper.createStorage(cluster, feed);

            if (!input.isOptional()) {
                if (coord.getDatasets() == null) {
                    coord.setDatasets(new DATASETS());
                }
                if (coord.getInputEvents() == null) {
                    coord.setInputEvents(new INPUTEVENTS());
                }

                SYNCDATASET syncdataset = createDataSet(feed, cluster, storage, input.getName(), LocationType.DATA);
                if (syncdataset == null) {
                    return;
                }
                coord.getDatasets().getDatasetOrAsyncDataset().add(syncdataset);

                DATAIN datain = createDataIn(input);
                coord.getInputEvents().getDataIn().add(datain);
            }

            String inputExpr = null;
            if (storage.getType() == Storage.TYPE.FILESYSTEM) {
                inputExpr = getELExpression("dataIn('" + input.getName() + "', '" + input.getPartition() + "')");
                props.put(input.getName(), inputExpr);
            } else if (storage.getType() == Storage.TYPE.TABLE) {
                inputExpr = "${coord:dataIn('" + input.getName() + "')}";
                propagateCatalogTableProperties(input, (CatalogStorage) storage, props);
            }

            inputFeeds.add(feed.getName());
            inputPaths.add(inputExpr);
            inputNames.add(input.getName());
            inputFeedStorageTypes.add(storage.getType().name());
        }

        propagateLateDataProperties(inputFeeds, inputNames, inputPaths, inputFeedStorageTypes, props);
    }

    private void propagateLateDataProperties(List<String> inputFeeds, List<String> inputNames, List<String> inputPaths,
        List<String> inputFeedStorageTypes, Properties props) {
        // populate late data handler - should-record action
        props.put(WorkflowExecutionArgs.INPUT_FEED_NAMES.getName(), StringUtils.join(inputFeeds, '#'));
        props.put(WorkflowExecutionArgs.INPUT_NAMES.getName(), StringUtils.join(inputNames, '#'));
        props.put(WorkflowExecutionArgs.INPUT_FEED_PATHS.getName(), StringUtils.join(inputPaths, '#'));

        // storage type for each corresponding feed sent as a param to LateDataHandler
        // needed to compute usage based on storage type in LateDataHandler
        props.put(WorkflowExecutionArgs.INPUT_STORAGE_TYPES.getName(), StringUtils.join(inputFeedStorageTypes, '#'));
    }

    private SYNCDATASET createDataSet(Feed feed, Cluster cluster, Storage storage,
        String datasetName, LocationType locationType) throws FalconException {
        SYNCDATASET syncdataset = new SYNCDATASET();
        syncdataset.setName(datasetName);
        syncdataset.setFrequency("${coord:" + feed.getFrequency().toString() + "}");

        String uriTemplate = storage.getUriTemplate(locationType);
        if (uriTemplate == null) {
            return null;
        }
        if (storage.getType() == Storage.TYPE.TABLE) {
            uriTemplate = uriTemplate.replace("thrift", "hcat"); // Oozie requires this!!!
        }
        syncdataset.setUriTemplate(uriTemplate);

        org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, cluster.getName());
        syncdataset.setInitialInstance(SchemaHelper.formatDateUTC(feedCluster.getValidity().getStart()));
        syncdataset.setTimezone(feed.getTimezone().getID());

        if (feed.getAvailabilityFlag() == null) {
            syncdataset.setDoneFlag("");
        } else {
            syncdataset.setDoneFlag(feed.getAvailabilityFlag());
        }

        return syncdataset;
    }

    private DATAIN createDataIn(Input input) {
        DATAIN datain = new DATAIN();
        datain.setName(input.getName());
        datain.setDataset(input.getName());
        datain.setStartInstance(getELExpression(input.getStart()));
        datain.setEndInstance(getELExpression(input.getEnd()));
        return datain;
    }

    private String getELExpression(String expr) {
        if (expr != null) {
            expr = "${" + expr + "}";
        }
        return expr;
    }

    private void initializeOutputPaths(Cluster cluster, COORDINATORAPP coord, Properties props) throws FalconException {
        if (entity.getOutputs() == null) {
            props.put(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName(), IGNORE);
            props.put(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName(), IGNORE);
            return;
        }

        if (coord.getDatasets() == null) {
            coord.setDatasets(new DATASETS());
        }

        if (coord.getOutputEvents() == null) {
            coord.setOutputEvents(new OUTPUTEVENTS());
        }

        List<String> outputFeeds = new ArrayList<String>();
        List<String> outputPaths = new ArrayList<String>();
        for (Output output : entity.getOutputs().getOutputs()) {
            Feed feed = EntityUtil.getEntity(EntityType.FEED, output.getFeed());
            Storage storage = FeedHelper.createStorage(cluster, feed);

            SYNCDATASET syncdataset = createDataSet(feed, cluster, storage, output.getName(), LocationType.DATA);
            if (syncdataset == null) {
                return;
            }
            coord.getDatasets().getDatasetOrAsyncDataset().add(syncdataset);

            DATAOUT dataout = createDataOut(output);
            coord.getOutputEvents().getDataOut().add(dataout);

            String outputExpr = "${coord:dataOut('" + output.getName() + "')}";
            outputFeeds.add(feed.getName());
            outputPaths.add(outputExpr);

            if (storage.getType() == Storage.TYPE.FILESYSTEM) {
                props.put(output.getName(), outputExpr);

                propagateFileSystemProperties(output, feed, cluster, coord, storage, props);
            } else if (storage.getType() == Storage.TYPE.TABLE) {
                propagateCatalogTableProperties(output, (CatalogStorage) storage, props);
            }
        }

        // Output feed name and path for parent workflow
        props.put(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName(), StringUtils.join(outputFeeds, ','));
        props.put(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName(), StringUtils.join(outputPaths, ','));
    }

    private DATAOUT createDataOut(Output output) {
        DATAOUT dataout = new DATAOUT();
        dataout.setName(output.getName());
        dataout.setDataset(output.getName());
        dataout.setInstance(getELExpression(output.getInstance()));
        return dataout;
    }

    private void propagateFileSystemProperties(Output output, Feed feed, Cluster cluster, COORDINATORAPP coord,
        Storage storage, Properties props) throws FalconException {
        // stats and meta paths
        createOutputEvent(output, feed, cluster, LocationType.STATS, coord, props, storage);
        createOutputEvent(output, feed, cluster, LocationType.META, coord, props, storage);
        createOutputEvent(output, feed, cluster, LocationType.TMP, coord, props, storage);
    }

    //SUSPEND CHECKSTYLE CHECK ParameterNumberCheck
    private void createOutputEvent(Output output, Feed feed, Cluster cluster, LocationType locType,
        COORDINATORAPP coord, Properties props, Storage storage) throws FalconException {
        String name = output.getName();
        String type = locType.name().toLowerCase();

        SYNCDATASET dataset = createDataSet(feed, cluster, storage, name + type, locType);
        if (dataset == null) {
            return;
        }
        coord.getDatasets().getDatasetOrAsyncDataset().add(dataset);

        DATAOUT dataout = new DATAOUT();
        dataout.setName(name + type);
        dataout.setDataset(name + type);
        dataout.setInstance(getELExpression(output.getInstance()));

        OUTPUTEVENTS outputEvents = coord.getOutputEvents();
        if (outputEvents == null) {
            outputEvents = new OUTPUTEVENTS();
            coord.setOutputEvents(outputEvents);
        }
        outputEvents.getDataOut().add(dataout);

        String outputExpr = "${coord:dataOut('" + name + type + "')}";
        props.put(name + "." + type, outputExpr);
    }
    //RESUME CHECKSTYLE CHECK ParameterNumberCheck

    private void propagateUserWorkflowProperties(Workflow processWorkflow, Properties props) {
        props.put("userWorkflowName", ProcessHelper.getProcessWorkflowName(
            processWorkflow.getName(), entity.getName()));
        props.put("userWorkflowVersion", processWorkflow.getVersion());
        props.put("userWorkflowEngine", processWorkflow.getEngine().value());
    }

    protected void propagateCatalogTableProperties(Input input, CatalogStorage tableStorage, Properties props) {
        String prefix = "falcon_" + input.getName();

        propagateCommonCatalogTableProperties(tableStorage, props, prefix);

        props.put(prefix + "_partition_filter_pig",
            "${coord:dataInPartitionFilter('" + input.getName() + "', 'pig')}");
        props.put(prefix + "_partition_filter_hive",
            "${coord:dataInPartitionFilter('" + input.getName() + "', 'hive')}");
        props.put(prefix + "_partition_filter_java",
            "${coord:dataInPartitionFilter('" + input.getName() + "', 'java')}");
    }
}


text:
package service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import DAO.IContactDao;
import model.Contact;
import model.Entreprise;
import model.Group;

public class ContactServiceImpl implements IContactService {

	private IContactDao cdao;

	public void setCdao(IContactDao cdao) {
		this.cdao = cdao;
	}

	public boolean createContact(Contact contact) throws Exception {
		return cdao.insertDB(contact);
	}

	// Pour la création Entreprise
	public boolean addEntreprise(Entreprise etp) throws Exception {
		return cdao.insertDB(etp);
	}

	@Override
	public boolean insertDBObjects(List<Object> objects) throws Exception {
		return cdao.insertDBObjects(objects);
	}

	@Override
	public boolean insertDB(Object object) throws Exception {
		return cdao.insertDB(object);
	}

	@Override
	public Contact getContact(long id) {
		return cdao.getContact(id);
	}

	@Override
	public Set<Contact> getAllContacts() {
		return new HashSet<Contact>(cdao.getAllContacts());
	}

	@Override
	public Set<Contact> getAllContactsLazy() {
		return cdao.getAllContactsLazy();
	}

	@Override
	public Set<Contact> getContactsByGroupId(long groupId) {
		return cdao.getContactsByGroupId(groupId);
	}

	@Override
	public Group getGroup(long groupId) {
		return cdao.getGroup(groupId);
	}

	@Override
	public Set<Group> getAllGroups() {
		return cdao.getAllGroups();
	}

	@Override
	public Set<Contact> getAllContactsWgroups() {
		return cdao.getAllContactsWGroups();
	}

	@Override
	public Set<Contact> searchContacts(String keywords) {
		return cdao.searchContacts(keywords);
	}

	@Override
	public boolean saveUpdate(Contact contact) {
		return cdao.saveUpdate(contact);
	}

	@Override
	public boolean update(Contact contact) {
		return cdao.update(contact);
	}

	@Override
	public boolean update(Group group) {
		return cdao.update(group);
	}

	@Override
	public boolean deleteContact(long contact_ID) {
		return cdao.deleteContact(contact_ID);
	}

	@Override
	public boolean deleteGroup(long groupId) {
		return cdao.deleteGroup(groupId);
	}

	@Override
	public long getNbContact(){
		return cdao.getNbContact();
	}

	@Override
	public long getNbGroup(){
		return cdao.getNbGroup();
	}

	@Override
	public Set<Contact> getLastContacts(){
		return cdao.getLastContacts();
	}

	@Override
	public boolean updateGroupName(long id, String newName){
		return cdao.updateGroupName(id, newName);
	}

}


text:
[![Build Status](https://travis-ci.org/nicjhan/oasis-grids.svg?branch=master)](https://travis-ci.org/nicjhan/oasis-grids)

# oasis-grids

Create OASIS3-MCT model coupling grid configurations.

The oasisgrids.py tool is a grid translator. It takes model grid definitions as netCDF files, converts to an Object/Python representation, then translates these to a format understood by the OASIS3-MCT coupler.

# Description

Coupling models together using the OASIS3-MCT coupler involves defining the model grids in a particular format. OASIS then uses these when regridding coupling fields. This tool can be used to create the OASIS grid definition files, called grids.nc, areas.nc, masks.nc for a collection of coupled models.

At a high level the OASIS regridding setup looks like this:

1. Start with model grid definitions as NetCDF files.
2. Offline transformation of above to OASIS grids (grids.nc, areas.nc, masks.nc).
3. OASIS uses grids from above and it's namcouple configuration to create regridding weights files for each pair of coupled grids. This only needs to be done once, thereafter the regridding weights files are reused.
4. During runtime the regridding weights files are used to interpolate fields between model grids.

The oasisgrids.py tool takes care of step 2 in this process.

In addition it provides an option to also do step 3. The advantage of doing step 3 offline, rather than depending on OASIS to do it, is that a more sophisticated (and a lot faster) regridding weight generation tool can be used. Step 3 depends on [ESMF_RegridWeighGen](https://www.earthsystemcog.org/projects/regridweightgen/)

# Use

The tool adds one model grid definition to the files grids.nc, areas.nc, masks.nc each time it is invoked. As such it is necessary to invoke it mulitiple times, once for every model which participates in the coupling.

For example to couple MOM with T42 atmosphere:

```{shell}
cd test
wget http://s3-ap-southeast-2.amazonaws.com/dp-drop/oasis-grids/test/test_data.tar.gz
tar zxvf test_data.tar.gz
cd test_data/input
../../../oasisgrids.py MOM --model_hgrid ocean_hgrid.nc  --model_mask ocean_mask.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
../../../oasisgrids.py T42 --model_mask lsm.20040101000000.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
```

This first invocation of oasisgrids adds the MOM grid specification to the OASIS files, the second adds the T42 grid specification.

In this case no grid id/name is being provided and it will default to: lowercase model name postfixed with t, u, or v. The grid name can be given explicitly with the --grid_name option. The grid name needs to match what has been used in the OASIS namcouple file.

If there are multiple model configurations then all model grid variables can be added to the same OASIS files. For example with a T42 atmosphere coupled to both MOM and NEMO in different configs:

```{shell}
cd test
wget http://s3-ap-southeast-2.amazonaws.com/dp-drop/oasis-grids/test/test_data.tar.gz
tar zxvf test_data.tar.gz
cd test_data/input
../../../oasisgrids.py MOM --model_hgrid ocean_hgrid.nc --model_mask ocean_mask.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
../../../oasisgrids.py NEMO --model_hgrid coordinates.nc --model_mask mesh_mask.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
../../../oasisgrids.py T42 --model_mask lsm.20040101000000.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
../../../oasisgrids.py FV300 --model_mask lsm.20040101000000.nc \
  --grids grids.nc --areas areas.nc --masks masks.nc
```

This will result in grids.nc, areas.nc, masks.nc files that contain grid definitions for all of the above models. OASIS will use this to create the remapping weights files depending on the contents of the namcouple file.

# Examples

The [ACCESS-OM development wiki](https://github.com/OceansAus/access-om/wiki/Development) shows how this tool can be used to help couple models together.


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="form.csrf_provider" class="Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfTokenManagerAdapter">
            <argument type="service" id="security.csrf.token_manager" />
            <deprecated>The "%service_id%" service is deprecated since Symfony 2.4 and will be removed in 3.0. Use the "security.csrf.token_manager" service instead.</deprecated>
        </service>

        <service id="form.type_extension.csrf" class="Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension">
            <tag name="form.type_extension" alias="Symfony\Component\Form\Extension\Core\Type\FormType" />
            <argument type="service" id="security.csrf.token_manager" />
            <argument>%form.type_extension.csrf.enabled%</argument>
            <argument>%form.type_extension.csrf.field_name%</argument>
            <argument type="service" id="translator.default" />
            <argument>%validator.translation_domain%</argument>
        </service>
    </services>
</container>