<commit_before>#include "stdafx.h"
#include "EsriClientThread.h"
#include "EsriHandler.h"
#include "strOps.h"
#include <algorithm>

namespace libESRI
{
  bool IsTextOrNumber(const char c)
  {
    return c >= 32 && c < 127;
  }

  EsriClientThread::EsriClientThread(toni::TcpClient* tcpClient, EsriHandler* handler)
    : m_tcpClient(tcpClient)
    , m_handler(handler)
  {

  }

  bool EsriClientThread::SendWelcomeMessage()
  {
    char const * const welcomeMessage = m_handler->OnProvideWelcomeMessage();
    if (welcomeMessage)
    {
      size_t welcomeMessageLength = strlen(welcomeMessage);
      return m_tcpClient->Send(welcomeMessage, (int)welcomeMessageLength) > 0;
    }

    return true;
  }

  bool EsriClientThread::SendCurrentDirectory()
  {
    char const * const curDir = m_handler->OnGetCurrentDirectory();
    if (curDir)
    {
      std::string currentDirectory = curDir;
      currentDirectory += ">";
      return m_tcpClient->Send(currentDirectory.c_str(), (int)currentDirectory.length()) > 0;
    }

    return true;
  }

  void EsriClientThread::AutoComplete(std::string& input, std::string& commonStartOfAllCandidates, std::vector<std::string>& candidates)
  {
    auto* allCommandsAsString = m_handler->OnProvideCommands();
    if (!allCommandsAsString)
    {
      commonStartOfAllCandidates = input;
      return;
    }

    auto allCommands = toni::Tokenize<std::string>(allCommandsAsString, ";");
    for (auto& candidate : allCommands)
    {
      if (!candidate.empty() && candidate.find(input) == 0)
        candidates.push_back(candidate);
    }

    if (candidates.empty())
    {
      commonStartOfAllCandidates = input;
      return;
    }

    if (candidates.size() == 1)
    {
      commonStartOfAllCandidates = candidates[0];
      return;
    }

    //candidates.size() now >= 2
    std::sort(candidates.begin(), candidates.end());

    std::string& first = candidates[0];
    std::string& last = candidates[candidates.size() - 1];

    size_t shortestCandidate = std::min(first.size(), last.size());
    commonStartOfAllCandidates = "";
    for (size_t i = 0; i < shortestCandidate; i++)
    {
      if (first[i] == last[i])
        commonStartOfAllCandidates += first[i];
      else
        break;
    }
  }

  bool EsriClientThread::HandleAutoComplete(std::string& input)
  {
    std::string autoCompletedInput;
    std::vector<std::string> otherCandidates;
    AutoComplete(input, autoCompletedInput, otherCandidates);

    if (otherCandidates.size() > 1)
    {
      std::string allCandidates = "\r\n";
      for (auto& candidate : otherCandidates)
      {
        allCandidates += '\t' + candidate + "\r\n";
      }

      input = autoCompletedInput;

      allCandidates += m_handler->OnGetCurrentDirectory();
      allCandidates += ">";
      allCandidates += input;
      return m_tcpClient->Send(allCandidates.c_str(), (int)allCandidates.length()) > 0;
    }
    else
    {
      input = autoCompletedInput;

      std::string autoCompletedInputWithPrompt = "\r";
      autoCompletedInputWithPrompt += m_handler->OnGetCurrentDirectory();
      autoCompletedInputWithPrompt += "\>";
      autoCompletedInputWithPrompt += input;
      return m_tcpClient->Send(autoCompletedInputWithPrompt.c_str(), (int)autoCompletedInputWithPrompt.length()) > 0;
    }
  }

  void EsriClientThread::EntryPoint()
  {
    if (!SendWelcomeMessage())
      return;

    if (!SendCurrentDirectory())
      return;

    int recvVal = 0;
    std::vector<char> receiveBuffer(1024);
    std::string inputBuffer;
    while ((recvVal = m_tcpClient->Recv(&receiveBuffer[0], (int)receiveBuffer.size())) > 0)
    {
      bool sentResponse = false;
      if (recvVal > 1 && receiveBuffer[0] == 27) //27 = ESC
      {
        std::string controlBuffer;
        controlBuffer.assign(receiveBuffer.begin() + 1, receiveBuffer.end());
      }
      else
      {
        for (size_t i = 0; i < recvVal && !sentResponse; i++)
        {
          const char curChar = receiveBuffer[i];
          switch (curChar)
          {
          case '\t':
            if (!HandleAutoComplete(inputBuffer))
              return;
            sentResponse = true;
            break;
          case '\n':
            m_handler->OnCommitCommand(inputBuffer.c_str());
            inputBuffer.clear();
            sentResponse = true;
            break;
          default:
            if (IsTextOrNumber(curChar))
              inputBuffer += curChar;
            break;
          }
        }
      }

    }
  }
}<commit_msg>fixed controlBuffer<commit_after>#include "stdafx.h"
#include "EsriClientThread.h"
#include "EsriHandler.h"
#include "strOps.h"
#include <algorithm>

namespace libESRI
{
  bool IsTextOrNumber(const char c)
  {
    return c >= 32 && c < 127;
  }

  EsriClientThread::EsriClientThread(toni::TcpClient* tcpClient, EsriHandler* handler)
    : m_tcpClient(tcpClient)
    , m_handler(handler)
  {

  }

  bool EsriClientThread::SendWelcomeMessage()
  {
    char const * const welcomeMessage = m_handler->OnProvideWelcomeMessage();
    if (welcomeMessage)
    {
      size_t welcomeMessageLength = strlen(welcomeMessage);
      return m_tcpClient->Send(welcomeMessage, (int)welcomeMessageLength) > 0;
    }

    return true;
  }

  bool EsriClientThread::SendCurrentDirectory()
  {
    char const * const curDir = m_handler->OnGetCurrentDirectory();
    if (curDir)
    {
      std::string currentDirectory = curDir;
      currentDirectory += ">";
      return m_tcpClient->Send(currentDirectory.c_str(), (int)currentDirectory.length()) > 0;
    }

    return true;
  }

  void EsriClientThread::AutoComplete(std::string& input, std::string& commonStartOfAllCandidates, std::vector<std::string>& candidates)
  {
    auto* allCommandsAsString = m_handler->OnProvideCommands();
    if (!allCommandsAsString)
    {
      commonStartOfAllCandidates = input;
      return;
    }

    auto allCommands = toni::Tokenize<std::string>(allCommandsAsString, ";");
    for (auto& candidate : allCommands)
    {
      if (!candidate.empty() && candidate.find(input) == 0)
        candidates.push_back(candidate);
    }

    if (candidates.empty())
    {
      commonStartOfAllCandidates = input;
      return;
    }

    if (candidates.size() == 1)
    {
      commonStartOfAllCandidates = candidates[0];
      return;
    }

    //candidates.size() now >= 2
    std::sort(candidates.begin(), candidates.end());

    std::string& first = candidates[0];
    std::string& last = candidates[candidates.size() - 1];

    size_t shortestCandidate = std::min(first.size(), last.size());
    commonStartOfAllCandidates = "";
    for (size_t i = 0; i < shortestCandidate; i++)
    {
      if (first[i] == last[i])
        commonStartOfAllCandidates += first[i];
      else
        break;
    }
  }

  bool EsriClientThread::HandleAutoComplete(std::string& input)
  {
    std::string autoCompletedInput;
    std::vector<std::string> otherCandidates;
    AutoComplete(input, autoCompletedInput, otherCandidates);

    if (otherCandidates.size() > 1)
    {
      std::string allCandidates = "\r\n";
      for (auto& candidate : otherCandidates)
      {
        allCandidates += '\t' + candidate + "\r\n";
      }

      input = autoCompletedInput;

      allCandidates += m_handler->OnGetCurrentDirectory();
      allCandidates += ">";
      allCandidates += input;
      return m_tcpClient->Send(allCandidates.c_str(), (int)allCandidates.length()) > 0;
    }
    else
    {
      input = autoCompletedInput;

      std::string autoCompletedInputWithPrompt = "\r";
      autoCompletedInputWithPrompt += m_handler->OnGetCurrentDirectory();
      autoCompletedInputWithPrompt += ">";
      autoCompletedInputWithPrompt += input;
      return m_tcpClient->Send(autoCompletedInputWithPrompt.c_str(), (int)autoCompletedInputWithPrompt.length()) > 0;
    }
  }

  void EsriClientThread::EntryPoint()
  {
    if (!SendWelcomeMessage())
      return;

    if (!SendCurrentDirectory())
      return;

    int recvVal = 0;
    std::vector<char> receiveBuffer(1024);
    std::string inputBuffer;
    while ((recvVal = m_tcpClient->Recv(&receiveBuffer[0], (int)receiveBuffer.size())) > 0)
    {
      bool sentResponse = false;
      if (recvVal > 1 && receiveBuffer[0] == 27) //27 = ESC
      {
        std::string controlBuffer;
        controlBuffer.assign(receiveBuffer.begin() + 1, receiveBuffer.begin() + recvVal);

        if (controlBuffer.compare("clearInputBuffer") == 0)
        {
          inputBuffer.clear();
        }
      }
      else
      {
        for (size_t i = 0; i < recvVal && !sentResponse; i++)
        {
          const char curChar = receiveBuffer[i];
          switch (curChar)
          {
          case '\t':
            if (!HandleAutoComplete(inputBuffer))
              return;
            sentResponse = true;
            break;
          case '\n':
            m_handler->OnCommitCommand(inputBuffer.c_str());
            inputBuffer.clear();
            sentResponse = true;
            break;
          default:
            if (IsTextOrNumber(curChar))
              inputBuffer += curChar;
            break;
          }
        }
      }

    }
  }
}<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/blocked_plugin.h"

#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"

using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;

static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
// TODO(cevans) - move these to a shared header file so that there are no
// collisions in the longer term. Currently, blocked_plugin.cc is the only
// user of custom menu commands (extension menu items have their own range).
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;

BlockedPlugin::BlockedPlugin(RenderView* render_view,
                             WebFrame* frame,
                             const webkit::npapi::PluginGroup& info,
                             const WebPluginParams& params,
                             const WebPreferences& preferences,
                             int template_id,
                             const string16& message,
                             bool is_blocked_for_prerendering)
    : RenderViewObserver(render_view),
      frame_(frame),
      plugin_params_(params),
      is_blocked_for_prerendering_(is_blocked_for_prerendering) {
  const base::StringPiece template_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));

  DCHECK(!template_html.empty()) << "unable to load template. ID: "
                                 << template_id;

  DictionaryValue values;
  values.SetString("message", message);
  name_ = info.GetGroupName();
  values.SetString("name", name_);

  // "t" is the id of the templates root node.
  std::string html_data = jstemplate_builder::GetTemplatesHtml(
      template_html, &values, "t");

  plugin_ = webkit::npapi::WebViewPlugin::Create(this,
                                                 preferences,
                                                 html_data,
                                                 GURL(kBlockedPluginDataURL));
}

