text:
#include "drape_frontend/watch/cpu_drawer.hpp"
#include "drape_frontend/watch/proto_to_styles.hpp"
#include "drape_frontend/watch/software_renderer.hpp"
#include "drape_frontend/navigator.hpp"
#include "drape_frontend/visual_params.hpp"

#include "geometry/angles.hpp"
#include "geometry/tree4d.hpp"
#include "geometry/transformations.hpp"

#include "indexer/scales.hpp"
#include "indexer/drules_include.hpp"

#include "base/macros.hpp"
#include "base/logging.hpp"

#include "std/algorithm.hpp"
#include "std/bind.hpp"

namespace
{

void CorrectFont(dp::FontDecl & font)
{
  font.m_size = font.m_size * 0.75;
}

strings::UniString PreProcessText(string const & text)
{
  // Warning! This code processes text as left-to-right text
  // and doesn't reorder right-to-left text. To support right-to-left text
  // bidi algorithm should be applied.
  strings::UniString visText = strings::MakeUniString(text);
  char const * delims = " \n\t";

  size_t count = visText.size();
  if (count > 15)
  {
    // split on two parts
    typedef strings::UniString::const_iterator TIter;
    TIter const iBegin = visText.begin();
    TIter const iMiddle = iBegin + count / 2;
    TIter const iEnd = visText.end();

    size_t const delimsSize = strlen(delims);

    // find next delimeter after middle [m, e)
    TIter iNext = find_first_of(iMiddle, iEnd,
                                delims, delims + delimsSize);

    // find last delimeter before middle [b, m)
    TIter iPrev = find_first_of(reverse_iterator<TIter>(iMiddle),
                                reverse_iterator<TIter>(iBegin),
                                delims, delims + delimsSize).base();
    // don't do split like this:
    //     xxxx
    // xxxxxxxxxxxx
    if (4 * distance(iBegin, iPrev) <= count)
      iPrev = visText.end();
    else
      --iPrev;

    // get closest delimiter to the middle
    if (iNext == iEnd ||
        (iPrev != iEnd && distance(iPrev, iMiddle) < distance(iMiddle, iNext)))
    {
      iNext = iPrev;
    }

    // split string on 2 parts
    if (iNext != visText.end())
      ASSERT_NOT_EQUAL(iNext, iEnd, ());
      visText.insert(iNext, '\n');
  }

  return visText;
}

template<typename TInfo>
FeatureID const & InsertImpl(FeatureID const & id, map<FeatureID, TInfo> & map, TInfo const & info)
{
  if (map.find(id) == map.end())
    map.insert(make_pair(id, info));

  return id;
}

template<typename TInfo>
TInfo const & GetInfo(FeatureID const & id, map<FeatureID, TInfo> & m)
{
  ASSERT(m.find(id) != m.end(), ());
  return m[id];
}

}

namespace df
{
namespace watch
{

class CPUDrawer::CPUOverlayTree
{
  struct OverlayWrapperTraits
  {
    static m2::RectD const LimitRect(CPUDrawer::OverlayWrapper const * elem)
    {
      m2::RectD result;
      for_each(elem->m_rects.begin(), elem->m_rects.end(), [&result](m2::RectD const & r)
      {
        result.Add(r);
      });

      return result;
    }
  };

  class DoPreciseIntersect
  {
    CPUDrawer::OverlayWrapper const * m_elem;
    bool m_isIntersect;

  public:
    DoPreciseIntersect(CPUDrawer::OverlayWrapper const * oe)
      : m_elem(oe), m_isIntersect(false)
    {
    }

    void operator()(CPUDrawer::OverlayWrapper const * e)
    {
      if (m_isIntersect)
        return;

      if (m_elem == e)
        return;

      for (m2::RectD const & elemR : m_elem->m_rects)
        for (m2::RectD const & inputR : e->m_rects)
        {
          m_isIntersect = elemR.IsIntersect(inputR);
          if (m_isIntersect)
            return;
        }
    }

    bool IsIntersect() const { return m_isIntersect; }
  };

public:
  template <typename Fn>
  void forEach(Fn fn)
  {
    m_tree.ForEach(fn);
  }

