diff --git a/pool/shard002/C++/0034609_web_apps.cc b/pool/shard002/C++/0034609_web_apps.cc
new file mode 100644
index 0000000000000000000000000000000000000000..375adf8125383e9929e5fa463a6dcb29547ac9ca
--- /dev/null
+++ b/pool/shard002/C++/0034609_web_apps.cc
@@ -0,0 +1,57 @@
+// Copyright 2019 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/browser/apps/app_service/web_apps.h"
+
+#include "base/bind_helpers.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h"
+#include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h"
+#include "chrome/browser/web_applications/system_web_app_manager.h"
+#include "chrome/browser/web_applications/web_app_provider.h"
+
+namespace apps {
+
+WebApps::WebApps(const mojo::Remote& app_service,
+ Profile* profile)
+ : WebAppsBase(app_service, profile) {}
+
+WebApps::~WebApps() = default;
+
+// static
+void WebApps::UninstallImpl(Profile* profile,
+ const std::string& app_id,
+ gfx::NativeWindow parent_window) {
+ web_app::WebAppUiManagerImpl* web_app_ui_manager =
+ web_app::WebAppUiManagerImpl::Get(profile);
+ if (!web_app_ui_manager) {
+ return;
+ }
+
+ web_app::WebAppDialogManager& web_app_dialog_manager =
+ web_app_ui_manager->dialog_manager();
+ if (web_app_dialog_manager.CanUninstallWebApp(app_id)) {
+ web_app_dialog_manager.UninstallWebApp(
+ app_id, web_app::WebAppDialogManager::UninstallSource::kAppMenu,
+ parent_window, base::DoNothing());
+ }
+}
+
+apps::mojom::AppPtr WebApps::Convert(const web_app::WebApp* web_app,
+ apps::mojom::Readiness readiness) {
+ apps::mojom::AppPtr app = ConvertImpl(web_app, readiness);
+
+ app->icon_key = icon_key_factory().MakeIconKey(GetIconEffects(web_app));
+
+ app->has_badge = apps::mojom::OptionalBool::kFalse;
+ app->paused = apps::mojom::OptionalBool::kFalse;
+
+ return app;
+}
+
+bool WebApps::Accepts(const std::string& app_id) {
+ return true;
+}
+
+} // namespace apps
diff --git a/pool/shard002/C++/0034610_ServicePortCollection.cpp b/pool/shard002/C++/0034610_ServicePortCollection.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a5836d61d8356f677fbba867fbc82f195fb0296c
--- /dev/null
+++ b/pool/shard002/C++/0034610_ServicePortCollection.cpp
@@ -0,0 +1,176 @@
+// Copyright 2015 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 "config.h"
+#include "modules/navigatorconnect/ServicePortCollection.h"
+
+#include "bindings/core/v8/ScriptPromiseResolver.h"
+#include "bindings/core/v8/SerializedScriptValueFactory.h"
+#include "core/dom/DOMException.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/dom/MessagePort.h"
+#include "core/events/MessageEvent.h"
+#include "modules/EventTargetModules.h"
+#include "modules/navigatorconnect/AcceptConnectionObserver.h"
+#include "modules/navigatorconnect/ServicePort.h"
+#include "modules/navigatorconnect/ServicePortConnectEvent.h"
+#include "modules/navigatorconnect/ServicePortConnectEventInit.h"
+#include "modules/navigatorconnect/ServicePortConnectOptions.h"
+#include "public/platform/Platform.h"
+#include "public/platform/modules/navigator_services/WebServicePortProvider.h"
+
+namespace blink {
+
+namespace {
+
+class ConnectCallbacks : public WebServicePortConnectCallbacks {
+public:
+ ConnectCallbacks(ScriptPromiseResolver* resolver, ServicePortCollection* collection, const KURL& targetUrl, const String& portName, const String& serializedPortData)
+ : m_resolver(resolver), m_collection(collection), m_targetUrl(targetUrl), m_portName(portName), m_serializedPortData(serializedPortData)
+ {
+ ASSERT(m_resolver);
+ }
+
+ ~ConnectCallbacks() override { }
+
+ void onSuccess(WebServicePortID* portIdRaw) override
+ {
+ OwnPtr webPortId = adoptPtr(portIdRaw);
+ if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) {
+ return;
+ }
+ WebServicePort webPort;
+ webPort.id = *webPortId;
+ webPort.targetUrl = m_targetUrl;
+ webPort.name = m_portName;
+ webPort.data = m_serializedPortData;
+ ServicePort* port = ServicePort::create(m_collection, webPort);
+ m_collection->addPort(port);
+ m_resolver->resolve(port);
+ }
+
+ void onError() override
+ {
+ // TODO(mek): Pass actual error code back.
+ if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) {
+ return;
+ }
+ m_resolver->reject(DOMException::create(AbortError));
+ }
+
+private:
+ Persistent m_resolver;
+ Persistent m_collection;
+ KURL m_targetUrl;
+ String m_portName;
+ String m_serializedPortData;
+
+ WTF_MAKE_NONCOPYABLE(ConnectCallbacks);
+};
+
+} // namespace
+
+ServicePortCollection* ServicePortCollection::create(ExecutionContext* context)
+{
+ return new ServicePortCollection(context);
+}
+
+ServicePortCollection::~ServicePortCollection()
+{
+}
+
+void ServicePortCollection::addPort(ServicePort* port)
+{
+ m_ports.append(port);
+}
+
+void ServicePortCollection::closePort(ServicePort* port)
+{
+ m_ports.remove(m_ports.find(port));
+ if (m_provider)
+ m_provider->closePort(port->id());
+}
+
+ScriptPromise ServicePortCollection::connect(ScriptState* scriptState, const String& url, const ServicePortConnectOptions& options, ExceptionState& exceptionState)
+{
+ if (!m_provider)
+ return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));
+
+ RefPtr portData;
+ if (options.hasData()) {
+ portData = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState);
+ if (exceptionState.hadException())
+ return exceptionState.reject(scriptState);
+ }
+ ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
+ ScriptPromise promise = resolver->promise();
+ KURL targetUrl = scriptState->executionContext()->completeURL(url);
+ m_provider->connect(
+ targetUrl,
+ scriptState->executionContext()->securityOrigin()->toString(),
+ new ConnectCallbacks(resolver, this, targetUrl, options.name(), portData ? portData->toWireString() : String()));
+ return promise;
+}
+
+ScriptPromise ServicePortCollection::match(ScriptState* scriptState, const ServicePortMatchOptions& options)
+{
+ return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));
+}
+
+ScriptPromise ServicePortCollection::matchAll(ScriptState* scriptState, const ServicePortMatchOptions& options)
+{
+ return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));
+}
+
+const AtomicString& ServicePortCollection::interfaceName() const
+{
+ return EventTargetNames::ServicePortCollection;
+}
+
+ExecutionContext* ServicePortCollection::executionContext() const
+{
+ return ContextLifecycleObserver::executionContext();
+}
+
+void ServicePortCollection::postMessage(WebServicePortID portId, const WebString& messageString, const WebMessagePortChannelArray& webChannels)
+{
+ OwnPtr channels;
+ if (webChannels.size()) {
+ channels = adoptPtr(new MessagePortChannelArray(webChannels.size()));
+ for (size_t i = 0; i < webChannels.size(); ++i)
+ (*channels)[i] = adoptPtr(webChannels[i]);
+ }
+ RefPtr message = SerializedScriptValueFactory::instance().createFromWire(messageString);
+
+ MessagePortArray* ports = MessagePort::entanglePorts(*executionContext(), channels.release());
+ RefPtrWillBeRawPtr evt = MessageEvent::create(ports, message.release());
+ // TODO(mek): Lookup ServicePort and set events source attribute.
+ dispatchEvent(evt.release());
+}
+
+void ServicePortCollection::dispatchConnectEvent(PassOwnPtr callbacks, const WebURL& targetURL, const WebString& origin, WebServicePortID portID)
+{
+ AcceptConnectionObserver* observer = AcceptConnectionObserver::create(this, callbacks, portID, targetURL);
+ ServicePortConnectEventInit init;
+ init.setTargetURL(targetURL.string());
+ init.setOrigin(origin);
+ RefPtrWillBeRawPtr event = ServicePortConnectEvent::create(EventTypeNames::connect, init, observer);
+ dispatchEvent(event.release());
+ observer->didDispatchEvent();
+}
+
+DEFINE_TRACE(ServicePortCollection)
+{
+ visitor->trace(m_ports);
+ RefCountedGarbageCollectedEventTargetWithInlineData::trace(visitor);
+ ContextLifecycleObserver::trace(visitor);
+}
+
+ServicePortCollection::ServicePortCollection(ExecutionContext* context)
+ : ContextLifecycleObserver(context)
+ , m_provider(adoptPtr(Platform::current()->createServicePortProvider(this)))
+{
+}
+
+} // namespace blink
diff --git a/pool/shard002/C++/0034611_qxtpushbutton.cpp b/pool/shard002/C++/0034611_qxtpushbutton.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..9cc69db2dc6e46daaf6c5259217db751d0157af3
--- /dev/null
+++ b/pool/shard002/C++/0034611_qxtpushbutton.cpp
@@ -0,0 +1,323 @@
+#include "qxtpushbutton.h"
+/****************************************************************************
+** Copyright (c) 2006 - 2011, the LibQxt project.
+** See the Qxt AUTHORS file for a list of authors and copyright holders.
+** All rights reserved.
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in the
+** documentation and/or other materials provided with the distribution.
+** * Neither the name of the LibQxt project nor the
+** names of its contributors may be used to endorse or promote products
+** derived from this software without specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+** DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
+** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+**
+**
+*****************************************************************************/
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+static const int Vertical_Mask = 0x02;
+
+class QxtPushButtonPrivate : public QxtPrivate
+{
+public:
+ QXT_DECLARE_PUBLIC(QxtPushButton)
+ QxtPushButtonPrivate();
+
+ bool isRichText() const;
+ QStyleOptionButton getStyleOption() const;
+
+ QString text;
+ Qxt::Rotation rot;
+ Qt::TextFormat format;
+ mutable QTextDocument* doc;
+};
+
+QxtPushButtonPrivate::QxtPushButtonPrivate() :
+ rot(Qxt::NoRotation), format(Qt::PlainText), doc(0)
+{
+}
+
+bool QxtPushButtonPrivate::isRichText() const
+{
+ bool rich = (format == Qt::RichText) || (format == Qt::AutoText && Qt::mightBeRichText(qxt_p().text()));
+ if (rich && !doc)
+ {
+ doc = new QTextDocument(const_cast(&qxt_p()));
+ doc->setUndoRedoEnabled(false);
+ }
+ return rich;
+}
+
+QStyleOptionButton QxtPushButtonPrivate::getStyleOption() const
+{
+ QStyleOptionButton option;
+ option.initFrom(&qxt_p());
+ if (rot & Vertical_Mask)
+ {
+ QSize size = option.rect.size();
+ size.transpose();
+ option.rect.setSize(size);
+ }
+ option.features = QStyleOptionButton::None;
+ if (qxt_p().isFlat())
+ option.features |= QStyleOptionButton::Flat;
+ if (qxt_p().menu())
+ option.features |= QStyleOptionButton::HasMenu;
+ if (qxt_p().autoDefault() || qxt_p().isDefault())
+ option.features |= QStyleOptionButton::AutoDefaultButton;
+ if (qxt_p().isDefault())
+ option.features |= QStyleOptionButton::DefaultButton;
+ if (qxt_p().isDown() || (qxt_p().menu() && qxt_p().menu()->isVisible()))
+ option.state |= QStyle::State_Sunken;
+ if (qxt_p().isChecked())
+ option.state |= QStyle::State_On;
+ if (!qxt_p().isFlat() && !qxt_p().isDown())
+ option.state |= QStyle::State_Raised;
+ if (!isRichText())
+ {
+ option.text = qxt_p().text();
+ option.icon = qxt_p().icon();
+ option.iconSize = qxt_p().iconSize();
+ }
+ return option;
+}
+
+/*!
+ \class QxtPushButton
+ \inmodule QxtWidgets
+ \brief The QxtPushButton widget is an extended QPushButton with rotation and rich text support.
+
+ QxtPushButton is a QPushButton which can be rotated. In addition, QxtPushButton
+ provides rich text support.
+
+ \image qxtpushbutton.png "QxtPushButton in action."
+ */
+
+/*!
+ Constructs a new QxtPushButton with \a parent.
+ */
+QxtPushButton::QxtPushButton(QWidget* parent) : QPushButton(parent)
+{
+ QXT_INIT_PRIVATE(QxtPushButton);
+}
+
+/*!
+ Constructs a new QxtPushButton with \a text and \a parent.
+ */
+QxtPushButton::QxtPushButton(const QString& text, QWidget* parent) : QPushButton(text, parent)
+{
+ QXT_INIT_PRIVATE(QxtPushButton);
+}
+
+/*!
+ Constructs a new QxtPushButton with \a icon, \a text and \a parent.
+
+ \bold {Note:} An icon is not rendered when using rich text.
+ */
+QxtPushButton::QxtPushButton(const QIcon& icon, const QString& text, QWidget* parent) : QPushButton(icon, text, parent)
+{
+ QXT_INIT_PRIVATE(QxtPushButton);
+}
+
+/*!
+ Constructs a new QxtPushButton with \a rotation, \a text and \a parent.
+ */
+QxtPushButton::QxtPushButton(Qxt::Rotation rotation, const QString& text, QWidget* parent) : QPushButton(text, parent)
+{
+ QXT_INIT_PRIVATE(QxtPushButton);
+ setRotation(rotation);
+}
+
+/*!
+ Destructs the button.
+ */
+QxtPushButton::~QxtPushButton()
+{}
+
+/*!
+ \property QxtPushButton::rotation
+ \brief the rotation of the button
+
+ The button is rotated according to this property.
+ The default value is Qxt::NoRotation.
+
+ \sa Qxt::Rotation
+ */
+Qxt::Rotation QxtPushButton::rotation() const
+{
+ return qxt_d().rot;
+}
+
+void QxtPushButton::setRotation(Qxt::Rotation rotation)
+{
+ if (qxt_d().rot != rotation)
+ {
+ qxt_d().rot = rotation;
+ switch (rotation)
+ {
+ case Qxt::NoRotation:
+ case Qxt::UpsideDown:
+ setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
+ break;
+
+ case Qxt::Clockwise:
+ case Qxt::CounterClockwise:
+ setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
+ break;
+
+ default:
+ // nothing to do
+ break;
+ }
+ updateGeometry();
+ update();
+ }
+}
+
+/*!
+ \property QxtPushButton::textFormat
+ \brief the text format of the button
+
+ Supported formats are Qt::PlainText, Qt::RichText and Qt::AutoText.
+
+ The default format is Qt::PlainText.
+
+ \sa Qt::TextFormat
+ */
+Qt::TextFormat QxtPushButton::textFormat() const
+{
+ return qxt_d().format;
+}
+
+void QxtPushButton::setTextFormat(Qt::TextFormat format)
+{
+ if (qxt_d().format != format)
+ {
+ qxt_d().format = format;
+ if (!qxt_d().isRichText())
+ {
+ delete qxt_d().doc;
+ qxt_d().doc = 0;
+ }
+ qxt_d().text.clear();
+ update();
+ updateGeometry();
+ }
+}
+
+/*!
+ \reimp
+ */
+QSize QxtPushButton::sizeHint() const
+{
+ QSize size;
+ if (qxt_d().isRichText())
+ size = qxt_d().doc->documentLayout()->documentSize().toSize();
+ else
+ size = QPushButton::sizeHint();
+
+ if (qxt_d().rot & Vertical_Mask)
+ size.transpose();
+ return size;
+}
+
+/*!
+ \reimp
+ */
+QSize QxtPushButton::minimumSizeHint() const
+{
+ return sizeHint();
+}
+
+/*!
+ \reimp
+ */
+void QxtPushButton::paintEvent(QPaintEvent* event)
+{
+ Q_UNUSED(event);
+
+ // the only reliable way to detect text changes
+ if (text() != qxt_d().text)
+ {
+ qxt_d().text = text();
+ if (qxt_d().isRichText())
+ qxt_d().doc->setHtml(qxt_d().text);
+ updateGeometry();
+ }
+
+ QStylePainter painter(this);
+ painter.rotate(qxt_d().rot);
+ switch (qxt_d().rot)
+ {
+ case Qxt::UpsideDown:
+ painter.translate(-width(), -height());
+ break;
+
+ case Qxt::Clockwise:
+ painter.translate(0, -width());
+ break;
+
+ case Qxt::CounterClockwise:
+ painter.translate(-height(), 0);
+ break;
+
+ default:
+ // nothing to do
+ break;
+ }
+
+ const QStyleOptionButton option = qxt_d().getStyleOption();
+ painter.drawControl(QStyle::CE_PushButton, option);
+
+ if (qxt_d().isRichText())
+ {
+ int dx = 0;
+ int dy = 0;
+ if (option.state & (QStyle::State_On | QStyle::State_Sunken))
+ {
+ dx += style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option, this);
+ dy += style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option, this);
+ }
+
+ QRect area = rect();
+ const QSizeF docSize = qxt_d().doc->documentLayout()->documentSize();
+ if (qxt_d().rot & Vertical_Mask)
+ {
+ dx += static_cast((height() - docSize.width()) / 2);
+ dy += static_cast((width() - docSize.height()) / 2);
+ painter.translate(dx, dy);
+
+ QSize size = area.size();
+ size.transpose();
+ area.setSize(size);
+ }
+ else
+ {
+ dx += static_cast((width() - docSize.width()) / 2);
+ dy += static_cast((height() - docSize.height()) / 2);
+ painter.translate(dx, dy);
+ }
+ qxt_d().doc->drawContents(&painter, area);
+ }
+}
diff --git a/pool/shard002/C++/0034619_http_client.cpp b/pool/shard002/C++/0034619_http_client.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..79af43b58578fadd06d6c2b3575094fe106a6dfe
--- /dev/null
+++ b/pool/shard002/C++/0034619_http_client.cpp
@@ -0,0 +1,216 @@
+#include "platform/http_client.hpp"
+
+#include "coding/base64.hpp"
+
+#include "base/string_utils.hpp"
+
+#include
+
+using namespace std;
+
+namespace platform
+{
+HttpClient::HttpClient(string const & url) : m_urlRequested(url)
+{
+// Http client for linux supports only "deflate" encoding, but osrm server cannot
+// correctly process "Accept-Encoding: deflate" header, so do not encode data on linux.
+#if !defined(OMIM_OS_LINUX)
+ m_headers.emplace("Accept-Encoding", "gzip, deflate");
+#endif
+}
+
+bool HttpClient::RunHttpRequest(string & response, SuccessChecker checker /* = nullptr */)
+{
+ static auto const simpleChecker = [](HttpClient const & request)
+ {
+ return request.ErrorCode() == 200;
+ };
+
+ if (checker == nullptr)
+ checker = simpleChecker;
+
+ if (RunHttpRequest() && checker(*this))
+ {
+ response = ServerResponse();
+ return true;
+ }
+
+ return false;
+}
+
+HttpClient & HttpClient::SetUrlRequested(string const & url)
+{
+ m_urlRequested = url;
+ return *this;
+}
+
+HttpClient & HttpClient::SetHttpMethod(string const & method)
+{
+ m_httpMethod = method;
+ return *this;
+}
+
+HttpClient & HttpClient::SetBodyFile(string const & body_file, string const & content_type,
+ string const & http_method /* = "POST" */,
+ string const & content_encoding /* = "" */)
+{
+ m_inputFile = body_file;
+ m_bodyData.clear();
+ m_headers.emplace("Content-Type", content_type);
+ m_httpMethod = http_method;
+ m_headers.emplace("Content-Encoding", content_encoding);
+ return *this;
+}
+
+HttpClient & HttpClient::SetReceivedFile(string const & received_file)
+{
+ m_outputFile = received_file;
+ return *this;
+}
+
+HttpClient & HttpClient::SetUserAndPassword(string const & user, string const & password)
+{
+ m_headers.emplace("Authorization", "Basic " + base64::Encode(user + ":" + password));
+ return *this;
+}
+
+HttpClient & HttpClient::SetCookies(string const & cookies)
+{
+ m_cookies = cookies;
+ return *this;
+}
+
+HttpClient & HttpClient::SetHandleRedirects(bool handle_redirects)
+{
+ m_handleRedirects = handle_redirects;
+ return *this;
+}
+
+HttpClient & HttpClient::SetRawHeader(string const & key, string const & value)
+{
+ m_headers.emplace(key, value);
+ return *this;
+}
+
+HttpClient & HttpClient::SetRawHeaders(Headers const & headers)
+{
+ m_headers.insert(headers.begin(), headers.end());
+ return *this;
+}
+
+void HttpClient::SetTimeout(double timeoutSec)
+{
+ m_timeoutSec = timeoutSec;
+}
+
+string const & HttpClient::UrlRequested() const
+{
+ return m_urlRequested;
+}
+
+string const & HttpClient::UrlReceived() const
+{
+ return m_urlReceived;
+}
+
+bool HttpClient::WasRedirected() const
+{
+ return m_urlRequested != m_urlReceived;
+}
+
+int HttpClient::ErrorCode() const
+{
+ return m_errorCode;
+}
+
+string const & HttpClient::ServerResponse() const
+{
+ return m_serverResponse;
+}
+
+string const & HttpClient::HttpMethod() const
+{
+ return m_httpMethod;
+}
+
+string HttpClient::CombinedCookies() const
+{
+ string serverCookies;
+ auto const it = m_headers.find("Set-Cookie");
+ if (it != m_headers.end())
+ serverCookies = it->second;
+
+ if (serverCookies.empty())
+ return m_cookies;
+
+ if (m_cookies.empty())
+ return serverCookies;
+
+ return serverCookies + "; " + m_cookies;
+}
+
+string HttpClient::CookieByName(string name) const
+{
+ string const str = CombinedCookies();
+ name += "=";
+ auto const cookie = str.find(name);
+ auto const eq = cookie + name.size();
+ if (cookie != string::npos && str.size() > eq)
+ return str.substr(eq, str.find(';', eq) - eq);
+
+ return {};
+}
+
+void HttpClient::LoadHeaders(bool loadHeaders)
+{
+ m_loadHeaders = loadHeaders;
+}
+
+HttpClient::Headers const & HttpClient::GetHeaders() const
+{
+ return m_headers;
+}
+
+// static
+string HttpClient::NormalizeServerCookies(string && cookies)
+{
+ istringstream is(cookies);
+ string str, result;
+
+ // Split by ", ". Can have invalid tokens here, expires= can also contain a comma.
+ while (getline(is, str, ','))
+ {
+ size_t const leading = str.find_first_not_of(" ");
+ if (leading != string::npos)
+ str.substr(leading).swap(str);
+
+ // In the good case, we have '=' and it goes before any ' '.
+ auto const eq = str.find('=');
+ if (eq == string::npos)
+ continue; // It's not a cookie: no valid key value pair.
+
+ auto const sp = str.find(' ');
+ if (sp != string::npos && eq > sp)
+ continue; // It's not a cookie: comma in expires date.
+
+ // Insert delimiter.
+ if (!result.empty())
+ result.append("; ");
+
+ // Read cookie itself.
+ result.append(str, 0, str.find(";"));
+ }
+ return result;
+}
+
+string DebugPrint(HttpClient const & request)
+{
+ ostringstream ostr;
+ ostr << "HTTP " << request.ErrorCode() << " url [" << request.UrlRequested() << "]";
+ if (request.WasRedirected())
+ ostr << " was redirected to [" << request.UrlReceived() << "]";
+ if (!request.ServerResponse().empty())
+ ostr << " response: " << request.ServerResponse();
+ return ostr.str();
+}
+} // namespace platform
diff --git a/pool/shard002/C++/0034623_PGLoader.cpp b/pool/shard002/C++/0034623_PGLoader.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b3ef8d2be2cd94e042e81a922275c7c3ca0b8037
--- /dev/null
+++ b/pool/shard002/C++/0034623_PGLoader.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2011-2021 FlylinkDC++ Team http://flylinkdc.com
+ *
+ * This program 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+#include "stdinc.h"
+
+#include "PGLoader.h"
+#include "ResourceManager.h"
+#include "File.h"
+#include "IpGuard.h"
+#include "SettingsManager.h"
+#include "../windows/resource.h"
+
+#ifdef FLYLINKDC_USE_IPFILTER
+
+FastCriticalSection PGLoader::g_cs;
+IPList PGLoader::g_ipTrustListAllow;
+IPList PGLoader::g_ipTrustListBlock;
+
+void PGLoader::load(const string& p_data /*= BaseUtil::emptyString*/)
+{
+ string l_data;
+ const string l_url = SETTING(URL_IPTRUST);
+ bool l_is_download = false;
+ CFlyLog l_IPTrust_log("[IPTrust]");
+ if (p_data.empty())
+ {
+ if (!l_url.empty())
+ {
+ try
+ {
+ const string l_log_message = STRING(DOWNLOAD) + ": " + l_url;
+ if (Util::getDataFromInet(true, l_url, l_data, 0) == 0)
+ {
+ l_IPTrust_log.step(l_log_message + " [" + STRING(ERROR_STRING) + ']');
+ }
+ else
+ {
+ l_IPTrust_log.step(l_log_message + " [OK]");
+ // "ðàñïàðñèì" îòâåò (TODO - ïåðåéòè íà regexp)
+ {
+ string::size_type linestart = 0;
+ string::size_type lineend = 0;
+ for (;;)
+ {
+ lineend = l_data.find('\n', linestart);
+ if (lineend == string::npos)
+ break;
+ const string line = l_data.substr(linestart, lineend - linestart - 1);
+ int u1, u2, u3, u4, u5, u6, u7, u8;
+ int iItems = sscanf_s(line.c_str(), "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8);
+ if (iItems == 8 || iItems == 4)
+ {
+ l_is_download = true;
+ break;
+ }
+ iItems = sscanf_s(line.c_str(), "#%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8);
+ if (iItems == 8 || iItems == 4)
+ {
+ l_is_download = true;
+ break;
+ }
+ linestart = lineend + 1;
+ }
+ }
+ if (l_is_download)
+ {
+ const auto l_IPTrust_ini = getConfigFileName();
+ File(l_IPTrust_ini, File::WRITE, File::CREATE | File::TRUNCATE).write(l_data);
+ l_IPTrust_log.step(l_IPTrust_ini + " [" + STRING(SAVE) + ']');
+ }
+ }
+ }
+ catch (const FileException& e)
+ {
+ l_IPTrust_log.step("Can't write IPTrust.ini file: " + e.getError());
+ dcdebug("IPTrust::save: %s\n", e.getError().c_str());
+ }
+ }
+ if (l_data.empty())
+ {
+ const string l_IPTrust_ini = getConfigFileName();
+ if (File::isExist(l_IPTrust_ini))
+ {
+ try
+ {
+ l_data = File(l_IPTrust_ini, File::READ, File::OPEN).read();
+ }
+ catch (const FileException& e)
+ {
+ l_IPTrust_log.step("Can't read IPTrust.ini file: " + e.getError());
+ dcdebug("IPTrust::load: %s\n", e.getError().c_str());
+ }
+ }
+ else
+ {
+ Util::WriteTextResourceToFile(IDR_IPTRUST_EXAMPLE, Text::toT(l_IPTrust_ini));
+ l_IPTrust_log.step("IPTrust.ini restored from internal resources");
+ }
+ }
+ }
+ else
+ {
+ l_data = p_data;
+ }
+
+ CFlyFastLock(g_cs);
+ l_IPTrust_log.step("parse IPTrust.ini");
+ g_ipTrustListAllow.clear();
+ g_ipTrustListBlock.clear();
+
+ if (!l_data.empty())
+ {
+ string::size_type linestart = 0;
+ string::size_type lineend = 0;
+ for (;;)
+ {
+ lineend = l_data.find('\n', linestart);
+ if (lineend == string::npos)
+ {
+ string l_line = l_data.substr(linestart);
+ addLine(l_line, l_IPTrust_log);
+ break;
+ }
+ else
+ {
+ string l_line = l_data.substr(linestart, lineend - linestart - 1);
+ addLine(l_line, l_IPTrust_log);
+ linestart = lineend + 1;
+ }
+ }
+ }
+ l_IPTrust_log.step("parse IPTrust.ini done");
+}
+
+bool PGLoader::check(uint32_t p_ip4)
+{
+ if (BOOLSETTING(ENABLE_IPTRUST))
+ {
+ CFlyFastLock(g_cs);
+ if (!g_ipTrustListBlock.empty())
+ {
+ if (g_ipTrustListBlock.checkIp(p_ip4))
+ {
+ return true;
+ }
+ }
+ if (!g_ipTrustListAllow.empty())
+ {
+ const auto l_ipguard = g_ipTrustListAllow.checkIp(p_ip4);
+ return !l_ipguard;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ return false;
+ }
+}
+
+void PGLoader::addLine(string& p_Line, CFlyLog& p_log)
+{
+ Text::replace_all(p_Line, " ", "");
+ if (p_Line.empty())
+ return;
+
+ if (p_Line[0] == '#')
+ return;
+
+ if (p_Line[0] == '-')
+ {
+ p_Line.erase(0, 1);
+ g_ipTrustListBlock.addLine(p_Line, p_log);
+ }
+ else
+ {
+ g_ipTrustListAllow.addLine(p_Line, p_log);
+ }
+}
+
+#endif // FLYLINKDC_USE_IPFILTER
diff --git a/pool/shard002/C++/0034625_boss_cyanigosa.cpp b/pool/shard002/C++/0034625_boss_cyanigosa.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a3f2691145ef022c13633c9eb51497f66e863190
--- /dev/null
+++ b/pool/shard002/C++/0034625_boss_cyanigosa.cpp
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2008-2011 WCloudCore
+ *
+ * This program 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 2 of the License, or (at your
+ * option) any later version.
+ *
+ * This program 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 this program. If not, see .
+ */
+
+#include "ScriptPCH.h"
+#include "violet_hold.h"
+
+enum Spells
+{
+ SPELL_ARCANE_VACUUM = 58694,
+ SPELL_BLIZZARD = 58693,
+ H_SPELL_BLIZZARD = 59369,
+ SPELL_MANA_DESTRUCTION = 59374,
+ SPELL_TAIL_SWEEP = 58690,
+ H_SPELL_TAIL_SWEEP = 59283,
+ SPELL_UNCONTROLLABLE_ENERGY = 58688,
+ H_SPELL_UNCONTROLLABLE_ENERGY = 59281,
+ SPELL_TRANSFORM = 58668
+};
+
+enum Yells
+{
+ SAY_AGGRO = -1608000,
+ SAY_SLAY_1 = -1608001,
+ SAY_SLAY_2 = -1608002,
+ SAY_SLAY_3 = -1608003,
+ SAY_DEATH = -1608004,
+ SAY_SPAWN = -1608005,
+ SAY_DISRUPTION = -1608006,
+ SAY_BREATH_ATTACK = -1608007,
+ SAY_SPECIAL_ATTACK_1 = -1608008,
+ SAY_SPECIAL_ATTACK_2 = -1608009
+};
+
+class boss_cyanigosa : public CreatureScript
+{
+public:
+ boss_cyanigosa() : CreatureScript("boss_cyanigosa") { }
+
+ CreatureAI* GetAI(Creature* creature) const
+ {
+ return new boss_cyanigosaAI (creature);
+ }
+
+ struct boss_cyanigosaAI : public ScriptedAI
+ {
+ boss_cyanigosaAI(Creature* c) : ScriptedAI(c)
+ {
+ instance = c->GetInstanceScript();
+ }
+
+ uint32 uiArcaneVacuumTimer;
+ uint32 uiBlizzardTimer;
+ uint32 uiManaDestructionTimer;
+ uint32 uiTailSweepTimer;
+ uint32 uiUncontrollableEnergyTimer;
+
+ InstanceScript* instance;
+
+ void Reset()
+ {
+ uiArcaneVacuumTimer = 10000;
+ uiBlizzardTimer = 15000;
+ uiManaDestructionTimer = 30000;
+ uiTailSweepTimer = 20000;
+ uiUncontrollableEnergyTimer = 25000;
+ if (instance)
+ instance->SetData(DATA_CYANIGOSA_EVENT, NOT_STARTED);
+ }
+
+ void EnterCombat(Unit* /*who*/)
+ {
+ DoScriptText(SAY_AGGRO, me);
+
+ if (instance)
+ instance->SetData(DATA_CYANIGOSA_EVENT, IN_PROGRESS);
+ }
+
+ void MoveInLineOfSight(Unit* /*who*/) {}
+
+ void UpdateAI(const uint32 diff)
+ {
+ if (instance && instance->GetData(DATA_REMOVE_NPC) == 1)
+ {
+ me->DespawnOrUnsummon();
+ instance->SetData(DATA_REMOVE_NPC, 0);
+ }
+
+ //Return since we have no target
+ if (!UpdateVictim())
+ return;
+
+ if (uiArcaneVacuumTimer <= diff)
+ {
+ DoCast(SPELL_ARCANE_VACUUM);
+ uiArcaneVacuumTimer = 10000;
+ } else uiArcaneVacuumTimer -= diff;
+
+ if (uiBlizzardTimer <= diff)
+ {
+ if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
+ DoCast(target, SPELL_BLIZZARD);
+ uiBlizzardTimer = 15000;
+ } else uiBlizzardTimer -= diff;
+
+ if (uiTailSweepTimer <= diff)
+ {
+ DoCast(SPELL_TAIL_SWEEP);
+ uiTailSweepTimer = 20000;
+ } else uiTailSweepTimer -= diff;
+
+ if (uiUncontrollableEnergyTimer <= diff)
+ {
+ DoCastVictim(SPELL_UNCONTROLLABLE_ENERGY);
+ uiUncontrollableEnergyTimer = 25000;
+ } else uiUncontrollableEnergyTimer -= diff;
+
+ if (IsHeroic())
+ {
+ if (uiManaDestructionTimer <= diff)
+ {
+ if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
+ DoCast(target, SPELL_MANA_DESTRUCTION);
+ uiManaDestructionTimer = 30000;
+ } else uiManaDestructionTimer -= diff;
+ }
+
+ DoMeleeAttackIfReady();
+ }
+
+ void JustDied(Unit* /*killer*/)
+ {
+ DoScriptText(SAY_DEATH, me);
+
+ if (instance)
+ instance->SetData(DATA_CYANIGOSA_EVENT, DONE);
+ }
+
+ void KilledUnit(Unit* victim)
+ {
+ if (victim == me)
+ return;
+ DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me);
+ }
+ };
+};
+
+class achievement_defenseless : public AchievementCriteriaScript
+{
+ public:
+ achievement_defenseless() : AchievementCriteriaScript("achievement_defenseless")
+ {
+ }
+
+ bool OnCheck(Player* /*player*/, Unit* target)
+ {
+ if(!target)
+ return false;
+
+ InstanceScript* instance = target->GetInstanceScript();
+ if (!instance)
+ return false;
+
+ if (!instance->GetData(DATA_DEFENSELESS))
+ return false;
+
+ return true;
+ }
+};
+
+void AddSC_boss_cyanigosa()
+{
+ new boss_cyanigosa();
+ new achievement_defenseless();
+}
\ No newline at end of file
diff --git a/pool/shard002/C++/0034631_encoder_containers.cpp b/pool/shard002/C++/0034631_encoder_containers.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a5ca3c43dd625a7c41dc36526db6a4fa11e51ee0
--- /dev/null
+++ b/pool/shard002/C++/0034631_encoder_containers.cpp
@@ -0,0 +1,84 @@
+/*-----------------------------------------------------------------------------
+cboreli - CBOR library
+
+encoder_containers.cpp
+
+The MIT License (MIT)
+
+Copyright (c) 2016 Elisha Kendagor kendagor@live.com
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+-----------------------------------------------------------------------------*/
+
+#include "encoder.h"
+#include "random_number.h"
+
+using namespace std;
+using namespace cboreli;
+
+codec_res_ptr encoder::add_byte_array(const_str key, vector& value,
+ item_ptr container){
+ item_ptr p = make_shared();
+ p->value_type = t_byte_string;
+ new(&(p->p_byte_string)) arr_uint8_ptr();
+ p->p_byte_string = make_shared(value);
+ return make_result(codec_result::status::ok, codec_result::res_comment_ok,
+ key, p, container);
+}
+
+codec_res_ptr encoder::add_byte_array(const_str key, arr_uint8& value,
+ item_ptr container){
+ item_ptr p = make_shared();
+ p->value_type = t_byte_string;
+ new(&(p->p_byte_string)) arr_uint8_ptr();
+ p->p_byte_string = make_shared(value);
+ return make_result(codec_result::status::ok, codec_result::res_comment_ok,
+ key, p, container);
+}
+
+codec_res_ptr encoder::add_byte_array(const_str key, arr_uint8&& value,
+ item_ptr container){
+ item_ptr p = make_shared();
+ p->value_type = t_byte_string;
+ new(&(p->p_byte_string)) arr_uint8_ptr();
+ p->p_byte_string = make_shared(value);
+ return make_result(codec_result::status::ok, codec_result::res_comment_ok,
+ key, p, container);
+}
+
+codec_res_ptr encoder::add_items_array(const_str key, vector_items& value,
+ item_ptr container){
+ item_ptr p = make_shared();
+ p->value_type = t_array;
+ new(&(p->p_array_items)) vector_items_ptr();
+ p->p_array_items = make_shared(value);
+ return make_result(codec_result::status::ok, codec_result::res_comment_ok,
+ key, p, container);
+}
+
+codec_res_ptr encoder::add_items_map(const_str key, map_items& value,
+ item_ptr container){
+ item_ptr p = make_shared();
+ p->value_type = t_map;
+ new(&(p->p_map_items)) map_items_ptr();
+ p->p_map_items = make_shared(value);
+ return make_result(codec_result::status::ok, codec_result::res_comment_ok,
+ key, p, container);
+}
+
diff --git a/pool/shard002/C++/0034634_AppDefaultIconElement.cpp b/pool/shard002/C++/0034634_AppDefaultIconElement.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e814af56b602499da468417fcb24cc064d17b034
--- /dev/null
+++ b/pool/shard002/C++/0034634_AppDefaultIconElement.cpp
@@ -0,0 +1,93 @@
+/* UOL Messenger
+ * Copyright (c) 2005 Universo Online S/A
+ *
+ * Direitos Autorais Reservados
+ * All rights reserved
+ *
+ * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo
+ * sob os termos da Licença Pública Geral GNU conforme publicada pela Free
+ * Software Foundation; tanto a versão 2 da Licença, como (a seu critério)
+ * qualquer versão posterior.
+ * Este programa é distribuído na expectativa de que seja útil, porém,
+ * SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE
+ * OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral
+ * do GNU para mais detalhes.
+ * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto
+ * com este programa; se não, escreva para a Free Software Foundation, Inc.,
+ * no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
+ *
+ * This program 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 2
+ * of the License, or (at your option) any later version.
+ * This program 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 this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Universo Online S/A - A/C: UOL Messenger 5o. Andar
+ * Avenida Brigadeiro Faria Lima, 1.384 - Jardim Paulistano
+ * São Paulo SP - CEP 01452-002 - BRASIL */
+
+
+#include "stdafx.h"
+#include "AppDefaultIconElement.h"
+
+
+CAppDefaultIconElement::CAppDefaultIconElement()
+{
+}
+
+
+CAppDefaultIconElement::~CAppDefaultIconElement()
+{
+}
+
+
+CString CAppDefaultIconElement::GetName() const
+{
+ return _T("__AppDefaultIconInstance");
+}
+
+
+void CAppDefaultIconElement::SetParameters(CString2StringMapPtr& pMapParams, IElementTable* pElementTable)
+{
+ try
+ {
+ CString strIconSmall;
+ GetParameterValue(strIconSmall, pMapParams, "smallicon");
+
+ m_pIconSmall = ap_dynamic_cast(pElementTable->GetElement(strIconSmall));
+ }
+ catch (const CSkinException&)
+ {
+ m_pIconSmall = CIconElementPtr();
+ }
+
+ try
+ {
+ CString strIconLarge;
+ GetParameterValue(strIconLarge, pMapParams, "largeicon");
+
+ m_pIconLarge = ap_dynamic_cast(pElementTable->GetElement(strIconLarge));
+ }
+ catch (const CSkinException&)
+ {
+ m_pIconLarge = CIconElementPtr();
+ }
+}
+
+
+CIconElementPtr CAppDefaultIconElement::GetSmallIcon() const
+{
+ return m_pIconSmall;
+}
+
+
+CIconElementPtr CAppDefaultIconElement::GetLargeIcon() const
+{
+ return m_pIconLarge;
+}
\ No newline at end of file
diff --git a/pool/shard002/C++/0034638_standalone_example_docs1.cpp b/pool/shard002/C++/0034638_standalone_example_docs1.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..7f88f9883dea0703d86746f887e0a2741fd0d2ed
--- /dev/null
+++ b/pool/shard002/C++/0034638_standalone_example_docs1.cpp
@@ -0,0 +1,87 @@
+/*
+Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+
+The MySQL Connector/C++ is licensed under the terms of the GPLv2
+, like most
+MySQL Connectors. There are special exceptions to the terms and
+conditions of the GPLv2 as it is applied to this software, see the
+FLOSS License Exception
+.
+
+This program 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; version 2 of the License.
+
+This program 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 this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+
+
+/* Standard C++ includes */
+#include
+#include
+
+/*
+ Include directly the different
+ headers from cppconn/ and mysql_driver.h + mysql_util.h
+ (and mysql_connection.h). This will reduce your build time!
+*/
+#include "mysql_connection.h"
+
+#include
+#include
+#include
+#include
+
+using namespace std;
+
+int main(void)
+{
+cout << endl;
+cout << "Running 'SELECT 'Hello World!' AS _message'..." << endl;
+
+try {
+ sql::Driver *driver;
+ sql::Connection *con;
+ sql::Statement *stmt;
+ sql::ResultSet *res;
+
+ /* Create a connection */
+ driver = sql::mysql::get_driver_instance();
+ con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
+ /* Connect to the MySQL test database */
+ con->setSchema("test");
+
+ stmt = con->createStatement();
+ res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
+ while (res->next()) {
+ cout << "\t... MySQL replies: ";
+ /* Access column data by alias or column name */
+ cout << res->getString("_message") << endl;
+ cout << "\t... MySQL says it again: ";
+ /* Access column fata by numeric offset, 1 is the first column */
+ cout << res->getString(1) << endl;
+ }
+ delete res;
+ delete stmt;
+ delete con;
+
+} catch (sql::SQLException &e) {
+ cout << "# ERR: SQLException in " << __FILE__;
+ cout << "(" << EXAMPLE_FUNCTION << ") on line " << __LINE__ << endl;
+ cout << "# ERR: " << e.what();
+ cout << " (MySQL error code: " << e.getErrorCode();
+ cout << ", SQLState: " << e.getSQLState() << " )" << endl;
+}
+
+cout << endl;
+
+return EXIT_SUCCESS;
+}
diff --git a/pool/shard002/C++/0034641_main.cc b/pool/shard002/C++/0034641_main.cc
new file mode 100644
index 0000000000000000000000000000000000000000..0f99a501fe4cb3dd5984ccfe9596dabad16815ec
--- /dev/null
+++ b/pool/shard002/C++/0034641_main.cc
@@ -0,0 +1,83 @@
+#include
+#include
+#include
+
+#include "find.h"
+#include "parse.h"
+#include "argpc.h"
+#include "build.h"
+#include "plotter.h"
+#include "debug.h"
+#include "dependencies.h"
+#include "argpcoption.h"
+
+using namespace std;
+
+bool makefile_specified = false;
+string plotfile = "";
+std::string makefile;
+extern std::string depfile;
+
+void set_makefile( std::string file )
+{
+ makefile_specified = true;
+ makefile = file;
+}
+
+void set_depfile( std::string file )
+{
+ depfile = file;
+}
+
+void plot( std::string file )
+{
+ plotfile = file;
+}
+
+int main(int argc, char *argv[])
+{
+ Plotter p;
+ int ret;
+
+ try {
+ Argpc *options = Argpc::getInstance( );
+
+ // Set up the standard argument options
+ options->addHelp( );
+ options->addUsage( );
+ options->addVersion( );
+ options->setVersion( "0.1" );
+ options->setBugAddress( "Aaron Small " );
+ options->setDoc( "Yet another make clone" );
+ options->setArgumentDescription( "..." );
+ options->addOption( ArgpcOption( "file", 'f', "file", "Read FILE as a makefile.", set_makefile ) );
+ options->addOption( ArgpcOption( "depfile", 'b', "depfile", "Use specified file as dependency database.", set_depfile ) );
+ options->addOption( ArgpcOption( "plot", 'p', "graphfile", "Draw the cached dependency information", plot ) );
+
+ debug_init( );
+
+ options->parse( &argc, argv );
+
+ dependencies_init();
+
+ if( !makefile_specified ) {
+ makefile = find_makefile( );
+ }
+ parse_makefile( makefile );
+ for( int i = 1; i < argc; i ++ ) {
+ set_target( argv[i] );
+ }
+ set_default_target();
+ if( plotfile != "" ) {
+ p.open( plotfile );
+ set_plotter( &p );
+ }
+ ret = build_targets();
+ } catch ( const std::exception &e ) {
+ cerr << "make: " << e.what() << endl;
+ dependencies_deinit();
+ return 1;
+ }
+ dependencies_deinit();
+ return ret;
+}
diff --git a/pool/shard002/C++/0034642_ColourUtils.cpp b/pool/shard002/C++/0034642_ColourUtils.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a1bb6fa9563ee3ffff15897308d93ca1592b545d
--- /dev/null
+++ b/pool/shard002/C++/0034642_ColourUtils.cpp
@@ -0,0 +1,76 @@
+//
+// ColourUtils.cpp
+// Chilli Source
+// Created by Scott Downie on 03/04/2014.
+//
+// The MIT License (MIT)
+//
+// Copyright (c) 2014 Tag Games Limited
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#include
+
+#include
+
+namespace ChilliSource
+{
+ namespace Core
+ {
+ namespace ColourUtils
+ {
+ //-----------------------------------------------------------
+ //-----------------------------------------------------------
+ ByteColour ColourToByteColour(const Colour& in_colour)
+ {
+ return ColourToByteColour(in_colour.r, in_colour.g, in_colour.b, in_colour.a);
+ }
+ //-----------------------------------------------------------
+ //-----------------------------------------------------------
+ ByteColour ColourToByteColour(f32 in_red, f32 in_green, f32 in_blue, f32 in_alpha)
+ {
+ CS_ASSERT(in_red >= 0.0f && in_red <= 1.0f, "Colour must be in range 0.0 - 1.0");
+ CS_ASSERT(in_green >= 0.0f && in_green <= 1.0f, "Colour must be in range 0.0 - 1.0");
+ CS_ASSERT(in_blue >= 0.0f && in_blue <= 1.0f, "Colour must be in range 0.0 - 1.0");
+ CS_ASSERT(in_alpha >= 0.0f && in_alpha <= 1.0f, "Colour must be in range 0.0 - 1.0");
+
+ ByteColour result;
+
+ result.r = (u8)MathUtils::Round(in_red * 255.0f);
+ result.g = (u8)MathUtils::Round(in_green * 255.0f);
+ result.b = (u8)MathUtils::Round(in_blue * 255.0f);
+ result.a = (u8)MathUtils::Round(in_alpha * 255.0f);
+
+ return result;
+ }
+ //-----------------------------------------------------------
+ //-----------------------------------------------------------
+ Colour PackedRGBAToColour(u32 in_rgba)
+ {
+ u8 byteR = (in_rgba >> 24) & 255;
+ u8 byteG = (in_rgba >> 16) & 255;
+ u8 byteB = (in_rgba >> 8) & 255;
+ u8 byteA = (in_rgba) & 255;
+
+ return Colour((f32)byteR/255.0f, (f32)byteG/255.0f, (f32)byteB/255.0f, (f32)byteA/255.0f);
+ }
+ }
+ }
+}
diff --git a/pool/shard002/C++/0034643_BigNumber.cpp b/pool/shard002/C++/0034643_BigNumber.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..5292f1364b4847176c692f14cb4ab30da8ff2c01
--- /dev/null
+++ b/pool/shard002/C++/0034643_BigNumber.cpp
@@ -0,0 +1,206 @@
+/*
+ *
+ * Copyright (C) 2011-2013 ArkCORE
+ *
+ * Copyright (C) 2008-2013 TrinityCore
+ *
+ * Copyright (C) 2005-2009 MaNGOS
+ *
+ * This program 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 2 of the License, or (at your
+ * option) any later version.
+ *
+ * This program 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 this program. If not, see .
+ */
+
+#include
+
+#include "Cryptography/BigNumber.h"
+#include
+#include
+#include
+
+BigNumber::BigNumber()
+ : _bn(BN_new()), _array(NULL)
+{ }
+
+BigNumber::BigNumber(BigNumber const& bn)
+ : _bn(BN_dup(bn._bn)), _array(NULL)
+{ }
+
+BigNumber::BigNumber(uint32 val)
+ : _bn(BN_new()), _array(NULL)
+{
+ BN_set_word(_bn, val);
+}
+
+BigNumber::~BigNumber()
+{
+ BN_free(_bn);
+ delete[] _array;
+}
+
+void BigNumber::SetDword(uint32 val)
+{
+ BN_set_word(_bn, val);
+}
+
+void BigNumber::SetQword(uint64 val)
+{
+ BN_add_word(_bn, (uint32)(val >> 32));
+ BN_lshift(_bn, _bn, 32);
+ BN_add_word(_bn, (uint32)(val & 0xFFFFFFFF));
+}
+
+void BigNumber::SetBinary(uint8 const* bytes, int32 len)
+{
+ uint8 t[1000];
+ for (int i = 0; i < len; i++) t[i] = bytes[len - 1 - i];
+ BN_bin2bn(t, len, _bn);
+}
+
+void BigNumber::SetHexStr(char const* str)
+{
+ BN_hex2bn(&_bn, str);
+}
+
+void BigNumber::SetRand(int32 numbits)
+{
+ BN_rand(_bn, numbits, 0, 1);
+}
+
+BigNumber& BigNumber::operator=(BigNumber const& bn)
+{
+ if (this == &bn)
+ return *this;
+
+ BN_copy(_bn, bn._bn);
+ return *this;
+}
+
+BigNumber BigNumber::operator+=(BigNumber const& bn)
+{
+ BN_add(_bn, _bn, bn._bn);
+ return *this;
+}
+
+BigNumber BigNumber::operator-=(BigNumber const& bn)
+{
+ BN_sub(_bn, _bn, bn._bn);
+ return *this;
+}
+
+BigNumber BigNumber::operator*=(BigNumber const& bn)
+{
+ BN_CTX *bnctx;
+
+ bnctx = BN_CTX_new();
+ BN_mul(_bn, _bn, bn._bn, bnctx);
+ BN_CTX_free(bnctx);
+
+ return *this;
+}
+
+BigNumber BigNumber::operator/=(BigNumber const& bn)
+{
+ BN_CTX *bnctx;
+
+ bnctx = BN_CTX_new();
+ BN_div(_bn, NULL, _bn, bn._bn, bnctx);
+ BN_CTX_free(bnctx);
+
+ return *this;
+}
+
+BigNumber BigNumber::operator%=(BigNumber const& bn)
+{
+ BN_CTX *bnctx;
+
+ bnctx = BN_CTX_new();
+ BN_mod(_bn, _bn, bn._bn, bnctx);
+ BN_CTX_free(bnctx);
+
+ return *this;
+}
+
+BigNumber BigNumber::Exp(BigNumber const& bn)
+{
+ BigNumber ret;
+ BN_CTX *bnctx;
+
+ bnctx = BN_CTX_new();
+ BN_exp(ret._bn, _bn, bn._bn, bnctx);
+ BN_CTX_free(bnctx);
+
+ return ret;
+}
+
+BigNumber BigNumber::ModExp(BigNumber const& bn1, BigNumber const& bn2)
+{
+ BigNumber ret;
+ BN_CTX *bnctx;
+
+ bnctx = BN_CTX_new();
+ BN_mod_exp(ret._bn, _bn, bn1._bn, bn2._bn, bnctx);
+ BN_CTX_free(bnctx);
+
+ return ret;
+}
+
+int32 BigNumber::GetNumBytes(void)
+{
+ return BN_num_bytes(_bn);
+}
+
+uint32 BigNumber::AsDword()
+{
+ return (uint32)BN_get_word(_bn);
+}
+
+bool BigNumber::isZero() const
+{
+ return BN_is_zero(_bn);
+}
+
+uint8* BigNumber::AsByteArray(int32 minSize, bool reverse)
+{
+ int length = (minSize >= GetNumBytes()) ? minSize : GetNumBytes();
+
+ ACE_GUARD_RETURN(ACE_Mutex, g, _lock, 0);
+
+ if (_array)
+ {
+ delete[] _array;
+ _array = NULL;
+ }
+ _array = new uint8[length];
+
+ // If we need more bytes than length of BigNumber set the rest to 0
+ if (length > GetNumBytes())
+ memset((void*)_array, 0, length);
+
+ BN_bn2bin(_bn, (unsigned char *)_array);
+
+ if (reverse)
+ std::reverse(_array, _array + length);
+
+ return _array;
+}
+
+char * BigNumber::AsHexStr() const
+{
+ return BN_bn2hex(_bn);
+}
+
+char * BigNumber::AsDecStr() const
+{
+ return BN_bn2dec(_bn);
+}
+
diff --git a/pool/shard002/C++/0034649_Process_test.cpp b/pool/shard002/C++/0034649_Process_test.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..f351fbc1089316393067c8924ab882a14fac0aee
--- /dev/null
+++ b/pool/shard002/C++/0034649_Process_test.cpp
@@ -0,0 +1,141 @@
+
+/*
+ * Copyright (C) 2017 Anoop Chandran
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ * or see
+*/
+
+#include"Process_test.h"
+
+Process_test::Process_test()
+{}
+
+
+Process_test::~Process_test()
+{}
+
+
+void Process_test::run_sleep()
+{
+ char* args[] = {"/bin/sleep", "2", NULL};
+ process.create("/bin/sleep",args,NULL);
+ process.requester.Connect(this,&Process_test::process_exit);
+ process.run();
+}
+
+void Process_test::run_ls()
+{
+ char* args[] = {"/bin/ls", "-ls", NULL};
+ process.create("/bin/ls",args,NULL);
+ process.requester.Connect(this,&Process_test::process_exit);
+ process.run();
+}
+
+
+void Process_test::run_a_disable_test()
+{
+ char* args[] = {"/home/neo/build/OSAL/Process/unit_test/process_test","--gtest_filter=Process_test.print_test",NULL};
+ process.create("/home/neo/build/OSAL/Process/unit_test/process_test",args,NULL);
+ process.requester.Connect(this,&Process_test::process_exit);
+ process.run();
+}
+
+
+void Process_test::process_exit(uint64_t exit_code, uint32_t exit_signal)
+{
+ printf("Process_test::process_exit exit_code = %d exit_signal = %d\n", exit_code, exit_signal);
+}
+
+
+void Process_test::SetUp()
+{
+ osal_test_base::SetUp();
+}
+
+
+void Process_test::TearDown()
+{
+ osal_test_base::TearDown();
+}
+
+
+TEST_F(Process_test, run_sleep )
+{
+ printf("start test");
+ run_sleep();
+ run();
+}
+
+
+TEST_F(Process_test, run_ls )
+{
+ printf("start test");
+ run_ls();
+ run();
+}
+
+
+TEST_F(Process_test, run_a_disable_test )
+{
+ printf("start test");
+ run_a_disable_test();
+ run();
+}
+
+
+TEST_F(Process_test, DISABLED_run_ls )
+{
+ printf("start ls test");
+}
+
+TEST_F(Process_test, print_test )
+{
+ fprintf(stderr,"start ls test");
+}
+
+
+#if 0
+
+void on_exit(uv_process_t *req, int exit_status, int term_signal) {
+ fprintf(stderr, "Process exited with status %d, signal %d\n", exit_status, term_signal);
+ uv_close((uv_handle_t*)req, NULL);
+}
+
+uv_process_options_t options;
+TEST_F(Process_test, run_ls_test)
+{
+ uv_loop_t *loop;
+ loop = uv_default_loop();
+uv_process_t child_req;
+
+ char *args[] = { "/bin/sleep", "2", NULL };
+
+ options.exit_cb = NULL;
+ options.file = "/bin/sleep";
+ options.args = args;
+ options.flags = UV_PROCESS_DETACHED;
+ fprintf(stderr,"loop %d\n",loop);
+ int error = uv_spawn(loop, &child_req, &options);
+ if (error) {
+ fprintf(stderr, "Error = %s!\n",uv_err_name(error));
+ }
+ fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid);
+// uv_unref((uv_handle_t*) &child_req);
+
+ uv_run(loop, UV_RUN_DEFAULT);
+}
+
+#endif
diff --git a/pool/shard002/C++/0034658_PhyloTree.cpp b/pool/shard002/C++/0034658_PhyloTree.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..300632d59c98963cbf592c6bc8a7f76fc383439a
--- /dev/null
+++ b/pool/shard002/C++/0034658_PhyloTree.cpp
@@ -0,0 +1,326 @@
+/* Copyright (C) 2014 University of Southern California and
+ * Andrew D. Smith
+ *
+ * Authors: Andrew D. Smith and Jenny Qu
+ *
+ * This program 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.
+ *
+ * This program 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 this program. If not, see .
+ */
+
+
+/*
+
+ ABOUT NEWICK FORMAT
+ -------------------
+
+ The following should all be legal, according to wikipedia.
+
+ (,,(,)); no nodes are named
+ (A,B,(C,D)); leaf nodes are named
+ (A,B,(C,D)E)F; all nodes are named
+ (:0.1,:0.2,(:0.3,:0.4):0.5); all but root node have a distance to parent
+ (:0.1,:0.2,(:0.3,:0.4):0.5):0.0; all have a distance to parent
+ (A:0.1,B:0.2,(C:0.3,D:0.4):0.5); distances and leaf names (popular)
+ (A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F; distances and all names
+ ((B:0.2,(C:0.3,D:0.4)E:0.5)F:0.1)A; a tree rooted on a leaf node (rare)
+
+ ========================================================================
+
+ (1) It seems like a tree always ends in a semicolon
+ (2) Trees need not be binary, but usually are ***
+ (3) Since the code needs to have uniform nodes, we will always have
+ a distance, even for the root, but this will be 0.0
+ (4) The parsing will look for commas, but not within parentheses
+ (5) No whitespace will be allowed. It will be removed initially
+ (6) There is a question of whether to allow commas or colons inside
+ names, for example by using quotes around the names or trying to
+ parse intelligently
+*/
+
+
+#include "PhyloTree.hpp"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include // for isspace
+
+#include "smithlab_utils.hpp"
+
+using std::string;
+using std::vector;
+using std::endl;
+using std::cerr;
+using std::cout;
+using std::unordered_set;
+
+
+static bool
+check_balanced_parentheses(const string &s) {
+ int count = 0;
+ for (size_t i = 0; i < s.length(); ++i) {
+ if (s[i] == '(') ++count;
+ if (s[i] == ')') --count;
+ }
+ return count == 0;
+}
+
+
+// static bool
+// check_unique_names(const string &s) {
+// /// ADS: this function is really poorly coded
+// bool is_unique=true;
+// string s_copy =s;
+// unordered_set names;
+// size_t f1, f2;
+// while (!s_copy.empty()) {
+// f1 = s_copy.find_first_not_of("()0123456789:,;");
+// s_copy.erase(0,f1);
+// if (s_copy.empty()) break;
+// f2 = s_copy.find_first_of("()0123456789:,;");
+// string name=s_copy.substr(0,f2);
+// if (names.find(name)== names.end()){
+// names.insert(name);
+// }
+// else {
+// is_unique=false;
+// break;
+// }
+// }
+// return is_unique;
+// }
+
+
+void
+PhyloTree::PTNode::swap(PTNode &other) {
+ std::swap(child, other.child);
+ std::swap(name, other.name);
+ std::swap(branch_length, other.branch_length);
+}
+
+size_t
+PhyloTree::PTNode::get_size() const {
+ size_t sz = 1;
+ for (size_t i = 0; i < child.size(); ++i)
+ sz += child[i].get_size();
+ return sz;
+}
+
+
+string
+PhyloTree::PTNode::tostring(const size_t depth) const {
+ std::ostringstream oss;
+ oss << string(depth, '\t') << branch_length << ':' << name;
+ for (size_t i = 0; i < child.size(); ++i)
+ oss << endl << child[i].tostring(depth + 1);
+ return oss.str();
+}
+
+
+string
+PhyloTree::PTNode::Newick_format() const {
+ std::ostringstream oss;
+ if (!child.empty()) {
+ oss << '(';
+ oss << child.front().Newick_format();
+ for (size_t i = 1; i < child.size(); ++i)
+ oss << ',' << child[i].Newick_format();
+ oss << ')';
+ }
+ oss << name << ':' << branch_length;
+ return oss.str();
+}
+
+
+static bool
+represents_leaf(const string &tree_rep) {
+ return (tree_rep.find_first_of(',') == string::npos);
+}
+
+
+static string
+extract_name(const string &tree_rep) {
+ const size_t final_parenthesis = tree_rep.find_last_of(")");
+ const size_t possible_name_start =
+ (final_parenthesis == string::npos) ? 0 : final_parenthesis + 1;
+ const size_t branch_len_start =
+ std::min(tree_rep.find_first_of(":", possible_name_start),
+ tree_rep.length());
+ return string(tree_rep.begin() + possible_name_start,
+ tree_rep.begin() + branch_len_start);
+}
+
+
+static double
+extract_branch_length(const string &tree_rep) {
+ const size_t final_parenthesis = tree_rep.find_last_of(")");
+ const size_t colon_pos = tree_rep.find_first_of(":", final_parenthesis + 1);
+ if (colon_pos == string::npos)
+ return 0.0;
+ const size_t non_numeric =
+ tree_rep.find_first_not_of("0123456789.", colon_pos + 1);
+ if (non_numeric == 0)
+ return 0.0;
+ return atof(tree_rep.substr(colon_pos + 1).c_str());
+}
+
+
+static bool
+root_has_name(const string &tree_rep) {
+ const size_t final_parenthesis = tree_rep.find_last_of(")");
+ const size_t possible_name_start =
+ (final_parenthesis == string::npos) ? 0 : final_parenthesis;
+ return (tree_rep[possible_name_start] != ':');
+}
+
+
+static void
+extract_subtrees(const string &tree_rep,
+ vector &subtree_reps) {
+ const size_t offset = (tree_rep[0] == '(') ? 1 : 0;
+ const string tmp(tree_rep.begin() + offset,
+ tree_rep.begin() + tree_rep.find_last_of(")"));
+ vector split_points;
+ size_t p_count = 0;
+ for (size_t i = 0; i < tmp.length(); ++i) {
+ if (p_count == 0 && tmp[i] == ',')
+ split_points.push_back(i);
+ if (tmp[i] == '(') ++p_count;
+ if (tmp[i] == ')') --p_count;
+ }
+ split_points.push_back(tmp.length());
+ subtree_reps.push_back(tmp.substr(0, split_points[0]));
+ for (size_t i = 0; i < split_points.size() - 1; ++i)
+ subtree_reps.push_back(string(tmp.begin() + split_points[i] + 1,
+ tmp.begin() + split_points[i + 1]));
+}
+
+
+PhyloTree::PTNode::PTNode(const string &tree_rep) {
+ // This function needs to test the various ways that a string can be
+ // passed in to represent a subtree at the current node
+
+ branch_length = extract_branch_length(tree_rep);
+ if (root_has_name(tree_rep))
+ name = extract_name(tree_rep);
+
+ if (!represents_leaf(tree_rep)) {
+ vector subtree_reps;
+ extract_subtrees(tree_rep, subtree_reps);
+ for (size_t i = 0; i < subtree_reps.size(); ++i)
+ child.push_back(PTNode(subtree_reps[i]));
+ }
+}
+
+void
+PhyloTree::PTNode::copy_subtree_with_species(const PTNode &t,
+ const
+ unordered_set &species,
+ PTNode &u) {
+ if (t.is_leaf()) {
+ if (species.find(t.name) != species.end()) {
+ u.name = t.name;
+ u.branch_length = t.branch_length;
+ }
+ }
+ else {
+
+ vector children;
+ for (size_t i = 0; i < t.child.size(); ++i) {
+ PTNode v;
+ copy_subtree_with_species(t.child[i], species, v);
+ if (v.has_children() || !v.name.empty()) {
+ children.push_back(PTNode());
+ children.back().swap(v);
+ }
+ }
+
+ if (children.size() > 0) {
+ if (children.size() == 1) {
+ u.swap(children.front());
+ u.branch_length += t.branch_length;
+ }
+ else {
+ u.name = t.name;
+ u.branch_length = t.branch_length;
+ u.child.swap(children);
+ }
+ }
+ }
+}
+
+
+
+////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////
+//// PHYLO TREE CLASS BELOW HERE ////
+////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////
+
+
+PhyloTree::PhyloTree(string tree_rep) {
+ if (!check_balanced_parentheses(tree_rep))
+ throw SMITHLABException("Unbalanced parentheses in Newick format: " +
+ tree_rep);
+ // remove whitespace
+ string::iterator w =
+ std::remove_copy_if(tree_rep.begin(), tree_rep.end(),
+ tree_rep.begin(), &isspace);
+ assert(w != tree_rep.begin());
+ if (*(w - 1) == ';')
+ tree_rep.erase(--w, tree_rep.end()); // The "--w" is for the ";"
+
+ /* ADS: requirement for unique names should only apply to leafs
+ */
+ // if (!check_unique_names(tree_rep))
+ // throw SMITHLABException("duplicate names in: " + tree_rep);
+
+ root = PTNode(tree_rep);
+}
+
+
+void
+PhyloTree::copy_subtree_with_species(const PhyloTree &t,
+ const unordered_set &species,
+ PhyloTree &u) {
+ PTNode::copy_subtree_with_species(t.root, species, u.root);
+}
+
+
+std::istream&
+operator>>(std::istream &in, PhyloTree &t) {
+ /* doing it this way to just get one tree at a time */
+ string r;
+ char c;
+ bool found_end = false;
+ while (!found_end && in >> c) {
+ r += c;
+ if (c == ';')
+ found_end = true;
+ }
+ if (!found_end)
+ throw SMITHLABException("bad tree format");
+ t = PhyloTree(r);
+ return in;
+}
+
+
+std::ostream&
+operator<<(std::ostream &out, const PhyloTree &t) {
+ return out << t.Newick_format();
+}
diff --git a/pool/shard002/C++/0034662_BitmapWindow.cpp b/pool/shard002/C++/0034662_BitmapWindow.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4949e63158ac89cf5dcb2c8e46c8ca123b1f8f88
--- /dev/null
+++ b/pool/shard002/C++/0034662_BitmapWindow.cpp
@@ -0,0 +1,60 @@
+/////////////////////////////////////////////////////////////////////////////
+// The GaugeWorks project is released under the GNU Lesser Public License
+// with modifications. See the License.txt file for the full text
+// Copyright (c) 2007 Brent Picasso http://picasso.org
+// Name: BitmapWindow
+// Purpose: wxLed implementation
+/////////////////////////////////////////////////////////////////////////////
+#include "BitmapWindow.h"
+
+BEGIN_EVENT_TABLE(BitmapWindow,wxWindow)
+ EVT_PAINT(BitmapWindow::OnPaint)
+ EVT_SIZE(BitmapWindow::OnSize)
+
+END_EVENT_TABLE()
+
+//BitmapWindow::BitmapWindow() : _imageXpm(NULL){}
+
+BitmapWindow::BitmapWindow( wxWindow *parent,
+ wxWindowID id,
+ const char ** xpm_bitmap,
+ const wxPoint &pos,
+ const wxSize &size )
+: wxWindow(parent, id, pos, size, 0)
+{
+ _imageXpm = new wxBitmap(xpm_bitmap);
+}
+
+BitmapWindow::~BitmapWindow(){
+ delete (_imageXpm);
+}
+
+void BitmapWindow::SetBitmap(const char ** newXpm){
+ if (_imageXpm) delete (_imageXpm);
+ _imageXpm = new wxBitmap(newXpm);
+ Refresh();
+}
+
+
+void BitmapWindow::OnSize(wxSizeEvent &event){
+ Refresh();
+}
+
+wxSize BitmapWindow::GetMinSize() const{
+ return wxSize(_imageXpm->GetWidth(), _imageXpm->GetHeight());
+}
+
+void BitmapWindow::OnPaint(wxPaintEvent &event){
+
+
+ int w,h ;
+ GetClientSize(&w,&h);
+
+ wxPaintDC dc( this );
+ PrepareDC( dc );
+ dc.SetBackground(*wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(),wxSOLID));
+ dc.SetBrush(*wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(),wxSOLID));
+ dc.Clear();
+
+ dc.DrawBitmap(*_imageXpm, w -_imageXpm->GetWidth(),0,true);
+}
diff --git a/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc b/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc
new file mode 100644
index 0000000000000000000000000000000000000000..21a18b0dba8753e14cf37c0b64a1e3a734f31d70
--- /dev/null
+++ b/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc
@@ -0,0 +1,263 @@
+// Copyright 2016 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 "base/task_scheduler/task_scheduler_impl.h"
+
+#include
+
+#include
+#include
+#include
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/callback.h"
+#include "base/macros.h"
+#include "base/memory/ptr_util.h"
+#include "base/synchronization/lock.h"
+#include "base/synchronization/waitable_event.h"
+#include "base/task_scheduler/scheduler_worker_pool_params.h"
+#include "base/task_scheduler/task_traits.h"
+#include "base/task_scheduler/test_task_factory.h"
+#include "base/threading/platform_thread.h"
+#include "base/threading/simple_thread.h"
+#include "base/threading/thread.h"
+#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace base {
+namespace internal {
+
+namespace {
+
+struct TraitsExecutionModePair {
+ TraitsExecutionModePair(const TaskTraits& traits,
+ ExecutionMode execution_mode)
+ : traits(traits), execution_mode(execution_mode) {}
+
+ TaskTraits traits;
+ ExecutionMode execution_mode;
+};
+
+#if DCHECK_IS_ON()
+// Returns whether I/O calls are allowed on the current thread.
+bool GetIOAllowed() {
+ const bool previous_value = ThreadRestrictions::SetIOAllowed(true);
+ ThreadRestrictions::SetIOAllowed(previous_value);
+ return previous_value;
+}
+#endif
+
+// Verify that the current thread priority and I/O restrictions are appropriate
+// to run a Task with |traits|.
+// Note: ExecutionMode is verified inside TestTaskFactory.
+void VerifyTaskEnvironement(const TaskTraits& traits) {
+ const bool supports_background_priority =
+ Lock::HandlesMultipleThreadPriorities() &&
+ PlatformThread::CanIncreaseCurrentThreadPriority();
+
+ EXPECT_EQ(supports_background_priority &&
+ traits.priority() == TaskPriority::BACKGROUND
+ ? ThreadPriority::BACKGROUND
+ : ThreadPriority::NORMAL,
+ PlatformThread::GetCurrentThreadPriority());
+
+#if DCHECK_IS_ON()
+ // The #if above is required because GetIOAllowed() always returns true when
+ // !DCHECK_IS_ON(), even when |traits| don't allow file I/O.
+ EXPECT_EQ(traits.with_file_io(), GetIOAllowed());
+#endif
+
+ // Verify that the thread the task is running on is named as expected.
+ const std::string current_thread_name(PlatformThread::GetName());
+ EXPECT_NE(std::string::npos, current_thread_name.find("TaskScheduler"));
+ EXPECT_NE(std::string::npos,
+ current_thread_name.find(
+ traits.priority() == TaskPriority::BACKGROUND ? "Background"
+ : "Foreground"));
+ EXPECT_EQ(traits.with_file_io(),
+ current_thread_name.find("FileIO") != std::string::npos);
+}
+
+void VerifyTaskEnvironementAndSignalEvent(const TaskTraits& traits,
+ WaitableEvent* event) {
+ DCHECK(event);
+ VerifyTaskEnvironement(traits);
+ event->Signal();
+}
+
+class ThreadPostingTasks : public SimpleThread {
+ public:
+ // Creates a thread that posts Tasks to |scheduler| with |traits| and
+ // |execution_mode|.
+ ThreadPostingTasks(TaskSchedulerImpl* scheduler,
+ const TaskTraits& traits,
+ ExecutionMode execution_mode)
+ : SimpleThread("ThreadPostingTasks"),
+ traits_(traits),
+ factory_(scheduler->CreateTaskRunnerWithTraits(traits, execution_mode),
+ execution_mode) {}
+
+ void WaitForAllTasksToRun() { factory_.WaitForAllTasksToRun(); }
+
+ private:
+ void Run() override {
+ EXPECT_FALSE(factory_.task_runner()->RunsTasksOnCurrentThread());
+
+ const size_t kNumTasksPerThread = 150;
+ for (size_t i = 0; i < kNumTasksPerThread; ++i) {
+ factory_.PostTask(test::TestTaskFactory::PostNestedTask::NO,
+ Bind(&VerifyTaskEnvironement, traits_));
+ }
+ }
+
+ const TaskTraits traits_;
+ test::TestTaskFactory factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(ThreadPostingTasks);
+};
+
+// Returns a vector with a TraitsExecutionModePair for each valid
+// combination of {ExecutionMode, TaskPriority, WithFileIO()}.
+std::vector GetTraitsExecutionModePairs() {
+ std::vector params;
+
+ const ExecutionMode execution_modes[] = {ExecutionMode::PARALLEL,
+ ExecutionMode::SEQUENCED,
+ ExecutionMode::SINGLE_THREADED};
+
+ for (ExecutionMode execution_mode : execution_modes) {
+ for (size_t priority_index = static_cast(TaskPriority::LOWEST);
+ priority_index <= static_cast(TaskPriority::HIGHEST);
+ ++priority_index) {
+ const TaskPriority priority = static_cast(priority_index);
+ params.push_back(TraitsExecutionModePair(
+ TaskTraits().WithPriority(priority), execution_mode));
+ params.push_back(TraitsExecutionModePair(
+ TaskTraits().WithPriority(priority).WithFileIO(), execution_mode));
+ }
+ }
+
+ return params;
+}
+
+enum WorkerPoolType {
+ BACKGROUND_WORKER_POOL = 0,
+ BACKGROUND_FILE_IO_WORKER_POOL,
+ FOREGROUND_WORKER_POOL,
+ FOREGROUND_FILE_IO_WORKER_POOL,
+};
+
+size_t GetThreadPoolIndexForTraits(const TaskTraits& traits) {
+ if (traits.with_file_io()) {
+ return traits.priority() == TaskPriority::BACKGROUND
+ ? BACKGROUND_FILE_IO_WORKER_POOL
+ : FOREGROUND_FILE_IO_WORKER_POOL;
+ }
+ return traits.priority() == TaskPriority::BACKGROUND ? BACKGROUND_WORKER_POOL
+ : FOREGROUND_WORKER_POOL;
+}
+
+class TaskSchedulerImplTest
+ : public testing::TestWithParam {
+ protected:
+ TaskSchedulerImplTest() = default;
+
+ void SetUp() override {
+ using IORestriction = SchedulerWorkerPoolParams::IORestriction;
+
+ std::vector params_vector;
+
+ ASSERT_EQ(BACKGROUND_WORKER_POOL, params_vector.size());
+ params_vector.emplace_back("Background", ThreadPriority::BACKGROUND,
+ IORestriction::DISALLOWED, 1U, TimeDelta::Max());
+
+ ASSERT_EQ(BACKGROUND_FILE_IO_WORKER_POOL, params_vector.size());
+ params_vector.emplace_back("BackgroundFileIO", ThreadPriority::BACKGROUND,
+ IORestriction::ALLOWED, 3U, TimeDelta::Max());
+
+ ASSERT_EQ(FOREGROUND_WORKER_POOL, params_vector.size());
+ params_vector.emplace_back("Foreground", ThreadPriority::NORMAL,
+ IORestriction::DISALLOWED, 4U, TimeDelta::Max());
+
+ ASSERT_EQ(FOREGROUND_FILE_IO_WORKER_POOL, params_vector.size());
+ params_vector.emplace_back("ForegroundFileIO", ThreadPriority::NORMAL,
+ IORestriction::ALLOWED, 12U, TimeDelta::Max());
+
+ scheduler_ = TaskSchedulerImpl::Create(params_vector,
+ Bind(&GetThreadPoolIndexForTraits));
+ ASSERT_TRUE(scheduler_);
+ }
+
+ void TearDown() override { scheduler_->JoinForTesting(); }
+
+ std::unique_ptr scheduler_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TaskSchedulerImplTest);
+};
+
+} // namespace
+
+// Verifies that a Task posted via PostTaskWithTraits with parameterized
+// TaskTraits runs on a thread with the expected priority and I/O restrictions.
+// The ExecutionMode parameter is ignored by this test.
+TEST_P(TaskSchedulerImplTest, PostTaskWithTraits) {
+ WaitableEvent task_ran(WaitableEvent::ResetPolicy::MANUAL,
+ WaitableEvent::InitialState::NOT_SIGNALED);
+ scheduler_->PostTaskWithTraits(
+ FROM_HERE, GetParam().traits,
+ Bind(&VerifyTaskEnvironementAndSignalEvent, GetParam().traits,
+ Unretained(&task_ran)));
+ task_ran.Wait();
+}
+
+// Verifies that Tasks posted via a TaskRunner with parameterized TaskTraits and
+// ExecutionMode run on a thread with the expected priority and I/O restrictions
+// and respect the characteristics of their ExecutionMode.
+TEST_P(TaskSchedulerImplTest, PostTasksViaTaskRunner) {
+ test::TestTaskFactory factory(
+ scheduler_->CreateTaskRunnerWithTraits(GetParam().traits,
+ GetParam().execution_mode),
+ GetParam().execution_mode);
+ EXPECT_FALSE(factory.task_runner()->RunsTasksOnCurrentThread());
+
+ const size_t kNumTasksPerTest = 150;
+ for (size_t i = 0; i < kNumTasksPerTest; ++i) {
+ factory.PostTask(test::TestTaskFactory::PostNestedTask::NO,
+ Bind(&VerifyTaskEnvironement, GetParam().traits));
+ }
+
+ factory.WaitForAllTasksToRun();
+}
+
+INSTANTIATE_TEST_CASE_P(OneTraitsExecutionModePair,
+ TaskSchedulerImplTest,
+ ::testing::ValuesIn(GetTraitsExecutionModePairs()));
+
+// Spawns threads that simultaneously post Tasks to TaskRunners with various
+// TaskTraits and ExecutionModes. Verifies that each Task runs on a thread with
+// the expected priority and I/O restrictions and respects the characteristics
+// of its ExecutionMode.
+TEST_F(TaskSchedulerImplTest, MultipleTraitsExecutionModePairs) {
+ std::vector> threads_posting_tasks;
+ for (const auto& traits_execution_mode_pair : GetTraitsExecutionModePairs()) {
+ threads_posting_tasks.push_back(WrapUnique(new ThreadPostingTasks(
+ scheduler_.get(), traits_execution_mode_pair.traits,
+ traits_execution_mode_pair.execution_mode)));
+ threads_posting_tasks.back()->Start();
+ }
+
+ for (const auto& thread : threads_posting_tasks) {
+ thread->WaitForAllTasksToRun();
+ thread->Join();
+ }
+}
+
+// TODO(fdoray): Add tests with Sequences that move around worker pools once
+// child TaskRunners are supported.
+
+} // namespace internal
+} // namespace base
diff --git a/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp b/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..9adedba52468edaddf8b25cbb2f16dce11a6828a
--- /dev/null
+++ b/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp
@@ -0,0 +1,121 @@
+/*
+ Copyright 2013-2021 Paul Colby
+
+ This file is part of QtAws.
+
+ QtAws is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ QtAws 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 the QtAws. If not, see .
+*/
+
+#include "updategeomatchsetresponse.h"
+#include "updategeomatchsetresponse_p.h"
+
+#include
+#include
+#include
+
+namespace QtAws {
+namespace WAF {
+
+/*!
+ * \class QtAws::WAF::UpdateGeoMatchSetResponse
+ * \brief The UpdateGeoMatchSetResponse class provides an interace for WAF UpdateGeoMatchSet responses.
+ *
+ * \inmodule QtAwsWAF
+ *
+ *
+ *
+ * This is AWS WAF Classic documentation. For more information, see AWS WAF Classic in the
+ * developer
+ *
+ * guide>
+ *
+ * For the latest version of AWS WAF, use the AWS WAFV2 API and see the AWS WAF Developer Guide. With the
+ * latest version, AWS WAF has a single set of endpoints for regional and global use.
+ *
+ *
+ *
+ * This is the AWS WAF Classic API Reference for using AWS WAF Classic with Amazon CloudFront. The AWS WAF Classic
+ * actions and data types listed in the reference are available for protecting Amazon CloudFront distributions. You can use
+ * these actions and data types via the endpoint waf.amazonaws.com. This guide is for developers who need detailed
+ * information about the AWS WAF Classic API actions, data types, and errors. For detailed information about AWS WAF
+ * Classic features and an overview of how to use the AWS WAF Classic API, see the AWS WAF Classic in the
+ * developer
+ *
+ * \sa WafClient::updateGeoMatchSet
+ */
+
+/*!
+ * Constructs a UpdateGeoMatchSetResponse object for \a reply to \a request, with parent \a parent.
+ */
+UpdateGeoMatchSetResponse::UpdateGeoMatchSetResponse(
+ const UpdateGeoMatchSetRequest &request,
+ QNetworkReply * const reply,
+ QObject * const parent)
+ : WafResponse(new UpdateGeoMatchSetResponsePrivate(this), parent)
+{
+ setRequest(new UpdateGeoMatchSetRequest(request));
+ setReply(reply);
+}
+
+/*!
+ * \reimp
+ */
+const UpdateGeoMatchSetRequest * UpdateGeoMatchSetResponse::request() const
+{
+ Q_D(const UpdateGeoMatchSetResponse);
+ return static_cast(d->request);
+}
+
+/*!
+ * \reimp
+ * Parses a successful WAF UpdateGeoMatchSet \a response.
+ */
+void UpdateGeoMatchSetResponse::parseSuccess(QIODevice &response)
+{
+ //Q_D(UpdateGeoMatchSetResponse);
+ QXmlStreamReader xml(&response);
+ /// @todo
+}
+
+/*!
+ * \class QtAws::WAF::UpdateGeoMatchSetResponsePrivate
+ * \brief The UpdateGeoMatchSetResponsePrivate class provides private implementation for UpdateGeoMatchSetResponse.
+ * \internal
+ *
+ * \inmodule QtAwsWAF
+ */
+
+/*!
+ * Constructs a UpdateGeoMatchSetResponsePrivate object with public implementation \a q.
+ */
+UpdateGeoMatchSetResponsePrivate::UpdateGeoMatchSetResponsePrivate(
+ UpdateGeoMatchSetResponse * const q) : WafResponsePrivate(q)
+{
+
+}
+
+/*!
+ * Parses a WAF UpdateGeoMatchSet response element from \a xml.
+ */
+void UpdateGeoMatchSetResponsePrivate::parseUpdateGeoMatchSetResponse(QXmlStreamReader &xml)
+{
+ Q_ASSERT(xml.name() == QLatin1String("UpdateGeoMatchSetResponse"));
+ Q_UNUSED(xml) ///< @todo
+}
+
+} // namespace WAF
+} // namespace QtAws
diff --git a/pool/shard002/C++/0034688_output_m001u006.cpp b/pool/shard002/C++/0034688_output_m001u006.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ba0eb77b171d5ab4ff16dda5bd2f9bfcf4e14921
--- /dev/null
+++ b/pool/shard002/C++/0034688_output_m001u006.cpp
@@ -0,0 +1,29 @@
+#include
+#include "gtest/gtest.h"
+#include "test_miranda.hpp"
+
+namespace {
+
+class OM001U006 : public TestIOBase {
+protected:
+ OM001U006() {
+ IFNAME1 = (char *) "mir_001.fasta";
+ IFNAME2 = (char *) "utr3_006.fasta";
+ O1FNAME1 = (char *) "test_output1_site_6.txt";
+ O1FNAME2 = (char *) "test_output1_mrna_6.txt";
+ O2FNAME1 = (char *) "test_output2_site_6.txt";
+ O2FNAME2 = (char *) "test_output2_mrna_6.txt";
+ OMPATH = (char *) "mk_miranda/";
+ }
+};
+
+TEST_F(OM001U006, comp_site) {
+ (void) mikan::MKCoreMain(argc, (const char **) argv);
+ gtest_compare_two_files(o1file1, o2file1);
+}
+
+TEST_F(OM001U006, comp_mrna) {
+ (void) mikan::MKCoreMain(argc, (const char **) argv);
+ gtest_compare_two_files(o1file2, o2file2);
+}
+}
\ No newline at end of file
diff --git a/pool/shard002/C++/0034689_emi2.cpp b/pool/shard002/C++/0034689_emi2.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b5126f91edcd0a22d1da9f1ef898696506636cc8
--- /dev/null
+++ b/pool/shard002/C++/0034689_emi2.cpp
@@ -0,0 +1,140 @@
+/*
+ EIBD eib bus access and management daemon
+ Copyright (C) 2005-2011 Martin Koegler
+
+ This program 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 2 of the License, or
+ (at your option) any later version.
+
+ This program 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 this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#include "emi2.h"
+
+#include "emi.h"
+
+EMI2Driver::EMI2Driver (LowLevelIface* c, IniSectionPtr& s, LowLevelDriver *i) : EMI_Common(c,s,i)
+{
+ t->setAuxName("EMI2");
+ sendLocal_done.set(this);
+}
+
+void
+EMI2Driver::sendLocal_done_cb(bool success)
+{
+ if (!success || sendLocal_done_next == N_bad)
+ {
+ errored();
+ LowLevelFilter::stopped();
+ }
+ else if (sendLocal_done_next == N_down)
+ LowLevelFilter::stop();
+ else if (sendLocal_done_next == N_up)
+ LowLevelFilter::started();
+ else if (sendLocal_done_next == N_open)
+ {
+ sendLocal_done_next = N_up;
+ const uint8_t t2[] = { 0xa9, 0x00, 0x18, 0x34, 0x56, 0x78, 0x0a };
+ send_Local (CArray (t2, sizeof (t2)),1);
+ }
+ else if (sendLocal_done_next == N_enter)
+ {
+ sendLocal_done_next = N_up;
+ const uint8_t t2[] = { 0xa9, 0x90, 0x18, 0x34, 0x45, 0x67, 0x8a };
+ send_Local (CArray (t2, sizeof (t2)),1);
+ }
+
+}
+
+void
+EMI2Driver::cmdEnterMonitor ()
+{
+ sendLocal_done_next = N_enter;
+ const uint8_t t1[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a };
+ send_Local (CArray (t1, sizeof (t1)),1);
+}
+
+void
+EMI2Driver::cmdLeaveMonitor ()
+{
+ if (wait_confirm_low)
+ {
+ sendLocal_done_next = N_want_leave;
+ return;
+ }
+ sendLocal_done_next = N_down;
+ uint8_t t[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a };
+ send_Local (CArray (t, sizeof (t)),1);
+}
+
+void
+EMI2Driver::cmdOpen ()
+{
+ sendLocal_done_next = N_open;
+ const uint8_t t1[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a };
+ send_Local (CArray (t1, sizeof (t1)),1);
+}
+
+void
+EMI2Driver::cmdClose ()
+{
+ if (wait_confirm_low)
+ {
+ sendLocal_done_next = N_want_close;
+ return;
+ }
+ sendLocal_done_next = N_down;
+ uint8_t t[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a };
+ send_Local (CArray (t, sizeof (t)),1);
+}
+
+void EMI2Driver::started()
+{
+ reset_ack_wait = true;
+ reset_timer.start(0.5, 0);
+ sendReset();
+}
+
+void EMI2Driver::reset_timer_cb(ev::timer&, int)
+{
+ ERRORPRINTF(t, E_ERROR | 57, "reset timed out");
+ errored();
+}
+
+void EMI2Driver::do_send_Next()
+{
+ if (reset_ack_wait)
+ {
+ reset_ack_wait = false;
+ reset_timer.stop();
+ EMI_Common::started();
+ }
+ else if (sendLocal_done_next == N_want_close)
+ {
+ wait_confirm_low = false;
+ cmdClose();
+ }
+ else if (sendLocal_done_next == N_want_leave)
+ {
+ wait_confirm_low = false;
+ cmdLeaveMonitor();
+ }
+ else
+ EMI_Common::do_send_Next();
+}
+
+const uint8_t *
+EMI2Driver::getIndTypes() const
+{
+ static const uint8_t indTypes[] = { 0x2E, 0x29, 0x2B };
+ return indTypes;
+}
+
diff --git a/pool/shard002/C++/0034691_memoryagent.cpp b/pool/shard002/C++/0034691_memoryagent.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ecb8b44ad2a68e8750debf150ea67305563b7a66
--- /dev/null
+++ b/pool/shard002/C++/0034691_memoryagent.cpp
@@ -0,0 +1,317 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "memoryagent.h"
+#include "memoryview.h"
+
+#include "breakhandler.h"
+#include "debuggerengine.h"
+#include "debuggerstartparameters.h"
+#include "debuggercore.h"
+#include "debuggerinternalconstants.h"
+
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+#include
+
+#include
+
+using namespace Core;
+
+namespace Debugger {
+namespace Internal {
+
+///////////////////////////////////////////////////////////////////////
+//
+// MemoryAgent
+//
+///////////////////////////////////////////////////////////////////////
+
+/*!
+ \class Debugger::Internal::MemoryAgent
+
+ Objects form this class are created in response to user actions in
+ the Gui for showing raw memory from the inferior. After creation
+ it handles communication between the engine and the bineditor.
+
+ Memory can be shown as
+ \list
+ \li Editor: Create an IEditor using the normal editor factory
+ interface (m_editors)
+ \li View: Separate top-level view consisting of a Bin Editor widget
+ (m_view).
+ \endlist
+
+ Views are updated on the DebuggerEngine::stackFrameCompleted signal.
+ An exception are views of class Debugger::RegisterMemoryView tracking the
+ content pointed to by a register (eg stack pointer, instruction pointer).
+ They are connected to the set/changed signals of
+ the engine's register handler.
+
+ \sa Debugger::MemoryView, Debugger::RegisterMemoryView
+*/
+
+MemoryAgent::MemoryAgent(DebuggerEngine *engine)
+ : QObject(engine), m_engine(engine)
+{
+ QTC_CHECK(engine);
+ connect(engine, SIGNAL(stateChanged(Debugger::DebuggerState)),
+ this, SLOT(engineStateChanged(Debugger::DebuggerState)));
+ connect(engine, SIGNAL(stackFrameCompleted()), this,
+ SLOT(updateContents()));
+}
+
+MemoryAgent::~MemoryAgent()
+{
+ closeEditors();
+ closeViews();
+}
+
+void MemoryAgent::closeEditors()
+{
+ if (m_editors.isEmpty())
+ return;
+
+ QSet documents;
+ foreach (QPointer editor, m_editors)
+ if (editor)
+ documents.insert(editor->document());
+ EditorManager::closeDocuments(documents.toList());
+ m_editors.clear();
+}
+
+void MemoryAgent::closeViews()
+{
+ foreach (const QPointer &w, m_views)
+ if (w)
+ w->close();
+ m_views.clear();
+}
+
+void MemoryAgent::updateMemoryView(quint64 address, quint64 length)
+{
+ m_engine->fetchMemory(this, sender(), address, length);
+}
+
+void MemoryAgent::connectBinEditorWidget(QWidget *w)
+{
+ connect(w, SIGNAL(dataRequested(quint64)), SLOT(fetchLazyData(quint64)));
+ connect(w, SIGNAL(newWindowRequested(quint64)), SLOT(createBinEditor(quint64)));
+ connect(w, SIGNAL(newRangeRequested(quint64)), SLOT(provideNewRange(quint64)));
+ connect(w, SIGNAL(dataChanged(quint64,QByteArray)), SLOT(handleDataChanged(quint64,QByteArray)));
+ connect(w, SIGNAL(dataChanged(quint64,QByteArray)), SLOT(handleDataChanged(quint64,QByteArray)));
+ connect(w, SIGNAL(addWatchpointRequested(quint64,uint)), SLOT(handleWatchpointRequest(quint64,uint)));
+}
+
+bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags,
+ const QList &ml, const QPoint &pos,
+ QString title, QWidget *parent)
+{
+ const bool readOnly = (flags & DebuggerEngine::MemoryReadOnly) != 0;
+ if (title.isEmpty())
+ title = tr("Memory at 0x%1").arg(addr, 0, 16);
+ // Separate view?
+ if (flags & DebuggerEngine::MemoryView) {
+ // Ask BIN editor plugin for factory service and have it create a bin editor widget.
+ QWidget *binEditor = 0;
+ if (QObject *factory = ExtensionSystem::PluginManager::getObjectByClassName(QLatin1String("BinEditor::BinEditorWidgetFactory")))
+ binEditor = ExtensionSystem::invoke(factory, "createWidget", (QWidget *)0);
+ if (!binEditor)
+ return false;
+ connectBinEditorWidget(binEditor);
+ MemoryView::setBinEditorReadOnly(binEditor, readOnly);
+ MemoryView::setBinEditorNewWindowRequestAllowed(binEditor, true);
+ MemoryView *topLevel = 0;
+ // Memory view tracking register value, providing its own updating mechanism.
+ if (flags & DebuggerEngine::MemoryTrackRegister) {
+ RegisterMemoryView *rmv = new RegisterMemoryView(binEditor, parent);
+ rmv->init(m_engine->registerHandler(), int(addr));
+ topLevel = rmv;
+ } else {
+ // Ordinary memory view
+ MemoryView::setBinEditorMarkup(binEditor, ml);
+ MemoryView::setBinEditorRange(binEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
+ topLevel = new MemoryView(binEditor, parent);
+ topLevel->setWindowTitle(title);
+ }
+ m_views << topLevel;
+ topLevel->move(pos);
+ topLevel->show();
+ return true;
+ }
+ // Editor: Register tracking not supported.
+ QTC_ASSERT(!(flags & DebuggerEngine::MemoryTrackRegister), return false);
+ if (!title.endsWith(QLatin1Char('$')))
+ title.append(QLatin1String(" $"));
+ IEditor *editor = EditorManager::openEditorWithContents(
+ Core::Constants::K_DEFAULT_BINARY_EDITOR_ID, &title);
+ if (!editor)
+ return false;
+ editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, QVariant(true));
+ editor->document()->setTemporary(true);
+ QWidget *editorBinEditor = editor->widget();
+ connectBinEditorWidget(editorBinEditor);
+ MemoryView::setBinEditorReadOnly(editorBinEditor, readOnly);
+ MemoryView::setBinEditorNewWindowRequestAllowed(editorBinEditor, true);
+ MemoryView::setBinEditorRange(editorBinEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
+ MemoryView::setBinEditorMarkup(editorBinEditor, ml);
+ m_editors << editor;
+ return true;
+}
+
+void MemoryAgent::createBinEditor(quint64 addr, unsigned flags,
+ const QList &ml, const QPoint &pos,
+ const QString &title, QWidget *parent)
+{
+ if (!doCreateBinEditor(addr, flags, ml, pos, title, parent))
+ showMessageBox(QMessageBox::Warning,
+ tr("No Memory Viewer Available"),
+ tr("The memory contents cannot be shown as no viewer plugin "
+ "for binary data has been loaded."));
+}
+
+void MemoryAgent::createBinEditor(quint64 addr)
+{
+ createBinEditor(addr, 0, QList(), QPoint(), QString(), 0);
+}
+
+void MemoryAgent::fetchLazyData(quint64 block)
+{
+ m_engine->fetchMemory(this, sender(), BinBlockSize * block, BinBlockSize);
+}
+
+void MemoryAgent::addLazyData(QObject *editorToken, quint64 addr,
+ const QByteArray &ba)
+{
+ QWidget *w = qobject_cast(editorToken);
+ QTC_ASSERT(w, return);
+ MemoryView::binEditorAddData(w, addr, ba);
+}
+
+void MemoryAgent::provideNewRange(quint64 address)
+{
+ QWidget *w = qobject_cast(sender());
+ QTC_ASSERT(w, return);
+ MemoryView::setBinEditorRange(w, address, DataRange, BinBlockSize);
+}
+
+void MemoryAgent::handleDataChanged(quint64 addr, const QByteArray &data)
+{
+ m_engine->changeMemory(this, sender(), addr, data);
+}
+
+void MemoryAgent::handleWatchpointRequest(quint64 address, uint size)
+{
+ m_engine->breakHandler()->setWatchpointAtAddress(address, size);
+}
+
+void MemoryAgent::updateContents()
+{
+ foreach (const QPointer &e, m_editors)
+ if (e)
+ MemoryView::binEditorUpdateContents(e->widget());
+ // Update all views except register views, which trigger on
+ // register value set/changed.
+ foreach (const QPointer &w, m_views)
+ if (w && !qobject_cast(w.data()))
+ w->updateContents();
+}
+
+bool MemoryAgent::hasVisibleEditor() const
+{
+ QList visible = EditorManager::visibleEditors();
+ foreach (QPointer editor, m_editors)
+ if (visible.contains(editor.data()))
+ return true;
+ return false;
+}
+
+void MemoryAgent::engineStateChanged(Debugger::DebuggerState s)
+{
+ switch (s) {
+ case DebuggerFinished:
+ closeViews();
+ foreach (const QPointer &editor, m_editors)
+ if (editor) { // Prevent triggering updates, etc.
+ MemoryView::setBinEditorReadOnly(editor->widget(), true);
+ editor->widget()->disconnect(this);
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+bool MemoryAgent::isBigEndian(const ProjectExplorer::Abi &a)
+{
+ switch (a.architecture()) {
+ case ProjectExplorer::Abi::UnknownArchitecture:
+ case ProjectExplorer::Abi::X86Architecture:
+ case ProjectExplorer::Abi::ItaniumArchitecture: // Configureable
+ case ProjectExplorer::Abi::ArmArchitecture: // Configureable
+ case ProjectExplorer::Abi::ShArchitecture: // Configureable
+ break;
+ case ProjectExplorer::Abi::MipsArchitecture: // Configureable
+ case ProjectExplorer::Abi::PowerPCArchitecture: // Configureable
+ return true;
+ }
+ return false;
+}
+
+// Read a POD variable from a memory location. Swap bytes if endianness differs
+template POD readPod(const unsigned char *data, bool swapByteOrder)
+{
+ POD pod = 0;
+ if (swapByteOrder) {
+ unsigned char *target = reinterpret_cast(&pod) + sizeof(POD) - 1;
+ for (size_t i = 0; i < sizeof(POD); i++)
+ *target-- = data[i];
+ } else {
+ std::memcpy(&pod, data, sizeof(POD));
+ }
+ return pod;
+}
+
+// Read memory from debuggee
+quint64 MemoryAgent::readInferiorPointerValue(const unsigned char *data, const ProjectExplorer::Abi &a)
+{
+ const bool swapByteOrder = isBigEndian(a) != isBigEndian(ProjectExplorer::Abi::hostAbi());
+ return a.wordWidth() == 32 ? readPod(data, swapByteOrder) :
+ readPod(data, swapByteOrder);
+}
+
+} // namespace Internal
+} // namespace Debugger
+;
diff --git a/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp b/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..bd22b3adee8cd2479f20bb35dc281721711b0500
--- /dev/null
+++ b/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp
@@ -0,0 +1,82 @@
+#include
+#include
+#include
+
+using namespace System;
+using namespace System::Diagnostics;
+
+namespace UnitTests {
+ TEST(ProcessStartInfoUnitTest, Constructor) {
+ ProcessStartInfo psi;
+ ASSERT_EQ(string::Empty, psi.Arguments);
+ ASSERT_FALSE(psi.CreateNoWindow);
+ ASSERT_EQ(string::Empty, psi.Domain);
+ ASSERT_EQ(0, psi.EnvironmentVariables().Count);
+ ASSERT_FALSE(psi.ErrorDialog);
+ ASSERT_EQ(0, psi.ErrorDialogParamHandle());
+ ASSERT_EQ(string::Empty, psi.FileName);
+ ASSERT_FALSE(psi.LoadUserProfile);
+ ASSERT_EQ(string::Empty, psi.PasswordInClearText);
+ ASSERT_FALSE(psi.RedirectStandardError);
+ ASSERT_FALSE(psi.RedirectStandardInput);
+ ASSERT_FALSE(psi.RedirectStandardOutput);
+ }
+
+ TEST(ProcessStartInfoUnitTest, ConstructorWithFileName) {
+ ProcessStartInfo psi("FileName");
+ ASSERT_EQ(string::Empty, psi.Arguments);
+ ASSERT_FALSE(psi.CreateNoWindow);
+ ASSERT_EQ(string::Empty, psi.Domain);
+ ASSERT_EQ(0, psi.EnvironmentVariables().Count);
+ ASSERT_FALSE(psi.ErrorDialog);
+ ASSERT_EQ(0, psi.ErrorDialogParamHandle());
+ ASSERT_EQ("FileName", psi.FileName);
+ ASSERT_FALSE(psi.LoadUserProfile);
+ ASSERT_EQ(string::Empty, psi.PasswordInClearText);
+ ASSERT_FALSE(psi.RedirectStandardError);
+ ASSERT_FALSE(psi.RedirectStandardInput);
+ ASSERT_FALSE(psi.RedirectStandardOutput);
+ }
+
+ TEST(ProcessStartInfoUnitTest, ConstructorWithFileNameAndArgument) {
+ ProcessStartInfo psi("FileName", "Arguments");
+ ASSERT_EQ("Arguments", psi.Arguments);
+ ASSERT_FALSE(psi.CreateNoWindow);
+ ASSERT_EQ(string::Empty, psi.Domain);
+ ASSERT_EQ(0, psi.EnvironmentVariables().Count);
+ ASSERT_FALSE(psi.ErrorDialog);
+ ASSERT_EQ(0, psi.ErrorDialogParamHandle());
+ ASSERT_EQ("FileName", psi.FileName);
+ ASSERT_FALSE(psi.LoadUserProfile);
+ ASSERT_EQ(string::Empty, psi.PasswordInClearText);
+ ASSERT_FALSE(psi.RedirectStandardError);
+ ASSERT_FALSE(psi.RedirectStandardInput);
+ ASSERT_FALSE(psi.RedirectStandardOutput);
+ }
+
+ TEST(ProcessStartInfoUnitTest, ConstructorByCopy) {
+ ProcessStartInfo psiOriginal("FileName", "Arguments");
+ ProcessStartInfo psi = psiOriginal;
+ ASSERT_EQ(psiOriginal.Arguments, psi.Arguments);
+ ASSERT_EQ(psiOriginal.CreateNoWindow, psi.CreateNoWindow);
+ ASSERT_EQ(psiOriginal.Domain, psi.Domain);
+ ASSERT_EQ(psiOriginal.EnvironmentVariables, psi.EnvironmentVariables);
+ ASSERT_EQ(psiOriginal.ErrorDialog, psi.ErrorDialog);
+ ASSERT_EQ(psiOriginal.ErrorDialogParamHandle, psi.ErrorDialogParamHandle);
+ ASSERT_EQ(psiOriginal.FileName, psi.FileName);
+ }
+
+ TEST(ProcessStartInfoUnitTest, SetPasswordThenCheckPasswordInClearText) {
+ ProcessStartInfo psi;
+ char32 password[] = {'M', 'y', ' ', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
+ psi.Pasword = System::Security::SecureString(password, 11);
+ ASSERT_EQ("My password", psi.PasswordInClearText);
+ }
+
+ TEST(ProcessStartInfoUnitTest, SetPasswordInClearTextThenCheckPasswordInClearText) {
+ ProcessStartInfo psi;
+ psi.PasswordInClearText = "My password";
+ ASSERT_EQ("My password", psi.PasswordInClearText);
+ }
+}
+
diff --git a/pool/shard002/C++/0034699_ioutil_test.cpp b/pool/shard002/C++/0034699_ioutil_test.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..6b15f5701e1e68f38bd079c86aa8bdd223fdb6d8
--- /dev/null
+++ b/pool/shard002/C++/0034699_ioutil_test.cpp
@@ -0,0 +1,20 @@
+#include "libreactor/ioutil.h"
+#include "libreactor/misc.h"
+#include
+
+int main() {
+ Reactor reactor;
+
+ std::vector fds = fd_pair(reactor);
+
+ ioutil::write(fds[0], ByteString::copy_from("hello")).wait(reactor);
+ ioutil::read(fds[1], 4).then([&](ByteString ret) {
+ std::cerr << ret << std::endl;
+ return ioutil::read(fds[1], 1);
+ }).then([](ByteString ret) {
+ std::cerr << ret << std::endl;
+ return unit();
+ }).wait(reactor);
+
+ exit(0);
+}
diff --git a/pool/shard002/C++/0034704_coincontroltreewidget.cpp b/pool/shard002/C++/0034704_coincontroltreewidget.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4e250600f56c16b7fdb9bcdd88add82871295947
--- /dev/null
+++ b/pool/shard002/C++/0034704_coincontroltreewidget.cpp
@@ -0,0 +1,33 @@
+// Copyright (c) 2011-2015 The Oakcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "coincontroltreewidget.h"
+#include "coincontroldialog.h"
+
+CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
+ QTreeWidget(parent)
+{
+
+}
+
+void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
+{
+ if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
+ {
+ event->ignore();
+ int COLUMN_CHECKBOX = 0;
+ if(this->currentItem())
+ this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
+ }
+ else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
+ {
+ event->ignore();
+ CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
+ coinControlDialog->done(QDialog::Accepted);
+ }
+ else
+ {
+ this->QTreeWidget::keyPressEvent(event);
+ }
+}
diff --git a/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp b/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4de24f7dcb8f4080e8410511ea13256c9e39a427
--- /dev/null
+++ b/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp
@@ -0,0 +1,62 @@
+/* TEMPLATE GENERATED TESTCASE FILE
+Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp
+Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
+Template File: sources-sink-65b.tmpl.cpp
+*/
+/*
+ * @description
+ * CWE: 122 Heap Based Buffer Overflow
+ * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
+ * GoodSource: Allocate enough memory for a string and the NULL terminator
+ * Sinks: memmove
+ * BadSink : Copy string to data using memmove()
+ * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
+ *
+ * */
+
+#include "std_testcase.h"
+
+#ifndef _WIN32
+#include
+#endif
+
+/* MAINTENANCE NOTE: The length of this string should equal the 10 */
+#define SRC_STRING "AAAAAAAAAA"
+
+namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65
+{
+
+#ifndef OMITBAD
+
+void badSink(char * data)
+{
+ {
+ char source[10+1] = SRC_STRING;
+ /* Copy length + 1 to include NUL terminator from source */
+ /* POTENTIAL FLAW: data may not have enough space to hold source */
+ memmove(data, source, (strlen(source) + 1) * sizeof(char));
+ printLine(data);
+ delete [] data;
+ }
+}
+
+#endif /* OMITBAD */
+
+#ifndef OMITGOOD
+
+/* goodG2B uses the GoodSource with the BadSink */
+void goodG2BSink(char * data)
+{
+ {
+ char source[10+1] = SRC_STRING;
+ /* Copy length + 1 to include NUL terminator from source */
+ /* POTENTIAL FLAW: data may not have enough space to hold source */
+ memmove(data, source, (strlen(source) + 1) * sizeof(char));
+ printLine(data);
+ delete [] data;
+ }
+}
+
+#endif /* OMITGOOD */
+
+} /* close namespace */
diff --git a/pool/shard002/C++/0034708_QxSqlLimit.cpp b/pool/shard002/C++/0034708_QxSqlLimit.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..38e39348d4e257ce33df0e3f479e46c991e5d6dd
--- /dev/null
+++ b/pool/shard002/C++/0034708_QxSqlLimit.cpp
@@ -0,0 +1,110 @@
+/****************************************************************************
+**
+** http://www.qxorm.com/
+** http://sourceforge.net/projects/qxorm/
+** Original file by Lionel Marty
+**
+** This file is part of the QxOrm library
+**
+** This software is provided 'as-is', without any express or implied
+** warranty. In no event will the authors be held liable for any
+** damages arising from the use of this software.
+**
+** GNU Lesser General Public License Usage
+** This file must be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file 'license.lgpl.txt' included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** If you have questions regarding the use of this file, please contact :
+** contact@qxorm.com
+**
+****************************************************************************/
+
+#include
+
+#include
+
+#include
+
+#include
+
+namespace qx {
+namespace dao {
+namespace detail {
+
+QxSqlLimit::QxSqlLimit(int index) : IxSqlElement(index) { ; }
+
+QxSqlLimit::~QxSqlLimit() { ; }
+
+QString QxSqlLimit::toString() const
+{
+ if (! m_pSqlGenerator) { qAssert(false); return ""; }
+ return m_pSqlGenerator->getLimit(this);
+}
+
+void QxSqlLimit::resolve(QSqlQuery & query) const
+{
+ if (! m_pSqlGenerator) { qAssert(false); return; }
+ m_pSqlGenerator->resolveLimit(query, this);
+}
+
+void QxSqlLimit::postProcess(QString & sql) const
+{
+ if (! m_pSqlGenerator) { qAssert(false); return; }
+ m_pSqlGenerator->postProcess(sql, this);
+}
+
+int QxSqlLimit::getStartRow() const
+{
+ qAssert(m_lstValues.count() == 2);
+ return ((m_lstValues.count() > 0) ? m_lstValues.at(0).toInt() : 0);
+}
+
+int QxSqlLimit::getRowsCount() const
+{
+ qAssert(m_lstValues.count() == 2);
+ return ((m_lstValues.count() > 1) ? m_lstValues.at(1).toInt() : 0);
+}
+
+int QxSqlLimit::getMaxRow() const
+{
+ qAssert(m_lstValues.count() == 2);
+ return ((m_lstValues.count() > 1) ? (m_lstValues.at(0).toInt() + m_lstValues.at(1).toInt()) : 0);
+}
+
+QString QxSqlLimit::getStartRow_ParamKey() const
+{
+ QString sStartRow("offset_start_row");
+ sStartRow += "_" + QString::number(m_iIndex) + "_0";
+ if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sStartRow = "?"; }
+ else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sStartRow = "@" + sStartRow; }
+ else { sStartRow = ":" + sStartRow; }
+ return sStartRow;
+}
+
+QString QxSqlLimit::getRowsCount_ParamKey() const
+{
+ QString sRowsCount("limit_rows_count");
+ sRowsCount += "_" + QString::number(m_iIndex) + "_0";
+ if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sRowsCount = "?"; }
+ else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sRowsCount = "@" + sRowsCount; }
+ else { sRowsCount = ":" + sRowsCount; }
+ return sRowsCount;
+}
+
+QString QxSqlLimit::getMaxRow_ParamKey() const
+{
+ QString sMaxRow("offset_max_row");
+ sMaxRow += "_" + QString::number(m_iIndex) + "_0";
+ if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sMaxRow = "?"; }
+ else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sMaxRow = "@" + sMaxRow; }
+ else { sMaxRow = ":" + sMaxRow; }
+ return sMaxRow;
+}
+
+} // namespace detail
+} // namespace dao
+} // namespace qx
diff --git a/pool/shard002/C++/0034717_ThirdPartyUtil.cpp b/pool/shard002/C++/0034717_ThirdPartyUtil.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2b2718ab42a02542b348ec7088d764fc2bb9592c
--- /dev/null
+++ b/pool/shard002/C++/0034717_ThirdPartyUtil.cpp
@@ -0,0 +1,288 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ThirdPartyUtil.h"
+#include "nsNetUtil.h"
+#include "nsIServiceManager.h"
+#include "nsIHttpChannelInternal.h"
+#include "nsIDOMWindow.h"
+#include "nsILoadContext.h"
+#include "nsIPrincipal.h"
+#include "nsIScriptObjectPrincipal.h"
+#include "nsThreadUtils.h"
+
+NS_IMPL_ISUPPORTS1(ThirdPartyUtil, mozIThirdPartyUtil)
+
+nsresult
+ThirdPartyUtil::Init()
+{
+ NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_AVAILABLE);
+
+ nsresult rv;
+ mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID, &rv);
+ return rv;
+}
+
+// Determine if aFirstDomain is a different base domain to aSecondURI; or, if
+// the concept of base domain does not apply, determine if the two hosts are not
+// string-identical.
+nsresult
+ThirdPartyUtil::IsThirdPartyInternal(const nsCString& aFirstDomain,
+ nsIURI* aSecondURI,
+ bool* aResult)
+{
+ NS_ASSERTION(aSecondURI, "null URI!");
+
+ // Get the base domain for aSecondURI.
+ nsCString secondDomain;
+ nsresult rv = GetBaseDomain(aSecondURI, secondDomain);
+ if (NS_FAILED(rv))
+ return rv;
+
+ // Check strict equality.
+ *aResult = aFirstDomain != secondDomain;
+ return NS_OK;
+}
+
+// Get the URI associated with a window.
+already_AddRefed
+ThirdPartyUtil::GetURIFromWindow(nsIDOMWindow* aWin)
+{
+ nsCOMPtr scriptObjPrin = do_QueryInterface(aWin);
+ NS_ENSURE_TRUE(scriptObjPrin, NULL);
+
+ nsIPrincipal* prin = scriptObjPrin->GetPrincipal();
+ NS_ENSURE_TRUE(prin, NULL);
+
+ nsCOMPtr result;
+ prin->GetURI(getter_AddRefs(result));
+ return result.forget();
+}
+
+// Determine if aFirstURI is third party with respect to aSecondURI. See docs
+// for mozIThirdPartyUtil.
+NS_IMETHODIMP
+ThirdPartyUtil::IsThirdPartyURI(nsIURI* aFirstURI,
+ nsIURI* aSecondURI,
+ bool* aResult)
+{
+ NS_ENSURE_ARG(aFirstURI);
+ NS_ENSURE_ARG(aSecondURI);
+ NS_ASSERTION(aResult, "null outparam pointer");
+
+ nsCString firstHost;
+ nsresult rv = GetBaseDomain(aFirstURI, firstHost);
+ if (NS_FAILED(rv))
+ return rv;
+
+ return IsThirdPartyInternal(firstHost, aSecondURI, aResult);
+}
+
+// Determine if any URI of the window hierarchy of aWindow is foreign with
+// respect to aSecondURI. See docs for mozIThirdPartyUtil.
+NS_IMETHODIMP
+ThirdPartyUtil::IsThirdPartyWindow(nsIDOMWindow* aWindow,
+ nsIURI* aURI,
+ bool* aResult)
+{
+ NS_ENSURE_ARG(aWindow);
+ NS_ASSERTION(aResult, "null outparam pointer");
+
+ bool result;
+
+ // Get the URI of the window, and its base domain.
+ nsCOMPtr currentURI = GetURIFromWindow(aWindow);
+ NS_ENSURE_TRUE(currentURI, NS_ERROR_INVALID_ARG);
+
+ nsCString bottomDomain;
+ nsresult rv = GetBaseDomain(currentURI, bottomDomain);
+ if (NS_FAILED(rv))
+ return rv;
+
+ if (aURI) {
+ // Determine whether aURI is foreign with respect to currentURI.
+ rv = IsThirdPartyInternal(bottomDomain, aURI, &result);
+ if (NS_FAILED(rv))
+ return rv;
+
+ if (result) {
+ *aResult = true;
+ return NS_OK;
+ }
+ }
+
+ nsCOMPtr current = aWindow, parent;
+ nsCOMPtr parentURI;
+ do {
+ // We use GetScriptableParent rather than GetParent because we consider
+ //