BlockedPlugin::~BlockedPlugin() {
}

void BlockedPlugin::BindWebFrame(WebFrame* frame) {
  BindToJavascript(frame, "plugin");
  BindMethod("load", &BlockedPlugin::Load);
  BindMethod("hide", &BlockedPlugin::Hide);
}

void BlockedPlugin::WillDestroyPlugin() {
  delete this;
}

void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
  WebContextMenuData menu_data;
  WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));

  WebMenuItemInfo name_item;
  name_item.label = name_;
  custom_items[0] = name_item;

  WebMenuItemInfo separator_item;
  separator_item.type = WebMenuItemInfo::Separator;
  custom_items[1] = separator_item;

  WebMenuItemInfo run_item;
  run_item.action = kMenuActionLoad;
  run_item.enabled = true;
  run_item.label = WebString::fromUTF8(
      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
  custom_items[2] = run_item;

  WebMenuItemInfo hide_item;
  hide_item.action = kMenuActionRemove;
  hide_item.enabled = true;
  hide_item.label = WebString::fromUTF8(
      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
  custom_items[3] = hide_item;

  menu_data.customItems.swap(custom_items);
  menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
  render_view()->showContextMenu(NULL, menu_data);
}

bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
  // We don't swallow ViewMsg_CustomContextMenuAction because we listen for all
  // custom menu IDs, and not just our own. We don't swallow
  // ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an
  // interest in it.
  if (message.type() == ViewMsg_CustomContextMenuAction::ID) {
    ViewMsg_CustomContextMenuAction::Dispatch(
        &message, this, this, &BlockedPlugin::OnMenuItemSelected);
  } else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
    LoadPlugin();
  } else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {
    if (is_blocked_for_prerendering_)
      LoadPlugin();
  }

  return false;
}

void BlockedPlugin::OnMenuItemSelected(unsigned id) {
  if (id == kMenuActionLoad) {
    LoadPlugin();
  } else if (id == kMenuActionRemove) {
    HidePlugin();
  }
}

void BlockedPlugin::LoadPlugin() {
  CHECK(plugin_);
  WebPluginContainer* container = plugin_->container();
  WebPlugin* new_plugin =
      render_view()->CreatePluginNoCheck(frame_, plugin_params_);
  if (new_plugin && new_plugin->initialize(container)) {
    container->setPlugin(new_plugin);
    container->invalidate();
    container->reportGeometry();
    plugin_->ReplayReceivedData(new_plugin);
    plugin_->destroy();
  }
}

void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
  LoadPlugin();
}

void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
  HidePlugin();
}

void BlockedPlugin::HidePlugin() {
  CHECK(plugin_);
  WebPluginContainer* container = plugin_->container();
  WebElement element = container->element();
  element.setAttribute("style", "display: none;");
  // If we have a width and height, search for a parent (often <div>) with the
  // same dimensions. If we find such a parent, hide that as well.
  // This makes much more uncovered page content usable (including clickable)
  // as opposed to merely visible.
  // TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
  // now for these reasons:
  // 1) Makes the user experience better.
  // 2) Foulness is encapsulated within this single function.
  // 3) Confidence in no fasle positives.
  // 4) Seems to have a good / low false negative rate at this time.
  if (element.hasAttribute("width") && element.hasAttribute("height")) {
    std::string width_str("width:[\\s]*");
    width_str += element.getAttribute("width").utf8().data();
    if (EndsWith(width_str, "px", false)) {
      width_str = width_str.substr(0, width_str.length() - 2);
    }
    TrimWhitespace(width_str, TRIM_TRAILING, &width_str);
    width_str += "[\\s]*px";
    WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
                                     WebKit::WebTextCaseSensitive);
    std::string height_str("height:[\\s]*");
    height_str += element.getAttribute("height").utf8().data();
    if (EndsWith(height_str, "px", false)) {
      height_str = height_str.substr(0, height_str.length() - 2);
    }
    TrimWhitespace(height_str, TRIM_TRAILING, &height_str);
    height_str += "[\\s]*px";
    WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
                                      WebKit::WebTextCaseSensitive);
    WebNode parent = element;
    while (!parent.parentNode().isNull()) {
      parent = parent.parentNode();
      if (!parent.isElementNode())
        continue;
      element = parent.toConst<WebElement>();
      if (element.hasAttribute("style")) {
        WebString style_str = element.getAttribute("style");
        if (width_regex.match(style_str) >= 0 &&
            height_regex.match(style_str) >= 0)
          element.setAttribute("style", "display: none;");
      }
    }
  }
}

<commit_msg>Oops, fix my previous fix to the refactor breakage. Make sure we only apply the current menu command to whoever opened the custom menu. We have to track it in a slightly ugly manner thanks to GTK's out-of-order messaging for "menu item selected" vs. "context menu closed".<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/blocked_plugin.h"

#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"

using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;

static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
// TODO(cevans) - move these to a shared header file so that there are no
// collisions in the longer term. Currently, blocked_plugin.cc is the only
// user of custom menu commands (extension menu items have their own range).
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;

static const BlockedPlugin* gLastActiveMenu;

BlockedPlugin::BlockedPlugin(RenderView* render_view,
                             WebFrame* frame,
                             const webkit::npapi::PluginGroup& info,
                             const WebPluginParams& params,
                             const WebPreferences& preferences,
                             int template_id,
                             const string16& message,
                             bool is_blocked_for_prerendering)
    : RenderViewObserver(render_view),
      frame_(frame),
      plugin_params_(params),
      is_blocked_for_prerendering_(is_blocked_for_prerendering) {
  const base::StringPiece template_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));

  DCHECK(!template_html.empty()) << "unable to load template. ID: "
                                 << template_id;

  DictionaryValue values;
  values.SetString("message", message);
  name_ = info.GetGroupName();
  values.SetString("name", name_);

  // "t" is the id of the templates root node.
  std::string html_data = jstemplate_builder::GetTemplatesHtml(
      template_html, &values, "t");

  plugin_ = webkit::npapi::WebViewPlugin::Create(this,
                                                 preferences,
                                                 html_data,
                                                 GURL(kBlockedPluginDataURL));
}

BlockedPlugin::~BlockedPlugin() {
}

void BlockedPlugin::BindWebFrame(WebFrame* frame) {
  BindToJavascript(frame, "plugin");
  BindMethod("load", &BlockedPlugin::Load);
  BindMethod("hide", &BlockedPlugin::Hide);
}

void BlockedPlugin::WillDestroyPlugin() {
  delete this;
}

void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
  WebContextMenuData menu_data;
  WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));

  WebMenuItemInfo name_item;
  name_item.label = name_;
  custom_items[0] = name_item;

  WebMenuItemInfo separator_item;
  separator_item.type = WebMenuItemInfo::Separator;
  custom_items[1] = separator_item;

  WebMenuItemInfo run_item;
  run_item.action = kMenuActionLoad;
  run_item.enabled = true;
  run_item.label = WebString::fromUTF8(
      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
  custom_items[2] = run_item;

  WebMenuItemInfo hide_item;
  hide_item.action = kMenuActionRemove;
  hide_item.enabled = true;
  hide_item.label = WebString::fromUTF8(
      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
  custom_items[3] = hide_item;

  menu_data.customItems.swap(custom_items);
  menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
  render_view()->showContextMenu(NULL, menu_data);
  gLastActiveMenu = this;
}

bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
  // We don't swallow ViewMsg_CustomContextMenuAction because we listen for all
  // custom menu IDs, and not just our own. We don't swallow
  // ViewMsg_LoadBlockedPlugins because multiple blocked plugins have an
  // interest in it.
  if (message.type() == ViewMsg_CustomContextMenuAction::ID &&
      gLastActiveMenu == this) {
    ViewMsg_CustomContextMenuAction::Dispatch(
        &message, this, this, &BlockedPlugin::OnMenuItemSelected);
  } else if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
    LoadPlugin();
  } else if (message.type() == ViewMsg_DisplayPrerenderedPage::ID) {
    if (is_blocked_for_prerendering_)
      LoadPlugin();
  }

  return false;
}

void BlockedPlugin::OnMenuItemSelected(unsigned id) {
  if (id == kMenuActionLoad) {
    LoadPlugin();
  } else if (id == kMenuActionRemove) {
    HidePlugin();
  }
}

void BlockedPlugin::LoadPlugin() {
  CHECK(plugin_);
  WebPluginContainer* container = plugin_->container();
  WebPlugin* new_plugin =
      render_view()->CreatePluginNoCheck(frame_, plugin_params_);
  if (new_plugin && new_plugin->initialize(container)) {
    container->setPlugin(new_plugin);
    container->invalidate();
    container->reportGeometry();
    plugin_->ReplayReceivedData(new_plugin);
    plugin_->destroy();
  }
}

void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
  LoadPlugin();
}

void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
  HidePlugin();
}

void BlockedPlugin::HidePlugin() {
  CHECK(plugin_);
  WebPluginContainer* container = plugin_->container();
  WebElement element = container->element();
  element.setAttribute("style", "display: none;");
  // If we have a width and height, search for a parent (often <div>) with the
  // same dimensions. If we find such a parent, hide that as well.
  // This makes much more uncovered page content usable (including clickable)
  // as opposed to merely visible.
  // TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
  // now for these reasons:
  // 1) Makes the user experience better.
  // 2) Foulness is encapsulated within this single function.
  // 3) Confidence in no fasle positives.
  // 4) Seems to have a good / low false negative rate at this time.
  if (element.hasAttribute("width") && element.hasAttribute("height")) {
    std::string width_str("width:[\\s]*");
    width_str += element.getAttribute("width").utf8().data();
    if (EndsWith(width_str, "px", false)) {
      width_str = width_str.substr(0, width_str.length() - 2);
    }
    TrimWhitespace(width_str, TRIM_TRAILING, &width_str);
    width_str += "[\\s]*px";
    WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
                                     WebKit::WebTextCaseSensitive);
    std::string height_str("height:[\\s]*");
    height_str += element.getAttribute("height").utf8().data();
    if (EndsWith(height_str, "px", false)) {
      height_str = height_str.substr(0, height_str.length() - 2);
    }
    TrimWhitespace(height_str, TRIM_TRAILING, &height_str);
    height_str += "[\\s]*px";
    WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
                                      WebKit::WebTextCaseSensitive);
    WebNode parent = element;
    while (!parent.parentNode().isNull()) {
      parent = parent.parentNode();
      if (!parent.isElementNode())
        continue;
      element = parent.toConst<WebElement>();
      if (element.hasAttribute("style")) {
        WebString style_str = element.getAttribute("style");
        if (width_regex.match(style_str) >= 0 &&
            height_regex.match(style_str) >= 0)
          element.setAttribute("style", "display: none;");
      }
    }
  }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: appsettings.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:16:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _APPSETTINGS_HXX
#define _APPSETTINGS_HXX

#ifndef __STARDIV_UNO_UTIL_CONTAINR_HXX__
#include <stardiv/uno/util/containr.hxx>
#endif