  void replaceOverlayElement(CPUDrawer::OverlayWrapper const * oe)
  {
    DoPreciseIntersect fn(oe);
    m_tree.ForEachInRect(OverlayWrapperTraits::LimitRect(oe), ref(fn));

    if (fn.IsIntersect())
    {
      m_tree.ReplaceAllInRect(oe, [](CPUDrawer::OverlayWrapper const * l,
                                     CPUDrawer::OverlayWrapper const * r)
      {
        return l->m_rules[0]->m_drawRule.m_depth > r->m_rules[0]->m_drawRule.m_depth;
      });
    }
    else
      m_tree.Add(oe);
  }

private:
  m4::Tree<CPUDrawer::OverlayWrapper const *, OverlayWrapperTraits> m_tree;
};

CPUDrawer::CPUDrawer(Params const & params)
  : m_generationCounter(0)
  , m_visualScale(params.m_visualScale)
{
  auto glyphParams = GlyphCache::Params("unicode_blocks.txt",
                                        "fonts_whitelist.txt",
                                        "fonts_blacklist.txt",
                                        2 * 1024 * 1024, m_visualScale, false);
  m_renderer = make_unique<SoftwareRenderer>(glyphParams, params.m_resourcesPrefix);
}

CPUDrawer::~CPUDrawer()
{
}

void CPUDrawer::BeginFrame(uint32_t width, uint32_t height, dp::Color const & bgColor)
{
  m_renderer->BeginFrame(width, height, bgColor);
}

void CPUDrawer::Flush()
{
  Render();
}

void CPUDrawer::DrawMyPosition(m2::PointD const & myPxPotision)
{
  m_renderer->DrawSymbol(myPxPotision, dp::Center, IconInfo("current-position"));
}

void CPUDrawer::DrawSearchResult(m2::PointD const & pxPosition)
{
  m_renderer->DrawSymbol(pxPosition, dp::Top, IconInfo("search-result"));
}

void CPUDrawer::DrawSearchArrow(double azimut)
{
  PathWrapper path;

  {
    PathParams firstPass;
    firstPass.m_isFill = true;
    firstPass.m_fillColor = agg::rgba8(0x4C, 0xAF, 0x50);
    firstPass.m_isStroke = true;
    firstPass.m_strokeColor = agg::rgba8(0x0, 0x0, 0x0, 0x1A);
    firstPass.m_isEventOdd = true;
    firstPass.m_strokeWidth = 6;

    path.AddParams(firstPass);
  }

  {
    PathParams secondPass;
    secondPass.m_isFill = false;
    secondPass.m_fillColor = agg::rgba8(0, 0, 0);
    secondPass.m_isStroke = true;
    secondPass.m_strokeColor = agg::rgba8(0xFF, 0xFF, 0xFF);
    secondPass.m_strokeWidth = 4;

    path.AddParams(secondPass);
  }

  path.MoveTo(m2::PointD(349.05025, 55.3532299));
  path.CurveTo(m2::PointD(352.214211, 55.3532299),
               m2::PointD(354.779108, 52.671954),
               m2::PointD(354.779108, 49.3644327));
  path.CurveTo(m2::PointD(354.779108, 46.0569113),
               m2::PointD(352.214211, 43.3756355),
               m2::PointD(349.05025,  43.3756355));
  path.CurveTo(m2::PointD(345.886289, 43.3756355),
               m2::PointD(343.321392, 46.0569113),
               m2::PointD(343.321392, 49.3644327));
  path.CurveTo(m2::PointD(343.321392, 52.671954),
               m2::PointD(345.886289, 55.3532299),
               m2::PointD(349.05025,  55.3532299));
  path.ClosePath();
  path.MoveTo(m2::PointD(333.752104, 42.7175982));

  path.CurveTo(m2::PointD(332.709155, 43.0810222),
               m2::PointD(332.359503, 42.6413443),
               m2::PointD(332.978094, 41.7252445));
  path.LineTo(m2::PointD(347.935833, 19.5736386));
  path.CurveTo(m2::PointD(348.551309, 18.6621528),
               m2::PointD(349.546076, 18.6575388),
               m2::PointD(350.164667, 19.5736386));
  path.LineTo(m2::PointD(365.122406, 41.7252445));

  path.CurveTo(m2::PointD(365.737881, 42.6367303),
               m2::PointD(365.384538, 43.0786501),
               m2::PointD(364.348396, 42.7175982));
  path.LineTo(m2::PointD(349.05025, 37.3868384));
  path.LineTo(m2::PointD(333.752104, 42.7175982));
  path.ClosePath();

  m2::RectD symbolRect;
  path.BoundingRect(symbolRect);
  m2::PointD symbolCenter = symbolRect.Center();

  m2::RectD frameRect = m_renderer->FrameRect();
  m2::PointD halfSize(0.5 * frameRect.SizeX(), 0.5 * frameRect.SizeY());
  m2::PointD frameCenter = frameRect.Center();

  double length = halfSize.x;
  double azIn2Pi = ang::AngleIn2PI(azimut);

  if (azIn2Pi > math::pi4 && azIn2Pi < math::pi2 + math::pi4)
  {
    length = halfSize.y;
    azIn2Pi = fabs(math::pi2 - azimut);
  }
  else if (azIn2Pi > math::pi + math::pi4 && azIn2Pi < math::pi + math::pi2 + math::pi4)
  {
    length = halfSize.y;
    azIn2Pi = fabs(math::pi2 - azimut);
  }

  double cosa = cos(azIn2Pi);
  if (!my::AlmostEqualULPs(cosa, 0.0))
    length = length / fabs(cosa);

  m2::PointD offsetPoint(length - 0.65 * symbolRect.SizeY(), 0.0);
  offsetPoint.Rotate(-azimut);

  math::Matrix<double, 3, 3> m = math::Shift(math::Rotate(math::Scale(math::Shift(math::Identity<double, 3>(),
                                                                                -symbolCenter),
                                                                      1.5, 1.5),
                                                          math::pi2 - azimut),
                                             frameCenter + offsetPoint);

  m_renderer->DrawPath(path, m);
}

void CPUDrawer::EndFrame(FrameImage & image)
{
  m_renderer->EndFrame(image);
  m_stylers.clear();
  m_areasGeometry.clear();
  m_pathGeometry.clear();
  m_roadNames.clear();

  m_areaPathShapes.clear();
  m_pointShapes.clear();
  m_textShapes.clear();
  m_pathTextShapes.clear();
  m_overlayList.clear();
}

void CPUDrawer::DrawSymbol(m2::PointD const & pt, dp::Anchor pos, DrawRule const & rule)
{
  m_pointShapes.emplace_back(pt, pos, TYPE_SYMBOL, rule, GetGeneration());
  OverlayWrapper & overlay = AddOverlay(&m_pointShapes.back());

  IconInfo icon;
  ConvertStyle(overlay.m_rules[0]->m_drawRule.m_rule->GetSymbol(), icon);

  m2::RectD rect;
  m_renderer->CalculateSymbolMetric(pt, pos, icon, rect);
  overlay.m_rects.push_back(rect);
}

void CPUDrawer::DrawPath(PathInfo const & path, DrawRule const * rules, size_t count)
{
  FeatureID const & id = Insert(path);
  for (size_t i = 0; i < count; ++i)
    m_areaPathShapes.emplace_back(id, rules[i], GetGeneration(), TYPE_PATH);
}

void CPUDrawer::DrawArea(AreaInfo const & area, DrawRule const & rule)
{
  m_areaPathShapes.emplace_back(Insert(area), rule, GetGeneration(), TYPE_AREA);
}

void CPUDrawer::DrawText(m2::PointD const & pt, dp::Anchor pos,
                         FeatureStyler const & fs, DrawRule const & rule)
{
  m_textShapes.emplace_back(pt, pos, Insert(fs), rule, GetGeneration(), TYPE_TEXT);
  TextShape const * shape = &m_textShapes.back();
  OverlayWrapper & overlay = AddOverlay(shape);

  TTextRendererCall callback = [this, &overlay](m2::PointD const & pt, dp::Anchor anchor,
                                                dp::FontDecl const & primFont,
                                                dp::FontDecl const & secFont,
                                                strings::UniString const & primText,
                                                strings::UniString const & secText)
  {
    m2::RectD rect;
    if (secText.empty())
      m_renderer->CalculateTextMetric(pt, anchor, primFont, primText, rect);
    else
      m_renderer->CalculateTextMetric(pt, anchor, primFont, secFont, primText, secText, rect);
    overlay.m_rects.push_back(rect);
  };

  CallTextRendererFn(shape, callback);
}

void CPUDrawer::DrawPathText(PathInfo const & info, FeatureStyler const & fs, DrawRule const & rule)
{
  FeatureID const & geomID = Insert(info);
  FeatureID const & styleID = Insert(fs);
  ASSERT(geomID == styleID, ());
  UNUSED_VALUE(styleID);
  m_pathTextShapes.emplace_back(geomID, rule, GetGeneration(), TYPE_PATH_TEXT);
  ComplexShape const * shape = &m_pathTextShapes.back();
  OverlayWrapper & overlay = AddOverlay(shape);

  TPathTextRendererCall callback = [this, &overlay](PathInfo const & geometry,
                                                    dp::FontDecl const & font,
                                                    strings::UniString const & text)
  {
    m_renderer->CalculateTextMetric(geometry, font, text, overlay.m_rects);
  };

  CallTextRendererFn(shape, callback);
}

void CPUDrawer::DrawPathNumber(PathInfo const & path, FeatureStyler const & fs, DrawRule const & rule)
{
  dp::FontDecl font;
  ConvertStyle(rule.m_rule->GetShield(), m_visualScale, font);

  FeatureID const & id = Insert(fs.m_refText);
  GenerateRoadNumbers(path, font, fs, [this, &id](m2::PointD const & pt, dp::FontDecl const & font, string const & /*text*/)
  {
    m_roadNumberFont = font;
    m_textShapes.emplace_back(pt, dp::Center, id, DrawRule(), GetGeneration(), TYPE_ROAD_NUMBER);
    TextShape const * shape = &m_textShapes.back();
    OverlayWrapper & overlay = AddOverlay(shape);

    TRoadNumberRendererCall callback = [this, &overlay](m2::PointD const & pt, dp::Anchor anchor,
                                                        dp::FontDecl const & font, strings::UniString const & text)
    {
      m2::RectD rect;
      m_renderer->CalculateTextMetric(pt, anchor, font, text, rect);
      overlay.m_rects.push_back(rect);
    };

    CallTextRendererFn(shape, callback);
  });
}

void CPUDrawer::GenerateRoadNumbers(PathInfo const & path, dp::FontDecl const & font, FeatureStyler const & fs,
                                    TRoadNumberCallbackFn const & fn)
{
  double const length = path.GetFullLength();
  if (length >= (fs.m_refText.size() + 2) * font.m_size)
  {
    size_t const count = size_t(length / 1000.0) + 2;

    m2::PointD pt;
    for (size_t j = 1; j < count; ++j)
    {
      if (path.GetSmPoint(double(j) / double(count), pt))
        fn(pt, font, fs.m_refText);
    }
  }
}

void CPUDrawer::DrawFeatureStart(FeatureID const & id)
{
  m_currentFeatureID = id;
}

void CPUDrawer::DrawFeatureEnd(FeatureID const & id)
{
  ASSERT_EQUAL(m_currentFeatureID, id, ());
  UNUSED_VALUE(id);
  m_currentFeatureID = FeatureID();
}

FeatureID const & CPUDrawer::GetCurrentFeatureID() const
{
  ASSERT(m_currentFeatureID.IsValid(), ());
  return m_currentFeatureID;
}

FeatureID const & CPUDrawer::Insert(PathInfo const & info)
{
  return InsertImpl(GetCurrentFeatureID(), m_pathGeometry, info);
}

FeatureID const & CPUDrawer::Insert(AreaInfo const & info)
{
  return InsertImpl(GetCurrentFeatureID(), m_areasGeometry, info);
}

FeatureID const & CPUDrawer::Insert(FeatureStyler const & styler)
{
  return InsertImpl(GetCurrentFeatureID(), m_stylers, styler);
}

FeatureID const & CPUDrawer::Insert(string const & text)
{
  return InsertImpl(GetCurrentFeatureID(), m_roadNames, text);
}

void CPUDrawer::Render()
{
  m_areaPathShapes.sort([](BaseShape const & lsh, BaseShape const & rsh)
  {
    if (lsh.m_drawRule.m_depth == rsh.m_drawRule.m_depth)
      return lsh.m_generation < rsh.m_generation;

    return lsh.m_drawRule.m_depth < rsh.m_drawRule.m_depth;
  });

  auto const renderFn = [this](BaseShape const & s)
  {
    BaseShape const * shape = &s;
    switch (shape->m_type)
    {
    case TYPE_SYMBOL:
      DrawSymbol(static_cast<PointShape const *>(shape));
      break;
    case TYPE_PATH:
      DrawPath(static_cast<ComplexShape const *>(shape));
      break;
    case TYPE_AREA:
      DrawArea(static_cast<ComplexShape const *>(shape));
      break;
    case TYPE_PATH_TEXT:
      DrawPathText(static_cast<ComplexShape const *>(shape));
      break;
    case TYPE_TEXT:
      DrawText(static_cast<TextShape const *>(shape));
      break;
    case TYPE_ROAD_NUMBER:
      DrawRoadNumber(static_cast<TextShape const *>(shape));
      break;
    default:
      ASSERT(false, ());
      break;
    }
  };

  for_each(m_areaPathShapes.begin(), m_areaPathShapes.end(), renderFn);
  CPUOverlayTree tree;
  for_each(m_overlayList.begin(), m_overlayList.end(), [&tree](OverlayWrapper const & oe)
  {
    tree.replaceOverlayElement(&oe);
  });

  tree.forEach([&renderFn](OverlayWrapper const * oe)
  {
    ASSERT(oe->m_rules[0] != nullptr, ());
    renderFn(*oe->m_rules[0]);
    if (oe->m_ruleCount > 1)
    {
      ASSERT(oe->m_rules[1] != nullptr, ());
      renderFn(*oe->m_rules[1]);
    }
  });
}

void CPUDrawer::DrawSymbol(PointShape const * shape)
{
  ASSERT(shape->m_type == TYPE_SYMBOL, ());
  ASSERT(shape->m_drawRule.m_rule != nullptr, ());
  ASSERT(shape->m_drawRule.m_rule->GetSymbol() != nullptr, ());

  IconInfo info;
  ConvertStyle(shape->m_drawRule.m_rule->GetSymbol(), info);
  m_renderer->DrawSymbol(shape->m_position, shape->m_anchor, info);
}

void CPUDrawer::DrawPath(ComplexShape const * shape)
{
  ASSERT(shape->m_type == TYPE_PATH, ());
  ASSERT(shape->m_drawRule.m_rule != nullptr, ());
  ASSERT(shape->m_drawRule.m_rule->GetLine() != nullptr, ());

  PenInfo info;
  ConvertStyle(shape->m_drawRule.m_rule->GetLine(), m_visualScale, info);

  m_renderer->DrawPath(GetInfo(shape->m_geomID, m_pathGeometry), info);
}

void CPUDrawer::DrawArea(ComplexShape const * shape)
{
  ASSERT(shape->m_type == TYPE_AREA, ());
  ASSERT(shape->m_drawRule.m_rule != nullptr, ());
  ASSERT(shape->m_drawRule.m_rule->GetArea() != nullptr, ());

  BrushInfo info;
  ConvertStyle(shape->m_drawRule.m_rule->GetArea(), info);

  m_renderer->DrawArea(GetInfo(shape->m_geomID, m_areasGeometry), info);
}

void CPUDrawer::DrawPathText(ComplexShape const * shape)
{
  TPathTextRendererCall callback = [this](PathInfo const & geometry,
                                          dp::FontDecl const & font,
                                          strings::UniString const & text)
  {
    m_renderer->DrawPathText(geometry, font, text);
  };

  CallTextRendererFn(shape, callback);
}

void CPUDrawer::DrawRoadNumber(TextShape const * shape)
{
  TRoadNumberRendererCall callback = [this](m2::PointD const & pt, dp::Anchor pos,
                                            dp::FontDecl const & font, strings::UniString const & text)
  {
    m_renderer->DrawText(pt, pos, font, text);
  };

  CorrectFont(m_roadNumberFont);
  CallTextRendererFn(shape, callback);
}

void CPUDrawer::DrawText(TextShape const * shape)
{
  TTextRendererCall callback = [this](m2::PointD const & pt, dp::Anchor anchor,
                                      dp::FontDecl const & primFont, dp::FontDecl const & secFont,
                                      strings::UniString const & primText, strings::UniString const & secText)
  {
    if (secText.empty())
      m_renderer->DrawText(pt, anchor, primFont, primText);
    else
      m_renderer->DrawText(pt, anchor, primFont, secFont, primText, secText);
  };
  CallTextRendererFn(shape, callback);
}

CPUDrawer::OverlayWrapper & CPUDrawer::AddOverlay(BaseShape const * shape1, CPUDrawer::BaseShape const * shape2)
{
  BaseShape const * shapes[] = { shape1, shape2 };
  m_overlayList.emplace_back(shapes, shape2 == nullptr ? 1 : 2);
  return m_overlayList.back();
}

void CPUDrawer::CallTextRendererFn(TextShape const * shape, TTextRendererCall const & fn)
{
  ASSERT(shape->m_type == TYPE_TEXT, ());
  ASSERT(shape->m_drawRule.m_rule != nullptr, ());
  ASSERT(shape->m_drawRule.m_rule->GetCaption(0) != nullptr, ());
  FeatureStyler const & fs = GetInfo(shape->m_geomID, m_stylers);

  CaptionDefProto const * primCaption = shape->m_drawRule.m_rule->GetCaption(0);
  CaptionDefProto const * secCaption = shape->m_drawRule.m_rule->GetCaption(1);

  dp::FontDecl primFont, secFont;
  m2::PointD primOffset, secOffset;
  ConvertStyle(primCaption, m_visualScale, primFont, primOffset);
  CorrectFont(primFont);
  if (secCaption != nullptr)
  {
    ConvertStyle(secCaption, m_visualScale, secFont, secOffset);
    CorrectFont(secFont);
  }

  fn(shape->m_position + primOffset, shape->m_anchor, primFont, secFont,
     PreProcessText(fs.m_primaryText), PreProcessText(fs.m_secondaryText));
}

void CPUDrawer::CallTextRendererFn(TextShape const * shape, TRoadNumberRendererCall const & fn)
{
  string const & text = GetInfo(shape->m_geomID, m_roadNames);

  // Warning! This code processes text as left-to-right text
  // and doesn't reorder right-to-left text. To support right-to-left text
  // bidi algorithm should be applied.
  fn(shape->m_position, shape->m_anchor, m_roadNumberFont, strings::MakeUniString(text));
}

void CPUDrawer::CallTextRendererFn(ComplexShape const * shape, TPathTextRendererCall const & fn)
{
  ASSERT(shape->m_type == TYPE_PATH_TEXT, ());

  PathInfo const & path = GetInfo(shape->m_geomID, m_pathGeometry);
  FeatureStyler const & styler = GetInfo(shape->m_geomID, m_stylers);

  if (styler.m_offsets.empty())
    return;

  dp::FontDecl font;
  m2::PointD offset;
  ConvertStyle(shape->m_drawRule.m_rule->GetCaption(0), m_visualScale, font, offset);
  CorrectFont(font);

  fn(path, font, strings::MakeUniString(styler.GetPathName()));
}

GlyphCache * CPUDrawer::GetGlyphCache() const
{
  return m_renderer->GetGlyphCache();
}

ScreenBase CPUDrawer::CalculateScreen(m2::PointD const & center, int zoomModifier,
                                      uint32_t pxWidth, uint32_t pxHeight,
                                      FrameSymbols const & symbols, int & resultZoom)
{
  df::Navigator frameNavigator;
  frameNavigator.OnSize(pxWidth, pxHeight);

  uint32_t const tileSize = static_cast<uint32_t>(df::CalculateTileSize(pxWidth, pxHeight));

  m2::RectD rect = df::GetRectForDrawScale(scales::GetUpperComfortScale() - 1, center, tileSize, m_visualScale);
  if (symbols.m_showSearchResult && !rect.IsPointInside(symbols.m_searchResult))
  {
    double const kScaleFactor = 1.3;
    m2::PointD oldCenter = rect.Center();
    rect.Add(symbols.m_searchResult);
    double const centersDiff = 2 * (rect.Center() - oldCenter).Length();

    m2::RectD resultRect;
    resultRect.SetSizes(rect.SizeX() + centersDiff, rect.SizeY() + centersDiff);
    resultRect.SetCenter(center);
    resultRect.Scale(kScaleFactor);
    rect = resultRect;
    ASSERT(rect.IsPointInside(symbols.m_searchResult), ());
  }

  int baseZoom = df::GetDrawTileScale(rect, tileSize, m_visualScale);
  resultZoom = baseZoom + zoomModifier;
  int const minZoom = symbols.m_bottomZoom == -1 ? resultZoom : symbols.m_bottomZoom;
  resultZoom = my::clamp(resultZoom, minZoom, scales::GetUpperScale());
  rect = df::GetRectForDrawScale(resultZoom, rect.Center(), tileSize, m_visualScale);

  df::CheckMinGlobalRect(rect, tileSize, m_visualScale);
  df::CheckMinMaxVisibleScale(rect, -1, tileSize, m_visualScale);
  frameNavigator.SetFromRect(m2::AnyRectD(rect), tileSize, m_visualScale);

  return frameNavigator.Screen();
}

void CPUDrawer::Draw(FeatureData const & data)
{
  DrawFeatureStart(data.m_id);

  buffer_vector<DrawRule, 8> const & rules = data.m_styler.m_rules;
  buffer_vector<DrawRule, 8> pathRules;

  bool const isPath = !data.m_pathes.empty();
  bool const isArea = !data.m_areas.empty();

  drule::BaseRule const * pSymbolRule = nullptr;
  double symbolDepth = df::watch::minDepth;

  drule::BaseRule const * pShieldRule = nullptr;
  double shieldDepth = df::watch::minDepth;

  // separating path rules from other
  for (size_t i = 0; i < rules.size(); ++i)
  {
    drule::BaseRule const * pRule = rules[i].m_rule;

    bool const isSymbol = pRule->GetSymbol() != 0;
    bool const isCaption = pRule->GetCaption(0) != 0;

    if (pSymbolRule == nullptr && isSymbol)
    {
      pSymbolRule = pRule;
      symbolDepth = rules[i].m_depth;
    }

    if (pShieldRule == nullptr && pRule->GetShield() != nullptr)
    {
      pShieldRule = pRule;
      shieldDepth = rules[i].m_depth;
    }

    if (!isCaption && isPath && !isSymbol && (pRule->GetLine() != 0))
      pathRules.push_back(rules[i]);
  }

  if (!pathRules.empty())
  {
    for (auto i = data.m_pathes.cbegin(); i != data.m_pathes.cend(); ++i)
      DrawPath(*i, pathRules.data(), pathRules.size());
  }

  for (size_t i = 0; i < rules.size(); ++i)
  {
    drule::BaseRule const * pRule = rules[i].m_rule;
    double const depth = rules[i].m_depth;

    bool const isCaption = pRule->GetCaption(0) != 0;
    bool const isSymbol = pRule->GetSymbol() != 0;

    if (!isCaption)
    {
      // draw area
      if (isArea)
      {
        bool const isFill = pRule->GetArea() != 0;

        for (auto i = data.m_areas.cbegin(); i != data.m_areas.cend(); ++i)
        {
          if (isFill)
            DrawArea(*i, DrawRule(pRule, depth));
          else if (isSymbol)
            DrawSymbol(i->GetCenter(), dp::Center, DrawRule(pRule, depth));
        }
      }

      // draw point symbol
      if (isSymbol && !isPath && !isArea && ((pRule->GetType() & drule::node) != 0))
      {
        DrawSymbol(data.m_point, dp::Center, DrawRule(pRule, depth));
      }
    }
    else
    {
      if (!data.m_styler.m_primaryText.empty() && (pRule->GetCaption(0) != 0))
      {
        bool isN = ((pRule->GetType() & drule::way) != 0);

        dp::Anchor textPosition = dp::Center;
        if (pRule->GetCaption(0)->offset_y() != 0)
        {
          if (pRule->GetCaption(0)->offset_y() > 0)
            textPosition = dp::Bottom;
          else
            textPosition = dp::Top;
        }
        if (pRule->GetCaption(0)->offset_x() != 0)
        {
          if (pRule->GetCaption(0)->offset_x() > 0)
            textPosition = dp::Right;
          else
            textPosition = dp::Left;
        }

        // draw area text
        if (isArea)
        {
          for (auto i = data.m_areas.cbegin(); i != data.m_areas.cend(); ++i)
            DrawText(i->GetCenter(), textPosition, data.m_styler, DrawRule(pRule, depth));
        }

        // draw way name
        if (isPath && !isArea && isN && !data.m_styler.FilterTextSize(pRule))
        {
          for (auto i = data.m_pathes.cbegin(); i != data.m_pathes.cend(); ++i)
            DrawPathText(*i, data.m_styler, DrawRule(pRule, depth));
        }

        // draw point text
        isN = ((pRule->GetType() & drule::node) != 0);
        if (!isPath && !isArea && isN)
          DrawText(data.m_point, textPosition, data.m_styler, DrawRule(pRule, depth));
      }
    }
  }

  // draw road numbers
  if (isPath && !data.m_styler.m_refText.empty() && pShieldRule != nullptr)
    for (auto n : data.m_pathes)
      DrawPathNumber(n, data.m_styler, DrawRule(pShieldRule, shieldDepth));

  DrawFeatureEnd(data.m_id);
}

}
}