#ifdef __cplusplus
extern "C" {
#endif

XNameContainer* getApplicationSettings();

#ifdef __cplusplus
}
#endif

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.604); FILE MERGED 2005/09/05 12:58:25 rt 1.1.1.1.604.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appsettings.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:00:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _APPSETTINGS_HXX
#define _APPSETTINGS_HXX

#ifndef __STARDIV_UNO_UTIL_CONTAINR_HXX__
#include <stardiv/uno/util/containr.hxx>
#endif

#ifdef __cplusplus
extern "C" {
#endif

XNameContainer* getApplicationSettings();

#ifdef __cplusplus
}
#endif

#endif

<|endoftext|>


<commit_before>#include <iostream>
#include <utility>
#include <vector>
#include <array>
#include <string>

struct Point final
{
	using value_type = int;
	explicit Point(const value_type& x = value_type(), const value_type& y = value_type()) noexcept
	: x_{x}, y_{y}
	{}
	Point(const Point&) noexcept = default;
	~Point() noexcept = default;
	Point& operator=(const Point&) noexcept = default;

	bool operator==(const Point& p) const noexcept {
		return std::tie(x_, y_) == std::tie(p.x_, p.y_);
	}
	bool operator!=(const Point& p) const noexcept { return !(p == *this); }

	bool operator<(const Point& p) const noexcept {
		return std::tie(x_, y_) < std::tie(p.x_, p.y_);
	}

	bool operator<=(const Point& p) const noexcept { return !(p < *this); }
	bool operator>=(const Point& p) const noexcept { return !(*this < p); }
	bool operator>(const Point& p) const noexcept  { return !(*this <= p); }

	Point& operator-=(const Point& p) noexcept { x_ -= p.x_; y_ -= p.y_; return *this; }
	friend Point operator-(const Point& p1, const Point& p2) {
		return Point(p1.x_ - p2.x_, p1.y_ - p2.y_);
	}
 	Point& operator+=(const Point& p) noexcept { x_ += p.x_; y_ += p.y_; return *this; }
	friend Point operator+(const Point& p1, const Point& p2) {
		return Point(p1.x_ + p2.x_, p1.y_ + p2.y_);
	}
	bool is_top_left(const Point& p) const noexcept {
		return x_ <= p.x_ && y_ <= p.y_;
	}
	/**
	 * Assert p1 is top left of p2
	 * i.e. p1.x <= p2.x and p1.y <= p2.y
	 */
	static void assert_top_left(Point& p1, Point& p2) {
		if (p1.x_ > p2.x_)
			std::swap(p1.x_, p2.x_);
		if (p1.y_ > p2.y_)
			std::swap(p1.y_, p2.y_);
	}

	value_type x_{0}, y_{0};
};

struct Rect final
{
	enum class ConstructionType { unchecked };
	explicit Rect(const Point& p1, const Point& p2) noexcept
	: p1_{p1}, p2_{p2}
	{
		Point::assert_top_left(p1_, p2_);
	}
	explicit Rect(ConstructionType ct = ConstructionType::unchecked, const Point& p1 = Point(), const Point& p2 = Point()) noexcept
	: p1_{p1}, p2_{p2}
	{}
	Rect(const Rect&) noexcept = default;
	~Rect() noexcept = default;
	Rect& operator=(const Rect& r) noexcept = default;
	bool contains(const Point& p) const noexcept {
		return p1_.is_top_left(p) && p.is_top_left(p2_);
	}
	bool contains(const Rect& r) const noexcept {
		return p1_.is_top_left(r.p1_) && r.p2_.is_top_left(p2_);
	}
	bool intersects(const Rect& r) const noexcept {
		return p1_.is_top_left(r.p2_) && r.p2_.is_top_left(p1_);
	}
	static Rect combination(const Rect& r1, const Rect& r2) {
		Point p1(
			std::min(r1.p1_.x_, r2.p1_.x_),
			std::min(r1.p1_.y_, r2.p1_.y_)
			);
		Point p2(
			std::max(r1.p2_.x_, r2.p2_.x_),
			std::max(r1.p2_.y_, r2.p2_.y_)
			);
		return Rect(ConstructionType::unchecked, p1, p2);
	}
	static std::pair<bool, Rect> intersection(const Rect& r1, const Rect& r2) {
		Point p1(std::max(r1.p1_.x_, r2.p1_.x_), std::max(r1.p1_.y_, r2.p1_.y_));
		Point p2(std::min(r1.p2_.x_, r2.p2_.x_), std::min(r1.p2_.y_, r2.p2_.y_));
		bool intersect = p1.is_top_left(p2);
		Rect r;
		if (intersect) {
			r.p1_ = p1;
			r.p2_ = p2;
		}
		return std::make_pair(intersect, r);
	}
	Point::value_type area() const { auto p = p2_ - p1_; return std::abs(p.x_ * p.y_); }
	Point p1_, p2_;
};

struct RTree
{
	using value_type = std::pair<Rect, size_t>;
	static const size_t max_node_size = 16;
	struct RTIterator;
	struct INode;
	struct NodeBase {
		// Basic common elements
		explicit NodeBase(INode* parent) : parent_{parent} {}
		virtual ~NodeBase() =default;

		size_t size_ {0};
		INode* parent_;
		Rect outline_;
	};
	struct LeafNode;
	struct IndexNode;
	struct AbstractOperation {
		virtual ~AbstractOperation() =0;
		virtual void visit(IndexNode& n) =0;
		virtual void visit(LeafNode& n) =0;
	};
	struct INode {
		// pure abstract interface
		virtual ~INode() =default;
		virtual size_t size() const = 0;
		virtual void accept(AbstractOperation& a) =0;
		//virtual void add(const value_type& r)  =0;
		virtual INode* parent() =0;
		virtual LeafNode* first_leaf(size_t* depth) =0;
		virtual bool is_full() const { return size() == RTree::max_node_size; }
		virtual const Rect& outline() const =0;
		//virtual std::unique_ptr<INode> clone() =0;
	};
	struct IndexNode : public NodeBase, public INode {
		using value_type = std::pair<Rect, std::unique_ptr<INode>>;
		explicit IndexNode(INode* parent) : NodeBase(parent)
		{}
		virtual ~IndexNode() = default;
		virtual INode* parent() override { return parent_; }
		virtual size_t size() const override { return size_; }
		friend class AbstractOperation;
		virtual void accept(AbstractOperation& a) override { a.visit(*this); }
		virtual LeafNode* first_leaf(size_t* depth) override {
			if (elements_.size() == 0)
				return nullptr;
			if (depth != nullptr)
				++(*depth);
			return std::get<1>(elements_[0])->first_leaf(depth);
		}
		virtual const Rect& outline() const override { return outline_; }
		virtual bool is_full() const override { return size_ == elements_.size(); }

		using NodeBase::size_;
		using NodeBase::parent_;
		using NodeBase::outline_;
		std::array<IndexNode::value_type, RTree::max_node_size> elements_;

	};
	struct LeafNode : public NodeBase, public INode {
		explicit LeafNode(INode* parent) : NodeBase(parent)
		{}
		virtual ~LeafNode() = default;
		using NodeBase::size_;
		using NodeBase::parent_;
		virtual INode* parent() override { return parent_; }
		virtual size_t size() const override { return size_; }
		friend class AbstractOperation;
		virtual void accept(AbstractOperation& a) override { a.visit(*this); }
		virtual LeafNode* first_leaf(size_t* depth) override { return this; }
		virtual const Rect& outline() const override { return outline_; }
		virtual bool is_full() const override { return size_ == elements_.size(); }
		std::array<RTree::value_type, RTree::max_node_size> elements_;
	};
	struct AddOperation : public AbstractOperation {
		explicit AddOperation(const RTree::value_type& v, RTIterator& it)
		: value_(v), it_(it)
		{}
		virtual void visit(IndexNode& n) {
			// TODO
			// choose sub tree
			// if it contains value_ rect
			// or choose the subtree which needs the least enlargement
			vector<std::pair<float, INode*>> heap;
			for(const auto& e : n.elements_) {
				auto area = e.first.area();
				auto enlarged_rect = Rect::combination(e.first, value_.first);
				float enlargement = static_cast<float>(enlarged_rect.area()) / (area > 0 ? area : 1);
				std::push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
			}

			// update outline
			n.outline_ = Rect::combination(n.outline_, it_.current_node_->outline_);
		}
		virtual void visit(LeafNode& n) {
			if (n.is_full()) {
				// TODO split node
			} else {
				// insert here
				n.elements_[n.size()] =value_;
				it_.current_node_ = &n;
				it_.itstack_.push_back(n.size());
				n.size_++;
				// TODO n.outline_ = Rect::combination(n.outline_, std::get<0>(value_));
				n.outline_ = Rect::combination(n.outline(), value_.first);
			}
		}
		RTIterator& it_;
		const RTree::value_type& value_;
	};
	using FindResult = std::vector<RTree::value_type>;
	struct FindExactOperation : public AbstractOperation {
		explicit FindExactOperation(const Point& p) : p_{p}
		{}
		auto begin() { return result_.begin(); }
		auto end() { return result_.end(); }
		virtual void visit(IndexNode& n) {
			for(const auto& e : n.elements_) {
				const auto& r = std::get<0>(e);
				if (r.contains(p_))
					std::get<1>(e)->accept(*this);
			}
		}
		virtual void visit(LeafNode& n) {
			for(const auto& e : n.elements_) {
				const auto& r = std::get<0>(e);
				if (r.contains(p_)) {
					result_.push_back(e);
				}
			}
		}
		FindResult result_;
		const Point& p_;
	};
	struct FindNearestOperation : public AbstractOperation {
		explicit FindNearestOperation(const Point& p) : p_{p}
		{}
		virtual void visit(IndexNode& n) {
			// TODO
		}
		virtual void visit(LeafNode& n) {
			// TODO
		}
		FindResult result_;
		const Point p_;
	};
	struct RTIterator
	{
		bool operator==(const RTIterator& i) const {
			if (current_node_ == nullptr && i.current_node_ == nullptr)
				return true;
			return std::tie(current_node_, itstack_) == std::tie(i.current_node_, i.itstack_);
		}
		bool operator!=(const RTIterator& i) const { return !(*this == i); }
		RTIterator& operator++() {
			if (itstack_.size() > 0) {
				auto pos = itstack_.back();
				++pos;
				if (pos + 1 < current_node_->size())
					return *this;

				// search into upwards index nodes
				INode* node = current_node_;
				while (itstack_.size() > 0 && node != nullptr && node->size() <= pos) {
					itstack_.pop_back();
					pos = ++itstack_.back();
					node = node->parent();
				}
				if (itstack_.size() == 0) {
					// nothing found; we're at the end
					current_node_ = nullptr;
				} else {
					// search downward to leaf node
					size_t depth {0};
					current_node_ = node->first_leaf(&depth);
					for(size_t i = 0; i < depth; ++i) {
						itstack_.push_back(0);
					}
				}
			}
			return *this;
		}
		RTree::value_type& operator*() { return current_node_->elements_[itstack_.back()]; }
		//RTIterator& operator++(int) { return *this; }
		//RTree* tree_ { nullptr };
		LeafNode* current_node_ { nullptr };
		std::vector<size_t> itstack_;
	};
	RTIterator begin();
	RTIterator end() { return RTIterator(); }