text:
<f:layout name="Default" />
<f:section name="Main">

    <f:cObject typoscriptObjectPath="lib.dynamicContent" data="{pageUid: '{data.uid}', colPos: '3'}" />

                    <f:cObject typoscriptObjectPath="lib.dynamicContent" data="{pageUid: '{data.uid}', colPos: '20'}" />

                    <f:cObject typoscriptObjectPath="lib.dynamicContent" data="{pageUid: '{data.uid}', colPos: '21'}" />

                    <f:cObject typoscriptObjectPath="lib.dynamicContent" data="{pageUid: '{data.uid}', colPos: '22'}" />

            <f:cObject typoscriptObjectPath="lib.dynamicContent" data="{pageUid: '{data.uid}', colPos: '0'}" />

</f:section>

redpajama_set_name: RedPajamaGithub


text:
package OpenXPKI::Server::API2::Plugin::UI::get_session_info;
use OpenXPKI::Server::API2::EasyPlugin;

=head1 NAME

OpenXPKI::Server::API2::Plugin::UI::get_session_info

=cut

# Project modules
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Server::API2::Types;

=head1 COMMANDS

=head2 get_session_info

B<Parameters>

=over

=item * C<XXX> I<Bool> - XXX. Default: XXX

=back

=cut
command "get_session_info" => {
} => sub {
    my ($self, $params) = @_;

    my $session = CTX('session');
    return {
        name            => $session->data->user,
        role            => $session->data->role,
        role_label      => CTX('config')->get([ 'auth', 'roles', $session->data->role, 'label' ]),
        pki_realm       => $session->data->pki_realm,
        pki_realm_label => CTX('config')->get([ 'system', 'realms', $session->data->pki_realm, 'label' ]),
        lang            => 'en',
        checksum        => CTX('config')->checksum(),
        sid             => substr($session->id,0,4),
    }
};