	RTIterator add(const value_type& r) {
		RTIterator it;
		AddOperation ao(r, it);
		root_->accept(ao);
		return it;
	}
	FindResult find_containing(const Point& p) {
		FindExactOperation feo(p);
		root_->accept(feo);
		return feo.result_;
	}
	FindResult find_nearest(const Point& p, size_t n = 1) {
		// TODO
		FindNearestOperation fno(p);
		root_->accept(fno);
		return fno.result_;
	}

	std::unique_ptr<INode> root_ = std::make_unique<LeafNode>(nullptr);
};

int main(int argc, char const *argv[])
{
	std::vector<std::string> params(argv, argv + argc);
	RTree rt;
	for(const auto& p : params) {
		std::cout << p << std::endl;
	}
	return 0;
}<commit_msg>20171025<commit_after>#include <iostream>
#include <utility>
#include <vector>
#include <array>
#include <string>

struct Point final
{
	using value_type = int;
	explicit Point(const value_type& x = value_type(), const value_type& y = value_type()) noexcept
	: x_{x}, y_{y}
	{}
	Point(const Point&) noexcept = default;
	~Point() noexcept = default;
	Point& operator=(const Point&) noexcept = default;

	bool operator==(const Point& p) const noexcept {
		return std::tie(x_, y_) == std::tie(p.x_, p.y_);
	}
	bool operator!=(const Point& p) const noexcept { return !(p == *this); }

	bool operator<(const Point& p) const noexcept {
		return std::tie(x_, y_) < std::tie(p.x_, p.y_);
	}

	bool operator<=(const Point& p) const noexcept { return !(p < *this); }
	bool operator>=(const Point& p) const noexcept { return !(*this < p); }
	bool operator>(const Point& p) const noexcept  { return !(*this <= p); }

	Point& operator-=(const Point& p) noexcept { x_ -= p.x_; y_ -= p.y_; return *this; }
	friend Point operator-(const Point& p1, const Point& p2) {
		return Point(p1.x_ - p2.x_, p1.y_ - p2.y_);
	}
 	Point& operator+=(const Point& p) noexcept { x_ += p.x_; y_ += p.y_; return *this; }
	friend Point operator+(const Point& p1, const Point& p2) {
		return Point(p1.x_ + p2.x_, p1.y_ + p2.y_);
	}
	bool is_top_left(const Point& p) const noexcept {
		return x_ <= p.x_ && y_ <= p.y_;
	}
	/**
	 * Assert p1 is top left of p2
	 * i.e. p1.x <= p2.x and p1.y <= p2.y
	 */
	static void assert_top_left(Point& p1, Point& p2) {
		if (p1.x_ > p2.x_)
			std::swap(p1.x_, p2.x_);
		if (p1.y_ > p2.y_)
			std::swap(p1.y_, p2.y_);
	}

	value_type x_{0}, y_{0};
};

struct Rect final
{
	enum class ConstructionType { unchecked };
	explicit Rect(const Point& p1, const Point& p2) noexcept
	: p1_{p1}, p2_{p2}
	{
		Point::assert_top_left(p1_, p2_);
	}
	explicit Rect(ConstructionType ct = ConstructionType::unchecked, const Point& p1 = Point(), const Point& p2 = Point()) noexcept
	: p1_{p1}, p2_{p2}
	{}
	Rect(const Rect&) noexcept = default;
	~Rect() noexcept = default;
	Rect& operator=(const Rect& r) noexcept = default;
	bool operator==(const Rect& r) const noexcept { return std::tie(p1_, p2_) == std::tie(r.p1_, r.p2_); }
	bool contains(const Point& p) const noexcept {
		return p1_.is_top_left(p) && p.is_top_left(p2_);
	}
	bool contains(const Rect& r) const noexcept {
		return p1_.is_top_left(r.p1_) && r.p2_.is_top_left(p2_);
	}
	bool intersects(const Rect& r) const noexcept {
		return p1_.is_top_left(r.p2_) && r.p2_.is_top_left(p1_);
	}
	static Rect combination(const Rect& r1, const Rect& r2) {
		Point p1(
			std::min(r1.p1_.x_, r2.p1_.x_),
			std::min(r1.p1_.y_, r2.p1_.y_)
			);
		Point p2(
			std::max(r1.p2_.x_, r2.p2_.x_),
			std::max(r1.p2_.y_, r2.p2_.y_)
			);
		return Rect(ConstructionType::unchecked, p1, p2);
	}
	static std::pair<bool, Rect> intersection(const Rect& r1, const Rect& r2) {
		Point p1(std::max(r1.p1_.x_, r2.p1_.x_), std::max(r1.p1_.y_, r2.p1_.y_));
		Point p2(std::min(r1.p2_.x_, r2.p2_.x_), std::min(r1.p2_.y_, r2.p2_.y_));
		bool intersect = p1.is_top_left(p2);
		Rect r;
		if (intersect) {
			r.p1_ = p1;
			r.p2_ = p2;
		}
		return std::make_pair(intersect, r);
	}
	Point::value_type area() const { auto p = p2_ - p1_; return std::abs(p.x_ * p.y_); }
	Point p1_, p2_;
};

struct RTree
{
	using value_type = std::pair<Rect, size_t>;
	static const size_t max_node_size = 16;
	struct RTIterator;
	struct INode;
	struct NodeBase {
		// Basic common elements
		explicit NodeBase(INode* parent) : parent_{parent} {}
		virtual ~NodeBase() =default;

		size_t size_ {0};
		INode* parent_;
		Rect outline_;
	};
	struct LeafNode;
	struct IndexNode;
	struct AbstractOperation {
		virtual void visit(IndexNode& n) =0;
		virtual void visit(LeafNode& n) =0;
	};
	struct INode {
		// pure abstract interface
		virtual ~INode() =default;
		virtual size_t size() const = 0;
		virtual void accept(AbstractOperation& a) =0;
		//virtual void add(const value_type& r)  =0;
		virtual INode* parent() =0;
		virtual LeafNode* first_leaf(size_t* depth) =0;
		virtual bool is_full() const { return size() == RTree::max_node_size; }
		virtual const Rect& outline() const =0;
		//virtual std::unique_ptr<INode> clone() =0;
	};
	struct IndexNode : public NodeBase, public INode {
		using value_type = std::pair<Rect, std::unique_ptr<INode>>;
		explicit IndexNode(INode* parent) : NodeBase(parent)
		{}
		virtual ~IndexNode() = default;
		virtual INode* parent() override { return parent_; }
		virtual size_t size() const override { return size_; }
		friend class AbstractOperation;
		virtual void accept(AbstractOperation& a) override { a.visit(*this); }
		virtual LeafNode* first_leaf(size_t* depth) override {
			if (elements_.size() == 0)
				return nullptr;
			if (depth != nullptr)
				++(*depth);
			return std::get<1>(elements_[0])->first_leaf(depth);
		}
		virtual const Rect& outline() const override { return outline_; }
		virtual bool is_full() const override { return size_ == elements_.size(); }

		using NodeBase::size_;
		using NodeBase::parent_;
		using NodeBase::outline_;
		std::array<IndexNode::value_type, RTree::max_node_size> elements_;

	};
	struct LeafNode : public NodeBase, public INode {
		explicit LeafNode(INode* parent) : NodeBase(parent)
		{}
		virtual ~LeafNode() = default;
		using NodeBase::size_;
		using NodeBase::parent_;
		virtual INode* parent() override { return parent_; }
		virtual size_t size() const override { return size_; }
		friend class AbstractOperation;
		virtual void accept(AbstractOperation& a) override { a.visit(*this); }
		virtual LeafNode* first_leaf(size_t* depth) override { return this; }
		virtual const Rect& outline() const override { return outline_; }
		virtual bool is_full() const override { return size_ == elements_.size(); }
		std::array<RTree::value_type, RTree::max_node_size> elements_;
	};
	struct AddOperation : public AbstractOperation {
		explicit AddOperation(const RTree::value_type& v, RTIterator& it)
		: value_(v), it_(it)
		{}
		virtual void visit(IndexNode& n) {
			// TODO
			// choose sub tree
			// if it contains value_ rect
			// or choose the subtree which needs the least enlargement
			heap_.reserve(n.elements_.size());
			heap_.resize(0);
			static auto comp = [](const decltype(heap_)::value_type& a, const decltype(heap_)::value_type& b) -> bool {
				return a.first < b.first;
			};
			for(const auto& e : n.elements_) {
				auto area = e.first.area();
				auto enlarged_rect = Rect::combination(e.first, value_.first);
				float enlargement = static_cast<float>(enlarged_rect.area()) / (area > 0 ? area : 1);
				std::push_heap(heap_.begin(), heap_.end(), comp);
				if (e.first == enlarged_rect)
					break;
			}

			// update outline
			n.outline_ = Rect::combination(n.outline_, it_.current_node_->outline_);
		}
		virtual void visit(LeafNode& n) {
			if (n.is_full()) {
				// TODO split node
			} else {
				// insert here
				n.elements_[n.size()] =value_;
				it_.current_node_ = &n;
				it_.itstack_.push_back(n.size());
				n.size_++;
				// TODO n.outline_ = Rect::combination(n.outline_, std::get<0>(value_));
				n.outline_ = Rect::combination(n.outline(), value_.first);
			}
		}
		RTIterator& it_;
		const RTree::value_type& value_;
		std::vector<std::pair<float, INode*>> heap_;
	};
	using FindResult = std::vector<RTree::value_type>;
	struct FindExactOperation : public AbstractOperation {
		explicit FindExactOperation(const Point& p) : p_{p}
		{}
		auto begin() { return result_.begin(); }
		auto end() { return result_.end(); }
		virtual void visit(IndexNode& n) {
			for(const auto& e : n.elements_) {
				const auto& r = std::get<0>(e);
				if (r.contains(p_))
					std::get<1>(e)->accept(*this);
			}
		}
		virtual void visit(LeafNode& n) {
			for(const auto& e : n.elements_) {
				const auto& r = std::get<0>(e);
				if (r.contains(p_)) {
					result_.push_back(e);
				}
			}
		}
		FindResult result_;
		const Point& p_;
	};
	struct FindNearestOperation : public AbstractOperation {
		explicit FindNearestOperation(const Point& p) : p_{p}
		{}
		virtual void visit(IndexNode& n) {
			// TODO
		}
		virtual void visit(LeafNode& n) {
			// TODO
		}
		FindResult result_;
		const Point p_;
	};
	struct RTIterator
	{
		bool operator==(const RTIterator& i) const {
			if (current_node_ == nullptr && i.current_node_ == nullptr)
				return true;
			return std::tie(current_node_, itstack_) == std::tie(i.current_node_, i.itstack_);
		}
		bool operator!=(const RTIterator& i) const { return !(*this == i); }
		RTIterator& operator++() {
			if (itstack_.size() > 0) {
				auto pos = itstack_.back();
				++pos;
				if (pos + 1 < current_node_->size())
					return *this;

				// search into upwards index nodes
				INode* node = current_node_;
				while (itstack_.size() > 0 && node != nullptr && node->size() <= pos) {
					itstack_.pop_back();
					pos = ++itstack_.back();
					node = node->parent();
				}
				if (itstack_.size() == 0) {
					// nothing found; we're at the end
					current_node_ = nullptr;
				} else {
					// search downward to leaf node
					size_t depth {0};
					current_node_ = node->first_leaf(&depth);
					for(size_t i = 0; i < depth; ++i) {
						itstack_.push_back(0);
					}
				}
			}
			return *this;
		}
		RTree::value_type& operator*() { return current_node_->elements_[itstack_.back()]; }
		//RTIterator& operator++(int) { return *this; }
		//RTree* tree_ { nullptr };
		LeafNode* current_node_ { nullptr };
		std::vector<size_t> itstack_;
	};
	RTIterator begin();
	RTIterator end() { return RTIterator(); }