__PACKAGE__->meta->make_immutable;


text:
import * as React from 'react';
import './style.css';
import MenuBar from './Components/MenuBar';
import SlideShow from './Components/SlideShow';
import SearchBar from './Components/SearchBar';
import Caption from './Components/Caption';

class Header extends React.Component<{}, {}> {

  render() {
    return (

          <SlideShow />

          <MenuBar />

          <SearchBar />

    );
  }
}

export default Header;


text:
package org.tools.hqlbuilder.client;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swingeasy.CustomizableOptionPane;
import org.swingeasy.ETable;
import org.swingeasy.ETableConfig;
import org.swingeasy.ETableHeaders;
import org.swingeasy.ETableRecord;
import org.swingeasy.ETableRecordBean;
import org.swingeasy.MessageType;
import org.tools.hqlbuilder.client.PathResolver.End;
import org.tools.hqlbuilder.client.PathResolver.Result;
import org.tools.hqlbuilder.client.PathResolver.TreeNode;
import org.tools.hqlbuilder.common.HibernateWebResolver;
import org.tools.hqlbuilder.common.HibernateWebResolver.ClassNode;

/**
 * @author Jurgen
 */
public class HqlWizard {
    protected static final Logger logger = LoggerFactory.getLogger(HqlWizard.class);

    protected static class Stop extends RuntimeException {
        private static final long serialVersionUID = -8660143360351472707L;
    }

    public static interface HqlWizardListener {
        void query(String query);
    }

    public static class Option<T> implements Comparable<Option<T>> {
        public Option(String label, T option) {
            super();
            this.label = label;
            this.option = option;
        }

        final String label;

        final T option;

        @Override
        public String toString() {
            return label;
        }

        @Override
        public int compareTo(final Option<T> other) {
            return new CompareToBuilder().append(label, other.label).toComparison();
        }
    }

    protected ETable<Row> table;

    protected final ETableHeaders<Row> headers = new ETableHeaders<>();

    protected final HqlWizardListener listener;

    protected final JFrame parent;

    protected final Map<String, Integer> aliasUses = new HashMap<>();

    protected final List<String> orderedFields = new ArrayList<>();

    protected final HibernateWebResolver meta;

    protected int lastSelectedParentRow = -1;

    protected final JFrame queryBuilder = new JFrame();

    public HqlWizard(HqlWizardListener listener, JFrame parent, HibernateWebResolver info) {
        this.listener = listener;
        this.parent = parent;
        this.meta = info;
        initComponents();
    }

    protected void initComponents() {
        queryBuilder.setTitle(HqlResourceBundle.getMessage("find path between classes"));
        if (parent != null) {
            queryBuilder.setIconImage(parent.getIconImage());
        }
        ETableConfig cfg = new ETableConfig(true);
        table = new ETable<>(cfg);
        headers.add("collection", Boolean.class, false);
        headers.add("class", String.class, false);
        headers.add("parent", String.class, false);
        headers.add("path", String.class, false);
        headers.add("inner join", Boolean.class, true);
        headers.add("select", Boolean.class, true);
        orderedFields.add("collection");
        orderedFields.add("simpleClassName");
        orderedFields.add("parent");
        orderedFields.add("path");
        orderedFields.add("innerjoin");
        orderedFields.add("select");
        table.setHeaders(headers);

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
                        int selectedRow = table.getSelectedRow();
                        if (selectedRow != -1) {
                            Row row = table.getRecordAtVisualRow(selectedRow).getBean();
                            selectTargetAfterSource(row, false);
                        }
                    } else if (e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1) {
                        int selectedRow = table.getSelectedRow();
                        lastSelectedParentRow = -1;
                        if (selectedRow != -1) {
                            Row parentRef = table.getRecordAtVisualRow(selectedRow).getBean().getParentRef();
                            if (parentRef != null) {
                                lastSelectedParentRow = getRows().indexOf(parentRef);
                            }
                        }
                        table.repaint();
                    }

                } catch (Stop ex) {
                    logger.error("{}", ex);
                }
            }
        });

        queryBuilder.getContentPane().add(new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS),
                BorderLayout.CENTER);
        JPanel actions = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        actions.add(new JButton(new AbstractAction("done") {
            private static final long serialVersionUID = -4588826583392694461L;

            @Override
            public void actionPerformed(ActionEvent e) {
                queryBuilder.dispose();
                fini();
            }
        }));
        queryBuilder.getContentPane().add(actions, BorderLayout.SOUTH);
        queryBuilder.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        Dimension size = new Dimension(1000, 600);
        queryBuilder.setPreferredSize(size);
        queryBuilder.setSize(size);

        try {
            table.packColumn(0, 3);
            table.packColumn(4, 3);
            table.packColumn(5, 3);
        } catch (Exception ex) {
            //
        }

        table = table.stsi();

        SwingUtilities.invokeLater(() -> queryBuilder.setVisible(true));

        selectPoints();
    }

    protected void fini() {
        StringBuilder q1 = new StringBuilder();
        StringBuilder q2 = new StringBuilder();
        Iterator<Row> iterator = getRows().iterator();

        if (!iterator.hasNext()) {
            return;
        }

        Row firstRow = iterator.next();
        if (firstRow.select) {
            q1.append(" ").append(firstRow.getAlias()).append(getNewline());
        }
        q2.append("from ").append(firstRow.getPath()).append(" ").append(getAlias(firstRow.getAlias())).append(getNewline());
        while (iterator.hasNext()) {
            Row row = iterator.next();
            if (row.getPath().startsWith("SUB")) {
                // TODO "SUB"
                continue;
            }
            if (row.getInnerjoin()) {
                q2.append("inner join ");
            } else {
                q2.append("left outer join ");
            }
            q2.append(row.getParent()).append(".").append(row.getPath()).append(" ").append(getAlias(row.getAlias())).append(getNewline());
            if (row.select) {
                q1.append(" , ").append(row.getAlias()).append(getNewline());
            }
        }
        listener.query("select" + getNewline() + q1 + q2);
    }

    private String getNewline() {
        // return HqlBuilderFrame.getNewline();
        return "\n"; // FIXME newline
    }

    public List<Row> getRows() {
        List<Row> rows = new ArrayList<>();
        for (int j = 0; j < table.getRowCount(); j++) {
            ETableRecord<Row> record = table.getRecordAtVisualRow(j);
            rows.add(record.getBean());
        }

        return Collections.unmodifiableList(rows);
    }

    protected String getAlias(String base) {
        Integer count = aliasUses.get(base);
        if (count == null) {
            count = 1;
        } else {
            count++;
            base += count;
        }
        aliasUses.put(base, count);
        return base;
    }

    protected void selectPoints() {
        Row sourceRow = selectSource();

        if (sourceRow == null) {
            queryBuilder.dispose();
            return;
        }

        selectTargetAfterSource(sourceRow, true);
    }

    protected void selectTargetAfterSource(Row sourceRow, boolean addSingleRow) {
        Option<ClassNode> targetNode = selectTarget();

        if (targetNode == null) {
            if (addSingleRow) {
                table.addRecord(new ETableRecordBean<>(orderedFields, sourceRow));
            }
            return;
        }

        List<TreeNode> resolvedPath = resolvePath(sourceRow, targetNode);

        if (resolvedPath != null) {
            showAutoWizardResult(resolvedPath);
        }
    }

    protected List<TreeNode> resolvePath(Row sourceRow, Option<ClassNode> targetNode) {
        try {
            ClassNode source = meta.getNodes().get(sourceRow.type.getName());
            PathResolver pathResolver = new PathResolver(source, targetNode.option);
            while (true) {
                try {
                    pathResolver.findPath();
                } catch (Result ex) {
                    StringBuilder message = new StringBuilder();
                    for (TreeNode o : ex.resolvePath) {
                        message.append(o.value).append("
");
                    }
                    String[] options = {
                            HqlResourceBundle.getMessage("accept"),
                            HqlResourceBundle.getMessage("continue search"),
                            HqlResourceBundle.getMessage("stop") };
                    String rv = CustomizableOptionPane.showCustomDialog(parent, new JLabel("" + message.toString() + ""),
                            HqlResourceBundle.getMessage("find path between classes"), MessageType.QUESTION, options, options[1], null, null);
                    if (options[0].equals(rv)) {
                        return ex.resolvePath;
                    } else if (options[1].equals(rv)) {
                        continue;
                    } else {
                        break;
                    }
                }
            }
        } catch (End ex) {
            JOptionPane.showMessageDialog(parent, HqlResourceBundle.getMessage("no path found"));
        }
        return null;
    }

    protected Option<ClassNode> selectTarget() {
        Option<ClassNode> initialTarget;
        Collection<ClassNode> tmp = meta.getNodes().values();
        @SuppressWarnings("unchecked")
        Option<ClassNode>[] options = new Option[tmp.size()];
        int i = 0;
        for (ClassNode cn : tmp) {
            options[i++] = new Option<>(cn.getType().getSimpleName(), cn);
        }
        Arrays.sort(options);
        initialTarget = ClientUtils.showDialog(parent, HqlResourceBundle.getMessage("target class"), options);
        return initialTarget;
    }

    protected Row selectSource() {
        Row initialSelected;
        {
            final SortedSet<Row> options = new TreeSet<>();
            for (ClassNode node : meta.getClasses()) {
                String classname = node.getId();
                try {
                    Row row = new Row(classname.substring(classname.lastIndexOf('.') + 1));
                    row.alias = Character.toLowerCase(row.path.charAt(0)) + row.path.substring(1);
                    row.type = Class.forName(classname);
                    options.add(row);
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
            }
            initialSelected = ClientUtils.showDialog(parent, HqlResourceBundle.getMessage("source class"), options.toArray(new Row[options.size()]));
        }
        return initialSelected;
    }

    protected void showAutoWizardResult(List<TreeNode> resolvePath) {
        Iterator<TreeNode> iterator = resolvePath.iterator();
        TreeNode first = iterator.next();

        Row row = new Row(first.value.getType().getSimpleName());
        row.alias = Character.toLowerCase(row.path.charAt(0)) + row.path.substring(1);
        row.type = first.value.getType();
        table.addRecord(new ETableRecordBean<>(orderedFields, row));

        while (iterator.hasNext()) {
            TreeNode next = iterator.next();
            Row row2 = new Row(next.property.getId());
            row2.alias = next.property.getId();
            row2.type = next.value.getType();
            row2.collection = next.property.isCollection();
            row2.setParentRef(row);
            table.addRecord(new ETableRecordBean<>(orderedFields, row2));
            row = row2;
        }
    }
}


text:
package org.inspirenxe.alfred;

import org.kitteh.irc.client.library.event.channel.ChannelJoinEvent;
import org.kitteh.irc.lib.net.engio.mbassy.listener.Handler;

public class Listener {

    @Handler
    public void onUserJoinChannel(ChannelJoinEvent event) {
        if (event.getClient().isUser(event.getUser())) {
            event.getChannel().sendMessage("Hello!");
            return;
        }
        event.getChannel().sendMessage(String.format("Welcome, %s! Thank you for joining %s.", event.getUser().getNick(), event.getChannel()
                .getName()));
    }
}


text:
package org.apache.struts2.interceptor;

import java.util.Map;

/**
 * Actions implementing the CookiesAware interface will receive
 * a Map of filtered cookies via the setCookiesMap method.
 *
 * Please note that the {@link CookieInterceptor} needs to be
 * activated to receive a cookies map.
 */
public interface CookiesAware {
    /**
     * Sets a map of filtered cookies.
     * @param cookies the cookies
     */
    void setCookiesMap(Map<String, String> cookies);
}


text:
package org.openfact.models.utils;

import org.openfact.component.ComponentFactory;
import org.openfact.component.ComponentModel;
import org.openfact.models.OpenfactSession;
import org.openfact.provider.Provider;
import org.openfact.provider.ProviderConfigProperty;
import org.openfact.provider.ProviderFactory;

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

/**
 * @author Stian Thorgersen
 */
public class ComponentUtil {

    public static Map<String, ProviderConfigProperty> getComponentConfigProperties(OpenfactSession session, ComponentModel component) {
        try {
            List<ProviderConfigProperty> l = getComponentFactory(session, component).getConfigProperties();
            Map<String, ProviderConfigProperty> properties = new HashMap<>();
            for (ProviderConfigProperty p : l) {
                properties.put(p.getName(), p);
            }
            return properties;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ComponentFactory getComponentFactory(OpenfactSession session, ComponentModel component) {
        Class<? extends Provider> provider = session.getProviderClass(component.getProviderType());
        if (provider == null) {
            throw new RuntimeException("Invalid provider type '" + component.getProviderType() + "'");
        }

        ProviderFactory<? extends Provider> f = session.getOpenfactSessionFactory().getProviderFactory(provider, component.getProviderId());
        if (f == null) {
            throw new RuntimeException("No such provider '" + component.getProviderId() + "'");
        }

        ComponentFactory cf = (ComponentFactory) f;
        return cf;
    }

}


text:
package es.npatarino.android.gotchallenge.characters.data.source.network;

public class JSONGoTCharacter {

  public String name;
  public String imageUrl;
  public String description;
  public String houseId;
  public String houseName;
  public String houseImageUrl;

}


text:
#if HALE_INCLUDES
#include "hale_memory.h"
#endif

namespace hale {

struct PagedMemory;

#define hale_memory_push(Type, Memory, Count)\
    (Type*)memory_push((Memory), (Count) * sizeof(Type))

#define hale_memory_at(Type, Memory, At) \
    ( hale_assert((At * sizeof(Type)) <= (Memory)->size), \
      (Type*)((Memory)->base) + At \
    )

#define hale_memory_end(Type, Memory) \
    ( (Type*)((u8*)((Memory)->base) + (Memory)->size) )

#define hale_memory_begin(Type, Memory) \
    ( (Type*)(Memory)->base )

#define hale_memory_count(Type, Memory) \
    ( hale_memory_end(Type, Memory) - hale_memory_begin(Type, Memory) )

struct PagedMemory
{
    void *base;
    memi size;
    memi capacity;
    memi reserved;
};

// NOTE: These are implemented in platform.

void  memory_init(PagedMemory *memory, memi reserve, void *base);
void *memory_push(PagedMemory *memory, memi size);
void *memory_pop(PagedMemory *memory, memi size);

//
//
//

struct StackMemory
{
    void *base;
    memi size;
    memi capacity;

    PagedMemory *stack;

    StackMemory(PagedMemory *stack);
    ~StackMemory();

#if 0
    inline _T *
    ptr() {
        return base;
    }

    inline _T &
    ref() {
        return *ptr();
    }

    inline _T &operator *() {
        return ref();
    }
    inline _T *operator ->() {
        return ptr();
    }
    inline operator _T*() {
        return ptr();
    }
#endif
};

inline void *
memory_push_capacity(StackMemory *memory, memi size)
{
    memory->capacity += size;
    return memory_push(memory->stack, size);
}

inline void *
memory_pop(StackMemory *memory, memi size)
{
    hale_assert_input(memory->capacity >= size);
    memory_pop(memory->stack, size);
    void *ret = (u8*)memory->base + memory->capacity;
    memory->capacity -= size;
    return ret;
}

inline void *
memory_push(StackMemory *memory, memi size)
{
    if (memory->size + size > memory->capacity) {
        memory_push_capacity(memory, size);
    }
    void *ret = (u8*)memory->base + memory->size;
    memory->size += size;
    return ret;
}

StackMemory::StackMemory(PagedMemory *_stack) :
    stack(_stack),
    base(((u8*)_stack->base) + _stack->size),
    size(0),
    capacity(0)
{}

StackMemory::~StackMemory() {
    if (capacity) {
        memory_pop(this, capacity);
    }
}

} // namespace hale

#endif // HALE_STACK_MEMORY_H


text:
package org.ovirt.engine.ui.uicommon;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.core.common.*;

@SuppressWarnings("unused")
public interface ICommandTarget
{
	void ExecuteCommand(UICommand command);
}


text:
sr.fn.shippers.showConfirmationDialog = function() {
  var contents = i18n.are_you_sure;
  var dialog = shared.draw.dialog('','update_shipper_dialog', contents);
  var loader = shared.draw.loading(true,null,dialog);
  var okbutton = shared.create.dialog_button(i18n.menu.ok, function() {
    loader.show();
    sr.fn.debug.ajaxLog({
      action_taken:'confirmed_update_shipper_dialog'
    });
    window.location = '/shippers/update_all';
  });
  dialog.append(okbutton);
}
;


text:
/* Various useful definitions */

typedef unsigned int size_t;

extern void *malloc(size_t);

extern int bor(int, int);
extern int band(int, int);

extern void validptr(void *);

extern long random(void) ;
extern void assert(int);
extern int assume(int);
extern void exit(int);
extern int csolve_exit(int);

#define INT_MIN -2147483648
#define INT_MAX 2147483647

#define LONG_MIN -2147483648
#define LONG_MAX 2147483647

extern int errno;

#define EPERM            1      /* Operation not permitted */
#define ENOENT           2      /* No such file or directory */
#define ESRCH            3      /* No such process */
#define EINTR            4      /* Interrupted system call */
#define EIO              5      /* I/O error */
#define ENXIO            6      /* No such device or address */
#define E2BIG            7      /* Argument list too long */
#define ENOEXEC          8      /* Exec format error */
#define EBADF            9      /* Bad file number */
#define ECHILD          10      /* No child processes */
#define EAGAIN          11      /* Try again */
#define ENOMEM          12      /* Out of memory */
#define EACCES          13      /* Permission denied */
#define EFAULT          14      /* Bad address */
#define ENOTBLK         15      /* Block device required */
#define EBUSY           16      /* Device or resource busy */
#define EEXIST          17      /* File exists */
#define EXDEV           18      /* Cross-device link */
#define ENODEV          19      /* No such device */
#define ENOTDIR         20      /* Not a directory */
#define EISDIR          21      /* Is a directory */
#define EINVAL          22      /* Invalid argument */
#define ENFILE          23      /* File table overflow */
#define EMFILE          24      /* Too many open files */
#define ENOTTY          25      /* Not a typewriter */
#define ETXTBSY         26      /* Text file busy */
#define EFBIG           27      /* File too large */
#define ENOSPC          28      /* No space left on device */
#define ESPIPE          29      /* Illegal seek */
#define EROFS           30      /* Read-only file system */
#define EMLINK          31      /* Too many links */
#define EPIPE           32      /* Broken pipe */
#define EDOM            33      /* Math argument out of domain of func */
#define ERANGE          34      /* Math result not representable */

extern long int atol(char * __attribute__ ((array)));

extern char *strtok(char * __attribute__ ((array)), char * __attribute__ ((array)));

#define NULL   0

#define FILE   int

#define stdout (FILE *)0
#define stdin  (FILE *)1
#define stderr (FILE *)2

extern FILE *fopen(char * __attribute__ ((array)), char * __attribute__ ((array)));
extern int fprintf(FILE *, char * __attribute__ ((array)), ...);
extern int printf(char * __attribute__ ((array)), ...);
extern char *fgets(char * __attribute__ ((array)), int, FILE *);
extern int *getc(FILE *);
extern int sscanf(char * __attribute__ ((array)), char * __attribute__ ((array)), ...);

#define CLOCKS_PER_SEC 1000

typedef long int clock_t;

extern clock_t clock(void);

extern double sqrt(double);
extern double fabs(double);


text:
@implementation OBASituationsViewController

#pragma mark -
#pragma mark Initialization

@synthesize args;

- (id) initWithApplicationDelegate:(OBAApplicationDelegate*)appDelegate situations:(NSArray*)situations {

    if (self = [super initWithStyle:UITableViewStylePlain]) {
        _appDelegate = appDelegate;
        _situations = situations;
        self.navigationItem.title = NSLocalizedString(@"Service Alerts",@"self.navigationItem.title");
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self hideEmptySeparators];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [TestFlight passCheckpoint:[NSString stringWithFormat:@"View: %@", [self class]]];
    [[GAI sharedInstance].defaultTracker set:kGAIScreenName
                                       value:[NSString stringWithFormat:@"View: %@", [self class]]];
    [[GAI sharedInstance].defaultTracker
     send:[[GAIDictionaryBuilder createAppView] build]];
}

#pragma mark -
#pragma mark View lifecycle

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    int count = [_situations count];
    if( count == 0 )
        count = 1;
    return count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if( [_situations count] == 0 ) {
        UITableViewCell * cell = [UITableViewCell getOrCreateCellForTableView:tableView];
        cell.textLabel.text = NSLocalizedString(@"No active service alerts",@"cell.textLabel.text");
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:18];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }

    OBASituationV2 * situation = _situations[indexPath.row];

    UITableViewCell * cell = [UITableViewCell getOrCreateCellForTableView:tableView];
    cell.textLabel.text = situation.summary;
    cell.textLabel.textAlignment = UITextAlignmentCenter;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if( [_situations count] > 0) {
        OBASituationV2 * situation = _situations[indexPath.row];
        OBASituationViewController * vc = [[OBASituationViewController alloc] initWithApplicationDelegate:_appDelegate situation:situation];
        vc.args = self.args;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end


text:
<?php

/** Upgrade the metadataextractor module to version 1.1.0. */
class Metadataextractor_Upgrade_1_1_0 extends MIDASUpgrade
{
    /** @var string */
    public $moduleName = 'metadataextractor';

    /** Post database upgrade. */
    public function postUpgrade()
    {
        /** @var SettingModel $settingModel */
        $settingModel = MidasLoader::loadModel('Setting');
        $configPath = LOCAL_CONFIGS_PATH.DIRECTORY_SEPARATOR.$this->moduleName.'.local.ini';

        if (file_exists($configPath)) {
            $config = new Zend_Config_Ini($configPath, 'global');
            $settingModel->setConfig(METADATAEXTRACTOR_HACHOIR_METADATA_COMMAND_KEY, $config->get('hachoir', METADATAEXTRACTOR_HACHOIR_METADATA_COMMAND_DEFAULT_VALUE), $this->moduleName);

            $config = new Zend_Config_Ini($configPath, null, true);
            unset($config->global->hachoir);

            $writer = new Zend_Config_Writer_Ini();
            $writer->setConfig($config);
            $writer->setFilename($configPath);
            $writer->write();
        } else {
            $settingModel->setConfig(METADATAEXTRACTOR_HACHOIR_METADATA_COMMAND_KEY, METADATAEXTRACTOR_HACHOIR_METADATA_COMMAND_DEFAULT_VALUE, $this->moduleName);
        }
    }
}


text:
description = 'Produces new astro chart every minute while script runs and sets it as desktop background. Parses data once at beginning. For more see repository README.'
inputs = {'astro' : 'C:/Users/Nathan/Dropbox/GitHub/astro/inputs'}
outputs = {'astro' : 'C:/Users/Nathan/Dropbox/GitHub/astro/outputs'}
script = str(os.path.realpath(__file__)) if '__file__' in globals() else 'Current Script Unknown'
from X_Imports import *
header.scriptsummary(script, inputs, outputs)
pd.options.mode.chained_assignment = None
########################################################################################

# PARAMS
difference_from_utc_standard = -8

# GET AND PARSE DATA
temp = astro.parse_sr_ss(inputs, difference_from_utc_standard)
s_set = temp['s_set']
s_rise = temp['s_rise']
year = temp['year']

# PLOT ONCE AND SAVE IN OUTPUT FOLDER
os.chdir(outputs['astro'])
astro.astroplot(s_rise, s_set, outputs, year)


text:
declare namespace javax {
  namespace naming {

    interface Context {
      public static readonly INITIAL_CONTEXT_FACTORY: java.lang.String
      public static readonly OBJECT_FACTORIES: java.lang.String
      public static readonly STATE_FACTORIES: java.lang.String
      public static readonly URL_PKG_PREFIXES: java.lang.String
      public static readonly PROVIDER_URL: java.lang.String
      public static readonly DNS_URL: java.lang.String
      public static readonly AUTHORITATIVE: java.lang.String
      public static readonly BATCHSIZE: java.lang.String
      public static readonly REFERRAL: java.lang.String
      public static readonly SECURITY_PROTOCOL: java.lang.String
      public static readonly SECURITY_AUTHENTICATION: java.lang.String
      public static readonly SECURITY_PRINCIPAL: java.lang.String
      public static readonly SECURITY_CREDENTIALS: java.lang.String
      public static readonly LANGUAGE: java.lang.String
      public static readonly APPLET: java.lang.String
      lookup(arg0: javax.naming.Name): java.lang.Object
      lookup(arg0: java.lang.String | string): java.lang.Object
      bind(arg0: javax.naming.Name, arg1: java.lang.Object | any): void
      bind(arg0: java.lang.String | string, arg1: java.lang.Object | any): void
      rebind(arg0: javax.naming.Name, arg1: java.lang.Object | any): void
      rebind(arg0: java.lang.String | string, arg1: java.lang.Object | any): void
      unbind(arg0: javax.naming.Name): void
      unbind(arg0: java.lang.String | string): void
      rename(arg0: javax.naming.Name, arg1: javax.naming.Name): void
      rename(arg0: java.lang.String | string, arg1: java.lang.String | string): void
      list(arg0: javax.naming.Name): javax.naming.NamingEnumeration<javax.naming.NameClassPair>
      list(arg0: java.lang.String | string): javax.naming.NamingEnumeration<javax.naming.NameClassPair>
      listBindings(arg0: javax.naming.Name): javax.naming.NamingEnumeration<javax.naming.Binding>
      listBindings(arg0: java.lang.String | string): javax.naming.NamingEnumeration<javax.naming.Binding>
      destroySubcontext(arg0: javax.naming.Name): void
      destroySubcontext(arg0: java.lang.String | string): void
      createSubcontext(arg0: javax.naming.Name): javax.naming.Context
      createSubcontext(arg0: java.lang.String | string): javax.naming.Context
      lookupLink(arg0: javax.naming.Name): java.lang.Object
      lookupLink(arg0: java.lang.String | string): java.lang.Object
      getNameParser(arg0: javax.naming.Name): javax.naming.NameParser
      getNameParser(arg0: java.lang.String | string): javax.naming.NameParser
      composeName(arg0: javax.naming.Name, arg1: javax.naming.Name): javax.naming.Name
      composeName(arg0: java.lang.String | string, arg1: java.lang.String | string): java.lang.String
      addToEnvironment(arg0: java.lang.String | string, arg1: java.lang.Object | any): java.lang.Object
      removeFromEnvironment(arg0: java.lang.String | string): java.lang.Object
      getEnvironment(): java.util.Hashtable<unknown,unknown>
      close(): void
      getNameInNamespace(): java.lang.String
    }

  }
}


text:
/*
 * CLIENT VIEW
 * The king of all views.
 */

'use strict';

+function(window, $, _) {

    window.LCB = window.LCB || {};

    window.LCB.ClientView = Backbone.View.extend({
        el: '#lcb-client',
        events: {
            'click .lcb-tab': 'toggleSideBar',
            'click .lcb-header-toggle': 'toggleSideBar'
        },
        initialize: function(options) {
            this.client = options.client;
            //
            // Subviews
            //
            this.browser = new window.LCB.BrowserView({
                el: this.$el.find('.lcb-rooms-browser'),
                rooms: this.client.rooms,
                client: this.client
            });
            this.tabs = new window.LCB.TabsView({
                el: this.$el.find('.lcb-tabs'),
                rooms: this.client.rooms,
                client: this.client
            });
            this.panes = new window.LCB.PanesView({
                el: this.$el.find('.lcb-panes'),
                rooms: this.client.rooms,
                client: this.client
            });
            this.window = new window.LCB.WindowView({
                rooms: this.client.rooms,
                client: this.client
            });
            this.hotKeys = new window.LCB.HotKeysView({
                rooms: this.client.rooms,
                client: this.client
            });
            this.status = new window.LCB.StatusView({
                el: this.$el.find('.lcb-status-indicators'),
                client: this.client
            });
            this.accountButton = new window.LCB.AccountButtonView({
                el: this.$el.find('.lcb-account-button'),
                model: this.client.user
            });
            this.desktopNotifications = new window.LCB.DesktopNotificationsView({
                rooms: this.client.rooms,
                client: this.client
            });
            if (this.client.options.filesEnabled) {
                this.upload = new window.LCB.UploadView({
                    el: this.$el.find('#lcb-upload'),
                    rooms: this.client.rooms
                });
            }
            //
            // Modals
            //
            this.profileModal = new window.LCB.ProfileModalView({
                el: this.$el.find('#lcb-profile'),
                model: this.client.user
            });
            this.accountModal = new window.LCB.AccountModalView({
                el: this.$el.find('#lcb-account'),
                model: this.client.user
            });
            this.tokenModal = new window.LCB.AuthTokensModalView({
                el: this.$el.find('#lcb-tokens')
            });
            this.notificationsModal = new window.LCB.NotificationsModalView({
                el: this.$el.find('#lcb-notifications')
            });
            //
            // Misc
            //
            this.client.status.once('change:connected', _.bind(function(status, connected) {
                this.$el.find('.lcb-client-loading').hide(connected);
            }, this));
            return this;
        },
        toggleSideBar: function(e) {
            this.$el.toggleClass('lcb-sidebar-opened');
        }
    });

    window.LCB.AccountButtonView = Backbone.View.extend({
        initialize: function() {
            this.model.on('change', this.update, this);
        },
        update: function(user){
            this.$('.lcb-account-button-username').text('@' + user.get('username'));
            this.$('.lcb-account-button-name').text(user.get('displayName'));
        }
    });

}(window, $, _);


text:
{{define "scripts"}}
<script src='/public/pure-0.6.0/menu-ui.js'></script>
<script src='/public/voting.js'></script>
{{end}}


text:
Include test
============

This should always fail, as the include is invalid.

.. include:: inexistant_file.rst


text:
package cc.suitalk.ipcinvoker.activate;

import android.os.HandlerThread;

/**
 * Created by albieliang on 2018/4/2.
 */

public interface ThreadCreator {

    Thread createThread(Runnable run, String name);

    HandlerThread createHandlerThread(String name);
}


text:
package java.util

object FormattableFlags {
  final val ALTERNATE = 4
  final val LEFT_JUSTIFY = 1
  final val UPPERCASE = 2
}


text:
!> @ingroup is_sorted
!>
!> @brief
!> Checks if a vector of #<data><full># values is sorted.
!>
!> @details
!> Checks if a vector of #<data><full># values is sorted according to the specified ordering.
!>
!> @retval sorted
!> Indicated if the vector of #<data><full># values is sorted according to the specified ordering.
!>
!> | Value | Meaning                  |
!> |:-----:|:------------------------ |
!> | true  | The vector is sorted     |
!> | false | The vector is not sorted |
!>
!> @param #<data><var>#
!> The vector of #<data><full># values to be checked for being sorted.
!>
!> @param ascending
!> Indicates if the ordering to be checked for is ascending or decending.
!>
!> | Value | Meaning         |
!> |:-----:|:--------------- |
!> | true  | Ascending order |
!> | false | Decending order |
!>
!> @note
!> An empty or single value vector is considered sorted.
!>
!> @author Arin R. Bratt
!> @date 12/07/2014

pure function is_sorted#data#(#<data><var>#,ascending) result(sorted)

  ! Parameters
  #<data><full>#, intent(in) :: #<data><var>#(:)
  logical, intent(in) :: ascending

  ! Result
  logical :: sorted

  ! Check ascending and call the right function.
  if (ascending) then
     sorted = is_sorted_asc#data#(#<data><var>#)
  else
     sorted = is_sorted_dec#data#(#<data><var>#)
  end if

end function is_sorted#data#


text:
package org.apache.pinot.tools.admin.command;

import java.io.File;
import org.apache.pinot.core.segment.processing.framework.SegmentProcessorConfig;
import org.apache.pinot.core.segment.processing.framework.SegmentProcessorFramework;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.data.Schema;
import org.apache.pinot.spi.plugin.PluginManager;
import org.apache.pinot.spi.utils.JsonUtils;
import org.apache.pinot.tools.Command;
import org.apache.pinot.tools.segment.processor.SegmentProcessorFrameworkSpec;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command to run {@link org.apache.pinot.core.segment.processing.framework.SegmentProcessorFramework}
 */
public class SegmentProcessorFrameworkCommand extends AbstractBaseAdminCommand implements Command {

  private static final Logger LOGGER = LoggerFactory.getLogger(SegmentProcessorFrameworkCommand.class);

  @Option(name = "-segmentProcessorFrameworkSpec", required = true, metaVar = "<String>", usage = "Path to SegmentProcessorFrameworkSpec json file")
  private String _segmentProcessorFrameworkSpec;

  @Option(name = "-help", help = true, aliases = {"-h", "--h", "--help"}, usage = "Print this message.")
  private boolean _help = false;

  @Override
  public boolean getHelp() {
    return _help;
  }

  @Override
  public String getName() {
    return "SegmentProcessorFramework";
  }

  @Override
  public String toString() {
    return ("SegmentProcessorFramework -segmentProcessorFrameworkSpec " + _segmentProcessorFrameworkSpec);
  }

  @Override
  public void cleanup() {
  }

  @Override
  public String description() {
    return "Runs the SegmentProcessorFramework";
  }

  @Override
  public boolean execute()
      throws Exception {

    SegmentProcessorFrameworkSpec segmentProcessorFrameworkSpec =
        JsonUtils.fileToObject(new File(_segmentProcessorFrameworkSpec), SegmentProcessorFrameworkSpec.class);

    File inputSegmentsDir = new File(segmentProcessorFrameworkSpec.getInputSegmentsDir());
    File outputSegmentsDir = new File(segmentProcessorFrameworkSpec.getOutputSegmentsDir());
    if (!outputSegmentsDir.exists()) {
      if (!outputSegmentsDir.mkdirs()) {
        throw new RuntimeException(
            "Did not find output directory, and could not create it either: " + segmentProcessorFrameworkSpec
                .getOutputSegmentsDir());
      }
    }

    PluginManager.get().init();

    Schema schema = Schema.fromFile(new File(segmentProcessorFrameworkSpec.getSchemaFile()));
    TableConfig tableConfig =
        JsonUtils.fileToObject(new File(segmentProcessorFrameworkSpec.getTableConfigFile()), TableConfig.class);
    SegmentProcessorConfig segmentProcessorConfig =
        new SegmentProcessorConfig.Builder().setSchema(schema).setTableConfig(tableConfig)
            .setRecordTransformerConfig(segmentProcessorFrameworkSpec.getRecordTransformerConfig())
            .setRecordFilterConfig(segmentProcessorFrameworkSpec.getRecordFilterConfig())
            .setPartitionerConfigs(segmentProcessorFrameworkSpec.getPartitionerConfigs())
            .setCollectorConfig(segmentProcessorFrameworkSpec.getCollectorConfig())
            .setSegmentConfig(segmentProcessorFrameworkSpec.getSegmentConfig()).build();

    SegmentProcessorFramework framework =
        new SegmentProcessorFramework(inputSegmentsDir, segmentProcessorConfig, outputSegmentsDir);
    try {
      LOGGER.info("Starting processing segments via SegmentProcessingFramework");
      framework.processSegments();
      LOGGER.info("Finished processing segments via SegmentProcessingFramework");
    } catch (Exception e) {
      LOGGER.error("Caught exception when running SegmentProcessingFramework. Exiting", e);
      return false;
    } finally {
      framework.cleanup();
    }
    return true;
  }
}


text:
FOUNDATION_EXPORT double Pods_WOWMarkSlider_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_WOWMarkSlider_TestsVersionString[];


text:
package info.fingo.urlopia.api.v2.user;

import info.fingo.urlopia.acceptance.AcceptanceService;
import info.fingo.urlopia.user.NoSuchUserException;
import info.fingo.urlopia.user.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Component
@RequiredArgsConstructor
@Slf4j
public class UserRolesProvider {

    private final AcceptanceService acceptanceService;

    public Set<String> getRolesFromUser(User user){
        var roles = new HashSet<String>();
        if (!user.isActive()){
            throw NoSuchUserException.inactiveAccount(user.getMail());
        }
        roles.add(User.Role.WORKER.toString());
        if (user.getLeader() || acceptanceService.hasActiveAcceptances(user)) {
            roles.add(User.Role.LEADER.toString());
        }
        if (user.getAdmin()) {
            roles.add(User.Role.ADMIN.toString());
        }
        return roles;
    }
}


text:
if( ! TodoyuInstaller ) {
	var TodoyuInstaller = {};
}

/**
 * Todoyu installer namespace
 *
 */
TodoyuInstaller = {

	/**
	 * Focus first form field
	 *
	 * @method	focusFirstFormField
	 * @param	{Element}	form
	 */
	focusFirstFormField: function(form) {
		if( form ) {
			var field = form.select('input[type!=hidden]', 'select', 'textarea', 'button').first();
			if( field && field.visible() ) {
				field.focus();
			}
		}
	},

	/**
	 * Hide the next button
	 *
	 * @method	hideButton
	 */
	hideButton: function() {
		$('next').hide();
	},

	/**
	 * Show the next button
	 *
	 * @method	showButton
	 */
	showButton: function() {
		$('next').show();
	},

	/**
	 * Submit locale selection
	 *
	 * @method	selectLocale
	 * @param	{String}	locale
	 */
	selectLocale: function(locale) {
		$('locale').value = locale;
		$$('form').first().submit()
	},

	/**
	 * Disable given text box if selected value == 0
	 *
	 * @method	disableTextBox
	 * @param	{Element}	selector
	 */
	disableTextBox: function(selector)	{
		textbox = document.getElementById('database_new');
		textbox.disabled = selector.options[selector.selectedIndex].value === '0';
	},

	/**
	 * Check database selection / declaration of new database to be created
	 *
	 * @method	checkDbSelect
	 */
	checkDbSelect: function() {
		var newDbName	= $F('database_new').strip();

		if( newDbName !== '' ) {
				// New DB name specified? deactivate selector
			$('database').selectedIndex	= 0;
			$('database').disabled	= true;

				// Make sure there's no existing DB with that name
			$('error-newnameTaken').hide();
			$$('button').first().show();
			$$('#database option').each(function(dbOption){
				if ( dbOption.value == newDbName) {
					$('error-newnameTaken').show();
					$('next').hide();
				}
			});
		} else {
			$('database').disabled	= false;
		}
	},

	/**
	 * Ensure password and it's repetition are identical
	 *
	 * @method	validateAdminAccountData
	 */
	validateAdminAccountData: function() {
		var companyOk	= this.validateCompanyName();
		var firstnameOk	= this.validateFirstname();
		var lastnameOk	= this.validateLastname();
		var passwordOk	= this.validatePassword();

		var submitButton= $$('button')[0];

		if ( companyOk && firstnameOk && lastnameOk && passwordOk ) {
			submitButton.show();
		} else {
			submitButton.hide();
		}
	},

	/**
	 * Set CSS class of field label red / default depending on given validation result
	 *
	 * @method	updateLabelValidationClass
	 * @param	{String}		labelField
	 * @param	{Boolean}		isOk
	 */
	updateLabelValidationClass: function(labelField, isOk) {
		if ( isOk ) {
			$(labelField).removeClassName('redLabel');
			$(labelField).removeClassName('redLabel');
		} else {
			$(labelField).addClassName('redLabel');
			$(labelField).addClassName('redLabel');
		}
	},

	/**
	 * Validate input for company name
	 *
	 * @method	validateCompanyName
	 * @return	{Boolean}
	 */
	validateCompanyName: function() {
		var isOk	= $F('company').replace(' ', '').length > 0;
		this.updateLabelValidationClass('labelCompany', isOk);

		return isOk;
	},

	/**
	 * Validate input for firstname
	 *
	 * @method	validateFirstname
	 * @return  {Boolean}
	 */
	validateFirstname: function() {
		var isOk	= $F('firstname').replace(' ', '').length > 0;
		this.updateLabelValidationClass('labelFirstname', isOk);

		return isOk;
	},

	/**
	 * Validate input for lastname
	 *
	 * @method	validateLastname
	 * @return	{Boolean}
	 */
	validateLastname: function() {
		var isOk	= $F('lastname').replace(' ', '').length > 0;
		this.updateLabelValidationClass('labelLastname', isOk);

		return isOk;
	},

	/**
	 * Validate password to be long enough and both repetitions being identic
	 *
	 * @method	validatePassword
	 * @return	{Boolean}
	 */
	validatePassword: function() {
		var areIdentic	= $F('password') == $F('password_confirm');
		var longEnough	= $F('password').length >= 5;

		var isOk	= areIdentic && longEnough;

		this.updateLabelValidationClass('labelPassword',		isOk);
		this.updateLabelValidationClass('labelPasswordConfirm',	isOk);

		return isOk;
	}

};