	RTIterator add(const value_type& r) {
		RTIterator it;
		AddOperation ao(r, it);
		root_->accept(ao);
		return it;
	}
	FindResult find_containing(const Point& p) {
		FindExactOperation feo(p);
		root_->accept(feo);
		return feo.result_;
	}
	FindResult find_nearest(const Point& p, size_t n = 1) {
		// TODO
		FindNearestOperation fno(p);
		root_->accept(fno);
		return fno.result_;
	}

	std::unique_ptr<INode> root_ = std::make_unique<LeafNode>(nullptr);
};

int main(int argc, char const *argv[])
{
	std::vector<std::string> params(argv, argv + argc);
	RTree rt;
	for(const auto& p : params) {
		std::cout << p << std::endl;
	}
	size_t counter = 0;
	rt.add(std::make_pair(Rect(Point(1, 1), Point(2, 2)), ++counter));
	rt.add(std::make_pair(Rect(Point(1, 2), Point(2, 2)), ++counter));
	rt.add(std::make_pair(Rect(Point(1, 3), Point(9, 2)), ++counter));
	rt.add(std::make_pair(Rect(Point(2, 1), Point(4, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(3, 1), Point(4, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(4, 1), Point(7, 2)), ++counter));
	rt.add(std::make_pair(Rect(Point(4, 4), Point(9, 8)), ++counter));
	rt.add(std::make_pair(Rect(Point(5, 1), Point(9, 9)), ++counter));
	rt.add(std::make_pair(Rect(Point(5, 4), Point(6, 5)), ++counter));
	rt.add(std::make_pair(Rect(Point(6, 1), Point(6, 6)), ++counter));
	rt.add(std::make_pair(Rect(Point(6, 6), Point(7, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(1, 1), Point(7, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(8, 4), Point(9, 5)), ++counter));
	rt.add(std::make_pair(Rect(Point(2, 5), Point(4, 6)), ++counter));
	rt.add(std::make_pair(Rect(Point(2, 6), Point(6, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(2, 7), Point(9, 7)), ++counter));
	rt.add(std::make_pair(Rect(Point(2, 8), Point(8, 9)), ++counter));
	return 0;
}<|endoftext|>


<commit_before>#include "inline_widget.hxx"
#include "uri/uri_parser.hxx"
#include "widget.hxx"
#include "widget_http.hxx"
#include "widget_resolver.hxx"
#include "widget_request.hxx"
#include "processor.h"
#include "penv.hxx"
#include "async.hxx"
#include "http_response.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool.hxx"

#include <glib.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

struct istream *
istream_iconv_new(gcc_unused struct pool *pool, struct istream *input,
                  gcc_unused const char *tocode,
                  gcc_unused const char *fromcode)
{
    return input;
}

void
widget_cancel(struct widget *widget gcc_unused)
{
}

bool
widget_check_host(const struct widget *widget gcc_unused,
                  const char *host gcc_unused,
                  const char *site_name gcc_unused)
{
    return true;
}

Session *
session_get(gcc_unused SessionId id)
{
    return NULL;
}

void
session_put(Session *session gcc_unused)
{
}

void
widget_sync_session(struct widget *widget gcc_unused,
                    Session *session gcc_unused)
{
}

void
widget_http_request(gcc_unused struct pool &pool,
                    gcc_unused struct widget &widget,
                    gcc_unused struct processor_env &env,
                    const struct http_response_handler &handler,
                    void *handler_ctx,
                    gcc_unused struct async_operation_ref &async_ref)
{
    GError *error = g_error_new_literal(g_quark_from_static_string("test"), 0,
                                        "Test");
    handler.InvokeAbort(handler_ctx, error);
}

struct test_operation {
    struct async_operation operation;
    struct pool *pool;
};

static void
test_abort(struct async_operation *ao gcc_unused)
{
    struct test_operation *to = (struct test_operation *)ao;

    pool_unref(to->pool);
}

static const struct async_operation_class test_operation = {
    .abort = test_abort,
};

void
widget_resolver_new(struct pool &pool, gcc_unused struct pool &widget_pool,
                    gcc_unused struct widget &widget,
                    gcc_unused struct tcache &translate_cache,
                    gcc_unused widget_resolver_callback_t callback,
                    gcc_unused void *ctx,
                    struct async_operation_ref &async_ref)
{
    auto to = NewFromPool<struct test_operation>(pool);

    to->pool = &pool;

    to->operation.Init(test_operation);
    async_ref.Set(to->operation);
    pool_ref(&pool);
}

static void
test_abort_resolver(struct pool *pool)
{
    const char *uri;
    bool ret;
    struct parsed_uri parsed_uri;
    struct widget widget;
    struct processor_env env;
    struct istream *istream;

    pool = pool_new_linear(pool, "test", 4096);

    uri = "/beng.html";
    ret = parsed_uri.Parse(uri);
    if (!ret) {
        fprintf(stderr, "uri_parse() failed\n");
        exit(2);
    }

    widget.Init(*pool, nullptr);

    istream = embed_inline_widget(*pool, env, false, widget);
    pool_unref(pool);

    istream_close_unused(istream);
}

int main(int argc, char **argv) {
    struct pool *pool;

    (void)argc;
    (void)argv;

    pool = pool_new_libc(NULL, "root");

    test_abort_resolver(pool);
    pool_commit();

    pool_unref(pool);
    pool_commit();
    pool_recycler_clear();
}
<commit_msg>test/t_wembed: add missing include<commit_after>#include "inline_widget.hxx"
#include "uri/uri_parser.hxx"
#include "widget.hxx"
#include "widget_http.hxx"
#include "widget_resolver.hxx"
#include "widget_request.hxx"
#include "processor.h"
#include "penv.hxx"
#include "async.hxx"
#include "http_response.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool.hxx"
#include "session.hxx"

#include <glib.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

struct istream *
istream_iconv_new(gcc_unused struct pool *pool, struct istream *input,
                  gcc_unused const char *tocode,
                  gcc_unused const char *fromcode)
{
    return input;
}

void
widget_cancel(struct widget *widget gcc_unused)
{
}

bool
widget_check_host(const struct widget *widget gcc_unused,
                  const char *host gcc_unused,
                  const char *site_name gcc_unused)
{
    return true;
}

Session *
session_get(gcc_unused SessionId id)
{
    return NULL;
}

void
session_put(Session *session gcc_unused)
{
}

void
widget_sync_session(struct widget *widget gcc_unused,
                    Session *session gcc_unused)
{
}

void
widget_http_request(gcc_unused struct pool &pool,
                    gcc_unused struct widget &widget,
                    gcc_unused struct processor_env &env,
                    const struct http_response_handler &handler,
                    void *handler_ctx,
                    gcc_unused struct async_operation_ref &async_ref)
{
    GError *error = g_error_new_literal(g_quark_from_static_string("test"), 0,
                                        "Test");
    handler.InvokeAbort(handler_ctx, error);
}

struct test_operation {
    struct async_operation operation;
    struct pool *pool;
};

static void
test_abort(struct async_operation *ao gcc_unused)
{
    struct test_operation *to = (struct test_operation *)ao;

    pool_unref(to->pool);
}

static const struct async_operation_class test_operation = {
    .abort = test_abort,
};

void
widget_resolver_new(struct pool &pool, gcc_unused struct pool &widget_pool,
                    gcc_unused struct widget &widget,
                    gcc_unused struct tcache &translate_cache,
                    gcc_unused widget_resolver_callback_t callback,
                    gcc_unused void *ctx,
                    struct async_operation_ref &async_ref)
{
    auto to = NewFromPool<struct test_operation>(pool);

    to->pool = &pool;

    to->operation.Init(test_operation);
    async_ref.Set(to->operation);
    pool_ref(&pool);
}

static void
test_abort_resolver(struct pool *pool)
{
    const char *uri;
    bool ret;
    struct parsed_uri parsed_uri;
    struct widget widget;
    struct processor_env env;
    struct istream *istream;

    pool = pool_new_linear(pool, "test", 4096);

    uri = "/beng.html";
    ret = parsed_uri.Parse(uri);
    if (!ret) {
        fprintf(stderr, "uri_parse() failed\n");
        exit(2);
    }

    widget.Init(*pool, nullptr);

    istream = embed_inline_widget(*pool, env, false, widget);
    pool_unref(pool);

    istream_close_unused(istream);
}

int main(int argc, char **argv) {
    struct pool *pool;

    (void)argc;
    (void)argv;

    pool = pool_new_libc(NULL, "root");

    test_abort_resolver(pool);
    pool_commit();

    pool_unref(pool);
    pool_commit();
    pool_recycler_clear();
}
<|endoftext|>


<commit_before>// ==========================================================================
//                                  lambda
// ==========================================================================
// Copyright (c) 2013, Hannes Hauswedell, FU Berlin
// All rights reserved.
//
// This file is part of Lambda.
//
// Lambda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Lambda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Lambda.  If not, see <http://www.gnu.org/licenses/>.*/
// ==========================================================================
// Author: Hannes Hauswedell <hauswedell@mi.fu-berlin.de>
// ==========================================================================
// holders.hpp: Data container structs
// ==========================================================================

#ifndef SEQAN_LAMBDA_HOLDERS_H_
#define SEQAN_LAMBDA_HOLDERS_H_

#include "match.hpp"
#include "options.hpp"

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// struct StatsHolder
// ----------------------------------------------------------------------------

struct StatsHolder
{
// seeding
    uint64_t hitsAfterSeeding;
    uint64_t hitsMerged;
    uint64_t hitsTooShort;
    uint64_t hitsMasked;

// pre-extension
    uint64_t hitsFailedPreExtendTest;
    uint64_t hitsPutativeDuplicate;
    uint64_t hitsPutativeAbundant;

// post-extension
    uint64_t hitsFailedExtendPercentIdentTest;
    uint64_t hitsFailedExtendEValueTest;
    uint64_t hitsAbundant;
    uint64_t hitsDuplicate;

// final
    uint64_t hitsFinal;
    uint64_t qrysWithHit;

    StatsHolder()
    {
        clear();
    }

    void clear()
    {
        hitsAfterSeeding = 0;
        hitsMerged = 0;
        hitsTooShort = 0;
        hitsMasked = 0;

        hitsFailedPreExtendTest = 0;
        hitsPutativeDuplicate = 0;
        hitsPutativeAbundant = 0;

        hitsFailedExtendPercentIdentTest = 0;
        hitsFailedExtendEValueTest = 0;
        hitsAbundant = 0;
        hitsDuplicate = 0;

        hitsFinal = 0;
        qrysWithHit = 0;
    }

    StatsHolder plus(StatsHolder const & rhs)
    {
        hitsAfterSeeding = rhs.hitsAfterSeeding;
        hitsMerged = rhs.hitsMerged;
        hitsTooShort = rhs.hitsTooShort;
        hitsMasked = rhs.hitsMasked;

        hitsFailedPreExtendTest = rhs.hitsFailedPreExtendTest;
        hitsPutativeDuplicate = rhs.hitsPutativeDuplicate;
        hitsPutativeAbundant = rhs.hitsPutativeAbundant;

        hitsFailedExtendPercentIdentTest = rhs.hitsFailedExtendPercentIdentTest;
        hitsFailedExtendEValueTest = rhs.hitsFailedExtendEValueTest;
        hitsAbundant = rhs.hitsAbundant;
        hitsDuplicate = rhs.hitsDuplicate;

        hitsFinal = rhs.hitsFinal;
        qrysWithHit = rhs.qrysWithHit;
        return *this;
    }

    StatsHolder operator+(StatsHolder const& rhs)
    {
        StatsHolder tmp(*this);
        return tmp.plus(rhs);
    }

    StatsHolder operator+=(StatsHolder const& rhs)
    {
        this->plus(rhs);
        return *this;
    }
};

// ----------------------------------------------------------------------------
// struct GlobalDataHolder  -- one object per program
// ----------------------------------------------------------------------------

template <typename TRedAlph_,
          typename TScoreScheme,
          typename TIndexSpec_,
          BlastFormatFile m,
          BlastFormatProgram p,
          BlastFormatGeneration g>
class GlobalDataHolder
{
public:
    using TFormat       = BlastFormat<m,p,g>;

    // SEQUENCES AND THEIR TYPE //
    using TTransSeqs    = TCDStringSet<TransAlph<p>>;

    using TRedAlph      = RedAlph<p, TRedAlph_>; // ensures == Dna5 for BlastN
    using TRedSeqVirt   = ModifiedString<String<TransAlph<p>, PackSpec>,
                                ModView<FunctorConvert<TransAlph<p>,TRedAlph>>>;
    using TRedSeqsVirt  = StringSet<TRedSeqVirt, Owner<ConcatDirect<>>>;

    static bool constexpr
    indexIsFM           = std::is_same<TIndexSpec_, FMIndex<>>::value;
    static bool constexpr
    noReduction         = std::is_same<TransAlph<p>, TRedAlph>::value;

    using TRedSeqs      = typename std::conditional<
                            noReduction,
                            TTransSeqs,             // owner
                            TRedSeqsVirt>::type;    // modview
    using TRedSeqsACT   = typename std::conditional<
                            noReduction,
                            TTransSeqs &,           // reference to owner
                            TRedSeqsVirt>::type;    // modview

    // these are the sequences in *unreduced space*
    TTransSeqs          qrySeqs;
    TTransSeqs          subjSeqs;

    // reduced query sequences if using reduction, otherwise & = transSeqs
    TRedSeqsACT         redQrySeqs = qrySeqs;
    TRedSeqsACT         redSubjSeqs = subjSeqs;

    // INDECES AND THEIR TYPE //
    using TIndexSpec    = TIndexSpec_;
    using TDbIndex      = Index<TRedSeqs, TIndexSpec>;

    TDbIndex            dbIndex;
    BlastDbSpecs<>      dbSpecs;

    // TODO maybe remove these for other specs?
    using TPositions    = typename StringSetLimits<TTransSeqs>::Type;
    TPositions          untransQrySeqLengths; // used iff qHasFrames(p)
    TPositions          untransSubjSeqLengths; // used iff sHasFrames(p)

    using TMasking      = StringSet<String<unsigned>, Owner<ConcatDirect<>>>;
    TMasking            segIntStarts;
    TMasking            segIntEnds;

    using TIds          = StringSet<CharString, Owner<ConcatDirect<>>>;
    TIds                qryIds;
    TIds                subjIds;

    using TBlastScoringAdapter = BlastScoringAdapter<TScoreScheme>;
    TScoreScheme                scoreScheme;
    TBlastScoringAdapter        blastScoringAdapter;

    StatsHolder                 stats = StatsHolder();
};

// ----------------------------------------------------------------------------
// struct LocalDataHolder  -- one object per thread
// ----------------------------------------------------------------------------

template <typename TMatch,
          typename TGlobalHolder_,
          typename TScoreExtension>
class LocalDataHolder
{
public:
    using TGlobalHolder = TGlobalHolder_;
    using TFormat       = typename TGlobalHolder::TFormat;
    using TRedQrySeq    = typename Value<typename TGlobalHolder::TRedSeqs>::Type;
    using TSeeds        = StringSet<typename Infix<TRedQrySeq const>::Type>;
    using TSeedIndex    = Index<TSeeds,IndexSa<>>;

    // references to global stuff
    LambdaOptions     const & options;
    TGlobalHolder /*const*/ & gH;

    // this is the localHolder for the i-th part of the queries
    uint64_t            i;

    // regarding range of queries
    uint64_t            indexBeginQry;
    uint64_t            indexEndQry;

    // regarding seedingp
    TSeeds              seeds;
    TSeedIndex          seedIndex;
//     std::forward_list<TMatch>   matches;
    std::vector<TMatch>   matches;
    std::vector<typename Match::TQId>   seedRefs;  // mapping seed -> query
    std::vector<uint16_t>               seedRanks; // mapping seed -> relative rank

    // regarding extension
    typedef Align<
        typename Infix<
            typename Value<
                typename TGlobalHolder::TTransSeqs>::Type>::Type,
                ArrayGaps> TAlign;

    typedef DPContext<typename Value<decltype(gH.scoreScheme)>::Type,
                      TScoreExtension> TDPContext;
    typedef AliExtContext_<TAlign,
                          TDPContext> TAliExtContext;

    TAliExtContext      alignContext;

    // regarding the gathering of stats
    StatsHolder         stats;

    // progress string
    std::stringstream         statusStr;

    // constructor
    LocalDataHolder(LambdaOptions     const & _options,
                    TGlobalHolder     /*const*/ & _globalHolder) :
        options(_options), gH(_globalHolder), stats()
    {}

    // copy constructor SHALLOW COPY ONLY, REQUIRED FOR firsprivate()
    LocalDataHolder(LocalDataHolder const & rhs) :
        options(rhs.options), gH(rhs.gH), stats()
    {}

    void init(uint64_t const _i)
    {
        i = _i;

        if (options.doubleIndexing)
        {
            indexBeginQry = (length(gH.qrySeqs) / options.queryPart) * i;
            indexEndQry = (i+1 == options.queryPart) // last interval
                            ? length(gH.qrySeqs) // reach until end
                            : (length(gH.qrySeqs) / options.queryPart) * (i+1);
        } else
        {
            indexBeginQry = qNumFrames(TFormat()) * i;
            indexEndQry = qNumFrames(TFormat()) * (i+1);
        }

        clear(seeds);
        clear(seedIndex);
        matches.clear();
        seedRefs.clear();
        seedRanks.clear();
//         stats.clear();
        statusStr.clear();
        statusStr.precision(2);
    }

};

// perform a fast local alignment score calculation on the seed and see if we
// reach above threshold
// WARNING the following function only works for hammingdistanced seeds
template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension>
inline bool
seedLooksPromising(
            LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> const & lH,
            TMatch const & m)
{
    auto const & qSeq = infix(lH.gH.qrySeqs[m.qryId],
                              m.qryStart,
                              m.qryStart + lH.options.seedLength);
    auto const & sSeq = infix(lH.gH.subjSeqs[m.subjId],
                              m.subjStart,
                              m.subjStart + lH.options.seedLength);
    int maxScore = 0;

    int scores[lH.options.seedLength]; // C99, C++14, -Wno-vla before that
    scores[0] = 0;

    // score the diagonal
    for (unsigned i = 0; i < lH.options.seedLength; ++i)
    {
        scores[i] += score(lH.gH.scoreScheme, qSeq[i], sSeq[i]);
        if (scores[i] < 0)
            scores[i] = 0;
        else if (scores[i] >= maxScore)
            maxScore = scores[i];

        if (i < static_cast<unsigned>(lH.options.seedLength - 1))
            scores[i+1] = scores[i];
    }

    return (maxScore >= lH.options.minSeedScore);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TSeedId,
          typename TSubjOcc>
inline void
onFindImpl(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
           TSeedId const & seedId,
           TSubjOcc subjOcc)
{
    if (TGlobalHolder::indexIsFM) // positions are reversed
        setSeqOffset(subjOcc,
                     length(lH.gH.subjSeqs[getSeqNo(subjOcc)])
                     - getSeqOffset(subjOcc)
                     - lH.options.seedLength);

    Match m {static_cast<Match::TQId>(lH.seedRefs[seedId]),
             static_cast<Match::TSId>(getSeqNo(subjOcc)),
             static_cast<Match::TPos>(lH.seedRanks[seedId] * lH.options.seedOffset),
             static_cast<Match::TPos>(getSeqOffset(subjOcc))};

    bool discarded = false;
    auto const halfSubjL = lH.options.seedLength /  2;

    for (unsigned k = 0; k < length(lH.gH.segIntStarts[m.subjId]); ++k)
    {
        // more than half of the seed falls into masked interval
        if (intervalOverlap(m.subjStart,
                            m.subjStart + lH.options.seedLength,
                            lH.gH.segIntStarts[m.subjId][k],
                            lH.gH.segIntEnds[m.subjId][k])
                >= halfSubjL)
        {
            ++lH.stats.hitsMasked;
            discarded = true;
            break;
        }
    }

     if ((!TGlobalHolder::noReduction) && (!discarded) &&
         (!seedLooksPromising(lH, m)))
     {
         discarded = true;
         ++lH.stats.hitsFailedPreExtendTest;
     }

    if (!discarded)
        lH.matches.emplace_back(m);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TFinder>
inline void
onFindDoubleIndex(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
                  TFinder const & finder)
{
    auto qryOccs = getOccurrences(back(finder.patternStack));
    auto subjOccs = getOccurrences(back(finder.textStack));

    lH.stats.hitsAfterSeeding += length(qryOccs) * length(subjOccs);

    for (unsigned i = 0; i < length(qryOccs); ++i)
        for (unsigned j = 0; j < length(subjOccs); ++j)
            onFindImpl(lH, getSeqNo(qryOccs[i]), subjOccs[j]);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TSeedListIterator,
          typename TIndexIterator>
inline void
onFindSingleIndex(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
                  TSeedListIterator const & seedIt,
                  TIndexIterator const & indexIt)
{
    auto qryOcc = position(seedIt);
    auto subjOccs = getOccurrences(indexIt);

    lH.stats.hitsAfterSeeding += length(subjOccs);

    for (unsigned j = 0; j < length(subjOccs); ++j)
        onFindImpl(lH, qryOcc, subjOccs[j]);
}

#endif // SEQAN_LAMBDA_HOLDERS_H_
<commit_msg>[fix] plus operator had = instead of +=<commit_after>// ==========================================================================
//                                  lambda
// ==========================================================================
// Copyright (c) 2013, Hannes Hauswedell, FU Berlin
// All rights reserved.
//
// This file is part of Lambda.
//
// Lambda is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Lambda is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Lambda.  If not, see <http://www.gnu.org/licenses/>.*/
// ==========================================================================
// Author: Hannes Hauswedell <hauswedell@mi.fu-berlin.de>
// ==========================================================================
// holders.hpp: Data container structs
// ==========================================================================

#ifndef SEQAN_LAMBDA_HOLDERS_H_
#define SEQAN_LAMBDA_HOLDERS_H_

#include "match.hpp"
#include "options.hpp"

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// struct StatsHolder
// ----------------------------------------------------------------------------

struct StatsHolder
{
// seeding
    uint64_t hitsAfterSeeding;
    uint64_t hitsMerged;
    uint64_t hitsTooShort;
    uint64_t hitsMasked;

// pre-extension
    uint64_t hitsFailedPreExtendTest;
    uint64_t hitsPutativeDuplicate;
    uint64_t hitsPutativeAbundant;

// post-extension
    uint64_t hitsFailedExtendPercentIdentTest;
    uint64_t hitsFailedExtendEValueTest;
    uint64_t hitsAbundant;
    uint64_t hitsDuplicate;

// final
    uint64_t hitsFinal;
    uint64_t qrysWithHit;

    StatsHolder()
    {
        clear();
    }

    void clear()
    {
        hitsAfterSeeding = 0;
        hitsMerged = 0;
        hitsTooShort = 0;
        hitsMasked = 0;

        hitsFailedPreExtendTest = 0;
        hitsPutativeDuplicate = 0;
        hitsPutativeAbundant = 0;

        hitsFailedExtendPercentIdentTest = 0;
        hitsFailedExtendEValueTest = 0;
        hitsAbundant = 0;
        hitsDuplicate = 0;

        hitsFinal = 0;
        qrysWithHit = 0;
    }

    StatsHolder plus(StatsHolder const & rhs)
    {
        hitsAfterSeeding += rhs.hitsAfterSeeding;
        hitsMerged += rhs.hitsMerged;
        hitsTooShort += rhs.hitsTooShort;
        hitsMasked += rhs.hitsMasked;

        hitsFailedPreExtendTest += rhs.hitsFailedPreExtendTest;
        hitsPutativeDuplicate += rhs.hitsPutativeDuplicate;
        hitsPutativeAbundant += rhs.hitsPutativeAbundant;

        hitsFailedExtendPercentIdentTest += rhs.hitsFailedExtendPercentIdentTest;
        hitsFailedExtendEValueTest += rhs.hitsFailedExtendEValueTest;
        hitsAbundant += rhs.hitsAbundant;
        hitsDuplicate += rhs.hitsDuplicate;

        hitsFinal += rhs.hitsFinal;
        qrysWithHit += rhs.qrysWithHit;
        return *this;
    }

    StatsHolder operator+(StatsHolder const& rhs)
    {
        StatsHolder tmp(*this);
        return tmp.plus(rhs);
    }

    StatsHolder operator+=(StatsHolder const& rhs)
    {
        this->plus(rhs);
        return *this;
    }
};

// ----------------------------------------------------------------------------
// struct GlobalDataHolder  -- one object per program
// ----------------------------------------------------------------------------

template <typename TRedAlph_,
          typename TScoreScheme,
          typename TIndexSpec_,
          BlastFormatFile m,
          BlastFormatProgram p,
          BlastFormatGeneration g>
class GlobalDataHolder
{
public:
    using TFormat       = BlastFormat<m,p,g>;

    // SEQUENCES AND THEIR TYPE //
    using TTransSeqs    = TCDStringSet<TransAlph<p>>;

    using TRedAlph      = RedAlph<p, TRedAlph_>; // ensures == Dna5 for BlastN
    using TRedSeqVirt   = ModifiedString<String<TransAlph<p>, PackSpec>,
                                ModView<FunctorConvert<TransAlph<p>,TRedAlph>>>;
    using TRedSeqsVirt  = StringSet<TRedSeqVirt, Owner<ConcatDirect<>>>;

    static bool constexpr
    indexIsFM           = std::is_same<TIndexSpec_, FMIndex<>>::value;
    static bool constexpr
    noReduction         = std::is_same<TransAlph<p>, TRedAlph>::value;

    using TRedSeqs      = typename std::conditional<
                            noReduction,
                            TTransSeqs,             // owner
                            TRedSeqsVirt>::type;    // modview
    using TRedSeqsACT   = typename std::conditional<
                            noReduction,
                            TTransSeqs &,           // reference to owner
                            TRedSeqsVirt>::type;    // modview

    // these are the sequences in *unreduced space*
    TTransSeqs          qrySeqs;
    TTransSeqs          subjSeqs;

    // reduced query sequences if using reduction, otherwise & = transSeqs
    TRedSeqsACT         redQrySeqs = qrySeqs;
    TRedSeqsACT         redSubjSeqs = subjSeqs;

    // INDECES AND THEIR TYPE //
    using TIndexSpec    = TIndexSpec_;
    using TDbIndex      = Index<TRedSeqs, TIndexSpec>;

    TDbIndex            dbIndex;
    BlastDbSpecs<>      dbSpecs;

    // TODO maybe remove these for other specs?
    using TPositions    = typename StringSetLimits<TTransSeqs>::Type;
    TPositions          untransQrySeqLengths; // used iff qHasFrames(p)
    TPositions          untransSubjSeqLengths; // used iff sHasFrames(p)

    using TMasking      = StringSet<String<unsigned>, Owner<ConcatDirect<>>>;
    TMasking            segIntStarts;
    TMasking            segIntEnds;

    using TIds          = StringSet<CharString, Owner<ConcatDirect<>>>;
    TIds                qryIds;
    TIds                subjIds;

    using TBlastScoringAdapter = BlastScoringAdapter<TScoreScheme>;
    TScoreScheme                scoreScheme;
    TBlastScoringAdapter        blastScoringAdapter;

    StatsHolder                 stats = StatsHolder();
};

// ----------------------------------------------------------------------------
// struct LocalDataHolder  -- one object per thread
// ----------------------------------------------------------------------------

template <typename TMatch,
          typename TGlobalHolder_,
          typename TScoreExtension>
class LocalDataHolder
{
public:
    using TGlobalHolder = TGlobalHolder_;
    using TFormat       = typename TGlobalHolder::TFormat;
    using TRedQrySeq    = typename Value<typename TGlobalHolder::TRedSeqs>::Type;
    using TSeeds        = StringSet<typename Infix<TRedQrySeq const>::Type>;
    using TSeedIndex    = Index<TSeeds,IndexSa<>>;

    // references to global stuff
    LambdaOptions     const & options;
    TGlobalHolder /*const*/ & gH;

    // this is the localHolder for the i-th part of the queries
    uint64_t            i;

    // regarding range of queries
    uint64_t            indexBeginQry;
    uint64_t            indexEndQry;

    // regarding seedingp
    TSeeds              seeds;
    TSeedIndex          seedIndex;
//     std::forward_list<TMatch>   matches;
    std::vector<TMatch>   matches;
    std::vector<typename Match::TQId>   seedRefs;  // mapping seed -> query
    std::vector<uint16_t>               seedRanks; // mapping seed -> relative rank

    // regarding extension
    typedef Align<
        typename Infix<
            typename Value<
                typename TGlobalHolder::TTransSeqs>::Type>::Type,
                ArrayGaps> TAlign;

    typedef DPContext<typename Value<decltype(gH.scoreScheme)>::Type,
                      TScoreExtension> TDPContext;
    typedef AliExtContext_<TAlign,
                          TDPContext> TAliExtContext;

    TAliExtContext      alignContext;

    // regarding the gathering of stats
    StatsHolder         stats;

    // progress string
    std::stringstream         statusStr;

    // constructor
    LocalDataHolder(LambdaOptions     const & _options,
                    TGlobalHolder     /*const*/ & _globalHolder) :
        options(_options), gH(_globalHolder), stats()
    {}

    // copy constructor SHALLOW COPY ONLY, REQUIRED FOR firsprivate()
    LocalDataHolder(LocalDataHolder const & rhs) :
        options(rhs.options), gH(rhs.gH), stats()
    {}

    void init(uint64_t const _i)
    {
        i = _i;

        if (options.doubleIndexing)
        {
            indexBeginQry = (length(gH.qrySeqs) / options.queryPart) * i;
            indexEndQry = (i+1 == options.queryPart) // last interval
                            ? length(gH.qrySeqs) // reach until end
                            : (length(gH.qrySeqs) / options.queryPart) * (i+1);
        } else
        {
            indexBeginQry = qNumFrames(TFormat()) * i;
            indexEndQry = qNumFrames(TFormat()) * (i+1);
        }

        clear(seeds);
        clear(seedIndex);
        matches.clear();
        seedRefs.clear();
        seedRanks.clear();
//         stats.clear();
        statusStr.clear();
        statusStr.precision(2);
    }

};

// perform a fast local alignment score calculation on the seed and see if we
// reach above threshold
// WARNING the following function only works for hammingdistanced seeds
template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension>
inline bool
seedLooksPromising(
            LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> const & lH,
            TMatch const & m)
{
    auto const & qSeq = infix(lH.gH.qrySeqs[m.qryId],
                              m.qryStart,
                              m.qryStart + lH.options.seedLength);
    auto const & sSeq = infix(lH.gH.subjSeqs[m.subjId],
                              m.subjStart,
                              m.subjStart + lH.options.seedLength);
    int maxScore = 0;

    int scores[lH.options.seedLength]; // C99, C++14, -Wno-vla before that
    scores[0] = 0;

    // score the diagonal
    for (unsigned i = 0; i < lH.options.seedLength; ++i)
    {
        scores[i] += score(lH.gH.scoreScheme, qSeq[i], sSeq[i]);
        if (scores[i] < 0)
            scores[i] = 0;
        else if (scores[i] >= maxScore)
            maxScore = scores[i];

        if (i < static_cast<unsigned>(lH.options.seedLength - 1))
            scores[i+1] = scores[i];
    }

    return (maxScore >= lH.options.minSeedScore);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TSeedId,
          typename TSubjOcc>
inline void
onFindImpl(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
           TSeedId const & seedId,
           TSubjOcc subjOcc)
{
    if (TGlobalHolder::indexIsFM) // positions are reversed
        setSeqOffset(subjOcc,
                     length(lH.gH.subjSeqs[getSeqNo(subjOcc)])
                     - getSeqOffset(subjOcc)
                     - lH.options.seedLength);

    Match m {static_cast<Match::TQId>(lH.seedRefs[seedId]),
             static_cast<Match::TSId>(getSeqNo(subjOcc)),
             static_cast<Match::TPos>(lH.seedRanks[seedId] * lH.options.seedOffset),
             static_cast<Match::TPos>(getSeqOffset(subjOcc))};

    bool discarded = false;
    auto const halfSubjL = lH.options.seedLength /  2;

    for (unsigned k = 0; k < length(lH.gH.segIntStarts[m.subjId]); ++k)
    {
        // more than half of the seed falls into masked interval
        if (intervalOverlap(m.subjStart,
                            m.subjStart + lH.options.seedLength,
                            lH.gH.segIntStarts[m.subjId][k],
                            lH.gH.segIntEnds[m.subjId][k])
                >= halfSubjL)
        {
            ++lH.stats.hitsMasked;
            discarded = true;
            break;
        }
    }

     if ((!TGlobalHolder::noReduction) && (!discarded) &&
         (!seedLooksPromising(lH, m)))
     {
         discarded = true;
         ++lH.stats.hitsFailedPreExtendTest;
     }

    if (!discarded)
        lH.matches.emplace_back(m);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TFinder>
inline void
onFindDoubleIndex(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
                  TFinder const & finder)
{
    auto qryOccs = getOccurrences(back(finder.patternStack));
    auto subjOccs = getOccurrences(back(finder.textStack));

    lH.stats.hitsAfterSeeding += length(qryOccs) * length(subjOccs);

    for (unsigned i = 0; i < length(qryOccs); ++i)
        for (unsigned j = 0; j < length(subjOccs); ++j)
            onFindImpl(lH, getSeqNo(qryOccs[i]), subjOccs[j]);
}

template <typename TMatch,
          typename TGlobalHolder,
          typename TScoreExtension,
          typename TSeedListIterator,
          typename TIndexIterator>
inline void
onFindSingleIndex(LocalDataHolder<TMatch, TGlobalHolder, TScoreExtension> & lH,
                  TSeedListIterator const & seedIt,
                  TIndexIterator const & indexIt)
{
    auto qryOcc = position(seedIt);
    auto subjOccs = getOccurrences(indexIt);

    lH.stats.hitsAfterSeeding += length(subjOccs);

    for (unsigned j = 0; j < length(subjOccs); ++j)
        onFindImpl(lH, qryOcc, subjOccs[j]);
}

#endif // SEQAN_LAMBDA_HOLDERS_H_
<|endoftext|>


<commit_before>// Copyright 2008 Paul Hodge

#include "circa.h"

namespace circa {
namespace assert_function {

    void evaluate(Term* caller)
    {
        if (!as_bool(caller->input(0))) {
            error_occured(caller, "Assert failed");
        }
    }

    void setup(Branch& kernel)
    {
        /*Term* main_func = */import_c_function(kernel, evaluate,
                "function assert(bool)");
    }
}
}
<commit_msg>Minor<commit_after>// Copyright 2008 Paul Hodge

#include "circa.h"

namespace circa {
namespace assert_function {

    void evaluate(Term* caller)
    {
        if (!as_bool(caller->input(0))) {
            error_occured(caller, "Assert failed");
        }
    }

    void setup(Branch& kernel)
    {
        Term* main_func = import_c_function(kernel, evaluate,
                "function assert(bool)");
        as_function(main_func).pureFunction = false;
    }
}
}
<|endoftext|>


<commit_before>#ifndef BOOKMARK_HH
#define BOOKMARK_HH

#include <string>
#include <vector>

struct Duplication;
class Options;

class Bookmark
{
    struct FileRecord
    {
        FileRecord(const std::string& n, int i): fileName(n), endIx(i) {}
        std::string fileName;
        int         endIx; // Position right after the final char of the file.
    };

public:
    Bookmark(int i = 0, const char* p = 0): original(i), processed(p) {}

    /**
     * Reports one instance of duplication and optionally prints the duplicated
     * string.
     */
    void report(const Duplication& duplication,
                int                instanceNr,
                const Options&     options) const;

    void clear() { this->processed = 0; }

    bool isCleared() const { return this->processed == 0; }

    bool operator<(const Bookmark& another) const; // Used in sorting.

    int nrOfSame(Bookmark b) const;

    /**
     * Used for optimization purposes. By comparing strings backwards we can
     * find out quickly if the two strings are not equal in the given number of
     * characters and move on to the next comparison.
     */
    bool sameAs(Bookmark b, int nrOfCharacters, const char* end) const;

    static int getTotalNrOfLines() { return totalNrOfLines; }

    static void addFile(const std::string& fileName);

    static size_t totalLength() { return totalString.length(); }

    static const char& getChar(int i) { return totalString[i]; }

private:
    friend std::ostream& operator<<(std::ostream& os, const Bookmark& b);
    friend class BookmarkContainer;

    enum DetailType { PRINT_LINES, COUNT_LINES };

    int
    details(int processedLength, DetailType detailType, bool wordMode) const;

    static int lineNr(int offset, int index);

    static int                     totalNrOfLines;
    static std::vector<FileRecord> fileRecords;
    static std::string             totalString;

    int         original;
    const char* processed;
};

#endif
<commit_msg>Add comments<commit_after>#ifndef BOOKMARK_HH
#define BOOKMARK_HH

#include <string>
#include <vector>

struct Duplication;
class Options;

/**
 * A bookmark is something that points at a position in the processed
 * text while also keeping track of the corresponding position in the
 * file where the text originally came from.
 */
class Bookmark
{
    struct FileRecord
    {
        FileRecord(const std::string& n, int i): fileName(n), endIx(i) {}
        std::string fileName;
        int         endIx; // Position right after the final char of the file.
    };

public:
    Bookmark(int i = 0, const char* p = 0): original(i), processed(p) {}

    /**
     * Reports one instance of duplication and optionally prints the duplicated
     * string.
     */
    void report(const Duplication& duplication,
                int                instanceNr,
                const Options&     options) const;

    /**
     * Clear the bookmark, i.e. mark it for deletion.
     */
    void clear() { this->processed = 0; }

    bool isCleared() const { return this->processed == 0; }

    bool operator<(const Bookmark& another) const; // Used in sorting.

    /**
     * How many characters are equal when comparing the bookmark to
     * another bookmark?
     */
    int nrOfSame(Bookmark b) const;

    /**
     * Used for optimization purposes. By comparing strings backwards we can
     * find out quickly if the two strings are not equal in the given number of
     * characters and move on to the next comparison.
     */
    bool sameAs(Bookmark b, int nrOfCharacters, const char* end) const;

    static int getTotalNrOfLines() { return totalNrOfLines; }

    static void addFile(const std::string& fileName);

    static size_t totalLength() { return totalString.length(); }

    static const char& getChar(int i) { return totalString[i]; }

private:
    friend std::ostream& operator<<(std::ostream& os, const Bookmark& b);
    friend class BookmarkContainer;

    enum DetailType { PRINT_LINES, COUNT_LINES };

    int
    details(int processedLength, DetailType detailType, bool wordMode) const;

    static int lineNr(int offset, int index);

    static int                     totalNrOfLines;
    static std::vector<FileRecord> fileRecords;
    static std::string             totalString;

    int         original;
    const char* processed;
};

#endif
<|endoftext|>


<commit_before>
/* ========================================

   * File Name : 10.cpp

   * Creation Date : 24-07-2020

   * Last Modified : Pá 24. července 2020, 21:15:59

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2020/qualification-round/problems/A

   * Points Gained (in case of online contest) :

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;

const int CLEAN = -1;

template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

const char default_char = 'N';

vector<vector<char>> get_result(int N, string I, string O) {
  vector<vector<char>> reachability(N, vector<char>(N, default_char));
  REP(d,N) reachability[d][d] = 'Y';

  REP(d,N-1) {
    REP(i, N) REP(j, N) {
      if (reachability[i][j] == 'N' || O[j] == 'N') {
        continue;
      }

      int neigh;
      for (auto & delta: {-1, 1}) {
//         MSG(delta)
        neigh = j + delta;

        if (0 <= neigh && neigh < N && I[neigh] == 'Y') {
          reachability[i][neigh] = 'Y';
        }
      }
    }
  }

  return reachability;
}

int main() {
  int T;
  cin >> T;
//   MSG(T)

  REP(i,T) {
    int N;
    cin >> N;
//     MSG(N)

    string I, O;
    cin >> I;
    cin >> O;
//     MSG(I) MSG(O)

    cout << "Case #" << i + 1 << ":" << endl;
    vector<vector<char>> result = get_result(N, I, O);
    REP(r,N) {
      REP(c,N) {
        cout << result[r][c];
      }
      cout << endl;
    }

  }
  return 0;
}
<commit_msg>Add extra space after "Case #i:"<commit_after>
/* ========================================

   * File Name : 10.cpp

   * Creation Date : 24-07-2020

   * Last Modified : Pá 24. července 2020, 21:15:59

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2020/qualification-round/problems/A

   * Points Gained (in case of online contest) :

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;

const int CLEAN = -1;

template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

const char default_char = 'N';

vector<vector<char>> get_result(int N, string I, string O) {
  vector<vector<char>> reachability(N, vector<char>(N, default_char));
  REP(d,N) reachability[d][d] = 'Y';

  REP(d,N-1) {
    REP(i, N) REP(j, N) {
      if (reachability[i][j] == 'N' || O[j] == 'N') {
        continue;
      }

      int neigh;
      for (auto & delta: {-1, 1}) {
//         MSG(delta)
        neigh = j + delta;

        if (0 <= neigh && neigh < N && I[neigh] == 'Y') {
          reachability[i][neigh] = 'Y';
        }
      }
    }
  }

  return reachability;
}

int main() {
  int T;
  cin >> T;
//   MSG(T)

  REP(i,T) {
    int N;
    cin >> N;
//     MSG(N)

    string I, O;
    cin >> I;
    cin >> O;
//     MSG(I) MSG(O)

    cout << "Case #" << i + 1 << ": " << endl;
    vector<vector<char>> result = get_result(N, I, O);
    REP(r,N) {
      REP(c,N) {
        cout << result[r][c];
      }
      cout << endl;
    }

  }
  return 0;
}
<|endoftext|>