diff --git a/pool/shard006/C++/0073974_binding.cc b/pool/shard006/C++/0073974_binding.cc new file mode 100644 index 0000000000000000000000000000000000000000..05849b6c14fe314b04811f3aba4b2d84f0ae4d10 --- /dev/null +++ b/pool/shard006/C++/0073974_binding.cc @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +namespace { + +inline void RandomBytes(const v8::FunctionCallbackInfo& info) { + assert(info[0]->IsArrayBufferView()); + auto view = info[0].As(); + auto byte_offset = view->ByteOffset(); + auto byte_length = view->ByteLength(); + assert(view->HasBuffer()); + auto buffer = view->Buffer(); + auto contents = buffer->GetBackingStore(); + auto data = static_cast(contents->Data()) + byte_offset; + assert(RAND_poll()); + auto rval = RAND_bytes(data, static_cast(byte_length)); + info.GetReturnValue().Set(rval > 0); +} + +inline void Initialize(v8::Local exports, + v8::Local module, + v8::Local context) { + auto isolate = context->GetIsolate(); + auto key = v8::String::NewFromUtf8( + isolate, "randomBytes").ToLocalChecked(); + auto value = v8::FunctionTemplate::New(isolate, RandomBytes) + ->GetFunction(context) + .ToLocalChecked(); + assert(exports->Set(context, key, value).IsJust()); + + const SSL_METHOD* method = TLSv1_2_server_method(); + assert(method != nullptr); +} + +} // anonymous namespace + +NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize) diff --git a/pool/shard006/C++/0073980_removeuiobjectmembervisitor.cpp b/pool/shard006/C++/0073980_removeuiobjectmembervisitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05cdc3ce72f08384e16ef20b28d52960115d209e --- /dev/null +++ b/pool/shard006/C++/0073980_removeuiobjectmembervisitor.cpp @@ -0,0 +1,142 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** Commercial Usage +** +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** +**************************************************************************/ + +#include "removeuiobjectmembervisitor.h" + +#include +#include + +#include + +using namespace QmlDesigner; +using namespace QmlDesigner::Internal; +using namespace QmlJS; +using namespace QmlJS::AST; + +RemoveUIObjectMemberVisitor::RemoveUIObjectMemberVisitor(QmlDesigner::TextModifier &modifier, + quint32 objectLocation): + QMLRewriter(modifier), + objectLocation(objectLocation) +{ +} + +bool RemoveUIObjectMemberVisitor::preVisit(Node *ast) +{ + parents.push(ast); + + return true; +} + +void RemoveUIObjectMemberVisitor::postVisit(Node *) +{ + parents.pop(); +} + +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiPublicMember *ast) { return visitObjectMember(ast); } +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectDefinition *ast) { return visitObjectMember(ast); } +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiSourceElement *ast) { return visitObjectMember(ast); } +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectBinding *ast) { return visitObjectMember(ast); } +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiScriptBinding *ast) { return visitObjectMember(ast); } +bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiArrayBinding *ast) { return visitObjectMember(ast); } + +// FIXME: duplicate code in the QmlJS::Rewriter class, remove this +bool RemoveUIObjectMemberVisitor::visitObjectMember(QmlJS::AST::UiObjectMember *ast) +{ + const quint32 memberStart = ast->firstSourceLocation().offset; + + if (memberStart == objectLocation) { + // found it + int start = objectLocation; + int end = ast->lastSourceLocation().end(); + + if (UiArrayBinding *parentArray = containingArray()) { + extendToLeadingOrTrailingComma(parentArray, ast, start, end); + } else { + includeSurroundingWhitespace(start, end); + } + + includeLeadingEmptyLine(start); + replace(start, end - start, QLatin1String("")); + + setDidRewriting(true); + + return false; + } else if (ast->lastSourceLocation().end() <= objectLocation) { + // optimization: if the location of the object-to-be-removed is not inside the current member, skip any children + return false; + } else { + // only visit children if the rewriting isn't done yet. + return !didRewriting(); + } +} + +UiArrayBinding *RemoveUIObjectMemberVisitor::containingArray() const +{ + if (parents.size() > 2) { + if (cast(parents[parents.size() - 2])) { + return cast(parents[parents.size() - 3]); + } + } + + return 0; +} + +// FIXME: duplicate code in the QmlJS::Rewriter class, remove this +void RemoveUIObjectMemberVisitor::extendToLeadingOrTrailingComma(QmlJS::AST::UiArrayBinding *parentArray, + QmlJS::AST::UiObjectMember *ast, + int &start, + int &end) const +{ + UiArrayMemberList *currentMember = 0; + for (UiArrayMemberList *it = parentArray->members; it; it = it->next) { + if (it->member == ast) { + currentMember = it; + break; + } + } + + if (!currentMember) + return; + + if (currentMember->commaToken.isValid()) { + // leading comma + start = currentMember->commaToken.offset; + if (includeSurroundingWhitespace(start, end)) + --end; + } else if (currentMember->next && currentMember->next->commaToken.isValid()) { + // trailing comma + end = currentMember->next->commaToken.end(); + includeSurroundingWhitespace(start, end); + } else { + // array with 1 element, so remove the complete binding + start = parentArray->firstSourceLocation().offset; + end = parentArray->lastSourceLocation().end(); + includeSurroundingWhitespace(start, end); + } +} diff --git a/pool/shard006/C++/0073981_DMS.cpp b/pool/shard006/C++/0073981_DMS.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bab8621a1df4fd7de96149a758cd0cdeb101f4c4 --- /dev/null +++ b/pool/shard006/C++/0073981_DMS.cpp @@ -0,0 +1,122 @@ +//------------------------------------------------------ +// @file DMS.cpp +// @version 1.0 +// +// @section License +// Copyright (C) 2016, SlashDevin +// +// 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. +// + +#include "DMS.h" + +#include + +//---------------------------------------------------------------- +// Note that no division is used, and shifts are on byte boundaries. Fast! + +void DMS_t::From( int32_t deg_1E7 ) +{ + const uint32_t E7 = 10000000UL; + + if (deg_1E7 < 0) { + deg_1E7 = -deg_1E7; + hemisphere = SOUTH_H; // or WEST_H + } else + hemisphere = NORTH_H; // or EAST_H + + const uint32_t div_E32 = 429; // 1e-07 * 2^32 + degrees = ((deg_1E7 >> 16) * div_E32) >> 16; + uint32_t remainder = deg_1E7 - degrees * E7; + + remainder *= 60; // to minutes * E7 + minutes = ((remainder >> 16) * div_E32) >> 16; + remainder -= minutes * E7; + + remainder *= 60; // to seconds * E7 + uint32_t secs = ((remainder >> 16) * div_E32) >> 16; + remainder -= secs * E7; + + const uint32_t div_1E4_E24 = 1677; // 0.00001 * 2^24 + seconds_frac = (((remainder >> 8) * div_1E4_E24) >> 16); // thousandths + seconds_whole = secs; + + // Carry if thousandths too big + if (seconds_frac >= 1000) { + seconds_frac -= 1000; + seconds_whole++; + if (seconds_whole >= 60) { + seconds_whole -= 60; + minutes++; + if (minutes >= 60) { + minutes -= 60; + degrees++; + } + } + } + +} // From + +//---------------------------------------------------------------- + +Print & operator << ( Print & outs, const DMS_t & dms ) +{ + if (dms.degrees < 10) + outs.write( '0' ); + outs.print( dms.degrees ); + outs.write( ' ' ); + if (dms.minutes < 10) + outs.write( '0' ); + outs.print( dms.minutes ); + outs.print( F("\' ") ); + if (dms.seconds_whole < 10) + outs.write( '0' ); + outs.print( dms.seconds_whole ); + outs.write( '.' ); + if (dms.seconds_frac < 100) + outs.write( '0' ); + if (dms.seconds_frac < 10) + outs.write( '0' ); + outs.print( dms.seconds_frac ); + outs.print( F("\" ") ); + + return outs; + +} // operator << + +//---------------------------------------------------------------- + +void DMS_t::printDDDMMmmmm( Print & outs ) const +{ + outs.print( degrees ); + + if (minutes < 10) + outs.print( '0' ); + outs.print( minutes ); + outs.print( '.' ); + + // Calculate the fractional minutes from the seconds, + // *without* using floating-point numbers. + + uint16_t mmmm = seconds_whole * 166; // same as 10000/60, less .66666... + mmmm += (seconds_whole * 2 + seconds_frac/2 ) / 3; // ... plus the remaining .66666 + // ... plus the seconds_frac, scaled by 10000/(60*1000) = 1/6, which + // is implemented above as 1/2 * 1/3 + + // print leading zeroes, if necessary + if (mmmm < 1000) + outs.print( '0' ); + if (mmmm < 100) + outs.print( '0' ); + if (mmmm < 10) + outs.print( '0' ); + outs.print( mmmm ); +} \ No newline at end of file diff --git a/pool/shard006/C++/0073983_developerview.cpp b/pool/shard006/C++/0073983_developerview.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d0e0a9eba6a38cab4c483ee328a184e97dfcda6 --- /dev/null +++ b/pool/shard006/C++/0073983_developerview.cpp @@ -0,0 +1,93 @@ +#include "developerview.h" + +#include +#include +#include + +DeveloperView::DeveloperView(QWidget *parent) : + QDockWidget("Developer View", parent, Qt::Window) +{ + _index = 0; + _sendButton = new QPushButton ("Send Command"); + _sendButton->setEnabled(false); + _sendButton->setDefault(true); + + _commandLine = new QLineEdit; + _commandLine->installEventFilter(this); + + _commandsSent = new QStringList; + + _history = new QTextEdit; + _history->setReadOnly(true); + + _console = new QTextEdit; + _console->setReadOnly(true); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(new QLabel ("Command:")); + + QHBoxLayout *commandLayout = new QHBoxLayout; + commandLayout->addWidget(_commandLine); + commandLayout->addWidget(_sendButton); + + mainLayout->addLayout(commandLayout); + mainLayout->addWidget(new QLabel("Commands sent:")); + mainLayout->addWidget(_history); + mainLayout->addWidget(new QLabel("Ginga Console")); + mainLayout->addWidget(_console); + + QWidget *dock = new QWidget; + dock->setLayout(mainLayout); + + setWidget(dock); + + connect (_sendButton, SIGNAL(pressed()), this, SLOT(sendButtonPressed())); + connect (_commandLine, SIGNAL(textChanged(QString)), this, SLOT(changeSendButtonStatus())); + connect (_commandLine, SIGNAL(returnPressed()), _sendButton, SLOT(click())); +} + +void DeveloperView::sendButtonPressed() +{ + QString currentCommand = _commandLine->text(); + _commandLine->clear(); + + if (currentCommand != "") + { + _commandsSent->append(currentCommand); + _index = _commandsSent->count(); + + emit sendCommandRequested(currentCommand); + _history->append(currentCommand); + } +} + +void DeveloperView::changeSendButtonStatus() +{ + _sendButton->setEnabled(_commandLine->text() != ""); +} + +bool DeveloperView::eventFilter(QObject *obj, QEvent *event) +{ + if (obj == _commandLine && event->type() == QEvent::KeyPress) + { + if (((QKeyEvent *)event)->key() == Qt::Key_Up) + { + if (_index > 0) + { + _index--; + _commandLine->setText(_commandsSent->at(_index)); + } + return true; + } + else if (((QKeyEvent *)event)->key() == Qt::Key_Down) + { + if (_index < _commandsSent->count() - 1) + { + _index++; + _commandLine->setText(_commandsSent->at(_index)); + } + return true; + } + } + return false; +} diff --git a/pool/shard006/C++/0073986_DOMFileSystem.cpp b/pool/shard006/C++/0073986_DOMFileSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..addd710590bdc228f25aa3fb141c7fc1ed6c2e7d --- /dev/null +++ b/pool/shard006/C++/0073986_DOMFileSystem.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2010 Google Inc. 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 Google Inc. 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 THE COPYRIGHT + * OWNER OR CONTRIBUTORS 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 "config.h" +#include "modules/filesystem/DOMFileSystem.h" + +#include "modules/filesystem/DOMFilePath.h" +#include "modules/filesystem/DirectoryEntry.h" +#include "modules/filesystem/ErrorCallback.h" +#include "modules/filesystem/FileCallback.h" +#include "modules/filesystem/FileEntry.h" +#include "modules/filesystem/FileSystemCallbacks.h" +#include "modules/filesystem/FileWriter.h" +#include "modules/filesystem/FileWriterBaseCallback.h" +#include "modules/filesystem/FileWriterCallback.h" +#include "modules/filesystem/MetadataCallback.h" +#include "platform/FileMetadata.h" +#include "platform/weborigin/DatabaseIdentifier.h" +#include "platform/weborigin/SecurityOrigin.h" +#include "public/platform/WebFileSystem.h" +#include "public/platform/WebFileSystemCallbacks.h" +#include "wtf/OwnPtr.h" +#include "wtf/text/StringBuilder.h" +#include "wtf/text/WTFString.h" + +namespace blink { + +// static +DOMFileSystem* DOMFileSystem::create(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL) +{ + DOMFileSystem* fileSystem(new DOMFileSystem(context, name, type, rootURL)); + fileSystem->suspendIfNeeded(); + return fileSystem; +} + +DOMFileSystem* DOMFileSystem::createIsolatedFileSystem(ExecutionContext* context, const String& filesystemId) +{ + if (filesystemId.isEmpty()) + return 0; + + StringBuilder filesystemName; + filesystemName.append(createDatabaseIdentifierFromSecurityOrigin(context->securityOrigin())); + filesystemName.appendLiteral(":Isolated_"); + filesystemName.append(filesystemId); + + // The rootURL created here is going to be attached to each filesystem request and + // is to be validated each time the request is being handled. + StringBuilder rootURL; + rootURL.appendLiteral("filesystem:"); + rootURL.append(context->securityOrigin()->toString()); + rootURL.append('/'); + rootURL.append(isolatedPathPrefix); + rootURL.append('/'); + rootURL.append(filesystemId); + rootURL.append('/'); + + return DOMFileSystem::create(context, filesystemName.toString(), FileSystemTypeIsolated, KURL(ParsedURLString, rootURL.toString())); +} + +DOMFileSystem::DOMFileSystem(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL) + : DOMFileSystemBase(context, name, type, rootURL) + , ActiveDOMObject(context) + , m_numberOfPendingCallbacks(0) +{ +} + +DirectoryEntry* DOMFileSystem::root() +{ + return DirectoryEntry::create(this, DOMFilePath::root); +} + +void DOMFileSystem::addPendingCallbacks() +{ + ++m_numberOfPendingCallbacks; +} + +void DOMFileSystem::removePendingCallbacks() +{ + ASSERT(m_numberOfPendingCallbacks > 0); + --m_numberOfPendingCallbacks; +} + +bool DOMFileSystem::hasPendingActivity() const +{ + ASSERT(m_numberOfPendingCallbacks >= 0); + return m_numberOfPendingCallbacks; +} + +void DOMFileSystem::reportError(ErrorCallback* errorCallback, FileError* fileError) +{ + scheduleCallback(errorCallback, fileError); +} + +namespace { + +class ConvertToFileWriterCallback : public FileWriterBaseCallback { +public: + static ConvertToFileWriterCallback* create(FileWriterCallback* callback) + { + return new ConvertToFileWriterCallback(callback); + } + + void trace(Visitor* visitor) + { + visitor->trace(m_callback); + FileWriterBaseCallback::trace(visitor); + } + + void handleEvent(FileWriterBase* fileWriterBase) + { + m_callback->handleEvent(static_cast(fileWriterBase)); + } +private: + explicit ConvertToFileWriterCallback(FileWriterCallback* callback) + : m_callback(callback) + { + } + Member m_callback; +}; + +} + +void DOMFileSystem::createWriter(const FileEntry* fileEntry, FileWriterCallback* successCallback, ErrorCallback* errorCallback) +{ + ASSERT(fileEntry); + + if (!fileSystem()) { + reportError(errorCallback, FileError::create(FileError::ABORT_ERR)); + return; + } + + FileWriter* fileWriter = FileWriter::create(executionContext()); + FileWriterBaseCallback* conversionCallback = ConvertToFileWriterCallback::create(successCallback); + OwnPtr callbacks = FileWriterBaseCallbacks::create(fileWriter, conversionCallback, errorCallback, m_context); + fileSystem()->createFileWriter(createFileSystemURL(fileEntry), fileWriter, callbacks.release()); +} + +void DOMFileSystem::createFile(const FileEntry* fileEntry, FileCallback* successCallback, ErrorCallback* errorCallback) +{ + KURL fileSystemURL = createFileSystemURL(fileEntry); + if (!fileSystem()) { + reportError(errorCallback, FileError::create(FileError::ABORT_ERR)); + return; + } + + fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, SnapshotFileCallback::create(this, fileEntry->name(), fileSystemURL, successCallback, errorCallback, m_context)); +} + +void DOMFileSystem::trace(Visitor* visitor) +{ + DOMFileSystemBase::trace(visitor); + ActiveDOMObject::trace(visitor); +} + +} // namespace blink diff --git a/pool/shard006/C++/0073998_chan-quote.cpp b/pool/shard006/C++/0073998_chan-quote.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4da507819b82463404ea41e1649affe1ca1aacdf --- /dev/null +++ b/pool/shard006/C++/0073998_chan-quote.cpp @@ -0,0 +1,175 @@ +/* + chan-quote.cpp +*/ + +#include "../../../core/src/IRCBot/include/command-interface.hpp" +#include "../../../core/src/IRCBot/include/bot.hpp" +#include "../../../core/src/IRCBot/include/packet.hpp" + +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include + +#include +#include + +#include + +static inline void strip(std::string& s); + +class ChanQuotesPlugin : protected IRC::CommandInterface { + + const std::regex COMMAND_PATTERN{"^@((?:grab)|(?:rq))\\s*([-0-9a-zA-Z_]+)?"}; + const int LINES_TO_TRACK = 10; + + std::unordered_map> quotes; + + std::vector recorded_users; + + struct line { + std::string sender; + std::string msg; + }; + + std::vector last_n_lines; + int most_recent_line; + + std::minstd_rand gen; + + public: + + ChanQuotesPlugin() : IRC::CommandInterface("channel quotes", "@grab: take last line as quote; @rq [user] get a quote (optionally from a user)") { + gen.seed(std::chrono::system_clock::now().time_since_epoch().count()); + + most_recent_line = LINES_TO_TRACK; + last_n_lines.resize(LINES_TO_TRACK); + } + + bool triggered(const IRC::Packet& p) { + bool ans = false; + try { + std::vector::iterator it; + switch (p.type) { + case IRC::Packet::PacketType::NICK: + /* update nick changes. */ + quotes[p.content] = std::move(quotes[p.sender]); + quotes[p.sender].clear(); + + /* update vector of users */ + it = std::find(recorded_users.begin(), recorded_users.end(), p.sender); + if (it != recorded_users.end()) { + *it = p.content; + } + + break; + case IRC::Packet::PacketType::PRIVMSG: + ans = std::regex_search(p.content, COMMAND_PATTERN); + if (!ans) { + ++most_recent_line; + most_recent_line %= LINES_TO_TRACK; + + last_n_lines.at(most_recent_line) = {p.sender, p.content}; + + /* strip the whitespace */ + strip(last_n_lines.at(most_recent_line).msg); + } + break; + default: /* error occurs because of unhandled cases, so i put this line. */ + ; + } + } catch (std::exception& e) { + std::cerr << "Error in ChanQuotesPlugin::triggered(): " << e.what() << "\n"; + ans = false; + } + /* if we get here, it isn't a privmsg. */ + return ans; + } + + void run(const IRC::Packet& p) { + try { + std::smatch match; + std::regex_search(p.content, match, COMMAND_PATTERN); + + /* add quote if that's what was requested. */ + if (match[1] == "grab") { + int optional_offset; + try { + optional_offset = std::stoi(match[2].str()); + if (optional_offset < 0 || optional_offset >= LINES_TO_TRACK) { + std::stringstream err; + err << "\x03" << "04Invalid index.\x0f"; + p.reply(err.str()); + return; + } + + optional_offset %= LINES_TO_TRACK; + } catch (...) { + optional_offset = 0; + } + + int index = most_recent_line - optional_offset; + const line& last_line = last_n_lines.at(index < 0 ? index + LINES_TO_TRACK : index); + + /* this is how we know that last_line wasn't default initialized. */ + if (!last_line.sender.empty()) + quotes[last_line.sender].push_back(last_line.msg); + + /* this is how we can tell if the user hasn't yet been quoted */ + if (quotes[last_line.sender].size() <= 1) { + recorded_users.push_back(last_line.sender); + } + + std::stringstream res; + res << "Grabbed: \"" << quotes[last_line.sender].back() << "\" -- " << last_line.sender; + p.reply(res.str()); + return; + } + + /* if we get here, we are serving a random quote. */ + std::stringstream quote; + + /* avoiding sigfpe */ + if (recorded_users.empty()) { + p.reply("No quotes available."); + return; + } + + const std::string& user = match[2].str().empty() ? recorded_users.at(gen() % recorded_users.size()) : match[2].str(); + + if (quotes[user].empty()) { + quote << "No quotes available from that user."; + } else { + quote << "\"" << quotes[user].at(gen() % quotes[user].size()) << "\" -- " << user; + } + p.reply(quote.str()); + } catch (std::exception& e) { + std::cerr << "Error in ChanQuotesPlugin::run(): " << e.what() << "\n"; + } + } +}; + +extern "C" IRC::CommandInterface* maker(IRC::Bot* b = nullptr) { + return (IRC::CommandInterface*)(new ChanQuotesPlugin); +} + +static inline void strip(std::string& s) { + /* trim left side */ + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { + return !std::isspace(ch); + })); + + /* trim right side */ + s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { + return !std::isspace(ch); + }).base(), s.end()); +} diff --git a/pool/shard006/C++/0073999_xml_viewer.cpp b/pool/shard006/C++/0073999_xml_viewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2ff4b22e31001248c9f14e5fc34c0e95dae3ee5 --- /dev/null +++ b/pool/shard006/C++/0073999_xml_viewer.cpp @@ -0,0 +1,34 @@ +#include "xml_viewer.h" +#include "ui_xml_viewer.h" + +#include "acbrlib.h" +#include "application.h" + +XML_Viewer::XML_Viewer(const QString &content, QWidget *parent) : QDialog(parent), xml(content), ui(new Ui::XML_Viewer) { + ui->setupUi(this); + + setWindowFlags(Qt::Window); + + ui->treeView->setModel(&xml.model); + ui->treeView->expandAll(); + + setConnections(); + + show(); +} + +XML_Viewer::~XML_Viewer() { delete ui; } + +void XML_Viewer::setConnections() { + const auto connectionType = static_cast(Qt::AutoConnection | Qt::UniqueConnection); + + connect(ui->pushButtonDanfe, &QPushButton::clicked, this, &XML_Viewer::on_pushButtonDanfe_clicked, connectionType); +} + +void XML_Viewer::on_pushButtonDanfe_clicked() { +#ifdef Q_OS_WIN + ACBrLib::gerarDanfe(xml.fileContent, true); +#else + throw RuntimeException("Não implementado para linux!"); +#endif +} diff --git a/pool/shard006/C++/0074000_DeviceOpenGL.cpp b/pool/shard006/C++/0074000_DeviceOpenGL.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02656fc6e6b6275e1ba481a58269514a41639c52 --- /dev/null +++ b/pool/shard006/C++/0074000_DeviceOpenGL.cpp @@ -0,0 +1,164 @@ +/******************************************************************************* + Copyright ©2014 Advanced Micro Devices, Inc. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1 Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2 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. + + 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. + ******************************************************************************/ + +/** + ******************************************************************************* + * @file + * + * @brief Source file for OpenGL Device + * + ******************************************************************************* + */ + +#include "DeviceOpenGL.h" +#include "CmdLogger.h" +#include + +#pragma comment(lib, "opengl32.lib") + + +static bool ReportGLErrors(const char* file, int line) +{ + unsigned int err = glGetError(); + if(err != GL_NO_ERROR) + { + std::wstringstream ss; + ss << "GL failed. Error numbers: "; + while(err != GL_NO_ERROR) + { + ss << std::hex << err << ", "; + err = glGetError(); + } + ss << std::dec << " file: " << file << ", line: " << line; + LOG_ERROR(ss.str()); + return false; + } + return true; +} + + +#define CALL_GL(exp) \ +{ \ + exp; \ + if( !ReportGLErrors(__FILE__, __LINE__) ) return AMF_FAIL; \ +} + +DeviceOpenGL::DeviceOpenGL() : + m_hDC(NULL), + m_hContextOGL(NULL), + m_hWnd(NULL), + m_adaptersCount(0) +{ + memset(m_adaptersIndexes, 0, sizeof(m_adaptersIndexes)); +} + +DeviceOpenGL::~DeviceOpenGL() +{ + Terminate(); +} + +AMF_RESULT DeviceOpenGL::Init(HWND hWnd, const wchar_t* displayDeviceName) +{ + DWORD error = 0; + + if(hWnd == ::GetDesktopWindow() && displayDeviceName) + { + LOG_INFO("OPENGL : Choosen Device " << displayDeviceName); + m_hDC = CreateDC(displayDeviceName, NULL, NULL, NULL); + } + else + { + m_hWnd = hWnd; + m_hDC = GetDC(hWnd); + } + if(!m_hDC) + { + LOG_ERROR("Could not GetDC. Error: " << GetLastError()); + return AMF_FAIL; + } + + static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be + { + sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor + 1, // Version Number + PFD_DRAW_TO_WINDOW | // Format Must Support Window + PFD_SUPPORT_OPENGL | // Format Must Support OpenGL + PFD_DOUBLEBUFFER, // Must Support Double Buffering + PFD_TYPE_RGBA, // Request An RGBA Format + 24, // Select Our Color Depth + 0, 0, 0, 0, 0, 0, // Color Bits Ignored + 0, // No Alpha Buffer + 0, // Shift Bit Ignored + 0, // No Accumulation Buffer + 0, 0, 0, 0, // Accumulation Bits Ignored + 16, // 16Bit Z-Buffer (Depth Buffer) + 0, // No Stencil Buffer + 0, // No Auxiliary Buffer + PFD_MAIN_PLANE, // Main Drawing Layer + 0, // Reserved + 0, 0, 0 // Layer Masks Ignored + }; + + GLuint pixelFormat = (GLuint)ChoosePixelFormat(m_hDC, &pfd); + + BOOL res = SetPixelFormat(m_hDC, (int)pixelFormat, &pfd); + if(!res) + { + LOG_ERROR("SetPixelFormat() failed. Error: " << GetLastError()); + return AMF_FAIL; + } + + m_hContextOGL= wglCreateContext(m_hDC); + if(!m_hContextOGL) + { + LOG_ERROR("wglCreateContext() failed. Error: " << GetLastError()); + return AMF_FAIL; + } + return AMF_OK; +} + +AMF_RESULT DeviceOpenGL::Terminate() +{ + if(m_hContextOGL) + { + wglMakeCurrent( NULL , NULL ); + wglDeleteContext(m_hContextOGL); + m_hContextOGL = NULL; + } + if(m_hDC) + { + if(m_hWnd == NULL) + { + ::DeleteDC(m_hDC); + } + else + { + ::ReleaseDC(m_hWnd, m_hDC); + } + m_hDC = NULL; + m_hWnd = NULL; + } + return AMF_OK; +} diff --git a/pool/shard006/C++/0074003_RifCsvUserData.cpp b/pool/shard006/C++/0074003_RifCsvUserData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68eba6c62567ece5d699898dcf1f79ffaff146a4 --- /dev/null +++ b/pool/shard006/C++/0074003_RifCsvUserData.cpp @@ -0,0 +1,168 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2017- Statoil ASA +// +// ResInsight 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. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RifCsvUserData.h" + +#include "RiaDateStringParser.h" +#include "RiaLogging.h" +#include "RiaQDateTimeTools.h" + +#include "RifCsvUserDataParser.h" +#include "RifEclipseUserDataKeywordTools.h" +#include "RifEclipseUserDataParserTools.h" + +#include "cafUtils.h" + +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RifCsvUserData::RifCsvUserData() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RifCsvUserData::~RifCsvUserData() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifCsvUserData::parse( const QString& fileName, const AsciiDataParseOptions& parseOptions, QString* errorText ) +{ + m_allResultAddresses.clear(); + m_mapFromAddressToResultIndex.clear(); + + m_parser = std::unique_ptr( new RifCsvUserDataFileParser( fileName, errorText ) ); + if ( !m_parser->parse( parseOptions ) ) + { + RiaLogging::error( QString( "Failed to parse file" ) ); + return false; + } + + buildTimeStepsAndMappings(); + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifCsvUserData::values( const RifEclipseSummaryAddress& resultAddress, std::vector* values ) const +{ + auto search = m_mapFromAddressToResultIndex.find( resultAddress ); + if ( search != m_mapFromAddressToResultIndex.end() ) + { + size_t columnIndex = search->second; + + const Column* ci = m_parser->columnInfo( columnIndex ); + if ( !ci ) return false; + + values->clear(); + values->reserve( ci->values.size() ); + for ( double val : ci->values ) + { + values->push_back( val ); + } + } + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +const std::vector& RifCsvUserData::timeSteps( const RifEclipseSummaryAddress& resultAddress ) const +{ + // First, check whether date time values exist for the current address + auto search = m_mapFromAddressToResultIndex.find( resultAddress ); + if ( search != m_mapFromAddressToResultIndex.end() ) + { + size_t index = m_mapFromAddressToResultIndex.at( resultAddress ); + if ( !m_parser->tableData().columnInfos()[index].dateTimeValues.empty() ) + { + return m_parser->tableData().columnInfos()[index].dateTimeValues; + } + } + + // Then check for a separate date time column + int index = m_parser->tableData().dateTimeColumnIndex(); + if ( index >= 0 ) + { + return m_parser->tableData().columnInfos()[index].dateTimeValues; + } + + static std::vector emptyVector; + return emptyVector; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::string RifCsvUserData::unitName( const RifEclipseSummaryAddress& resultAddress ) const +{ + auto search = m_mapFromAddressToResultIndex.find( resultAddress ); + if ( search != m_mapFromAddressToResultIndex.end() ) + { + size_t columnIndex = search->second; + + const Column* ci = m_parser->columnInfo( columnIndex ); + if ( ci ) + { + return ci->unitName; + } + } + + return ""; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RiaDefines::EclipseUnitSystem RifCsvUserData::unitSystem() const +{ + return RiaDefines::EclipseUnitSystem::UNITS_UNKNOWN; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifCsvUserData::buildTimeStepsAndMappings() +{ + auto tableData = m_parser->tableData(); + + for ( size_t columnIndex = 0; columnIndex < tableData.columnInfos().size(); columnIndex++ ) + { + const Column& ci = tableData.columnInfos()[columnIndex]; + if ( ci.dataType == Column::NUMERIC ) + { + RifEclipseSummaryAddress sumAddress = ci.summaryAddress; + + m_allResultAddresses.insert( sumAddress ); + if ( sumAddress.isErrorResult() ) m_allErrorAddresses.insert( sumAddress ); + + m_mapFromAddressToResultIndex[sumAddress] = columnIndex; + } + } +} diff --git a/pool/shard006/C++/0074007_Client.cpp b/pool/shard006/C++/0074007_Client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2198ea0e0ca4d749f3a508c39ea439d8d3e803a --- /dev/null +++ b/pool/shard006/C++/0074007_Client.cpp @@ -0,0 +1,84 @@ +#include "Client.h" +#include "Server.h" + +namespace core +{ +Client::Client() +{ + send_buffer_.Init(SEND_BUFFER_SIZE); + recv_buffer_.Init(RECV_BUFFER_SIZE); +} +Client::~Client() +{ +} +BOOL Client::PrepareReceive() +{ + IoContext * recv_ready_context = Server::io_context_pool_->Construct(IoContext(this, IO_RECV_READY)); + DWORD recieved_bytes = 0; + DWORD flags = 0; + + if (WSARecv(socket_, &recv_ready_context->buffer_, 1, &recieved_bytes, &flags, (LPWSAOVERLAPPED)recv_ready_context, NULL) == SOCKET_ERROR) { + if (WSAGetLastError() != WSA_IO_PENDING) { + printf("Prepare WSARecv %d\n", WSAGetLastError()); + return FALSE; + } + } + return TRUE; +} +BOOL Client::Receive() +{ + IoContext * recv_context = Server::io_context_pool_->Construct(IoContext(this, IO_RECV)); + DWORD recieved_bytes = 0; + DWORD flags = 0; + recv_context->buffer_.len = recv_buffer_.GetRemained(); + recv_context->buffer_.buf = recv_buffer_.GetBuffer(); + + if (WSARecv(socket_, &recv_context->buffer_, 1, &recieved_bytes, &flags, (LPWSAOVERLAPPED)recv_context, NULL) == SOCKET_ERROR) { + if (WSAGetLastError() != WSA_IO_PENDING) { + printf("WSARecv %d\n", WSAGetLastError()); + return FALSE; + } + } + return TRUE; +} +BOOL Client::PostReceive(DWORD received_bytes, std::function& handler, IoContext& io_context) +{ + UWORD packet_size = ((UWORD)*(recv_buffer_.Read())); + if(received_bytes >= packet_size - recv_buffer_.offset_) + { + recv_buffer_.Produce(Server::packet_header_size_ + packet_size); + handler(&io_context); + recv_buffer_.Consume(Server::packet_header_size_ + packet_size); + } + return TRUE; +} +BOOL Client::Send(char * data, DWORD size) +{ + IoContext * send_context = Server::io_context_pool_->Construct(IoContext(this, IO_SEND)); + DWORD sent; + + memcpy(send_buffer_.GetBuffer(), data, size); + send_context->buffer_.len = size; + send_context->buffer_.buf = send_buffer_.GetBuffer(); + send_buffer_.Produce(size); + + if (WSASend(socket_, &(send_context->buffer_), 1, &sent, 0, (LPWSAOVERLAPPED)send_context, nullptr) == SOCKET_ERROR) { + if (WSAGetLastError() != WSA_IO_PENDING) { + printf("WSASend %d\n", WSAGetLastError()); + return FALSE; + } + } + return TRUE; +} +BOOL Client::PostSend(DWORD sent_bytes) +{ + send_buffer_.Consume(sent_bytes); + return TRUE; +} +BOOL Client::Disconnect() +{ + IoContext * disconnect_context = Server::io_context_pool_->Construct(IoContext(this, IO_DISCONNECT)); + core::Server::DisconnectEx(socket_, (LPWSAOVERLAPPED)disconnect_context, 0, 0); + return 0; +} +} \ No newline at end of file diff --git a/pool/shard006/C++/0074014_quiz3.cpp b/pool/shard006/C++/0074014_quiz3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b71f72d03364669e969ff2d0efb57f4a16ed669e --- /dev/null +++ b/pool/shard006/C++/0074014_quiz3.cpp @@ -0,0 +1,119 @@ +#include "stdafx.h" +#include +#include + +class IntArray +{ +public: + IntArray(int size) + : m_size(size) + { + m_array = new int[size]; + } + + IntArray(const IntArray &intArray) + { + resize(intArray); + } + + ~IntArray() + { + delete[] m_array; + } + + int& operator[] (const int index); + const int& operator[] (const int index) const; + IntArray& IntArray::operator= (const IntArray &intArray); + friend std::ostream& operator<<(std::ostream& out, const IntArray& intArray); + + void resize(const IntArray& intArray); + void copyToInternalArray(const IntArray& intArray) const; + +private: + int m_size; + int *m_array; +}; + +void IntArray::resize(const IntArray& intArray) +{ + delete[] m_array; + m_size = intArray.m_size; + m_array = new int[intArray.m_size]; + copyToInternalArray(intArray); +} + +void IntArray::copyToInternalArray(const IntArray& intArray) const +{ + for (int i = 0; i < intArray.m_size; i++) + { + m_array[i] = intArray.m_array[i]; + } +} + +IntArray& IntArray::operator= (const IntArray &intArray) +{ + // self-assignment guard + if (this == &intArray) + return *this; + + resize(intArray); + + // return the existing object so we can chain this operator + return *this; +} + +int& IntArray::operator[] (const int index) // for non-const objects: can be used for assignment +{ + assert(index >= 0 && index < m_size); + + return m_array[index]; +} + +const int& IntArray::operator[] (const int index) const // for const objects: can only be used for access +{ + assert(index >= 0 && index < m_size); + + return m_array[index]; +} + +std::ostream& operator<<(std::ostream& out, const IntArray& intArray) +{ + for(int i=0; i preorderTraversal(TreeNode *root) { + stack nodeStack; + vector result; + //base case + if(root==NULL) + return result; + nodeStack.push(root); + while(!nodeStack.empty()) + { + TreeNode* node= nodeStack.top(); + result.push_back(node->val); + nodeStack.pop(); + if(node->right) + nodeStack.push(node->right); + if(node->left) + nodeStack.push(node->left); + } + return result; + + } +}; +class Solution { +public: + vector preorderTraversal(TreeNode *root) { + if (!root) + return vector(); + + vector ans; + list s; + s.push_back(root); + while (!s.empty()) { + auto head = s.front(); + s.erase(s.begin()); + ans.push_back(head->val); + if (head->right) + s.push_front(head->right); + if (head->left) + s.push_front(head->left); + } + return ans; + } +}; diff --git a/pool/shard006/C++/0074016_x11_event_source_glib.cc b/pool/shard006/C++/0074016_x11_event_source_glib.cc new file mode 100644 index 0000000000000000000000000000000000000000..f56ed8bb95c4a3a76ce1e25c9d705e06c3195baa --- /dev/null +++ b/pool/shard006/C++/0074016_x11_event_source_glib.cc @@ -0,0 +1,102 @@ +// Copyright 2014 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 "ui/events/platform/x11/x11_event_source_glib.h" + +#include +#include + +#include "base/memory/ptr_util.h" + +namespace ui { + +namespace { + +struct GLibX11Source : public GSource { + // Note: The GLibX11Source is created and destroyed by GLib. So its + // constructor/destructor may or may not get called. + XDisplay* display; + GPollFD* poll_fd; +}; + +gboolean XSourcePrepare(GSource* source, gint* timeout_ms) { + GLibX11Source* gxsource = static_cast(source); + if (XPending(gxsource->display)) + *timeout_ms = 0; + else + *timeout_ms = -1; + return FALSE; +} + +gboolean XSourceCheck(GSource* source) { + GLibX11Source* gxsource = static_cast(source); + return XPending(gxsource->display); +} + +gboolean XSourceDispatch(GSource* source, + GSourceFunc unused_func, + gpointer data) { + X11EventSource* x11_source = static_cast(data); + x11_source->DispatchXEvents(); + return TRUE; +} + +GSourceFuncs XSourceFuncs = { + XSourcePrepare, + XSourceCheck, + XSourceDispatch, + NULL +}; + +} // namespace + +X11EventSourceGlib::X11EventSourceGlib(XDisplay* display) + : event_source_(this, display) { + InitXSource(ConnectionNumber(display)); +} + +X11EventSourceGlib::~X11EventSourceGlib() { + g_source_destroy(x_source_); + g_source_unref(x_source_); +} + +void X11EventSourceGlib::ProcessXEvent(XEvent* xevent) { + DispatchEvent(xevent); +} + +void X11EventSourceGlib::StopCurrentEventStream() { + event_source_.StopCurrentEventStream(); +} + +void X11EventSourceGlib::OnDispatcherListChanged() { + event_source_.OnDispatcherListChanged(); +} + +void X11EventSourceGlib::InitXSource(int fd) { + DCHECK(!x_source_); + DCHECK(event_source_.display()) << "Unable to get connection to X server"; + + x_poll_.reset(new GPollFD()); + x_poll_->fd = fd; + x_poll_->events = G_IO_IN; + x_poll_->revents = 0; + + GLibX11Source* glib_x_source = static_cast( + g_source_new(&XSourceFuncs, sizeof(GLibX11Source))); + glib_x_source->display = event_source_.display(); + glib_x_source->poll_fd = x_poll_.get(); + + x_source_ = glib_x_source; + g_source_add_poll(x_source_, x_poll_.get()); + g_source_set_can_recurse(x_source_, TRUE); + g_source_set_callback(x_source_, NULL, &event_source_, NULL); + g_source_attach(x_source_, g_main_context_default()); +} + +// static +std::unique_ptr PlatformEventSource::CreateDefault() { + return base::WrapUnique(new X11EventSourceGlib(gfx::GetXDisplay())); +} + +} // namespace ui diff --git a/pool/shard006/C++/0074017_runtimecolorfilter.cpp b/pool/shard006/C++/0074017_runtimecolorfilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a105de235e615da309cc7379f06cf80402195ee --- /dev/null +++ b/pool/shard006/C++/0074017_runtimecolorfilter.cpp @@ -0,0 +1,199 @@ +/* + * Copyright 2019 Google LLC + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "gm/gm.h" +#include "include/core/SkCanvas.h" +#include "include/core/SkColorFilter.h" +#include "include/core/SkData.h" +#include "include/core/SkImage.h" +#include "include/core/SkPaint.h" +#include "include/core/SkRSXform.h" +#include "include/core/SkRefCnt.h" +#include "include/core/SkSize.h" +#include "include/core/SkString.h" +#include "include/core/SkSurface.h" +#include "include/core/SkVertices.h" +#include "include/effects/SkRuntimeEffect.h" +#include "tools/Resources.h" + +#include +#include + +const char* gNoop = R"( + half4 main(half4 color) { + return color; + } +)"; + +const char* gLumaSrc = R"( + half4 main(half4 color) { + return dot(color.rgb, half3(0.3, 0.6, 0.1)).000r; + } +)"; + +// Build up the same effect with increasingly complex control flow syntax. +// All of these are semantically equivalent and can be reduced in principle to one basic block. + +// Simplest to run; hardest to write? +const char* gTernary = R"( + half4 main(half4 color) { + half luma = dot(color.rgb, half3(0.3, 0.6, 0.1)); + + half scale = luma < 0.33333 ? 0.5 + : luma < 0.66666 ? (0.166666 + 2.0 * (luma - 0.33333)) / luma + : /* else */ (0.833333 + 0.5 * (luma - 0.66666)) / luma; + return half4(color.rgb * scale, color.a); + } +)"; + +// Uses conditional if statements but no early return. +const char* gIfs = R"( + half4 main(half4 color) { + half luma = dot(color.rgb, half3(0.3, 0.6, 0.1)); + + half scale = 0; + if (luma < 0.33333) { + scale = 0.5; + } else if (luma < 0.66666) { + scale = (0.166666 + 2.0 * (luma - 0.33333)) / luma; + } else { + scale = (0.833333 + 0.5 * (luma - 0.66666)) / luma; + } + return half4(color.rgb * scale, color.a); + } +)"; + +// Distilled from AOSP tone mapping shaders, more like what people tend to write. +const char* gEarlyReturn = R"( + half4 main(half4 color) { + half luma = dot(color.rgb, half3(0.3, 0.6, 0.1)); + + half scale = 0; + if (luma < 0.33333) { + return half4(color.rgb * 0.5, color.a); + } else if (luma < 0.66666) { + scale = 0.166666 + 2.0 * (luma - 0.33333); + } else { + scale = 0.833333 + 0.5 * (luma - 0.66666); + } + return half4(color.rgb * (scale/luma), color.a); + } +)"; + + +DEF_SIMPLE_GM(runtimecolorfilter, canvas, 256 * 3, 256 * 2) { + sk_sp img = GetResourceAsImage("images/mandrill_256.png"); + + auto draw_filter = [&](const char* src) { + auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(src)); + if (!effect) { + SkDebugf("%s\n%s\n", src, err.c_str()); + } + SkASSERT(effect); + SkPaint p; + p.setColorFilter(effect->makeColorFilter(nullptr)); + canvas->drawImage(img, 0, 0, SkSamplingOptions(), &p); + canvas->translate(256, 0); + }; + + for (const char* src : { gNoop, gLumaSrc }) { + draw_filter(src); + } + canvas->translate(-256*2, 256); + for (const char* src : { gTernary, gIfs, gEarlyReturn}) { + draw_filter(src); + } +} + +DEF_SIMPLE_GM(runtimecolorfilter_vertices_atlas_and_patch, canvas, 404, 404) { + constexpr SkRect r = SkRect::MakeWH(128, 128); + + // Make a vertices that draws the same as SkRect 'r'. + SkPoint pos[4]; + r.toQuad(pos); + constexpr SkColor kColors[] = {SK_ColorBLUE, SK_ColorGREEN, SK_ColorCYAN, SK_ColorYELLOW}; + auto verts = SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, 4, pos, pos, kColors); + + // Make an image from the vertices to do equivalent drawAtlas, drawPatch using an image shader. + auto info = SkImageInfo::Make({128, 128}, + kRGBA_8888_SkColorType, + kPremul_SkAlphaType, + canvas->imageInfo().refColorSpace()); + auto surf = SkSurface::MakeRaster(info); + surf->getCanvas()->drawVertices(verts, SkBlendMode::kDst, SkPaint()); + auto atlas = surf->makeImageSnapshot(); + auto xform = SkRSXform::Make(1, 0, 0, 0); + + // Make a patch that draws the same as the SkRect 'r' + SkVector vx = pos[1] - pos[0]; + SkVector vy = pos[3] - pos[0]; + vx.setLength(vx.length()/3.f); + vy.setLength(vy.length()/3.f); + const SkPoint cubics[12] = { + pos[0], pos[0] + vx, pos[1] - vx, + pos[1], pos[1] + vy, pos[2] - vy, + pos[2], pos[2] - vx, pos[3] + vx, + pos[3], pos[3] - vy, pos[0] + vy + }; + + auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(gLumaSrc)); + if (!effect) { + SkDebugf("%s\n%s\n", gLumaSrc, err.c_str()); + } + SkASSERT(effect); + sk_sp colorfilter = effect->makeColorFilter(nullptr); + + auto makePaint = [&](bool useCF, bool useShader) { + SkPaint paint; + paint.setColorFilter(useCF ? colorfilter : nullptr); + paint.setShader(useShader ? atlas->makeShader(SkSamplingOptions{}) : nullptr); + return paint; + }; + + auto drawVertices = [&](float x, bool useCF, bool useShader) { + SkAutoCanvasRestore acr(canvas, /*doSave=*/true); + canvas->translate(x, 0); + // Use just the shader or just the vertex colors. + auto mode = useShader ? SkBlendMode::kSrc : SkBlendMode::kDst; + canvas->drawVertices(verts, mode, makePaint(useCF, useShader)); + }; + + auto drawAtlas = [&](float x, bool useCF) { + SkAutoCanvasRestore acr(canvas, /*doSave=*/true); + canvas->translate(x, 0); + SkPaint paint = makePaint(useCF, /*useShader=*/false); + constexpr SkColor kColor = SK_ColorWHITE; + canvas->drawAtlas(atlas.get(), + &xform, + &r, + &kColor, + 1, + SkBlendMode::kModulate, + SkSamplingOptions{}, + nullptr, + &paint); + }; + + auto drawPatch = [&](float x, bool useCF) { + SkAutoCanvasRestore acr(canvas, true); + canvas->translate(x, 0); + SkPaint paint = makePaint(useCF, /*useShader=*/true); + canvas->drawPatch(cubics, nullptr, pos, SkBlendMode::kModulate, paint); + }; + + drawVertices( 0, /*useCF=*/false, /*useShader=*/false); + drawVertices( r.width() + 10, /*useCF=*/ true, /*useShader=*/false); + drawVertices(2*(r.width() + 10), /*useCF=*/ true, /*useShader=*/ true); + + canvas->translate(0, r.height() + 10); + drawAtlas( 0, /*useCF=*/false); + drawAtlas(r.width() + 10, /*useCF=*/ true); + + canvas->translate(0, r.height() + 10); + drawPatch( 0, /*useCF=*/false); + drawPatch(r.width() + 10, /*useCF=*/ true); +} diff --git a/pool/shard006/C++/0074020_proto2.cpp b/pool/shard006/C++/0074020_proto2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7187e34a647c9bd8bb2cf0645564975bc26fce80 --- /dev/null +++ b/pool/shard006/C++/0074020_proto2.cpp @@ -0,0 +1,121 @@ +/*BEGIN_LEGAL +Intel Open Source License + +Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation 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 THE INTEL OR +ITS CONTRIBUTORS 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. +END_LEGAL */ + +/* ===================================================================== */ +/*! @file + Replace an original function with a custom function defined in the tool. The + new function can have either the same or different signature from that of its + original function. +*/ + +/* ===================================================================== */ +#include "pin.H" +#include +#include + +using namespace std; + +/* ===================================================================== */ +VOID Boo( UINT32 num0, UINT32 num1, UINT32 arg0, UINT32 arg1, + UINT32 num2, UINT32 num3, UINT32 num4, + UINT32 arg2, UINT32 arg3 ) +{ + cout << "Original Arguments = ( " + << arg0 << ", " + << arg1 << ", " + << arg2 << ", " + << arg3 << " )" + << endl << flush; + + cout << "New Arguments = ( " + << num0 << ", " + << num1 << ", " + << num2 << ", " + << num3 << ", " + << num4 << " )" + << endl << flush; +} + +/* ===================================================================== */ +VOID ImageLoad(IMG img, VOID *v) +{ + cout << IMG_Name(img) << endl; + + PROTO proto = PROTO_Allocate( PIN_PARG(void), CALLINGSTD_DEFAULT, + "Bar", PIN_PARG(int), PIN_PARG(int), + PIN_PARG(int), PIN_PARG(int), + PIN_PARG_END() ); + + RTN rtn = RTN_FindByName(img, "Bar"); + if (RTN_Valid(rtn)) + { + if ( ! RTN_IsSafeForProbedReplacement( rtn ) ) + { + cout << "Cannot replace " << RTN_Name(rtn) << " in " << IMG_Name(img) << endl; + exit(1); + } + + cout << "Replacing " << RTN_Name(rtn) << " in " << IMG_Name(img) << endl; + + RTN_ReplaceSignatureProbed( + rtn, AFUNPTR(Boo), + IARG_PROTOTYPE, proto, + IARG_UINT32, 100, + IARG_UINT32, 200, + IARG_FUNCARG_ENTRYPOINT_VALUE, 0, + IARG_FUNCARG_ENTRYPOINT_VALUE, 1, + IARG_UINT32, 300, + IARG_UINT32, 400, + IARG_UINT32, 500, + IARG_FUNCARG_ENTRYPOINT_VALUE, 2, + IARG_FUNCARG_ENTRYPOINT_VALUE, 3, + IARG_END); + } + PROTO_Free( proto ); +} + +/* ===================================================================== */ +int main(INT32 argc, CHAR *argv[]) +{ + PIN_InitSymbols(); + + PIN_Init(argc, argv); + + IMG_AddInstrumentFunction(ImageLoad, 0); + + PIN_StartProgramProbed(); + + return 0; +} + +/* ===================================================================== */ +/* eof */ +/* ===================================================================== */ diff --git a/pool/shard006/C++/0074021_config.cpp b/pool/shard006/C++/0074021_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f5b1b2c660b8dfd9b1926d24d93c13944434ca4 --- /dev/null +++ b/pool/shard006/C++/0074021_config.cpp @@ -0,0 +1,98 @@ +#include "config.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "model/db.h" + +namespace ConfigDef{ + static const char GEO[] = "geometry"; + static const char STAT[] = "state"; + static const char MAX[] = "maximized"; + static const char POS[] = "pos"; + static const char SIZE[] = "size"; +} + + +Config Config::singleton; + +Config::Config() +{ + std::unique_ptr settings(getSettings()); +} + +Config::~Config() +{ + std::unique_ptr settings(getSettings()); + settings->sync(); +} + + +QSettings* Config::getSettings() +{ + fs::path p = Db::homeDir(); + QString ini = QString(p.c_str()) + "/murphoto.ini"; + return new QSettings(ini,QSettings::IniFormat); +} + +void Config::saveWidget(QWidget* widget) +{ + std::unique_ptr settings(getSettings()); + + + settings->beginGroup(widget->objectName()); + settings->setValue(ConfigDef::SIZE, widget->size()); + settings->setValue(ConfigDef::GEO, widget->saveGeometry()); + + for(;;){ + QMainWindow* mainwnd = qobject_cast(widget); + if (mainwnd != nullptr){ + settings->setValue(ConfigDef::STAT, mainwnd->saveState()); + settings->setValue(ConfigDef::POS, mainwnd->pos()); + settings->setValue(ConfigDef::MAX, mainwnd->isMaximized()); + break; + } + + break; + } + + settings->endGroup(); +} + +void Config::restoreWidget(QWidget* widget) +{ + std::unique_ptr settings(getSettings()); + + settings->beginGroup(widget->objectName()); + if (settings->contains(ConfigDef::GEO)){ + widget->resize(settings->value(ConfigDef::SIZE).toSize()); + widget->restoreGeometry(settings->value(ConfigDef::GEO).toByteArray()); + + for (;;){ + QMainWindow* mainwnd = qobject_cast(widget); + if (mainwnd != nullptr){ + mainwnd->restoreState(settings->value(ConfigDef::STAT).toByteArray()); + mainwnd->move(settings->value(ConfigDef::POS).toPoint()); + if (settings->value(ConfigDef::MAX).toBool()){ + mainwnd->showMaximized(); + } + break; + } + + break; + } + } + settings->endGroup(); + +} + +QString Config::getConfigFilename(){ + return getSettings()->fileName(); +} diff --git a/pool/shard006/C++/0074028_fib_bench.cc b/pool/shard006/C++/0074028_fib_bench.cc new file mode 100644 index 0000000000000000000000000000000000000000..f1edccc5ebbfe2a272aeb43cd28583baa9883602 --- /dev/null +++ b/pool/shard006/C++/0074028_fib_bench.cc @@ -0,0 +1,55 @@ +/* Adapted from: https://svn.sosy-lab.org/software/sv-benchmarks/trunk/c/pthread/fib_bench_true-unreach-call.c */ + +#include +#include +#include + +std::atomic i, j; + +#ifndef N +# warning "N not defined, assuming 3" +# define N 3 +#endif + +void *t1(void* arg){ + int k = 0; + + for (k = 0; k < N; k++) + atomic_store(&i, atomic_load(&i) + atomic_load(&j)); + + return NULL; +} + +void *t2(void* arg){ + int k = 0; + + for (k = 0; k < N; k++) + atomic_store(&j, atomic_load(&j) + atomic_load(&i)); + + return NULL; +} + +int fib(int n) { + int cur = 1, prev = 0; + while(n--) { + int next = prev+cur; + prev = cur; + cur = next; + } + return prev; +} + +int main(int argc, char **argv) { + pthread_t id1, id2; + + atomic_init(&i, 1); + atomic_init(&j, 1); + + pthread_create(&id1, NULL, t1, NULL); + pthread_create(&id2, NULL, t2, NULL); + + int correct = fib(2+2*N); + assert(atomic_load(&i) <= correct && atomic_load(&j) <= correct); + + return 0; +} diff --git a/pool/shard006/C++/0074029_WiFi_Run_Dut_Cmd.cpp b/pool/shard006/C++/0074029_WiFi_Run_Dut_Cmd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1700fc6138ff82bb9780473651bff177a783e5d3 --- /dev/null +++ b/pool/shard006/C++/0074029_WiFi_Run_Dut_Cmd.cpp @@ -0,0 +1,260 @@ +#include "stdafx.h" +#include "TestManager.h" +#include "WiFi_11ac_MiMo_Test.h" +#include "WiFi_11ac_MiMo_Test_Internal.h" +#include "IQmeasure.h" +#include "vDUT.h" +#include "IQlite_Timer.h" +#include "IQlite_Logger.h" + +// This variable is declared in WiFi_Test_Internal.cpp +extern vDUT_ID g_WiFi_Dut; +extern TM_ID g_WiFi_Test_ID; +extern int g_WiFi_Test_timer; +extern int g_WiFi_Test_logger; + +using namespace std; + +#define MAX_RESULT_GROUP_NUM 3 +#define LP_RESULT_FORMAT "LitePoint_Data_Format" + +// Input Parameter Container +map l_runDutCmdParamMap; + +// Return Value Container +map l_runDutCmdReturnMap; + +struct tagParam +{ + char DUT_COMMAND[MAX_BUFFER_SIZE]; + int WAIT_TIME_MS; +} l_runDutCmdParam; + +struct tagReturn +{ + char RESPONSE[MAX_BUFFER_SIZE]; + char ERROR_MESSAGE[MAX_BUFFER_SIZE]; +} l_runDutCmdReturn; + +#ifndef WIN32 +int InitRunDutCommandMPSContainers = InitializeRunDutCommandContainers(); +#endif + +//! Insert WiFi DUT +/*! + * Input Parameters + * + * - Mandatory + * -# A string that is used to determine which DUT register function will be used + * + * Return Values + * -# A string that contains all DUT info, such as FW version, driver version, chip revision, etc. + * -# A string for error message + * + * \return 0 No error occurred + * \return -1 DUT failed to insert. Please see the returned error message for details + */ + +WIFI_11AC_MIMO_TEST_API int WiFi_Run_DUT_Command(void) +{ + int err = ERR_OK; + int dummyValue = 0; + char vErrorMsg[MAX_BUFFER_SIZE] = {'\0'}; + char logMessage[MAX_BUFFER_SIZE] = {'\0'}; + + /*---------------------------------------* + * Clear Return Parameters and Container * + *---------------------------------------*/ + ClearReturnParameters(l_runDutCmdReturnMap); + + /*------------------------* + * Respond to QUERY_INPUT * + *------------------------*/ + err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_INPUT", &dummyValue); + if( ERR_OK==err ) + { + RespondToQueryInput(l_runDutCmdParamMap); + return err; + } + else + { + // do nothing + } + + /*-------------------------* + * Respond to QUERY_RETURN * + *-------------------------*/ + err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_RETURN", &dummyValue); + if( ERR_OK==err ) + { + RespondToQueryReturn(l_runDutCmdReturnMap); + return err; + } + else + { + // do nothing + } + + try + { + TM_ClearReturns(g_WiFi_Test_ID); + + /*----------------------* + * Get input parameters * + *----------------------*/ + err = GetInputParameters(l_runDutCmdParamMap); + if ( ERR_OK!=err ) + { + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi_11ac_MiMo] Input parameters are not complete.\n"); + throw logMessage; + } + else + { + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] Get input parameters return OK.\n"); + } + + // And clear vDut parameters at beginning. + vDUT_ClearParameters(g_WiFi_Dut); + +#pragma region Execute external program + + // Then execute the DUT command + vDUT_AddStringParameter(g_WiFi_Dut, "DUT_COMMAND", l_runDutCmdParam.DUT_COMMAND); + + /*-------------------------------* + * Passing wl cmd file into dut * + *--------------------------------*/ + err = ::vDUT_Run(g_WiFi_Dut, "DUT_MISC_FUNCTION2"); + if ( ERR_OK!=err ) + { + // Check vDut return "ERROR_MESSAGE" or not, if "Yes", must handle it. + err = ::vDUT_GetStringReturn(g_WiFi_Dut, "ERROR_MESSAGE", vErrorMsg, MAX_BUFFER_SIZE); + if ( ERR_OK==err ) // Get "ERROR_MESSAGE" from vDut + { + err = -1; // set err to -1, means "Error". + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, vErrorMsg); + throw logMessage; + } + else // Just return normal error message in this case + { + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi_11ac_MiMo] vDUT_Run(Run_Dut_Cmd) return error.\n"); + throw logMessage; + } + + } + else + { + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] vDUT_Run(Run_Dut_Cmd) return OK.\n"); + + + // For retrieval of the DUT info + err = ::vDUT_GetStringReturn(g_WiFi_Dut, "RESPONSE", l_runDutCmdReturn.RESPONSE, MAX_BUFFER_SIZE); + if ( ERR_OK==err ) + { + LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] vDUT_GetStringReturn(RESPONSE) return OK.\n"); + } + } +#pragma endregion + +#pragma region Execute sleep enough time till external program over + Sleep(l_runDutCmdParam.WAIT_TIME_MS); +#pragma endregion + + /*-----------------------* + * Return Test Results * + *-----------------------*/ + if (ERR_OK==err) + { + sprintf_s(l_runDutCmdReturn.ERROR_MESSAGE, MAX_BUFFER_SIZE, "[Info] Function completed.\n"); + ReturnTestResults(l_runDutCmdReturnMap); + } + } + catch(char *msg) + { + ReturnErrorMessage(l_runDutCmdReturn.ERROR_MESSAGE, msg); + } + catch(...) + { + ReturnErrorMessage(l_runDutCmdReturn.ERROR_MESSAGE, "[WiFi_11ac_MiMo] Unknown Error!\n"); + } + + return err; +} + +int InitializeRunDutCommandContainers(void) +{ + /*------------------* + * Input Parameters: * + *------------------*/ + l_runDutCmdParamMap.clear(); + WIFI_SETTING_STRUCT setting; + + l_runDutCmdParam.WAIT_TIME_MS = 0; + setting.type = WIFI_SETTING_TYPE_INTEGER; + if (sizeof(int)==sizeof(l_runDutCmdParam.WAIT_TIME_MS)) // Type_Checking + { + setting.value = (void*)&l_runDutCmdParam.WAIT_TIME_MS; + setting.unit = "ms"; + setting.helpText = "Specify the wait time before extract the value from result file."; + l_runDutCmdParamMap.insert( pair("WAIT_TIME_MS", setting) ); + } + else + { + printf("Parameter Type Error!\n"); + exit(1); + } + + setting.unit = ""; + setting.helpText = "Specify DUT command to run, case sensitive\r\nSuch as: band a"; + setting.type = WIFI_SETTING_TYPE_STRING; + strcpy_s(l_runDutCmdParam.DUT_COMMAND, MAX_BUFFER_SIZE, ""); + if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdParam.DUT_COMMAND)) // Type_Checking + { + setting.value = (void*)l_runDutCmdParam.DUT_COMMAND; + l_runDutCmdParamMap.insert( pair("DUT_COMMAND", setting) ); + } + else + { + printf("Parameter Type Error!\n"); + exit(1); + } + + /*----------------* + * Return Values: * + * ERROR_MESSAGE * + *----------------*/ + l_runDutCmdReturnMap.clear(); + + l_runDutCmdReturn.ERROR_MESSAGE[0] = '\0'; + setting.type = WIFI_SETTING_TYPE_STRING; + if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdReturn.ERROR_MESSAGE)) // Type_Checking + { + setting.value = (void*)l_runDutCmdReturn.ERROR_MESSAGE; + setting.unit = ""; + setting.helpText = "Error message occurred"; + l_runDutCmdReturnMap.insert( pair("ERROR_MESSAGE", setting) ); + } + else + { + printf("Parameter Type Error!\n"); + exit(1); + } + + l_runDutCmdReturn.RESPONSE[0] = '\0'; + setting.type = WIFI_SETTING_TYPE_STRING; + if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdReturn.RESPONSE)) // Type_Checking + { + setting.value = (void*)l_runDutCmdReturn.RESPONSE; + setting.unit = ""; + setting.helpText = "Error message occurred"; + l_runDutCmdReturnMap.insert( pair("RESPONSE", setting) ); + } + else + { + printf("Parameter Type Error!\n"); + exit(1); + } + + + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0074040_Bob.cpp b/pool/shard006/C++/0074040_Bob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76a355afa5a5ea55115885d082c61df941d420d1 --- /dev/null +++ b/pool/shard006/C++/0074040_Bob.cpp @@ -0,0 +1,199 @@ +#include +#include +#include +#include +#include + +using namespace std; + +int compare(int i, int j) + { + if (i < j) + return (-1); + if (i == j) + return (0); + if (i > j) + return (1); + } + +int main() + { + int index; + int day; + int turn; + int slash_index; + int to_die; + int num_alive; + int mine_alive; + int turn_to_return; + bool returned; + string line; + vector last_returns; + vector today_returns; + + getline(cin, line); + + if (line.compare(0, 6, "INDEX ") != 0) + { + cerr << "INVALID INDEX LINE \"" << line << "\"" << endl; + + return (-1); + } + + index = atoi(line.substr(6).c_str()) - 1; + + while (1) // Day loop + { + getline(cin, line); + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + else if (line.compare(0, 9, "START_DAY") != 0 || (slash_index = line.find('/')) == string::npos) + { + cerr << "INVALID START_DAY \"" << line << "\"" << endl; + return (-1); + } + + day = atoi(line.substr(10, slash_index - 10).c_str()); + to_die = atoi(line.substr(slash_index + 1, line.length() - slash_index - 1).c_str()); + + if (day != 1) + { + if (to_die > num_alive) + { + turn_to_return = 30; + } + else + { + turn_to_return = last_returns[last_returns.size() - to_die] - 1; + } + } + + returned = false; + + for (turn = 1; turn <= 30; ++turn) + { + getline(cin, line); + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + if (line.compare(0, 7, "END_DAY") == 0) + { + goto end_day; + } + if (line.compare(0, 10, "START_TURN") != 0) + { + cerr << "INVALID START_TURN \"" << line << "\"" << endl; + } + + if (day == 1) + { + switch (compare(turn, 30)) + { + case -1: + cout << "S,S,S,S,S" << endl; + break; + + case 0: + cout << "R,R,R,R,R" << endl; + break; + + case 1: + cout << "N,N,N,N,N" << endl; + break; + } + } + else + { + if (returned) + { + cout << "N,N,N,N,N" << endl; + } + /* + else if (num_alive - today_returns.size() < to_die) + { + cout << "R,R,R,R,R" << endl; + returned = true; + } + */ + else if (turn >= turn_to_return) + { + cout << "R,R,R,R,R" << endl; + returned = true; + } + else + { + cout << "S,S,S,S,S" << endl; + } + } + + getline(cin, line); + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + if (line.compare(0, 8, "END_TURN") != 0) + { + cerr << "INVALID END_TURN \"" << line << "\"" << endl; + } + + stringstream ss(line); + string item; + int i = 0; + while (getline(ss, item, ' ')) + { + i++; + if (i > 2 && i - 3 != index) + { + int num_to_add = count(item.begin(), item.end(), 'R'); // Add turn to today_returns for each servant that returned + for (int j = 0; j < num_to_add; j++) + { + today_returns.push_back(turn); + } + } + } + + } + + getline(cin, line); + + end_day: + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + else if (line.compare(0, 7, "END_DAY") != 0) + { + cerr << "INVALID END_DAY \"" << line << "\"" << endl; + return (-1); + } + + stringstream ss(line); + string item; + int i = 0; + num_alive = 0; + while (getline(ss, item, ' ')) + { + i++; + if (i > 2 && i - 3 != index) + { + num_alive += count(item.begin(), item.end(), 'A'); + } + else if (i - 3 == index) + { + mine_alive = count(item.begin(), item.end(), 'A'); + } + } + + last_returns = today_returns; + today_returns.clear(); + + } + + return (0); + } diff --git a/pool/shard006/C++/0074053_CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp b/pool/shard006/C++/0074053_CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db03b9b33a75148dfc408ab33db50130c8c6d491 --- /dev/null +++ b/pool/shard006/C++/0074053_CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp @@ -0,0 +1,180 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp +Label Definition File: CWE23_Relative_Path_Traversal.label.xml +Template File: sources-sink-07.tmpl.cpp +*/ +/* + * @description + * CWE: 23 Relative Path Traversal + * BadSource: file Read input from a file + * GoodSource: Use a fixed file name + * Sink: open + * BadSink : Open the file named in data using open() + * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5) + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#define BASEPATH L"c:\\temp\\" +#else +#include +#define BASEPATH L"/tmp/" +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#ifdef _WIN32 +#define OPEN _wopen +#define CLOSE _close +#else +#include +#define OPEN open +#define CLOSE close +#endif + +/* The variable below is not declared "const", but is never assigned + any other value so a tool should be able to identify that reads of + this will always give its initialized value. */ +static int staticFive = 5; + +namespace CWE23_Relative_Path_Traversal__wchar_t_file_open_07 +{ + +#ifndef OMITBAD + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + if(staticFive==5) + { + { + /* Read input from a file */ + size_t dataLen = wcslen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (FILENAME_MAX-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + fclose(pFile); + } + } + } + } + { + int fileDesc; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + if (fileDesc != -1) + { + CLOSE(fileDesc); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + if(staticFive!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a fixed file name */ + wcscat(data, L"file.txt"); + } + { + int fileDesc; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + if (fileDesc != -1) + { + CLOSE(fileDesc); + } + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + if(staticFive==5) + { + /* FIX: Use a fixed file name */ + wcscat(data, L"file.txt"); + } + { + int fileDesc; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + if (fileDesc != -1) + { + CLOSE(fileDesc); + } + } +} + +void good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE23_Relative_Path_Traversal__wchar_t_file_open_07; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C++/0074056_idle_action_warning_observer.cc b/pool/shard006/C++/0074056_idle_action_warning_observer.cc new file mode 100644 index 0000000000000000000000000000000000000000..54f9b16dbad50268b8f4ca51c8bc2588c5ded6e5 --- /dev/null +++ b/pool/shard006/C++/0074056_idle_action_warning_observer.cc @@ -0,0 +1,103 @@ +// Copyright 2013 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/chromeos/power/idle_action_warning_observer.h" + +#include "ash/public/cpp/ash_pref_names.h" +#include "base/metrics/histogram_macros.h" +#include "base/time/time.h" +#include "chrome/browser/chromeos/login/demo_mode/demo_session.h" +#include "chrome/browser/chromeos/power/idle_action_warning_dialog_view.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/power/power_policy_controller.h" +#include "components/prefs/pref_service.h" + +namespace { + +// DO NOT REORDER - used to report metrics. +enum class IdleLogoutWarningEvent { + kShown = 0, + kCanceled = 1, + kMaxValue = kCanceled +}; + +void ReportMetricsForDemoMode(IdleLogoutWarningEvent event) { + if (chromeos::DemoSession::IsDeviceInDemoMode()) + UMA_HISTOGRAM_ENUMERATION("DemoMode.IdleLogoutWarningEvent", event); +} + +chromeos::PowerPolicyController::Action GetIdleAction(bool on_battery_power) { + PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs(); + int action; + if (on_battery_power) + action = prefs->GetInteger(ash::prefs::kPowerBatteryIdleAction); + else + action = prefs->GetInteger(ash::prefs::kPowerAcIdleAction); + return static_cast(action); +} + +} // namespace + +namespace chromeos { + +IdleActionWarningObserver::IdleActionWarningObserver() { + PowerManagerClient::Get()->AddObserver(this); +} + +IdleActionWarningObserver::~IdleActionWarningObserver() { + PowerManagerClient::Get()->RemoveObserver(this); + if (warning_dialog_) { + warning_dialog_->GetWidget()->RemoveObserver(this); + warning_dialog_->CloseDialog(); + } +} + +void IdleActionWarningObserver::IdleActionImminent( + const base::TimeDelta& time_until_idle_action) { + // Only display warning if idle action is to shut down or logout. + PowerPolicyController::Action idle_action = GetIdleAction(on_battery_power_); + if (idle_action != PowerPolicyController::ACTION_STOP_SESSION && + idle_action != PowerPolicyController::ACTION_SHUT_DOWN) { + HideDialogIfPresent(); + return; + } + + const base::TimeTicks idle_action_time = + base::TimeTicks::Now() + time_until_idle_action; + if (warning_dialog_) { + warning_dialog_->Update(idle_action_time); + } else { + warning_dialog_ = new IdleActionWarningDialogView(idle_action_time); + warning_dialog_->GetWidget()->AddObserver(this); + ReportMetricsForDemoMode(IdleLogoutWarningEvent::kShown); + } +} + +void IdleActionWarningObserver::IdleActionDeferred() { + HideDialogIfPresent(); +} + +void IdleActionWarningObserver::PowerChanged( + const power_manager::PowerSupplyProperties& proto) { + on_battery_power_ = + proto.battery_state() == + power_manager::PowerSupplyProperties_BatteryState_DISCHARGING; +} + +void IdleActionWarningObserver::OnWidgetClosing(views::Widget* widget) { + DCHECK(warning_dialog_); + DCHECK_EQ(widget, warning_dialog_->GetWidget()); + warning_dialog_->GetWidget()->RemoveObserver(this); + warning_dialog_ = nullptr; +} + +void IdleActionWarningObserver::HideDialogIfPresent() { + if (warning_dialog_) { + warning_dialog_->CloseDialog(); + ReportMetricsForDemoMode(IdleLogoutWarningEvent::kCanceled); + } +} + +} // namespace chromeos diff --git a/pool/shard006/C++/0074063_main.cpp b/pool/shard006/C++/0074063_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85985f9e231deabab0df76a30c057ac0a8316dce --- /dev/null +++ b/pool/shard006/C++/0074063_main.cpp @@ -0,0 +1,35 @@ +#include +#include +#include "reader.h" + +using namespace std; + +int main() +{ + bool command = false; + + cout << "Type 1 to use stack on array and 0 to use stack on list" << endl; + cin >> command; + if (command) + { + cout << "You're currently using array for calculating." << endl; + cout << "Type your sentence." << endl; + Reader run; + run.read(); + run.calculate(); + cout << "Current result is "; + cout << run.result(); + } + else + { + cout << "You're currently using list for calculating." << endl; + cout << "Type your sentence." << endl; + Reader run; + run.read(); + run.calculate(); + cout << "Current result is "; + cout << run.result(); + } + cout << endl << "Farewell!" << endl; + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0074069_importCtxtsSum.cpp b/pool/shard006/C++/0074069_importCtxtsSum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c401ce1c46c922c8ae16990aae93ab09af736f6 --- /dev/null +++ b/pool/shard006/C++/0074069_importCtxtsSum.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include +#include + +int main (int argc, char *argv[]) +{ + // Read public key from disk and initialize it + std::fstream pubKeyFile("pubkey.txt", std::fstream::in); + std::fstream secKeyFile("seckey.txt", std::fstream::in); + + assert(pubKeyFile.is_open()); + assert(secKeyFile.is_open()); + + std::string hexPubKey; + std::string hexSecKey; + std::getline(pubKeyFile, hexPubKey); + std::getline(secKeyFile, hexSecKey); + + pubKeyFile.close(); + secKeyFile.close(); + + paillier_pubkey_t* pubKey = paillier_pubkey_from_hex(&hexPubKey[0]); + paillier_prvkey_t* secKey = paillier_prvkey_from_hex(&hexSecKey[0], pubKey); + + // Read ciphertexts from file + std::fstream ctxt1File("ciphertext1.txt", std::fstream::in|std::fstream::binary); + std::fstream ctxt2File("ciphertext2.txt", std::fstream::in|std::fstream::binary); + + assert(ctxt1File.is_open()); + assert(ctxt2File.is_open()); + + // The length of the ciphertext is twice the length of the key + char* byteCtxt1 = (char*)malloc(PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + char* byteCtxt2 = (char*)malloc(PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + + ctxt1File.read(byteCtxt1, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + ctxt2File.read(byteCtxt2, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + + ctxt1File.close(); + ctxt2File.close(); + + paillier_ciphertext_t* ctxt1 = paillier_ciphertext_from_bytes((void*)byteCtxt1, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + paillier_ciphertext_t* ctxt2 = paillier_ciphertext_from_bytes((void*)byteCtxt2, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2); + + // Initialize the ciphertext that will hold the sum with an encryption of zero + paillier_ciphertext_t* encryptedSum = paillier_create_enc_zero(); + + // Sum the encrypted values by multiplying the ciphertexts + paillier_mul(pubKey, encryptedSum, ctxt1, ctxt2); + + // Decrypt the ciphertext (sum) + paillier_plaintext_t* dec; + dec = paillier_dec(NULL, pubKey, secKey, encryptedSum); + gmp_printf("Decrypted sum: %Zd\n", dec); + + // Cleaning up + paillier_freepubkey(pubKey); + paillier_freeprvkey(secKey); + paillier_freeplaintext(dec); + paillier_freeciphertext(ctxt1); + paillier_freeciphertext(ctxt2); + paillier_freeciphertext(encryptedSum); + free(byteCtxt1); + free(byteCtxt2); + + return 0; +} diff --git a/pool/shard006/C++/0074075_Experience.cpp b/pool/shard006/C++/0074075_Experience.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ecb2939784c22be1363a920719f07842220d75c --- /dev/null +++ b/pool/shard006/C++/0074075_Experience.cpp @@ -0,0 +1,78 @@ +#include + +#include + +namespace AIToolbox::MDP { + Experience::Experience(const size_t s, const size_t a) : + S(s), A(a), visits_(A, Table2D(S, S)), visitsSum_(S, A), rewards_(S, A), M2s_(S, A), timesteps_(0) + { + reset(); + } + + void Experience::record(const size_t s, const size_t a, const size_t s1, const double rew) { + ++timesteps_; + + // Count updates + visits_[a](s, s1) += 1; + visitsSum_(s, a) += 1; + + const auto delta = rew - rewards_(s, a); + // Rolling average for this s,a,s1 tuple + rewards_(s, a) += delta / visitsSum_(s, a); + // Rolling sum of square diffs. + M2s_(s, a) += delta * (rew - rewards_(s, a)); + } + + void Experience::reset() { + for (size_t a = 0; a < A; ++a) + visits_[a].setZero(); + visitsSum_.setZero(); + rewards_.setZero(); + M2s_.setZero(); + timesteps_ = 0; + } + + void Experience::setVisitsTable(const Table3D & v) { + visits_ = v; + visitsSum_.setZero(); + for ( size_t s = 0; s < S; ++s ) + for ( size_t a = 0; a < A; ++a ) + visitsSum_(s, a) = visits_[a].row(s).sum(); + } + + void Experience::setRewardMatrix(const Matrix2D & r) { + rewards_ = r; + } + + void Experience::setM2Matrix(const Matrix2D & mm) { + M2s_ = mm; + } + + unsigned long Experience::getTimesteps() const { + return timesteps_; + } + + unsigned long Experience::getVisits(const size_t s, const size_t a, const size_t s1) const { + return visits_[a](s, s1); + } + + unsigned long Experience::getVisitsSum(const size_t s, const size_t a) const { + return visitsSum_(s, a); + } + + double Experience::getReward(const size_t s, const size_t a) const { + return rewards_(s, a); + } + + double Experience::getM2(const size_t s, const size_t a) const { + return M2s_(s, a); + } + + const Table3D & Experience::getVisitsTable() const { return visits_; } + const Table2D & Experience::getVisitsTable(const size_t a) const { return visits_[a]; } + const Table2D & Experience::getVisitsSumTable() const { return visitsSum_; } + const QFunction & Experience::getRewardMatrix() const { return rewards_; } + const QFunction & Experience::getM2Matrix() const { return M2s_; } + size_t Experience::getS() const { return S; } + size_t Experience::getA() const { return A; } +} diff --git a/pool/shard006/C++/0074085_ImageTexture.cpp b/pool/shard006/C++/0074085_ImageTexture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5e79bcc150c6c082ed295923d23e7ae620bbd8d --- /dev/null +++ b/pool/shard006/C++/0074085_ImageTexture.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2013 Pavlo Lavrenenko + * + * 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 +#include +#include +#include + +namespace Graphene { + +ImageTexture::ImageTexture(const Image& image): + RgbaTexture(image.getWidth(), image.getHeight()) { + glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + int anisotropy = GetEngineConfig().getAnisotropy(); + if (anisotropy > 0 && OpenGL::isExtensionSupported("GL_ARB_texture_filter_anisotropic")) { + GLint maxAnisotropy; + glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnisotropy); + glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY, std::min(anisotropy, maxAnisotropy)); + } else { + LogWarn("GL_ARB_texture_filter_anisotropic unavailable, anisotropic filtering disabled"); + } + + this->update(image); +} + +void ImageTexture::update(const Image& image) { + this->bind(); + + GLenum format = (image.getPixelDepth() == 32) ? GL_BGRA : GL_BGR; // Little-endian ARGB or RGB format + glTexSubImage2D(this->target, 0, 0, 0, this->width, this->height, format, GL_UNSIGNED_BYTE, image.getPixels()); + glGenerateMipmap(this->target); +} + +ImageCubeTexture::ImageCubeTexture(const CubeImage& cubeImage): + RgbaCubeTexture(cubeImage[0]->getWidth(), cubeImage[0]->getHeight()) { + glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + int anisotropy = GetEngineConfig().getAnisotropy(); + if (anisotropy > 0 && OpenGL::isExtensionSupported("GL_ARB_texture_filter_anisotropic")) { + GLint maxAnisotropy; + glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnisotropy); + glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY, std::min(anisotropy, maxAnisotropy)); + } else { + LogWarn("GL_ARB_texture_filter_anisotropic unavailable, anisotropic filtering disabled"); + } + + this->update(cubeImage); +} + +void ImageCubeTexture::update(const CubeImage& cubeImage) { + this->bind(); + + for (int faceOffset = 0; faceOffset < 6; faceOffset++) { + auto& faceImage = cubeImage[faceOffset]; + GLenum faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceOffset; + GLenum faceFormat = (faceImage->getPixelDepth() == 32) ? GL_BGRA : GL_BGR; // Little-endian ARGB or RGB format + glTexSubImage2D(faceTarget, 0, 0, 0, faceImage->getWidth(), faceImage->getHeight(), faceFormat, GL_UNSIGNED_BYTE, faceImage->getPixels()); + } + + glGenerateMipmap(this->target); +} + +} // namespace Graphene diff --git a/pool/shard006/C++/0074092_rulebased_fuzzer.cc b/pool/shard006/C++/0074092_rulebased_fuzzer.cc new file mode 100644 index 0000000000000000000000000000000000000000..e636c289ee66b57c972296390662a9016ce2b950 --- /dev/null +++ b/pool/shard006/C++/0074092_rulebased_fuzzer.cc @@ -0,0 +1,107 @@ +// 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 +#include + +#include "ash/services/ime/public/cpp/rulebased/def/us.h" +#include "ash/services/ime/public/cpp/rulebased/engine.h" +#include "ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.pb.h" +#include "ash/services/ime/public/cpp/rulebased/rules_data.h" +#include "testing/libfuzzer/proto/lpm_interface.h" + +namespace rulebased = ::ash::ime::rulebased; +namespace mojom = ::ash::ime::mojom; + +namespace { + +// Must match ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.proto +constexpr mojom::DomCode kKeyCodes[] = { + mojom::DomCode::kBackquote, mojom::DomCode::kDigit1, + mojom::DomCode::kDigit2, mojom::DomCode::kDigit3, + mojom::DomCode::kDigit4, mojom::DomCode::kDigit5, + mojom::DomCode::kDigit6, mojom::DomCode::kDigit7, + mojom::DomCode::kDigit8, mojom::DomCode::kDigit9, + mojom::DomCode::kDigit0, mojom::DomCode::kMinus, + mojom::DomCode::kEqual, mojom::DomCode::kBackspace, + mojom::DomCode::kKeyQ, mojom::DomCode::kKeyW, + mojom::DomCode::kKeyE, mojom::DomCode::kKeyR, + mojom::DomCode::kKeyT, mojom::DomCode::kKeyY, + mojom::DomCode::kKeyU, mojom::DomCode::kKeyI, + mojom::DomCode::kKeyO, mojom::DomCode::kKeyP, + mojom::DomCode::kBracketLeft, mojom::DomCode::kBracketRight, + mojom::DomCode::kKeyA, mojom::DomCode::kKeyS, + mojom::DomCode::kKeyD, mojom::DomCode::kKeyF, + mojom::DomCode::kKeyG, mojom::DomCode::kKeyH, + mojom::DomCode::kKeyJ, mojom::DomCode::kKeyK, + mojom::DomCode::kKeyL, mojom::DomCode::kSemicolon, + mojom::DomCode::kQuote, mojom::DomCode::kBackslash, + mojom::DomCode::kIntlBackslash, mojom::DomCode::kEnter, + mojom::DomCode::kKeyZ, mojom::DomCode::kKeyX, + mojom::DomCode::kKeyC, mojom::DomCode::kKeyV, + mojom::DomCode::kKeyB, mojom::DomCode::kKeyN, + mojom::DomCode::kKeyM, mojom::DomCode::kComma, + mojom::DomCode::kPeriod, mojom::DomCode::kSlash, + mojom::DomCode::kSpace}; + +// Must match ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.proto +constexpr const char* kEngineIds[] = { + "ar", + "bn_phone", + "ckb_ar", + "ckb_en", + "deva_phone", + "ethi", + "fa", + "gu_phone", + "km", + "kn_phone", + "lo", + "ml_phone", + "my", + "my_myansan", + "ne_inscript", + "ne_phone", + "ru_phone_aatseel", + "ru_phone_yazhert", + "si", + "ta_inscript", + "ta_itrans", + "ta_phone", + "ta_tamil99", + "ta_typewriter", + "te_phone", + "th", + "th_pattajoti", + "th_tis", + "us", + "vi_tcvn", + "vi_telex", + "vi_viqr", + "vi_vni", +}; + +static rulebased::Engine engines[std::size(kEngineIds)]; + +uint8_t GetModifierFromKeyEvent(const rulebased_fuzzer::KeyEvent& e) { + uint8_t modifiers = 0; + if (e.shift()) + modifiers |= rulebased::MODIFIER_SHIFT; + if (e.altgr()) + modifiers |= rulebased::MODIFIER_ALTGR; + if (e.caps_lock()) + modifiers |= rulebased::MODIFIER_CAPSLOCK; + return modifiers; +} + +} // namespace + +DEFINE_PROTO_FUZZER(const rulebased_fuzzer::TestFuzzerInput& msg) { + auto& engine = engines[msg.engine_id()]; + engine.Activate(kEngineIds[msg.engine_id()]); + + for (const auto& event : msg.key_events()) { + engine.ProcessKey(kKeyCodes[event.code()], GetModifierFromKeyEvent(event)); + } +} diff --git a/pool/shard006/C++/0074094_signal.cpp b/pool/shard006/C++/0074094_signal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e891c198c47e11ab7f4c4c3ad194c4b350a442f --- /dev/null +++ b/pool/shard006/C++/0074094_signal.cpp @@ -0,0 +1,40 @@ +/*! + \\ Author: Karl Redmond + \\ Date: 10th Oct 2017 + \\ brief A Semaphore Implementation to show serialization, where task A must happen before task B, ie taskOne before taskTwo + \ \ + \\ Uses C++11 features such as mutex and condition variables to implement Semaphore + +*/ + +#include "Semaphore.h" +#include +#include + + +void taskOne(std::shared_ptr theSemaphore){ + std::cout <<"I "; + std::cout << "must "; + std::cout << "print "; + std::cout << "first"<Signal(); +} +void taskTwo(std::shared_ptr theSemaphore){ + theSemaphore->Wait(); + std::cout <<"This "; + std::cout << "will "; + std::cout << "appear "; + std::cout << "second"< sem( new Semaphore); + /**< Launch the threads */ + threadOne=std::thread(taskTwo,sem); + threadTwo=std::thread(taskOne,sem); + std::cout << "Launched from the main\n"; + threadOne.join(); + threadTwo.join(); + return 0; +} diff --git a/pool/shard006/C++/0074103_urlfilterbuilder.cc b/pool/shard006/C++/0074103_urlfilterbuilder.cc new file mode 100644 index 0000000000000000000000000000000000000000..64e94d92e119b5192dc1b8a369e7b78889fde42b --- /dev/null +++ b/pool/shard006/C++/0074103_urlfilterbuilder.cc @@ -0,0 +1,41 @@ +// Copyright 2009 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#include "sitemapservice/asteriskfilter.h" +#include "sitemapservice/urlfilterbuilder.h" + +UrlFilter* UrlFilterBuilder::Build(const Url& pattern) { + AsteriskFilter* filter = new AsteriskFilter(pattern.path_url()); + return filter; +} + +UrlFilter* UrlFilterBuilder::Build(const std::vector& patterns) { + OrFilter* orfilter = NULL; + for (int i = 0; i < static_cast(patterns.size()); ++i) { + UrlFilter* filter = Build(patterns[i]); + if (filter != NULL) { + if (orfilter == NULL) { + orfilter = new OrFilter(); + } + orfilter->AddFilter(filter); + } + } + + if (orfilter != NULL) { + return orfilter; + } else { + return new DummyFilter(false); + } +} diff --git a/pool/shard006/C++/0074109_TEvhttpServer.cpp b/pool/shard006/C++/0074109_TEvhttpServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57d0d6120399a4cb7bce2e62d07e233d0903758f --- /dev/null +++ b/pool/shard006/C++/0074109_TEvhttpServer.cpp @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#ifndef HTTP_INTERNAL // libevent < 2 +#define HTTP_INTERNAL 500 +#endif + +using apache::thrift::transport::TMemoryBuffer; + +namespace apache { +namespace thrift { +namespace async { + +struct TEvhttpServer::RequestContext { + struct evhttp_request* req; + boost::shared_ptr ibuf; + boost::shared_ptr obuf; + + RequestContext(struct evhttp_request* req); +}; + +TEvhttpServer::TEvhttpServer(boost::shared_ptr processor) + : processor_(processor), eb_(NULL), eh_(NULL) { +} + +TEvhttpServer::TEvhttpServer(boost::shared_ptr processor, int port) + : processor_(processor), eb_(NULL), eh_(NULL) { + // Create event_base and evhttp. + eb_ = event_base_new(); + if (eb_ == NULL) { + throw TException("event_base_new failed"); + } + eh_ = evhttp_new(eb_); + if (eh_ == NULL) { + event_base_free(eb_); + throw TException("evhttp_new failed"); + } + + // Bind to port. + int ret = evhttp_bind_socket(eh_, NULL, port); + if (ret < 0) { + evhttp_free(eh_); + event_base_free(eb_); + throw TException("evhttp_bind_socket failed"); + } + + // Register a handler. If you use the other constructor, + // you will want to do this yourself. + // Don't forget to unregister before destorying this TEvhttpServer. + evhttp_set_cb(eh_, "/", request, (void*)this); +} + +TEvhttpServer::~TEvhttpServer() { + if (eh_ != NULL) { + evhttp_free(eh_); + } + if (eb_ != NULL) { + event_base_free(eb_); + } +} + +int TEvhttpServer::serve() { + if (eb_ == NULL) { + throw TException("Unexpected call to TEvhttpServer::serve"); + } + return event_base_dispatch(eb_); +} + +TEvhttpServer::RequestContext::RequestContext(struct evhttp_request* req) + : req(req), + ibuf(new TMemoryBuffer(EVBUFFER_DATA(req->input_buffer), + static_cast(EVBUFFER_LENGTH(req->input_buffer)))), + obuf(new TMemoryBuffer()) { +} + +void TEvhttpServer::request(struct evhttp_request* req, void* self) { + try { + static_cast(self)->process(req); + } catch (std::exception& e) { + evhttp_send_reply(req, HTTP_INTERNAL, e.what(), 0); + } +} + +void TEvhttpServer::process(struct evhttp_request* req) { + RequestContext* ctx = new RequestContext(req); + return processor_->process(apache::thrift::stdcxx::bind(&TEvhttpServer::complete, + this, + ctx, + apache::thrift::stdcxx::placeholders::_1), + ctx->ibuf, + ctx->obuf); +} + +void TEvhttpServer::complete(RequestContext* ctx, bool success) { + (void)success; + std::auto_ptr ptr(ctx); + + int code = success ? 200 : 400; + const char* reason = success ? "OK" : "Bad Request"; + + int rv = evhttp_add_header(ctx->req->output_headers, "Content-Type", "application/x-thrift"); + if (rv != 0) { + // TODO: Log an error. + std::cerr << "evhttp_add_header failed " << __FILE__ << ":" << __LINE__ << std::endl; + } + + struct evbuffer* buf = evbuffer_new(); + if (buf == NULL) { + // TODO: Log an error. + std::cerr << "evbuffer_new failed " << __FILE__ << ":" << __LINE__ << std::endl; + } else { + uint8_t* obuf; + uint32_t sz; + ctx->obuf->getBuffer(&obuf, &sz); + int ret = evbuffer_add(buf, obuf, sz); + if (ret != 0) { + // TODO: Log an error. + std::cerr << "evhttp_add failed with " << ret << " " << __FILE__ << ":" << __LINE__ + << std::endl; + } + } + + evhttp_send_reply(ctx->req, code, reason, buf); + if (buf != NULL) { + evbuffer_free(buf); + } +} + +struct event_base* TEvhttpServer::getEventBase() { + return eb_; +} +} +} +} // apache::thrift::async diff --git a/pool/shard006/C++/0074118_unlinkd_daemon.cc b/pool/shard006/C++/0074118_unlinkd_daemon.cc new file mode 100644 index 0000000000000000000000000000000000000000..e3ca30480c0a6c31a6c7dd1a924159419ba91041 --- /dev/null +++ b/pool/shard006/C++/0074118_unlinkd_daemon.cc @@ -0,0 +1,74 @@ +/* + * Copyright (C) 1996-2015 The Squid Software Foundation and contributors + * + * Squid software is distributed under GPLv2+ license and includes + * contributions from numerous individuals and organizations. + * Please see the COPYING and CONTRIBUTORS files for details. + */ + +/* DEBUG: section -- Unlink Daemon */ + +#define SQUID_HELPER 1 + +#include "squid.h" + +#if HAVE_PATHS_H +#include +#endif + +/** + \defgroup unlinkd unlinkd + \ingroup ExternalPrograms + \par + The unlink(2) system call can cause a process to block + for a significant amount of time. Therefore we do not want + to make unlink() calls from Squid. Instead we pass them + to this external process. + */ + +/// \ingroup unlinkd +#define UNLINK_BUF_LEN 1024 + +/** + \ingroup unlinkd + \par This is the unlinkd external process. + * + \par + * unlinkd receives the full path of any files to be removed + * from stdin, each on its own line. + * + \par + * The results for each file are printed to stdout in the order + * they were received + * + \param argc Ignored. + \param argv Ignored. + \retval ERR An error occured removing the file. + \retval OK The file has been removed. + */ +int +main(int argc, char *argv[]) +{ + char buf[UNLINK_BUF_LEN]; + char *t; + int x; + setbuf(stdin, NULL); + setbuf(stdout, NULL); + close(2); + if (open(_PATH_DEVNULL, O_RDWR) < 0) { + ; // the irony of having to close(2) earlier is that we cannot report this failure. + } + + while (fgets(buf, sizeof(buf), stdin)) { + if ((t = strchr(buf, '\n'))) + *t = '\0'; + x = unlink(buf); + if (x < 0) + printf("ERR\n"); + else + printf("OK\n"); + } + + return 0; +} + diff --git a/pool/shard006/C++/0074121_system_clock_client.cc b/pool/shard006/C++/0074121_system_clock_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..cd803e211d7ebf0e8c5e930c390fe6243eb061a0 --- /dev/null +++ b/pool/shard006/C++/0074121_system_clock_client.cc @@ -0,0 +1,226 @@ +// Copyright (c) 2013 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 "chromeos/dbus/system_clock/system_clock_client.h" + +#include + +#include + +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/logging.h" +#include "base/observer_list.h" +#include "chromeos/dbus/system_clock/fake_system_clock_client.h" +#include "dbus/bus.h" +#include "dbus/message.h" +#include "dbus/object_path.h" +#include "third_party/cros_system_api/dbus/service_constants.h" + +namespace chromeos { + +namespace { + +// Handles replies to D-Bus calls made by GetLastSyncInfo. +void OnGetLastSyncInfo(SystemClockClient::GetLastSyncInfoCallback callback, + dbus::Response* response) { + if (!response) { + LOG(ERROR) << system_clock::kSystemClockInterface << "." + << system_clock::kSystemLastSyncInfo << " request failed."; + return; + } + dbus::MessageReader reader(response); + bool network_synchronized = false; + if (!reader.PopBool(&network_synchronized)) { + LOG(ERROR) << system_clock::kSystemClockInterface << "." + << system_clock::kSystemLastSyncInfo + << " response lacks network-synchronized argument."; + return; + } + std::move(callback).Run(network_synchronized); +} + +SystemClockClient* g_instance = nullptr; + +} // namespace + +// The SystemClockClient implementation used in production. +class SystemClockClientImpl : public SystemClockClient { + public: + explicit SystemClockClientImpl(dbus::Bus* bus) + : can_set_time_(false), + can_set_time_initialized_(false), + system_clock_proxy_(nullptr) { + CHECK(bus); + InitDBus(bus); + } + + SystemClockClientImpl(const SystemClockClientImpl&) = delete; + SystemClockClientImpl& operator=(const SystemClockClientImpl&) = delete; + + ~SystemClockClientImpl() override = default; + + void AddObserver(Observer* observer) override { + observers_.AddObserver(observer); + } + + void RemoveObserver(Observer* observer) override { + observers_.RemoveObserver(observer); + } + + bool HasObserver(const Observer* observer) const override { + return observers_.HasObserver(observer); + } + + void SetTime(int64_t time_in_seconds) override { + // Always try to set the time, because |can_set_time_| may be stale. + dbus::MethodCall method_call(system_clock::kSystemClockInterface, + system_clock::kSystemClockSet); + dbus::MessageWriter writer(&method_call); + writer.AppendInt64(time_in_seconds); + system_clock_proxy_->CallMethod(&method_call, + dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::DoNothing()); + } + + bool CanSetTime() override { return can_set_time_; } + + void GetLastSyncInfo(GetLastSyncInfoCallback callback) override { + dbus::MethodCall method_call(system_clock::kSystemClockInterface, + system_clock::kSystemLastSyncInfo); + system_clock_proxy_->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::BindOnce(OnGetLastSyncInfo, std::move(callback))); + } + + void WaitForServiceToBeAvailable( + dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) + override { + system_clock_proxy_->WaitForServiceToBeAvailable(std::move(callback)); + } + + TestInterface* GetTestInterface() override { return nullptr; } + + private: + void InitDBus(dbus::Bus* bus) { + system_clock_proxy_ = bus->GetObjectProxy( + system_clock::kSystemClockServiceName, + dbus::ObjectPath(system_clock::kSystemClockServicePath)); + system_clock_proxy_->ConnectToSignal( + system_clock::kSystemClockInterface, system_clock::kSystemClockUpdated, + base::BindRepeating(&SystemClockClientImpl::TimeUpdatedReceived, + weak_ptr_factory_.GetWeakPtr()), + base::BindOnce(&SystemClockClientImpl::TimeUpdatedConnected, + weak_ptr_factory_.GetWeakPtr())); + WaitForServiceToBeAvailable( + base::BindOnce(&SystemClockClientImpl::ServiceInitiallyAvailable, + weak_ptr_factory_.GetWeakPtr())); + } + + // Called once when the service initially becomes available (or immediately if + // it's already available). + void ServiceInitiallyAvailable(bool service_is_available) { + if (service_is_available) + GetCanSet(); + else + LOG(ERROR) << "Failed to wait for D-Bus service availability"; + } + + // Called when a TimeUpdated signal is received. + void TimeUpdatedReceived(dbus::Signal* signal) { + VLOG(1) << "TimeUpdated signal received: " << signal->ToString(); + dbus::MessageReader reader(signal); + for (auto& observer : observers_) + observer.SystemClockUpdated(); + + // Check if the system clock can be changed now. + GetCanSet(); + } + + // Called when the TimeUpdated signal is initially connected. + void TimeUpdatedConnected(const std::string& interface_name, + const std::string& signal_name, + bool success) { + LOG_IF(ERROR, !success) << "Failed to connect to TimeUpdated signal."; + } + + // Callback for CanSetTime method. + void OnGetCanSet(dbus::Response* response) { + if (!response) { + VLOG(1) << "CanSetTime request failed."; + return; + } + + dbus::MessageReader reader(response); + bool can_set_time; + if (!reader.PopBool(&can_set_time)) { + LOG(ERROR) << "CanSetTime response invalid: " << response->ToString(); + return; + } + + // Nothing to do if the CanSetTime response hasn't changed. + if (can_set_time_initialized_ && can_set_time_ == can_set_time) + return; + + can_set_time_initialized_ = true; + can_set_time_ = can_set_time; + + for (auto& observer : observers_) + observer.SystemClockCanSetTimeChanged(can_set_time); + } + + // Check whether the time can be set. + void GetCanSet() { + dbus::MethodCall method_call(system_clock::kSystemClockInterface, + system_clock::kSystemClockCanSet); + dbus::MessageWriter writer(&method_call); + system_clock_proxy_->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::BindOnce(&SystemClockClientImpl::OnGetCanSet, + weak_ptr_factory_.GetWeakPtr())); + } + + // Whether the time can be set. Value is false until the first + // CanSetTime response is received. + bool can_set_time_; + bool can_set_time_initialized_; + dbus::ObjectProxy* system_clock_proxy_; + base::ObserverList::Unchecked observers_; + + base::WeakPtrFactory weak_ptr_factory_{this}; +}; + +SystemClockClient::SystemClockClient() { + CHECK(!g_instance); + g_instance = this; +} + +SystemClockClient::~SystemClockClient() { + CHECK_EQ(this, g_instance); + g_instance = nullptr; +} + +// static +void SystemClockClient::Initialize(dbus::Bus* bus) { + CHECK(bus); + new SystemClockClientImpl(bus); +} + +// static +void SystemClockClient::InitializeFake() { + new FakeSystemClockClient(); +} + +// static +void SystemClockClient::Shutdown() { + CHECK(g_instance); + delete g_instance; +} + +// static +SystemClockClient* SystemClockClient::Get() { + return g_instance; +} + +} // namespace chromeos diff --git a/pool/shard006/C++/0074130_instance_endtime.cpp b/pool/shard006/C++/0074130_instance_endtime.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7057401768fd61765da8ef99b782595fea0b42cb --- /dev/null +++ b/pool/shard006/C++/0074130_instance_endtime.cpp @@ -0,0 +1,204 @@ +/* + * Copyright (C) 2005 - 2011 MaNGOS + * + * Copyright (C) 2008 - 2011 TrinityCore + * + * Copyright (C) 2011 TrilliumEMU + * + * 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 "ObjectMgr.h" +#include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" +#include "Map.h" +#include "PoolMgr.h" +#include "AccountMgr.h" +#include "endtime.h" +#include "Player.h" +#include "WorldPacket.h" +#include "WorldSession.h" + +#define MAX_ENCOUNTER 5 + +class instance_endtime : public InstanceMapScript +{ +public: + instance_endtime() : InstanceMapScript("instance_endtime", 938) { } + + struct instance_endtime_InstanceMapScript: public InstanceScript + { + instance_endtime_InstanceMapScript(InstanceMap* map) : InstanceScript(map) + { + SetBossNumber(MAX_ENCOUNTER); + uiBaine = 0; + uiJaina = 0; + uiSylvanas = 0; + uiTyrande = 0; + uiMurozond = 0; + GoHourGlassofTimeGUID = 0; + GoTimeTansitDeviceGUID = 0; + GoMurozondCacheGUID = 0; + GoBainePlatform1GUID = 0; + GoBainePlatform2GUID = 0; + GoBainePlatform3GUID = 0; + GoBainePlatform4GUID = 0; + GoFragmentsGUID = 0; + + } + + void OnGameObjectCreate(GameObject* go) + { + switch (go->GetEntry()) + { + case HOURGLASS_OF_TIME: + GoHourGlassofTimeGUID = go->GetGUID(); + break; + case BAINE_PLATFORM_1: + GoBainePlatform1GUID = go->GetGUID(); + break; + case BAINE_PLATFORM_2: + GoBainePlatform2GUID = go->GetGUID(); + break; + case BAINE_PLATFORM_3: + GoBainePlatform3GUID = go->GetGUID(); + break; + case BAINE_PLATFORM_4: + GoBainePlatform4GUID = go->GetGUID(); + break; + case JAINAS_STAFF: + GoFragmentsGUID = go->GetGUID(); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); + break; + case MUROSZONDS_TEMPORAL_CACHE: + GoMurozondCacheGUID = go->GetGUID(); + break; + } + } + + void OnCreatureCreate(Creature* creature, bool ) + { + switch (creature->GetEntry()) + { + case BOSS_BAINE: + uiBaine = creature->GetGUID(); + break; + case BOSS_JAINA: + uiJaina = creature->GetGUID(); + break; + case BOSS_SYLVANAS: + uiSylvanas = creature->GetGUID(); + break; + case BOSS_TYRANDE: + uiTyrande = creature->GetGUID(); + break; + case BOSS_MUROZOND: + uiMurozond = creature->GetGUID(); + break; + } + } + + uint64 getData64(uint32 index) const + { + switch (index) + { + case DATA_ECHO_OF_BAINE: + return uiBaine; + case DATA_ECHO_OF_JAINA: + return uiJaina; + case DATA_JAINAS_STAFF: + return jainasstaff; + case DATA_ECHO_OF_SYLVANAS: + return uiSylvanas; + case DATA_ECHO_OF_TYRANDE: + return uiTyrande; + case DATA_MUROZOND: + return uiMurozond; + } + return 0; + } + + std::string GetSaveData() + { + OUT_SAVE_INST_DATA; + + std::ostringstream saveStream; + saveStream << "H O " << GetBossSaveData(); + + OUT_SAVE_INST_DATA_COMPLETE; + return saveStream.str(); + } + + void Load(const char* in) + { + if (!in) + { + OUT_LOAD_INST_DATA_FAIL; + return; + } + + OUT_LOAD_INST_DATA(in); + + char dataHead1, dataHead2; + uint16 data0, data1; + + std::istringstream loadStream(in); + loadStream >> dataHead1 >> dataHead2; + + if (dataHead1 == 'H' && dataHead2 == 'O') + { + for (uint32 i = 0; i < EncounterCount; ++i) + { + uint32 tmpState; + loadStream >> tmpState; + if (tmpState == IN_PROGRESS || tmpState > SPECIAL) + tmpState = NOT_STARTED; + SetBossState(i, EncounterState(tmpState)); + } + uint32 tmp; + loadStream >> tmp; + } + else + OUT_LOAD_INST_DATA_FAIL; + + OUT_LOAD_INST_DATA_COMPLETE; + } + protected: + uint64 uiBaine; + uint64 uiJaina; + uint64 uiSylvanas; + uint64 uiTyrande; + uint64 uiMurozond; + uint64 GoHourGlassofTimeGUID; + uint64 GoTimeTansitDeviceGUID; + uint64 GoMurozondCacheGUID; + uint64 GoBainePlatform1GUID; + uint64 GoBainePlatform2GUID; + uint64 GoBainePlatform3GUID; + uint64 GoBainePlatform4GUID; + uint64 GoFragmentsGUID; + uint64 jainasstaff; + }; + + InstanceScript* GetInstanceScript(InstanceMap* map) const + { + return new instance_endtime_InstanceMapScript(map); + } +}; + +void AddSC_instance_endtime() +{ + new instance_endtime(); +} \ No newline at end of file diff --git a/pool/shard006/C++/0074139_password_manager_exporter.cc b/pool/shard006/C++/0074139_password_manager_exporter.cc new file mode 100644 index 0000000000000000000000000000000000000000..c394f10209b7c7ab72ede772609673a98c7df9c1 --- /dev/null +++ b/pool/shard006/C++/0074139_password_manager_exporter.cc @@ -0,0 +1,222 @@ +// Copyright 2017 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 "components/password_manager/core/browser/export/password_manager_exporter.h" + +#include + +#include "base/bind.h" +#include "base/containers/flat_set.h" +#include "base/files/file_util.h" +#include "base/location.h" +#include "base/metrics/histogram_macros.h" +#include "base/task/lazy_thread_pool_task_runner.h" +#include "base/task/post_task.h" +#include "base/task/task_runner_util.h" +#include "build/build_config.h" +#include "components/password_manager/core/browser/export/password_csv_writer.h" +#include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_list_sorter.h" +#include "components/password_manager/core/browser/password_manager_metrics_util.h" +#include "components/password_manager/core/browser/ui/credential_provider_interface.h" + +namespace password_manager { + +namespace { + +// Multiple exports should be queued in sequence. This helps avoid race +// conditions where there are multiple simultaneous exports to the same +// destination and one of them was cancelled and will delete the file. We use +// TaskPriority::USER_VISIBLE, because a busy UI is displayed while the +// passwords are being exported. +base::LazyThreadPoolSingleThreadTaskRunner g_task_runner = + LAZY_THREAD_POOL_SINGLE_THREAD_TASK_RUNNER_INITIALIZER( + base::TaskTraits(base::MayBlock(), base::TaskPriority::USER_VISIBLE), + base::SingleThreadTaskRunnerThreadMode::SHARED); + +// A wrapper for |write_function|, which can be bound and keep a copy of its +// data on the closure. +bool DoWriteOnTaskRunner( + PasswordManagerExporter::WriteCallback write_function, + PasswordManagerExporter::SetPosixFilePermissionsCallback + set_permissions_function, + const base::FilePath& destination, + const std::string& serialised) { + if (!write_function.Run(destination, serialised)) + return false; + + // Set file permissions. This is a no-op outside of Posix. + set_permissions_function.Run(destination, 0600 /* -rw------- */); + return true; +} + +bool DefaultWriteFunction(const base::FilePath& file, base::StringPiece data) { + return base::WriteFile(file, data); +} + +bool DefaultDeleteFunction(const base::FilePath& file) { + return base::DeleteFile(file); +} + +std::vector> DeduplicatePasswordsAcrossStores( + std::vector> passwords) { + auto get_sort_key = [](const auto& password) { + return CreateSortKey(*password, IgnoreStore(true)); + }; + auto cmp = [&](const auto& lhs, const auto& rhs) { + return get_sort_key(lhs) < get_sort_key(rhs); + }; + base::flat_set, decltype(cmp)> unique_passwords( + std::move(passwords), cmp); + return std::move(unique_passwords).extract(); +} + +} // namespace + +PasswordManagerExporter::PasswordManagerExporter( + CredentialProviderInterface* credential_provider_interface, + ProgressCallback on_progress) + : credential_provider_interface_(credential_provider_interface), + on_progress_(std::move(on_progress)), + last_progress_status_(ExportProgressStatus::NOT_STARTED), + write_function_(base::BindRepeating(&DefaultWriteFunction)), + delete_function_(base::BindRepeating(&DefaultDeleteFunction)), +#if defined(OS_POSIX) + set_permissions_function_( + base::BindRepeating(base::SetPosixFilePermissions)), +#else + set_permissions_function_( + base::BindRepeating([](const base::FilePath&, int) { return true; })), +#endif + task_runner_(g_task_runner.Get()) { +} + +PasswordManagerExporter::~PasswordManagerExporter() = default; + +void PasswordManagerExporter::PreparePasswordsForExport() { + DCHECK_EQ(GetProgressStatus(), ExportProgressStatus::NOT_STARTED); + + std::vector> password_list = + credential_provider_interface_->GetAllPasswords(); + + // Deduplicate passwords that are present in multiple stores, so the output + // file doesn't contain repeated data. + std::vector> deduplicated_password_list = + DeduplicatePasswordsAcrossStores(std::move(password_list)); + + size_t deduplicated_password_list_size = deduplicated_password_list.size(); + base::PostTaskAndReplyWithResult( + task_runner_.get(), FROM_HERE, + base::BindOnce(&PasswordCSVWriter::SerializePasswords, + std::move(deduplicated_password_list)), + base::BindOnce(&PasswordManagerExporter::SetSerialisedPasswordList, + weak_factory_.GetWeakPtr(), + deduplicated_password_list_size)); +} + +void PasswordManagerExporter::SetDestination( + const base::FilePath& destination) { + DCHECK_EQ(GetProgressStatus(), ExportProgressStatus::NOT_STARTED); + + destination_ = destination; + + if (IsReadyForExport()) + Export(); + + OnProgress(ExportProgressStatus::IN_PROGRESS, std::string()); +} + +void PasswordManagerExporter::SetSerialisedPasswordList( + size_t count, + const std::string& serialised) { + serialised_password_list_ = serialised; + password_count_ = count; + if (IsReadyForExport()) + Export(); +} + +void PasswordManagerExporter::Cancel() { + // Tasks which had their pointers invalidated won't run. + weak_factory_.InvalidateWeakPtrs(); + + // If we are currently still serialising, Export() will see the cancellation + // status and won't schedule writing. + OnProgress(ExportProgressStatus::FAILED_CANCELLED, std::string()); + + // If we are currently writing to the disk, we will have to cleanup the file + // once writing stops. + Cleanup(); +} + +ExportProgressStatus PasswordManagerExporter::GetProgressStatus() { + return last_progress_status_; +} + +void PasswordManagerExporter::SetWriteForTesting(WriteCallback write_function) { + write_function_ = std::move(write_function); +} + +void PasswordManagerExporter::SetDeleteForTesting( + DeleteCallback delete_callback) { + delete_function_ = std::move(delete_callback); +} + +void PasswordManagerExporter::SetSetPosixFilePermissionsForTesting( + SetPosixFilePermissionsCallback set_permissions_callback) { + set_permissions_function_ = std::move(set_permissions_callback); +} + +bool PasswordManagerExporter::IsReadyForExport() { + return !destination_.empty() && !serialised_password_list_.empty(); +} + +void PasswordManagerExporter::Export() { + // If cancelling was requested while we were serialising the passwords, don't + // write anything to the disk. + if (GetProgressStatus() == ExportProgressStatus::FAILED_CANCELLED) { + serialised_password_list_.clear(); + return; + } + + base::PostTaskAndReplyWithResult( + task_runner_.get(), FROM_HERE, + base::BindOnce(DoWriteOnTaskRunner, write_function_, + set_permissions_function_, destination_, + std::move(serialised_password_list_)), + base::BindOnce(&PasswordManagerExporter::OnPasswordsExported, + weak_factory_.GetWeakPtr())); +} + +void PasswordManagerExporter::OnPasswordsExported(bool success) { + if (success) { + OnProgress(ExportProgressStatus::SUCCEEDED, std::string()); + } else { + OnProgress(ExportProgressStatus::FAILED_WRITE_FAILED, + destination_.DirName().BaseName().AsUTF8Unsafe()); + // Don't leave partial password files, if we tell the user we couldn't write + Cleanup(); + } +} + +void PasswordManagerExporter::OnProgress(ExportProgressStatus status, + const std::string& folder) { + last_progress_status_ = status; + on_progress_.Run(status, folder); +} + +void PasswordManagerExporter::Cleanup() { + // The PasswordManagerExporter instance may be destroyed before the cleanup is + // executed, e.g. because a new export was initiated. The cleanup should be + // carried out regardless, so we only schedule tasks which own their + // arguments. + // TODO(crbug.com/811779) When Chrome is overwriting an existing file, cancel + // should restore the file rather than delete it. + if (!destination_.empty()) { + task_runner_->PostTask( + FROM_HERE, + base::BindOnce(base::IgnoreResult(delete_function_), destination_)); + } +} + +} // namespace password_manager diff --git a/pool/shard006/C++/0074141_smoothFit.cpp b/pool/shard006/C++/0074141_smoothFit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a9cc4410683d7dbc750d9aed76b4fb0aa52b987 --- /dev/null +++ b/pool/shard006/C++/0074141_smoothFit.cpp @@ -0,0 +1,165 @@ +// smoothFit.cpp : performs a smooth fit to scattered data +// + +#include +#include +#include + +#include "VectorField2D.h" +#include "ScatteredVectorData2D.h" +#include "ParameterFileReader.h" + +#include +#include + +#include +#include + + +bool getParameters(); + +bool getGridInfo(); + +bool constructGriddedFieldFromScatteredField(); + +UString inGridFileName; +UString inScatteredFieldFileName; +UString outGridFieldFileName; + +UArray imageSize; +UArray imageBounds; + +SInt32 smoothFitMinControlPointScatteredNeighbors; + + +int main(int argc, char * argv[]) +{ + + if(!getParameters()) + { + fprintf(stderr, "Could not read parameters\n"); + return -1; + } + + if(!getGridInfo()) + { + fprintf(stderr, "Could not read grid file\n"); + return -1; + } + + if(!constructGriddedFieldFromScatteredField()) + { + fprintf(stderr, "Could not perform smooth fit\n"); + return -1; + } + + + return 0; +} + + +bool getParameters() +{ + UString fileName = "parameters.ascii"; + ParameterFileReader reader(fileName); + + UString defaultParameterFile; + UString tag; + tag = "defaultParameterFile"; + if(reader.getString(tag, defaultParameterFile)) + { + reader.addFile(defaultParameterFile); + } + + tag = "inGridFileName"; + if(!reader.getString(tag, inGridFileName)) + { + fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag); + return false; + } + tag = "inScatteredFieldFileName"; + if(!reader.getString(tag, inScatteredFieldFileName)) + { + fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag); + return false; + } + tag = "outGridFieldFileName"; + if(!reader.getString(tag, outGridFieldFileName)) + { + fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag); + return false; + } + tag = "smoothFitMinControlPointScatteredNeighbors"; + if(!reader.getInteger(tag, smoothFitMinControlPointScatteredNeighbors)) + { + smoothFitMinControlPointScatteredNeighbors = 16; + } + return true; +} + +bool getGridInfo() +{ + + VectorField2D grid; + + if(!grid.read(inGridFileName)) + { + fprintf(stderr, "getGridInfo: Could not read grid velocity scaling from file %s\n", (const char *)inGridFileName); + return false; + } + + imageSize.setSize(2); + imageSize[0] = grid.getXSize(); + imageSize[1] = grid.getYSize(); + + imageBounds.setSize(4); + imageBounds[0] = grid.getXLower(); + imageBounds[1] = grid.getXUpper(); + imageBounds[2] = grid.getYLower(); + imageBounds[3] = grid.getYUpper(); + + return true; +} + +bool constructGriddedFieldFromScatteredField() +{ + + ScatteredVectorData2D scatteredField; + if(!scatteredField.read(inScatteredFieldFileName)) + return false; + + VectorField2D griddedField(imageSize[0], imageSize[1], imageBounds[0], imageBounds[1], imageBounds[2], imageBounds[3]); + + double meanRes = 0.0; + UArray residuals; + + scatteredField.smoothFit(griddedField, smoothFitMinControlPointScatteredNeighbors, residuals, meanRes); + + if(!griddedField.write(outGridFieldFileName)) + return false; + + // add the mean residual + hid_t fileID = H5Fopen(outGridFieldFileName, H5F_ACC_RDWR, H5P_DEFAULT); + if(fileID < 0) + { + fprintf(stderr, "constructGriddedFieldFromScatteredField: Could not open file %s\n", + (const char *)outGridFieldFileName); + return false; + } + + UString dataSetName = "/meanResidual"; + hsize_t dimensions[2]; + dimensions[0] = 1; + herr_t status = H5LTmake_dataset(fileID, dataSetName, 1, dimensions, H5T_NATIVE_DOUBLE, &meanRes); + if((status < 0)) + { + fprintf(stderr, "constructGriddedFieldFromScatteredField: Could not make dataset %s in file %s\n", + (const char *)dataSetName, (const char *)outGridFieldFileName); + return false; + } + + status = H5Fclose(fileID); + + return true; +} + diff --git a/pool/shard006/C++/0074149_BasilarMembraneNonlinearGammatone.cpp b/pool/shard006/C++/0074149_BasilarMembraneNonlinearGammatone.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09776dc6adfddcead7da2cb2a254e895d8d2c2ca --- /dev/null +++ b/pool/shard006/C++/0074149_BasilarMembraneNonlinearGammatone.cpp @@ -0,0 +1,234 @@ +#include +#include "Earlab.h" +#include "CParameterFile.h" +#include "ParameterStatus.h" +#include +#include +#include +#include +#include +#include "BasilarMembraneNonlinearGammatone.h" +#include "EarlabException.h" +#include +#ifdef _WIN32 +# include +#endif + +using namespace std; + +BasilarMembraneNonlinearGammatone::BasilarMembraneNonlinearGammatone() +{ + memset(this, 0, sizeof(BasilarMembraneNonlinearGammatone)); + SetModuleName("BasilarMembraneNonlinearGammatone"); +} + +BasilarMembraneNonlinearGammatone::~BasilarMembraneNonlinearGammatone() +{ + if (mMetadataFile != NULL) + delete mMetadataFile; + if (mCFArray_Hz != NULL) + delete [] mCFArray_Hz; + if (mDRNL != NULL) + delete [] mDRNL; + if (mLowpassFilter != NULL) + delete [] mLowpassFilter; +} + +int BasilarMembraneNonlinearGammatone::ReadParameters(const char *ParameterFileName) +{ + return ReadParameters(ParameterFileName, ModuleName()); +} + +int BasilarMembraneNonlinearGammatone::ReadParameters(const char *ParameterFileName, const char *SectionName) +{ + CParameterFile theParamFile(ParameterFileName); + ParameterStatus Status; + + Log(" ReadParameters: %s \"%s\"", ModuleName(), ParameterFileName); + + // Number of channels and Frame Size are passed as parameters to Start, see that function for details + Status = theParamFile.GetParameter(SectionName, "SampleRate_Hz", mSampleRate_Hz, mSampleRate_Hz); + + // Greenwood frequency placemap parameters + // boilerplate--------------------------------| Parameter Name (in file) | Local variable | default value + Status = theParamFile.GetParameter(SectionName, "DisableNonlinearPath", mDisableNonlinearPath, false); + Status = theParamFile.GetParameter(SectionName, "A", mA, 165); + Status = theParamFile.GetParameter(SectionName, "Alpha", mAlpha, 2.1); + Status = theParamFile.GetParameter(SectionName, "K", mK, 1.0); + Status = theParamFile.GetParameter(SectionName, "CochleaLength_mm", mCochleaLength_mm, 35.0); + Status = theParamFile.GetParameter(SectionName, "BMStartPercent", mBMStartPercent, 0.0); + Status = theParamFile.GetParameter(SectionName, "BMEndPercent", mBMEndPercent, 100.0); + + Status = theParamFile.GetParameter(SectionName, "ProduceOutputFile", mProduceOutputFile, false); + Status = theParamFile.GetParameter(SectionName, "BinaryOutput", mBinaryOutput, false); + Status = theParamFile.GetParameter(SectionName, "CFFileName", mCFFileName, sizeof(mCFFileName), NULL); + Status = theParamFile.GetParameter(SectionName, "InnerHaircellCouplingFrequency_Hz", InnerHaircellCouplingFrequency_Hz, 20000.0); + + return 1; +} + +int BasilarMembraneNonlinearGammatone::Start(int NumInputs, + EarlabDataStreamType InputTypes[EarlabMaxIOStreamCount], int InputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions], + int NumOutputs, + EarlabDataStreamType OutputTypes[EarlabMaxIOStreamCount], int OutputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions], + unsigned long OutputElementCounts[EarlabMaxIOStreamCount]) +{ + // Because this module produces data in a "Frequency-Time" format, the following statements apply: + // OutputSize[i][0] is the number of samples in a frame (the term "samples" includes data for all frequency channels at one time index) + // OutputSize[i][1] is the number of frequency channels provided + // OutputSize[i][2] must be 0 to mark the end of the dimension count + + int i,process_counter; + double PlacemapStepSize_mm, CurrentPlace_mm, CurrentCF_Hz; + char MetadataFileName[256]; + + Log(" Start: %s", ModuleName()); + // Perform some validation on my parameters to make sure I can handle the requested input and output streams... + if (NumInputs != 1) + throw EarlabException("%s: Currently this module can only handle one input stream. Sorry!", ModuleName()); + + if (NumOutputs != 1) + throw EarlabException("%s: Currently this module can only handle one output stream. Sorry!", ModuleName()); + + if (InputTypes[0] != WaveformData) + throw EarlabException("%s: Currently this module can only handle waveform input data streams. Sorry!", ModuleName()); + + if (OutputTypes[0] != WaveformData) + throw EarlabException("%s: Currently this module can only handle waveform output data streams. Sorry!", ModuleName()); + + if (InputSize[0][0] != OutputSize[0][0]) + throw EarlabException("%s: Input and output frame lengths must be identical. Sorry!", ModuleName()); + + if (InputSize[0][1] != 0) + throw EarlabException("%s: Input data must be one-dimensional array. Sorry!", ModuleName()); + + if (OutputSize[0][2] != 0) + throw EarlabException("%s: Output signal must be two-dimensional array. Sorry!", ModuleName()); + + OutputElementCounts[0] = OutputSize[0][0] * OutputSize[0][1]; + + mFrameSize_Samples = OutputSize[0][0]; + mNumChannels = OutputSize[0][1]; + + process_counter = 0; +/*****************************************************************************/ +/* SET BASILIAR MEMBRANE ARRAYS AND CONSTANTS */ +/*****************************************************************************/ + + mCounter = 0; + if (mProduceOutputFile) + { +#ifdef NOTWINDOWS +# define WR_BIN "w" +# define WR_TEXT "w" +#else +# define WR_BIN "wb" +# define WR_TEXT "wt" +#endif + if (mBinaryOutput) + { +#ifdef _WIN32 + _fmode = _O_BINARY; +#endif + mOutputFile = OpenOutputFile(mCFFileName, WR_BIN); + } + else + { +#ifdef _WIN32 + _fmode = _O_TEXT; +#endif + mOutputFile = OpenOutputFile(mCFFileName, WR_TEXT); + } + + if (mOutputFile == NULL) + return 0; + } + else + mOutputFile = NULL; + + mCFArray_Hz = new double [mNumChannels]; + mDRNL = new LopezPovedaMeddisDualResonanceNonlinear[mNumChannels]; + mCochleaStartPos_mm = mCochleaLength_mm * (mBMStartPercent / 100); + mCochleaEndPos_mm = mCochleaLength_mm * ( mBMEndPercent / 100); + mCochleaModeledLength_mm = mCochleaEndPos_mm - mCochleaStartPos_mm; + PlacemapStepSize_mm = mCochleaModeledLength_mm / (double)mNumChannels; + mLowpassFilter = new FirstOrderLowpass[mNumChannels]; + for (i = 0; i < mNumChannels; i++) + { + mLowpassFilter[i].SetSampleRate_Hz(mSampleRate_Hz); + mLowpassFilter[i].SetCornerFrequency_Hz(InnerHaircellCouplingFrequency_Hz); + CurrentPlace_mm = (PlacemapStepSize_mm * i) + mCochleaStartPos_mm; + CurrentCF_Hz = mA * (pow(10.0, mAlpha * (CurrentPlace_mm / mCochleaLength_mm)) - mK); + mCFArray_Hz[i] = CurrentCF_Hz; + + // Initialize the filter for this channel + mDRNL[i].Init(CurrentCF_Hz, mSampleRate_Hz); + + if (mOutputFile != NULL) + { + if (mBinaryOutput) + fwrite(&CurrentCF_Hz, sizeof(double), 1, mOutputFile); + else + fprintf(mOutputFile, "%g\n", CurrentCF_Hz); + } + } + if (mOutputFile != NULL) + fclose(mOutputFile); + + mInputScaleFactor = 1.0 / 3.2e10; + mOutputScaleFactor = 1.0e9 / (800 * PI); + sprintf(MetadataFileName, "%s.1.metadata", ModuleName()); + mMetadataFile = new XmlMetadataFile(MetadataFileName); + mMetadataFile->SetSampleRate_Hz(mSampleRate_Hz); + mMetadataFile->Add(new XmlParameter("Units", "Membrane displacement (nm)")); + //mMetadataFile->Add(new XmlParameter("FrameSize", mFrameSize_Samples)); + //mMetadataFile->Add(new XmlParameter("SampleRate_Hz", mSampleRate_Hz)); + mMetadataFile->Add(new XmlDimension("Frequency (Hz)", mNumChannels, mCFArray_Hz)); + mMetadataFile->SetSource(new XmlSource(ModuleName(), "BasilarMembraneNonlinearGammatone_0.1.0.0")); + mMetadataFile->Write(); + return 1; +} + +int BasilarMembraneNonlinearGammatone::Advance(EarlabDataStream *InputStream[EarlabMaxIOStreamCount], EarlabDataStream *OutputStream[EarlabMaxIOStreamCount]) +{ + int i,j; + double CurInputSample; + float CurOutputSample; + FloatMatrixN *Input, *Output; + + Log(" Advance: %s", ModuleName()); + + Input = ((EarlabWaveformStream *)InputStream[0])->GetData(); // Only supporting one output at the present moment + Output = ((EarlabWaveformStream *)OutputStream[0])->GetData(); // Only supporting one output at the present moment + + if (Input->Rank(0) != mFrameSize_Samples) + throw EarlabException("%s: Input size mismatch with Start()", ModuleName()); + if ((Output->Rank(0) != mFrameSize_Samples) || (Output->Rank(1) != mNumChannels)) + throw EarlabException("%s: Output size mismatch with Start()", ModuleName()); + + for (j = 0; j < mFrameSize_Samples; j++) + { + CurInputSample = Input->Data(j) * mInputScaleFactor; + for (i = 0; i < mNumChannels; i++) + { + CurOutputSample = (float)(mLowpassFilter[i].Filter(mDRNL[i].Filter(CurInputSample, mDisableNonlinearPath)) * mOutputScaleFactor); + mMetadataFile->UpdateMinMax(CurOutputSample); + Output->Data(j, i) = CurOutputSample; + } + mMetadataFile->AddSample(); + } + return (mFrameSize_Samples * mNumChannels); +} + +int BasilarMembraneNonlinearGammatone::Stop(void) +{ + Log(" Stop: %s", ModuleName()); + mMetadataFile->Write(); + return 1; +} + +int BasilarMembraneNonlinearGammatone::Unload(void) +{ + Log(" Unload: %s", ModuleName()); + return 1; +} diff --git a/pool/shard006/C++/0074151_HumanPodController.cpp b/pool/shard006/C++/0074151_HumanPodController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68a043f28d00e6946909ee9dbcaf8f7b686cd097 --- /dev/null +++ b/pool/shard006/C++/0074151_HumanPodController.cpp @@ -0,0 +1,26 @@ +#import "HumanPodController.h" + +void HumanPodController::Update(float dt) +{ + super::Update(dt); + + if (!theController.IsConnected()) + { + return; + } + + float leftTrigger = (theController.GetLeftTrigger() + 32768.0) / (2 * 32768.0); + float rightTrigger = (theController.GetRightTrigger() + 32768.0) / (2 * 32768.0); + float leftThrottle = theController.GetLeftThumbVec2().Y; + float rightThrottle = theController.GetRightThumbVec2().Y; + + racer->leftEngine->SetLeftFlap(leftTrigger); + racer->leftEngine->SetRightFlap(rightTrigger); + racer->rightEngine->SetLeftFlap(leftTrigger); + racer->rightEngine->SetRightFlap(rightTrigger); + racer->pod->SetLeftFlap(leftTrigger); + racer->pod->SetRightFlap(rightTrigger); + + racer->leftEngine->throttle = leftThrottle; + racer->rightEngine->throttle = rightThrottle; +} diff --git a/pool/shard006/C++/0074156_edittooldlg.cpp b/pool/shard006/C++/0074156_edittooldlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31d3731d8d83aa6febe3bfbbbd784181a3a2ad93 --- /dev/null +++ b/pool/shard006/C++/0074156_edittooldlg.cpp @@ -0,0 +1,91 @@ +/* + * This file is part of the Code::Blocks IDE and licensed under the GNU Lesser General Public License, version 3 + * http://www.gnu.org/licenses/lgpl-3.0.html + * + * $Revision$ + * $Id$ + * $HeadURL$ + */ + +#include "sdk_precomp.h" + +#ifndef CB_PRECOMP + #include + #include + #include + #include + #include + #include + #include + #include "cbtool.h" + #include "cbexception.h" + #include "globals.h" +#endif + +#include "edittooldlg.h" +#include + + +BEGIN_EVENT_TABLE(EditToolDlg, wxScrollingDialog) + EVT_BUTTON(XRCID("btnBrowseCommand"), EditToolDlg::OnBrowseCommand) + EVT_BUTTON(XRCID("btnBrowseDir"), EditToolDlg::OnBrowseDir) + EVT_UPDATE_UI(-1, EditToolDlg::OnUpdateUI) +END_EVENT_TABLE() + +EditToolDlg::EditToolDlg(wxWindow* parent, cbTool* tool) + : m_Tool(tool) +{ + if (!tool) + cbThrow(_T("Tool* parameter is mandatory in EditToolDlg()")); + + wxXmlResource::Get()->LoadObject(this, parent, _T("dlgEditTool"),_T("wxScrollingDialog")); + XRCCTRL(*this, "txtName", wxTextCtrl)->SetValue(m_Tool->GetName()); + XRCCTRL(*this, "txtCommand", wxTextCtrl)->SetValue(m_Tool->GetCommand()); + XRCCTRL(*this, "txtParams", wxTextCtrl)->SetValue(m_Tool->GetParams()); + XRCCTRL(*this, "txtDir", wxTextCtrl)->SetValue(m_Tool->GetWorkingDir()); + XRCCTRL(*this, "rbLaunchOptions", wxRadioBox)->SetSelection(static_cast(m_Tool->GetLaunchOption())); +} // end of constructor + +EditToolDlg::~EditToolDlg() +{ + //dtor +} + +// events + +void EditToolDlg::OnUpdateUI(cb_unused wxUpdateUIEvent& event) +{ + const wxString name = XRCCTRL(*this, "txtName", wxTextCtrl)->GetValue(); + const wxString command = XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue(); + bool en = !name.IsEmpty() && !command.IsEmpty(); + XRCCTRL(*this, "wxID_OK", wxButton)->Enable(en); +} // end of OnUpdateUI + +void EditToolDlg::OnBrowseCommand(cb_unused wxCommandEvent& event) +{ + const wxFileName file(XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue()); + wxString filename = wxFileSelector(_("Select executable"), file.GetPath(wxPATH_GET_VOLUME), file.GetFullName()); + if (!filename.IsEmpty()) + XRCCTRL(*this, "txtCommand", wxTextCtrl)->SetValue(filename); +} // end of OnBrowseCommand + +void EditToolDlg::OnBrowseDir(cb_unused wxCommandEvent& event) +{ + const wxString dir = ChooseDirectory(this, _("Select working directory"), XRCCTRL(*this, "txtDir", wxTextCtrl)->GetValue()); + if (!dir.IsEmpty()) + XRCCTRL(*this, "txtDir", wxTextCtrl)->SetValue(dir); +} // end of OnBrowseDir + +void EditToolDlg::EndModal(int retCode) +{ + if (retCode == wxID_OK) + { + m_Tool->SetName(XRCCTRL(*this, "txtName", wxTextCtrl)->GetValue()); + m_Tool->SetCommand(XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue()); + m_Tool->SetParams(XRCCTRL(*this, "txtParams", wxTextCtrl)->GetValue()); + m_Tool->SetWorkingDir(XRCCTRL(*this, "txtDir", wxTextCtrl)->GetValue()); + m_Tool->SetLaunchOption(static_cast(XRCCTRL(*this, "rbLaunchOptions", wxRadioBox)->GetSelection())); + } + + wxScrollingDialog::EndModal(retCode); +} // end of EndModal diff --git a/pool/shard006/C++/0074157_mediainfo.cpp b/pool/shard006/C++/0074157_mediainfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5159cfe7cf2a307e0da03d75062361df9b3d0d58 --- /dev/null +++ b/pool/shard006/C++/0074157_mediainfo.cpp @@ -0,0 +1,51 @@ +#include "mediainfo.h" +#include "qdebug.h" + +MediaInfo::MediaInfo(QString filepath, bool onlyTags) { + readed = false; + fileName = filepath.toStdWString(); + TagLib::FileRef f(fileName.c_str(), !onlyTags, onlyTags ? TagLib::AudioProperties::Fast : TagLib::AudioProperties::Accurate); + + if (!f.isNull()) { + size = f.file() -> length(); + readed = true; + artist = QString::fromStdWString(f.tag() -> artist().toWString()); + title = QString::fromStdWString(f.tag() -> title().toWString()); + album = QString::fromStdWString(f.tag() -> album().toWString()); + genre = QString::fromStdWString(f.tag() -> genre().toWString()); + year = f.tag() -> year(); + track = f.tag() -> track(); + + if (!onlyTags) + readInfo(f); + } +} + +void MediaInfo::initInfo() { + TagLib::FileRef f(fileName.c_str(), true, TagLib::AudioProperties::Accurate); + readInfo(f); +} + +void MediaInfo::readInfo(TagLib::FileRef f) { + bitrate = f.audioProperties() -> bitrate(); + channels = f.audioProperties() -> channels(); + duration = f.audioProperties() -> length(); + sampleRate = f.audioProperties() -> sampleRate(); +} + +bool MediaInfo::initiated() const { + return readed; +} + +QString MediaInfo::getArtist() const { return artist; } +QString MediaInfo::getTitle() const { return title; } +QString MediaInfo::getAlbum() const { return album; } +QString MediaInfo::getGenre() const { return genre; } + +long MediaInfo::getSize() const { return size; } +int MediaInfo::getYear() const { return year; } +int MediaInfo::getTrack() const { return track; } +int MediaInfo::getChannels() const { return channels; } +int MediaInfo::getBitrate() const { return bitrate; } +int MediaInfo::getDuration() const { return duration; } +int MediaInfo::getSampleRate() const { return sampleRate; } diff --git a/pool/shard006/C++/0074164_wld_mode_setpoint.cpp b/pool/shard006/C++/0074164_wld_mode_setpoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f6f9990bed9003922aec70a6a0e62335ce87145 --- /dev/null +++ b/pool/shard006/C++/0074164_wld_mode_setpoint.cpp @@ -0,0 +1,146 @@ +/* + * Platformer Game Engine by Wohlstand, a free platform for game making + * Copyright (c) 2014-2021 Vitaly Novichkov + * + * 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 + * 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 +#include + +#include "../wld_scene.h" +#include "../wld_item_placing.h" +#include "wld_mode_setpoint.h" + +WLD_ModeSetPoint::WLD_ModeSetPoint(QGraphicsScene *parentScene, QObject *parent) + : EditMode("SetPoint", parentScene, parent) +{} + +WLD_ModeSetPoint::~WLD_ModeSetPoint() +{} + +void WLD_ModeSetPoint::set() +{ + if(!scene) return; + WldScene *s = dynamic_cast(scene); + + s->resetResizers(); + + s->m_eraserIsEnabled = false; + s->m_pastingMode = false; + s->m_busyMode = true; + s->m_disableMoveItems = false; + + s->m_viewPort->setInteractive(true); + s->m_viewPort->setCursor(Themes::Cursor(Themes::cursor_placing)); + s->m_viewPort->setDragMode(QGraphicsView::NoDrag); + s->m_viewPort->setRenderHint(QPainter::Antialiasing, true); + s->m_viewPort->viewport()->setMouseTracking(true); +} + +void WLD_ModeSetPoint::mousePress(QGraphicsSceneMouseEvent *mouseEvent) +{ + if(!scene) return; + WldScene *s = dynamic_cast(scene); + Q_ASSERT(s); + + if((!s->m_isSelectionDialog) && ((mouseEvent->buttons() & Qt::RightButton) != 0)) + { + MainWinConnect::pMainWin->on_actionSelect_triggered(); + dontCallEvent = true; + s->m_mouseIsMovedAfterKey = true; + return; + } + + if(!(mouseEvent->buttons() & Qt::LeftButton)) // Deny any other mouse buttons + return; + + if(s->m_cursorItemImg) + { + s->m_cursorItemImg->setPos(QPointF(s->applyGrid(mouseEvent->scenePos().toPoint() - + QPoint(WldPlacingItems::c_offset_x, + WldPlacingItems::c_offset_y), + WldPlacingItems::gridSz, + WldPlacingItems::gridOffset))); + s->m_pointSelector.setPoint(s->m_cursorItemImg->scenePos().toPoint()); + emit s->m_pointSelector.pointSelected(s->m_pointSelector.m_pointCoord); + } + dontCallEvent = true; +} + +void WLD_ModeSetPoint::mouseMove(QGraphicsSceneMouseEvent *mouseEvent) +{ + if(!scene) return; + WldScene *s = dynamic_cast(scene); + + if(s->m_cursorItemImg) + { + + s->m_cursorItemImg->setPos(QPointF(s->applyGrid(mouseEvent->scenePos().toPoint() - + QPoint(WldPlacingItems::c_offset_x, + WldPlacingItems::c_offset_y), + WldPlacingItems::gridSz, + WldPlacingItems::gridOffset))); + s->m_cursorItemImg->show(); + + s->setMessageBoxItem(true, mouseEvent->scenePos(), + (s->m_cursorItemImg ? + ( + QString::number(s->m_cursorItemImg->scenePos().toPoint().x()) + "x" + + QString::number(s->m_cursorItemImg->scenePos().toPoint().y()) + ) + : "")); + + } +} + +void WLD_ModeSetPoint::mouseRelease(QGraphicsSceneMouseEvent *) +{ + if(!scene) return; + WldScene *s = dynamic_cast(scene); + + if(!s->m_isSelectionDialog) + { + MainWinConnect::pMainWin->on_actionSelect_triggered(); + MainWinConnect::pMainWin->dock_WldItemProps->acceptWarpToCoordinates(s->m_pointSelector.m_pointCoord); + s->openProps(); + //s->MouseReleaseEventOnly = true; + //s->mouseReleaseEvent(mouseEvent); + dontCallEvent = true; + } + +} + +void WLD_ModeSetPoint::keyPress(QKeyEvent *keyEvent) +{ + Q_UNUSED(keyEvent) +} + +void WLD_ModeSetPoint::keyRelease(QKeyEvent *keyEvent) +{ + if(!scene) return; + WldScene *s = dynamic_cast(scene); + + switch(keyEvent->key()) + { + case(Qt::Key_Escape): + if(s->m_isSelectionDialog) break; //Disable this key in the point selection dialog + MainWinConnect::pMainWin->on_actionSelect_triggered(); + break; + default: + break; + } +} + diff --git a/pool/shard006/C++/0074166_force_mic_volume_max.cc b/pool/shard006/C++/0074166_force_mic_volume_max.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6b15968665cfa982fca6a25fa54aa1a1c3919a8 --- /dev/null +++ b/pool/shard006/C++/0074166_force_mic_volume_max.cc @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +// This utility will portably force the volume of the default microphone to max. + +#include + +#include "webrtc/base/scoped_ptr.h" +#include "webrtc/test/channel_transport/channel_transport.h" +#include "webrtc/voice_engine/include/voe_audio_processing.h" +#include "webrtc/voice_engine/include/voe_base.h" +#include "webrtc/voice_engine/include/voe_volume_control.h" + +int main(int argc, char** argv) { + webrtc::VoiceEngine* voe = webrtc::VoiceEngine::Create(); + if (voe == NULL) { + fprintf(stderr, "Failed to initialize voice engine.\n"); + return 1; + } + + webrtc::VoEBase* base = webrtc::VoEBase::GetInterface(voe); + webrtc::VoEVolumeControl* volume_control = + webrtc::VoEVolumeControl::GetInterface(voe); + + if (base->Init() != 0) { + fprintf(stderr, "Failed to initialize voice engine base.\n"); + return 1; + } + // Set to 0 first in case the mic is above 100%. + if (volume_control->SetMicVolume(0) != 0) { + fprintf(stderr, "Failed set volume to 0.\n"); + return 1; + } + if (volume_control->SetMicVolume(255) != 0) { + fprintf(stderr, "Failed set volume to 255.\n"); + return 1; + } + + return 0; +} diff --git a/pool/shard006/C++/0074168_DispalyingVideo.cpp b/pool/shard006/C++/0074168_DispalyingVideo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f03504349df2a8f664360031220c2459385dc032 --- /dev/null +++ b/pool/shard006/C++/0074168_DispalyingVideo.cpp @@ -0,0 +1,22 @@ +#include + +int main() +{ + cvNamedWindow("Video Display", CV_WINDOW_AUTOSIZE); + CvCapture * capture = cvCreateFileCapture("C:\\Users\\sigit_000\\Downloads\\Video\\Opening a Video with Visual Studio 2013 and OpenCV 2.4.10.mp4"); + IplImage* frame; + while (true) + { + frame = cvQueryFrame(capture); + if (!frame) + break; + cvShowImage("Video Display", frame); + char c = cvWaitKey(20); + if (c == 27) + break; + } + cvReleaseCapture(&capture); + //cvDestroyWindow() + + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0074173_UnionTypesModules.cpp b/pool/shard006/C++/0074173_UnionTypesModules.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd60b7378d1f5e25e54cc75229e48e3382ea2535 --- /dev/null +++ b/pool/shard006/C++/0074173_UnionTypesModules.cpp @@ -0,0 +1,84 @@ +// Copyright 2014 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. + +// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! + +#include "config.h" +#include "bindings/modules/v8/UnionTypesModules.h" + + +namespace blink { + +BooleanOrString::BooleanOrString() + : m_type(SpecificTypeNone) +{ +} + +bool BooleanOrString::getAsBoolean() const +{ + ASSERT(isBoolean()); + return m_boolean; +} + +void BooleanOrString::setBoolean(bool value) +{ + ASSERT(isNull()); + m_boolean = value; + m_type = SpecificTypeBoolean; +} + +String BooleanOrString::getAsString() const +{ + ASSERT(isString()); + return m_string; +} + +void BooleanOrString::setString(String value) +{ + ASSERT(isNull()); + m_string = value; + m_type = SpecificTypeString; +} + +void V8BooleanOrString::toImpl(v8::Isolate* isolate, v8::Local v8Value, BooleanOrString& impl, ExceptionState& exceptionState) +{ + if (v8Value.IsEmpty()) + return; + + if (v8Value->IsBoolean()) { + impl.setBoolean(v8Value->ToBoolean()->Value()); + return; + } + + { + TOSTRING_VOID_EXCEPTIONSTATE(V8StringResource<>, cppValue, v8Value, exceptionState); + impl.setString(cppValue); + return; + } + +} + +v8::Local toV8(const BooleanOrString& impl, v8::Local creationContext, v8::Isolate* isolate) +{ + switch (impl.m_type) { + case BooleanOrString::SpecificTypeNone: + return v8::Null(isolate); + case BooleanOrString::SpecificTypeBoolean: + return v8Boolean(impl.getAsBoolean(), isolate); + case BooleanOrString::SpecificTypeString: + return v8String(isolate, impl.getAsString()); + default: + ASSERT_NOT_REACHED(); + } + return v8::Local(); +} + +BooleanOrString NativeValueTraits::nativeValue(const v8::Local& value, v8::Isolate* isolate, ExceptionState& exceptionState) +{ + BooleanOrString impl; + V8BooleanOrString::toImpl(isolate, value, impl, exceptionState); + return impl; +} + +} // namespace blink diff --git a/pool/shard006/C++/0074174_AP_Parachute.cpp b/pool/shard006/C++/0074174_AP_Parachute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e792571f14751d5dad58a9b2d7e8a1ce900d3b5b --- /dev/null +++ b/pool/shard006/C++/0074174_AP_Parachute.cpp @@ -0,0 +1,152 @@ +#include "AP_Parachute.h" +#include +#include +#include +#include +#include +#include +#include +#include + +extern const AP_HAL::HAL& hal; + +const AP_Param::GroupInfo AP_Parachute::var_info[] = { + + // @Param: ENABLED + // @DisplayName: Parachute release enabled or disabled + // @Description: Parachute release enabled or disabled + // @Values: 0:Disabled,1:Enabled + // @User: Standard + AP_GROUPINFO_FLAGS("ENABLED", 0, AP_Parachute, _enabled, 0, AP_PARAM_FLAG_ENABLE), + + // @Param: TYPE + // @DisplayName: Parachute release mechanism type (relay or servo) + // @Description: Parachute release mechanism type (relay or servo) + // @Values: 0:First Relay,1:Second Relay,2:Third Relay,3:Fourth Relay,10:Servo + // @User: Standard + AP_GROUPINFO("TYPE", 1, AP_Parachute, _release_type, AP_PARACHUTE_TRIGGER_TYPE_RELAY_0), + + // @Param: SERVO_ON + // @DisplayName: Parachute Servo ON PWM value + // @Description: Parachute Servo PWM value in microseconds when parachute is released + // @Range: 1000 2000 + // @Units: PWM + // @Increment: 1 + // @User: Standard + AP_GROUPINFO("SERVO_ON", 2, AP_Parachute, _servo_on_pwm, AP_PARACHUTE_SERVO_ON_PWM_DEFAULT), + + // @Param: SERVO_OFF + // @DisplayName: Servo OFF PWM value + // @Description: Parachute Servo PWM value in microseconds when parachute is not released + // @Range: 1000 2000 + // @Units: PWM + // @Increment: 1 + // @User: Standard + AP_GROUPINFO("SERVO_OFF", 3, AP_Parachute, _servo_off_pwm, AP_PARACHUTE_SERVO_OFF_PWM_DEFAULT), + + // @Param: ALT_MIN + // @DisplayName: Parachute min altitude in meters above home + // @Description: Parachute min altitude above home. Parachute will not be released below this altitude. 0 to disable alt check. + // @Range: 0 32000 + // @Units: m + // @Increment: 1 + // @User: Standard + AP_GROUPINFO("ALT_MIN", 4, AP_Parachute, _alt_min, AP_PARACHUTE_ALT_MIN_DEFAULT), + + // @Param: DELAY_MS + // @DisplayName: Parachute release delay + // @Description: Delay in millseconds between motor stop and chute release + // @Range: 0 5000 + // @Units: ms + // @Increment: 1 + // @User: Standard + AP_GROUPINFO("DELAY_MS", 5, AP_Parachute, _delay_ms, AP_PARACHUTE_RELEASE_DELAY_MS), + + AP_GROUPEND +}; + +/// enabled - enable or disable parachute release +void AP_Parachute::enabled(bool on_off) +{ + _enabled = on_off; + + // clear release_time + _release_time = 0; + + AP::logger().Write_Event(_enabled ? DATA_PARACHUTE_ENABLED : DATA_PARACHUTE_DISABLED); +} + +/// release - release parachute +void AP_Parachute::release() +{ + // exit immediately if not enabled + if (_enabled <= 0) { + return; + } + + gcs().send_text(MAV_SEVERITY_INFO,"Parachute: Released"); + AP::logger().Write_Event(DATA_PARACHUTE_RELEASED); + + // set release time to current system time + if (_release_time == 0) { + _release_time = AP_HAL::millis(); + } + + _release_initiated = true; + + // update AP_Notify + AP_Notify::flags.parachute_release = 1; +} + +/// update - shuts off the trigger should be called at about 10hz +void AP_Parachute::update() +{ + // exit immediately if not enabled or parachute not to be released + if (_enabled <= 0) { + return; + } + + // calc time since release + uint32_t time_diff = AP_HAL::millis() - _release_time; + uint32_t delay_ms = _delay_ms<=0 ? 0: (uint32_t)_delay_ms; + + // check if we should release parachute + if ((_release_time != 0) && !_release_in_progress) { + if (time_diff >= delay_ms) { + if (_release_type == AP_PARACHUTE_TRIGGER_TYPE_SERVO) { + // move servo + SRV_Channels::set_output_pwm(SRV_Channel::k_parachute_release, _servo_on_pwm); + }else if (_release_type <= AP_PARACHUTE_TRIGGER_TYPE_RELAY_3) { + // set relay + _relay.on(_release_type); + } + _release_in_progress = true; + _released = true; + } + }else if ((_release_time == 0) || time_diff >= delay_ms + AP_PARACHUTE_RELEASE_DURATION_MS) { + if (_release_type == AP_PARACHUTE_TRIGGER_TYPE_SERVO) { + // move servo back to off position + SRV_Channels::set_output_pwm(SRV_Channel::k_parachute_release, _servo_off_pwm); + }else if (_release_type <= AP_PARACHUTE_TRIGGER_TYPE_RELAY_3) { + // set relay back to zero volts + _relay.off(_release_type); + } + // reset released flag and release_time + _release_in_progress = false; + _release_time = 0; + // update AP_Notify + AP_Notify::flags.parachute_release = 0; + } +} + +// singleton instance +AP_Parachute *AP_Parachute::_singleton; + +namespace AP { + +AP_Parachute *parachute() +{ + return AP_Parachute::get_singleton(); +} + +} diff --git a/pool/shard006/C++/0074176_bosh_example.cpp b/pool/shard006/C++/0074176_bosh_example.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3acbc3ef12a16944bb405ec06f51e2edfa38ea33 --- /dev/null +++ b/pool/shard006/C++/0074176_bosh_example.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2004-2014 by Jakob Schröter + * This file is part of the gloox library. http://camaya.net/gloox + * + * This software is distributed under a license. The full license + * agreement can be found in the file LICENSE in this distribution. + * This software may not be copied, modified, sold or distributed + * other than expressed in the named license agreement. + * + * This software is distributed without any warranty. + */ + +#include "../client.h" +#include "../messagesessionhandler.h" +#include "../messageeventhandler.h" +#include "../messageeventfilter.h" +#include "../chatstatehandler.h" +#include "../chatstatefilter.h" +#include "../connectionlistener.h" +#include "../disco.h" +#include "../message.h" +#include "../gloox.h" +#include "../lastactivity.h" +#include "../loghandler.h" +#include "../logsink.h" +#include "../connectiontcpclient.h" +#include "../connectionsocks5proxy.h" +#include "../messagehandler.h" +#include "../connectionbosh.h" +#include "../connectionhttpproxy.h" + +using namespace gloox; + +#include +#include +#include + +#include // [s]print[f] + +#if defined( WIN32 ) || defined( _WIN32 ) +# include +#endif + +class MessageTest : public MessageSessionHandler, ConnectionListener, LogHandler, + MessageEventHandler, MessageHandler, ChatStateHandler +{ + public: + MessageTest() : m_session( 0 ), m_messageEventFilter( 0 ), m_chatStateFilter( 0 ) {} + + virtual ~MessageTest() {} + + void start() + { + + JID jid( "js@example.net/bosh" ); + j = new Client( jid, "test" ); + j->registerConnectionListener( this ); + j->registerMessageSessionHandler( this, 0 ); + j->disco()->setIdentity( "client", "bot" ); + j->disco()->addFeature( XMLNS_CHAT_STATES ); + j->setCompression(false); + //StringList ca; + //ca.push_back( "/path/to/cacert.crt" ); + //j->setCACerts( ca ); + + j->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this ); + + +/* + ConnectionTCPClient* conn0 = new ConnectionTCPClient( j->logInstance(), "example.net", 8081 ); + ConnectionHTTPProxy* conn1 = new ConnectionHTTPProxy( conn0, j->logInstance(), "foo", 8080 ); + ConnectionBOSH* conn2 = new ConnectionBOSH( j, conn1, j->logInstance(), "camaya.net", "camaya.net" ); + conn2->setMode( ConnectionBOSH::ModeLegacyHTTP ); +// conn2->setMode( ConnectionBOSH::ModePersistentHTTP ); + j->setConnectionImpl( conn2 ); +*/ + + // this code connects to a jabber server through a BOSH connection... + ConnectionTCPClient* conn0 = new ConnectionTCPClient( j->logInstance(), "example.net", 8080 ); + ConnectionBOSH* conn1 = new ConnectionBOSH( j, conn0, j->logInstance(), "example.net", "example.net" ); +// conn1->setMode( ConnectionBOSH::ModeLegacyHTTP ); +// conn1->setMode( ConnectionBOSH::ModePersistentHTTP ); + j->setConnectionImpl( conn1 ); + + j->setForceNonSasl( true ); + + + + + if( j->connect( false ) ) + { + ConnectionError ce = ConnNoError; + while( ce == ConnNoError ) + { + ce = j->recv(); + } + printf( "ce: %d\n", ce ); + } + + delete( j ); + } + + virtual void onConnect() + { + printf( "connected!!!\n" ); + } + + virtual void onDisconnect( ConnectionError e ) + { + printf( "message_test: disconnected: %d\n", e ); + if( e == ConnAuthenticationFailed ) + printf( "auth failed. reason: %d\n", j->authError() ); + } + + virtual bool onTLSConnect( const CertInfo& info ) + { + time_t from( info.date_from ); + time_t to( info.date_to ); + + printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n" + "from: %s\nto: %s\n", + info.status, info.issuer.c_str(), info.server.c_str(), + info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(), + info.compression.c_str(), ctime( &from ), ctime( &to ) ); + return true; + } + + virtual void handleMessage( const Message& msg, MessageSession * /*session*/ ) + { + printf( "type: %d, subject: %s, message: %s, thread id: %s\n", msg.subtype(), + msg.subject().c_str(), msg.body().c_str(), msg.thread().c_str() ); + + std::string re = "You said:\n> " + msg.body() + "\nI like that statement."; + std::string sub; + if( !msg.subject().empty() ) + sub = "Re: " + msg.subject(); + + m_messageEventFilter->raiseMessageEvent( MessageEventDisplayed ); + m_messageEventFilter->raiseMessageEvent( MessageEventComposing ); + m_chatStateFilter->setChatState( ChatStateComposing ); + m_session->send( re, sub ); + + if( msg.body() == "quit" ) + j->disconnect(); + } + + virtual void handleMessageEvent( const JID& from, MessageEventType event ) + { + printf( "received event: %d from: %s\n", event, from.full().c_str() ); + } + + virtual void handleChatState( const JID& from, ChatStateType state ) + { + printf( "received state: %d from: %s\n", state, from.full().c_str() ); + } + + virtual void handleMessageSession( MessageSession *session ) + { + printf( "got new session\n"); + // this example can handle only one session. so we get rid of the old session + j->disposeMessageSession( m_session ); + m_session = session; + m_session->registerMessageHandler( this ); + m_messageEventFilter = new MessageEventFilter( m_session ); + m_messageEventFilter->registerMessageEventHandler( this ); + m_chatStateFilter = new ChatStateFilter( m_session ); + m_chatStateFilter->registerChatStateHandler( this ); + } + + virtual void handleLog( LogLevel level, LogArea area, const std::string& message ) + { + printf("%d: ", int( time( 0 ) ) ); + switch(area) + { + case LogAreaXmlIncoming: + printf("Received XML: "); + break; + case LogAreaXmlOutgoing: + printf("Sent XML: "); + break; + case LogAreaClassConnectionBOSH: + printf("BOSH: "); + break; + default: + printf("log: level: %d, area: %d, ", level, area); + } + printf("%s\n", message.c_str() ); + } + + private: + Client *j; + MessageSession *m_session; + MessageEventFilter *m_messageEventFilter; + ChatStateFilter *m_chatStateFilter; +}; + +int main( int /*argc*/, char** /*argv*/ ) +{ + MessageTest *r = new MessageTest(); + r->start(); + delete( r ); + return 0; +} diff --git a/pool/shard006/C++/0074177_EdgeIntersectionList.cpp b/pool/shard006/C++/0074177_EdgeIntersectionList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17f0949449e9d700ad908929e1903179e639dfc4 --- /dev/null +++ b/pool/shard006/C++/0074177_EdgeIntersectionList.cpp @@ -0,0 +1,254 @@ +/********************************************************************** + * $Id$ + * + * GEOS - Geometry Engine Open Source + * http://geos.refractions.net + * + * Copyright (C) 2001-2002 Vivid Solutions Inc. + * + * This is free software; you can redistribute and/or modify it under + * the terms of the GNU Lesser General Public Licence as published + * by the Free Software Foundation. + * See the COPYING file for more information. + * + **********************************************************************/ + +#include + +#ifndef DEBUG +#define DEBUG 0 +#endif + +namespace geos { + +EdgeIntersectionList::EdgeIntersectionList(Edge *newEdge) +{ + list=new vector(); + edge=newEdge; +} + +EdgeIntersectionList::~EdgeIntersectionList() +{ +// delete edge; + for(int i=0;i<(int)list->size();i++) { + delete (*list)[i]; + } + delete list; +} + +EdgeIntersection* +EdgeIntersectionList::add(const Coordinate& coord, int segmentIndex, double dist) +{ +#if DEBUG + cerr<<"["<::iterator insertIt=list->begin(); + bool isInList=findInsertionPoint(segmentIndex,dist,&insertIt); + EdgeIntersection *ei; + if (!isInList) + { +#if DEBUG + cerr<<" intersection not in list"<insert(insertIt,ei); + } + else + { + ei=*insertIt; +#if DEBUG + cerr<<" intersection already in list (should merge z)"<coord.toString()<::iterator +EdgeIntersectionList::iterator() +{ + return list->begin(); +} + +bool +EdgeIntersectionList::isEmpty() +{ + return list->empty(); +} + +bool +EdgeIntersectionList::findInsertionPoint(int segmentIndex, double dist,vector::iterator *insertIt) +{ + vector::iterator findIt=list->begin(); + //bool found=false; + while(findItend()) { + EdgeIntersection *ei=*findIt; + findIt++; + int compare=ei->compare(segmentIndex, dist); + // intersection found - insertIt.next() will retrieve it + if (compare==0) return true; + // this ei is past the intersection location, so intersection was not found + if (compare>0) return false; + // this ei was before the intersection point, so move to next + (*insertIt)++; + } + return false; +} + +bool +EdgeIntersectionList::isIntersection(const Coordinate& pt) +{ + vector::iterator it; + for (it=list->begin();itend();it++) { + EdgeIntersection *ei=*it; + if (ei->coord==pt) + return true; + } + return false; +} + +void +EdgeIntersectionList::addEndpoints() +{ + int maxSegIndex=edge->pts->getSize()-1; + add(edge->pts->getAt(0), 0, 0.0); + add(edge->pts->getAt(maxSegIndex), maxSegIndex, 0.0); +} + +void +EdgeIntersectionList::addSplitEdges(vector *edgeList) +{ + // ensure that the list has entries for the first and last point + // of the edge + addEndpoints(); + vector::iterator it=list->begin(); + // there should always be at least two entries in the list + EdgeIntersection *eiPrev=*it; + it++; + while (itend()) { + EdgeIntersection *ei=*it; + Edge *newEdge=createSplitEdge(eiPrev,ei); + edgeList->push_back(newEdge); + eiPrev=ei; + it++; + } +} + +Edge* +EdgeIntersectionList::createSplitEdge(EdgeIntersection *ei0, EdgeIntersection *ei1) +{ +#if DEBUG + cerr<<"["<segmentIndex-ei0->segmentIndex+2; +#if DEBUG + cerr<<" npts:"<pts->getAt(ei1->segmentIndex); + + // if the last intersection point is not equal to the its segment + // start pt, add it to the points list as well. + // (This check is needed because the distance metric is not totally + // reliable!). The check for point equality is 2D only - Z values + // are ignored + bool useIntPt1=ei1->dist>0.0 || !ei1->coord.equals2D(lastSegStartPt); + if (!useIntPt1) { + npts--; +#if DEBUG + cerr<<" !useIntPt1 (npts:"<coord); + //pts->setAt(*c,ipt++); + //delete c; + pts->setAt(ei0->coord,ipt++); +#if DEBUG + cerr<<" pt"<<(ipt-1)<<": "<getAt(ipt-1).toString()<segmentIndex+1; i<=ei1->segmentIndex;i++) + { + if ( ! useIntPt1 && ei1->segmentIndex == i ) + { + pts->setAt(ei1->coord, ipt++); + } + else + { + pts->setAt(edge->pts->getAt(i),ipt++); + } +#if DEBUG + cerr<<" pt"<<(ipt-1)<<": "<getAt(ipt-1).toString()<setAt(ei1->coord,ipt); +#if DEBUG + cerr<<" ustIntPt1: pt"<<(ipt-1)<<": "<getAt(ipt-1).toString()<getLabel())); +} + +string +EdgeIntersectionList::print() +{ + string out="Intersections: "; + vector::iterator it; + for (it=list->begin();itend();it++) { + EdgeIntersection *ei=*it; + out+=ei->print(); + } + return out; +} + +} // namespace + +/********************************************************************** + * $Log$ + * Revision 1.10 2004/12/08 13:54:43 strk + * gcc warnings checked and fixed, general cleanups. + * + * Revision 1.9 2004/11/23 19:53:06 strk + * Had LineIntersector compute Z by interpolation. + * + * Revision 1.8 2004/11/22 13:02:12 strk + * Forced use if computed intersection point in ::createSplitEdge (for Z computation) + * + * Revision 1.7 2004/11/17 08:13:16 strk + * Indentation changes. + * Some Z_COMPUTATION activated by default. + * + * Revision 1.6 2004/11/04 19:08:06 strk + * Cleanups, initializers list, profiling. + * + * Revision 1.5 2004/10/21 22:29:54 strk + * Indentation changes and some more COMPUTE_Z rules + * + * Revision 1.4 2004/10/20 17:32:14 strk + * Initial approach to 2.5d intersection() + * + * Revision 1.3 2004/07/08 19:34:49 strk + * Mirrored JTS interface of CoordinateSequence, factory and + * default implementations. + * Added DefaultCoordinateSequenceFactory::instance() function. + * + * Revision 1.2 2004/07/02 13:28:26 strk + * Fixed all #include lines to reflect headers layout change. + * Added client application build tips in README. + * + * Revision 1.1 2004/03/19 09:48:45 ybychkov + * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4 + * + * Revision 1.18 2003/11/07 01:23:42 pramsey + * Add standard CVS headers licence notices and copyrights to all cpp and h + * files. + * + * Revision 1.17 2003/11/06 19:04:28 strk + * removed useless Coordinate copy in ::createSplitEdge() + * + **********************************************************************/ + diff --git a/pool/shard006/C++/0074181_r_clipsegment.cpp b/pool/shard006/C++/0074181_r_clipsegment.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e25daa350d8244e9e1746b6d02845fcd1c9d395 --- /dev/null +++ b/pool/shard006/C++/0074181_r_clipsegment.cpp @@ -0,0 +1,186 @@ +// +// Copyright (C) 1993-1996 by id Software, Inc. +// +// This source is available for distribution and/or modification +// only under the terms of the DOOM Source Code License as +// published by id Software. All rights reserved. +// +// The source is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License +// for more details. +// + +#include +#include "templates.h" +#include "doomdef.h" +#include "m_bbox.h" +#include "i_system.h" +#include "p_lnspec.h" +#include "p_setup.h" +#include "swrenderer/drawers/r_draw.h" +#include "swrenderer/scene/r_3dfloors.h" +#include "a_sharedglobal.h" +#include "g_level.h" +#include "p_effect.h" +#include "doomstat.h" +#include "r_state.h" +#include "swrenderer/scene/r_opaque_pass.h" +#include "v_palette.h" +#include "r_sky.h" +#include "po_man.h" +#include "r_data/colormaps.h" +#include "swrenderer/segments/r_clipsegment.h" + +namespace swrenderer +{ + void RenderClipSegment::Clear(short left, short right) + { + solidsegs[0].first = -0x7fff; + solidsegs[0].last = left; + solidsegs[1].first = right; + solidsegs[1].last = 0x7fff; + newend = solidsegs+2; + } + + bool RenderClipSegment::Check(int first, int last) + { + cliprange_t *start; + + // Find the first range that touches the range + // (adjacent pixels are touching). + start = solidsegs; + while (start->last < first) + start++; + + if (first < start->first) + { + return true; + } + + // Bottom contained in start? + if (last > start->last) + { + return true; + } + + return false; + } + + bool RenderClipSegment::IsVisible(int sx1, int sx2) + { + // Does not cross a pixel. + if (sx2 <= sx1) + return false; + + cliprange_t *start = solidsegs; + while (start->last < sx2) + start++; + + if (sx1 >= start->first && sx2 <= start->last) + { + // The clippost contains the new span. + return false; + } + + return true; + } + + bool RenderClipSegment::Clip(int first, int last, bool solid, VisibleSegmentRenderer *visitor) + { + cliprange_t *next, *start; + int i, j; + bool res = false; + + // Find the first range that touches the range + // (adjacent pixels are touching). + start = solidsegs; + while (start->last < first) + start++; + + if (first < start->first) + { + res = true; + if (last <= start->first) + { + // Post is entirely visible (above start). + if (!visitor->RenderWallSegment(first, last)) + return true; + + // Insert a new clippost for solid walls. + if (solid) + { + if (last == start->first) + { + start->first = first; + } + else + { + next = newend; + newend++; + while (next != start) + { + *next = *(next - 1); + next--; + } + next->first = first; + next->last = last; + } + } + return true; + } + + // There is a fragment above *start. + if (visitor->RenderWallSegment(first, start->first) && solid) + { + start->first = first; // Adjust the clip size for solid walls + } + } + + // Bottom contained in start? + if (last <= start->last) + return res; + + bool clipsegment; + next = start; + while (last >= (next + 1)->first) + { + // There is a fragment between two posts. + clipsegment = visitor->RenderWallSegment(next->last, (next + 1)->first); + next++; + + if (last <= next->last) + { + // Bottom is contained in next. + last = next->last; + goto crunch; + } + } + + // There is a fragment after *next. + clipsegment = visitor->RenderWallSegment(next->last, last); + + crunch: + if (!clipsegment) + { + return true; + } + if (solid) + { + // Adjust the clip size. + start->last = last; + + if (next != start) + { + // Remove start+1 to next from the clip list, + // because start now covers their area. + for (i = 1, j = (int)(newend - next); j > 0; i++, j--) + { + start[i] = next[i]; + } + newend = start + i; + } + } + return true; + } +} diff --git a/pool/shard006/C++/0074184_main.cpp b/pool/shard006/C++/0074184_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..401a9aa09f2824c1ed30e284d6b3661dbf272df7 --- /dev/null +++ b/pool/shard006/C++/0074184_main.cpp @@ -0,0 +1,64 @@ +/* + * Copyright 2015 J. Rick Ramstetter + * rick.ramstetter[at]gmail.[tld] + * + * Problem statement: + * https://www.hackerrank.com/challenges/building-a-list + * + * 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 . + */ + +#include +#include +#include + +void print(const std::string &prefix, /* Output prefix for the current recursion */ + const std::string &input, /* Input character array */ + const std::string::const_iterator start /* Start location of the char array */ + ) { + for (auto iter = start; iter != input.end(); ++iter) { + std::string temp (prefix + *iter); + + std::cout << temp << std::endl; + + print(temp, input, iter + 1); + } +} + +int handle_test_case(size_t test_num) { + size_t size; + std::cin >> size; + + std::string input; + std::cin >> input; + assert(size == input.size()); + + /* Treat input like a vector and sort it */ + std::sort(input.begin(), input.end()); + + print("", input, input.begin()); + return 0; +} + +int main() { + size_t test_cases; + std::cin >> test_cases; + + for (size_t i = 0; i < test_cases; ++i) { + if (handle_test_case(i)) + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C++/0074187_vector2.cpp b/pool/shard006/C++/0074187_vector2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..456d666c411370febe70e004483fae443e0f8c38 --- /dev/null +++ b/pool/shard006/C++/0074187_vector2.cpp @@ -0,0 +1,158 @@ +/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- +/* + * vector3.cpp + * Copyright (C) Andrew Tridgell 2012 + * + * This file 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 file 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 . + */ + +#pragma GCC optimize("O3") + +#include "AP_Math.h" + +template +float Vector2::length(void) const +{ + return pythagorous2(x, y); +} + + +// dot product +template +T Vector2::operator *(const Vector2 &v) const +{ + return x*v.x + y*v.y; +} + +// cross product +template +T Vector2::operator %(const Vector2 &v) const +{ + return x*v.y - y*v.x; +} + +template +Vector2 &Vector2::operator *=(const T num) +{ + x*=num; y*=num; + return *this; +} + +template +Vector2 &Vector2::operator /=(const T num) +{ + x /= num; y /= num; + return *this; +} + +template +Vector2 &Vector2::operator -=(const Vector2 &v) +{ + x -= v.x; y -= v.y; + return *this; +} + +template +bool Vector2::is_nan(void) const +{ + return isnan(x) || isnan(y); +} + +template +bool Vector2::is_inf(void) const +{ + return isinf(x) || isinf(y); +} + +template +Vector2 &Vector2::operator +=(const Vector2 &v) +{ + x+=v.x; y+=v.y; + return *this; +} + +template +Vector2 Vector2::operator /(const T num) const +{ + return Vector2(x/num, y/num); +} + +template +Vector2 Vector2::operator *(const T num) const +{ + return Vector2(x*num, y*num); +} + +template +Vector2 Vector2::operator -(const Vector2 &v) const +{ + return Vector2(x-v.x, y-v.y); +} + +template +Vector2 Vector2::operator +(const Vector2 &v) const +{ + return Vector2(x+v.x, y+v.y); +} + +template +Vector2 Vector2::operator -(void) const +{ + return Vector2(-x,-y); +} + +template +bool Vector2::operator ==(const Vector2 &v) const +{ + return (is_equal(x,v.x) && is_equal(y,v.y)); +} + +template +bool Vector2::operator !=(const Vector2 &v) const +{ + return (!is_equal(x,v.x) || !is_equal(y,v.y)); +} + +template +float Vector2::angle(const Vector2 &v2) const +{ + float len = this->length() * v2.length(); + if (len <= 0) { + return 0.0f; + } + float cosv = ((*this)*v2) / len; + if (fabsf(cosv) >= 1) { + return 0.0f; + } + return acosf(cosv); +} + +// only define for float +template float Vector2::length(void) const; +template float Vector2::operator *(const Vector2 &v) const; +template float Vector2::operator %(const Vector2 &v) const; +template Vector2 &Vector2::operator *=(const float num); +template Vector2 &Vector2::operator /=(const float num); +template Vector2 &Vector2::operator -=(const Vector2 &v); +template Vector2 &Vector2::operator +=(const Vector2 &v); +template Vector2 Vector2::operator /(const float num) const; +template Vector2 Vector2::operator *(const float num) const; +template Vector2 Vector2::operator +(const Vector2 &v) const; +template Vector2 Vector2::operator -(const Vector2 &v) const; +template Vector2 Vector2::operator -(void) const; +template bool Vector2::operator ==(const Vector2 &v) const; +template bool Vector2::operator !=(const Vector2 &v) const; +template bool Vector2::is_nan(void) const; +template bool Vector2::is_inf(void) const; +template float Vector2::angle(const Vector2 &v) const; diff --git a/pool/shard006/C++/0074188_fundwitnessdialog.cpp b/pool/shard006/C++/0074188_fundwitnessdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4beef57596a1d2bc24f76a712bb7b3bb12d53801 --- /dev/null +++ b/pool/shard006/C++/0074188_fundwitnessdialog.cpp @@ -0,0 +1,176 @@ +// Copyright (c) 2016-2019 The Gulden developers +// Authored by: Willem de Jonge (willem@isnapp.nl) +// Distributed under the GULDEN software license, see the accompanying +// file COPYING + +#include "fundwitnessdialog.h" +#include + +#include +#include "wallet/wallet.h" +#include "gui.h" +#include "wallet/witness_operations.h" +#include "units.h" +#include "witnessutil.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "consensus/validation.h" + +FundWitnessDialog::FundWitnessDialog(CAmount minimumFunding, CAmount lockedAmount_, int durationRemaining, int64_t minimumWeight, WalletModel* walletModel_, const QStyle *_platformStyle, QWidget *parent) +: QFrame( parent ) +, ui( new Ui::FundWitnessDialog ) +, platformStyle( _platformStyle ) +, walletModel(walletModel_) +, lockedAmount(lockedAmount_) +{ + ui->setupUi(this); + + ui->fundingSelection->setWalletModel(walletModel, minimumFunding); + + connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked())); + connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked())); + connect(ui->fundButton, SIGNAL(clicked()), this, SLOT(fundClicked())); + connect(ui->payAmount, SIGNAL(amountChanged()), this, SLOT(amountFieldChanged())); + + ui->payAmount->setOptionsModel(walletModel->getOptionsModel()); + ui->payAmount->setDisplayMaxButton(false); + ui->payAmount->setAmount(lockedAmount); + ui->lockDuration->configure(lockedAmount, durationRemaining, minimumWeight); +} + +FundWitnessDialog::FundWitnessDialog(CAmount lockedAmount_, int durationRemaining, int64_t minimumWeight, WalletModel* walletModel_, const QStyle *_platformStyle, QWidget *parent) + : FundWitnessDialog(1 * COIN, lockedAmount_, durationRemaining, minimumWeight, walletModel_, _platformStyle, parent) +{ + ui->extendButton->setVisible(true); + ui->fundButton->setVisible(false); + ui->labelExtendDescription->setText(tr("Extend a witness to increase amount and/or locking duration. A funding account is needed to provide the transaction fee, even if the amount is not increased.")); +} + +FundWitnessDialog::FundWitnessDialog(WalletModel* walletModel_, const QStyle *platformStyle, QWidget *parent) + : FundWitnessDialog(gMinimumWitnessAmount * COIN, 0, 0, 0, walletModel_, platformStyle, parent) +{ + ui->extendButton->setVisible(false); + ui->fundButton->setVisible(true); + ui->labelExtendDescription->setText(tr("Fund your witness to start witnessing and earn rewards.")); + + // Initial funding dialog is shown automatically when an empty witness account is selected and does not need the cancel button + ui->cancelButton->setVisible(false); +} + +FundWitnessDialog::~FundWitnessDialog() +{ + delete ui; +} + +void FundWitnessDialog::cancelClicked() +{ + LOG_QT_METHOD; + + Q_EMIT dismiss(this); +} + +void FundWitnessDialog::extendClicked() +{ + LOG_QT_METHOD; + + // Format confirmation message + QString questionString = tr("Are you sure you want to extend the witness?"); + questionString.append("

"); + int days = ui->lockDuration->duration() / DailyBlocksTarget(); + questionString.append(tr("%1 will be locked for %2 days (%3).") + .arg(GuldenUnits::formatHtmlWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), ui->payAmount->amount())) + .arg(days) + .arg(daysToHuman(days))); + questionString.append("

"); + questionString.append(tr("It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.")); + + if(QDialog::Accepted == GUI::createDialog(this, questionString, tr("Extend witness"), tr("Cancel"), 600, 360, "ExtendWitnessConfirmationDialog")->exec()) + { + // selected fundingAccount + CAccount* fundingAccount = ui->fundingSelection->selectedAccount(); + if (!fundingAccount) { + GUI::createDialog(this, tr("No funding account selected"), tr("Okay"), QString(""), 400, 180)->exec(); + return; + } + + pactiveWallet->BeginUnlocked(_("Wallet unlock required to extend witness"), [=](){ + + try { + LOCK2(cs_main, pactiveWallet->cs_wallet); + CAccount* witnessAccount = pactiveWallet->activeAccount; + extendwitnessaccount(pactiveWallet, + fundingAccount, + witnessAccount, + ui->payAmount->amount(), + ui->lockDuration->duration(), + nullptr, nullptr); // ignore result params + + // request dismissal only when succesful + Q_EMIT dismiss(this); + + } catch (std::runtime_error& e) { + GUI::createDialog(this, e.what(), tr("Okay"), QString(""), 400, 180)->exec(); + } + + pactiveWallet->EndUnlocked(); + }); + } +} + +void FundWitnessDialog::fundClicked() +{ + LOG_QT_METHOD; + + // Format confirmation message + QString questionString = tr("Are you sure you want to fund the witness?"); + questionString.append("

"); + int days = ui->lockDuration->duration() / DailyBlocksTarget(); + questionString.append(tr("%1 will be locked for %2 days (%3).") + .arg(GuldenUnits::formatHtmlWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), ui->payAmount->amount())) + .arg(days) + .arg(daysToHuman(days))); + questionString.append("

"); + questionString.append(tr("It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.")); + + if(QDialog::Accepted == GUI::createDialog(this, questionString, tr("Fund witness"), tr("Cancel"), 600, 360, "FundWitnessConfirmationDialog")->exec()) + { + // selected fundingAccount + CAccount* fundingAccount = ui->fundingSelection->selectedAccount(); + if (!fundingAccount) { + GUI::createDialog(this, tr("No funding account selected"), tr("Okay"), QString(""), 400, 180)->exec(); + return; + } + + pactiveWallet->BeginUnlocked(_("Wallet unlock required to fund witness"), [=](){ + + try + { + LOCK2(cs_main, pactiveWallet->cs_wallet); + CAccount* witnessAccount = pactiveWallet->activeAccount; + fundwitnessaccount(pactiveWallet, + fundingAccount, + witnessAccount, + ui->payAmount->amount(), + ui->lockDuration->duration(), + false, + nullptr, nullptr); // ignore result params + + // request dismissal only when succesful + Q_EMIT dismiss(this); + + } + catch (std::runtime_error& e) + { + GUI::createDialog(this, e.what(), tr("Okay"), QString(""), 400, 180)->exec(); + } + + pactiveWallet->EndUnlocked(); + }); + } +} + +void FundWitnessDialog::amountFieldChanged() +{ + CAmount newAmount = ui->payAmount->amount(); + ui->lockDuration->setAmount(newAmount); +} diff --git a/pool/shard006/C++/0074189_DescribeTaskSetsResult.cpp b/pool/shard006/C++/0074189_DescribeTaskSetsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f87e401500cbc692c8975e9f692c6ebe93804841 --- /dev/null +++ b/pool/shard006/C++/0074189_DescribeTaskSetsResult.cpp @@ -0,0 +1,52 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::ECS::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +DescribeTaskSetsResult::DescribeTaskSetsResult() +{ +} + +DescribeTaskSetsResult::DescribeTaskSetsResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +DescribeTaskSetsResult& DescribeTaskSetsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("taskSets")) + { + Array taskSetsJsonList = jsonValue.GetArray("taskSets"); + for(unsigned taskSetsIndex = 0; taskSetsIndex < taskSetsJsonList.GetLength(); ++taskSetsIndex) + { + m_taskSets.push_back(taskSetsJsonList[taskSetsIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("failures")) + { + Array failuresJsonList = jsonValue.GetArray("failures"); + for(unsigned failuresIndex = 0; failuresIndex < failuresJsonList.GetLength(); ++failuresIndex) + { + m_failures.push_back(failuresJsonList[failuresIndex].AsObject()); + } + } + + + + return *this; +} diff --git a/pool/shard006/C++/0074191_LoadsImpl.cpp b/pool/shard006/C++/0074191_LoadsImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf98d76742097b630227fbbcb99ee7f1a35913a2 --- /dev/null +++ b/pool/shard006/C++/0074191_LoadsImpl.cpp @@ -0,0 +1,203 @@ +// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- +/* + * kdm/platform/LoadsImpl.cpp + * Copyright (C) Cátedra SAES-UMU 2010 + * + * EMF4CPP 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. + * + * EMF4CPP 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 program. If not, see . + */ + +#include "Loads.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ::kdm::platform; + +/*PROTECTED REGION ID(LoadsImpl.cpp) START*/ +// Please, enable the protected region if you add manually written code. +// To do this, add the keyword ENABLED before START. +/*PROTECTED REGION END*/ + +void Loads::_initialize() +{ + // Supertypes + ::kdm::platform::AbstractPlatformRelationship::_initialize(); + + // Rerefences + + /*PROTECTED REGION ID(LoadsImpl__initialize) START*/ + // Please, enable the protected region if you add manually written code. + // To do this, add the keyword ENABLED before START. + /*PROTECTED REGION END*/ +} + +// Operations + + +// EObject +::ecore::EJavaObject Loads::eGet(::ecore::EInt _featureID, + ::ecore::EBoolean _resolve) +{ + ::ecore::EJavaObject _any; + switch (_featureID) + { + case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE: + { + _any = m_attribute->asEListOf< ::ecore::EObject > (); + } + return _any; + case ::kdm::core::CorePackage::ELEMENT__ANNOTATION: + { + _any = m_annotation->asEListOf< ::ecore::EObject > (); + } + return _any; + case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE: + { + _any = m_stereotype->asEListOf< ::ecore::EObject > (); + } + return _any; + case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE: + { + _any = m_taggedValue->asEListOf< ::ecore::EObject > (); + } + return _any; + case ::kdm::platform::PlatformPackage::LOADS__TO: + { + _any = static_cast< ::ecore::EObject* > (m_to); + } + return _any; + case ::kdm::platform::PlatformPackage::LOADS__FROM: + { + _any = static_cast< ::ecore::EObject* > (m_from); + } + return _any; + + } + throw "Error"; +} + +void Loads::eSet(::ecore::EInt _featureID, + ::ecore::EJavaObject const& _newValue) +{ + switch (_featureID) + { + case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE: + { + ::ecorecpp::mapping::EList_ptr _t0 = + ::ecorecpp::mapping::any::any_cast< + ::ecorecpp::mapping::EList_ptr >(_newValue); + ::kdm::core::Element::getAttribute().clear(); + ::kdm::core::Element::getAttribute().insert_all(*_t0); + } + return; + case ::kdm::core::CorePackage::ELEMENT__ANNOTATION: + { + ::ecorecpp::mapping::EList_ptr _t0 = + ::ecorecpp::mapping::any::any_cast< + ::ecorecpp::mapping::EList_ptr >(_newValue); + ::kdm::core::Element::getAnnotation().clear(); + ::kdm::core::Element::getAnnotation().insert_all(*_t0); + } + return; + case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE: + { + ::ecorecpp::mapping::EList_ptr _t0 = + ::ecorecpp::mapping::any::any_cast< + ::ecorecpp::mapping::EList_ptr >(_newValue); + ::kdm::core::ModelElement::getStereotype().clear(); + ::kdm::core::ModelElement::getStereotype().insert_all(*_t0); + } + return; + case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE: + { + ::ecorecpp::mapping::EList_ptr _t0 = + ::ecorecpp::mapping::any::any_cast< + ::ecorecpp::mapping::EList_ptr >(_newValue); + ::kdm::core::ModelElement::getTaggedValue().clear(); + ::kdm::core::ModelElement::getTaggedValue().insert_all(*_t0); + } + return; + case ::kdm::platform::PlatformPackage::LOADS__TO: + { + ::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast< + ::ecore::EObject_ptr >(_newValue); + ::kdm::platform::DeployedComponent_ptr _t1 = + dynamic_cast< ::kdm::platform::DeployedComponent_ptr > (_t0); + ::kdm::platform::Loads::setTo(_t1); + } + return; + case ::kdm::platform::PlatformPackage::LOADS__FROM: + { + ::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast< + ::ecore::EObject_ptr >(_newValue); + ::kdm::action::ActionElement_ptr _t1 = + dynamic_cast< ::kdm::action::ActionElement_ptr > (_t0); + ::kdm::platform::Loads::setFrom(_t1); + } + return; + + } + throw "Error"; +} + +::ecore::EBoolean Loads::eIsSet(::ecore::EInt _featureID) +{ + switch (_featureID) + { + case ::kdm::core::CorePackage::ELEMENT__ATTRIBUTE: + return m_attribute && m_attribute->size(); + case ::kdm::core::CorePackage::ELEMENT__ANNOTATION: + return m_annotation && m_annotation->size(); + case ::kdm::core::CorePackage::MODELELEMENT__STEREOTYPE: + return m_stereotype && m_stereotype->size(); + case ::kdm::core::CorePackage::MODELELEMENT__TAGGEDVALUE: + return m_taggedValue && m_taggedValue->size(); + case ::kdm::platform::PlatformPackage::LOADS__TO: + return m_to; + case ::kdm::platform::PlatformPackage::LOADS__FROM: + return m_from; + + } + throw "Error"; +} + +void Loads::eUnset(::ecore::EInt _featureID) +{ + switch (_featureID) + { + + } + throw "Error"; +} + +::ecore::EClass_ptr Loads::_eClass() +{ + static ::ecore::EClass_ptr + _eclass = + dynamic_cast< ::kdm::platform::PlatformPackage_ptr > (::kdm::platform::PlatformPackage::_instance())->getLoads(); + return _eclass; +} + diff --git a/pool/shard006/C++/0074193_initialization_types.cpp b/pool/shard006/C++/0074193_initialization_types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d76f2362e0c7e6ca61a760e58ee2dd8c508e1f7 --- /dev/null +++ b/pool/shard006/C++/0074193_initialization_types.cpp @@ -0,0 +1,199 @@ +// https://cirosantilli.com/linux-kernel-module-cheat#cpp-initialization-types + +#include +#include + +// zero-initialization because has static storage +// just like a static "local" function variable. +int global; + +int main() { + + // First let's list how different initializations are done explicitly in the code. + { + struct C { + int i; + constexpr C() : i(0) {} + constexpr C(int i) : i(i) {} + }; + + // Default-initialization. + { + C i; + C *j = new C; + } + + // Value initialization. + { + C i{}; + C j = C(); + C k = C{}; + C *l = new C(); + C *m = new C{}; + } + + // Direct initialization. + { + C i(1); + C j{1}; + C *k = new C(1); + } + + // Zero initialization + { + static C i; + } + + // Most vexing parse, function declaration! + { + C myfunc(); + } + + // The syntax goes for primitive types. These serve as the basis + // for the recursive definition.. + { + // Default. + int i; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/default_initialization + // i is POD and is not an array: therefore nothing is done. + //assert(i == ?); + + // Value. + constexpr int j{}; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/value_initialization + // j is not a class type, and is not an array type. Therefore it is zero initialized. + static_assert(j == 0); + + // Direct. + constexpr int k{1}; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/direct_initialization + // is not array, not class, not "if T is a non-class type but the source type is a + // class type" whatever that means, and not bool, therefore standard conversion is used + // and the value is set. + static_assert(k == 1); + } + } + + // Now, let's see which implicit initializations are done for each case recursively. + { + { + struct C { int i; }; + static_assert(std::is_default_constructible()); + static_assert(std::is_aggregate()); + + // Default + C a; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/default_initialization + // - non-POD? no + // - array? no + // - then: nothing is done. + //assert(i == ?); + + // Value + constexpr C b{}; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/value_initialization + // - class type with no default constructor? no + // - default constructor that is neither user-provided nor deleted: yes + // - zero initialize + // - has a non-trivial default constructor + // - no + assert(b.i == 0); + + // Aggregate + constexpr C c{5}; + static_assert(c.i == 5); + + // Zero + static C d; + assert(d.i == 0); + } + + { + struct C { + int i; + constexpr C() : i(3) {}; + constexpr C(int i) : i(i) {}; + }; + static_assert(!std::is_pod()); + + // Default + constexpr C a; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/default_initialization + // - non-POD? yes. Therefore: call C(). which initializes i. + static_assert(a.i == 3); + + // Value + constexpr C b{}; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/value_initialization + // - class type with no default constructor? no + // - user-provided default constructor? yes. Therefore, default initialize the object. + // So we fall on the above case, and the variable does get set. + static_assert(b.i == 3); + + // Direct + constexpr C c{5}; + // Following the cases at: + // https://en.cppreference.com/w/cpp/language/_initialization + // - array type? no + // - class type? yes. Call constructor. + static_assert(c.i == 5); + } + + { + struct C { + int i; + constexpr C(int i) : i(i) {}; + }; + static_assert(!std::is_pod()); + static_assert(!std::is_default_constructible()); + +#if 0 + // Cannot be default initialized if not default constructible. + // error: no matching function + constexpr C a; +#endif + +#if 0 + // Cannot be value initialized if not default constructible. + // error: no matching function + C b{}; +#endif + + // Direct initialize + constexpr C c{5}; + static_assert(!std::is_pod()); + // - class type with no default constructor? yes + } + + //struct A { T t; A() : t() {} }; + //A a; // t is value-initialized + //A a{}; // t is value-initialized + + //struct A { T t; A() : t{} {} }; + //A a; // t is TODO + //A a{}; // + + //struct A { T t; A() {} }; + //A a; // t is TODO + //A a{}; // t is TODO + + //struct A { T t; A() = default }; + //A d; // t is TOAO + //A d{}; // t is TOAO + + //struct A { T t; A() = deleted }; + //A e; // t is TODO + //A e{}; // t is TODO + + //struct A { T t; A(T t) {} }; + //A f; // t is TODO + //A f{}; // t is TODO + } +} diff --git a/pool/shard006/C++/0074196_TileTexturePreviewWidgetItemDelegate.cpp b/pool/shard006/C++/0074196_TileTexturePreviewWidgetItemDelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6e4ee78fe696f6f4055e64a4d6dba72fad320d5 --- /dev/null +++ b/pool/shard006/C++/0074196_TileTexturePreviewWidgetItemDelegate.cpp @@ -0,0 +1,37 @@ +#include "TileTexturePreviewWidgetItemDelegate.h" + +#include + +const QString TileTexturePreviewWidgetItemDelegate::TILE_COLOR_VALIDATE_REGEXP = "#{0,1}[A-F0-9]{6}"; + +TileTexturePreviewWidgetItemDelegate::TileTexturePreviewWidgetItemDelegate(QObject* parent /* = 0 */) + : QItemDelegate(parent) +{ +} + +TileTexturePreviewWidgetItemDelegate::~TileTexturePreviewWidgetItemDelegate() +{ +} + +QWidget* TileTexturePreviewWidgetItemDelegate::createEditor(QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + QWidget* widget = QItemDelegate::createEditor(parent, option, index); + + QLineEdit* edit = qobject_cast(widget); + if (edit != 0) + { + QRegExpValidator* validator = new QRegExpValidator(); + validator->setRegExp(QRegExp(TILE_COLOR_VALIDATE_REGEXP, Qt::CaseInsensitive)); + edit->setValidator(validator); + } + + return widget; +} + +void TileTexturePreviewWidgetItemDelegate::drawFocus(QPainter* painter, + const QStyleOptionViewItem& option, + const QRect& rect) const +{ +} \ No newline at end of file diff --git a/pool/shard006/C++/0074200_echse_coreFunct_saveState.cpp b/pool/shard006/C++/0074200_echse_coreFunct_saveState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c76b6d6a2e47c87e3213a9fac0137c1995428675 --- /dev/null +++ b/pool/shard006/C++/0074200_echse_coreFunct_saveState.cpp @@ -0,0 +1,117 @@ + +#include "echse_coreFunct_saveState.h" + +void saveState( + const string &outdir, + const fixedZoneTime &now, + const vector ×_stateOutput, + const string chars_colsep, const string chars_comment, + const vector &objects +) { + unsigned int nrecs; + // If output of states is requested for one/some time(s) + if (times_stateOutput.size() > 0) { + vector::const_iterator iter= find(times_stateOutput.begin(), + times_stateOutput.end(), now); + // If current time is in vector of desired output times + if (iter != times_stateOutput.end()) { + string file; + ofstream ost; + // Scalar states + file= outdir + "/" + "statesScal" + "_" + now.get("","","") + + globalConst::fileExtensions.tabular; + if (file_exists(file)) { + stringstream errmsg; + errmsg << "Cannot print values of scalar states to file '" << + file << "'. File already exists."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + ost.open(file.c_str()); + if (!ost.is_open()) { + stringstream errmsg; + errmsg << "Cannot print values of scalar states to file '" << + file << "'. File cannot be opened."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + ost << chars_comment << " Values of scalar state variables at: " << + now.get("-",":"," ") << endl; + ost << "object" << chars_colsep << "variable" << chars_colsep << "value" << endl; + nrecs= 0; + for (unsigned int i=0; i& names= objects[i]->get_objectGroupPointer()->get_namesStatesScal(); + struct T_index_stateScal index; + for (vector::size_type k=0; kget_idObject() << chars_colsep << names[k] << + chars_colsep << objects[i]->stateScal(index) << endl; + nrecs++; + } + } catch (except) { + stringstream errmsg; + errmsg << "Cannot print values of scalar states to file '" << + file << "'. Encountered problems with object '" << + objects[i]->get_idObject() << "'."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + } + if (nrecs == 0) { + ost << "none" << chars_colsep << "none" << chars_colsep << "none" << endl; + } + ost.close(); + // Vector states + file= outdir + "/" + "statesVect" + "_" + now.get("","","") + ".txt"; + if (file_exists(file)) { + stringstream errmsg; + errmsg << "Cannot print values of vector states to file '" << + file << "'. File already exists."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + ost.open(file.c_str()); + if (!ost.is_open()) { + stringstream errmsg; + errmsg << "Cannot print values of vector states to file '" << + file << "'. File cannot be opened."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + ost << chars_comment << " Values of vector state variables at: " << + now.get("-",":"," ") << endl; + ost << "object" << chars_colsep << "variable" << chars_colsep << "index" << + chars_colsep << "value" << endl; + nrecs= 0; + for (unsigned int i=0; i& names= objects[i]->get_objectGroupPointer()->get_namesStatesVect(); + struct T_index_stateVect index; + for (vector::size_type k=0; k& values= objects[i]->stateVect(index); + for (unsigned int n=0; nget_idObject() << chars_colsep << names[k] << + chars_colsep << n << chars_colsep << values[n] << endl; + nrecs++; + } + } + } catch (except) { + stringstream errmsg; + errmsg << "Cannot print values of vector states to file '" << + file << "'. Encountered problems with object '" << + objects[i]->get_idObject() << "'."; + except e(__PRETTY_FUNCTION__,errmsg,__FILE__,__LINE__); + throw(e); + } + } + if (nrecs == 0) { + ost << "none" << chars_colsep << "none" << chars_colsep << "none" << + chars_colsep << "none" << endl; + } + ost.close(); + } + } +} + diff --git a/pool/shard006/C++/0074202_g.cpp b/pool/shard006/C++/0074202_g.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c857781caf4c098150e446f8de9ca11f47d59b6d --- /dev/null +++ b/pool/shard006/C++/0074202_g.cpp @@ -0,0 +1,77 @@ +#include +using namespace std; + + +bool cmp(pair x, pair y) +{ + return x.first + x.second > y.first + y.second; + +} +int main() +{ + + vector < pair > maxi; + vector < pair > mini; + + int n; + int m; + int a; + int b; + int temp; + int x, y; + + scanf("%d", &n); + scanf("%d", &m); + + scanf("%d", &x); + scanf("%d", &x); + + for (int i = 0; i < n; i++) { + scanf("%d", &x); + scanf("%d", &y); + + maxi.push_back(make_pair(x, y)); + + } + + for (int i = 0; i < m; i++) { + scanf("%d", &x); + scanf("%d", &y); + + mini.push_back(make_pair(x, y)); + + } + +// sort(maxi.begin(), maxi.end(), cmp); +// sort(mini.begin(), mini.end(), cmp); + + for (int i = 0; i < n; i++) { + a = maxi[i].first; + b = maxi[i].second; + temp = 0; + + for (int j = 0; j < m; j++) { + if(mini[j].first > a and mini[j].second > b) { + temp = 1; + break; + } + + } + + if(temp == 0) { + printf("Max\n"); + return 0; + } + + } + + + printf("Min\n"); + return 0; + + + +} + + + diff --git a/pool/shard006/C++/0074206_visibleregion.cpp b/pool/shard006/C++/0074206_visibleregion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed87198fdff5aeaa49cdd356cb0834a23f51b71b --- /dev/null +++ b/pool/shard006/C++/0074206_visibleregion.cpp @@ -0,0 +1,246 @@ +// visibleregion.cpp +// +// Visible region reference mark for ellipsoidal bodies. +// +// Copyright (C) 2008, the Celestia Development Team +// Initial version by Chris Laurel, claurel@gmail.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. + +#include +#include +#include +#include +#include "body.h" +#include "render.h" +#include "selection.h" +#include "vecgl.h" +#include "vertexobject.h" +#include "visibleregion.h" + +using namespace std; +using namespace Eigen; +using namespace celmath; + + +/*! Construct a new reference mark that shows the outline of the + * region on the surface of a body in which the target object is + * visible. The following are assumed: + * - target is a point + * - the body is an ellipsoid + * + * This reference mark is useful in a few situations. When the + * body is a planet or moon and target is the sun, the outline of + * the visible region is the terminator. If target is a satellite, + * the outline is its circle of visibility. + */ +VisibleRegion::VisibleRegion(const Body& body, const Selection& target) : + m_body(body), + m_target(target), + m_color(1.0f, 1.0f, 0.0f), + m_opacity(1.0f) +{ + setTag("visible region"); +} + + +Color +VisibleRegion::color() const +{ + return m_color; +} + + +void +VisibleRegion::setColor(Color color) +{ + m_color = color; +} + + +float +VisibleRegion::opacity() const +{ + return m_opacity; +} + + +void +VisibleRegion::setOpacity(float opacity) +{ + m_opacity = opacity; +} + + +constexpr const unsigned maxSections = 360; + +static void +renderTerminator(Renderer* renderer, + const vector& pos, + const Color& color, + const Matrices& mvp) +{ + /*! + * Proper terminator calculation requires double precision floats in GLSL + * which were introduced in ARB_gpu_shader_fp64 unavailable with GL2.1. + * Because of this we make calculations on a CPU and stream results to GPU. + */ + + using AttributesType = celgl::VertexObject::AttributesType; + + ShaderProperties shadprop; + shadprop.texUsage = ShaderProperties::VertexColors; + shadprop.lightModel = ShaderProperties::UnlitModel; + + bool lineAsTriangles = renderer->shouldDrawLineAsTriangles(); + if (lineAsTriangles) + shadprop.texUsage |= ShaderProperties::LineAsTriangles; + + auto *prog = renderer->getShaderManager().getShader(shadprop); + if (prog == nullptr) + return; + + auto &vo = renderer->getVertexObject(VOType::Terminator, GL_ARRAY_BUFFER, 0, GL_STREAM_DRAW); + + vo.bindWritable(lineAsTriangles ? AttributesType::Default : AttributesType::Alternative1); + if (!vo.initialized()) + { + vo.setBufferSize((maxSections + 2) * 2 * sizeof(LineStripEnd)); + vo.allocate(); + + // Attributes for lines drawn as triangles + vo.setVertices(3, GL_FLOAT, false, sizeof(LineStripEnd), 0); + vo.setVertexAttribArray(CelestiaGLProgram::NextVCoordAttributeIndex, + 3, GL_FLOAT, false, sizeof(LineStripEnd) + , 2 * sizeof(LineStripEnd) + offsetof(LineStripEnd, point)); + vo.setVertexAttribArray(CelestiaGLProgram::ScaleFactorAttributeIndex, + 1, GL_FLOAT, false, sizeof(LineStripEnd) + , offsetof(LineStripEnd, scale)); + + // Attributes for lines drawn as lines + vo.setVertices(3, GL_FLOAT, false, 2 * sizeof(LineStripEnd), 0, AttributesType::Alternative1); + } + + vo.setBufferData(pos.data(), 0, pos.size() * sizeof(LineStripEnd)); + + prog->use(); + prog->setMVPMatrices(*mvp.projection, *mvp.modelview); + glVertexAttrib(CelestiaGLProgram::ColorAttributeIndex, color); + if (lineAsTriangles) + { + prog->lineWidthX = renderer->getLineWidthX(); + prog->lineWidthY = renderer->getLineWidthY(); + vo.draw(GL_TRIANGLE_STRIP, pos.size() - 2); + } + else + { + vo.draw(GL_LINE_STRIP, (pos.size() - 2) / 2, 0); + } + + vo.unbind(); +} + + +void +VisibleRegion::render(Renderer* renderer, + const Vector3f& position, + float discSizeInPixels, + double tdb, + const Matrices& m) const +{ + // Don't render anything if the current time is not within the + // target object's time window. + if (m_target.body() != nullptr) + { + if (!m_target.body()->extant(tdb)) + return; + } + + // Fade in the terminator when the planet is small + const float minDiscSize = 5.0f; + const float fullOpacityDiscSize = 10.0f; + float opacity = (discSizeInPixels - minDiscSize) / (fullOpacityDiscSize - minDiscSize); + + // Don't render the terminator if the it's smaller than the minimum size + if (opacity <= 0.0f) + return; + opacity = min(opacity, 1.0f) * m_opacity; + + // Base the amount of subdivision on the apparent size + auto nSections = (unsigned int) (30.0f + discSizeInPixels * 0.5f); + nSections = min(nSections, maxSections); + + Quaterniond q = m_body.getEclipticToBodyFixed(tdb); + Quaternionf qf = q.cast(); + + // The outline can't be rendered exactly on the planet sphere, or + // there will be z-fighting problems. Render it at a height above the + // planet that will place it about one pixel away from the planet. + float scale = (discSizeInPixels + 1) / discSizeInPixels; + scale = max(scale, 1.0001f); + + Vector3f semiAxes = m_body.getSemiAxes(); + + // Enable depth buffering + renderer->enableDepthTest(); + renderer->enableDepthMask(); + renderer->enableBlending(); + renderer->setBlendingFactors(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + double maxSemiAxis = m_body.getRadius(); + + // In order to avoid precision problems and extremely large values, scale + // the target position and semiaxes such that the largest semiaxis is 1.0. + Vector3d lightDir = m_body.getPosition(tdb).offsetFromKm(m_target.getPosition(tdb)); + lightDir = lightDir / maxSemiAxis; + lightDir = q * lightDir; + + // Another measure to prevent precision problems: if the distance to the + // object is much greater than the largest semi axis, clamp it to 1e4 times + // the radius, as body-to-target rays at that distance are nearly parallel anyhow. + if (lightDir.norm() > 10000.0) + lightDir *= (10000.0 / lightDir.norm()); + + // Pick two orthogonal axes both normal to the light direction + Vector3d lightDirNorm = lightDir.normalized(); + + Vector3d uAxis = lightDirNorm.unitOrthogonal(); + Vector3d vAxis = uAxis.cross(lightDirNorm); + + Vector3d recipSemiAxes = maxSemiAxis * semiAxes.cast().cwiseInverse(); + Vector3d e = -lightDir; + Vector3d e_ = e.cwiseProduct(recipSemiAxes); + double ee = e_.squaredNorm(); + + vector pos; + pos.reserve((nSections + 2) * 2); + + for (unsigned i = 0; i <= nSections + 1; i++) + { + double theta = (double) i / (double) (nSections) * 2.0 * celestia::numbers::pi; + Vector3d w = cos(theta) * uAxis + sin(theta) * vAxis; + + Vector3d toCenter = ellipsoidTangent(recipSemiAxes, w, e, e_, ee); + toCenter *= maxSemiAxis * scale; + Vector3f thisPoint = toCenter.cast(); + pos.emplace_back(thisPoint, -0.5); + pos.emplace_back(thisPoint, 0.5); + } + + Affine3f transform = Translation3f(position) * qf.conjugate(); + Matrix4f modelView = (*m.modelview) * transform.matrix(); + renderTerminator(renderer, pos, Color(m_color, opacity), { m.projection, &modelView }); + + renderer->enableBlending(); + renderer->setBlendingFactors(GL_SRC_ALPHA, GL_ONE); +} + + +float +VisibleRegion::boundingSphereRadius() const +{ + return m_body.getRadius(); +} diff --git a/pool/shard006/C++/0074208_ModulePrefs.cpp b/pool/shard006/C++/0074208_ModulePrefs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01544b50b03a34c97ef517e013943bfb73890d2a --- /dev/null +++ b/pool/shard006/C++/0074208_ModulePrefs.cpp @@ -0,0 +1,169 @@ +/********************************************************************** + + Audacity: A Digital Audio Editor + + ModulePrefs.cpp + + James Crook + +*******************************************************************//** + +\class ModulePrefs +\brief A PrefsPanel to enable/disable certain modules. 'Modules' are +dynamically linked libraries that modify Audacity. They are plug-ins +with names like mnod-script-pipe that add new features. + +*//*******************************************************************/ + +#include "../Audacity.h" + +#include +#include + +#include "../ShuttleGui.h" + +#include "ModulePrefs.h" +#include "../Prefs.h" + +//////////////////////////////////////////////////////////////////////////////// + +/* i18n-hint: Modules are optional extensions to Audacity that add new features.*/ +ModulePrefs::ModulePrefs(wxWindow * parent) +: PrefsPanel(parent, _("Modules")) +{ + Populate(); +} + +ModulePrefs::~ModulePrefs() +{ +} + +void ModulePrefs::GetAllModuleStatuses(){ + wxString str; + long dummy; + + // Modules could for example be: + // mod-script-pipe + // mod-nyq-bench + // mod-track-panel + // mod-menu-munger + // mod-theming + + // TODO: On an Audacity upgrade we should (?) actually untick modules. + // The old modules might be still around, and we do not want to use them. + mModules.Clear(); + mStatuses.Clear(); + mPaths.Clear(); + + + // Iterate through all Modules listed in prefs. + // Get their names and values. + gPrefs->SetPath( wxT("Module/") ); + bool bCont = gPrefs->GetFirstEntry(str, dummy); + while ( bCont ) { + int iStatus; + gPrefs->Read( str, &iStatus, kModuleDisabled ); + wxString fname; + gPrefs->Read( wxString( wxT("/ModulePath/") ) + str, &fname, wxEmptyString ); + if( fname != wxEmptyString && wxFileExists( fname ) ){ + if( iStatus > kModuleNew ){ + iStatus = kModuleNew; + gPrefs->Write( str, iStatus ); + } + //wxLogDebug( wxT("Entry: %s Value: %i"), str.c_str(), iStatus ); + mModules.Add( str ); + mStatuses.Add( iStatus ); + mPaths.Add( fname ); + } + bCont = gPrefs->GetNextEntry(str, dummy); + } + gPrefs->SetPath( wxT("") ); +} + +void ModulePrefs::Populate() +{ + GetAllModuleStatuses(); + //------------------------- Main section -------------------- + // Now construct the GUI itself. + // Use 'eIsCreatingFromPrefs' so that the GUI is + // initialised with values from gPrefs. + ShuttleGui S(this, eIsCreatingFromPrefs); + PopulateOrExchange(S); + // ----------------------- End of main section -------------- +} + +void ModulePrefs::PopulateOrExchange(ShuttleGui & S) +{ + wxArrayString StatusChoices; + StatusChoices.Add( _("Disabled" ) ); + StatusChoices.Add( _("Enabled" ) ); + StatusChoices.Add( _("Ask" ) ); + StatusChoices.Add( _("Failed" ) ); + StatusChoices.Add( _("New" ) ); + S.SetBorder(2); + + S.StartStatic(wxT("")); + { + S.AddFixedText(_("These are experimental modules. Enable them only if you've read the Audacity Manual\nand know what you are doing.") ); + S.AddFixedText(wxString(wxT(" ")) + _("'Ask' means Audacity will ask if you want to load the module each time it starts.") ); + S.AddFixedText(wxString(wxT(" ")) + _("'Failed' means Audacity thinks the module is broken and won't run it.") ); + S.AddFixedText(wxString(wxT(" ")) + _("'New' means no choice has been made yet.") ); + S.AddFixedText(_("Changes to these settings only take effect when Audacity starts up.")); + S.StartScroller(); + { + S.StartMultiColumn( 2 ); + int i; + for(i=0;i<(int)mModules.GetCount();i++) + S.TieChoice( mModules[i], mStatuses[i], &StatusChoices ); + S.EndMultiColumn(); + } + if( mModules.GetCount() < 1 ) + { + S.AddFixedText( _("No modules were found") ); + } + S.EndScroller(); + } + S.EndStatic(); +} + +bool ModulePrefs::Apply() +{ + ShuttleGui S(this, eIsSavingToPrefs); + PopulateOrExchange(S); + int i; + for(i=0;i<(int)mPaths.GetCount();i++) + SetModuleStatus( mPaths[i], mStatuses[i] ); + return true; +} + + +// static function that tells us about a module. +int ModulePrefs::GetModuleStatus( wxString fname ){ + // Default status is new module, and we will ask once. + int iStatus = kModuleNew; + + wxString ShortName = wxFileName( fname ).GetName(); + wxString PrefName = wxString( wxT("/Module/") ) + ShortName.Lower(); + + gPrefs->Read( PrefName, &iStatus, kModuleNew ); + // fix up a bad status. + if( iStatus > kModuleNew ) + iStatus=kModuleNew; + return iStatus; +} + +void ModulePrefs::SetModuleStatus( wxString fname, int iStatus ){ + wxString ShortName = wxFileName( fname ).GetName(); + wxString PrefName = wxString( wxT("/Module/") ) + ShortName.Lower(); + gPrefs->Write( PrefName, iStatus ); + PrefName = wxString( wxT("/ModulePath/") ) + ShortName.Lower(); + gPrefs->Write( PrefName, fname ); + gPrefs->Flush(); +} + +PrefsPanel *ModulePrefsFactory::Create(wxWindow *parent) +{ + return new ModulePrefs(parent); +} + + diff --git a/pool/shard006/C++/0074217_set_transparent_color.cpp b/pool/shard006/C++/0074217_set_transparent_color.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18d84bb1f7fbd657585566e7b488768b7985dbd6 --- /dev/null +++ b/pool/shard006/C++/0074217_set_transparent_color.cpp @@ -0,0 +1,58 @@ +/* Aseprite + * Copyright (C) 2001-2015 David Capello + * + * 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 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "app/cmd/set_transparent_color.h" + +#include "app/document.h" +#include "doc/document_event.h" +#include "doc/sprite.h" + +namespace app { +namespace cmd { + +SetTransparentColor::SetTransparentColor(Sprite* sprite, color_t newMask) + : WithSprite(sprite) + , m_oldMaskColor(sprite->transparentColor()) + , m_newMaskColor(newMask) +{ +} + +void SetTransparentColor::onExecute() +{ + sprite()->setTransparentColor(m_newMaskColor); +} + +void SetTransparentColor::onUndo() +{ + sprite()->setTransparentColor(m_oldMaskColor); +} + +void SetTransparentColor::onFireNotifications() +{ + Sprite* sprite = this->sprite(); + DocumentEvent ev(sprite->document()); + ev.sprite(sprite); + sprite->document()->notifyObservers(&DocumentObserver::onSpriteTransparentColorChanged, ev); +} + +} // namespace cmd +} // namespace app diff --git a/pool/shard006/C++/0074218_tile.cpp b/pool/shard006/C++/0074218_tile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcf80c403275306095ec86844580aa714045113e --- /dev/null +++ b/pool/shard006/C++/0074218_tile.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + Copyright (c) 2016-2019 Joel de Guzman + + Distributed under the MIT License [ https://opensource.org/licenses/MIT ] +=============================================================================*/ +#include +#include + +namespace cycfi { namespace photon +{ + //////////////////////////////////////////////////////////////////////////// + // Vertical Tiles + //////////////////////////////////////////////////////////////////////////// + view_limits vtile_element::limits(basic_context const& ctx) const + { + view_limits limits{ { 0.0, 0.0 }, { full_extent, 0.0 } }; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + + limits.min.y += el.min.y; + limits.max.y += el.max.y; + clamp_min(limits.min.x, el.min.x); + clamp_max(limits.max.x, el.max.x); + } + + clamp_min(limits.max.x, limits.min.x); + clamp_max(limits.max.y, full_extent); + return limits; + } + + void vtile_element::layout(context const& ctx) + { + _left = ctx.bounds.left; + _right = ctx.bounds.right; + + _tiles.resize(size()+1); + + double min_y = 0.0; + double max_y = 0.0; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + min_y += el.min.y; + max_y += el.max.y; + } + + double height = ctx.bounds.height(); + double extra = max_y - height; + double m_size = max_y - min_y; + double curr = ctx.bounds.top; + auto i = _tiles.begin(); + + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto& elem = at(ix); + auto limits = elem.limits(ctx); + + *i++ = curr; + auto prev = curr; + curr += limits.max.y; + + if ((extra != 0) && (m_size != 0)) + curr -= extra * (limits.max.y - limits.min.y) / m_size; + + rect ebounds = { _left, float(prev), _right, float(curr) }; + elem.layout(context{ ctx, &elem, ebounds }); + } + *i = curr; + } + + rect vtile_element::bounds_of(context const& ctx, std::size_t index) const + { + return rect{ _left, _tiles[index], _right, _tiles[index+1] }; + } + + //////////////////////////////////////////////////////////////////////////// + // Horizontal Tiles + //////////////////////////////////////////////////////////////////////////// + view_limits htile_element::limits(basic_context const& ctx) const + { + view_limits limits{ { 0.0, 0.0 }, { 0.0, full_extent } }; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + + limits.min.x += el.min.x; + limits.max.x += el.max.x; + clamp_min(limits.min.y, el.min.y); + clamp_max(limits.max.y, el.max.y); + } + + clamp_min(limits.max.y, limits.min.y); + clamp_max(limits.max.x, full_extent); + return limits; + } + + void htile_element::layout(context const& ctx) + { + _top = ctx.bounds.top; + _bottom = ctx.bounds.bottom; + + _tiles.resize(size()+1); + + double min_x = 0.0; + double max_x = 0.0; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + min_x += el.min.x; + max_x += el.max.x; + } + + double width = ctx.bounds.width(); + double extra = max_x - width; + double m_size = max_x - min_x; + double curr = ctx.bounds.left; + auto i = _tiles.begin(); + + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto& elem = at(ix); + auto limits = elem.limits(ctx); + + *i++ = curr; + auto prev = curr; + curr += limits.max.x; + + if ((extra != 0) && (m_size != 0)) + curr -= extra * (limits.max.x - limits.min.x) / m_size; + + rect ebounds = { float(prev), _top, float(curr), _bottom }; + elem.layout(context{ ctx, &elem, ebounds }); + } + *i = curr; + } + + rect htile_element::bounds_of(context const& ctx, std::size_t index) const + { + return rect{ _tiles[index], _top, _tiles[index + 1], _bottom }; + } +}} diff --git a/pool/shard006/C++/0074219_LuaSystemPath.cpp b/pool/shard006/C++/0074219_LuaSystemPath.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00ad48e6382a5091623d147d53095ca306174c58 --- /dev/null +++ b/pool/shard006/C++/0074219_LuaSystemPath.cpp @@ -0,0 +1,501 @@ +#include "LuaObject.h" +#include "LuaSystemPath.h" +#include "LuaUtils.h" +#include "LuaStarSystem.h" +#include "LuaSystemBody.h" +#include "galaxy/SystemPath.h" +#include "galaxy/StarSystem.h" +#include "galaxy/Sector.h" + +/* + * Class: SystemPath + * + * Describes the location of a system within the galaxy and optionally, a body + * within that system. + * + * A consists of five components + * - the X coordinate of the sector + * - the Y coordinate of the sector + * - the Z coordinate of the sector + * - the system number within that sector + * - optionally, the index of a body within that system + * + * objects are typically used to describe the location of a + * system, space station or other body when specifying hyperspace or other + * destinations. + * + * objects will compare equal if and only if all five of their + * components are the same. If you want to see if two paths correspond to the + * same system without reference to their body indexes, use . + */ + +/* + * Function: New + * + * Creates a new object + * + * > path = SystemPath.New(sectorX, sectorY, sectorZ, systemIndex, bodyIndex) + * + * Parameters: + * + * sectorX - galactic sector X coordinate + * + * sectorY - galactic sector Y coordinate + * + * sectorZ - galactic sector Z coordinate + * + * systemIndex - optional. the numeric index of the system within the sector + * + * bodyIndex - optional. the numeric index of a specific body within the + * system. Defaults to 0, which typically corresponds to the + * primary star. + * + * Availability: + * + * alpha 10, alpha 13 (updated) + * + * Status: + * + * stable + */ +static int l_sbodypath_new(lua_State *l) +{ + Sint32 sector_x = luaL_checkinteger(l, 1); + Sint32 sector_y = luaL_checkinteger(l, 2); + Sint32 sector_z = luaL_checkinteger(l, 3); + + SystemPath path(sector_x, sector_y, sector_z); + + if (lua_gettop(l) > 3) { + path.systemIndex = luaL_checkinteger(l, 4); + + // if this is a system path, then check that the system exists + Sector s(sector_x, sector_y, sector_z); + if (size_t(path.systemIndex) >= s.m_systems.size()) + luaL_error(l, "System %d in sector <%d,%d,%d> does not exist", path.systemIndex, sector_x, sector_y, sector_z); + + if (lua_gettop(l) > 4) { + path.bodyIndex = luaL_checkinteger(l, 5); + + // and if it's a body path, check that the body exists + RefCountedPtr sys = StarSystem::GetCached(path); + if (size_t(path.bodyIndex) >= sys->m_bodies.size()) { + luaL_error(l, "Body %d in system <%d,%d,%d : %d ('%s')> does not exist", + path.bodyIndex, sector_x, sector_y, sector_z, path.systemIndex, sys->GetName().c_str()); + } + } + } + LuaSystemPath::PushToLua(&path); + return 1; +} + +/* + * Method: IsSameSystem + * + * Determine if two objects point to objects in the same system. + * + * > is_same = path:IsSameSystem(otherpath) + * + * Parameters: + * + * otherpath - the to compare with this path + * + * Return: + * + * is_same - true if the path's point to the same system, false otherwise + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_is_same_system(lua_State *l) +{ + SystemPath *a = LuaSystemPath::GetFromLua(1); + SystemPath *b = LuaSystemPath::GetFromLua(2); + + lua_pushboolean(l, a->IsSameSystem(b)); + return 1; +} + +/* + * Method: IsSameSector + * + * Determine if two objects point to objects in the same sector. + * + * > is_same = path:IsSameSector(otherpath) + * + * Parameters: + * + * otherpath - the to compare with this path + * + * Return: + * + * is_same - true if the path's point to the same sector, false otherwise + * + * Availability: + * + * alpha 17 + * + * Status: + * + * stable + */ +static int l_sbodypath_is_same_sector(lua_State *l) +{ + SystemPath *a = LuaSystemPath::GetFromLua(1); + SystemPath *b = LuaSystemPath::GetFromLua(2); + + lua_pushboolean(l, a->IsSameSector(b)); + return 1; +} + +/* + * Method: SystemOnly + * + * Derive a SystemPath that points to the whole system. + * + * > system_path = path:SystemOnly() + * + * Return: + * + * system_path - the SystemPath that represents just the system + * + * Availability: + * + * alpha 17 + * + * Status: + * + * stable + */ +static int l_sbodypath_system_only(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + LuaSystemPath::PushToLuaGC(new SystemPath(path->SystemOnly())); + return 1; +} + +/* + * Method: SectorOnly + * + * Derive a SystemPath that points to the whole sector. + * + * > sector_path = path:SectorOnly() + * + * Return: + * + * sector_path - the SystemPath that represents just the sector + * + * Availability: + * + * alpha 17 + * + * Status: + * + * stable + */ +static int l_sbodypath_sector_only(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + LuaSystemPath::PushToLuaGC(new SystemPath(path->SectorOnly())); + return 1; +} + +/* + * Method: DistanceTo + * + * Calculate the distance between this and another system + * + * > dist = path:DistanceTo(system) + * + * Parameters: + * + * system - a or to calculate the distance to + * + * Return: + * + * dist - the distance, in light years + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_distance_to(lua_State *l) +{ + LUA_DEBUG_START(l); + + const SystemPath *loc1 = LuaSystemPath::GetFromLua(1); + + const SystemPath *loc2 = LuaSystemPath::CheckFromLua(2); + if (!loc2) { + StarSystem *s2 = LuaStarSystem::GetFromLua(2); + loc2 = &(s2->GetPath()); + } + + Sector sec1(loc1->sectorX, loc1->sectorY, loc1->sectorZ); + Sector sec2(loc2->sectorX, loc2->sectorY, loc1->sectorZ); + + double dist = Sector::DistanceBetween(&sec1, loc1->systemIndex, &sec2, loc2->systemIndex); + + lua_pushnumber(l, dist); + + LUA_DEBUG_END(l, 1); + return 1; +} + +/* + * Method: GetStarSystem + * + * Get a object for the system that this path points to + * + * > system = path:GetStarSystem() + * + * Return: + * + * system - the + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_get_star_system(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + RefCountedPtr s = StarSystem::GetCached(path); + // LuaStarSystem shares ownership of the StarSystem, + // because LuaAcquirer uses IncRefCount and DecRefCount + LuaStarSystem::PushToLua(s.Get()); + return 1; +} + +/* + * Method: GetSystemBody + * + * Get a object for the body that this path points to + * + * > body = path:GetSystemBody() + * + * Return: + * + * body - the + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_get_system_body(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + + if (path->IsSectorPath()) { + luaL_error(l, "Path <%d,%d,%d> does not name a system or body", path->sectorX, path->sectorY, path->sectorZ); + return 0; + } + + RefCountedPtr sys = StarSystem::GetCached(path); + if (path->IsSystemPath()) { + luaL_error(l, "Path <%d,%d,%d : %d ('%s')> does not name a body", path->sectorX, path->sectorY, path->sectorZ, path->systemIndex, sys->GetName().c_str()); + return 0; + } + + // Lua should never be able to get an invalid SystemPath + // (note: this may change if it becomes possible to remove systems during the game) + assert(size_t(path->bodyIndex) < sys->m_bodies.size()); + + SystemBody *sbody = sys->GetBodyByPath(path); + LuaSystemBody::PushToLua(sbody); + return 1; +} + + +/* + * Attribute: sectorX + * + * The X component of the path + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_attr_sector_x(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + lua_pushinteger(l, path->sectorX); + return 1; +} + +/* + * Attribute: sectorY + * + * The Y component of the path + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ + +static int l_sbodypath_attr_sector_y(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + lua_pushinteger(l, path->sectorY); + return 1; +} + +/* + * Attribute: sectorZ + * + * The Z component of the path + * + * Availability: + * + * alpha 13 + * + * Status: + * + * stable + */ + +static int l_sbodypath_attr_sector_z(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + lua_pushinteger(l, path->sectorZ); + return 1; +} + +/* + * Attribute: systemIndex + * + * The system index component of the path, or nil if the SystemPath does + * not point to a system. + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_attr_system_index(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + if (!path->IsSectorPath()) + lua_pushinteger(l, path->systemIndex); + else + lua_pushnil(l); + return 1; +} + +/* + * Attribute: bodyIndex + * + * The body index component of the path, or nil if the SystemPath does + * not point to a body. + * + * Availability: + * + * alpha 10 + * + * Status: + * + * stable + */ +static int l_sbodypath_attr_body_index(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + if (path->IsBodyPath()) + lua_pushinteger(l, path->bodyIndex); + else + lua_pushnil(l); + return 1; +} + +static int l_sbodypath_meta_eq(lua_State *l) +{ + SystemPath *a = LuaSystemPath::GetFromLua(1); + SystemPath *b = LuaSystemPath::GetFromLua(2); + + lua_pushboolean(l, *a == *b); + return 1; +} + +static int l_sbodypath_meta_tostring(lua_State *l) +{ + SystemPath *path = LuaSystemPath::GetFromLua(1); + if (path->IsSectorPath()) { + lua_pushfstring(l, "<%d,%d,%d>", path->sectorX, path->sectorY, path->sectorZ); + } else if (path->IsSystemPath()) { + lua_pushfstring(l, "<%d,%d,%d : %d>", + path->sectorX, path->sectorY, path->sectorZ, + path->systemIndex); + } else { + assert(path->IsBodyPath()); + lua_pushfstring(l, "<%d,%d,%d : %d, %d>", + path->sectorX, path->sectorY, path->sectorZ, + path->systemIndex, path->bodyIndex); + } + return 1; +} + +template <> const char *LuaObject >::s_type = "SystemPath"; + +template <> void LuaObject >::RegisterClass() +{ + static const luaL_Reg l_methods[] = { + { "New", l_sbodypath_new }, + + { "IsSameSystem", l_sbodypath_is_same_system }, + { "IsSameSector", l_sbodypath_is_same_sector }, + + { "SystemOnly", l_sbodypath_system_only }, + { "SectorOnly", l_sbodypath_sector_only }, + + { "DistanceTo", l_sbodypath_distance_to }, + + { "GetStarSystem", l_sbodypath_get_star_system }, + { "GetSystemBody", l_sbodypath_get_system_body }, + + { 0, 0 } + }; + + static const luaL_Reg l_attrs[] = { + { "sectorX", l_sbodypath_attr_sector_x }, + { "sectorY", l_sbodypath_attr_sector_y }, + { "sectorZ", l_sbodypath_attr_sector_z }, + { "systemIndex", l_sbodypath_attr_system_index }, + { "bodyIndex", l_sbodypath_attr_body_index }, + { 0, 0 } + }; + + static const luaL_Reg l_meta[] = { + { "__eq", l_sbodypath_meta_eq }, + { "__tostring", l_sbodypath_meta_tostring }, + { 0, 0 } + }; + + LuaObjectBase::CreateClass(s_type, NULL, l_methods, l_attrs, l_meta); +} diff --git a/pool/shard006/C++/0074222_video.cpp b/pool/shard006/C++/0074222_video.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47ca97cd8124efb790fd332eb2ae6129d51b957a --- /dev/null +++ b/pool/shard006/C++/0074222_video.cpp @@ -0,0 +1,114 @@ +#include "video.h" + +Video::Video(QQmlComponent *mc, QString r_id, Launcher *lc, QObject *parent) : PlayerBaseMedia(mc, r_id, lc, parent) +{ + setRegionId(r_id); + +#ifdef SUPPORT_QTAV + QString module = "import QtAV 1.7\n"; +#else + QString module = "import QtMultimedia 5.12\n"; +#endif + qml = "import QtQuick 2.12\n " + + module + + "Video { \ + id: "+getRegionId()+"_video; \ + orientation: 0; \ + autoLoad: true; \ + autoPlay: true; \ + anchors.fill: parent; \ + }\n"; + + media_component = mc; + video_item.reset(createMediaItem(media_component, qml)); + connect(video_item.data(), SIGNAL(stopped()), this, SLOT(doStopped())); +} + +Video::~Video() +{ + video_item.reset(); +} + +void Video::init(BaseMedia *media, Region *reg) +{ + SmilMedia = media; + region = reg; + if (load(video_item.data())) + { + // cannot be connected once in constructor due to again Android/QMultimedia problems + // see @ method finished + // connect(video_item.data(), SIGNAL(stopped()), this, SLOT(doStopped())); + + // to set Volume we need to cast + TVideo *MyVideo = qobject_cast (media); + float vol = determineVolume(MyVideo->getSoundLevel()); + video_item.data()->setProperty("volume", vol); + if (SmilMedia->getLogContentId() != "") + setStartTime(); + } +} + +void Video::deinit() +{ + if (!SmilMedia->getLogContentId().isEmpty()) + qInfo(PlayLog).noquote() << createPlayLogXml(); + + video_item.data()->setProperty("source", ""); +} + +void Video::setParentItem(QQuickItem *parent) +{ + video_item.data()->setParentItem(parent); +} + +void Video::changeSize(int w, int h) +{ + QString smil_fit = SmilMedia->getFit().toLower(); + int fill_mode = 6; // for do nothing + if (smil_fit == "fill") + fill_mode = Qt::IgnoreAspectRatio; + else if (smil_fit == "meet") + fill_mode = Qt::KeepAspectRatio; + else if (smil_fit == "meetbest") + { +// if (loaded_image.width() >= w || loaded_image.height() > h) +// fill_mode = Qt::KeepAspectRatio; +// else + fill_mode = NONE; + } + else if (smil_fit == "slice") + fill_mode = Qt::KeepAspectRatioByExpanding; + + video_item.data()->setProperty("fillMode", fill_mode); +} + +qreal Video::determineVolume(QString percent) +{ + qreal vol = 0; + if (percent.endsWith('%')) + vol = percent.midRef(0, percent.length()-1).toFloat(); + + return vol / (float) 100; +} + +void Video::doStopped() +{ + // deprecated? 17.01.2021 + // must be disconected otherwise QMultimedia/Android will stop immediately when new video will be load + // so only first Video will shown + // disconnect(video_item.data(), SIGNAL(qmlSignal(QString)), this, SLOT(doStopped(QString))); + + if (video_item.data()->property("error").toInt() != 0) + { + QStringList list; + list << "resourceURI" << SmilMedia->getSrc() + << "error"<< video_item.data()->property("error").toString() + << "errorMessage" << video_item.data()->property("errorString").toString(); + qCritical(MediaPlayer) << MyLogger.createEventLogMetaData("MEDIA_PLAYBACK_ERROR", list); + } + + if (video_item.data()->property("status").toString() == "7") // 7 means EndOfFile Shitty QML has no signal for finish + { + SmilMedia->finishIntrinsicDuration(); + } +} diff --git a/pool/shard006/C++/0074223_citra.cpp b/pool/shard006/C++/0074223_citra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..128b9a16ddeb2d9c8a587d8eb0b90c9253a8087f --- /dev/null +++ b/pool/shard006/C++/0074223_citra.cpp @@ -0,0 +1,156 @@ +// Copyright 2014 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include + +// This needs to be included before getopt.h because the latter #defines symbols used by it +#include "common/microprofile.h" + +#ifdef _MSC_VER +#include +#else +#include +#include +#endif + +#ifdef _WIN32 +#include +#endif + +#include "common/logging/log.h" +#include "common/logging/backend.h" +#include "common/logging/filter.h" +#include "common/scm_rev.h" +#include "common/scope_exit.h" +#include "common/string_util.h" + +#include "core/settings.h" +#include "core/system.h" +#include "core/core.h" +#include "core/gdbstub/gdbstub.h" +#include "core/loader/loader.h" + +#include "citra/config.h" +#include "citra/emu_window/emu_window_sdl2.h" + +#include "video_core/video_core.h" + + +static void PrintHelp(const char *argv0) +{ + std::cout << "Usage: " << argv0 << " [options] \n" + "-g, --gdbport=NUMBER Enable gdb stub on port NUMBER\n" + "-h, --help Display this help and exit\n" + "-v, --version Output version information and exit\n"; +} + +static void PrintVersion() +{ + std::cout << "Citra " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl; +} + +/// Application entry point +int main(int argc, char **argv) { + Config config; + int option_index = 0; + bool use_gdbstub = Settings::values.use_gdbstub; + u32 gdb_port = static_cast(Settings::values.gdbstub_port); + char *endarg; +#ifdef _WIN32 + int argc_w; + auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w); + + if (argv_w == nullptr) { + LOG_CRITICAL(Frontend, "Failed to get command line arguments"); + return -1; + } +#endif + std::string boot_filename; + + static struct option long_options[] = { + { "gdbport", required_argument, 0, 'g' }, + { "help", no_argument, 0, 'h' }, + { "version", no_argument, 0, 'v' }, + { 0, 0, 0, 0 } + }; + + while (optind < argc) { + char arg = getopt_long(argc, argv, "g:hv", long_options, &option_index); + if (arg != -1) { + switch (arg) { + case 'g': + errno = 0; + gdb_port = strtoul(optarg, &endarg, 0); + use_gdbstub = true; + if (endarg == optarg) errno = EINVAL; + if (errno != 0) { + perror("--gdbport"); + exit(1); + } + break; + case 'h': + PrintHelp(argv[0]); + return 0; + case 'v': + PrintVersion(); + return 0; + } + } else { +#ifdef _WIN32 + boot_filename = Common::UTF16ToUTF8(argv_w[optind]); +#else + boot_filename = argv[optind]; +#endif + optind++; + } + } + +#ifdef _WIN32 + LocalFree(argv_w); +#endif + + Log::Filter log_filter(Log::Level::Debug); + Log::SetFilter(&log_filter); + + MicroProfileOnThreadCreate("EmuThread"); + SCOPE_EXIT({ MicroProfileShutdown(); }); + + if (boot_filename.empty()) { + LOG_CRITICAL(Frontend, "Failed to load ROM: No ROM specified"); + return -1; + } + + log_filter.ParseFilterString(Settings::values.log_filter); + + // Apply the command line arguments + Settings::values.gdbstub_port = gdb_port; + Settings::values.use_gdbstub = use_gdbstub; + Settings::Apply(); + + std::unique_ptr emu_window = std::make_unique(); + + System::Init(emu_window.get()); + SCOPE_EXIT({ System::Shutdown(); }); + + std::unique_ptr loader = Loader::GetLoader(boot_filename); + if (!loader) { + LOG_CRITICAL(Frontend, "Failed to obtain loader for %s!", boot_filename.c_str()); + return -1; + } + + Loader::ResultStatus load_result = loader->Load(); + if (Loader::ResultStatus::Success != load_result) { + LOG_CRITICAL(Frontend, "Failed to load ROM (Error %i)!", load_result); + return -1; + } + + while (emu_window->IsOpen()) { + Core::RunLoop(); + } + + return 0; +} diff --git a/pool/shard006/C++/0074228_main.cpp b/pool/shard006/C++/0074228_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7b7d8feee78e059bebfde492a564a162973a9dd --- /dev/null +++ b/pool/shard006/C++/0074228_main.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +extern "C" +{ +extern int LTGR01(char* p_0, char* p_1); + +int main() +{ + FILE *fp; + unsigned char p_0[8]={0}, p_1[8]={0}; + int i, temp=-1; + + for(i=0; i<8; i++) + { + p_0[i] = 0xf0+i; + p_1[i] = 0x10+i+i; + } + + fp = fopen("OUT", "w+"); + + fprintf(fp, "before: p_0 = [0x%02x%02x%02x%02x%02x%02x%02x%02x], p_1 = [0x%02x%02x%02x%02x%02x%02x%02x%02x]\n", + p_0[0], p_0[1], p_0[2], p_0[3], + p_0[4], p_0[5], p_0[6], p_0[7], + p_1[0], p_1[1], p_1[2], p_1[3], + p_1[4], p_1[5], p_1[6], p_1[7] + ); + LTGR01((char*)p_0, (char*)p_1); + fprintf(fp, "after: p_0 = [0x%02x%02x%02x%02x%02x%02x%02x%02x], p_1 = [0x%02x%02x%02x%02x%02x%02x%02x%02x]\n", + p_0[0], p_0[1], p_0[2], p_0[3], + p_0[4], p_0[5], p_0[6], p_0[7], + p_1[0], p_1[1], p_1[2], p_1[3], + p_1[4], p_1[5], p_1[6], p_1[7] + ); + + fclose(fp); + return 0; +} +} diff --git a/pool/shard006/C++/0074229_RouteObjects.cpp b/pool/shard006/C++/0074229_RouteObjects.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5015e223e48ad840ea6a56dce4508d5390f4de67 --- /dev/null +++ b/pool/shard006/C++/0074229_RouteObjects.cpp @@ -0,0 +1,138 @@ +/****************************************************************** +* +* Round for C++ +* +* Copyright (C) Satoshi Konno 2015 +* +* This is licensed under BSD-style license, see file COPYING. +* +******************************************************************/ + +#include +#include +#include + +#include + +#include + +const std::string Round::RouteObjects::OBJECT_SEP = "."; +const int Round::RouteObjects::OBJECT_NUM = 3; + +const int Round::RouteObjects::TARGET = 0; +const int Round::RouteObjects::NODE = 1; +const int Round::RouteObjects::CLUSTER = 2; + +Round::RouteObjects::RouteObjects() { +} + +Round::RouteObjects::RouteObjects(const std::string &value) { + parse(value); +} + +Round::RouteObjects::~RouteObjects() { +} + +bool Round::RouteObjects::isValid() const { + if (size() != OBJECT_NUM) + return false; + return true; +} + +bool Round::RouteObjects::parse(const std::string &value) { + clear(); + + if (value.length() <= 0) + return false; + + std::list objectList; + boost::split(objectList, value, boost::is_any_of(OBJECT_SEP)); + + size_t objectSize = objectList.size(); + if ((objectSize < 1) || (OBJECT_NUM < objectSize)) + return false; + + this->insert(std::pair(TARGET, Route::METHOD_DEFALUT)); + this->insert(std::pair(NODE, Route::NODE_DEFALUT)); + this->insert(std::pair(CLUSTER, Route::CLUSTER_DEFALUT)); + + int objectIdx = 0; + BOOST_REVERSE_FOREACH(std::string object, objectList) { + RouteObjects::iterator objIt = find(objectIdx); + if (objIt != RouteObjects::end()) { + erase(objIt); + } + this->insert(std::pair(objectIdx, object)); + objectIdx++; + } + + return true; +} + +bool Round::RouteObjects::getObject(int objIdx, std::string *value) const { + RouteObjects::const_iterator objIt = find(objIdx); + if (objIt == end()) + return false; + *value = objIt->second; + return true; +} + +bool Round::RouteObjects::equals(const RouteObjects &otherObj) const { + if (!isValid() || !otherObj.isValid()) + return false; + + for (RouteObjects::const_iterator objIt = begin(); objIt != end(); objIt++) { + int objIdx = objIt->first; + std::string objVal = objIt->second; + RouteObjects::const_iterator otherObjIt = otherObj.find(objIdx); + if (otherObjIt == otherObj.end()) + return false; + if (objVal.compare(otherObjIt->second) != 0) + return false; + } + + return true; +} + +bool Round::RouteObjects::isMethod(const std::string &value) const { + std::string thisValue; + if (!getTarget(&thisValue)) + return false; + return (thisValue.compare(value) == 0) ? true : false; +} + +bool Round::RouteObjects::isNode(const std::string &value) const { + std::string thisValue; + if (!getNode(&thisValue)) + return false; + return (thisValue.compare(value) == 0) ? true : false; +} + +bool Round::RouteObjects::isCluster(const std::string &value) const { + std::string thisValue; + if (!getCluster(&thisValue)) + return false; + return (thisValue.compare(value) == 0) ? true : false; +} + +bool Round::RouteObjects::equals(const std::string &otherRoute) const { + RouteObjects otherRouteObjs(otherRoute); + return equals(otherRouteObjs); +} + +bool Round::RouteObjects::toString(std::string *value) const { + if (!value) + return false; + + *value = ""; + for (int n=(OBJECT_NUM-1); 0<=n; n--) { + std::string objStr; + if (!getObject(n, &objStr)) + continue; + if (0 < (*value).length()) { + *value += OBJECT_SEP; + } + *value += objStr; + } + return true; +} diff --git a/pool/shard006/C++/0074232_UseVector.cpp b/pool/shard006/C++/0074232_UseVector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..63022fbf1d317fff02734792cbac1e0a509f894e --- /dev/null +++ b/pool/shard006/C++/0074232_UseVector.cpp @@ -0,0 +1,71 @@ +/* + * UseVector.cpp + * + * Created on: Oct 3, 2015 + * Author: kelly + */ + +#include "UseVector.h" + +#include + + +namespace gitux { + +using namespace std; + +UseVector::UseVector() { + shapeVector = new vector(); +} + +UseVector::~UseVector() { + vector::iterator vectorIterator; + for (vectorIterator = shapeVector->begin(); vectorIterator < shapeVector->end(); vectorIterator++) { + delete (*vectorIterator); + } + delete shapeVector; +} + +void UseVector::pushBackVector(Shape *element) { + shapeVector->push_back(element); +} + +void UseVector::printElement(Circle *element) { + cout << "in printElement for circle" << endl; +} + +void UseVector::printElement(Rectangle *element) { + cout << "in printElement for rectangle" << endl; +} + +void UseVector::printElement(Triangle *element) { + cout << "in printElement for triangle" << endl; +} + +void UseVector::printVector() { + vector::iterator vectorIterator; + Circle *circleElement; + Rectangle *rectangleElement; + Triangle *triangleElement; + + for (vectorIterator = shapeVector->begin(); vectorIterator < shapeVector->end(); vectorIterator++) { + if ((*vectorIterator)->getShapeType() == "Circle") { + circleElement = dynamic_cast((*vectorIterator)); + cout << "The circle has a area of " << (*vectorIterator)->getArea() << endl;; + cout << "The circleElement has an area of " << circleElement->getArea() << endl; + this->printElement(circleElement); + } else if ((*vectorIterator)->getShapeType() == "Rectangle") { + rectangleElement = dynamic_cast((*vectorIterator)); + cout << "The rectangle has a area of " << (*vectorIterator)->getArea() << endl; + cout << "The rectangleElement has an area of " << rectangleElement->getArea() << endl; + this->printElement(rectangleElement); + } else if ((*vectorIterator)->getShapeType() == "Triangle") { + triangleElement = dynamic_cast((*vectorIterator)); + cout << "The triangle has a area of " << (*vectorIterator)->getArea() << endl; + cout << "The triangleElement has an area of " << triangleElement->getArea() << endl; + this->printElement(triangleElement); + } + } +} + +} /* namespace gitux */ diff --git a/pool/shard006/C++/0074260_framebuffer.cpp b/pool/shard006/C++/0074260_framebuffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2210c899d800e2f475e23836cdda4634e9c183a3 --- /dev/null +++ b/pool/shard006/C++/0074260_framebuffer.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include +#include "framebuffer.h" + +namespace fb +{ + +FrameBuffer::FrameBuffer(std::string device) +{ + fbp = NULL; + fbh = 0; + + memset(&vinfo, 0, sizeof(struct fb_var_screeninfo)); + memset(&finfo, 0, sizeof(struct fb_fix_screeninfo)); + bytes_per_pixel = 0; + x_bytes_per_pixel = 0; + y_bytes_per_pixel = 0; + + if(device.empty()) + return; + + fbh = open(device.c_str(), O_RDWR); + + if(fbh < 0) + return; + + // Get fixed screen information + if (ioctl(fbh, FBIOGET_FSCREENINFO, &finfo) == -1) { + perror("Error reading fixed information"); + return; + } + + // Get variable screen information + if (ioctl(fbh, FBIOGET_VSCREENINFO, &vinfo) == -1) { + perror("Error reading variable information"); + return; + } + + bytes_per_pixel = vinfo.bits_per_pixel / 8; + x_bytes_per_pixel = vinfo.xres * bytes_per_pixel; + y_bytes_per_pixel = vinfo.yres * bytes_per_pixel; + + // Figure out the size of the screen in bytes + int screensize = vinfo.xres * vinfo.yres * bytes_per_pixel; + + // Map the device to memory + fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbh, 0); + + if (fbp == NULL) { + perror("Error: failed to map framebuffer device to memory"); + return; + } +} + +FrameBuffer::~FrameBuffer() +{ + if(this->isOpen()){ + int screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8; + munmap(fbp, screensize); // Unmap the allocated memory + + close(fbh); + + fbp = NULL; + fbh = 0; + + memset(&vinfo, 0, sizeof(struct fb_var_screeninfo)); + memset(&finfo, 0, sizeof(struct fb_fix_screeninfo)); + } +} + +int FrameBuffer::put(unsigned int location, unsigned char value) +{ + *(fbp + location) = value; + return 0; +} + +int FrameBuffer::put(unsigned int location, unsigned short value) +{ + *(fbp + location) = (char)value; + *(fbp + location + 1) = (char)(value >> 8); + return 0; +} + +int FrameBuffer::put_pixel(int x, int y, unsigned short value) +{ + if((x > (int)this->vinfo.xres) || (y > (int)this->vinfo.yres)) + return -1; + + unsigned int location = (y * this->finfo.line_length) + (x * bytes_per_pixel); + + *(fbp + location) = (char)value; + *(fbp + location + 1) = (char)(value >> 8); + + return 0; +} + +} diff --git a/pool/shard006/C++/0074261_OgreShaderHLSLProgramProcessor.cpp b/pool/shard006/C++/0074261_OgreShaderHLSLProgramProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1189303bd4d0582dec8aa5886b33381cdb1c629 --- /dev/null +++ b/pool/shard006/C++/0074261_OgreShaderHLSLProgramProcessor.cpp @@ -0,0 +1,79 @@ +/* +----------------------------------------------------------------------------- +This source file is part of OGRE +(Object-oriented Graphics Rendering Engine) +For the latest info, see http://www.ogre3d.org/ + +Copyright (c) 2000-2012 Torus Knot Software Ltd +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 "OgreShaderHLSLProgramProcessor.h" +#include "OgreShaderProgramSet.h" +#include "OgreShaderProgram.h" + +namespace Ogre { +namespace RTShader { + +String HLSLProgramProcessor::TargetLanguage = "hlsl"; + +//----------------------------------------------------------------------------- +HLSLProgramProcessor::HLSLProgramProcessor() +{ + +} + +//----------------------------------------------------------------------------- +HLSLProgramProcessor::~HLSLProgramProcessor() +{ + +} + +//----------------------------------------------------------------------------- +bool HLSLProgramProcessor::preCreateGpuPrograms( ProgramSet* programSet ) +{ + Program* vsProgram = programSet->getCpuVertexProgram(); + Program* psProgram = programSet->getCpuFragmentProgram(); + Function* vsMain = vsProgram->getEntryPointFunction(); + Function* fsMain = psProgram->getEntryPointFunction(); + bool success; + + // Compact vertex shader outputs. + success = ProgramProcessor::compactVsOutputs(vsMain, fsMain); + if (success == false) + return false; + + return true; +} + +//----------------------------------------------------------------------------- +bool HLSLProgramProcessor::postCreateGpuPrograms( ProgramSet* programSet ) +{ + // Bind vertex shader auto parameters. + bindAutoParameters(programSet->getCpuVertexProgram(), programSet->getGpuVertexProgram()); + + // Bind fragment shader auto parameters. + bindAutoParameters(programSet->getCpuFragmentProgram(), programSet->getGpuFragmentProgram()); + + return true; +} + +} +} diff --git a/pool/shard006/C++/0074266_ocamlhelp.cc b/pool/shard006/C++/0074266_ocamlhelp.cc new file mode 100644 index 0000000000000000000000000000000000000000..1bc46ffa1d88821c0a5ad485a4cd2fff42d02e9b --- /dev/null +++ b/pool/shard006/C++/0074266_ocamlhelp.cc @@ -0,0 +1,45 @@ +// Copyright 2006-2007, Hendrik Tews, All rights reserved. * +// See file license.txt for terms of use * +//********************************************************************** + +// implementation of ocamlhelp.h -- ocaml serialization helpers + + +#include "ocamlhelp.h" + + +// hand written ocaml serialization function +value option_some_constr(value v){ + CAMLparam1(v); + CAMLlocal1(result); + result = caml_alloc(1, 0); // the option cell + Store_field(result, 0, v); + xassert(IS_OCAML_AST_VALUE(result)); + CAMLreturn(result); +} + + +value ocaml_list_rev(value l){ + CAMLparam1(l); + static value * list_rev_callback = NULL; + if(list_rev_callback == NULL) + list_rev_callback = caml_named_value("List.rev"); + xassert(list_rev_callback); + CAMLreturn(caml_callback(*list_rev_callback, l)); +} + +value ocaml_from_StringRef(StringRef sr, ToOcamlData *d){ + CAMLparam0(); + CAMLlocal2(result, tmp); + + static value *reg_string_callback = NULL; + if(reg_string_callback == NULL) + reg_string_callback = caml_named_value("Reg_StringRef"); + xassert(reg_string_callback); + + xassert(sr); + tmp = caml_copy_string(sr); + result = caml_callback2(*reg_string_callback, Val_long(unsigned(sr)>>1), tmp); + + CAMLreturn(result); +} diff --git a/pool/shard006/C++/0074280_extensions_helper.cc b/pool/shard006/C++/0074280_extensions_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..c6a91c4112dbf0e9dea0a8c36cc99d50a1c24a37 --- /dev/null +++ b/pool/shard006/C++/0074280_extensions_helper.cc @@ -0,0 +1,132 @@ +// Copyright (c) 2012 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/sync/test/integration/extensions_helper.h" + +#include + +#include "base/logging.h" +#include "base/string_number_conversions.h" +#include "base/string_util.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sync/test/integration/sync_datatype_helper.h" +#include "chrome/browser/sync/test/integration/sync_extension_helper.h" +#include "chrome/common/extensions/extension.h" + +using sync_datatype_helper::test; + +namespace extensions_helper { + +const char extension_name_prefix[] = "fakeextension"; + +bool HasSameExtensionsAsVerifier(int index) { + return SyncExtensionHelper::GetInstance()->ExtensionStatesMatch( + test()->GetProfile(index), test()->verifier()); +} + +bool AllProfilesHaveSameExtensionsAsVerifier() { + for (int i = 0; i < test()->num_clients(); ++i) { + if (!HasSameExtensionsAsVerifier(i)) { + LOG(ERROR) << "Profile " << i << " doesn't have the same extensions as" + " the verifier profile."; + return false; + } + } + return true; +} + +bool AllProfilesHaveSameExtensions() { + for (int i = 1; i < test()->num_clients(); ++i) { + if (!SyncExtensionHelper::GetInstance()->ExtensionStatesMatch( + test()->GetProfile(0), test()->GetProfile(i))) { + LOG(ERROR) << "Profile " << i << " doesnt have the same extensions as" + " profile 0."; + return false; + } + } + return true; +} + + +std::string InstallExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->InstallExtension( + profile, + CreateFakeExtensionName(index), + extensions::Extension::TYPE_EXTENSION); +} + +std::string InstallExtensionForAllProfiles(int index) { + for (int i = 0; i < test()->num_clients(); ++i) + InstallExtension(test()->GetProfile(i), index); + return InstallExtension(test()->verifier(), index); +} + +void UninstallExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->UninstallExtension( + profile, CreateFakeExtensionName(index)); +} + +std::vector GetInstalledExtensions(Profile* profile) { + std::vector indices; + std::vector names = + SyncExtensionHelper::GetInstance()->GetInstalledExtensionNames(profile); + for (std::vector::const_iterator it = names.begin(); + it != names.end(); ++it) { + int index; + if (ExtensionNameToIndex(*it, &index)) { + indices.push_back(index); + } + } + return indices; +} + +void EnableExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->EnableExtension( + profile, CreateFakeExtensionName(index)); +} + +void DisableExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->DisableExtension( + profile, CreateFakeExtensionName(index)); +} + +bool IsExtensionEnabled(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->IsExtensionEnabled( + profile, CreateFakeExtensionName(index)); +} + +void IncognitoEnableExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->IncognitoEnableExtension( + profile, CreateFakeExtensionName(index)); +} + +void IncognitoDisableExtension(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->IncognitoDisableExtension( + profile, CreateFakeExtensionName(index)); +} + +bool IsIncognitoEnabled(Profile* profile, int index) { + return SyncExtensionHelper::GetInstance()->IsIncognitoEnabled( + profile, CreateFakeExtensionName(index)); +} + +void InstallExtensionsPendingForSync(Profile* profile) { + SyncExtensionHelper::GetInstance()->InstallExtensionsPendingForSync(profile); +} + +std::string CreateFakeExtensionName(int index) { + return extension_name_prefix + base::IntToString(index); +} + +bool ExtensionNameToIndex(const std::string& name, int* index) { + if (!StartsWithASCII(name, extension_name_prefix, true) || + !base::StringToInt(name.substr(strlen(extension_name_prefix)), index)) { + LOG(WARNING) << "Unable to convert extension name \"" << name + << "\" to index"; + return false; + } + return true; +} + +} // namespace extensions_helper diff --git a/pool/shard006/C++/0074281_padding.cpp b/pool/shard006/C++/0074281_padding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23219b480fc9cac7e439d48638e74124ae058e9a --- /dev/null +++ b/pool/shard006/C++/0074281_padding.cpp @@ -0,0 +1,44 @@ +/* +* Sets of allowed padding schemes for public key types +* +* This file was automatically generated by ./src/scripts/oids.py on 2017-12-20 +* +* All manual edits to this file will be lost. Edit the script +* then regenerate this source file. +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include +#include +#include +#include +#include + +namespace Botan { + +const std::map> allowed_signature_paddings = + { + { "DSA", {"EMSA1"} }, + { "ECDSA", {"EMSA1"} }, + { "ECGDSA", {"EMSA1"} }, + { "ECKCDSA", {"EMSA1"} }, + { "GOST-34.10", {"EMSA1"} }, + { "GOST-34.10-2012-256", {"EMSA1"} }, + { "GOST-34.10-2012-512", {"EMSA1"} }, + { "RSA", {"EMSA4", "EMSA3"} }, + }; + +std::vector get_sig_paddings(const std::string& algo) + { + if(allowed_signature_paddings.count(algo) > 0) + return allowed_signature_paddings.at(algo); + return {}; + } + +bool sig_algo_and_pad_ok(const std::string& algo, const std::string& padding) + { + std::vector pads = get_sig_paddings(algo); + return std::find(pads.begin(), pads.end(), padding) != pads.end(); + } +} diff --git a/pool/shard006/C++/0074282_LuaContext.cpp b/pool/shard006/C++/0074282_LuaContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..895d5ef68c652705eac489d820eacec8e9bc1fff --- /dev/null +++ b/pool/shard006/C++/0074282_LuaContext.cpp @@ -0,0 +1,150 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2013 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * 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 "LuaContext.h" + +#include + +extern "C" +{ +#include +#include +} + +namespace Orthanc +{ + int LuaContext::PrintToLog(lua_State *state) + { + // Get the pointer to the "LuaContext" underlying object + lua_getglobal(state, "_LuaContext"); + assert(lua_type(state, -1) == LUA_TLIGHTUSERDATA); + LuaContext* that = const_cast(reinterpret_cast(lua_topointer(state, -1))); + assert(that != NULL); + lua_pop(state, 1); + + // http://medek.wordpress.com/2009/02/03/wrapping-lua-errors-and-print-function/ + int nArgs = lua_gettop(state); + lua_getglobal(state, "tostring"); + + // Make sure you start at 1 *NOT* 0 for arrays in Lua. + std::string result; + + for (int i = 1; i <= nArgs; i++) + { + const char *s; + lua_pushvalue(state, -1); + lua_pushvalue(state, i); + lua_call(state, 1, 1); + s = lua_tostring(state, -1); + + if (result.size() > 0) + result.append(", "); + + if (s == NULL) + result.append(""); + else + result.append(s); + + lua_pop(state, 1); + } + + LOG(INFO) << "Lua says: " << result; + that->log_.append(result); + that->log_.append("\n"); + + return 0; + } + + + LuaContext::LuaContext() + { + lua_ = luaL_newstate(); + if (!lua_) + { + throw LuaException("Unable to create the Lua context"); + } + + luaL_openlibs(lua_); + lua_register(lua_, "print", PrintToLog); + + lua_pushlightuserdata(lua_, this); + lua_setglobal(lua_, "_LuaContext"); + } + + + LuaContext::~LuaContext() + { + lua_close(lua_); + } + + + void LuaContext::Execute(std::string* output, + const std::string& command) + { + boost::mutex::scoped_lock lock(mutex_); + + log_.clear(); + int error = (luaL_loadbuffer(lua_, command.c_str(), command.size(), "line") || + lua_pcall(lua_, 0, 0, 0)); + + if (error) + { + assert(lua_gettop(lua_) >= 1); + + std::string description(lua_tostring(lua_, -1)); + lua_pop(lua_, 1); /* pop error message from the stack */ + throw LuaException(description); + } + + if (output != NULL) + { + *output = log_; + } + } + + + void LuaContext::Execute(EmbeddedResources::FileResourceId resource) + { + std::string command; + EmbeddedResources::GetFileResource(command, resource); + Execute(command); + } + + + bool LuaContext::IsExistingFunction(const char* name) + { + boost::mutex::scoped_lock lock(mutex_); + lua_settop(lua_, 0); + lua_getglobal(lua_, name); + return lua_type(lua_, -1) == LUA_TFUNCTION; + } +} diff --git a/pool/shard006/C++/0074285_ExampleWithARelation.cc b/pool/shard006/C++/0074285_ExampleWithARelation.cc new file mode 100644 index 0000000000000000000000000000000000000000..91add5442b17fea160c32330fed764170f9bc817 --- /dev/null +++ b/pool/shard006/C++/0074285_ExampleWithARelation.cc @@ -0,0 +1,140 @@ +// datamodel specific includes +#include "ExampleWithARelation.h" +#include "ExampleWithARelationCollection.h" +#include "ExampleWithARelationConst.h" +#include "ExampleWithARelationData.h" +#include "ExampleWithARelationObj.h" +#include "ExampleWithNamespace.h" +#include + +namespace ex { + +ExampleWithARelation::ExampleWithARelation() + : m_obj(new ExampleWithARelationObj()) { + m_obj->acquire(); +} + +ExampleWithARelation::ExampleWithARelation(float number) + : m_obj(new ExampleWithARelationObj()) { + m_obj->acquire(); + m_obj->data.number = number; +} + +ExampleWithARelation::ExampleWithARelation(const ExampleWithARelation &other) + : m_obj(other.m_obj) { + m_obj->acquire(); +} + +ExampleWithARelation &ExampleWithARelation:: +operator=(const ExampleWithARelation &other) { + if (m_obj != nullptr) + m_obj->release(); + m_obj = other.m_obj; + return *this; +} + +ExampleWithARelation::ExampleWithARelation(ExampleWithARelationObj *obj) + : m_obj(obj) { + if (m_obj != nullptr) + m_obj->acquire(); +} + +ExampleWithARelation ExampleWithARelation::clone() const { + return {new ExampleWithARelationObj(*m_obj)}; +} + +ExampleWithARelation::~ExampleWithARelation() { + if (m_obj != nullptr) + m_obj->release(); +} + +ExampleWithARelation::operator ConstExampleWithARelation() const { + return ConstExampleWithARelation(m_obj); +} + +const float &ExampleWithARelation::number() const { return m_obj->data.number; } +const ex::ConstExampleWithNamespace ExampleWithARelation::ref() const { + if (m_obj->m_ref == nullptr) { + return ex::ConstExampleWithNamespace(nullptr); + } + return ex::ConstExampleWithNamespace(*(m_obj->m_ref)); +} +void ExampleWithARelation::number(float value) { m_obj->data.number = value; } +void ExampleWithARelation::ref(ex::ConstExampleWithNamespace value) { + if (m_obj->m_ref != nullptr) + delete m_obj->m_ref; + m_obj->m_ref = new ConstExampleWithNamespace(value); +} + +std::vector::const_iterator +ExampleWithARelation::refs_begin() const { + auto ret_value = m_obj->m_refs->begin(); + std::advance(ret_value, m_obj->data.refs_begin); + return ret_value; +} + +std::vector::const_iterator +ExampleWithARelation::refs_end() const { + auto ret_value = m_obj->m_refs->begin(); + std::advance(ret_value, m_obj->data.refs_end); + return ret_value; +} + +void ExampleWithARelation::addrefs(ex::ConstExampleWithNamespace component) { + m_obj->m_refs->push_back(component); + m_obj->data.refs_end++; +} + +unsigned int ExampleWithARelation::refs_size() const { + return (m_obj->data.refs_end - m_obj->data.refs_begin); +} + +ex::ConstExampleWithNamespace +ExampleWithARelation::refs(unsigned int index) const { + if (refs_size() > index) { + return m_obj->m_refs->at(m_obj->data.refs_begin + index); + } else + throw std::out_of_range("index out of bounds for existing references"); +} + +bool ExampleWithARelation::isAvailable() const { + if (m_obj != nullptr) { + return true; + } + return false; +} + +const podio::ObjectID ExampleWithARelation::getObjectID() const { + if (m_obj != nullptr) { + return m_obj->id; + } + return podio::ObjectID{-2, -2}; +} + +bool ExampleWithARelation:: +operator==(const ConstExampleWithARelation &other) const { + return (m_obj == other.m_obj); +} + +std::ostream &operator<<(std::ostream &o, + const ConstExampleWithARelation &value) { + o << " id : " << value.id() << std::endl; + o << " number : " << value.number() << std::endl; + o << " ref : " << value.ref().id() << std::endl; + o << " refs : "; + for (unsigned i = 0, N = value.refs_size(); i < N; ++i) + o << value.refs(i) << " "; + o << std::endl; + return o; +} + +// bool operator< (const ExampleWithARelation& p1, const ExampleWithARelation& +// p2 ) { +// if( p1.m_containerID == p2.m_containerID ) { +// return p1.m_index < p2.m_index; +// } else { +// return p1.m_containerID < p2.m_containerID; +// } +//} + +} // namespace ex diff --git a/pool/shard006/C++/0074291_render_media_client.cc b/pool/shard006/C++/0074291_render_media_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4f7291b1449a29fbb8db445cef0e357b2ab3a2b --- /dev/null +++ b/pool/shard006/C++/0074291_render_media_client.cc @@ -0,0 +1,57 @@ +// Copyright 2014 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 "content/renderer/media/render_media_client.h" + +#include "base/command_line.h" +#include "base/time/default_tick_clock.h" +#include "content/public/common/content_client.h" +#include "content/public/renderer/content_renderer_client.h" +#include "media/base/audio_parameters.h" +#include "media/base/media_switches.h" +#include "media/base/video_color_space.h" +#include "ui/display/display_switches.h" + +namespace content { + +void RenderMediaClient::Initialize() { + static RenderMediaClient* client = new RenderMediaClient(); + media::SetMediaClient(client); +} + +RenderMediaClient::RenderMediaClient() {} + +RenderMediaClient::~RenderMediaClient() { +} + +void RenderMediaClient::AddSupportedKeySystems( + std::vector>* key_systems) { + GetContentClient()->renderer()->AddSupportedKeySystems(key_systems); +} + +bool RenderMediaClient::IsKeySystemsUpdateNeeded() { + return GetContentClient()->renderer()->IsKeySystemsUpdateNeeded(); +} + +bool RenderMediaClient::IsSupportedAudioType(const media::AudioType& type) { + return GetContentClient()->renderer()->IsSupportedAudioType(type); +} + +bool RenderMediaClient::IsSupportedVideoType(const media::VideoType& type) { + return GetContentClient()->renderer()->IsSupportedVideoType(type); +} + +bool RenderMediaClient::IsSupportedBitstreamAudioCodec( + media::AudioCodec codec) { + return GetContentClient()->renderer()->IsSupportedBitstreamAudioCodec(codec); +} + +absl::optional<::media::AudioRendererAlgorithmParameters> +RenderMediaClient::GetAudioRendererAlgorithmParameters( + media::AudioParameters audio_parameters) { + return GetContentClient()->renderer()->GetAudioRendererAlgorithmParameters( + audio_parameters); +} + +} // namespace content diff --git a/pool/shard006/C++/0074292_encoder_state_feedback_unittest.cc b/pool/shard006/C++/0074292_encoder_state_feedback_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..5351e1516b18e078799630297550498b4aa30bc1 --- /dev/null +++ b/pool/shard006/C++/0074292_encoder_state_feedback_unittest.cc @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/video/encoder_state_feedback.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "webrtc/modules/utility/include/mock/mock_process_thread.h" +#include "webrtc/video/vie_encoder.h" + +using ::testing::NiceMock; + +namespace webrtc { + +class MockVieEncoder : public ViEEncoder { + public: + explicit MockVieEncoder(ProcessThread* process_thread) + : ViEEncoder(1, process_thread, nullptr, nullptr, nullptr) {} + ~MockVieEncoder() {} + + MOCK_METHOD1(OnReceivedIntraFrameRequest, void(size_t)); + MOCK_METHOD1(OnReceivedSLI, void(uint8_t picture_id)); + MOCK_METHOD1(OnReceivedRPSI, void(uint64_t picture_id)); +}; + +class VieKeyRequestTest : public ::testing::Test { + public: + VieKeyRequestTest() + : encoder_(&process_thread_), + simulated_clock_(123456789), + encoder_state_feedback_( + &simulated_clock_, + std::vector(1, VieKeyRequestTest::kSsrc), + &encoder_) {} + + protected: + const uint32_t kSsrc = 1234; + NiceMock process_thread_; + MockVieEncoder encoder_; + SimulatedClock simulated_clock_; + EncoderStateFeedback encoder_state_feedback_; +}; + +TEST_F(VieKeyRequestTest, CreateAndTriggerRequests) { + EXPECT_CALL(encoder_, OnReceivedIntraFrameRequest(0)).Times(1); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + + const uint8_t sli_picture_id = 3; + EXPECT_CALL(encoder_, OnReceivedSLI(sli_picture_id)).Times(1); + encoder_state_feedback_.OnReceivedSLI(kSsrc, sli_picture_id); + + const uint64_t rpsi_picture_id = 9; + EXPECT_CALL(encoder_, OnReceivedRPSI(rpsi_picture_id)).Times(1); + encoder_state_feedback_.OnReceivedRPSI(kSsrc, rpsi_picture_id); +} + +TEST_F(VieKeyRequestTest, TooManyOnReceivedIntraFrameRequest) { + EXPECT_CALL(encoder_, OnReceivedIntraFrameRequest(0)).Times(1); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + simulated_clock_.AdvanceTimeMilliseconds(10); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + + EXPECT_CALL(encoder_, OnReceivedIntraFrameRequest(0)).Times(1); + simulated_clock_.AdvanceTimeMilliseconds(300); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); + encoder_state_feedback_.OnReceivedIntraFrameRequest(kSsrc); +} + +} // namespace webrtc diff --git a/pool/shard006/C++/0074295_WdbDataRequestCommand.cpp b/pool/shard006/C++/0074295_WdbDataRequestCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e4f8fef5ce4630462afc2d7d6208b392febf447 --- /dev/null +++ b/pool/shard006/C++/0074295_WdbDataRequestCommand.cpp @@ -0,0 +1,193 @@ +/* + wdb - weather and water data storage + + Copyright (C) 2007 met.no + + Contact information: + Norwegian Meteorological Institute + Box 43 Blindern + 0313 OSLO + NORWAY + E-mail: wdb@met.no + + 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 +#include +#include +#include +#include +#include +#include + +namespace { + +class ReadHelper : public wdb2ts::WciReadHelper +{ + wdb2ts::LocationPointData &data; + std::string query_; + const wdb2ts::ParamDefList ¶mDefs; + const wdb2ts::ProviderList &providerPriority; + wdb2ts::PtrProviderRefTimes refTimes; + const int wciProtocol; + bool isPolygon; + std::string id_; + +public: + ReadHelper( wdb2ts::LocationPointData &data_, + const std::string &query, + const wdb2ts::ParamDefList ¶mDefs_, + const wdb2ts::ProviderList &providerPriority_, + wdb2ts::PtrProviderRefTimes refTimes_, + const int wciProtocol_, + bool isPolygon_ ) + : data( data_ ), + query_( query ), + paramDefs( paramDefs_ ), + providerPriority( providerPriority_ ), + refTimes( refTimes_ ), + wciProtocol( wciProtocol_ ), + isPolygon( isPolygon_ ) + { + std::ostringstream ost; + ost << "tid: " << boost::this_thread::get_id() << ""; + ost << ". WdbDataRequestCommand"; + id_ = ost.str(); + } + + std::string id() { return id_; } + std::string query() { return query_; } + void clear() { data.clear(); } + + void doRead( pqxx::result &result ) { + //miutil::container::PqContainer container( result ); + decodePData( paramDefs, providerPriority, *refTimes, result, isPolygon, data, wciProtocol ); + } +}; + +} + + +namespace wdb2ts { + + +void +WdbDataRequestCommand:: +operator()() +{ + //Register the requesthandler in this thread. + WEBFW_USE_LOGGER_REQUESTHANDLER( "wdb", reqHandler ); + log4cpp::Priority::Value loglevel = WEBFW_GET_LOGLEVEL(); + std::ostringstream tidOst; + + tidOst << boost::this_thread::get_id(); + myTid = tidOst.str(); + + try { + ReadHelper readHelper( *data_, query_, *paramDefs, *providerPriority, + refTimes, wciProtocol, isPolygon ); + + WciRead transactor( &readHelper ); + + if( connection_ ) + connection_->perform( transactor, 2 ); + + validate(); + } + catch( const std::exception &ex ) { + *ok_ = false; + *errMsg_ = ex.what(); + } + catch( ... ) { + *ok_ = false; + *errMsg_ = "Unknown exception"; + } + + connection_.reset(); //Release the connection +}; + + +/** + * The function removes data if the forecast data is shorter than the + * prognosis length. + */ +void +WdbDataRequestCommand:: +validatePrognosisLength() +{ + using namespace boost; + using namespace boost::posix_time; + + if( minPrognosisEndTime_.is_special() ) + return; + + WEBFW_USE_LOGGER_REQUESTHANDLER( "wdb", reqHandler ); + ptime constFieldTime( gregorian::date(1970, 1, 1), time_duration( 0, 0, 0 ) ); + //ptime progLength = now + seconds( prognosisLengthSeconds_ ); + + LocationPointData::iterator itLocation=data_->begin(); + + while( itLocation != data_->end() ) { + if( ! itLocation->second || itLocation->second->empty() ) { + itLocation = miutil::eraseElement( *data_, itLocation ); + WEBFW_LOG_INFO("tid: " << myTid << ". Data removed, less data than the minimum prognosis length " << minPrognosisEndTime_ << "."); + continue; + } + +// if( logLevel >= log4cpp::Priority::DEBUG ) { +// std::ostringstream ost; +// printTimeSerie( ost, itLocation->second->begin(), itLocation->second->end(), 3 ); +// WEBFW_LOG_DEBUG("tid: " << myTid <<".\n" << ost.str()); +// } + + //The TimeSerie collection is sorted by to_time. With the start of + //the forecast first. + //We use a reverse iterator, ie we start at the end of the forecast. + //If there is only constant fields, this is now at the start of the + //reverse iterator. + TimeSerie::reverse_iterator ritTime = itLocation->second->rbegin(); + + //Ignore constant fields, ie fields that do not vary i time. + if( ritTime->first == constFieldTime ) + continue; + + if( ritTime->first < minPrognosisEndTime_ ) { + if( logLevel >= log4cpp::Priority::DEBUG ) { + std::ostringstream ost; + printTimeSerie( ost, itLocation->second->begin(), itLocation->second->end(), 3 ); + WEBFW_LOG_DEBUG("tid: " << myTid << ". Data removed, less data than the minimum prognosis length " << minPrognosisEndTime_ << ".\n" + << ost.str()); + } + + itLocation = miutil::eraseElement( *data_, itLocation ); + WEBFW_LOG_INFO("tid: " << myTid << ". Data removed, less data than the minimum prognosis length " << minPrognosisEndTime_ << "."); + continue; + } + + ++itLocation; + } +} + +void +WdbDataRequestCommand:: +validate() +{ + validatePrognosisLength(); + removeEmptyData( *data_ ); +} + +} diff --git a/pool/shard006/C++/0074296_AboutBoxDialog.cpp b/pool/shard006/C++/0074296_AboutBoxDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af9afedf0a57a9a42e6342b50161c753160f25f4 --- /dev/null +++ b/pool/shard006/C++/0074296_AboutBoxDialog.cpp @@ -0,0 +1,65 @@ +/* + * QForceStudio - Explore Force Feedback on Linux. + * + * Copyright (C) 2014 Logitech Europe S.A. + * + * 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. + * + * To Contact Logitech Europe S.A. please send an email to + * devtechsupport@logitech.com or via mail at EPFL - Quartier de + * l'Innovation Daniel Borel Innovation Center CH - 1015 Lausanne, + * Attention Roland Bosa. + * + */ + +#include "AboutBoxDialog.h" +#include "ui_AboutBoxDialog.h" +#include +#include "QForceStudio.h" +#include + +AboutBoxDialog::AboutBoxDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::AboutBoxDialog) +{ + ui->setupUi(this); + + connect(ui->licenseButton, SIGNAL(clicked()), this, SLOT(onLicense())); + connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(reject())); + + ui->licenseTextEdit->setVisible(false); + + QFile licenseFile(":LICENSE"); + licenseFile.open(QIODevice::ReadOnly); + QByteArray license = licenseFile.readAll(); + licenseFile.close(); + + ui->licenseTextEdit->setPlainText(QString::fromUtf8(license)); + + ui->versionLabel->setText(tr("QForceStudio V%1").arg(_VERSION_STR_)); +} + +AboutBoxDialog::~AboutBoxDialog(void) +{ + delete ui; +} + +void AboutBoxDialog::onLicense(void) +{ + qDebug() << "Showing license..."; + ui->licenseTextEdit->setVisible(true); + ui->licenseButton->setEnabled(false); +} diff --git a/pool/shard006/C++/0074298_SpriteManager.cpp b/pool/shard006/C++/0074298_SpriteManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12d2ff9fe467338a23bdf0e114d3038603d7f1ad --- /dev/null +++ b/pool/shard006/C++/0074298_SpriteManager.cpp @@ -0,0 +1,27 @@ +#include "SpriteManager.h" + +void SpriteManager::addNamedSprite(const std::string spriteName, const std::string textureName, int numFrames, SDL_Rect startDimensions, int fps) +{ + SDL_assert(numFrames > 0); + Sprite s; + s.numFrames = numFrames; + s.fps = fps; + //TODO make this handle non-horizontal frames + for(int i = 0; i < numFrames; ++i) + { + SDL_Rect frame; + frame.x = i * startDimensions.w + startDimensions.x; + frame.y = startDimensions.y; + frame.w = startDimensions.w; + frame.h = startDimensions.h; + s.frames.push_back(frame); + } + s.texture = manager->getTextureForName(textureName); + + _spriteIndex.insert(std::pair(spriteName, s)); +} +Sprite *SpriteManager::getNamedSprite(const std::string spriteName) +{ + std::map::iterator finder = _spriteIndex.find(spriteName); + return &finder->second; +} diff --git a/pool/shard006/C++/0074303_nodebuiltinback.cpp b/pool/shard006/C++/0074303_nodebuiltinback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d23672a8d8fd1d8cad263852043a3cdcb7949e3d --- /dev/null +++ b/pool/shard006/C++/0074303_nodebuiltinback.cpp @@ -0,0 +1,78 @@ +/* + * Copyright 2009 Michal Turek + * + * This file is part of Graphal library. + * http://graphal.sourceforge.net/ + * + * Graphal 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, version 3 of the License. + * + * Graphal 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 Graphal library. If not, see . + */ + + +/**************************************************************************** + * * + * This file was generated by gen_builtin.pl script. * + * Don't update it manually! * + * * + ****************************************************************************/ + + +#include +#include "generated/nodebuiltinback.h" +#include "valuenull.h" +#include "context.h" +#include "logger.h" +#include "valuearray.h" + + +///////////////////////////////////////////////////////////////////////////// +//// + +NodeBuiltinBack::NodeBuiltinBack(identifier name, list* parameters) + : NodeFunctionBuiltin(name, parameters) +{ + +} + +NodeBuiltinBack::~NodeBuiltinBack(void) +{ + +} + + +///////////////////////////////////////////////////////////////////////////// +//// + + +CountPtr NodeBuiltinBack::execute(void) +{ + vector< CountPtr > par = getParametersValues(); + assert(par.size() == 1); + + ValueArray* a = NULL; + + if((a = par[0]->toValueArray()) != NULL) + return a->back(); + else + { + WARN_P(_("Bad parameters type: back(array) : object|null")); + return VALUENULL; + } + +} + +ostream& operator<<(ostream& os, const NodeBuiltinBack& node) +{ + node.dump(os, 0); + return os; +} + diff --git a/pool/shard006/C++/0074309_Application.cpp b/pool/shard006/C++/0074309_Application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30afb20235dbf1e691a59072b201a3e96c023a01 --- /dev/null +++ b/pool/shard006/C++/0074309_Application.cpp @@ -0,0 +1,56 @@ + + +#include "Application.h" + +#include "platform/Device.h" + + +Application::Application ( const char* name ) + : _name( name ) + , _run ( true ) +{ + // empty +} + + +Application::~Application ( void ) +{ + // empty +} + + +void Application::Run ( void ) +{ + float delta = 0.016f; + + while ( _run ) { + + this->OnUpdate(delta); + + Device::Sleep( delta ); + } +} + + +void Application::Close ( void ) +{ + _run = false; +} + + +const char* Application::GetName ( void ) const +{ + return _name.c_str(); +} + + + + + +void Application::Load ( HSystem sys ) +{ + _systems.push_back( sys ); +} + + + diff --git a/pool/shard006/C++/0074314_wifidupefilter.cc b/pool/shard006/C++/0074314_wifidupefilter.cc new file mode 100644 index 0000000000000000000000000000000000000000..59796918dc1aa22facd761614edbd7563a6704b7 --- /dev/null +++ b/pool/shard006/C++/0074314_wifidupefilter.cc @@ -0,0 +1,172 @@ +/* + * wifidupefilter.{cc,hh} -- Filters out duplicate packets based on + * 802.11 sequence numbers. + * John Bicket + * + * Copyright (c) 1999-2000 Massachusetts Institute of Technology + * + * 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, subject to the conditions + * listed in the Click LICENSE file. These conditions include: you must + * preserve this copyright notice, and you cannot mention the copyright + * holders in advertising related to the Software without their permission. + * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This + * notice is a summary of the Click LICENSE file; the license in that file is + * legally binding. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wifidupefilter.hh" + +CLICK_DECLS + +WifiDupeFilter::WifiDupeFilter() + : _debug(false), + _dupes(0) +{ +} + +WifiDupeFilter::~WifiDupeFilter() +{ +} + +int +WifiDupeFilter::configure(Vector &conf, ErrorHandler* errh) +{ + int ret; + ret = cp_va_kparse(conf, this, errh, + "DEBUG", 0, cpBool, &_debug, + cpEnd); + return ret; +} + +Packet * +WifiDupeFilter::simple_action(Packet *p_in) +{ + click_wifi *w = (click_wifi *) p_in->data(); + + if (p_in->length() < sizeof(click_wifi)) { + return p_in; + } + + EtherAddress src = EtherAddress(w->i_addr2); + EtherAddress dst = EtherAddress(w->i_addr1); + uint16_t seq = le16_to_cpu(*(uint16_t *) w->i_seq) >> WIFI_SEQ_SEQ_SHIFT; + uint8_t frag = le16_to_cpu(*(u_int16_t *)w->i_seq) & WIFI_SEQ_FRAG_MASK; + u_int8_t more_frag = w->i_fc[1] & WIFI_FC1_MORE_FRAG; + + bool is_frag = frag || more_frag; + + DstInfo *nfo = _table.findp(src); + + if (w->i_fc[0] & WIFI_FC0_TYPE_CTL || dst.is_group()) { + return p_in; + } + if (!nfo) { + _table.insert(src, DstInfo(src)); + nfo = _table.findp(src); + nfo->clear(); + } + + if (w->i_fc[1] & WIFI_FC1_RETRY && seq == nfo->seq && + (!is_frag || frag <= nfo->frag)) { + /* duplicate detected */ + if (_debug) { + click_chatter("%{element}: dup seq %d frag %d src %s\n", + this, + seq, + frag, + src.unparse().c_str()); + } + nfo->_dupes++; + _dupes++; + p_in->kill(); + return 0; + } + + nfo->seq = seq; + nfo->frag = frag; + return p_in; +} + + +String +WifiDupeFilter::static_read_stats(Element *xf, void *) +{ + WifiDupeFilter *e = (WifiDupeFilter *) xf; + StringAccum sa; + + for(DstTable::const_iterator i = e->_table.begin(); i.live(); i++) { + DstInfo nfo = i.value(); + sa << nfo._eth; + sa << " packets " << nfo._packets; + sa << " dupes " << nfo._dupes; + sa << " seq " << nfo.seq; + sa << " frag " << nfo.frag; + sa << "\n"; + + } + return sa.take_string(); +} + +enum {H_DEBUG, H_DUPES, H_RESET}; + +static String +WifiDupeFilter_read_param(Element *e, void *thunk) +{ + WifiDupeFilter *td = (WifiDupeFilter *)e; + switch ((uintptr_t) thunk) { + case H_DEBUG: + return String(td->_debug) + "\n"; + case H_DUPES: + return String(td->_dupes) + "\n"; + default: + return String(); + } +} +static int +WifiDupeFilter_write_param(const String &in_s, Element *e, void *vparam, + ErrorHandler *errh) +{ + WifiDupeFilter *f = (WifiDupeFilter *)e; + String s = cp_uncomment(in_s); + switch((intptr_t)vparam) { + case H_DEBUG: { //debug + bool debug; + if (!cp_bool(s, &debug)) + return errh->error("debug parameter must be boolean"); + f->_debug = debug; + break; + } + case H_RESET: { + f->_table.clear(); + f->_dupes = 0; + } + } + return 0; +} +void +WifiDupeFilter::add_handlers() +{ + add_read_handler("debug", WifiDupeFilter_read_param, (void *) H_DEBUG); + add_read_handler("dupes", WifiDupeFilter_read_param, (void *) H_DUPES); + add_read_handler("drops", WifiDupeFilter_read_param, (void *) H_DUPES); + + add_write_handler("debug", WifiDupeFilter_write_param, (void *) H_DEBUG); + add_write_handler("reset", WifiDupeFilter_write_param, (void *) H_RESET, Handler::BUTTON); + + add_read_handler("stats", static_read_stats, 0); +} + +EXPORT_ELEMENT(WifiDupeFilter) +CLICK_ENDDECLS + diff --git a/pool/shard006/C++/0074326_binary_classifier_predictor.cc b/pool/shard006/C++/0074326_binary_classifier_predictor.cc new file mode 100644 index 0000000000000000000000000000000000000000..54e1eb9889f8b3fee2785ea36e28b3f68821c09c --- /dev/null +++ b/pool/shard006/C++/0074326_binary_classifier_predictor.cc @@ -0,0 +1,120 @@ +// Copyright 2017 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 "components/assist_ranker/binary_classifier_predictor.h" + +#include + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/files/file_path.h" +#include "components/assist_ranker/generic_logistic_regression_inference.h" +#include "components/assist_ranker/proto/ranker_model.pb.h" +#include "components/assist_ranker/ranker_model.h" +#include "components/assist_ranker/ranker_model_loader_impl.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace assist_ranker { + +BinaryClassifierPredictor::BinaryClassifierPredictor( + const PredictorConfig& config) + : BasePredictor(config) {} +BinaryClassifierPredictor::~BinaryClassifierPredictor() {} + +// static +std::unique_ptr BinaryClassifierPredictor::Create( + const PredictorConfig& config, + const base::FilePath& model_path, + scoped_refptr url_loader_factory) { + std::unique_ptr predictor( + new BinaryClassifierPredictor(config)); + if (!predictor->is_query_enabled()) { + DVLOG(1) << "Query disabled, bypassing model loading."; + return predictor; + } + const GURL& model_url = predictor->GetModelUrl(); + DVLOG(1) << "Creating predictor instance for " << predictor->GetModelName(); + DVLOG(1) << "Model URL: " << model_url; + DVLOG(1) << "Using predict threshold replacement: " + << predictor->GetPredictThresholdReplacement(); + auto model_loader = std::make_unique( + base::BindRepeating(&BinaryClassifierPredictor::ValidateModel), + base::BindRepeating(&BinaryClassifierPredictor::OnModelAvailable, + base::Unretained(predictor.get())), + url_loader_factory, model_path, model_url, config.uma_prefix); + predictor->LoadModel(std::move(model_loader)); + return predictor; +} + +bool BinaryClassifierPredictor::Predict(const RankerExample& example, + bool* prediction) { + if (!IsReady()) { + DVLOG(1) << "Predictor " << GetModelName() << " not ready for prediction."; + return false; + } + + float predict_threshold_replacement = GetPredictThresholdReplacement(); + if (predict_threshold_replacement != kNoPredictThresholdReplacement) { + *prediction = inference_module_->PredictScore(PreprocessExample(example)) >= + predict_threshold_replacement; + } else { + *prediction = inference_module_->Predict(PreprocessExample(example)); + } + DVLOG(1) << "Predictor " << GetModelName() << " predicted: " << *prediction; + return true; +} + +bool BinaryClassifierPredictor::PredictScore(const RankerExample& example, + float* prediction) { + if (!IsReady()) { + DVLOG(1) << "Predictor " << GetModelName() << " not ready for prediction."; + return false; + } + *prediction = inference_module_->PredictScore(PreprocessExample(example)); + DVLOG(1) << "Predictor " << GetModelName() << " predicted: " << prediction; + return true; +} + +// static +RankerModelStatus BinaryClassifierPredictor::ValidateModel( + const RankerModel& model) { + if (model.proto().model_case() != RankerModelProto::kLogisticRegression) { + DVLOG(0) << "Model is incompatible."; + return RankerModelStatus::INCOMPATIBLE; + } + const GenericLogisticRegressionModel& glr = + model.proto().logistic_regression(); + if (glr.is_preprocessed_model()) { + if (glr.fullname_weights().empty() || !glr.weights().empty()) { + DVLOG(0) << "Model is incompatible. Preprocessed model should use " + "fullname_weights."; + return RankerModelStatus::INCOMPATIBLE; + } + if (!glr.preprocessor_config().feature_indices().empty()) { + DVLOG(0) << "Preprocessed model doesn't need feature indices."; + return RankerModelStatus::INCOMPATIBLE; + } + } else { + if (!glr.fullname_weights().empty() || glr.weights().empty()) { + DVLOG(0) << "Model is incompatible. Non-preprocessed model should use " + "weights."; + return RankerModelStatus::INCOMPATIBLE; + } + } + return RankerModelStatus::OK; +} + +bool BinaryClassifierPredictor::Initialize() { + if (ranker_model_->proto().model_case() == + RankerModelProto::kLogisticRegression) { + inference_module_ = std::make_unique( + ranker_model_->proto().logistic_regression()); + return true; + } + + DVLOG(0) << "Could not initialize inference module."; + return false; +} + +} // namespace assist_ranker diff --git a/pool/shard006/C++/0074329_double.cpp b/pool/shard006/C++/0074329_double.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d059755843112be79d6e014672f05e0e31feb806 --- /dev/null +++ b/pool/shard006/C++/0074329_double.cpp @@ -0,0 +1,101 @@ +/* + * This file is part of the PulseView project. + * + * Copyright (C) 2013 Joel Holdsworth + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include + +#include "double.hpp" + +using boost::optional; +using std::pair; + +namespace pv { +namespace prop { + +Double::Double(QString name, + int decimals, + QString suffix, + optional< pair > range, + optional step, + Getter getter, + Setter setter) : + Property(name, getter, setter), + decimals_(decimals), + suffix_(suffix), + range_(range), + step_(step), + spin_box_(NULL) +{ +} + +Double::~Double() +{ +} + +QWidget* Double::get_widget(QWidget *parent, bool auto_commit) +{ + if (spin_box_) + return spin_box_; + + if (!getter_) + return NULL; + + Glib::VariantBase variant = getter_(); + if (!variant.gobj()) + return NULL; + + double value = Glib::VariantBase::cast_dynamic>( + variant).get(); + + spin_box_ = new QDoubleSpinBox(parent); + spin_box_->setDecimals(decimals_); + spin_box_->setSuffix(suffix_); + if (range_) + spin_box_->setRange(range_->first, range_->second); + if (step_) + spin_box_->setSingleStep(*step_); + + spin_box_->setValue(value); + + if (auto_commit) + connect(spin_box_, SIGNAL(valueChanged(double)), + this, SLOT(on_value_changed(double))); + + return spin_box_; +} + +void Double::commit() +{ + assert(setter_); + + if (!spin_box_) + return; + + setter_(Glib::Variant::create(spin_box_->value())); +} + +void Double::on_value_changed(double) +{ + commit(); +} + +} // prop +} // pv diff --git a/pool/shard006/C++/0074333_DynamicProgrammingLowMemoryParallelSolverTest.cpp b/pool/shard006/C++/0074333_DynamicProgrammingLowMemoryParallelSolverTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a33864a9db5e52de0be80506d68a3c974a199de --- /dev/null +++ b/pool/shard006/C++/0074333_DynamicProgrammingLowMemoryParallelSolverTest.cpp @@ -0,0 +1,45 @@ +#include "main/algorithms/DynamicProgrammingLowMemoryParallelSolver.h" +#include "util/TestUtils.h" +#include "test/TestData.h" + +/** + * Tests whether the parallel dynamic programming low memory algorithm for solving the knapsack problem works correctly. + * Returns 0 if test succeeds. + * Returns -1 if actual output missmatches assumed output. + */ +int testDPLMPSolver(const char* inputFile, const char* outputFile, const std::string* assumedContent, int assumedContentLength) { + KnapSackSolver* solver = new DynamicProgrammingLowMemoryParallelSolver(inputFile, outputFile); + + solver->start(); + + delete solver; + + return TestUtils::checkOutput(assumedContent, assumedContentLength, outputFile); +} + +/** + * Tests whether the parallel dynamic programming low memory algorithm for solving the knapsack problem works correctly. + * Returns 0 if test succeeds. + * Returns 1 if actual output of KNAPSACK_INPUT_FILE_FIRST_EXAMPLE missmatches assumed output. + * Returns 2 if actual output of KNAPSACK_INPUT_FILE_THIRD_EXAMPLE missmatches assumed output. + * Returns 3 if actual output of KNAPSACK_INPUT_FILE_DP_EXAMPLE missmatches assumed output. + */ +int main(int argc, char* argv[]){ + int returnCode = testDPLMPSolver(KNAPSACK_INPUT_FILE_FIRST_EXAMPLE, TEST_OUTPUT_FILE, + ASSUMED_CONTENT_FILE_1, ASSUMED_CONTENT_LINES_FILE_1); + if (0 != returnCode) + return 1; + + returnCode = testDPLMPSolver(KNAPSACK_INPUT_FILE_THIRD_EXAMPLE, TEST_OUTPUT_FILE, + ASSUMED_CONTENT_FILE_3, ASSUMED_CONTENT_LINES_FILE_3); + if (0 != returnCode) + return 2; + + returnCode = testDPLMPSolver(KNAPSACK_INPUT_FILE_DP_EXAMPLE, TEST_OUTPUT_FILE, + ASSUMED_CONTENT_FILE_DP_DIFFERENT_ORDER, ASSUMED_CONTENT_LINES_FILE_DP); + + if (0 != returnCode) + return 3; + + return returnCode; +} diff --git a/pool/shard006/C++/0074334_mainwindow.cpp b/pool/shard006/C++/0074334_mainwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93cc2b77f256549ea0d3dd5e53389913b71b1621 --- /dev/null +++ b/pool/shard006/C++/0074334_mainwindow.cpp @@ -0,0 +1,31 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" + +#include "bibtableview.h" +#include "bibitemeditwidget.h" +#include "BibStorage/bibfile.h" + + +MainWindow::MainWindow(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::MainWindow) +{ + ui->setupUi(this); + + BibItemModel *model = new BibItemModel(); + model->loadItems(BibFile("proxiVision.bib")); + + BibTableView *t = this->findChild("tableView"); + t->setModel(model); + + BibItemEditWidget *w = this->findChild("editWidget"); + w->setModel(model); + + + connect(t, SIGNAL(clicked(QModelIndex)), w, SLOT(selectionChanged(QModelIndex))); +} + +MainWindow::~MainWindow() +{ + delete ui; +} diff --git a/pool/shard006/C++/0074342_child_process_sandbox_support_impl_linux.cc b/pool/shard006/C++/0074342_child_process_sandbox_support_impl_linux.cc new file mode 100644 index 0000000000000000000000000000000000000000..9040cd055c904b2a180fab4e2521df89f29b691b --- /dev/null +++ b/pool/shard006/C++/0074342_child_process_sandbox_support_impl_linux.cc @@ -0,0 +1,176 @@ +// Copyright (c) 2011 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 "content/common/child_process_sandbox_support_impl_linux.h" + +#include + +#include "base/eintr_wrapper.h" +#include "base/memory/scoped_ptr.h" +#include "base/pickle.h" +#include "content/common/sandbox_methods_linux.h" +#include "content/common/unix_domain_socket_posix.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/linux/WebFontFamily.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/linux/WebFontRenderStyle.h" + +namespace content { + +void GetFontFamilyForCharacters(const uint16_t* utf16, + size_t num_utf16, + const char* preferred_locale, + WebKit::WebFontFamily* family) { + Pickle request; + request.WriteInt(LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHARS); + request.WriteInt(num_utf16); + for (size_t i = 0; i < num_utf16; ++i) + request.WriteUInt32(utf16[i]); + request.WriteString(preferred_locale); + + uint8_t buf[512]; + const ssize_t n = UnixDomainSocket::SendRecvMsg(GetSandboxFD(), buf, + sizeof(buf), NULL, request); + + std::string family_name; + bool isBold = false; + bool isItalic = false; + if (n != -1) { + Pickle reply(reinterpret_cast(buf), n); + void* pickle_iter = NULL; + if (reply.ReadString(&pickle_iter, &family_name) && + reply.ReadBool(&pickle_iter, &isBold) && + reply.ReadBool(&pickle_iter, &isItalic)) { + family->name = family_name; + family->isBold = isBold; + family->isItalic = isItalic; + } + } +} + +void GetRenderStyleForStrike(const char* family, int sizeAndStyle, + WebKit::WebFontRenderStyle* out) { + Pickle request; + request.WriteInt(LinuxSandbox::METHOD_GET_STYLE_FOR_STRIKE); + request.WriteString(family); + request.WriteInt(sizeAndStyle); + + uint8_t buf[512]; + const ssize_t n = UnixDomainSocket::SendRecvMsg(GetSandboxFD(), buf, + sizeof(buf), NULL, request); + + out->setDefaults(); + if (n == -1) { + return; + } + + Pickle reply(reinterpret_cast(buf), n); + void* pickle_iter = NULL; + int useBitmaps, useAutoHint, useHinting, hintStyle, useAntiAlias, useSubpixel; + if (reply.ReadInt(&pickle_iter, &useBitmaps) && + reply.ReadInt(&pickle_iter, &useAutoHint) && + reply.ReadInt(&pickle_iter, &useHinting) && + reply.ReadInt(&pickle_iter, &hintStyle) && + reply.ReadInt(&pickle_iter, &useAntiAlias) && + reply.ReadInt(&pickle_iter, &useSubpixel)) { + out->useBitmaps = useBitmaps; + out->useAutoHint = useAutoHint; + out->useHinting = useHinting; + out->hintStyle = hintStyle; + out->useAntiAlias = useAntiAlias; + out->useSubpixel = useSubpixel; + } +} + +int MatchFontWithFallback(const std::string& face, bool bold, + bool italic, int charset) { + Pickle request; + request.WriteInt(LinuxSandbox::METHOD_MATCH_WITH_FALLBACK); + request.WriteString(face); + request.WriteBool(bold); + request.WriteBool(italic); + request.WriteUInt32(charset); + uint8_t reply_buf[64]; + int fd = -1; + UnixDomainSocket::SendRecvMsg(GetSandboxFD(), reply_buf, sizeof(reply_buf), + &fd, request); + return fd; +} + +bool GetFontTable(int fd, uint32_t table, uint8_t* output, + size_t* output_length) { + if (table == 0) { + struct stat st; + if (fstat(fd, &st) < 0) + return false; + size_t length = st.st_size; + if (!output) { + *output_length = length; + return true; + } + if (*output_length < length) + return false; + *output_length = length; + ssize_t n = HANDLE_EINTR(pread(fd, output, length, 0)); + if (n != static_cast(length)) + return false; + return true; + } + + unsigned num_tables; + uint8_t num_tables_buf[2]; + + ssize_t n = HANDLE_EINTR(pread(fd, &num_tables_buf, sizeof(num_tables_buf), + 4 /* skip the font type */)); + if (n != sizeof(num_tables_buf)) + return false; + + num_tables = static_cast(num_tables_buf[0]) << 8 | + num_tables_buf[1]; + + // The size in bytes of an entry in the table directory. + static const unsigned kTableEntrySize = 16; + scoped_array table_entries( + new uint8_t[num_tables * kTableEntrySize]); + n = HANDLE_EINTR(pread(fd, table_entries.get(), num_tables * kTableEntrySize, + 12 /* skip the SFNT header */)); + if (n != static_cast(num_tables * kTableEntrySize)) + return false; + + size_t offset; + size_t length = 0; + for (unsigned i = 0; i < num_tables; i++) { + const uint8_t* entry = table_entries.get() + i * kTableEntrySize; + if (memcmp(entry, &table, sizeof(table)) == 0) { + offset = static_cast(entry[8]) << 24 | + static_cast(entry[9]) << 16 | + static_cast(entry[10]) << 8 | + static_cast(entry[11]); + length = static_cast(entry[12]) << 24 | + static_cast(entry[13]) << 16 | + static_cast(entry[14]) << 8 | + static_cast(entry[15]); + + break; + } + } + + if (!length) + return false; + + if (!output) { + *output_length = length; + return true; + } + + if (*output_length < length) + return false; + + *output_length = length; + n = HANDLE_EINTR(pread(fd, output, length, offset)); + if (n != static_cast(length)) + return false; + + return true; +} + +} // namespace content diff --git a/pool/shard006/C++/0074343_mcollUtil.cpp b/pool/shard006/C++/0074343_mcollUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebee6f8240668a906766637dc9e1fe5ee4f1f6f1 --- /dev/null +++ b/pool/shard006/C++/0074343_mcollUtil.cpp @@ -0,0 +1,163 @@ +/*** Copyright (c), The Regents of the University of California *** + *** For more information please refer to files in the COPYRIGHT directory ***/ +#include "rodsPath.h" +#include "rodsErrorTable.h" +#include "rodsLog.h" +#include "mcollUtil.h" +#include "miscUtil.h" +#include "rcGlobalExtern.h" + +/* redefine of some input option */ +#define syncCacheDir sizeFlag +#define purgeCacheDir physicalPath +int +mcollUtil( rcComm_t *conn, rodsEnv *myRodsEnv, rodsArguments_t *myRodsArgs, + rodsPathInp_t *rodsPathInp ) { + rodsPath_t *destPath, *srcPath; + dataObjInp_t dataObjOprInp; + + if ( rodsPathInp == NULL ) { + return USER__NULL_INPUT_ERR; + } + + int savedStatus = initCondForMcoll( myRodsEnv, myRodsArgs, &dataObjOprInp ); + if ( savedStatus < 0 ) { + return savedStatus; + } + + for ( int i = 0; i < rodsPathInp->numSrc; i++ ) { + int status; + if ( myRodsArgs->mountCollection == True ) { + destPath = &rodsPathInp->destPath[i]; /* iRODS path */ + srcPath = &rodsPathInp->srcPath[i]; /* file Path */ + + getRodsObjType( conn, destPath ); + + addKeyVal( &dataObjOprInp.condInput, FILE_PATH_KW, + srcPath->outPath ); + rstrcpy( dataObjOprInp.objPath, destPath->outPath, MAX_NAME_LEN ); + status = rcPhyPathReg( conn, &dataObjOprInp ); + } + else if ( myRodsArgs->unmount == True ) { /* unmount */ + srcPath = &rodsPathInp->srcPath[i]; /* file Path */ + + getRodsObjType( conn, srcPath ); + + rstrcpy( dataObjOprInp.objPath, srcPath->outPath, MAX_NAME_LEN ); + status = rcPhyPathReg( conn, &dataObjOprInp ); + } + else if ( myRodsArgs->syncCacheDir == True || + myRodsArgs->purgeCacheDir == True ) { /* sync or purge */ + srcPath = &rodsPathInp->srcPath[i]; /* file Path */ + + getRodsObjType( conn, srcPath ); + + rstrcpy( dataObjOprInp.objPath, srcPath->outPath, MAX_NAME_LEN ); + status = rcSyncMountedColl( conn, &dataObjOprInp ); + } + else { + status = USER_INPUT_OPTION_ERR; + } + + /* XXXX may need to return a global status */ + if ( status < 0 && + status != CAT_NO_ROWS_FOUND ) { + rodsLogError( LOG_ERROR, status, + "imcoll error" ); + savedStatus = status; + } + } + return savedStatus; +} + +int +initCondForMcoll( rodsEnv *myRodsEnv, rodsArguments_t *rodsArgs, + dataObjInp_t *dataObjOprInp ) { + if ( dataObjOprInp == NULL ) { + rodsLog( LOG_ERROR, + "initCondForReg: NULL dataObjOprInp input" ); + return USER__NULL_INPUT_ERR; + } + + memset( dataObjOprInp, 0, sizeof( dataObjInp_t ) ); + + if ( rodsArgs == NULL ) { + return USER_INPUT_OPTION_ERR; + } + + if ( rodsArgs->collection == True ) { + addKeyVal( &dataObjOprInp->condInput, COLLECTION_KW, "" ); + } + + if ( rodsArgs->purgeCacheDir == True ) { + dataObjOprInp->oprType = + dataObjOprInp->oprType | PURGE_STRUCT_FILE_CACHE; + } + + if ( rodsArgs->unmount == True ) { + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, UNMOUNT_STR ); + } + else if ( rodsArgs->mountCollection == True ) { + char *mountType = rodsArgs->mountType; + if ( strcmp( mountType, "h" ) == 0 || + strcmp( mountType, "haaw" ) == 0 ) { + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, HAAW_STRUCT_FILE_STR ); + } + else if ( strcmp( mountType, "m" ) == 0 || + strcmp( mountType, "msso" ) == 0 ) { + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, MSSO_STRUCT_FILE_STR ); + /* XXXXX need to add "msso structFile" token */ + addKeyVal( &dataObjOprInp->condInput, DATA_TYPE_KW, MSSO_DT_STR ); + } + else if ( strcmp( mountType, "t" ) == 0 || + strcmp( mountType, "tar" ) == 0 ) { + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, TAR_STRUCT_FILE_STR ); + /* XXXXX need to add "tar structFile" token */ + addKeyVal( &dataObjOprInp->condInput, DATA_TYPE_KW, TAR_DT_STR ); + } + else if ( strcmp( mountType, "f" ) == 0 || + strcmp( mountType, "filesystem" ) == 0 ) { + /* the collection is a filesystem mount point */ + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, MOUNT_POINT_STR ); + } + else if ( strcmp( mountType, "l" ) == 0 || + strcmp( mountType, "link" ) == 0 ) { + /* the collection is a softlink point */ + addKeyVal( &dataObjOprInp->condInput, + COLLECTION_TYPE_KW, LINK_POINT_STR ); + } + } + else if ( rodsArgs->purgeCacheDir == True ) { + dataObjOprInp->oprType = + dataObjOprInp->oprType | PURGE_STRUCT_FILE_CACHE; + } + else if ( rodsArgs->syncCacheDir != True ) { + /* should not be here */ + rodsLog( LOG_ERROR, "initCondForMcoll: -U or -m must be used. " ); + return USER_INPUT_OPTION_ERR; + } + + if ( rodsArgs->resource == True ) { + if ( rodsArgs->resourceString == NULL ) { + rodsLog( LOG_ERROR, + "initCondForReg: NULL resourceString error" ); + return USER__NULL_INPUT_ERR; + } + else { + addKeyVal( &dataObjOprInp->condInput, DEST_RESC_NAME_KW, + rodsArgs->resourceString ); + } + } + else if ( myRodsEnv != NULL && strlen( myRodsEnv->rodsDefResource ) > 0 ) { + addKeyVal( &dataObjOprInp->condInput, DEST_RESC_NAME_KW, + myRodsEnv->rodsDefResource ); + } + + return 0; +} + diff --git a/pool/shard006/C++/0074346_Position.cpp b/pool/shard006/C++/0074346_Position.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3387452e68fd3e4d7cdee592f58e2151bcab21e6 --- /dev/null +++ b/pool/shard006/C++/0074346_Position.cpp @@ -0,0 +1,94 @@ +// Copyright 2015 Urs Fässler, www.bitzgi.ch +// SPDX-License-Identifier: GPL-3.0+ + +#include "Position.hpp" + +Point ZeroPosition::getAbsolutePosition() const +{ + return Point(0,0); +} + +ZeroPosition *ZeroPosition::singleton() +{ + static ZeroPosition zero; + return &zero; +} + + +RelativePosition::RelativePosition(const Point &aOffset) : + anchor(ZeroPosition::singleton()), + offset(aOffset) +{ + anchor->registerObserver(this); +} + +RelativePosition::~RelativePosition() +{ + anchor->unregisterObserver(this); +} + +void RelativePosition::removeAnchor() +{ + replaceAnchor(ZeroPosition::singleton()); +} + +void RelativePosition::replaceAnchor(IPosition *newAnchor) +{ + precondition(newAnchor != nullptr); + + Point oldPos = getAbsolutePosition(); + + anchor->unregisterObserver(this); + anchor = newAnchor; + anchor->registerObserver(this); + + if (oldPos != getAbsolutePosition()) { + ObserverCollection::notify(&PositionObserver::absolutePositionChanged, static_cast(this)); + } +} + +IPosition *RelativePosition::getAnchor() const +{ + return anchor; +} + +bool RelativePosition::hasAnchor() const +{ + return anchor != ZeroPosition::singleton(); +} + +const Point &RelativePosition::getOffset() const +{ + return offset; +} + +void RelativePosition::setOffset(const Point &value) +{ + if (offset != value) { + offset = value; + ObserverCollection::notify(&PositionObserver::offsetChanged, static_cast(this)); + ObserverCollection::notify(&PositionObserver::absolutePositionChanged, static_cast(this)); + } +} + +Point RelativePosition::getAbsolutePosition() const +{ + return offset + anchor->getAbsolutePosition(); +} + +void RelativePosition::setAbsolutePosition(const Point &value) +{ + setOffset(value - anchor->getAbsolutePosition()); +} + +void RelativePosition::absolutePositionChanged(const RelativePosition *sender) +{ + if (sender == anchor) { + ObserverCollection::notify(&PositionObserver::absolutePositionChanged, static_cast(this)); + } +} + +void RelativePosition::offsetChanged(const RelativePosition *) +{ +} + diff --git a/pool/shard006/C++/0074348_pop.cc b/pool/shard006/C++/0074348_pop.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7527d9321e0c7e97b47027bf496dd1da1e39bd3 --- /dev/null +++ b/pool/shard006/C++/0074348_pop.cc @@ -0,0 +1,108 @@ +// Copyright (C) 2016-2017 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// { dg-options "-lstdc++fs" } +// { dg-do run { target c++11 } } +// { dg-require-filesystem-ts "" } + +#include +#include +#include + +namespace fs = std::experimental::filesystem; + +void +test01() +{ + std::error_code ec; + fs::recursive_directory_iterator dir; + dir.pop(ec); // This is undefined, but our implementation + VERIFY( ec ); // checks and returns an error. + VERIFY( dir == end(dir) ); + + std::error_code ec2; + try + { + dir.pop(); + } + catch (const fs::filesystem_error& ex) + { + ec2 = ex.code(); + } + VERIFY( ec2 == ec ); +} + +void +test02() +{ + std::error_code ec = make_error_code(std::errc::interrupted); + const auto p = __gnu_test::nonexistent_path(); + create_directories(p / "d1/d2/d3"); + for (int i = 0; i < 3; ++i) + { + fs::recursive_directory_iterator dir(p); + std::advance(dir, i); + VERIFY( dir.depth() == i ); + dir.pop(ec); + VERIFY( !ec ); + VERIFY( dir == end(dir) ); + + dir = fs::recursive_directory_iterator(p); + std::advance(dir, i); + VERIFY( dir.depth() == i ); + dir.pop(); + VERIFY( dir == end(dir) ); + } + remove_all(p, ec); +} + +void +test03() +{ + std::error_code ec = make_error_code(std::errc::interrupted); + const auto p = __gnu_test::nonexistent_path(); + create_directories(p / "d1/d2/d3"); + create_directories(p / "d1/d2/e3"); + create_directories(p / "d1/e2/d3"); + for (int i = 0; i < 3; ++i) + { + fs::recursive_directory_iterator dir(p); + std::advance(dir, i); + int expected_depth = i; + VERIFY( dir.depth() == expected_depth ); + dir.pop(ec); + VERIFY( !ec ); + if (dir != end(dir)) + VERIFY( dir.depth() == (expected_depth - 1) ); + + dir = fs::recursive_directory_iterator(p); + std::advance(dir, i); + VERIFY( dir.depth() == i ); + dir.pop(); + if (dir != end(dir)) + VERIFY( dir.depth() == (i -1) ); + } + remove_all(p, ec); +} + +int +main() +{ + test01(); + test02(); + test03(); +} diff --git a/pool/shard006/C++/0074350_tstSessionHack.cpp b/pool/shard006/C++/0074350_tstSessionHack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0df40a9ab8c1263f358f9ccbb292fe0bae269f2 --- /dev/null +++ b/pool/shard006/C++/0074350_tstSessionHack.cpp @@ -0,0 +1,55 @@ +/* $Id: tstSessionHack.cpp $ */ +/** @file + * tstSessionHack + */ + +/* + * Copyright (C) 2006-2007 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + */ +#define _WIN32_WINNT 0x0500 +#include +#include +#include +#include +#include + +void main(int argc, char *argv[]) +{ + DWORD cbReturned; + DWORD status = NO_ERROR; + HANDLE gVBoxDriver; + + /* open VBox guest driver */ + gVBoxDriver = CreateFile(VBOXGUEST_DEVICE_NAME, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + if (gVBoxDriver == INVALID_HANDLE_VALUE) + { + printf("Could not open VBox Guest Additions driver! rc = %d\n", GetLastError()); + return; + } + + if (argc == 1) + printf("Installing session hack\n"); + else + printf("Removing session hack\n"); + + if (!DeviceIoControl (gVBoxDriver, (argc == 1) ? VBOXGUEST_IOCTL_ENABLE_VRDP_SESSION : VBOXGUEST_IOCTL_DISABLE_VRDP_SESSION, NULL, 0, NULL, 0, &cbReturned, NULL)) + { + printf("VBoxRestoreThread: DeviceIOControl(CtlMask) failed, SeamlessChangeThread exited\n"); + } + CloseHandle(gVBoxDriver); +} + diff --git a/pool/shard006/C++/0074357_qdesigner_dockwidget.cpp b/pool/shard006/C++/0074357_qdesigner_dockwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5df08e39681fe8cd22a78507b3dc0c9d5d00e605 --- /dev/null +++ b/pool/shard006/C++/0074357_qdesigner_dockwidget.cpp @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the Qt Designer of the Qt Toolkit. +** +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information +** to ensure GNU General Public Licensing requirements will be met: +** http://www.fsf.org/licensing/licenses/info/GPLv2.html and +** http://www.gnu.org/copyleft/gpl.html. In addition, as a special +** exception, Nokia gives you certain additional rights. These rights +** are described in the Nokia Qt GPL Exception version 1.3, included in +** the file GPL_EXCEPTION.txt in this package. +** +** Qt for Windows(R) Licensees +** As a special exception, Nokia, as the sole copyright holder for Qt +** Designer, grants users of the Qt/Eclipse Integration plug-in the +** right for the Qt/Eclipse Integration to link to functionality +** provided by Qt Designer and its related libraries. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** +****************************************************************************/ + +#include "qdesigner_dockwidget_p.h" +#include "layoutinfo_p.h" + +#include +#include +#include +#include +#include + +#include +#include + +QT_BEGIN_NAMESPACE + +QDesignerDockWidget::QDesignerDockWidget(QWidget *parent) + : QDockWidget(parent) +{ +} + +QDesignerDockWidget::~QDesignerDockWidget() +{ +} + +bool QDesignerDockWidget::docked() const +{ + return qobject_cast(parentWidget()) != 0; +} + +void QDesignerDockWidget::setDocked(bool b) +{ + if (QMainWindow *mainWindow = findMainWindow()) { + QDesignerFormEditorInterface *core = formWindow()->core(); + QDesignerContainerExtension *c; + c = qt_extension(core->extensionManager(), mainWindow); + if (b && !docked()) { + // Dock it + // ### undo/redo stack + setParent(0); + c->addWidget(this); + formWindow()->selectWidget(this, formWindow()->cursor()->isWidgetSelected(this)); + } else if (!b && docked()) { + // Undock it + for (int i = 0; i < c->count(); ++i) { + if (c->widget(i) == this) { + c->remove(i); + break; + } + } + // #### restore the position + setParent(mainWindow->centralWidget()); + show(); + formWindow()->selectWidget(this, formWindow()->cursor()->isWidgetSelected(this)); + } + } +} + +Qt::DockWidgetArea QDesignerDockWidget::dockWidgetArea() const +{ + if (QMainWindow *mainWindow = qobject_cast(parentWidget())) + return mainWindow->dockWidgetArea(const_cast(this)); + + return Qt::LeftDockWidgetArea; +} + +void QDesignerDockWidget::setDockWidgetArea(Qt::DockWidgetArea dockWidgetArea) +{ + if (QMainWindow *mainWindow = qobject_cast(parentWidget())) { + if ((dockWidgetArea != Qt::NoDockWidgetArea) + && isAreaAllowed(dockWidgetArea)) { + mainWindow->addDockWidget(dockWidgetArea, this); + } + } +} + +bool QDesignerDockWidget::inMainWindow() const +{ + QMainWindow *mw = findMainWindow(); + if (mw && !mw->centralWidget()->layout()) { + if (mw == parentWidget()) + return true; + if (mw->centralWidget() == parentWidget()) + return true; + } + return false; +} + +QDesignerFormWindowInterface *QDesignerDockWidget::formWindow() const +{ + return QDesignerFormWindowInterface::findFormWindow(const_cast(this)); +} + +QMainWindow *QDesignerDockWidget::findMainWindow() const +{ + if (QDesignerFormWindowInterface *fw = formWindow()) + return qobject_cast(fw->mainContainer()); + return 0; +} + +QT_END_NAMESPACE diff --git a/pool/shard006/C++/0074363_security_interstitial_tab_helper_unittest.cc b/pool/shard006/C++/0074363_security_interstitial_tab_helper_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..40b4a146597a3f0c3387c7761ee06e9eff88bc6d --- /dev/null +++ b/pool/shard006/C++/0074363_security_interstitial_tab_helper_unittest.cc @@ -0,0 +1,278 @@ +// Copyright 2017 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 "components/security_interstitials/content/security_interstitial_tab_helper.h" + +#include + +#include "base/bind.h" +#include "base/i18n/rtl.h" +#include "base/memory/raw_ptr.h" +#include "base/test/scoped_feature_list.h" +#include "base/time/time.h" +#include "components/security_interstitials/content/security_interstitial_controller_client.h" +#include "components/security_interstitials/content/security_interstitial_page.h" +#include "components/security_interstitials/content/settings_page_helper.h" +#include "components/security_interstitials/core/controller_client.h" +#include "components/security_interstitials/core/metrics_helper.h" +#include "content/public/browser/certificate_request_result_type.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/test/mock_navigation_handle.h" +#include "content/public/test/navigation_simulator.h" +#include "content/public/test/test_renderer_host.h" +#include "net/base/net_errors.h" +#include "net/test/cert_test_util.h" +#include "net/test/test_data_directory.h" +#include "third_party/blink/public/common/features.h" +#include "url/gurl.h" + +namespace security_interstitials { + +const char kTestSslMetricsName[] = "test_blocking_page"; + +std::unique_ptr CreateTestMetricsHelper( + content::WebContents* web_contents) { + MetricsHelper::ReportDetails report_details; + report_details.metric_prefix = kTestSslMetricsName; + return std::make_unique( + GURL(), report_details, nullptr); +} + +class TestInterstitialPage : public SecurityInterstitialPage { + public: + // |*destroyed_tracker| is set to true in the destructor. + TestInterstitialPage(content::WebContents* web_contents, + const GURL& request_url, + bool* destroyed_tracker) + : SecurityInterstitialPage( + web_contents, + request_url, + std::make_unique( + web_contents, + CreateTestMetricsHelper(web_contents), + nullptr, + base::i18n::GetConfiguredLocale(), + GURL(), + /* settings_page_helper*/ nullptr)), + destroyed_tracker_(destroyed_tracker) {} + + ~TestInterstitialPage() override { *destroyed_tracker_ = true; } + + void OnInterstitialClosing() override {} + + protected: + void PopulateInterstitialStrings(base::Value* load_time_data) override {} + + private: + raw_ptr destroyed_tracker_; +}; + +class SecurityInterstitialTabHelperTest + : public content::RenderViewHostTestHarness { + protected: + std::unique_ptr CreateHandle( + bool committed, + bool is_same_document) { + std::unique_ptr handle = + std::make_unique(GURL(), main_rfh()); + handle->set_has_committed(committed); + handle->set_is_same_document(is_same_document); + return handle; + } + + // The lifetime of the blocking page is managed by the + // SecurityInterstitialTabHelper for the test's web_contents. + // |destroyed_tracker| will be set to true when the corresponding blocking + // page is destroyed. + void CreateAssociatedBlockingPage(content::NavigationHandle* handle, + bool* destroyed_tracker) { + SecurityInterstitialTabHelper::AssociateBlockingPage( + handle, std::make_unique(web_contents(), GURL(), + destroyed_tracker)); + } +}; + +// Tests that the helper properly handles the lifetime of a single blocking +// page, interleaved with other navigations. +TEST_F(SecurityInterstitialTabHelperTest, SingleBlockingPage) { + std::unique_ptr blocking_page_handle = + CreateHandle(true, false); + bool blocking_page_destroyed = false; + CreateAssociatedBlockingPage(blocking_page_handle.get(), + &blocking_page_destroyed); + SecurityInterstitialTabHelper* helper = + SecurityInterstitialTabHelper::FromWebContents(web_contents()); + + // Test that a same-document navigation doesn't destroy the blocking page if + // its navigation hasn't committed yet. + std::unique_ptr same_document_handle = + CreateHandle(true, true); + helper->DidFinishNavigation(same_document_handle.get()); + EXPECT_FALSE(blocking_page_destroyed); + + // Test that a committed (non-same-document) navigation doesn't destroy the + // blocking page if its navigation hasn't committed yet. + std::unique_ptr committed_handle1 = + CreateHandle(true, false); + helper->DidFinishNavigation(committed_handle1.get()); + EXPECT_FALSE(blocking_page_destroyed); + + // Simulate comitting the interstitial. + helper->DidFinishNavigation(blocking_page_handle.get()); + EXPECT_FALSE(blocking_page_destroyed); + + // Test that a subsequent committed navigation releases the blocking page + // stored for the currently committed navigation. + std::unique_ptr committed_handle2 = + CreateHandle(true, false); + helper->DidFinishNavigation(committed_handle2.get()); + EXPECT_TRUE(blocking_page_destroyed); +} + +// Tests that the helper properly handles the lifetime of multiple blocking +// pages, committed in a different order than they are created. +TEST_F(SecurityInterstitialTabHelperTest, DISABLED_MultipleBlockingPages) { + // Simulate associating the first interstitial. + std::unique_ptr handle1 = + CreateHandle(true, false); + bool blocking_page1_destroyed = false; + CreateAssociatedBlockingPage(handle1.get(), &blocking_page1_destroyed); + + // We can directly retrieve the helper for testing once + // CreateAssociatedBlockingPage() was called. + SecurityInterstitialTabHelper* helper = + SecurityInterstitialTabHelper::FromWebContents(web_contents()); + + // Simulate commiting the first interstitial. + helper->DidFinishNavigation(handle1.get()); + EXPECT_FALSE(blocking_page1_destroyed); + + // Associate the second interstitial. + std::unique_ptr handle2 = + CreateHandle(true, false); + bool blocking_page2_destroyed = false; + CreateAssociatedBlockingPage(handle2.get(), &blocking_page2_destroyed); + EXPECT_FALSE(blocking_page1_destroyed); + EXPECT_FALSE(blocking_page2_destroyed); + + // Associate the third interstitial. + std::unique_ptr handle3 = + CreateHandle(true, false); + bool blocking_page3_destroyed = false; + CreateAssociatedBlockingPage(handle3.get(), &blocking_page3_destroyed); + EXPECT_FALSE(blocking_page1_destroyed); + EXPECT_FALSE(blocking_page2_destroyed); + EXPECT_FALSE(blocking_page3_destroyed); + + // Simulate commiting the third interstitial. + helper->DidFinishNavigation(handle3.get()); + EXPECT_TRUE(blocking_page1_destroyed); + EXPECT_FALSE(blocking_page2_destroyed); + EXPECT_FALSE(blocking_page3_destroyed); + + // Simulate commiting the second interstitial. + helper->DidFinishNavigation(handle2.get()); + EXPECT_TRUE(blocking_page1_destroyed); + EXPECT_FALSE(blocking_page2_destroyed); + EXPECT_TRUE(blocking_page3_destroyed); + + // Test that a subsequent committed navigation releases the last blocking + // page. + std::unique_ptr committed_handle4 = + CreateHandle(true, false); + helper->DidFinishNavigation(committed_handle4.get()); + EXPECT_TRUE(blocking_page2_destroyed); +} + +// Tests that the helper properly handles a navigation that finishes without +// committing. +TEST_F(SecurityInterstitialTabHelperTest, NavigationDoesNotCommit) { + std::unique_ptr committed_handle = + CreateHandle(true, false); + bool committed_blocking_page_destroyed = false; + CreateAssociatedBlockingPage(committed_handle.get(), + &committed_blocking_page_destroyed); + SecurityInterstitialTabHelper* helper = + SecurityInterstitialTabHelper::FromWebContents(web_contents()); + helper->DidFinishNavigation(committed_handle.get()); + EXPECT_FALSE(committed_blocking_page_destroyed); + + // Simulate a navigation that does not commit. + std::unique_ptr non_committed_handle = + CreateHandle(false, false); + bool non_committed_blocking_page_destroyed = false; + CreateAssociatedBlockingPage(non_committed_handle.get(), + &non_committed_blocking_page_destroyed); + helper->DidFinishNavigation(non_committed_handle.get()); + + // The blocking page for the non-committed navigation should have been cleaned + // up, but the one for the previous committed navigation should still be + // around. + EXPECT_TRUE(non_committed_blocking_page_destroyed); + EXPECT_FALSE(committed_blocking_page_destroyed); + + // When a navigation does commit, the previous one should be cleaned up. + std::unique_ptr next_committed_handle = + CreateHandle(true, false); + helper->DidFinishNavigation(next_committed_handle.get()); + EXPECT_TRUE(committed_blocking_page_destroyed); +} + +class SecurityInterstitialTabHelperFencedFrameTest + : public SecurityInterstitialTabHelperTest { + public: + SecurityInterstitialTabHelperFencedFrameTest() { + scoped_feature_list_.InitAndEnableFeatureWithParameters( + blink::features::kFencedFrames, {{"implementation_type", "mparch"}}); + } + ~SecurityInterstitialTabHelperFencedFrameTest() override = default; + + content::RenderFrameHost* CreateFencedFrame( + content::RenderFrameHost* parent) { + content::RenderFrameHost* fenced_frame = + content::RenderFrameHostTester::For(parent)->AppendFencedFrame(); + return fenced_frame; + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + +// Tests that a FencedFrame does not close the interstitial page. +TEST_F(SecurityInterstitialTabHelperFencedFrameTest, + FencedFrameDoesNotCloseInterstitialPage) { + std::unique_ptr blocking_page_handle = + CreateHandle(true, false); + bool blocking_page_destroyed = false; + CreateAssociatedBlockingPage(blocking_page_handle.get(), + &blocking_page_destroyed); + SecurityInterstitialTabHelper* helper = + SecurityInterstitialTabHelper::FromWebContents(web_contents()); + helper->DidFinishNavigation(blocking_page_handle.get()); + EXPECT_FALSE(blocking_page_destroyed); + EXPECT_TRUE(helper->IsDisplayingInterstitial()); + + // Navigate a fenced frame and the interstitial page should be kept visible on + // the fenced frame. + GURL fenced_frame_url = GURL("https://fencedframe.com"); + content::RenderFrameHostTester::For(main_rfh()) + ->InitializeRenderFrameIfNeeded(); + content::RenderFrameHost* fenced_frame_rfh = CreateFencedFrame(main_rfh()); + std::unique_ptr navigation_simulator = + content::NavigationSimulator::CreateForFencedFrame(fenced_frame_url, + fenced_frame_rfh); + navigation_simulator->Commit(); + EXPECT_TRUE(fenced_frame_rfh->IsFencedFrameRoot()); + EXPECT_FALSE(blocking_page_destroyed); + EXPECT_TRUE(helper->IsDisplayingInterstitial()); + + // When a navigation does commit, the fenced frame one should be cleaned up. + std::unique_ptr next_committed_handle = + CreateHandle(true, false); + helper->DidFinishNavigation(next_committed_handle.get()); + EXPECT_TRUE(blocking_page_destroyed); + EXPECT_FALSE(helper->IsDisplayingInterstitial()); +} + +} // namespace security_interstitials diff --git a/pool/shard006/C++/0074364_mysqlclient_wrapper.cpp b/pool/shard006/C++/0074364_mysqlclient_wrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..108c5eb97a5918218a4372e14166baabdc8b798d --- /dev/null +++ b/pool/shard006/C++/0074364_mysqlclient_wrapper.cpp @@ -0,0 +1,106 @@ +/* + Copyright (c) 2012, Oracle and/or its affiliates. All rights + reserved. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License, version 2.0, + as published by the Free Software Foundation. + + This program is also distributed with certain software (including + but not limited to OpenSSL) that is licensed under separate terms, + as designated in a particular file or component or in included license + documentation. The authors of MySQL hereby grant you an additional + permission to link the program and your derivative works with the + separately licensed software that they have included with MySQL. + + 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, version 2.0, 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 + */ + +#include + +#include "adapter_global.h" +#include "v8_binder.h" +#include "js_wrapper_macros.h" +#include "NativeCFunctionCall.h" + +using namespace v8; + +Handle mysql_init_wrapper(const Arguments &args) { + HandleScope scope; + + REQUIRE_ARGS_LENGTH(0); // there is one arg but we supply it here + + NativeCFunctionCall_1_ ncall(& mysql_init, args); + ncall.arg0 = 0; + ncall.run(); + + return scope.Close(ncall.jsReturnVal()); +} + + +Handle mysql_close_wrapper(const Arguments &args) { + HandleScope scope; + + REQUIRE_ARGS_LENGTH(0); + + NativeCVoidFunctionCall_1_ ncall(* mysql_close, args); + ncall.run(); + + return scope.Close(ncall.jsReturnVal()); +} + + +Handle mysql_real_connect_wrapper(const Arguments &args) { + HandleScope scope; + + REQUIRE_ARGS_LENGTH(8); + + NativeCFunctionCall_8_ + ncall(& mysql_real_connect, args); + ncall.run(); + + return scope.Close(ncall.jsReturnVal()); +} + + +Handle mysql_error_wrapper(const Arguments &args) { + HandleScope scope; + + REQUIRE_ARGS_LENGTH(1); + + NativeCFunctionCall_1_ ncall(& mysql_error, args); + ncall.run(); + + return scope.Close(ncall.jsReturnVal()); +} + + +Handle mysql_query_wrapper(const Arguments &args) { + HandleScope scope; + + REQUIRE_ARGS_LENGTH(2); + + NativeCFunctionCall_2_ ncall(& mysql_query, args); + ncall.run(); + + return scope.Close(ncall.jsReturnVal()); +} + + +void mysqlclient_initOnLoad(Handle target) { + DEFINE_JS_FUNCTION(target, "mysql_init", mysql_init_wrapper); + DEFINE_JS_FUNCTION(target, "mysql_close", mysql_close_wrapper); + DEFINE_JS_FUNCTION(target, "mysql_real_connect", mysql_real_connect_wrapper); + DEFINE_JS_FUNCTION(target, "mysql_error", mysql_error_wrapper); + DEFINE_JS_FUNCTION(target, "myqsl_query", mysql_query_wrapper); +} + diff --git a/pool/shard006/C++/0074371_SGDWithMomentumSolver.cpp b/pool/shard006/C++/0074371_SGDWithMomentumSolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ae595199e5df8451f63a0b235ec5b72185bc2c9 --- /dev/null +++ b/pool/shard006/C++/0074371_SGDWithMomentumSolver.cpp @@ -0,0 +1,27 @@ +#include +#include "SGDWithMomentumSolver.h" + +NumGrind::Solvers::SGDWithMomentumSolver::SGDWithMomentumSolver(const NumGrind::Solvers::SolverSettings &settings, + const float stepSize, const float momentumCoeff, + const Eigen::VectorXf &vars) + : NumGrind::Solvers::SGDSolver(settings, stepSize, vars), momentumCoeff(momentumCoeff) { + this->oldGrad.resize(vars.size()); + this->oldGrad.fill(0); +// assert(false);//Not implemented +} + +void NumGrind::Solvers::SGDWithMomentumSolver::makeStep(std::function func, + std::function gradFunc) { + this->grad.resize(mVars.size()); + grad.fill(0); + gradFunc(mVars, grad); + grad *= stepSize; + grad += this->momentumCoeff * this->oldGrad; + oldGrad = grad; + mVars -= grad; + const float err = func(mVars); + this->updateBestVars(err); + if (this->settings.verbose) + std::cout << "err " << err << std::endl; +} diff --git a/pool/shard006/C++/0074387_h5cpp.cpp b/pool/shard006/C++/0074387_h5cpp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a48f9979d6855a6d587380d531b095608b19ea66 --- /dev/null +++ b/pool/shard006/C++/0074387_h5cpp.cpp @@ -0,0 +1,133 @@ +// +// (c) Copyright 2011 DESY, Eugen Wintersberger +// +// This file is part of python-pninexus. +// +// python-pninexus 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. +// +// python-pninexus 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 python-pninexus. If not, see . +// =========================================================================== +// +// Created on: Jan 5, 2012 +// Author: Eugen Wintersberger +// + + +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION +#define PY_ARRAY_UNIQUE_SYMBOL PNI_CORE_USYMBOL +extern "C"{ +#include +#include +} + +#include +#include +#include + + +//import here the namespace for the nxh5 module +using namespace boost::python; + +#include "boost_filesystem_path_conversion.hpp" +#include "dimensions_conversion.hpp" +#include "errors.hpp" + + +#if PY_MAJOR_VERSION >= 3 +static void * init_numpy() +{ + import_array(); + return NULL; +} +#else +static void init_numpy() +{ + import_array(); +} +#endif + +std::string path_to_string(const hdf5::Path &self) +{ + return std::string(self); +} + +void print_hdf5_errors(bool value) +{ + hdf5::error::Singleton::instance().auto_print(value); +} + + +//=================implementation of the python extension====================== +BOOST_PYTHON_MODULE(_h5cpp) +{ + init_numpy(); + + // + // setting up the documentation options + // + docstring_options doc_opts; + doc_opts.disable_signatures(); + doc_opts.enable_user_defined(); + + // ====================================================================== + // Register object converters + // ====================================================================== + BoostFilesystemPathToPythonObject(); + PythonObjectToBoostFilesystemPath(); + DimensionsToTuple(); + PythonToDimensions(); + + enum_("IterationOrder") + .value("INCREASING",hdf5::IterationOrder::INCREASING) + .value("DECREASING",hdf5::IterationOrder::DECREASING) + .value("NATIVE",hdf5::IterationOrder::NATIVE); + + enum_("IterationIndex") + .value("NAME",hdf5::IterationIndex::NAME) + .value("CREATION_ORDER",hdf5::IterationIndex::CREATION_ORDER); + + + hdf5::IterationOrder (hdf5::IteratorConfig::*get_iteration_order)() const = &hdf5::IteratorConfig::order; + void (hdf5::IteratorConfig::*set_iteration_order)(hdf5::IterationOrder) = &hdf5::IteratorConfig::order; + hdf5::IterationIndex (hdf5::IteratorConfig::*get_iteration_index)() const = &hdf5::IteratorConfig::index; + void (hdf5::IteratorConfig::*set_iteration_index)(hdf5::IterationIndex) = &hdf5::IteratorConfig::index; + const hdf5::property::LinkAccessList &(hdf5::IteratorConfig::*get_link_access_list)() const = + &hdf5::IteratorConfig::link_access_list; + void (hdf5::IteratorConfig::*set_link_access_list)(const hdf5::property::LinkAccessList &) = + &hdf5::IteratorConfig::link_access_list; + class_("IteratorConfig") + .add_property("order",get_iteration_order,set_iteration_order) + .add_property("index",get_iteration_index,set_iteration_index) + .add_property("link_access_list",make_function(get_link_access_list,return_internal_reference<>()),set_link_access_list) + ; + + bool (hdf5::Path::*get_absolute)() const = &hdf5::Path::absolute; + void (hdf5::Path::*set_absolute)(bool) = &hdf5::Path::absolute; + class_("Path") + .def(init<>()) + .def(init()) + .add_property("name",&hdf5::Path::name) + .add_property("size",&hdf5::Path::size) + .add_property("parent",&hdf5::Path::parent) + .add_property("absolute",get_absolute,set_absolute) + .def("append",&hdf5::Path::append) + .def("is_root",&hdf5::Path::is_root) + .def("__str__",path_to_string) + .def("__repr__",path_to_string) + .def(self == hdf5::Path()) + .def(self + hdf5::Path()) + ; + + def("print_hdf5_errors",print_hdf5_errors); + + exception_registration(); +} diff --git a/pool/shard006/C++/0074390_BandSPDLinSOE.cpp b/pool/shard006/C++/0074390_BandSPDLinSOE.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b310c0493572d5d16a3f5f5b47e872df965cf274 --- /dev/null +++ b/pool/shard006/C++/0074390_BandSPDLinSOE.cpp @@ -0,0 +1,280 @@ +//---------------------------------------------------------------------------- +// XC program; finite element analysis code +// for structural analysis and design. +// +// Copyright (C) Luis Claudio Pérez Tato +// +// This program derives from OpenSees +// developed by the «Pacific earthquake engineering research center». +// +// Except for the restrictions that may arise from the copyright +// of the original program (see copyright_opensees.txt) +// XC 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 software 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 . +//---------------------------------------------------------------------------- +/* ****************************************************************** ** +** OpenSees - Open System for Earthquake Engineering Simulation ** +** Pacific Earthquake Engineering Research Center ** +** ** +** ** +** (C) Copyright 1999, The Regents of the University of California ** +** All Rights Reserved. ** +** ** +** Commercial use of this program without express permission of the ** +** University of California, Berkeley, is strictly prohibited. See ** +** file 'COPYRIGHT' in main directory for information on usage and ** +** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** +** ** +** Developed by: ** +** Frank McKenna (fmckenna@ce.berkeley.edu) ** +** Gregory L. Fenves (fenves@ce.berkeley.edu) ** +** Filip C. Filippou (filippou@ce.berkeley.edu) ** +** ** +** ****************************************************************** */ + +// $Revision: 1.4 $ +// $Date: 2005/12/06 22:03:48 $ +// $Source: /usr/local/cvs/OpenSees/SRC/system_of_eqn/linearSOE/bandSPD/BandSPDLinSOE.cpp,v $ + + +// file: ~/system_of_eqn/linearSOE/bandSPD/BandSPDLinSOE.C +// +// Written: fmk +// Created: Febuary 1997 +// Revision: A +// +// Description: This file contains the implementation for XC::BandSPDLinSOE + + +#include +#include +#include +#include +#include "solution/graph/graph/Graph.h" +#include +#include + +void XC::BandSPDLinSOE::inicA(const size_t &hsz) + { + A.resize(hsz); + A.Zero(); + } + +//! @brief Constructor. +//! +//! The system size is set to \f$0\f$ and the matrix \f$A\f$ is marked as +//! not having been factored. Invokes {\em setLinearSOE(*this)} on the +//! \p solver. No memory is allocated for the 3 1d arrays. +//! +//! @param owr: analysis aggregation that owns this object. +XC::BandSPDLinSOE::BandSPDLinSOE(AnalysisAggregation *owr) + :FactoredSOEBase(owr,LinSOE_TAGS_BandSPDLinSOE), half_band(0){} + + +//! @brief Constructor. +//! +//! @param owr: analysis aggregation that owns this object. +//! @param classTag: identifier of the class. +XC::BandSPDLinSOE::BandSPDLinSOE(AnalysisAggregation *owr,int classTag) + :FactoredSOEBase(owr,classTag), half_band(0) {} + + +//! @brief Constructor. +//! +//! Invokes {\em setLinearSOE(*this)} and setSize() on the \p theSolver, +//! printing a warning message if setSize() returns a negative number. Also +//! creates Vector objects for \f$x\f$ and \f$b\f$ using the +//! {\em (double *,int)} Vector constructor. +//! +//! @param owr: analysis aggregation that owns this object. +//! @param classTag: identifier of the class. +//! @param N: size of the system. +//! @param numSuper: number of super diagonals. +//! @param the_Solver: pointer to the solver. +XC::BandSPDLinSOE::BandSPDLinSOE(AnalysisAggregation *owr,int N, int numSuper,BandSPDLinSolver *the_Solver) + :FactoredSOEBase(owr,LinSOE_TAGS_BandSPDLinSOE,N), half_band(0) + { + half_band = numSuper+1; + + inicA(half_band*size); + + inic(size); + + if(the_Solver) + setSolver(the_Solver); + else + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; solver not set." << std::endl; + } + +//! @brief Virtual constructor. +XC::SystemOfEqn *XC::BandSPDLinSOE::getCopy(void) const + { return new BandSPDLinSOE(*this); } + +//! @brief Set pointer to solver. +//! +//! Invokes {\em setLinearSOE(*this)} on \p newSolver. +//! If the system size is not equal to \f$0\f$, it also invokes setSize() +//! on \p newSolver, printing a warning and returning the returned value if this +//! method returns a number less than \f$0\f$. Finally it returns the result +//! of invoking the LinearSOE classes setSolver() method. +bool XC::BandSPDLinSOE::setSolver(LinearSOESolver *newSolver) + { + bool retval= false; + BandSPDLinSolver *tmp= dynamic_cast(newSolver); + if(tmp) + retval= FactoredSOEBase::setSolver(tmp); + else + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; incompatible solver." << std::endl; + return retval; + } + +//! @brief Sets the size of the system from the number of vertices in the graph. +//! +//! The size of the system is determined by looking at the adjacency ID of +//! each Vertex in the Graph object \p G. This is done by first setting +//! \p ku equal to \f$0\f$ and then checking for each Vertex +//! in \p G, whether any of the vertex tags in the Vertices adjacency +//! ID results in \p ku being increased. Knowing \p ku and the size +//! of the system (the number of Vertices in \p G, a check to see if +//! the previously allocated 1d arrays for \f$A\f$, \f$x\f$ and \f$b\f$ are +//! large enough. If the memory portions allocated for the 1d arrays are not big +//! enough, the old space is returned to the heap and new space is +//! allocated from the heap. Prints a warning message if not enough +//! memory is available on the heap for the 1d arrays and returns a +//! \f$-1\f$. If memory is available, the components of the arrays are zeroed +//! and \f$A\f$ is marked as being unfactored. If the system size has +//! increased, new Vector objects for \f$x\f$ and \f$b\f$ using the {\em (double +//! *,int)} Vector constructor are created. Finally, the result of +//! invoking setSize() on the associated Solver object is +//! returned. +int XC::BandSPDLinSOE::setSize(Graph &theGraph) + { + int result = 0; + size= checkSize(theGraph); + half_band= theGraph.getVertexDiffMaxima(); + + + half_band+= 1; // include the diagonal + + + if(half_band*size > A.Size())// we have to get another space for A + inicA(half_band*size); + + factored = false; + + if(size > B.Size()) + inic(size); + + + // invoke setSize() on the Solver + LinearSOESolver *the_Solver= this->getSolver(); + int solverOK = the_Solver->setSize(); + if(solverOK < 0) + { + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; WARNING: solver failed in setSize()\n"; + return solverOK; + } + + return result; + } + +//! First tests that \p loc and \p M are of compatible sizes; if not +//! a warning message is printed and a \f$-1\f$ is returned. The LinearSOE +//! object then assembles \p fact times the Matrix {\em +//! M} into the matrix \f$A\f$. The Matrix is assembled into \f$A\f$ at the +//! locations given by the ID object \p loc, i.e. \f$a_{loc(i),loc(j)} += +//! fact * M(i,j)\f$. If the location specified is outside the range, +//! i.e. \f$(-1,-1)\f$ the corresponding entry in \p M is not added to +//! \f$A\f$. If \p fact is equal to \f$0.0\f$ or \f$1.0\f$, more efficient steps +//! are performed. Returns \f$0\f$. +int XC::BandSPDLinSOE::addA(const Matrix &m, const ID &id, double fact) + { + // check for a quick return + if(fact == 0.0) return 0; + + // check that m and id are of similar size + int idSize = id.Size(); + if(idSize != m.noRows() && idSize != m.noCols()) + { + std::cerr << getClassName() << "::" << __FUNCTION__ + << "; Matrix and ID not of similar sizes.\n"; + return -1; + } + + if(fact == 1.0) + { // do not need to multiply + for(int i=0; i= 0) + { + double *coliiPtr = A.getDataPtr() +(col+1)*half_band -1; + int minColRow = col - half_band + 1; + for(int j=0; j= 0 && + row <= col && row >= minColRow) + { // only add upper + double *APtr = coliiPtr + (row-col); + *APtr += m(j,i); + } + } // for j + } + } // for i + } + else + { + for(int i=0; i= 0) + { + double *coliiPtr = A.getDataPtr() +(col+1)*half_band -1; + int minColRow = col - half_band +1; + for(int j=0; j= 0 && + row <= col && row >= minColRow) + { // only add upper + double *APtr = coliiPtr + (row-col); + *APtr += m(j,i)*fact; + } + } // for j + } + } // for i + } + return 0; + } + + +//! @brief Zeros the entries in the 1d array for \f$A\f$ and marks the system +//! as not having been factored. +void XC::BandSPDLinSOE::zeroA(void) + { + A.Zero(); + factored = false; + } + +int XC::BandSPDLinSOE::sendSelf(CommParameters &cp) + { return 0; } + + +int XC::BandSPDLinSOE::recvSelf(const CommParameters &cp) + { return 0; } diff --git a/pool/shard006/C++/0074391_describequeueresponse.cpp b/pool/shard006/C++/0074391_describequeueresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a605ede66179eff18a57627ca06dc751c93d65c3 --- /dev/null +++ b/pool/shard006/C++/0074391_describequeueresponse.cpp @@ -0,0 +1,124 @@ +/* + 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 "describequeueresponse.h" +#include "describequeueresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace Connect { + +/*! + * \class QtAws::Connect::DescribeQueueResponse + * \brief The DescribeQueueResponse class provides an interace for Connect DescribeQueue responses. + * + * \inmodule QtAwsConnect + * + * Amazon Connect is a cloud-based contact center solution that you use to set up and manage a customer contact center and + * provide reliable customer engagement at any + * + * scale> + * + * Amazon Connect provides metrics and real-time reporting that enable you to optimize contact routing. You can also + * resolve customer issues more efficiently by getting customers in touch with the appropriate + * + * agents> + * + * There are limits to the number of Amazon Connect resources that you can create. There are also limits to the number of + * requests that you can make per second. For more information, see Amazon Connect Service + * Quotas in the Amazon Connect Administrator + * + * Guide> + * + * You can connect programmatically to an AWS service by using an endpoint. For a list of Amazon Connect endpoints, see Amazon Connect + * + * Endpoints> + * + * Working with contact flows? Check out the Amazon Connect Flow + * + * \sa ConnectClient::describeQueue + */ + +/*! + * Constructs a DescribeQueueResponse object for \a reply to \a request, with parent \a parent. + */ +DescribeQueueResponse::DescribeQueueResponse( + const DescribeQueueRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : ConnectResponse(new DescribeQueueResponsePrivate(this), parent) +{ + setRequest(new DescribeQueueRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const DescribeQueueRequest * DescribeQueueResponse::request() const +{ + Q_D(const DescribeQueueResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful Connect DescribeQueue \a response. + */ +void DescribeQueueResponse::parseSuccess(QIODevice &response) +{ + //Q_D(DescribeQueueResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::Connect::DescribeQueueResponsePrivate + * \brief The DescribeQueueResponsePrivate class provides private implementation for DescribeQueueResponse. + * \internal + * + * \inmodule QtAwsConnect + */ + +/*! + * Constructs a DescribeQueueResponsePrivate object with public implementation \a q. + */ +DescribeQueueResponsePrivate::DescribeQueueResponsePrivate( + DescribeQueueResponse * const q) : ConnectResponsePrivate(q) +{ + +} + +/*! + * Parses a Connect DescribeQueue response element from \a xml. + */ +void DescribeQueueResponsePrivate::parseDescribeQueueResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("DescribeQueueResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace Connect +} // namespace QtAws diff --git a/pool/shard006/C++/0074400_Slider.cpp b/pool/shard006/C++/0074400_Slider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7f06c8e3b3b1c326816a83a1b75fa62883a9869 --- /dev/null +++ b/pool/shard006/C++/0074400_Slider.cpp @@ -0,0 +1,205 @@ +/* smplayer, GUI front-end for mplayer. + Copyright (C) 2006-2010 Ricardo Villalba + + 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) version 3, or any + later version accepted by the membership of KDE e.V. (or its + successor approved by the membership of KDE e.V.), Trolltech ASA + (or its successors, if any) and the KDE Free Qt Foundation, which shall + act as a proxy defined in Section 6 of version 3 of the license. + + 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, see . +*/ + +#define CODE_FOR_CLICK 1 // 0 = old code, 1 = code copied from QSlider, 2 = button swap + +#include "Slider.h" +#include +#include + +#if CODE_FOR_CLICK <= 1 +#include +#if CODE_FOR_CLICK == 1 +#include +#endif +#endif + +#if QT_VERSION < 0x040300 +#define initStyleOption initStyleOption_Qt430 +#endif //QT_VERSION + + +Slider::Slider(QWidget *parent): + QSlider(parent) +{ + setOrientation(Qt::Horizontal); + setMouseTracking(true); //mouseMoveEvent without press. +} + +Slider::~Slider() +{ +} + +#if CODE_FOR_CLICK == 1 +// Function copied from qslider.cpp +inline int Slider::pick(const QPoint &pt) const +{ + return orientation() == Qt::Horizontal ? pt.x() : pt.y(); +} + +// Function copied from qslider.cpp and modified to make it compile +void Slider::initStyleOption_Qt430(QStyleOptionSlider *option) const +{ + if (!option) + return; + + option->initFrom(this); + option->subControls = QStyle::SC_None; + option->activeSubControls = QStyle::SC_None; + option->orientation = orientation(); + option->maximum = maximum(); + option->minimum = minimum(); + option->tickPosition = (QSlider::TickPosition) tickPosition(); + option->tickInterval = tickInterval(); + option->upsideDown = (orientation() == Qt::Horizontal) ? + (invertedAppearance() != (option->direction == Qt::RightToLeft)) + : (!invertedAppearance()); + option->direction = Qt::LeftToRight; // we use the upsideDown option instead + option->sliderPosition = sliderPosition(); + option->sliderValue = value(); + option->singleStep = singleStep(); + option->pageStep = pageStep(); + if (orientation() == Qt::Horizontal) + option->state |= QStyle::State_Horizontal; +} + +// Function copied from qslider.cpp and modified to make it compile +int Slider::pixelPosToRangeValue(int pos) const +{ + QStyleOptionSlider opt; + initStyleOption(&opt); + QRect gr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + int sliderMin, sliderMax, sliderLength; + if (orientation() == Qt::Horizontal) { + sliderLength = sr.width(); + sliderMin = gr.x(); + sliderMax = gr.right() - sliderLength + 1; + } else { + sliderLength = sr.height(); + sliderMin = gr.y(); + sliderMax = gr.bottom() - sliderLength + 1; + } + return QStyle::sliderValueFromPosition(minimum(), maximum(), pos - sliderMin, + sliderMax - sliderMin, opt.upsideDown); +} + +void Slider::enterEvent(QEvent *event) +{ + emit onEnter(); + QSlider::enterEvent(event); +} + +void Slider::leaveEvent(QEvent *e) +{ + emit onLeave(); + QSlider::leaveEvent(e); +} + +void Slider::mouseMoveEvent(QMouseEvent *e) +{ + const int o = style()->pixelMetric(QStyle::PM_SliderLength ) - 1; + int v = QStyle::sliderValueFromPosition(minimum(), maximum(), e->pos().x()-o/2, width()-o, false); + emit onHover(e->x(), v); + QSlider::mouseMoveEvent(e); +} + +// Based on code from qslider.cpp +void Slider::mousePressEvent(QMouseEvent *e) +{ + qDebug("pressed (%d, %d)", e->pos().x(), e->pos().y()); + if (e->button() == Qt::LeftButton) { + QStyleOptionSlider opt; + initStyleOption(&opt); + const QRect sliderRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + const QPoint center = sliderRect.center() - sliderRect.topLeft(); + // to take half of the slider off for the setSliderPosition call we use the center - topLeft + + if (!sliderRect.contains(e->pos())) { + qDebug("accept"); + e->accept(); + + int v = pixelPosToRangeValue(pick(e->pos() - center)); + setSliderPosition(v); + triggerAction(SliderMove); + setRepeatAction(SliderNoAction); + emit sliderMoved(v);//TODO: ok? + emit sliderPressed(); //TODO: ok? + } else { + QSlider::mousePressEvent(e); + } + } else { + QSlider::mousePressEvent(e); + } +} +#endif // CODE_FOR_CLICK == 1 +#if CODE_FOR_CLICK == 2 +void Slider::mousePressEvent(QMouseEvent *e) +{ + // Swaps middle button click with left click + if (e->button() == Qt::LeftButton) { + QMouseEvent ev2(QEvent::MouseButtonRelease, e->pos(), e->globalPos(), Qt::MidButton, Qt::MidButton, e->modifiers()); + QSlider::mousePressEvent(&ev2); + } else if (e->button() == Qt::MidButton) { + QMouseEvent ev2(QEvent::MouseButtonRelease, e->pos(), e->globalPos(), Qt::LeftButton, Qt::LeftButton, e->modifiers()); + QSlider::mousePressEvent(&ev2); + } + else { + QSlider::mousePressEvent(e); + } +} +#endif // CODE_FOR_CLICK == 2 +#if CODE_FOR_CLICK == 0 +void Slider::mousePressEvent(QMouseEvent *e) +{ + // FIXME: + // The code doesn't work well with right to left layout, + // so it's disabled. + if (qApp->isRightToLeft()) { + QSlider::mousePressEvent(e); + return; + } + + int range = maximum()-minimum(); + int pos = (e->x() * range) / width(); + //qDebug( "width: %d x: %d", width(), e->x()); + //qDebug( "range: %d pos: %d value: %d", range, pos, value()); + + // Calculate how many positions takes the slider handle + int metric = qApp->style()->pixelMetric(QStyle::PM_SliderLength); + double one_tick_pixels = (double)width() / range; + int slider_handle_positions = (int)(metric / one_tick_pixels); + + /* + qDebug("metric: %d", metric ); + qDebug("one_tick_pixels :%f", one_tick_pixels); + qDebug("width() :%d", width()); + qDebug("slider_handle_positions: %d", slider_handle_positions); + */ + + if (abs(pos - value()) > slider_handle_positions) { + setValue(pos); + emit sliderMoved(pos); + } else { + QSlider::mousePressEvent(e); + } +} +#endif diff --git a/pool/shard006/C++/0074410_m4dlua_main.cpp b/pool/shard006/C++/0074410_m4dlua_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d491031e396bcebab81e3fc30978380bfbf34932 --- /dev/null +++ b/pool/shard006/C++/0074410_m4dlua_main.cpp @@ -0,0 +1,59 @@ +/* ------------------------------------------------------------------------------- + m4dlua_main.cpp + + Copyright (c) 2015 Thomas Mueller + + This file is part of the m4d-library. + + The m4d-library 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. + + The m4d-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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the m4d-library. If not, see . + ------------------------------------------------------------------------------- */ + +#include + +#include "lua/m4dlua.h" +#include "lua/m4dlua_metric.h" +#include "lua/m4dlua_solver.h" +#include "lua/m4dlua_utils.h" + +lua_State* L = NULL; + +m4d::Object mObject; + + + +int main(int argc, char* argv[]) { + if (argc!=2) { + fprintf(stderr,"Usage: ./m4dLua \n"); + return -1; + } + + L = luaL_newstate(); + luaL_openlibs(L); + + // register all functions + lua_reg_metric(L); + lua_reg_solver(L); + lua_reg_utils(L); + + + //int numErrors = 0; + //if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) { + int errornr = LUA_OK; + if ((errornr = luaL_dofile(L, argv[1]))) { + mlua_error(L, "Error: %s\n", lua_tostring(L, -1)); + } else { + lua_close(L); + } + return 0; +} diff --git a/pool/shard006/C++/0074411_SampleCharacterCloth_CCT.cpp b/pool/shard006/C++/0074411_SampleCharacterCloth_CCT.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d256044b4551b18a5f09e2e9599db531b0a50d9c --- /dev/null +++ b/pool/shard006/C++/0074411_SampleCharacterCloth_CCT.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#include "PxPhysXConfig.h" + +#if PX_USE_CLOTH_API + +#include "SampleCharacterCloth.h" + +#include "SampleCharacterClothCameraController.h" +#include "SampleAllocatorSDKClasses.h" + +#include "PxPhysicsAPI.h" +#include "extensions/PxExtensionsAPI.h" + +#include "characterkinematic/PxControllerManager.h" +#include "characterkinematic/PxBoxController.h" +#include "characterkinematic/PxCapsuleController.h" + + +#include "geometry/PxMeshQuery.h" +#include "geometry/PxTriangle.h" + +#include "RenderBaseActor.h" +#include "RenderBoxActor.h" +#include "RenderCapsuleActor.h" +#include +#include +#include +#include + +using namespace SampleRenderer; +using namespace SampleFramework; + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::bufferCCTMotion(const PxVec3& targetDisp, PxReal dtime) +{ + PxVec3 disp = targetDisp; + + if(!isPaused()) + { + // advance jump controller + mJump.tick(dtime); + + // modify y component of displacement due to jump status + disp.y = mJump.getDisplacement(dtime); + + if (mJump.isInFreefall()) + { + disp.x = 0; + disp.z = 0; + mCCTActive = false; + } + } + + // buffer the displacement and timestep to feed in onSubstep function + mCCTDisplacement = disp; + mCCTTimeStep = dtime; +} + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::createCCTController() +{ + mControllerManager = PxCreateControllerManager(getActiveScene()); + + // use ray casting to position the CCT on the terrain + PxScene& scene = getActiveScene(); + PxRaycastBuffer hit; + bool didHit = scene.raycast(PxVec3(0,100,0), PxVec3(0,-1,0), 500.0f, hit, PxHitFlags(0xffff)); + PX_UNUSED(didHit); + PX_ASSERT(didHit); + mControllerInitialPosition = hit.block.position + PxVec3(0.0f, 1.6f, 0.0f); + + // create and fill in the descriptor for the capsule controller + PxCapsuleControllerDesc cDesc; + + cDesc.height = 2.0f; + cDesc.radius = 0.5f; + cDesc.material = &getDefaultMaterial(); + cDesc.position = PxExtendedVec3(mControllerInitialPosition.x, mControllerInitialPosition.y, mControllerInitialPosition.z); + cDesc.slopeLimit = 0.1f; + cDesc.contactOffset = 0.01f; + cDesc.stepOffset = 0.1f; + cDesc.scaleCoeff = 0.9f; + cDesc.climbingMode = PxCapsuleClimbingMode::eEASY; + cDesc.invisibleWallHeight = 0.0f; + cDesc.maxJumpHeight = 2.0f; + cDesc.reportCallback = this; + + mController = static_cast(mControllerManager->createController(cDesc)); + + // create camera + mCCTCamera = SAMPLE_NEW(SampleCharacterClothCameraController)(*mController, *this); + + setCameraController(mCCTCamera); +} + + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::onShapeHit(const PxControllerShapeHit& hit) +{ + PxRigidDynamic* hitActor = hit.shape->getActor()->is(); + + const size_t nbPlatforms = mPlatforms.size(); + for(PxU32 i = 0;i < nbPlatforms;i++) + { + if (mPlatforms[i]->getType() == SampleCharacterClothPlatform::ePLATFORM_TYPE_TRIGGERED) + { + PxRigidDynamic* actor = mPlatforms[i]->getPhysicsActor(); + if (hitActor == actor) + mPlatforms[i]->setActive(true); + } + } +} + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::onControllerHit(const PxControllersHit& hit) +{ +} + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::onObstacleHit(const PxControllerObstacleHit& hit) +{ +} + +/////////////////////////////////////////////////////////////////////////////// +PxControllerBehaviorFlags SampleCharacterCloth::getBehaviorFlags(const PxShape&, const PxActor&) +{ + return PxControllerBehaviorFlags(0); +} + +/////////////////////////////////////////////////////////////////////////////// +PxControllerBehaviorFlags SampleCharacterCloth::getBehaviorFlags(const PxController&) +{ + return PxControllerBehaviorFlags(0); +} + +/////////////////////////////////////////////////////////////////////////////// +PxControllerBehaviorFlags SampleCharacterCloth::getBehaviorFlags(const PxObstacle& obstacle) +{ + return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT; +} + +/////////////////////////////////////////////////////////////////////////////// +void SampleCharacterCloth::updateCCT(float dtime) +{ + // compute target cct displacment for this time step + PxVec3 dispCurStep = (mCCTTimeStep > 0.0f) ? mCCTDisplacement * (dtime / mCCTTimeStep) : PxVec3(0.0f); + + // limit horizontal acceleration so that character motion does not produce abrupt impulse + PxVec3 accel = dispCurStep - mCCTDisplacementPrevStep; + const PxReal accelLimit = 0.3f * dtime; + PxVec3 accelHorizontal(accel.x, 0, accel.z); + PxReal accelHorizontalMagnitude = accelHorizontal.magnitude(); + if (accelHorizontalMagnitude > accelLimit) + { + const PxReal accelScale = accelLimit / accelHorizontalMagnitude; + accel.x *= accelScale; + accel.z *= accelScale; + } + + dispCurStep = mCCTDisplacementPrevStep + accel; + mCCTDisplacementPrevStep = dispCurStep; + + // move the CCT and change jump status due to contact + const PxU32 flags = mController->move(dispCurStep, 0.01f, dtime, PxControllerFilters()); + if(flags & PxControllerCollisionFlag::eCOLLISION_DOWN) + mJump.reset(); + + // update camera controller + mCCTCamera->updateFromCCT(dtime); + +} + +#endif // PX_USE_CLOTH_API diff --git a/pool/shard006/C++/0074417_1051C.cpp b/pool/shard006/C++/0074417_1051C.cpp new file mode 100644 index 0000000000000000000000000000000000000000..679a67ab111603377a7821270147a9fc21f466c9 --- /dev/null +++ b/pool/shard006/C++/0074417_1051C.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include +#include +using namespace std; + +// Useful constants +#define INF (int)1e9 +#define EPS 1e-9 +// Useful hardware instructions +#define bitcount __builtin_popcount +#define gcd __gcd + +#define all(a) begin(a), end(a) +#define in(a, b) ((b).find(a) != (b).end()) +#define pb push_back +#define sz(a) ((int)(a.size())) +#define mp make_pair +// Some common useful functions +#define maX(a, b) ((a) > (b) ? (a) : (b)) +#define miN(a, b) ((a) < (b) ? (a) : (b)) +#define checkbit(n, b) ((n >> b) & 1) + +template +inline constexpr bool odd(const T& a) { + return bool(a & 1); +} + +template +inline constexpr bool even(const T& a) { + return !odd(a); +} + +template +inline T mod(const T& m, const T& n) { + return m >= 0 ? m % n : (n - abs(m % n)) % n; +} + +using uint = unsigned; +constexpr unsigned S = 105; + +using pii = pair; + +int main() { + array V; + array ans; + fill(all(V), 0); + int n; + cin >> n; + const uint nn = n; + for (int i = 0; i < n; ++i) { + int a; + cin >> a; + V[a]++; + ans[i] = make_pair(a, 0); + } + int num_nice = 0; + int candidate = -1; + for (int i = 0; i < S; ++i) { + if (V[i] == 1) + num_nice++; + else if (V[i] >= 3) + candidate = i; + } + + if (odd(num_nice) && candidate == -1) { + cout << "NO" << endl; + return 0; + } + + cout << "YES" << endl; + if (odd(num_nice) && candidate != -1) { + auto it = find_if( + all(ans), [&candidate](const auto p) { return p.first == candidate; }); + (*it).second = 1; + } + int nice2 = num_nice / 2; + for (int i = 0; nice2 && i < n; ++i) { + if (V[ans[i].first] == 1) { + ans[i].second = 1; + nice2--; + } + } + + for (int i = 0; i < n; ++i) { + char c = ans[i].second ? 'B' : 'A'; + cout << c; + } + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0074418_future2.cc b/pool/shard006/C++/0074418_future2.cc new file mode 100644 index 0000000000000000000000000000000000000000..2474f9bda17cd3496d5eee979a39767ffec076c8 --- /dev/null +++ b/pool/shard006/C++/0074418_future2.cc @@ -0,0 +1,27 @@ +#include +#include +#include + +int main() +{ + // future from a packaged_task + std::packaged_task task([](){ return 7; }); // wrap the function + std::future f1 = task.get_future(); // get a future + std::thread(std::move(task)).detach(); // launch on a thread + + // future from an async() + std::future f2 = std::async(std::launch::async, [](){ return 8; }); + + // future from a promise + std::promise p; + std::future f3 = p.get_future(); + std::thread( [](std::promise p){ p.set_value_at_thread_exit(9); }, + std::move(p) ).detach(); + + std::cout << "Waiting..." << std::flush; + f1.wait(); + f2.wait(); + f3.wait(); + std::cout << "Done!\nResults are: " + << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; +} \ No newline at end of file diff --git a/pool/shard006/C++/0074420_g018.cpp b/pool/shard006/C++/0074420_g018.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93584ad9e93372618659c9aa68e9e2644d4d4d2f --- /dev/null +++ b/pool/shard006/C++/0074420_g018.cpp @@ -0,0 +1,75 @@ +//{ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +typedef long long ll; +typedef double lf; +typedef pair ii; +#define REP(i,n) for(ll i=0;i ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} +template ostream& _OUTC(ostream &_s,It _ita,It _itb) +{ + _s<<"{"; + for(It _it=_ita;_it!=_itb;_it++) + { + _s<<(_it==_ita?"":",")<<*_it; + } + _s<<"}"; + return _s; +} +template ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} +template ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} +template ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} +template void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<. +*/ +/** @file MemoryDB.cpp + * @author Gav Wood + * @date 2014 + */ + +#include "MemoryDB.h" +#include "Common.h" +#include "CommonData.h" +using namespace std; +using namespace dev; + +namespace dev +{ + +const char* DBChannel::name() { return "TDB"; } +const char* DBWarn::name() { return "TDB"; } + +std::unordered_map MemoryDB::get() const +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + std::unordered_map ret; + for (auto const& i: m_main) + if (!m_enforceRefs || i.second.second > 0) + ret.insert(make_pair(i.first, i.second.first)); + return ret; +} + +MemoryDB& MemoryDB::operator=(MemoryDB const& _c) +{ + if (this == &_c) + return *this; +#if DEV_GUARDED_DB + ReadGuard l(_c.x_this); + WriteGuard l2(x_this); +#endif + m_main = _c.m_main; + m_aux = _c.m_aux; + return *this; +} + +std::string MemoryDB::lookup(h256 const& _h) const +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + auto it = m_main.find(_h); + if (it != m_main.end()) + { + if (!m_enforceRefs || it->second.second > 0) + return it->second.first; + else + cwarn << "Lookup required for value with refcount == 0. This is probably a critical trie issue" << _h; + } + return std::string(); +} + +bool MemoryDB::exists(h256 const& _h) const +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + auto it = m_main.find(_h); + if (it != m_main.end() && (!m_enforceRefs || it->second.second > 0)) + return true; + return false; +} + +void MemoryDB::insert(h256 const& _h, bytesConstRef _v) +{ +#if DEV_GUARDED_DB + WriteGuard l(x_this); +#endif + auto it = m_main.find(_h); + if (it != m_main.end()) + { + it->second.first = _v.toString(); + it->second.second++; + } + else + m_main[_h] = make_pair(_v.toString(), 1); +#if ETH_PARANOIA + dbdebug << "INST" << _h << "=>" << m_main[_h].second; +#endif +} + +bool MemoryDB::kill(h256 const& _h) +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + if (m_main.count(_h)) + { + if (m_main[_h].second > 0) + { + m_main[_h].second--; + return true; + } +#if ETH_PARANOIA + else + { + // If we get to this point, then there was probably a node in the level DB which we need to remove and which we have previously + // used as part of the memory-based MemoryDB. Nothing to be worried about *as long as the node exists in the DB*. + dbdebug << "NOKILL-WAS" << _h; + } + dbdebug << "KILL" << _h << "=>" << m_main[_h].second; + } + else + { + dbdebug << "NOKILL" << _h; +#endif + } + return false; +} + +bytes MemoryDB::lookupAux(h256 const& _h) const +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + auto it = m_aux.find(_h); + if (it != m_aux.end() && (!m_enforceRefs || it->second.second)) + return it->second.first; + return bytes(); +} + +void MemoryDB::removeAux(h256 const& _h) +{ +#if DEV_GUARDED_DB + WriteGuard l(x_this); +#endif + m_aux[_h].second = false; +} + +void MemoryDB::insertAux(h256 const& _h, bytesConstRef _v) +{ +#if DEV_GUARDED_DB + WriteGuard l(x_this); +#endif + m_aux[_h] = make_pair(_v.toBytes(), true); +} + +void MemoryDB::purge() +{ +#if DEV_GUARDED_DB + WriteGuard l(x_this); +#endif + // purge m_main + for (auto it = m_main.begin(); it != m_main.end(); ) + if (it->second.second) + ++it; + else + it = m_main.erase(it); + + // purge m_aux + for (auto it = m_aux.begin(); it != m_aux.end(); ) + if (it->second.second) + ++it; + else + it = m_aux.erase(it); +} + +h256Hash MemoryDB::keys() const +{ +#if DEV_GUARDED_DB + ReadGuard l(x_this); +#endif + h256Hash ret; + for (auto const& i: m_main) + if (i.second.second) + ret.insert(i.first); + return ret; +} + +} diff --git a/pool/shard006/C++/0074423_Condition.cpp b/pool/shard006/C++/0074423_Condition.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21e148f4a89f31590314db12c68ec4bd3e12e30f --- /dev/null +++ b/pool/shard006/C++/0074423_Condition.cpp @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Condition.hpp" + +namespace apache { +namespace geode { +namespace client { + +/** + * Create a Condition protected by the mutex provided. + */ +Condition::Condition(ACE_Recursive_Thread_Mutex& mutex) + : m_cond(mutex), m_signaled(false) {} + +bool Condition::waitUntil(ACE_Time_Value* absoluteStopTime) { + ACE_OS::last_error(0); + + ACE_Time_Value stopAt = *absoluteStopTime; + while ((!m_signaled) && (m_cond.wait(&stopAt) != 0) && + (ACE_OS::last_error() != ETIME)) { + ACE_OS::last_error(0); + stopAt = *absoluteStopTime; + ACE_Time_Value now = ACE_OS::gettimeofday(); + if (now >= stopAt) { + break; + } + } + bool result = m_signaled; + m_signaled = false; + return result; +} +} // namespace client +} // namespace geode +} // namespace apache diff --git a/pool/shard006/C++/0074447_generateTrees.cpp b/pool/shard006/C++/0074447_generateTrees.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7043510079600e843d462e4acb59adc1488729f1 --- /dev/null +++ b/pool/shard006/C++/0074447_generateTrees.cpp @@ -0,0 +1,47 @@ +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector recursiveGenerateTrees(int n, int startNum) + { + vector output; + + if (n == 0) + { + output.push_back(NULL); + return output; + } + + // i: pick ith number as root for this subtree + for (int i = 1; i <= n; i++) + { + TreeNode *root = new TreeNode(startNum+i-1); + + vector leftSubTrees = recursiveGenerateTrees(i-1, startNum); + vector rightSubTrees = recursiveGenerateTrees(n-i, startNum+i); + for (int l = 1; l <= leftSubTrees.size(); l++) + for (int r = 1; r <= rightSubTrees.size(); r++) + { + TreeNode *root = new TreeNode(startNum+i-1); + root->left = leftSubTrees[l-1]; + root->right = rightSubTrees[r-1]; + output.push_back(root); + } + } + return output; + } + + + vector generateTrees(int n) { + // Start typing your C/C++ solution below + // DO NOT write int main() function + return recursiveGenerateTrees(n, 1); + } +}; \ No newline at end of file diff --git a/pool/shard006/C++/0074449_staging.cpp b/pool/shard006/C++/0074449_staging.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43364a3d9907b5f0c4fa3457cf3c219caaaf57e4 --- /dev/null +++ b/pool/shard006/C++/0074449_staging.cpp @@ -0,0 +1,285 @@ +/* + * @file $/source/libnparse_script/src/script/staging.cpp + * +This file is a part of the "nParse" project - + a general purpose parsing framework, version 0.1.8 + +The MIT License (MIT) +Copyright (c) 2007-2017 Alex Kudinov + +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 +#include +#include +#include +#include "../static.hpp" +#include "../source_tree.hpp" + +namespace { + +using namespace nparse; + +class Staging: public IStaging +{ + plugin::instance m_factory; + SourceTree m_st; + + typedef std::vector stored_t; + stored_t m_stored; + + typedef boost::unordered_map*> clusters_t; + clusters_t m_clusters; + + typedef boost::unordered_map acceptors_t; + acceptors_t m_acceptors; + + typedef std::vector action_stack_t; + action_stack_t m_action_stack; + + typedef std::vector joint_stack_t; + joint_stack_t m_joint_stack; + + typedef std::vector bound_factories_t; + bound_factories_t m_bound_factories; + + typedef std::vector::type> import_hints_t; + import_hints_t m_import_hints; + + string_t m_namespace; + +public: + Staging (): + m_factory ("nparse.AcceptorFactory") + { + } + + ~Staging () + { + utility::free_all(m_stored); + utility::free2nds(m_clusters); + utility::free2nds(m_acceptors); + utility::free_all(m_bound_factories); + } + +public: + // Overridden from IStaging: + + anta::ndl::Cluster& cluster (const string_t& a_name) + { + string_t name = a_name; + + clusters_t::iterator found_at = m_clusters. find(name); + if (found_at == m_clusters. end() && ! m_namespace. empty() + && name. find_first_of(L'.') == name. npos) + { + name. insert(0, m_namespace); + found_at = m_clusters. find(name); + } + + if (found_at == m_clusters. end()) + { + const std::pair p = m_clusters. insert( + clusters_t::value_type(name, new anta::ndl::Cluster(name)) + ); + assert(p. second); + found_at = p. first; + } + + return *(found_at -> second); + } + + const anta::Acceptor& acceptor (const string_t& a_def) + { + // @todo: acceptor key (a_def) depends on current path + const std::string& path = m_st. current_path(); + acceptors_t::iterator found_at = m_acceptors. find(a_def); + if (found_at == m_acceptors. end()) + { + const IAcceptor* instance = NULL; + if (! m_factory -> create(a_def, instance, path)) + { + // NOTE: Yes, it's a logic error! + throw std::logic_error("unable to create an acceptor from" + " the given definition"); + } + const std::pair p = + m_acceptors. insert(acceptors_t::value_type(a_def, instance)); + assert(p. second); + found_at = p. first; + } + return *(found_at -> second); + } + + const anta::Acceptor& acceptor (IAcceptor* a_ptr) + { + m_stored. push_back(a_ptr); + return *a_ptr; + } + + void push (const action_pointer& a_ptr) + { + m_action_stack. push_back(a_ptr); + } + + action_pointer pop () + { + assert(! m_action_stack. empty()); + const action_pointer top = m_action_stack. back(); + m_action_stack. pop_back(); + return top; + } + + action_pointer top () const + { + assert(! m_action_stack. empty()); + return m_action_stack. back(); + } + + void swap (std::vector& a_av) + { + m_action_stack. swap(a_av); + m_action_stack. clear(); + } + + void import (const std::string& a_path, const bool a_reset) + { + m_st. import(a_path, a_reset, -1); + } + + void import (const anta::range::type& a_path) + { + const string_t path(a_path. first, a_path. second); + const int hint = static_cast(m_import_hints. size()); + m_import_hints. push_back(a_path); + m_st. import(path, false, hint); + } + + bool load (anta::range::type& a_range) + { + SourceTree::range r; + try + { + if (! m_st. load(r)) + { + return false; + } + } + catch (const std::exception& err_) + { + ex::compile_error err; + err << ex::message(err_. what()); + const int hint_ = m_st. current_hint(); + if (hint_ >= 0) + { + const import_hints_t::size_type index = + static_cast(hint_); + const anta::range::type& where = m_import_hints[index]; + err << ex::location(where); + } + throw err; + } + a_range. first = &* r. first; + a_range. second = &* r. second; + m_namespace. clear(); + return true; + } + + bool identify (const anta::iterator::type& a_iterator, + std::string& a_file, int& a_line, int& a_offset) const + { + const SourceTree::iterator iter(a_iterator); + return m_st. identify(iter, a_file, a_line, a_offset); + } + + void setNamespace (const string_t& a_namespace) + { + m_namespace = a_namespace; + if (! m_namespace. empty()) + { + m_namespace. append(1, L'.'); + } + } + + const string_t& getNamespace () const + { + return m_namespace; + } + + void pushJoint (const joint_pointer& a_ptr) + { + m_joint_stack. push_back(a_ptr); + } + + joint_pointer popJoint () + { + assert(! m_joint_stack. empty()); + const joint_pointer top = m_joint_stack. back(); + m_joint_stack. pop_back(); + return top; + } + + void bind (plugin::IFactory* a_factory) + { + m_bound_factories. push_back(a_factory); + } + + void extend (ex::generic_error& a_error) const + { + // Check whether the exception has been bound to a file already. + if (boost::get_error_info(a_error)) + { + return; + } + + // Check whether the exception has location information. + const anta::range::type* pin = + boost::get_error_info(a_error); + if (! pin) + { + return; + } + + // Try to identify location. + std::string file; + int line, offset; + if (! identify(pin -> first, file, line, offset)) + { + return; + } + + // Add file/line/offset to the exception. + a_error << ex::file(file) << ex::line(line) << ex::offset(offset); + } + +}; + +class StagingFactory: public IStagingFactory +{ +public: + boost::shared_ptr createInstance () + { + return boost::shared_ptr(new Staging()); + } + +}; + +} // namespace + +PLUGIN(StagingFactory, script_staging, nparse.script.StagingFactory) diff --git a/pool/shard006/C++/0074451_perfetto_platform.cc b/pool/shard006/C++/0074451_perfetto_platform.cc new file mode 100644 index 0000000000000000000000000000000000000000..62a6ea479435be3b5c7c28ffb20ae73f216eff3d --- /dev/null +++ b/pool/shard006/C++/0074451_perfetto_platform.cc @@ -0,0 +1,98 @@ +// Copyright 2020 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/tracing/perfetto_platform.h" + +#include "base/task/deferred_sequenced_task_runner.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "base/trace_event/trace_event.h" +#include "base/tracing/perfetto_task_runner.h" +#include "base/tracing_buildflags.h" +#include "build/build_config.h" +#include "third_party/perfetto/protos/perfetto/trace/track_event/thread_descriptor.gen.h" + +#if !BUILDFLAG(IS_NACL) +#include "third_party/perfetto/include/perfetto/ext/base/thread_task_runner.h" +#endif + +namespace base { +namespace tracing { + +PerfettoPlatform::PerfettoPlatform(TaskRunnerType task_runner_type) + : task_runner_type_(task_runner_type), + deferred_task_runner_(new DeferredSequencedTaskRunner()), + thread_local_object_([](void* object) { + delete static_cast(object); + }) { + ThreadIdNameManager::GetInstance()->AddObserver(this); +} + +PerfettoPlatform::~PerfettoPlatform() { + ThreadIdNameManager::GetInstance()->RemoveObserver(this); +} + +void PerfettoPlatform::StartTaskRunner( + scoped_refptr task_runner) { + DCHECK_EQ(task_runner_type_, TaskRunnerType::kThreadPool); + DCHECK(!did_start_task_runner_); + deferred_task_runner_->StartWithTaskRunner(task_runner); + did_start_task_runner_ = true; +} + +SequencedTaskRunner* PerfettoPlatform::task_runner() const { + return deferred_task_runner_.get(); +} + +PerfettoPlatform::ThreadLocalObject* +PerfettoPlatform::GetOrCreateThreadLocalObject() { + auto* object = static_cast(thread_local_object_.Get()); + if (!object) { + object = ThreadLocalObject::CreateInstance().release(); + thread_local_object_.Set(object); + } + return object; +} + +std::unique_ptr PerfettoPlatform::CreateTaskRunner( + const CreateTaskRunnerArgs&) { + switch (task_runner_type_) { + case TaskRunnerType::kBuiltin: +#if !BUILDFLAG(IS_NACL) + return std::make_unique( + perfetto::base::ThreadTaskRunner::CreateAndStart()); +#else + DCHECK(false); + return nullptr; +#endif + case TaskRunnerType::kThreadPool: + // We can't create a real task runner yet because the ThreadPool may not + // be initialized. Instead, we point Perfetto to a buffering task runner + // which will become active as soon as the thread pool is up (see + // StartTaskRunner). + return std::make_unique(deferred_task_runner_); + } +} + +std::string PerfettoPlatform::GetCurrentProcessName() { + // TODO(skyostil): Unimplemented since we're not registering producers through + // the client API yet. + return ""; +} + +void PerfettoPlatform::OnThreadNameChanged(const char* name) { +#if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) + // TODO(skyostil): Also capture names for threads which predate tracing being + // initialized. + if (perfetto::Tracing::IsInitialized()) { + auto track = perfetto::ThreadTrack::Current(); + auto desc = track.Serialize(); + desc.mutable_thread()->set_thread_name(name); + perfetto::TrackEvent::SetTrackDescriptor(track, std::move(desc)); + } +#endif // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY) +} + +} // namespace tracing +} // namespace base diff --git a/pool/shard006/C++/0074454_davixcontext.cpp b/pool/shard006/C++/0074454_davixcontext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2469e982c4dd8d2f022f7ade8aec6fe008e5fc95 --- /dev/null +++ b/pool/shard006/C++/0074454_davixcontext.cpp @@ -0,0 +1,197 @@ +/* + * This File is part of Davix, The IO library for HTTP based protocols + * Copyright (C) CERN 2013 + * Author: Adrien Devresse + * + * 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 + * +*/ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace Davix{ + +struct LibPath; + + +static LibPath lib_path; + + +static bool redirCachingDisabled(){ + return ( getenv("DAVIX_DISABLE_REDIRECT_CACHING") != NULL); +} + +/// Implementation f the core logic in davix +struct ContextInternal +{ + ContextInternal(): + _fsess(new SessionFactory()), + _redirectionResolver(new RedirectionResolver(!redirCachingDisabled())), + _hook_list() + { + DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "libdavix path {}, version: {}", getLibPath(), version()); + } + + ContextInternal(const ContextInternal & orig) : + _fsess(new SessionFactory()), + _redirectionResolver(new RedirectionResolver(!redirCachingDisabled())), + _hook_list(orig._hook_list) + { + } + + virtual ~ContextInternal(){} + + // implementation of getSessionFactory + inline SessionFactory* getSessionFactory(){ + return _fsess.get(); + } + + inline RedirectionResolver* getRedirectionResolver() { + return _redirectionResolver.get(); + } + + std::unique_ptr _fsess; + std::unique_ptr _redirectionResolver; + HookList _hook_list; +}; + +/////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////// + + +Context::Context() : + _intern(new ContextInternal()) +{ +} + +Context::Context(const Context &c) : + _intern(new ContextInternal(*(c._intern))){ +} + +Context & Context::operator=(const Context & c){ + if( this != &c ){ + if( _intern != NULL) + delete _intern; + _intern = new ContextInternal(*(c._intern)); + } + return *this; +} + +Context::~Context(){ + delete _intern; +} + +Context* Context::clone(){ + return new Context(*this); +} + + +void Context::setSessionCaching(bool caching){ + _intern->_fsess->setSessionCaching(caching); +} + +bool Context::getSessionCaching() const{ + return _intern->_fsess->getSessionCaching(); +} + +void Context::clearCache() { + _intern->_fsess.reset(new SessionFactory()); +} + +HttpRequest* Context::createRequest(const std::string & url, DavixError** err){ + return new HttpRequest(*this, Uri(url), err); +} + + +HttpRequest* Context::createRequest(const Uri &uri, DavixError **err){ + return new HttpRequest(*this, uri, err); +} + + +void Context::loadModule(const std::string &name){ + if( StrUtil::compare_ncase("grid",name) == 0){ + loadGridProfile(*this); + return; + } + DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_CORE, "No module named {} found", name); +} + +HookList & Context::getHookList(){ + return _intern->_hook_list; +} + +SessionFactory& ContextExplorer::SessionFactoryFromContext(Context & c){ + return *(c._intern->getSessionFactory()); +} + +RedirectionResolver & ContextExplorer::RedirectionResolverFromContext(Context &c) { + return *c._intern->getRedirectionResolver(); +} + +LibPath::LibPath(){ + Dl_info shared_lib_infos; + + // do an address resolution on a local function + // get this resolution to determine davix shared library path at runtime + if( dladdr((void*) &version, &shared_lib_infos) != 0){ + path = shared_lib_infos.dli_fname; + } + +} + +const std::string & version(){ + static const std::string _version = DAVIX_VERSION_STRING; + return _version; +} + +const std::string backendRuntimeVersion() { + curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); + + std::ostringstream ss; + ss << data->version << " " << data->ssl_version; + + return ss.str(); +} + +const std::string backendHeadersVersion() { + curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); + + std::ostringstream ss; + ss << LIBCURL_VERSION; + + return ss.str(); +} + + +const std::string & getLibPath(){ + return lib_path.path; +} + + +} // End Davix diff --git a/pool/shard006/C++/0074457_BtChokeMessageTest.cc b/pool/shard006/C++/0074457_BtChokeMessageTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..2980427ef86357cc355e381724904bddb84cf7db --- /dev/null +++ b/pool/shard006/C++/0074457_BtChokeMessageTest.cc @@ -0,0 +1,145 @@ +#include "BtChokeMessage.h" + +#include + +#include + +#include "bittorrent_helper.h" +#include "MockBtMessageDispatcher.h" +#include "MockBtRequestFactory.h" +#include "Peer.h" +#include "FileEntry.h" +#include "SocketBuffer.h" + +namespace aria2 { + +class BtChokeMessageTest:public CppUnit::TestFixture { + + CPPUNIT_TEST_SUITE(BtChokeMessageTest); + CPPUNIT_TEST(testCreate); + CPPUNIT_TEST(testCreateMessage); + CPPUNIT_TEST(testDoReceivedAction); + CPPUNIT_TEST(testOnSendComplete); + CPPUNIT_TEST(testToString); + CPPUNIT_TEST_SUITE_END(); +private: + +public: + std::shared_ptr peer; + + void setUp() { + peer.reset(new Peer("host", 6969)); + peer->allocateSessionResource(1_k, 1_m); + } + + void testCreate(); + void testCreateMessage(); + void testDoReceivedAction(); + void testOnSendComplete(); + void testToString(); + + class MockBtMessageDispatcher2 : public MockBtMessageDispatcher { + public: + bool doChokedActionCalled; + bool doChokingActionCalled; + public: + MockBtMessageDispatcher2() + : doChokedActionCalled{false}, + doChokingActionCalled{false} + {} + + virtual void doChokedAction() CXX11_OVERRIDE + { + doChokedActionCalled = true; + } + + virtual void doChokingAction() CXX11_OVERRIDE + { + doChokingActionCalled = true; + } + }; + + class MockBtRequestFactory2 : public MockBtRequestFactory { + public: + bool doChokedActionCalled; + public: + MockBtRequestFactory2():doChokedActionCalled{false} {} + + virtual void doChokedAction() CXX11_OVERRIDE + { + doChokedActionCalled = true; + } + }; +}; + + +CPPUNIT_TEST_SUITE_REGISTRATION(BtChokeMessageTest); + +void BtChokeMessageTest::testCreate() { + unsigned char msg[5]; + bittorrent::createPeerMessageString(msg, sizeof(msg), 1, 0); + auto pm = BtChokeMessage::create(&msg[4], 1); + CPPUNIT_ASSERT_EQUAL((uint8_t)0, pm->getId()); + + // case: payload size is wrong + try { + unsigned char msg[6]; + bittorrent::createPeerMessageString(msg, sizeof(msg), 2, 0); + BtChokeMessage::create(&msg[4], 2); + CPPUNIT_FAIL("exception must be thrown."); + } catch(...) { + } + // case: id is wrong + try { + unsigned char msg[5]; + bittorrent::createPeerMessageString(msg, sizeof(msg), 1, 1); + BtChokeMessage::create(&msg[4], 1); + CPPUNIT_FAIL("exception must be thrown."); + } catch(...) { + } +} + +void BtChokeMessageTest::testCreateMessage() { + BtChokeMessage msg; + unsigned char data[5]; + bittorrent::createPeerMessageString(data, sizeof(data), 1, 0); + unsigned char* rawmsg = msg.createMessage(); + CPPUNIT_ASSERT(memcmp(rawmsg, data, 5) == 0); + delete [] rawmsg; +} + +void BtChokeMessageTest::testDoReceivedAction() { + BtChokeMessage msg; + msg.setPeer(peer); + + auto dispatcher = make_unique(); + msg.setBtMessageDispatcher(dispatcher.get()); + auto requestFactory = make_unique(); + msg.setBtRequestFactory(requestFactory.get()); + + msg.doReceivedAction(); + + CPPUNIT_ASSERT(dispatcher->doChokedActionCalled); + CPPUNIT_ASSERT(peer->peerChoking()); +} + +void BtChokeMessageTest::testOnSendComplete() { + BtChokeMessage msg; + msg.setPeer(peer); + + auto dispatcher = make_unique(); + msg.setBtMessageDispatcher(dispatcher.get()); + + auto pu = std::unique_ptr{msg.getProgressUpdate()}; + pu->update(0, true); + + CPPUNIT_ASSERT(dispatcher->doChokingActionCalled); + CPPUNIT_ASSERT(peer->amChoking()); +} + +void BtChokeMessageTest::testToString() { + BtChokeMessage msg; + CPPUNIT_ASSERT_EQUAL(std::string("choke"), msg.toString()); +} + +} // namespace aria2 diff --git a/pool/shard006/C++/0074459_gps_l2_m_pcps_acquisition.cc b/pool/shard006/C++/0074459_gps_l2_m_pcps_acquisition.cc new file mode 100644 index 0000000000000000000000000000000000000000..ae43ea8cd49c24f978ca5facecd1a1435915a792 --- /dev/null +++ b/pool/shard006/C++/0074459_gps_l2_m_pcps_acquisition.cc @@ -0,0 +1,307 @@ +/*! + * \file gps_l2_m_pcps_acquisition.cc + * \brief Adapts a PCPS acquisition block to an AcquisitionInterface for + * GPS L2 M signals + * \authors
    + *
  • Javier Arribas, 2015. jarribas(at)cttc.es + *
+ * + * ------------------------------------------------------------------------- + * + * Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors) + * + * GNSS-SDR is a software defined Global Navigation + * Satellite Systems receiver + * + * This file is part of GNSS-SDR. + * + * GNSS-SDR 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. + * + * GNSS-SDR 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 GNSS-SDR. If not, see . + * + * ------------------------------------------------------------------------- + */ + +#include "gps_l2_m_pcps_acquisition.h" +#include +#include +#include "gps_l2c_signal.h" +#include "GPS_L2C.h" +#include "configuration_interface.h" + + +using google::LogMessage; + +GpsL2MPcpsAcquisition::GpsL2MPcpsAcquisition( + ConfigurationInterface* configuration, std::string role, + unsigned int in_streams, unsigned int out_streams) : + role_(role), in_streams_(in_streams), out_streams_(out_streams) +{ + configuration_ = configuration; + std::string default_item_type = "gr_complex"; + std::string default_dump_filename = "./data/acquisition.dat"; + + LOG(INFO) << "role " << role; + + item_type_ = configuration_->property(role + ".item_type", default_item_type); + //float pfa = configuration_->property(role + ".pfa", 0.0); + + long fs_in_deprecated = configuration_->property("GNSS-SDR.internal_fs_hz", 2048000); + fs_in_ = configuration_->property("GNSS-SDR.internal_fs_sps", fs_in_deprecated); + if_ = configuration_->property(role + ".if", 0); + dump_ = configuration_->property(role + ".dump", false); + blocking_ = configuration_->property(role + ".blocking", true); + doppler_max_ = configuration->property(role + ".doppler_max", 5000); + + bit_transition_flag_ = configuration_->property(role + ".bit_transition_flag", false); + use_CFAR_algorithm_flag_=configuration_->property(role + ".use_CFAR_algorithm", true); //will be false in future versions + + max_dwells_ = configuration_->property(role + ".max_dwells", 1); + + dump_filename_ = configuration_->property(role + ".dump_filename", default_dump_filename); + + //--- Find number of samples per spreading code ------------------------- + code_length_ = round(static_cast(fs_in_) + / (GPS_L2_M_CODE_RATE_HZ / static_cast(GPS_L2_M_CODE_LENGTH_CHIPS))); + + vector_length_ = code_length_; + + if( bit_transition_flag_ ) + { + vector_length_ *= 2; + } + + code_ = new gr_complex[vector_length_]; + + if (item_type_.compare("cshort") == 0 ) + { + item_size_ = sizeof(lv_16sc_t); + } + else + { + item_size_ = sizeof(gr_complex); + } + acquisition_ = pcps_make_acquisition(1, max_dwells_, + doppler_max_, if_, fs_in_, code_length_, code_length_, + bit_transition_flag_, use_CFAR_algorithm_flag_, dump_, blocking_, + dump_filename_, item_size_); + DLOG(INFO) << "acquisition(" << acquisition_->unique_id() << ")"; + + stream_to_vector_ = gr::blocks::stream_to_vector::make(item_size_, vector_length_); + DLOG(INFO) << "stream_to_vector(" << stream_to_vector_->unique_id() << ")"; + + if (item_type_.compare("cbyte") == 0) + { + cbyte_to_float_x2_ = make_complex_byte_to_float_x2(); + float_to_complex_ = gr::blocks::float_to_complex::make(); + } + + channel_ = 0; + threshold_ = 0.0; + doppler_step_ = 0; + gnss_synchro_ = 0; +} + + +GpsL2MPcpsAcquisition::~GpsL2MPcpsAcquisition() +{ + delete[] code_; +} + + +void GpsL2MPcpsAcquisition::set_channel(unsigned int channel) +{ + channel_ = channel; + acquisition_->set_channel(channel_); +} + + +void GpsL2MPcpsAcquisition::set_threshold(float threshold) +{ + float pfa = configuration_->property(role_ + boost::lexical_cast(channel_) + ".pfa", 0.0); + + if(pfa == 0.0) + { + pfa = configuration_->property(role_ + ".pfa", 0.0); + } + if(pfa == 0.0) + { + threshold_ = threshold; + } + else + { + threshold_ = calculate_threshold(pfa); + } + + DLOG(INFO) << "Channel " << channel_ <<" Threshold = " << threshold_; + + acquisition_->set_threshold(threshold_); +} + + +void GpsL2MPcpsAcquisition::set_doppler_max(unsigned int doppler_max) +{ + doppler_max_ = doppler_max; + + acquisition_->set_doppler_max(doppler_max_); +} + + +// Be aware that Doppler step should be set to 2/(3T) Hz, where T is the coherent integration time (GPS L2 period is 0.02s) +// Doppler bin minimum size= 33 Hz +void GpsL2MPcpsAcquisition::set_doppler_step(unsigned int doppler_step) +{ + doppler_step_ = doppler_step; + + acquisition_->set_doppler_step(doppler_step_); +} + + +void GpsL2MPcpsAcquisition::set_gnss_synchro(Gnss_Synchro* gnss_synchro) +{ + gnss_synchro_ = gnss_synchro; + + acquisition_->set_gnss_synchro(gnss_synchro_); +} + + +signed int GpsL2MPcpsAcquisition::mag() +{ + return acquisition_->mag(); +} + + +void GpsL2MPcpsAcquisition::init() +{ + acquisition_->init(); + //set_local_code(); +} + + +void GpsL2MPcpsAcquisition::set_local_code() +{ + + gps_l2c_m_code_gen_complex_sampled(code_, gnss_synchro_->PRN, fs_in_); + + acquisition_->set_local_code(code_); +} + + +void GpsL2MPcpsAcquisition::reset() +{ + acquisition_->set_active(true); +} + +void GpsL2MPcpsAcquisition::set_state(int state) +{ + acquisition_->set_state(state); +} + + + +float GpsL2MPcpsAcquisition::calculate_threshold(float pfa) +{ + //Calculate the threshold + unsigned int frequency_bins = 0; + for (int doppler = static_cast(-doppler_max_); doppler <= static_cast(doppler_max_); doppler += doppler_step_) + { + frequency_bins++; + } + DLOG(INFO) << "Channel " << channel_<< " Pfa = " << pfa; + unsigned int ncells = vector_length_ * frequency_bins; + double exponent = 1.0 / static_cast(ncells); + double val = pow(1.0 - pfa, exponent); + double lambda = double(vector_length_); + boost::math::exponential_distribution mydist (lambda); + float threshold = static_cast(quantile(mydist,val)); + + return threshold; +} + + +void GpsL2MPcpsAcquisition::connect(gr::top_block_sptr top_block) +{ + if (item_type_.compare("gr_complex") == 0) + { + top_block->connect(stream_to_vector_, 0, acquisition_, 0); + } + else if (item_type_.compare("cshort") == 0) + { + top_block->connect(stream_to_vector_, 0, acquisition_, 0); + } + else if (item_type_.compare("cbyte") == 0) + { + top_block->connect(cbyte_to_float_x2_, 0, float_to_complex_, 0); + top_block->connect(cbyte_to_float_x2_, 1, float_to_complex_, 1); + top_block->connect(float_to_complex_, 0, stream_to_vector_, 0); + top_block->connect(stream_to_vector_, 0, acquisition_, 0); + } + else + { + LOG(WARNING) << item_type_ << " unknown acquisition item type"; + } +} + + +void GpsL2MPcpsAcquisition::disconnect(gr::top_block_sptr top_block) +{ + if (item_type_.compare("gr_complex") == 0) + { + top_block->disconnect(stream_to_vector_, 0, acquisition_, 0); + } + else if (item_type_.compare("cshort") == 0) + { + top_block->disconnect(stream_to_vector_, 0, acquisition_, 0); + } + else if (item_type_.compare("cbyte") == 0) + { + // Since a byte-based acq implementation is not available, + // we just convert cshorts to gr_complex + top_block->disconnect(cbyte_to_float_x2_, 0, float_to_complex_, 0); + top_block->disconnect(cbyte_to_float_x2_, 1, float_to_complex_, 1); + top_block->disconnect(float_to_complex_, 0, stream_to_vector_, 0); + top_block->disconnect(stream_to_vector_, 0, acquisition_, 0); + } + else + { + LOG(WARNING) << item_type_ << " unknown acquisition item type"; + } +} + + +gr::basic_block_sptr GpsL2MPcpsAcquisition::get_left_block() +{ + if (item_type_.compare("gr_complex") == 0) + { + return stream_to_vector_; + } + else if (item_type_.compare("cshort") == 0) + { + return stream_to_vector_; + } + else if (item_type_.compare("cbyte") == 0) + { + return cbyte_to_float_x2_; + } + else + { + LOG(WARNING) << item_type_ << " unknown acquisition item type"; + return nullptr; + } +} + + +gr::basic_block_sptr GpsL2MPcpsAcquisition::get_right_block() +{ + return acquisition_; +} + diff --git a/pool/shard006/C++/0074467_DustSystemDensityCalculator.cpp b/pool/shard006/C++/0074467_DustSystemDensityCalculator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a295afea391942c14c6755efe354bfd8ee0467b0 --- /dev/null +++ b/pool/shard006/C++/0074467_DustSystemDensityCalculator.cpp @@ -0,0 +1,70 @@ +/*////////////////////////////////////////////////////////////////// +//// SKIRT -- an advanced radiative transfer code //// +//// © Astronomical Observatory, Ghent University //// +///////////////////////////////////////////////////////////////// */ + +#include +#include "DustSystemDensityCalculator.hpp" +#include "DustDistribution.hpp" +#include "DustGrid.hpp" +#include "DustSystem.hpp" +#include "Random.hpp" + +using namespace std; + +////////////////////////////////////////////////////////////////////// + +DustSystemDensityCalculator::DustSystemDensityCalculator(const DustSystem *ds, int numBodies, int numSamplesPerBody) + : _ds(ds), _dd(ds->dustDistribution()), _grid(ds->dustGrid()), _random(ds->find()), + _numBodies(numBodies), _numSamplesPerBody(numSamplesPerBody), + _extent(_grid->boundingbox()), + _drhov(numBodies), _drho2v(numBodies), + _meanDelta(0), _stddevDelta(0), + _consolidated(false) +{ +} + +////////////////////////////////////////////////////////////////////// + +void DustSystemDensityCalculator::body(size_t n) +{ + int k = _numSamplesPerBody; + while (k--) + { + Position pos = _random->position(_extent); + double rhot = _dd->density(pos); + double rhog = _ds->density(_grid->whichcell(pos)); + double drho = fabs(rhog-rhot); + _drhov[n] += drho; + _drho2v[n] += drho*drho; + } + _drhov[n] /= _numSamplesPerBody; + _drho2v[n] /= _numSamplesPerBody; +} + +////////////////////////////////////////////////////////////////////// + +void DustSystemDensityCalculator::consolidate() +{ + _meanDelta = _drhov.sum()/_numBodies; + _stddevDelta = sqrt(_drho2v.sum()/_numBodies - _meanDelta*_meanDelta); + _consolidated = true; +} + +////////////////////////////////////////////////////////////////////// + +double DustSystemDensityCalculator::meanDelta() +{ + if (!_consolidated) consolidate(); + return _meanDelta; +} + +////////////////////////////////////////////////////////////////////// + +double DustSystemDensityCalculator::stddevDelta() +{ + if (!_consolidated) consolidate(); + return _stddevDelta; +} + +////////////////////////////////////////////////////////////////////// diff --git a/pool/shard006/C++/0074472_image_viewer.cpp b/pool/shard006/C++/0074472_image_viewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68b04515e1036a7ce8718f6b643577414865d6c3 --- /dev/null +++ b/pool/shard006/C++/0074472_image_viewer.cpp @@ -0,0 +1,79 @@ +/* + * Software License Agreement (BSD License) + * + * Point Cloud Library (PCL) - www.pointclouds.org + * Copyright (c) 2011, Willow Garage, Inc. + * Copyright (c) 2012-, Open Perception, Inc. + * + * 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 copyright holder(s) 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 THE + * COPYRIGHT OWNER OR CONTRIBUTORS 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 //fps calculations +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +int +main (int, char ** argv) +{ + pcl::PCDReader reader; + sensor_msgs::PointCloud2 cloud; + reader.read (argv[1], cloud); + + pcl::PointCloud xyz; + pcl::fromROSMsg (cloud, xyz); + + pcl::visualization::ImageViewer depth_image_viewer_; + float* img = new float[cloud.width * cloud.height]; + + for (int i = 0; i < static_cast (xyz.points.size ()); ++i) + img[i] = xyz.points[i].z; + + depth_image_viewer_.showFloatImage (img, + cloud.width, cloud.height, + std::numeric_limits::min (), + // Scale so that the colors look brigher on screen + std::numeric_limits::max () / 10, + true); + depth_image_viewer_.spin (); + return (0); +} diff --git a/pool/shard006/C++/0074477_DisplayListCompositingBuilderTest.cpp b/pool/shard006/C++/0074477_DisplayListCompositingBuilderTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92cc0dc56baab4f54b65b2f87d6919740cf185eb --- /dev/null +++ b/pool/shard006/C++/0074477_DisplayListCompositingBuilderTest.cpp @@ -0,0 +1,49 @@ +// 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 "core/compositing/DisplayListCompositingBuilder.h" + +#include "platform/RuntimeEnabledFeatures.h" +#include + +namespace blink { + +class DisplayListCompositingBuilderTest : public ::testing::Test { +public: + DisplayListCompositingBuilderTest() + : m_originalSlimmingPaintV2Enabled(RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { } + +private: + void SetUp() override + { + ASSERT_TRUE(RuntimeEnabledFeatures::slimmingPaintEnabled()); + RuntimeEnabledFeatures::setSlimmingPaintV2Enabled(true); + } + + void TearDown() override + { + RuntimeEnabledFeatures::setSlimmingPaintV2Enabled(m_originalSlimmingPaintV2Enabled); + } + + bool m_originalSlimmingPaintV2Enabled; +}; + +TEST_F(DisplayListCompositingBuilderTest, BasicTransformPropertyTree) +{ + OwnPtr displayItemList = DisplayItemList::create(); + DisplayListDiff displayListDiff; + displayItemList->commitNewDisplayItems(&displayListDiff); + + DisplayListCompositingBuilder compositingBuilder(*displayItemList, displayListDiff); + CompositedDisplayList compositedDisplayList; + compositingBuilder.build(compositedDisplayList); + + const auto& tree = *compositedDisplayList.transformTree; + ASSERT_EQ(1u, tree.nodeCount()); + EXPECT_TRUE(tree.nodeAt(0).isRoot()); + EXPECT_TRUE(tree.nodeAt(0).matrix.isIdentity()); +} + +} // namespace blink diff --git a/pool/shard006/C++/0074484_simple.cpp b/pool/shard006/C++/0074484_simple.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adcad11f1bbfe55e357e901000311c509c812b3a --- /dev/null +++ b/pool/shard006/C++/0074484_simple.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include "mini_lex.cpp" + +using namespace std; + +void list(); +void term(); +void x(); +void match(int); +void print(char); + +token lookahead; + +void print_char(char c){ + printf("%c ", c); +} + +void print_int(int i){ + printf("%d ", i); +} + +void list(){ + term(); + x(); +} + +void x(){ + if (lookahead.type == PLUS) { + match(PLUS); term(); print_char('+'); x(); + } else if (lookahead.type == MINUS){ + match(MINUS); term(); print_char('-'); x(); + } else if (lookahead.type == EOF){ + printf("\nSuccess.\n"); + } else { + printf("Syntax error on x\n"); + exit(1); + } +} + +void term(){ + if (lookahead.type == NUM) { + print_int(lookahead.value); + match(NUM); + } else { + printf("Syntax error on term\n"); + exit(1); + } +} + +void match(int type){ + if (lookahead.type == type){ + lookahead = next_token(); + } else { + printf("Match error"); + } +} + +int main(){ + input = "123-321+111"; + lookahead = next_token(); + list(); +} diff --git a/pool/shard006/C++/0074486_qatomic_generic_unix.cpp b/pool/shard006/C++/0074486_qatomic_generic_unix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56e40ae98c0a60e510ef698b38afaf66ab26b201 --- /dev/null +++ b/pool/shard006/C++/0074486_qatomic_generic_unix.cpp @@ -0,0 +1,123 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** 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, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#if !defined(Q_OS_SYMBIAN) || (defined(Q_OS_SYMBIAN) && !defined(Q_CC_RVCT)) + +#include "qplatformdefs.h" + +#include + +QT_BEGIN_NAMESPACE +static pthread_mutex_t qAtomicMutex = PTHREAD_MUTEX_INITIALIZER; + +Q_CORE_EXPORT +bool QBasicAtomicInt_testAndSetOrdered(volatile int *_q_value, int expectedValue, int newValue) +{ + bool returnValue = false; + pthread_mutex_lock(&qAtomicMutex); + if (*_q_value == expectedValue) { + *_q_value = newValue; + returnValue = true; + } + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} + +Q_CORE_EXPORT +int QBasicAtomicInt_fetchAndStoreOrdered(volatile int *_q_value, int newValue) +{ + int returnValue; + pthread_mutex_lock(&qAtomicMutex); + returnValue = *_q_value; + *_q_value = newValue; + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} + +Q_CORE_EXPORT +int QBasicAtomicInt_fetchAndAddOrdered(volatile int *_q_value, int valueToAdd) +{ + int returnValue; + pthread_mutex_lock(&qAtomicMutex); + returnValue = *_q_value; + *_q_value += valueToAdd; + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} + +Q_CORE_EXPORT +bool QBasicAtomicPointer_testAndSetOrdered(void * volatile *_q_value, + void *expectedValue, + void *newValue) +{ + bool returnValue = false; + pthread_mutex_lock(&qAtomicMutex); + if (*_q_value == expectedValue) { + *_q_value = newValue; + returnValue = true; + } + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} + +Q_CORE_EXPORT +void *QBasicAtomicPointer_fetchAndStoreOrdered(void * volatile *_q_value, void *newValue) +{ + void *returnValue; + pthread_mutex_lock(&qAtomicMutex); + returnValue = *_q_value; + *_q_value = newValue; + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} + +Q_CORE_EXPORT +void *QBasicAtomicPointer_fetchAndAddOrdered(void * volatile *_q_value, qptrdiff valueToAdd) +{ + void *returnValue; + pthread_mutex_lock(&qAtomicMutex); + returnValue = *_q_value; + *_q_value = reinterpret_cast(returnValue) + valueToAdd; + pthread_mutex_unlock(&qAtomicMutex); + return returnValue; +} +QT_END_NAMESPACE +#endif //!defined(Q_OS_SYMBIAN) && !defined(Q_CC_RVCT) diff --git a/pool/shard006/C++/0074488_kis_sobel_filter.cpp b/pool/shard006/C++/0074488_kis_sobel_filter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f398fb97659e3f16deab73780cf86d45021cfdd7 --- /dev/null +++ b/pool/shard006/C++/0074488_kis_sobel_filter.cpp @@ -0,0 +1,203 @@ +/* + * This file is part of Krita + * + * Copyright (c) 2005 Michael Thaler + * + * ported from Gimp, Copyright (C) 1997 Eiichi Takamori + * original pixelize.c for GIMP 0.54 by Tracy Scott + * + * 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 "kis_sobel_filter.h" + +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "widgets/kis_multi_bool_filter_widget.h" + + +#define MIN(a,b) (((a)<(b))?(a):(b)) + +// void KisSobelFilterConfiguration::fromXML(const QString & s) +// { +// KisFilterConfiguration::fromXML(s); +// m_doHorizontally = getBool( "doHorizontally" ); +// m_doVertically = getBool( "doVertically" ); +// m_keepSign = getBool( "makeOpaque" ); +// } +// +// QString KisSobelFilterConfiguration::toString() +// { +// m_properties.clear(); +// setProperty("doHorizontally", m_doHorizontally); +// setProperty("doVertically", m_doVertically); +// setProperty("keepSign", m_keepSign); +// setProperty("makeOpaque", m_makeOpaque); +// +// return KisFilterConfiguration::toString(); +// } +#include + +KisSobelFilter::KisSobelFilter() : KisFilter(id(), categoryEdgeDetection(), i18n("&Sobel...")) +{ + setSupportsPainting(false); + setSupportsThreading(false); // TODO Sobel doesn't support threading on image with height > 512 +} + + +void KisSobelFilter::prepareRow(KisPaintDeviceSP src, quint8* data, quint32 x, quint32 y, quint32 w, quint32 h) const +{ + if (y > h - 1) y = h - 1; + quint32 pixelSize = src->pixelSize(); + + src->readBytes(data, x, y, w, 1); + + for (quint32 b = 0; b < pixelSize; b++) { + int offset = pixelSize - b; + data[-offset] = data[b]; + data[w * pixelSize + b] = data[(w - 1) * pixelSize + b]; + } +} + +#define RMS(a, b) (sqrt ((qreal)(a) * (a) + (b) * (b))) +#define ROUND(x) ((int) ((x) + 0.5)) + +void KisSobelFilter::processImpl(KisPaintDeviceSP device, + const QRect& applyRect, + const KisFilterConfiguration* configuration, + KoUpdater* progressUpdater + ) const +{ + QPoint srcTopLeft = applyRect.topLeft(); + Q_ASSERT(!device.isNull()); + + //read the filter configuration values from the KisFilterConfiguration object + bool doHorizontal = configuration->getBool("doHorizontally", true); + bool doVertical = configuration->getBool("doVertically", true); + bool keepSign = configuration->getBool("keepSign", true); + bool makeOpaque = configuration->getBool("makeOpaque", true); + + quint32 width = applyRect.width(); + quint32 height = applyRect.height(); + quint32 pixelSize = device->pixelSize(); + + int cost = applyRect.height(); + + /* allocate row buffers */ + quint8* prevRow = new quint8[(width + 2) * pixelSize]; + Q_CHECK_PTR(prevRow); + quint8* curRow = new quint8[(width + 2) * pixelSize]; + Q_CHECK_PTR(curRow); + quint8* nextRow = new quint8[(width + 2) * pixelSize]; + Q_CHECK_PTR(nextRow); + quint8* dest = new quint8[width * pixelSize]; + Q_CHECK_PTR(dest); + + quint8* pr = prevRow + pixelSize; + quint8* cr = curRow + pixelSize; + quint8* nr = nextRow + pixelSize; + + prepareRow(device, pr, srcTopLeft.x(), srcTopLeft.y() - 1, width, height); + prepareRow(device, cr, srcTopLeft.x(), srcTopLeft.y(), width, height); + + quint32 counter = 0; + quint8* d; + quint8* tmp; + qint32 gradient, horGradient, verGradient; + // loop through the rows, applying the sobel convolution + + KisHLineIteratorSP dstIt = device->createHLineIteratorNG(srcTopLeft.x(), srcTopLeft.y(), width); + + for (quint32 row = 0; row < height; row++) { + + // prepare the next row + prepareRow(device, nr, srcTopLeft.x(), srcTopLeft.y() + row + 1, width, height); + d = dest; + + for (quint32 col = 0; col < width * pixelSize; col++) { + int positive = col + pixelSize; + int negative = col - pixelSize; + horGradient = (doHorizontal ? + ((pr[negative] + 2 * pr[col] + pr[positive]) - + (nr[negative] + 2 * nr[col] + nr[positive])) + : 0); + + verGradient = (doVertical ? + ((pr[negative] + 2 * cr[negative] + nr[negative]) - + (pr[positive] + 2 * cr[positive] + nr[positive])) + : 0); + gradient = (qint32)((doVertical && doHorizontal) ? + (ROUND(RMS(horGradient, verGradient)) / 5.66) // always >0 + : (keepSign ? (127 + (ROUND((horGradient + verGradient) / 8.0))) + : (ROUND(qAbs(horGradient + verGradient) / 4.0)))); + + *d++ = gradient; + if (gradient > 10) counter ++; + } + + // shuffle the row pointers + tmp = pr; + pr = cr; + cr = nr; + nr = tmp; + + //store the dest + device->writeBytes(dest, srcTopLeft.x(), row, width, 1); + + if (makeOpaque) { + do { + device->colorSpace()->setOpacity(dstIt->rawData(), OPACITY_OPAQUE_U8, 1); + } while(dstIt->nextPixel()); + dstIt->nextRow(); + } + if (progressUpdater) progressUpdater->setProgress(row / cost); + } + + delete[] prevRow; + delete[] curRow; + delete[] nextRow; + delete[] dest; +} + + +KisConfigWidget * KisSobelFilter::createConfigurationWidget(QWidget* parent, const KisPaintDeviceSP) const +{ + vKisBoolWidgetParam param; + param.push_back(KisBoolWidgetParam(true, i18n("Sobel horizontally"), "doHorizontally")); + param.push_back(KisBoolWidgetParam(true, i18n("Sobel vertically"), "doVertically")); + param.push_back(KisBoolWidgetParam(true, i18n("Keep sign of result"), "keepSign")); + param.push_back(KisBoolWidgetParam(true, i18n("Make image opaque"), "makeOpaque")); + return new KisMultiBoolFilterWidget(id().id(), parent, id().id(), param); +} diff --git a/pool/shard006/C++/0074493_aosim.cc b/pool/shard006/C++/0074493_aosim.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5b1f29169f520c7b523092814315f8912125dad --- /dev/null +++ b/pool/shard006/C++/0074493_aosim.cc @@ -0,0 +1,234 @@ +/* + aosim.cc + Implementation of AnalogOutput simulating an analog output device + + RELACS - Relaxed ELectrophysiological data Acquisition, Control, and Stimulation + Copyright (C) 2002-2015 Jan Benda + + 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. + + RELACS 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 + +namespace relacs { + + +AOSim::AOSim( void ) + : AnalogOutput( "Analog Output Simulation", SimAnalogOutputType ) +{ + initOptions(); +} + + +AOSim::~AOSim( void ) +{ +} + +void AOSim::initOptions() +{ + AnalogOutput::initOptions(); + + addNumber("extref", "dummy description", -1.0); +} + + +int AOSim::open( const string &device ) +{ + Info.clear(); + Settings.clear(); + setDeviceName( "AO Simulation" ); + setDeviceVendor( "RELACS" ); + setDeviceFile( device ); + // external reference: + double extr = number( "extref", -1.0, "V" ); + setExternalReference( extr ); + setInfo(); + return 0; +} + + +int AOSim::open( Device &device ) +{ + Info.clear(); + Settings.clear(); + setDeviceName( "AO Simulation" ); + setDeviceVendor( "RELACS" ); + setDeviceFile( device.deviceIdent() ); + // external reference: + double extr = number( "extref", -1.0, "V" ); + setExternalReference( extr ); + setInfo(); + return 0; +} + + +bool AOSim::isOpen( void ) const +{ + return true; +} + + +void AOSim::close( void ) +{ + Info.clear(); + Settings.clear(); +} + + +int AOSim::stop( void ) +{ + return 0; +} + + +int AOSim::reset( void ) +{ + Settings.clear(); + return 0; +} + + +int AOSim::channels( void ) const +{ + return 4; +} + + +int AOSim::bits( void ) const +{ + return 16; +} + + +double AOSim::maxRate( void ) const +{ + return 500000.0; +} + + +int AOSim::testWriteDevice( OutList &sigs ) +{ + for ( int k=0; k sigs[k].maxValue() ) + sigs[k].addError( DaqError::Overflow ); + } + else { + if ( max > 1.0+1.0e-8 ) + sigs[k].addError( DaqError::Overflow ); + else if ( min < -1.0-1.0e-8 ) + sigs[k].addError( DaqError::Underflow ); + } + } + + if ( ! sigs.success() ) + return -1; + + // success: + setSettings( sigs, -1 ); + return 0; +} + + +int AOSim::convertData( OutList &sigs ) +{ + return sigs.failed() ? -1 : 0; +} + + +int AOSim::startWrite( QSemaphore *sp ) +{ + return 0; +} + + +int AOSim::writeData( void ) +{ + return 0; +} + + +AnalogOutput::Status AOSim::statusUnlocked( void ) const +{ + return Idle; +} + + +int AOSim::error( void ) const +{ + return 0; +} + + +int AOSim::getAISyncDevice( const vector< AnalogInput* > &ais ) const +{ + for ( unsigned int k=0; kdeviceFile().size() > 0 && deviceFile().size() > 0 && + ais[k]->deviceFile()[ais[k]->deviceFile().size()-1] == deviceFile()[deviceFile().size()-1] ) { + return k; + } + } + return -1; +} + + +}; /* namespace relacs */ + diff --git a/pool/shard006/C++/0074494_contentwindow.cpp b/pool/shard006/C++/0074494_contentwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..609afe34f5dc058ea315ef32ca3b48a73a5bbd62 --- /dev/null +++ b/pool/shard006/C++/0074494_contentwindow.cpp @@ -0,0 +1,172 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (info@qt.nokia.com) +** +** +** GNU Lesser General Public License Usage +** +** 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, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** Other Usage +** +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** If you have questions regarding the use of this file, please contact +** Nokia at info@qt.nokia.com. +** +**************************************************************************/ + +#include "contentwindow.h" + +#include "centralwidget.h" +#include "helpviewer.h" +#include "localhelpmanager.h" +#include "openpagesmanager.h" + +#include +#include +#include + +#include +#include + +using namespace Help::Internal; + +ContentWindow::ContentWindow() + : m_contentWidget(0) + , m_expandDepth(-2) +{ + m_contentWidget = (&LocalHelpManager::helpEngine())->contentWidget(); + m_contentWidget->installEventFilter(this); + m_contentWidget->viewport()->installEventFilter(this); + m_contentWidget->setContextMenuPolicy(Qt::CustomContextMenu); + setFocusProxy(m_contentWidget); + + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setMargin(0); + layout->addWidget(m_contentWidget); + + connect(m_contentWidget, SIGNAL(customContextMenuRequested(QPoint)), this, + SLOT(showContextMenu(QPoint))); + connect(m_contentWidget, SIGNAL(linkActivated(QUrl)), this, + SIGNAL(linkActivated(QUrl))); + + QHelpContentModel *contentModel = + qobject_cast(m_contentWidget->model()); + connect(contentModel, SIGNAL(contentsCreated()), this, SLOT(expandTOC())); + + m_contentWidget->setFrameStyle(QFrame::NoFrame); +} + +ContentWindow::~ContentWindow() +{ +} + +bool ContentWindow::syncToContent(const QUrl& url) +{ + QModelIndex idx = m_contentWidget->indexOf(url); + if (!idx.isValid()) + return false; + m_contentWidget->setCurrentIndex(idx); + return true; +} + +void ContentWindow::expandTOC() +{ + if (m_expandDepth > -2) { + expandToDepth(m_expandDepth); + m_expandDepth = -2; + } +} + +void ContentWindow::expandToDepth(int depth) +{ + m_expandDepth = depth; + if (depth == -1) + m_contentWidget->expandAll(); + else + m_contentWidget->expandToDepth(depth); +} + +bool ContentWindow::eventFilter(QObject *o, QEvent *e) +{ + if (m_contentWidget && o == m_contentWidget->viewport() + && e->type() == QEvent::MouseButtonRelease) { + QMouseEvent *me = static_cast(e); + QItemSelectionModel *sm = m_contentWidget->selectionModel(); + if (!me || !sm) + return QWidget::eventFilter(o, e); + + Qt::MouseButtons button = me->button(); + const QModelIndex &index = m_contentWidget->indexAt(me->pos()); + + if (index.isValid() && sm->isSelected(index)) { + if ((button == Qt::LeftButton && (me->modifiers() & Qt::ControlModifier)) + || (button == Qt::MidButton)) { + QHelpContentModel *contentModel = + qobject_cast(m_contentWidget->model()); + if (contentModel) { + QHelpContentItem *itm = contentModel->contentItemAt(index); + if (itm && HelpViewer::canOpenPage(itm->url().path())) + OpenPagesManager::instance().createPage(itm->url()); + } + } else if (button == Qt::LeftButton) { + itemClicked(index); + } + } + } + return QWidget::eventFilter(o, e); +} + +void ContentWindow::showContextMenu(const QPoint &pos) +{ + if (!m_contentWidget->indexAt(pos).isValid()) + return; + + QHelpContentModel *contentModel = + qobject_cast(m_contentWidget->model()); + QHelpContentItem *itm = + contentModel->contentItemAt(m_contentWidget->currentIndex()); + + QMenu menu; + QAction *curTab = menu.addAction(tr("Open Link")); + QAction *newTab = menu.addAction(tr("Open Link as New Page")); + if (!HelpViewer::canOpenPage(itm->url().path())) + newTab->setEnabled(false); + + menu.move(m_contentWidget->mapToGlobal(pos)); + + QAction *action = menu.exec(); + if (curTab == action) + emit linkActivated(itm->url()); + else if (newTab == action) + OpenPagesManager::instance().createPage(itm->url()); +} + +void ContentWindow::itemClicked(const QModelIndex &index) +{ + QHelpContentModel *contentModel = + qobject_cast(m_contentWidget->model()); + + if (contentModel) { + if (QHelpContentItem *itm = contentModel->contentItemAt(index)) { + const QUrl &url = itm->url(); + if (url != CentralWidget::instance()->currentHelpViewer()->source()) + emit linkActivated(itm->url()); + } + } +} diff --git a/pool/shard006/C++/0074501_main.cpp b/pool/shard006/C++/0074501_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18a3923751a1c423a1070e32a1361c92914d2979 --- /dev/null +++ b/pool/shard006/C++/0074501_main.cpp @@ -0,0 +1,245 @@ +/* + * main.cpp + * + * Created on: Nov 16, 2016 + * Author: chao + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "kinect2.h" + +static bool keep_running = true; +static void sigint_handler(int s) { + if (s) + keep_running = false; +} + +template +struct PCLCloud { + typename pcl::PointCloud::Ptr ptr { new pcl::PointCloud() }; + typename pcl::visualization::PointCloudColorHandlerRGBField rgb { + ptr }; + pcl::PointCloud::Ptr normals_ptr { new pcl::PointCloud< + pcl::Normal> }; + + cv::Mat rgb_mat { }; + cv::Mat depth_mat { }; + + std::string cloud_name { "PCL Cloud" }; + std::string img_name { "PCL Image" }; + +}; + +struct ProgramOptions { + bool exit { false }; + + std::string calibration_image { "calibration_img.png" }; + +}; + +ProgramOptions read_args(int argc, char ** argv) { + boost::program_options::options_description desc { + "Usage: holospace [options...]\n" + "Options:" }; + desc.add_options()("help", "Shows this help message")("calibration-image", + boost::program_options::value(), + "Calibration image file used to calibrate cameras for registration"); + + boost::program_options::variables_map variables_map { }; + boost::program_options::store( + boost::program_options::parse_command_line(argc, argv, desc), + variables_map); + boost::program_options::notify(variables_map); + + ProgramOptions program_options { }; + + if (variables_map.count("help")) { + std::cout << desc << std::endl; + program_options.exit = true; + } + + if (variables_map.count("calibration-image")) + program_options.calibration_image = + variables_map["calibration-image"].as(); + + return program_options; +} + +int main(int argc, char ** argv) { + signal(SIGINT, sigint_handler); + ProgramOptions program_options { read_args(argc, argv) }; + + if (program_options.exit) + return 1; + + // Kinect2DeviceFactory initialization + device::Kinect2DeviceFactory k2_factory { }; + + std::vector> device_ptrs { + k2_factory.create_devices() }; + + size_t num_devices { device_ptrs.size() }; + if (num_devices == 0) { + printf("Failed to detect any connected devices. Exiting.\n"); + return 0; + } else { + printf("Detected %lu devices...\n", device_ptrs.size()); + for (auto device : device_ptrs) + printf("Device %s\n", device->get_serial_number().c_str()); + } + + std::vector> > pcl_cloud_ptrs { + num_devices, nullptr }; + + for (size_t i { 0 }; i < num_devices; ++i) { + auto device_ptr = device_ptrs.at(i); + // TODO: Surround with TRY/CATCH + device_ptr->start(); + + if (device_ptr->started()) { + std::shared_ptr> pcl_cloud_ptr { + std::make_shared>() }; + pcl_cloud_ptr->cloud_name.append(" " + i); + pcl_cloud_ptr->img_name.append(" " + i); + pcl_cloud_ptrs.at(i) = pcl_cloud_ptr; + } + } + +// Pre-processing initialization + pcl::IntegralImageNormalEstimation ne { }; + ne.setNormalEstimationMethod(ne.COVARIANCE_MATRIX); + ne.setMaxDepthChangeFactor(0.02f); + ne.setNormalSmoothingSize(10.0f); + +// pcl::FPFHEstimationOMP fpfh { }; +// pcl::search::KdTree::Ptr tree { new pcl::search::KdTree< +// pcl::PointXYZRGB> }; +// fpfh.setSearchMethod(tree); +// pcl::PointCloud::Ptr fpfhs { new pcl::PointCloud< +// pcl::FPFHSignature33> }; +// fpfh.setRadiusSearch(0.05f); + +// Visualizer initialization + std::vector visualizer_handles(static_cast(num_devices) << 1, 0); + printf("Visualizer Handle Size %zu\n", visualizer_handles.size()); + std::shared_ptr visualizer { + new pcl::visualization::PCLVisualizer("Cloud Visualizer") }; + + visualizer->addCoordinateSystem(1.0); + visualizer->initCameraParameters(); + + for (size_t i { 0 }; i < num_devices; ++i) { + int & cloud_visualizer_handle { visualizer_handles.at(i) }; + int & img_visualizer_handle { visualizer_handles.at(i + num_devices) }; + + visualizer->createViewPort(static_cast(i) / num_devices, 0.5, + static_cast(i + 1) / num_devices, 1.0, + cloud_visualizer_handle); + visualizer->createViewPort(static_cast(i) / num_devices, 0.0, + static_cast(i + 1) / num_devices, 0.5, + img_visualizer_handle); + visualizer->setBackgroundColor(0, 0, 0, cloud_visualizer_handle); + visualizer->setBackgroundColor(0, 0, 0, img_visualizer_handle); + + std::shared_ptr> pcl_cloud_ptr { + pcl_cloud_ptrs.at(i) }; + + visualizer->addPointCloud(pcl_cloud_ptr->ptr, pcl_cloud_ptr->rgb, + pcl_cloud_ptr->cloud_name, cloud_visualizer_handle); + visualizer->addPointCloud(pcl_cloud_ptr->ptr, pcl_cloud_ptr->rgb, + pcl_cloud_ptr->img_name, img_visualizer_handle); + visualizer->setPointCloudRenderingProperties( + pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, + pcl_cloud_ptr->cloud_name); + visualizer->setPointCloudRenderingProperties( + pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, + pcl_cloud_ptr->img_name); + } + + while (keep_running) { + std::chrono::high_resolution_clock::time_point start { + std::chrono::high_resolution_clock::now() }; + + for (size_t i { 0 }; i < num_devices; ++i) { + std::shared_ptr device_ptr { device_ptrs.at( + i) }; + std::shared_ptr> pcl_cloud_ptr { + pcl_cloud_ptrs.at(i) }; + + if (device_ptr->started() && pcl_cloud_ptr) { + device_ptr->read_cloud(pcl_cloud_ptr->ptr, + pcl_cloud_ptr->rgb_mat, pcl_cloud_ptr->depth_mat); + +// ne.setInputCloud(cloud_1_ptr); +// ne.compute(*normals_1); + } + } + + // TODO: Figure out how to extract points via indices. Maybe applicable to the voxel filter, which would be very handy. +// std::vector indices { }; +// pcl::removeNaNNormalsFromPointCloud(*normals_1, *normals_1, indices); + +// for(size_t i = 0; i < normals_1->points.size(); i++) +// { +// if(!pcl::isFinite(normals_1->points[i])) +// { +// PCL_WARN("normals[%zu] is not finite\n", i); +// break; +// } +// } + +// fpfh.setInputCloud(cloud_1_ptr); +// fpfh.setInputNormals(normals_1); +// fpfh.compute(*fpfhs); + + std::chrono::high_resolution_clock::time_point end { + std::chrono::high_resolution_clock::now() }; + double duration { std::chrono::duration_cast( + (end - start)).count() / 1000000.0 }; + printf("Elapsed time: %.3f\n", duration); + + for (size_t i { 0 }; i < num_devices; ++i) { + std::shared_ptr device_ptr { device_ptrs.at( + i) }; + std::shared_ptr> pcl_cloud_ptr { + pcl_cloud_ptrs.at(i) }; + + if (device_ptr->started() && pcl_cloud_ptr) { + pcl::PointCloud::Ptr cloud_ptr { + pcl_cloud_ptr->ptr }; + visualizer->updatePointCloud( + pcl_cloud_ptr->ptr, pcl_cloud_ptr->rgb, + pcl_cloud_ptr->cloud_name); + + for (auto itr { cloud_ptr->points.begin() }; + itr != cloud_ptr->points.end(); ++itr) + itr->z = 0; + + visualizer->updatePointCloud( + pcl_cloud_ptr->ptr, pcl_cloud_ptr->rgb, + pcl_cloud_ptr->img_name); + } + } + + visualizer->spinOnce(); + } + + for (auto itr { device_ptrs.begin() }; itr != device_ptrs.end(); ++itr) { + (*itr)->stop(); + } +} + diff --git a/pool/shard006/C++/0074502_TerrainRayWalker.cpp b/pool/shard006/C++/0074502_TerrainRayWalker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..638977bab7295a23cb7f135929c702258a824097 --- /dev/null +++ b/pool/shard006/C++/0074502_TerrainRayWalker.cpp @@ -0,0 +1,131 @@ +#include "TerrainRayWalker.h" + +#include "Matrix4.h" +#include "Scenery.h" +#include "SoftwareRenderer.h" +#include "TerrainDefinition.h" +#include "TerrainRenderer.h" +#include "TexturesDefinition.h" +#include "TexturesRenderer.h" +#include + +TerrainRayWalker::TerrainRayWalker(SoftwareRenderer *renderer) : renderer(renderer) { + setQuality(0.5); +} + +void TerrainRayWalker::setQuality(double displacement_safety, double minimal_step, double maximal_step, + double step_factor, double max_distance, double escape_step) { + this->displacement_safety = displacement_safety; + this->minimal_step = minimal_step; + this->maximal_step = maximal_step; + this->step_factor = step_factor; + this->max_distance = max_distance; + this->escape_step = escape_step; +} + +void TerrainRayWalker::setQuality(double factor) { + setQuality(0.2 + 0.8 * factor, 1.0 / (factor * factor * 30.0 + 1.0), 50.0 / (factor * 10.0 + 1.0), + 1.0 / (factor * 10.0 + 1.0), 10.0 + factor * 200.0, factor * factor * 100.0); +} + +void TerrainRayWalker::update() { + TerrainDefinition *terrain = renderer->getScenery()->getTerrain(); + HeightInfo info = terrain->getHeightInfo(); + + TexturesDefinition *textures = renderer->getScenery()->getTextures(); + displacement_base = textures->getMaximalDisplacement(); + + ymin = info.min_height - displacement_base; + ymax = info.max_height + displacement_base; +} + +static inline Vector3 _getShiftAxis(const Vector3 &direction) { + if (fabs(direction.y) > 0.99) { + // When the ray is vertical, we choose an arbitrary shift axis + return VECTOR_NORTH; + } else { + return VECTOR_UP.crossProduct(direction); + } +} + +bool TerrainRayWalker::startWalking(const Vector3 &start, Vector3 direction, double escape_angle, + TerrainHitResult &result) { + auto terrain_renderer = renderer->getTerrainRenderer(); + auto textures_renderer = renderer->getTexturesRenderer(); + auto textures_definition = renderer->getScenery()->getTextures(); + TerrainRenderer::TerrainResult terrain_result; + Vector3 cursor, displaced; + double diff; + Matrix4 shift_matrix; + double shift_step = 0.0; + + Vector3 previous_cursor = start; + bool hit = false; + double step_length = minimal_step; + double walked_length = 0.0; + + result.escape_angle = 0.0; + if (escape_angle != 0.0) { + // Prepare escape + shift_step = escape_angle / escape_step; + shift_matrix = Matrix4::newRotateAxis(-shift_step, _getShiftAxis(direction)); + } + + do { + // Perform a step + cursor = previous_cursor.add(direction.scale(step_length)); + + // Get the terrain info at end (without textures displacement) + terrain_result = terrain_renderer->getResult(cursor.x, cursor.z, true); + diff = cursor.y - terrain_result.location.y; + + // If we are very under the terrain, consider a hit + if (diff < -displacement_base * displacement_safety) { + hit = true; + } + + // If we are close enough to the terrain, apply displacement + else if (diff < displacement_base * displacement_safety) { + displaced = + textures_renderer->displaceTerrain(textures_definition, terrain_result.location, terrain_result.normal); + diff = cursor.y - displaced.y; + hit = diff < 0.0; + } + + if (hit) { + // TODO Refine the hit with dichotomy at high quality + /*if (renderer->render_quality > 7) + { + cursor = refineHit(previous_cursor, cursor, step_length); + }*/ + + // Shift ray to escape terrain + if (escape_angle != 0.0) { + result.escape_angle += shift_step; + if (result.escape_angle > escape_angle) { + // Too much shifted to escape, make it a hit + result.escape_angle = 0.0; + return true; + } + hit = false; + direction = shift_matrix.multPoint(direction); + previous_cursor = start.add(shift_matrix.multPoint(previous_cursor.sub(start))); + } + + result.hit_location = cursor; + } else { + // Prepare next step + previous_cursor = cursor; + walked_length += step_length; + + step_length = diff * step_factor; + if (step_length < minimal_step) { + step_length = minimal_step; + } else if (step_length > maximal_step) { + step_length = maximal_step; + } + } + } while (not hit and cursor.y < ymax and walked_length < max_distance); + + return hit or result.escape_angle > 0.0; +} diff --git a/pool/shard006/C++/0074509_window_cerrar.cpp b/pool/shard006/C++/0074509_window_cerrar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b35e0fc2bf244a33dc4ba66e6315b7991a5a0da9 --- /dev/null +++ b/pool/shard006/C++/0074509_window_cerrar.cpp @@ -0,0 +1,57 @@ +#include +#include +#include + +int main(int argc, char **argv){ + + ALLEGRO_DISPLAY *display = NULL; + ALLEGRO_EVENT_QUEUE *event_queue = NULL; + + al_init(); + +/* if(!al_init()) { + fprintf(stderr, "failed to initialize allegro!\n"); + return -1; + }*/ + + display = al_create_display(640, 480); +/* if(!display) { + fprintf(stderr, "failed to create display!\n"); + return -1; + }*/ + + event_queue = al_create_event_queue(); +/* if(!event_queue) { + fprintf(stderr, "failed to create event_queue!\n"); + al_destroy_display(display); + return -1; + }*/ + + al_register_event_source(event_queue, al_get_display_event_source(display)); + + al_clear_to_color(al_map_rgb(0,0,0)); + + al_flip_display(); + + while(1) + { + ALLEGRO_EVENT ev; + ALLEGRO_TIMEOUT timeout; + al_init_timeout(&timeout, 0.06); + + bool get_event = al_wait_for_event_until(event_queue, &ev, &timeout); + + if(get_event && ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { + break; + } + + al_clear_to_color(al_map_rgb(0,0,0)); + al_flip_display(); + } + + al_destroy_display(display); + al_destroy_event_queue(event_queue); + + return 0; +} + diff --git a/pool/shard006/C++/0074511_bandwidth.cc b/pool/shard006/C++/0074511_bandwidth.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e4b7adaa57cde2830cfa3dec55f69624037efae --- /dev/null +++ b/pool/shard006/C++/0074511_bandwidth.cc @@ -0,0 +1,88 @@ +// roundtrip.cc : tests roundtrip rpc. +// by: allison morris + +#include "basic_service.h" +#include "measure.h" + +int run_client(std::string); +int run_server(std::string); + +// data to be passed to measurement functions. +struct message_data { + tiny_message request; + tiny_message response; + basic_service::Stub* stub; +}; + +// predicate function executed on each iteration of the tester. +struct roundtrip { + void run(message_data& data) { + grpc::ClientContext ctx; + data.stub->int_echo(&ctx, data.request, &data.response); + data.request.set_data(data.response.data()); + } +}; + +int main(int argc, char** argv) { + if (argc < 3) { + std::cerr << "Need SERVER or CLIENT followed by ADDRESS.\n"; + return 1; + } + + std::string mode = argv[1]; + if (mode == "SERVER") { + return run_server(argv[2]); + } else if (mode == "CLIENT") { + return run_client(argv[2]); + } else { + std::cerr << "Need SERVER or CLIENT followed by ADDRESS.\n"; + return 1; + } +} + + + +// runs the client side of the test. +int run_client(std::string address) { + std::shared_ptr channel = grpc::CreateChannel(address, grpc::InsecureCredentials()); + std::shared_ptr stub = basic_service::NewStub(channel); + clocker::mode mode = clocker::clock_gettime; + int count = basic_service_impl::count; + + // create clock. + clocker clk; + std::cout << "client\n"; + + grpc::ClientContext context; + bulk_message msg; + tiny_message req; + clk.begin(); + std::unique_ptr> reader = + stub->pull_list(&context, req); + while (reader->Read(&msg)) { } + grpc::Status stat = reader->Finish(); + clk.end(); + + std::cout << std::left << std::setw(60) << std::setfill(' ') + << "streaming bandwidth" << (count * 2048 * 8 / 1024) << " " << ((double)clk.difference() / 1000000000) << "\n"; + //std::cout << count * 65 * 8 << " " << clk.difference() << "\n"; + //clk.dump_cgt(); + return 0; +} + +// runs the server side of the test. +int run_server(std::string address) { + grpc::ServerBuilder builder; + basic_service_impl service; + + // start service. + builder.AddListeningPort(address, grpc::InsecureServerCredentials()); + builder.RegisterService(&service); + + // launch. + std::cout << "Launching server on " << address << std::endl; + builder.BuildAndStart()->Wait(); + + // note: this is never reached. + return 0; +} diff --git a/pool/shard006/C++/0074516_maxrectsalgorithm.cpp b/pool/shard006/C++/0074516_maxrectsalgorithm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7fb628ff1957d642d771435e5c1bcc6592522f5 --- /dev/null +++ b/pool/shard006/C++/0074516_maxrectsalgorithm.cpp @@ -0,0 +1,165 @@ + +#include "maxrectsalgorithm.h" + +#include + +#include "imagenode.h" + +namespace c2d::gen +{ + MaxRectsAlgorithm::MaxRectsAlgorithm(int width, int height): + mWidth(width), + mHeight(height), + mFreeRects() + { + init(); + } + + void MaxRectsAlgorithm::init() + { + RectI n(0, 0, mWidth, mHeight); + mFreeRects.push_back(n); + } + + void MaxRectsAlgorithm::insert(std::vector& images, std::vector& used) + { + while ( !images.empty() ) + { + FindInfo bestImage; + size_t bestImageIndex = images.size(); + + for ( size_t index = 0; index < images.size(); index++ ) + { + ImageNode& image = images[index]; + + FindInfo info; + if ( findPositionForNewNode(image, info) ) + { + if ( info.bestShortSideFit < bestImage.bestShortSideFit + || (info.bestShortSideFit == bestImage.bestShortSideFit && info.bestLongSideFit < bestImage.bestLongSideFit) ) + { + bestImage = info; + bestImageIndex = index; + } + } + } + + if ( bestImageIndex == images.size() ) + { + // There is no image anymore that fits in this atlas, + // continue with next sheet. + return; + } + + insertRect(bestImage); + + ImageNode& image = images[bestImageIndex]; + image.mCoords = bestImage.bestNode; + image.mRotated = bestImage.rotated; + + used.push_back(std::move(image)); + images.erase(images.begin() + bestImageIndex); + } + } + + bool MaxRectsAlgorithm::findPositionForNewNode(const ImageNode& node, FindInfo& info) + { + for ( size_t index = 0; index < mFreeRects.size(); index++ ) + { + const RectI& rect = mFreeRects[index]; + + if ( rect.width() >= node.width() && rect.height() >= node.height() ) + { + int leftoverHoriz = rect.width() - node.width(); + int leftoverVert = rect.height() - node.height(); + int shortSideFit = std::min(leftoverHoriz, leftoverVert); + int longSideFit = std::max(leftoverHoriz, leftoverVert); + + if ( shortSideFit < info.bestShortSideFit + || (shortSideFit == info.bestShortSideFit && longSideFit < info.bestLongSideFit) ) + { + info.bestNode.set(rect.left, rect.top, node.width(), node.height()); + info.freerectIndex = index; + info.bestShortSideFit = shortSideFit; + info.bestLongSideFit = longSideFit; + info.rotated = false; + } + } + + if ( rect.width() >= node.height() && rect.height() >= node.width() ) + { + int flippedLeftoverHoriz = rect.width() - node.height(); + int flippedLeftoverVert = rect.height() - node.width(); + int flippedShortSideFit = std::min(flippedLeftoverHoriz, flippedLeftoverVert); + int flippedLongSideFit = std::max(flippedLeftoverHoriz, flippedLeftoverVert); + + if ( flippedShortSideFit < info.bestShortSideFit + || (flippedShortSideFit == info.bestShortSideFit && flippedLongSideFit < info.bestLongSideFit) ) + { + info.bestNode.set(rect.left, rect.top, node.height(), node.width()); + info.freerectIndex = index; + info.bestShortSideFit = flippedShortSideFit; + info.bestLongSideFit = flippedLongSideFit; + info.rotated = true; + } + } + } + + return info.freerectIndex != -1; + } + + void MaxRectsAlgorithm::insertRect(const FindInfo& info) + { + if ( info.bestNode.height() == 99 ) + { + int aap = 53; + } + mFreeRects.reserve(mFreeRects.size() + 2); + const RectI& freerect = mFreeRects[info.freerectIndex]; + + splitFreeNode(freerect, info.bestNode); + + mFreeRects.erase(mFreeRects.begin() + info.freerectIndex); + } + + bool MaxRectsAlgorithm::splitFreeNode(const RectI& freeNode, const RectI& usedNode) + { + if ( usedNode.width() < freeNode.width() ) + { + RectI node = freeNode; + node.left = freeNode.left + usedNode.width(); + node.bottom = freeNode.top + usedNode.height(); + mFreeRects.push_back(node); + } + + if ( usedNode.height() < freeNode.height() ) + { + RectI node = freeNode; + node.top = freeNode.top + usedNode.height(); + mFreeRects.push_back(node); + } + return true; + } + + void MaxRectsAlgorithm::pruneFreeList() + { + /// Go through each pair and remove any rectangle that is redundant. + for ( size_t i = 0; i < mFreeRects.size(); ++i ) + { + for ( size_t j = i + 1; j < mFreeRects.size(); ++j ) + { + if ( mFreeRects[j].contains(mFreeRects[i]) ) + { + mFreeRects.erase(mFreeRects.begin() + i); + --i; + break; + } + if ( mFreeRects[i].contains(mFreeRects[j]) ) + { + mFreeRects.erase(mFreeRects.begin() + j); + --j; + } + } + } + } +} diff --git a/pool/shard006/C++/0074520_SVIParticlePropertyAnimation.cpp b/pool/shard006/C++/0074520_SVIParticlePropertyAnimation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71fa2ada7389b2b924dd3fa03d81e4394bebf267 --- /dev/null +++ b/pool/shard006/C++/0074520_SVIParticlePropertyAnimation.cpp @@ -0,0 +1,240 @@ +#include "SVIParticlePropertyAnimation.h" +#include "../Slide/SVIBeamedSlide.h" +#include "./Interpolator/SVIInterpolator.h" +#include "../Mathematics/SVIQuaternion.h" +#include "../Particle/SVIParticles.h" +#include "../Particle/SVIParticleEffect.h" +#include "../Particle/SVIKeyFrameParticleEffect.h" + +namespace SVI { + +const static SVIBool DEBUG = SVIFALSE; + +#define SETTING_PROPERTY_VALUE(PropertyType, DataType) \ + case PropertyType : \ + { \ + if( mFromValue == NULL ) \ + mFromValue = (SVIPVoid*)new DataType(); \ + \ + if( mToValue == NULL ) \ + mToValue = (SVIPVoid*)new DataType(); \ + \ + mFrom.get( *((DataType*)mFromValue) ); \ + mTo.get( *((DataType*)mToValue) ); \ + } break + + +#define FREE_PROPERTY_VALUE(PropertyType, DataType) \ + case PropertyType : \ + { \ + DataType* from = (DataType*)mFromValue; \ + DataType* to = (DataType*)mToValue; \ + SVI_SVIFE_DELETE(from); \ + SVI_SVIFE_DELETE(to); \ + } break + +#define CALCULATE_CURRENT_VALUE(PropertyType, Name, ratio) \ + case PropertyType : \ + calculate##Name(ratio); \ + break + + const SVIChar* SVIParticlePropertyAnimation::mParticlePropertyAnimationTypeString[] = { + "PARTICLE_NONE=0", + "PARTICLE_SCALE", + "PARTICLE_COLOR", + "PARTICLE_POSITION", + "PARTICLE_EFFECT_SCALE", + "PARTICLE_EFFECT_COLOR", + "PARTICLE_EFFECT_POSITION", + "PARTICLE_EFFECT_GENERATOR", + "PARTICLE_PROPERTY_ANI_COUNT" + }; + + const SVIChar* SVIParticlePropertyAnimation::getPropertyTypeString(ParticlePropertyAnimationType type) { + return mParticlePropertyAnimationTypeString[type]; + } + + SVIParticlePropertyAnimation::SVIParticlePropertyAnimation(SVIGLSurface* saGLSurface):SVIAnimation(saGLSurface) { + mParticlePropertyAnimationType = PARTICLE_NONE; + mFromValue = NULL; + mToValue = NULL; + mParticleEffect = NULL; + mParticles = NULL; + } + + SVIParticlePropertyAnimation::SVIParticlePropertyAnimation(ParticlePropertyAnimationType type, SVIGLSurface* saGLSurface):SVIAnimation(saGLSurface) { + mParticlePropertyAnimationType = type; + initData(); + } + + SVIParticlePropertyAnimation::~SVIParticlePropertyAnimation() { + deInitData(); + mParticlePropertyAnimationType = PARTICLE_NONE; + } + + void SVIParticlePropertyAnimation::updateInfo(SVIUInt time) { + if( getStatus() == IDLE ) { + + initData(); + startAnimation(time); + if( mListener != NULL ) + mListener->onAnimationStart(this); + } + + if( getStatus() == ANIMATING ) { + + mTimeRatio = mInterpolator->getTimeInterpolation(time); + if( mListener != NULL ) { + SVIUInt currentCount = mInterpolator->getCurrentCount(); + // currentCount is elapsedTime / duration. So current means current animation index. + // and RepeatCount means total count of playing animation. + // Default RepeatCount is 1, because animation must play once. + if( mRepeatCount > 1 && mCurrentCount != currentCount && mRepeatCount != currentCount ) { + //LOGE("Current repeat count %d, Interpolator repeatCount %d", mCurrentCount, currentCount); + mListener->onAnimationRepeat(this); + } + mCurrentCount = currentCount; + } + } + } + + void SVIParticlePropertyAnimation::initData() { + switch(mParticlePropertyAnimationType) { + SETTING_PROPERTY_VALUE(PARTICLE_SCALE, SVIVector3); + SETTING_PROPERTY_VALUE(PARTICLE_COLOR, SVIColor); + SETTING_PROPERTY_VALUE(PARTICLE_POSITION, SVIVector3); + SETTING_PROPERTY_VALUE(PARTICLE_EFFECT_SCALE, SVIVector3); + SETTING_PROPERTY_VALUE(PARTICLE_EFFECT_COLOR, SVIColor); + SETTING_PROPERTY_VALUE(PARTICLE_EFFECT_POSITION, SVIVector3); + SETTING_PROPERTY_VALUE(PARTICLE_EFFECT_GENERATOR, SVIVector3); + } + + } + + void SVIParticlePropertyAnimation::deInitData() { + switch(mParticlePropertyAnimationType) { + FREE_PROPERTY_VALUE(PARTICLE_SCALE, SVIVector3); + FREE_PROPERTY_VALUE(PARTICLE_COLOR, SVIColor); + FREE_PROPERTY_VALUE(PARTICLE_POSITION, SVIVector3); + FREE_PROPERTY_VALUE(PARTICLE_EFFECT_SCALE, SVIVector3); + FREE_PROPERTY_VALUE(PARTICLE_EFFECT_COLOR, SVIColor); + FREE_PROPERTY_VALUE(PARTICLE_EFFECT_POSITION, SVIVector3); + FREE_PROPERTY_VALUE(PARTICLE_EFFECT_GENERATOR, SVIVector3); + } + + mFromValue = NULL; + mToValue = NULL; + } + + void SVIParticlePropertyAnimation::calculateAndApply(const SVIFloat& ratio) { + + DEBUG_CHECK_LOGI("SVIParticlePropertyAnimation::calculateAndApply animation type:%d, ratio:%f", mParticlePropertyAnimationType, ratio); + switch(mParticlePropertyAnimationType) { + CALCULATE_CURRENT_VALUE(PARTICLE_SCALE, ParticleScale, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_COLOR, ParticleColor, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_POSITION, ParticlePosition, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_EFFECT_SCALE, ParticleEffectScale, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_EFFECT_COLOR, ParticleEffectColor, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_EFFECT_POSITION, ParticleEffectPosition, ratio); + CALCULATE_CURRENT_VALUE(PARTICLE_EFFECT_GENERATOR, ParticleEffectGenerator, ratio); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleScale(const SVIFloat& ratio) { + SVIVector3& from = *(SVIVector3*)(mFromValue); + SVIVector3& to = *(SVIVector3*)(mToValue); + + SVIVector3 dPoint = calculateCurrentValue(from, to, ratio); + + if( mParticles != NULL ) { + mParticles->setChangeScale(dPoint); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleColor(const SVIFloat& ratio) { + SVIColor& from = *(SVIColor*)(mFromValue); + SVIColor& to = *(SVIColor*)(mToValue); + + SVIColor dColor = calculateCurrentValue(from, to, ratio); + + if( mParticles != NULL ) { + mParticles->setChangeColor(dColor); + } + } + + + void SVIParticlePropertyAnimation::calculateParticlePosition(const SVIFloat& ratio) { + SVIVector3& from = *(SVIVector3*)(mFromValue); + SVIVector3& to = *(SVIVector3*)(mToValue); + + SVIVector3 dPoint = calculateCurrentValue(from, to, ratio); + + if( mParticles != NULL ) { + mParticles->setChangePosition(dPoint); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleEffectScale(const SVIFloat& ratio) { + SVIVector3& from = *(SVIVector3*)(mFromValue); + SVIVector3& to = *(SVIVector3*)(mToValue); + + SVIVector3 dPoint = calculateCurrentValue(from, to, ratio); + + if( mParticleEffect != NULL ) { + mParticleEffect->setScale(dPoint); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleEffectColor(const SVIFloat &ratio) { + SVIColor& from = *(SVIColor*)(mFromValue); + SVIColor& to = *(SVIColor*)(mToValue); + + SVIColor dColor = calculateCurrentValue(from, to, ratio); + + if( mParticleEffect != NULL ) { + mParticleEffect->setColor(dColor); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleEffectPosition(const SVIFloat& ratio) { + SVIVector3& from = *(SVIVector3*)(mFromValue); + SVIVector3& to = *(SVIVector3*)(mToValue); + + SVIVector3 dPoint = calculateCurrentValue(from, to, ratio); + + if( mParticleEffect != NULL ) { + mParticleEffect->setPosition(dPoint); + } + } + + + void SVIParticlePropertyAnimation::calculateParticleEffectGenerator(const SVIFloat& ratio) { + SVIVector3& from = *(SVIVector3*)(mFromValue); + SVIVector3& to = *(SVIVector3*)(mToValue); + + SVIVector3 dPoint = calculateCurrentValue(from, to, ratio); + + if( mParticleEffect != NULL ) { + ( (SVIKeyFrameParticleEffect*)mParticleEffect )->setGeneratorPosition(dPoint); + } + } + + + void SVIParticlePropertyAnimation::copy(const SVIParticlePropertyAnimation* rhs) { + SVIAnimation::copy(rhs); + + mParticlePropertyAnimationType = rhs->mParticlePropertyAnimationType; + mFrom = rhs->mFrom; + mTo = rhs->mTo; + mParticles = rhs->mParticles; + mParticleEffect = rhs->mParticleEffect; + deInitData(); + initData(); + } + +} \ No newline at end of file diff --git a/pool/shard006/C++/0074523_main.cpp b/pool/shard006/C++/0074523_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fddf5836dc3c77a3b836db17ef34661144add96c --- /dev/null +++ b/pool/shard006/C++/0074523_main.cpp @@ -0,0 +1,105 @@ +/* + +Copyright (C) 2009 Angel (angel.d.death@gmail.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 included (GNU.txt) 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 "stdafx.h" +#include "mm_map.h" +#include "odmmap.h" + +//float fov = 90; +float m_speed = 0.12; +float speed = 1200; + +int zFar = 8196*2; + +void Game_Init() +{ + Timer.reset( new aeTimer() ); + Input.Init(); + LodManager.AddLod("data/bitmaps.lod"); + LodManager.AddLod("data/games.lod"); + LodManager.AddLod("data/icons.lod"); + LodManager.AddLod("data/events.lod"); + LodManager.AddLod("data/sprites.lod"); + LodManager.AddLod("data/EnglishD.lod"); + LodManager.AddLod("data/EnglishT.lod"); + GL_Init(); +} + +void GL_Shutdown(); +void Game_Shutdown() +{ + Input.Shutdown(); + GL_Shutdown(); +} +void LoadMap( ); +void SetFrustum(); +void ApplyInput( ) +{ + int key; + + + while ( key = Input.GetKeyMessage( ) ) + { + if ( key == K_ESCAPE ) + Sys_Quit( ); + if ( key == 'l') + LoadMap( ); + if( pODMMap ) + pODMMap->ProcessInput( key ); + if( pMap ) + pMap->ProcessInput( key ); + } + point_t pt = Input.GetMouseMove( ); + Camera.Rotate( -m_speed * pt.x, m_speed * pt.y ); + + float forwardmove = 0, sidemove = 0; + if ( Input.GetKeyStatus( 'w' ) ) + forwardmove += speed; + if ( Input.GetKeyStatus( 's' ) ) + forwardmove -= speed; + + if ( Input.GetKeyStatus( 'a' ) ) + sidemove -= speed; + if ( Input.GetKeyStatus( 'd' ) ) + sidemove += speed; + if( Input.GetKeyStatus( K_SHIFT ) ) + { + forwardmove*=3; + sidemove*=3; + } + forwardmove *= Timer->FrameTime(); + sidemove *= Timer->FrameTime(); + Camera.Move( forwardmove , sidemove ); + if ( pODMMap) + { + int posx = Camera.pos(0); + int posy = Camera.pos(1); + int posz = Camera.pos(2); + posx = bound( -0x40*512, posx, 0x40*512 ); + posy = bound( -0x40*512, posy, 0x40*512 ); + posz = bound( -0x100*32, posz, 0x100*32); + Camera.MoveTo(vec3_t(posx,posy,posz)); + } +} +void Game_Frame( ) +{ + Input.ProcessInput( ); + ApplyInput( ); + display(); +} diff --git a/pool/shard006/C++/0074542_MdtLibrary.cpp b/pool/shard006/C++/0074542_MdtLibrary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00389d7ff66da5fa4509ba10e8145a560e261aea --- /dev/null +++ b/pool/shard006/C++/0074542_MdtLibrary.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** + ** + ** Copyright (C) 2011-2017 Philippe Steinmann. + ** + ** This file is part of Mdt library. + ** + ** Mdt 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. + ** + ** Mdt 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 Mdt. If not, see . + ** + ****************************************************************************/ +#include "MdtLibrary.h" +#include "LibraryName.h" +#include +#include +#include + +namespace Mdt{ namespace DeployUtils{ + +LibraryInfoList MdtLibrary::getMdtLibraries(const LibraryInfoList& libraries) +{ + LibraryInfoList mdtLibraries; + + std::copy_if(libraries.cbegin(), libraries.cend(), std::back_inserter(mdtLibraries), isMdtLibrary); + + return mdtLibraries; +} + +QString MdtLibrary::baseName(const LibraryInfo & library) +{ + const auto name = library.libraryName().name(); + if(name.startsWith(QLatin1String("Mdt0"), Qt::CaseInsensitive)){ + return name.right(name.size() - 4); + } + return name; +} + +QStringList MdtLibrary::getBaseNames(const LibraryInfoList& libraries) +{ + QStringList baseNames; + + for(const auto & library : libraries){ + baseNames.append( baseName(library) ); + } + + return baseNames; +} + +bool MdtLibrary::isMdtLibrary(const LibraryInfo& libraryInfo) +{ + return libraryInfo.libraryName().name().startsWith(QLatin1String("Mdt0"), Qt::CaseInsensitive); +} + +}} // namespace Mdt{ namespace DeployUtils{ diff --git a/pool/shard006/C++/0074544_KPrPlaceholderTool.cpp b/pool/shard006/C++/0074544_KPrPlaceholderTool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d88b2225940af9380a0f469d477896c060a25bd4 --- /dev/null +++ b/pool/shard006/C++/0074544_KPrPlaceholderTool.cpp @@ -0,0 +1,107 @@ +/* This file is part of the KDE project + * Copyright (C) 2008-2009 Thorsten Zachmann + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "KPrPlaceholderTool.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "KPrPlaceholderShape.h" + +KPrPlaceholderTool::KPrPlaceholderTool( KoCanvasBase *canvas ) +: KoTool( canvas ) +{ +} + +KPrPlaceholderTool::~KPrPlaceholderTool() +{ +} + +void KPrPlaceholderTool::paint( QPainter &painter, const KoViewConverter &converter ) +{ + Q_UNUSED( painter ); + Q_UNUSED( converter ); +} + +void KPrPlaceholderTool::mousePressEvent( KoPointerEvent *event ) +{ + Q_UNUSED( event ); +} + +void KPrPlaceholderTool::mouseMoveEvent( KoPointerEvent *event ) +{ + Q_UNUSED( event ); +} + +void KPrPlaceholderTool::mouseReleaseEvent( KoPointerEvent *event ) +{ + Q_UNUSED( event ); +} + +void KPrPlaceholderTool::activate( bool temporary ) +{ + QList selectedShapes; + + foreach( KoShape *shape, m_canvas->shapeManager()->selection()->selectedShapes() ) { + if ( KPrPlaceholderShape * ps = dynamic_cast( shape ) ) { + selectedShapes.append( ps ); + } + } + + if ( selectedShapes.isEmpty() ) { + emit done(); + return; + } + + KPrPlaceholderShape * shape = selectedShapes.at( 0 ); + + KoShape * newShape = shape->createShape( m_canvas->shapeController()->dataCenterMap() ); + // only do anything when we got a shape back + if ( newShape ) { + // copy settings from placeholder shape + newShape->setParent( shape->parent() ); + newShape->setZIndex( shape->zIndex() ); + newShape->setSize( shape->size() ); + newShape->setPosition( shape->position() ); + newShape->setAdditionalAttribute( "presentation:class", shape->additionalAttribute( "presentation:class" ) ); + + QUndoCommand *cmd = new QUndoCommand( i18n( "Edit Shape" ) ); + + // replace placeholder by shape + m_canvas->shapeController()->removeShape( shape, cmd ); + m_canvas->shapeController()->addShapeDirect( newShape, cmd ); + m_canvas->addCommand( cmd ); + + // activate the correct tool for the shape + QList shapes; + shapes.append( newShape ); + m_canvas->shapeManager()->selection()->select( newShape ); + activateTool( KoToolManager::instance()->preferredToolForSelection( shapes ) ); + } + else { + emit done(); + } +} diff --git a/pool/shard006/C++/0074547_window_selectable.cpp b/pool/shard006/C++/0074547_window_selectable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a7dacfa22709e05e660085a1dd09ab3ed6dff2d --- /dev/null +++ b/pool/shard006/C++/0074547_window_selectable.cpp @@ -0,0 +1,157 @@ +/* + * This file is part of EasyRPG Player. + * + * EasyRPG Player 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. + * + * EasyRPG Player 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 EasyRPG Player. If not, see . + */ + +// Headers +#include "window_selectable.h" +#include "game_system.h" +#include "input.h" +#include "util_macro.h" +#include "bitmap.h" + +// Constructor +Window_Selectable::Window_Selectable(int ix, int iy, int iwidth, int iheight) : + Window_Base(ix, iy, iwidth, iheight), + item_max(1), + column_max(1), + index(-1), + help_window(NULL) { +} + +void Window_Selectable::CreateContents() { + SetContents(Bitmap::Create(width - 16, max(height - 16, GetRowMax() * 16))); + contents->SetTransparentColor(windowskin->GetTransparentColor()); +} + +// Properties + +int Window_Selectable::GetIndex() const { + return index; +} +void Window_Selectable::SetIndex(int nindex) { + index = min(nindex, item_max - 1); + if (active && help_window != NULL) { + UpdateHelp(); + } + UpdateCursorRect(); +} +int Window_Selectable::GetRowMax() const { + return (item_max + column_max - 1) / column_max; +} +int Window_Selectable::GetTopRow() const { + return oy / 16; +} +void Window_Selectable::SetTopRow(int row) { + if (row < 0) row = 0; + if (row > GetRowMax() - 1) row = GetRowMax() - 1; + SetOy(row * 16); +} +int Window_Selectable::GetPageRowMax() const { + return (height - 16) / 16; +} +int Window_Selectable::GetPageItemMax() { + return GetPageRowMax() * column_max; +} + +Rect Window_Selectable::GetItemRect(int index) { + Rect rect = Rect(); + rect.width = (contents->GetWidth()) / column_max - 4; + rect.height = 12; + rect.x = index % column_max * rect.width; + if (rect.x > 0){ + rect.x += 8; + } + rect.y = index / column_max * 16 + 2; + return rect; +} + +Window_Help* Window_Selectable::GetHelpWindow() { + return help_window; +} + +void Window_Selectable::SetHelpWindow(Window_Help* nhelp_window) { + help_window = nhelp_window; + if (active && help_window != NULL) { + UpdateHelp(); + } +} + +void Window_Selectable::UpdateHelp() { +} + +// Update Cursor Rect +void Window_Selectable::UpdateCursorRect() { + int cursor_width = 0; + int x = 0; + if (index < 0) { + SetCursorRect(Rect()); + return; + } + int row = index / column_max; + if (row < GetTopRow()) { + SetTopRow(row); + } else if (row > GetTopRow() + (GetPageRowMax() - 1)) { + SetTopRow(row - (GetPageRowMax() - 1)); + } + + if (column_max > 1){ + cursor_width = (width / column_max - 16) + 12; + x = (index % column_max * cursor_width) - 4 ; + } + else{ + cursor_width = (width / column_max - 16) + 8; + x = (index % column_max * (cursor_width + 16)) - 4; + } + + int y = index / column_max * 16 - oy; + SetCursorRect(Rect(x, y, cursor_width, 16)); + +} + +// Update +void Window_Selectable::Update() { + Window_Base::Update(); + if (active && item_max > 0 && index >= 0) { + if (Input::IsRepeated(Input::DOWN)) { + if ((column_max == 1 && Input::IsTriggered(Input::DOWN)) || index < item_max - column_max) { + Game_System::SePlay(Game_System::GetSystemSE(Game_System::SFX_Cursor)); + index = (index + column_max) % item_max; + } + } + if (Input::IsRepeated(Input::UP)) { + if ((column_max == 1 && Input::IsTriggered(Input::UP)) || index >= column_max) { + Game_System::SePlay(Game_System::GetSystemSE(Game_System::SFX_Cursor)); + index = (index - column_max + item_max) % item_max; + } + } + if (Input::IsRepeated(Input::RIGHT)) { + if (column_max >= 2 && index < item_max - 1) { + Game_System::SePlay(Game_System::GetSystemSE(Game_System::SFX_Cursor)); + index += 1; + } + } + if (Input::IsRepeated(Input::LEFT)) { + if (column_max >= 2 && index > 0) { + Game_System::SePlay(Game_System::GetSystemSE(Game_System::SFX_Cursor)); + index -= 1; + } + } + } + if (active && help_window != NULL) { + UpdateHelp(); + } + UpdateCursorRect(); +} diff --git a/pool/shard006/C++/0074554_ZeroLengthContact.cc b/pool/shard006/C++/0074554_ZeroLengthContact.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe7e9bad6247162e507a5cd6fbcec5c1039934a4 --- /dev/null +++ b/pool/shard006/C++/0074554_ZeroLengthContact.cc @@ -0,0 +1,99 @@ +//---------------------------------------------------------------------------- +// XC program; finite element analysis code +// for structural analysis and design. +// +// Copyright (C) Luis Claudio Pérez Tato +// +// This program derives from OpenSees +// developed by the «Pacific earthquake engineering research center». +// +// Except for the restrictions that may arise from the copyright +// of the original program (see copyright_opensees.txt) +// XC 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 software 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 . +//---------------------------------------------------------------------------- +//ZeroLengthContact.cpp + +#include "ZeroLengthContact.h" +#include "domain/mesh/element/utils/Information.h" +#include "utility/recorder/response/ElementResponse.h" +#include "domain/mesh/node/Node.h" + + +//! @brief Constructor. +XC::ZeroLengthContact::ZeroLengthContact(int tag, int classTag, int dim, int Nd1, int Nd2,double Knormal, double Ktangent, double frictionRatio) + :Element0D(tag,classTag,Nd1,Nd2,dim), N(dim*numNodes()) + { + // assign Kn, Kt, fs + Kn = Knormal; + Kt = Ktangent; + fs = frictionRatio; + + // initialized contact flag be zero + ContactFlag=0; + + gap_n = 0 ; + pressure=0; // add for augmented lagrange + } + +//! @brief Default constructor. +XC::ZeroLengthContact::ZeroLengthContact(int tag,int classTag, int dim) + :Element0D(tag,classTag,0,0,dim), + N(dim*numNodes()) + {} + +int XC::ZeroLengthContact::addLoad(ElementalLoad *theLoad, double loadFactor) + { + // meaningless to addLoad to a contact ! + if(isDead()) + std::cerr << getClassName() + << "; load over inactive element: " + << getTag() << std::endl; + return 0; + } + +int XC::ZeroLengthContact::addInertiaLoadToUnbalance(const Vector &accel) + { + // does nothing as element has no mass yet! + return 0; + } + +int XC::ZeroLengthContact::sendSelf(CommParameters &cp) + { + // doing nothing here + return 0; + } + +int XC::ZeroLengthContact::recvSelf(const CommParameters &cp) + { + // doing nothing here + return 0; + } + + +void XC::ZeroLengthContact::Print(std::ostream &s, int flag) + { + if(flag == 0) + { // print everything + s << "Element: " << this->getTag() + << " type: ZeroLengthContact Nodes: " + << theNodes << std::endl; + } + else if(flag == 1) + { + s << this->getTag() << " "; + } + } + diff --git a/pool/shard006/C++/0074560_note_test.cpp b/pool/shard006/C++/0074560_note_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9e64ef0db4225bff363be7cf6c7e0767d238c25 --- /dev/null +++ b/pool/shard006/C++/0074560_note_test.cpp @@ -0,0 +1,13 @@ +#include "lang/note.h" +#include "gtest/gtest.h" + +using namespace intent::lang; + +TEST(note_test, to_string) { + note n(ii_unterminated_string_literal, "sample.i", 1, 25); + auto txt = n.to_string(); + EXPECT_TRUE(strstr(txt.c_str(), "line 1")); + EXPECT_TRUE(strstr(txt.c_str(), "offset 25")); + EXPECT_TRUE(strstr(txt.c_str(), "sample.i")); + EXPECT_TRUE(strstr(txt.c_str(), "String literal ends without a closing quote.")); +} diff --git a/pool/shard006/C++/0074562_Box.cpp b/pool/shard006/C++/0074562_Box.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa9977a194453dde41700b62ad894a1e512bf2fb --- /dev/null +++ b/pool/shard006/C++/0074562_Box.cpp @@ -0,0 +1,234 @@ +/* + Copyright 2014 Statoil ASA. + + This file is part of the Open Porous Media project (OPM). + + OPM 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. + + OPM 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 OPM. If not, see . +*/ + +#include + +#include +#include + +#include +#include + +namespace { + + void assert_dims(int len, int l1 , int l2) { + if (len <= 0) + throw std::invalid_argument("Box must have finite size in all directions"); + + if ((l1 < 0) || (l2 < 0) || (l1 > l2)) + throw std::invalid_argument("Invalid index values for sub box"); + + if (l2 >= len) + throw std::invalid_argument("Invalid index values for sub box"); + } + + + void update_default(int &value, std::size_t& default_count, const Opm::DeckItem& item) { + if (item.defaultApplied(0)) + default_count += 1; + else + value = item.get(0) - 1; + } +} + +namespace Opm { + + Box::Box(const EclipseGrid& grid_arg) : + grid(grid_arg) + { + this->reset(); + } + + + Box::Box(const EclipseGrid& grid_arg, int i1 , int i2 , int j1 , int j2 , int k1 , int k2) : + grid(grid_arg) + { + this->init(i1,i2,j1,j2,k1,k2); + } + + + void Box::update(const DeckRecord& deckRecord) { + const auto& I1Item = deckRecord.getItem("I1"); + const auto& I2Item = deckRecord.getItem("I2"); + const auto& J1Item = deckRecord.getItem("J1"); + const auto& J2Item = deckRecord.getItem("J2"); + const auto& K1Item = deckRecord.getItem("K1"); + const auto& K2Item = deckRecord.getItem("K2"); + + std::size_t default_count = 0; + int i1 = 0; + int i2 = this->grid.getNX() - 1; + int j1 = 0; + int j2 = this->grid.getNY() - 1; + int k1 = 0; + int k2 = this->grid.getNZ() - 1; + + update_default(i1, default_count, I1Item); + update_default(i2, default_count, I2Item); + update_default(j1, default_count, J1Item); + update_default(j2, default_count, J2Item); + update_default(k1, default_count, K1Item); + update_default(k2, default_count, K2Item); + + if (default_count != 6) + this->init(i1,i2,j1,j2,k1,k2); + } + + + void Box::reset() + { + this->init(0, this->grid.getNX() - 1 , 0, this->grid.getNY() - 1, 0, this->grid.getNZ() - 1); + } + + + void Box::init(int i1, int i2, int j1, int j2, int k1, int k2) { + assert_dims(this->grid.getNX(), i1 , i2); + assert_dims(this->grid.getNY(), j1 , j2); + assert_dims(this->grid.getNZ(), k1 , k2); + m_stride[0] = 1; + m_stride[1] = this->grid.getNX(); + m_stride[2] = this->grid.getNX() * this->grid.getNY(); + + m_dims[0] = (size_t) (i2 - i1 + 1); + m_dims[1] = (size_t) (j2 - j1 + 1); + m_dims[2] = (size_t) (k2 - k1 + 1); + + m_offset[0] = (size_t) i1; + m_offset[1] = (size_t) j1; + m_offset[2] = (size_t) k1; + + if (size() == this->grid.getCartesianSize()) + m_isGlobal = true; + else + m_isGlobal = false; + + initIndexList(); + } + + + + size_t Box::size() const { + return m_dims[0] * m_dims[1] * m_dims[2]; + } + + + bool Box::isGlobal() const { + return m_isGlobal; + } + + + size_t Box::getDim(size_t idim) const { + if (idim >= 3) + throw std::invalid_argument("The input dimension value is invalid"); + + return m_dims[idim]; + } + + + + const std::vector& Box::index_list() const { + return this->m_active_index_list; + } + + const std::vector& Box::global_index_list() const { + return this->m_global_index_list; + } + + + + void Box::initIndexList() { + m_active_index_list.clear(); + m_global_index_list.clear(); + + size_t ii,ij,ik; + for (ik=0; ik < m_dims[2]; ik++) { + size_t k = ik + m_offset[2]; + for (ij=0; ij < m_dims[1]; ij++) { + size_t j = ij + m_offset[1]; + for (ii=0; ii < m_dims[0]; ii++) { + std::size_t i = ii + m_offset[0]; + std::size_t global_index = i * m_stride[0] + j*m_stride[1] + k*m_stride[2]; + std::size_t data_index = ii + ij*this->m_dims[0] + ik*this->m_dims[0]*this->m_dims[1]; + + if (this->grid.cellActive(global_index)) { + std::size_t active_index = this->grid.activeIndex(global_index); + m_active_index_list.emplace_back(global_index, active_index, data_index); + } + + this->m_global_index_list.emplace_back( global_index, data_index ); + } + } + } + } + + bool Box::equal(const Box& other) const { + + if (size() != other.size()) + return false; + + { + for (size_t idim = 0; idim < 3; idim++) { + if (m_dims[idim] != other.m_dims[idim]) + return false; + + if (m_stride[idim] != other.m_stride[idim]) + return false; + + if (m_offset[idim] != other.m_offset[idim]) + return false; + } + } + + return true; + } + + + int Box::lower(int dim) const { + return m_offset[dim]; + } + + int Box::upper(int dim) const { + return m_offset[dim] + m_dims[dim] - 1; + } + + int Box::I1() const { + return lower(0); + } + + int Box::I2() const { + return upper(0); + } + + int Box::J1() const { + return lower(1); + } + + int Box::J2() const { + return upper(1); + } + + int Box::K1() const { + return lower(2); + } + + int Box::K2() const { + return upper(2); + } + +} diff --git a/pool/shard006/C++/0074565_SVG.cpp b/pool/shard006/C++/0074565_SVG.cpp new file mode 100644 index 0000000000000000000000000000000000000000..315428fecd42b2b97b8c3474c674f20ba031a4ec --- /dev/null +++ b/pool/shard006/C++/0074565_SVG.cpp @@ -0,0 +1,182 @@ +// +// libavg - Media Playback Engine. +// Copyright (C) 2003-2021 Ulrich von Zadow +// +// 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Current versions can be found at www.libavg.de +// + +#include "SVG.h" + +#include "../base/Exception.h" +#include "../base/ObjectCounter.h" +#include "../base/ScopeTimer.h" +#include "../base/OSHelper.h" +#include "../base/StringHelper.h" +#include "../base/Logger.h" + +#include "../graphics/PixelFormat.h" +#include "../graphics/Filterfill.h" +#include "../graphics/Filterfliprgb.h" +#include "../graphics/FilterUnmultiplyAlpha.h" +#include "../graphics/BitmapLoader.h" + +#include "OGLSurface.h" +#include "Player.h" +#include "ImageNode.h" + +#include + +#ifndef RSVG_CAIRO_H +#include +#endif + +#include + +#include + +using namespace std; + + +namespace avg { + +SVG::SVG(const UTF8String& sFilename, + bool bUnescapeIllustratorIDs, bool bUseLogicalBbox) + : m_sFilename(sFilename), + m_bUnescapeIllustratorIDs(bUnescapeIllustratorIDs), + m_bUseLogicalBbox(bUseLogicalBbox) +{ + GError* pErr = 0; + m_pRSVG = rsvg_handle_new_from_file(m_sFilename.c_str(), &pErr); + if (!m_pRSVG) { + throw Exception(AVG_ERR_INVALID_ARGS, + string("Could not open svg file: ") + m_sFilename); + g_error_free(pErr); + } +} + +SVG::~SVG() +{ + g_object_unref(m_pRSVG); +} + +BitmapPtr SVG::renderElement(const UTF8String& sElementID) +{ + return renderElement(sElementID, 1); +} + +BitmapPtr SVG::renderElement(const UTF8String& sElementID, const glm::vec2& size) +{ + SVGElementPtr pElement = getElement(sElementID); + glm::vec2 elementSize = pElement->getSize(); + return internalRenderElement(pElement, size, elementSize); +} + +BitmapPtr SVG::renderElement(const UTF8String& sElementID, float scale) +{ + SVGElementPtr pElement = getElement(sElementID); + glm::vec2 size = pElement->getSize(); + glm::vec2 renderSize = size * scale; + return internalRenderElement(pElement, renderSize, size); +} + +NodePtr SVG::createImageNode(const UTF8String& sElementID, const py::dict& nodeAttrs) +{ + BitmapPtr pBmp = renderElement(sElementID); + return createImageNodeFromBitmap(pBmp, nodeAttrs); +} + +NodePtr SVG::createImageNode(const UTF8String& sElementID, const py::dict& nodeAttrs, + const glm::vec2& renderSize) +{ + BitmapPtr pBmp = renderElement(sElementID, renderSize); + return createImageNodeFromBitmap(pBmp, nodeAttrs); +} + +NodePtr SVG::createImageNode(const UTF8String& sElementID, const py::dict& nodeAttrs, + float scale) +{ + BitmapPtr pBmp = renderElement(sElementID, scale); + return createImageNodeFromBitmap(pBmp, nodeAttrs); +} + +glm::vec2 SVG::getElementPos(const UTF8String& sElementID) +{ + SVGElementPtr pElement = getElement(sElementID); + return pElement->getPos(); +} + +glm::vec2 SVG::getElementSize(const UTF8String& sElementID) +{ + SVGElementPtr pElement = getElement(sElementID); + return pElement->getSize(); +} + +BitmapPtr SVG::internalRenderElement(const SVGElementPtr& pElement, + const glm::vec2& renderSize, const glm::vec2& size) +{ + glm::vec2 pos = pElement->getPos(); + glm::vec2 scale(renderSize.x/size.x, renderSize.y/size.y); + IntPoint boundingBox = IntPoint(renderSize) + + IntPoint(int(scale.x+0.5), int(scale.y+0.5)); + BitmapPtr pBmp(new Bitmap(boundingBox, B8G8R8A8)); + FilterFill(Pixel32(0,0,0,0)).applyInPlace(pBmp); + + cairo_surface_t* pSurface; + cairo_t* pCairo; + pSurface = cairo_image_surface_create_for_data(pBmp->getPixels(), + CAIRO_FORMAT_ARGB32, boundingBox.x, boundingBox.y, + pBmp->getStride()); + pCairo = cairo_create(pSurface); + cairo_scale(pCairo, scale.x, scale.y); + cairo_translate(pCairo, -pos.x, -pos.y); + rsvg_handle_render_cairo_sub(m_pRSVG, pCairo, pElement->getUnescapedID().c_str()); + + FilterUnmultiplyAlpha().applyInPlace(pBmp); + + cairo_surface_destroy(pSurface); + cairo_destroy(pCairo); + + if (!BitmapLoader::get()->isBlueFirst()) { + FilterFlipRGB().applyInPlace(pBmp); + } + + return pBmp; +} + +NodePtr SVG::createImageNodeFromBitmap(BitmapPtr pBmp, const py::dict& nodeAttrs) +{ + ImageNodePtr pNode = boost::dynamic_pointer_cast( + Player::get()->createNode("image", nodeAttrs)); + pNode->setBitmap(pBmp); + return pNode; +} + +SVGElementPtr SVG::getElement(const UTF8String& sElementID) +{ + map::iterator pos = m_ElementMap.find(sElementID); + if (pos == m_ElementMap.end()) { + SVGElementPtr pElement(new SVGElement(m_pRSVG, m_sFilename, sElementID, + m_bUnescapeIllustratorIDs, m_bUseLogicalBbox)); + m_ElementMap[sElementID] = pElement; + return pElement; + } else { + return pos->second; + } +} + +} + diff --git a/pool/shard006/C++/0074569_paramhandler.cpp b/pool/shard006/C++/0074569_paramhandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..124fde0655c856ccac469c0c9dbb9750b1f08503 --- /dev/null +++ b/pool/shard006/C++/0074569_paramhandler.cpp @@ -0,0 +1,158 @@ +/****************************************************************************** + * + * $Id$ + * + * + * Copyright (C) 1997-2012 by Dimitri van Heesch. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation under the terms of the GNU General Public License is hereby + * granted. No representations are made about the suitability of this software + * for any purpose. It is provided "as is" without express or implied warranty. + * See the GNU General Public License for more details. + * + */ + +#include "paramhandler.h" +#include "memberhandler.h" +#include "linkedtexthandler.h" +#include "debug.h" +#include "dochandler.h" + +TemplateParamListHandler::TemplateParamListHandler(IBaseHandler *parent) : m_parent(parent) +{ + addStartHandler("param",this,&TemplateParamListHandler::startParam); + + addEndHandler("templateparamlist",this,&TemplateParamListHandler::endTemplateParamList); +} + +void TemplateParamListHandler::startParam(const QXmlAttributes& attrib) +{ + ParamHandler *ph = new ParamHandler(this); + ph->startParam(attrib); + m_templateParams.append(ph); +} + +void TemplateParamListHandler::endParam() +{ +} + +void TemplateParamListHandler::startTemplateParamList(const QXmlAttributes& /*attrib*/) +{ + m_parent->setDelegate(this); + debug(2,"templateparamlist\n"); +} + +void TemplateParamListHandler::endTemplateParamList() +{ + m_parent->setDelegate(0); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////// + +ParamHandler::ParamHandler(IBaseHandler *parent) : m_brief(0), m_parent(parent) +{ + addEndHandler("param",this,&ParamHandler::endParam); + + addStartHandler("type",this,&ParamHandler::startType); + + addStartHandler("declname"); + addEndHandler("declname",this,&ParamHandler::endDeclName); + + addStartHandler("defname"); + addEndHandler("defname",this,&ParamHandler::endDefName); + + addStartHandler("array"); + addEndHandler("array",this,&ParamHandler::endArray); + + addStartHandler("attribute"); + addEndHandler("attribute",this,&ParamHandler::endAttrib); + + addStartHandler("briefdescription",this,&ParamHandler::startBriefDesc); + + addStartHandler("defval",this,&ParamHandler::startDefVal); + + m_linkedTextHandler = 0; +} + +ParamHandler::~ParamHandler() +{ + delete m_brief; + delete m_linkedTextHandler; +} + +void ParamHandler::startParam(const QXmlAttributes& /*attrib*/) +{ + m_parent->setDelegate(this); + debug(2,"param\n"); +} + +void ParamHandler::endParam() +{ + m_parent->setDelegate(0); +} + +void ParamHandler::startType(const QXmlAttributes& /*attrib*/) +{ + delete m_linkedTextHandler; + m_linkedTextHandler = new LinkedTextHandler(this,m_type); + m_linkedTextHandler->start("type"); + debug(2,"param type\n"); +} + +void ParamHandler::endDeclName() +{ + m_declName = m_curString.stripWhiteSpace(); + debug(2,"member declName=`%s'\n",m_declName.data()); +} + +void ParamHandler::endDefName() +{ + m_defName = m_curString.stripWhiteSpace(); + debug(2,"member defName=`%s'\n",m_defName.data()); +} + +void ParamHandler::endAttrib() +{ + m_attrib = m_curString.stripWhiteSpace(); + debug(2,"member attrib=`%s'\n",m_attrib.data()); +} + +void ParamHandler::endArray() +{ + m_array = m_curString.stripWhiteSpace(); + debug(2,"member array=`%s'\n",m_array.data()); +} + +void ParamHandler::startDefVal(const QXmlAttributes& /*attrib*/) +{ + delete m_linkedTextHandler; + m_linkedTextHandler = new LinkedTextHandler(this,m_defVal); + m_linkedTextHandler->start("defval"); + debug(2,"member defVal\n"); +} + +void ParamHandler::startBriefDesc(const QXmlAttributes& attrib) +{ + DocHandler *docHandler = new DocHandler(this); + docHandler->startDoc(attrib); + m_brief = docHandler; +} + +ILinkedTextIterator *ParamHandler::type() const +{ + return new LinkedTextIterator(m_type); +} + +ILinkedTextIterator *ParamHandler::defaultValue() const +{ + return new LinkedTextIterator(m_defVal); +} + +IDocRoot *ParamHandler::briefDescription() const +{ + return m_brief; +} + + + diff --git a/pool/shard006/C++/0074572_cutSchema.cpp b/pool/shard006/C++/0074572_cutSchema.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c784d0ee1ce9fc1a34b7a450cdfb5d013cff101 --- /dev/null +++ b/pool/shard006/C++/0074572_cutSchema.cpp @@ -0,0 +1,90 @@ +/************************************************************************ + ************************************************************************ + FAUST compiler + Copyright (C) 2003-2004 GRAME, Centre National de Creation Musicale + --------------------------------------------------------------------- + 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., 675 Mass Ave, Cambridge, MA 02139, USA. + ************************************************************************ + ************************************************************************/ + + +#include "cutSchema.h" +#include + +using namespace std; + + + +/** + * Creates a new Cut schema. + */ +schema* makeCutSchema () +{ + return new cutSchema(); +} + + +/** + * A Cut is represented by a small black dot. It has 1 input + * and no outputs. It has a 0 width and a 1 wire height. The + * constructor is private in order to enforce the usage of + * makeCutSchema. + */ +cutSchema::cutSchema () + : schema (1, 0, 0, dWire/100.0), fPoint(0,0) +{} + + +/** + * The input point is placed in the middle + */ +void cutSchema::place(double ox, double oy, int orientation) +{ + beginPlace(ox, oy, orientation); + fPoint = point(ox, oy + height()*0.5); //, -1); + endPlace(); +} + + +/** + * A cut is represented by a small black dot + */ +void cutSchema::draw(device& dev) +{ + //dev.rond(fPoint.x, fPoint.y, dWire/8.0); +} + +void cutSchema::collectTraits(collector& c) +{} + +/** + * By definition a Cut has only one input point + */ +point cutSchema::inputPoint(unsigned int i) const +{ + assert(i==0); + return fPoint; +} + +/** + * By definition a Cut has no output point + */ +point cutSchema::outputPoint(unsigned int) const +{ + assert(false); + return point(-1,-1); +} + + diff --git a/pool/shard006/C++/0074575_quriloader.cpp b/pool/shard006/C++/0074575_quriloader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29a3e8e64702d856a6799d0ea3256d3b80b13b26 --- /dev/null +++ b/pool/shard006/C++/0074575_quriloader.cpp @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtXmlPatterns module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** 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. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include "qiodevicedelegate_p.h" +#include "quriloader_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +URILoader::URILoader(QObject *const parent, + const NamePool::Ptr &np, + const VariableLoader::Ptr &l) : QNetworkAccessManager(parent) + , m_variableNS(QLatin1String("tag:trolltech.com,2007:QtXmlPatterns:QIODeviceVariable:")) + , m_namePool(np) + , m_variableLoader(l) +{ + Q_ASSERT(m_variableLoader); +} + +QNetworkReply *URILoader::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData) +{ + const QString requestedUrl(req.url().toString()); + + /* We got a QIODevice variable. */ + const QString name(requestedUrl.right(requestedUrl.length() - m_variableNS.length())); + + const QVariant variant(m_variableLoader->valueFor(m_namePool->allocateQName(QString(), name, QString()))); + + if(!variant.isNull() && variant.userType() == qMetaTypeId()) + return new QIODeviceDelegate(qVariantValue(variant)); + else + { + /* If we're entering this code path, the variable URI identified a variable + * which we don't have, which means we either have a bug, or the user had + * crafted an invalid URI manually. */ + + return QNetworkAccessManager::createRequest(op, req, outgoingData); + } +} + +QT_END_NAMESPACE + diff --git a/pool/shard006/C++/0074578_SequenceTimer.cpp b/pool/shard006/C++/0074578_SequenceTimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc4a29fc87b7c787e7f989cf31a9adf4f0aadc68 --- /dev/null +++ b/pool/shard006/C++/0074578_SequenceTimer.cpp @@ -0,0 +1,228 @@ +//////////////////////////////////////////////////////////// +// +// MIT License +// +// Copyright(c) 2017 Kurt Slagle - kurt_slagle@yahoo.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. +// +// The origin of this software must not be misrepresented; you must not claim +// that you wrote the original software.If you use this software in a product, +// an acknowledgment of the software used is required. +// +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Internal Headers +//////////////////////////////////////////////////////////// +#include + +//////////////////////////////////////////////////////////// +// Dependency Headers +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Standard Library Headers +//////////////////////////////////////////////////////////// + +namespace sfui +{ + /* + Individual sequence nodes + */ + SequenceNode::SequenceNode(const SequenceNode &SeqCopy) + : m_Duration(SeqCopy.m_Duration) + , m_EndCallback(SeqCopy.m_EndCallback) + , m_StartCallback(SeqCopy.m_StartCallback) + , m_UpdateCallback(SeqCopy.m_UpdateCallback) + { + m_Timer.setTime(m_Duration); + } + + SequenceNode::SequenceNode(std::initializer_list Seq) + { + + } + + SequenceNode::SequenceNode(uint32 Duration, std::function StartCall, std::function EndCall, std::function UpdateCall) + : m_EndCallback(EndCall) + , m_StartCallback(StartCall) + , m_UpdateCallback(UpdateCall) + { + m_Duration.setFromMilliseconds(static_cast< int >( Duration )); + m_Timer.setTime(m_Duration); + } + + void SequenceNode::Update() + { + m_Timer.getTime(); + m_UpdateCallback(); + + //Make sure we only fire off the call to the end callback once + if (m_Timer.isDone() && !m_IsDone) { + m_EndCallback(); + m_IsDone = true; + } + + } + + bool SequenceNode::IsDone() const + { + return m_IsDone; + } + + void SequenceNode::Start() + { + m_Timer.start(); + m_StartCallback(); + m_IsDone = false; + } + + void SequenceNode::Pause() + { + m_Timer.pause(); + } + + void SequenceNode::Resume() + { + m_Timer.resume(); + } + + void SequenceNode::Stop() + { + m_Timer.stop(); + m_IsDone = true; + } + + void SequenceNode::Restart() + { + m_Timer.restart(); + m_IsDone = false; + } + + /* + Main sequence timer + */ + + SequenceTimer::SequenceTimer(std::function SequenceStartCB, std::function SequenceUpdateCB, std::function SequenceEndCB) + : m_SequenceStartCallback(SequenceStartCB) + , m_SequenceUpdateCallback(SequenceUpdateCB) + , m_SequenceEndCallback(SequenceEndCB) + { + + } + + void SequenceTimer::Clear() + { + while (!m_Nodes.empty()) { + m_Nodes.pop(); + } + } + + void SequenceTimer::Update() + { + if (!m_IsTiming || m_Nodes.empty()) + return; + + m_Nodes.front().Update(); + + if (m_Nodes.front().IsDone()) { + m_Nodes.pop(); + MoveToNextNode(); + } + + m_SequenceUpdateCallback(); + } + + void SequenceTimer::AddSequence(uint32 Duration, std::function NodeStartCB, std::function NodeUpdateCB, std::function NodeEndCB) + { + m_Nodes.emplace(Duration, NodeStartCB, NodeUpdateCB, NodeEndCB); + } + + void SequenceTimer::AddSequences(std::function SequenceStartCB, std::function SequenceUpdateCB, std::function SequenceEndCB, std::initializer_list Nodes) + { + m_SequenceStartCallback = SequenceStartCB; + m_SequenceUpdateCallback = SequenceUpdateCB; + m_SequenceEndCallback = SequenceEndCB; + + for (auto & node : Nodes) + m_Nodes.push(node); + } + + void SequenceTimer::Start() + { + m_IsTiming = true; + + if (!m_Nodes.empty()) { + m_Nodes.front().Start(); + } + + m_SequenceStartCallback(); + } + + void SequenceTimer::Stop() + { + m_IsTiming = false; + + if (!m_Nodes.empty()) { + m_Nodes.front().Stop(); + } + } + + void SequenceTimer::Pause() + { + m_IsTiming = false; + + if (!m_Nodes.empty()) { + m_Nodes.front().Pause(); + } + } + + void SequenceTimer::Resume() + { + m_IsTiming = true; + + if (!m_Nodes.empty()) { + m_Nodes.front().Resume(); + } + + } + + void SequenceTimer::Restart() + { + m_IsTiming = true; + + if (!m_Nodes.empty()) { + m_Nodes.front().Restart(); + } + } + + void SequenceTimer::MoveToNextNode() + { + if (!m_Nodes.empty()) { + m_Nodes.front().Start(); + } + else { + //We finished the sequence + m_SequenceEndCallback(); + m_IsTiming = false; + } + } + +} diff --git a/pool/shard006/C++/0074582_FGInertial.cpp b/pool/shard006/C++/0074582_FGInertial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..730055de9e1af566e0df03081d47b0c69b2f8131 --- /dev/null +++ b/pool/shard006/C++/0074582_FGInertial.cpp @@ -0,0 +1,303 @@ +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + Module: FGInertial.cpp + Author: Jon S. Berndt + Date started: 09/13/00 + Purpose: Encapsulates the inertial frame forces (coriolis and centrifugal) + + ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) ------------- + + This program 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 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 Lesser General Public License for more + details. + + You should have received a copy of the GNU Lesser 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. + + Further information about the GNU Lesser General Public License can also be + found on the world wide web at http://www.gnu.org. + +FUNCTIONAL DESCRIPTION +-------------------------------------------------------------------------------- + +HISTORY +-------------------------------------------------------------------------------- +09/13/00 JSB Created + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +INCLUDES +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +#include "FGInertial.h" +#include "input_output/FGXMLElement.h" + +using namespace std; + +namespace JSBSim { + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +CLASS IMPLEMENTATION +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + + +FGInertial::FGInertial(FGFDMExec* fgex) + : FGModel(fgex) +{ + Name = "Earth"; + + // Earth defaults + double RotationRate = 0.00007292115; + GM = 14.0764417572E15; // WGS84 value + J2 = 1.08262982E-03; // WGS84 value for J2 + a = 20925646.32546; // WGS84 semimajor axis length in feet + b = 20855486.5951; // WGS84 semiminor axis length in feet + gravType = gtWGS84; + + // Lunar defaults + /* + double RotationRate = 0.0000026617; + GM = 1.7314079E14; // Lunar GM + J2 = 2.033542482111609E-4; // value for J2 + a = 5702559.05; // semimajor axis length in feet + b = 5695439.63; // semiminor axis length in feet + */ + + vOmegaPlanet = { 0.0, 0.0, RotationRate }; + GroundCallback.reset(new FGDefaultGroundCallback(a, b)); + + bind(); + + Debug(0); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FGInertial::~FGInertial(void) +{ + Debug(1); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +bool FGInertial::Load(Element* el) +{ + if (!Upload(el, true)) return false; + + Name = el->GetAttributeValue("name"); + + if (el->FindElement("semimajor_axis")) + a = el->FindElementValueAsNumberConvertTo("semimajor_axis", "FT"); + if (el->FindElement("semiminor_axis")) + b = el->FindElementValueAsNumberConvertTo("semiminor_axis", "FT"); + if (el->FindElement("rotation_rate")) { + double RotationRate = el->FindElementValueAsNumberConvertTo("rotation_rate", "RAD/SEC"); + vOmegaPlanet = {0., 0., RotationRate}; + } + if (el->FindElement("GM")) + GM = el->FindElementValueAsNumberConvertTo("GM", "FT3/SEC2"); + if (el->FindElement("J2")) + J2 = el->FindElementValueAsNumber("J2"); // Dimensionless + + GroundCallback->SetEllipse(a, b); + + // Messages to warn the user about possible inconsistencies. + if (a != b && J2 == 0.0) + cout << "Gravitational constant J2 is null for a non-spherical planet." << endl; + if (a == b && J2 != 0.0) + cout << "Gravitational constant J2 is non-zero for a spherical planet." << endl; + + Debug(2); + + return true; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +bool FGInertial::Run(bool Holding) +{ + // Fast return if we have nothing to do ... + if (FGModel::Run(Holding)) return true; + if (Holding) return false; + + // Gravitation accel + switch (gravType) { + case gtStandard: + { + double radius = in.Position.GetRadius(); + vGravAccel = -(GetGAccel(radius) / radius) * in.Position; + } + break; + case gtWGS84: + vGravAccel = GetGravityJ2(in.Position); + break; + } + + return false; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FGMatrix33 FGInertial::GetTl2ec(const FGLocation& location) const +{ + FGColumnVector3 North, Down, East{-location(eY), location(eX), 0.}; + + switch (gravType) { + case gtStandard: + { + Down = location; + Down *= -1.0; + } + break; + case gtWGS84: + { + FGLocation sea_level = location; + sea_level.SetPositionGeodetic(location.GetLongitude(), + location.GetGeodLatitudeRad(), 0.0); + Down = GetGravityJ2(location); + Down -= vOmegaPlanet*(vOmegaPlanet*sea_level);} + } + Down.Normalize(); + East.Normalize(); + North = East*Down; + + return FGMatrix33{North(eX), East(eX), Down(eX), + North(eY), East(eY), Down(eY), + North(eZ), 0.0, Down(eZ)}; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +double FGInertial::GetGAccel(double r) const +{ + return GM/(r*r); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// +// Calculate the WGS84 gravitation value in ECEF frame. Pass in the ECEF +// position via the position parameter. The J2Gravity value returned is in ECEF +// frame, and therefore may need to be expressed (transformed) in another frame, +// depending on how it is used. See Stevens and Lewis eqn. 1.4-16. + +FGColumnVector3 FGInertial::GetGravityJ2(const FGLocation& position) const +{ + FGColumnVector3 J2Gravity; + + // Gravitation accel + double r = position.GetRadius(); + double sinLat = sin(position.GetLatitude()); + + double adivr = a/r; + double preCommon = 1.5*J2*adivr*adivr; + double xy = 1.0 - 5.0*(sinLat*sinLat); + double z = 3.0 - 5.0*(sinLat*sinLat); + double GMOverr2 = GM/(r*r); + + J2Gravity(1) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eX)/r); + J2Gravity(2) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eY)/r); + J2Gravity(3) = -GMOverr2 * ((1.0 + (preCommon * z)) * position(eZ)/r); + + return J2Gravity; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGInertial::SetAltitudeAGL(FGLocation& location, double altitudeAGL) +{ + FGColumnVector3 vDummy; + FGLocation contact; + contact.SetEllipse(a, b); + GroundCallback->GetAGLevel(location, contact, vDummy, vDummy, vDummy); + double groundHeight = contact.GetGeodAltitude(); + double longitude = location.GetLongitude(); + double geodLat = location.GetGeodLatitudeRad(); + location.SetPositionGeodetic(longitude, geodLat, + groundHeight + altitudeAGL); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGInertial::SetGravityType(int gt) +{ + // Messages to warn the user about possible inconsistencies. + switch (gt) + { + case eGravType::gtStandard: + if (a != b) + cout << "Warning: Standard gravity model has been set for a non-spherical planet" << endl; + break; + case eGravType::gtWGS84: + if (J2 == 0.0) + cout << "Warning: WGS84 gravity model has been set without specifying the J2 gravitational constant." << endl; + } + + gravType = gt; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGInertial::bind(void) +{ + PropertyManager->Tie("inertial/sea-level-radius_ft", &in.Position, + &FGLocation::GetSeaLevelRadius); + PropertyManager->Tie("simulation/gravity-model", this, &FGInertial::GetGravityType, + &FGInertial::SetGravityType); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// The bitmasked value choices are as follows: +// unset: In this case (the default) JSBSim would only print +// out the normally expected messages, essentially echoing +// the config files as they are read. If the environment +// variable is not set, debug_lvl is set to 1 internally +// 0: This requests JSBSim not to output any messages +// whatsoever. +// 1: This value explicity requests the normal JSBSim +// startup messages +// 2: This value asks for a message to be printed out when +// a class is instantiated +// 4: When this value is set, a message is displayed when a +// FGModel object executes its Run() method +// 8: When this value is set, various runtime state variables +// are printed out periodically +// 16: When set various parameters are sanity checked and +// a message is printed out when they go out of bounds + +void FGInertial::Debug(int from) +{ + if (debug_lvl <= 0) return; + + if (debug_lvl & 1) { // Standard console startup message output + if (from == 0) {} // Constructor + if (from == 2) { // Loading + cout << endl << " Planet " << Name << endl; + cout << " Semi major axis: " << a << endl; + cout << " Semi minor axis: " << b << endl; + cout << " Rotation rate : " << scientific << vOmegaPlanet(eZ) << endl; + cout << " GM : " << GM << endl; + cout << " J2 : " << J2 << endl << defaultfloat; + } + } + if (debug_lvl & 2 ) { // Instantiation/Destruction notification + if (from == 0) cout << "Instantiated: FGInertial" << endl; + if (from == 1) cout << "Destroyed: FGInertial" << endl; + } + if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects + } + if (debug_lvl & 8 ) { // Runtime state variables + } + if (debug_lvl & 16) { // Sanity checking + } + if (debug_lvl & 64) { + if (from == 0) { // Constructor + } + } +} +} diff --git a/pool/shard006/C++/0074589_candydialog.cpp b/pool/shard006/C++/0074589_candydialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fd505c13e4e5f891bf24c1b97636c2570253f96 --- /dev/null +++ b/pool/shard006/C++/0074589_candydialog.cpp @@ -0,0 +1,70 @@ +#include + +#include "candydialog.h" + +CandyDialog::CandyDialog(QWidget *parent) + : QDialog(parent) +{ + nameComboBox = new QComboBox; + nameComboBox->setEditable(true); + nameComboBox->addItem("Albert Camus"); + nameComboBox->addItem("Dag Solstad"); + nameComboBox->addItem("Haruki Murakami"); + nameComboBox->addItem("Mark Haddon"); + + nameLabel = new QLabel(tr("&Name:")); + nameLabel->setBuddy(nameComboBox); + + passwordLineEdit = new QLineEdit; + passwordLineEdit->setEchoMode(QLineEdit::Password); + passwordLineEdit->setText("password1"); + + passwordLabel = new QLabel(tr("&Password:")); + passwordLabel->setBuddy(passwordLineEdit); + + countryComboBox = new QComboBox; + countryComboBox->addItem(tr("France")); + countryComboBox->addItem(tr("Germany")); + countryComboBox->addItem(tr("United States of America")); + countryComboBox->addItem(tr("United Kingdom")); + countryComboBox->addItem(tr("Other")); + + countryLabel = new QLabel(tr("&Country:")); + countryLabel->setBuddy(countryComboBox); + + professionListWidget = new QListWidget; + professionListWidget->addItem(tr("Ambassador")); + professionListWidget->addItem(tr("Cab driver")); + professionListWidget->addItem(tr("Psychologist")); + professionListWidget->addItem(tr("Scientist")); + professionListWidget->addItem(tr("Tax collector")); + + professionLabel = new QLabel(tr("P&rofession:")); + professionLabel->setBuddy(professionListWidget); + + acceptCheckBox = new QCheckBox(tr("I accept the terms and " + "conditions")); + + buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok + | QDialogButtonBox::Cancel); + + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(nameLabel, 0, 0); + mainLayout->addWidget(nameComboBox, 0, 1); + mainLayout->addWidget(passwordLabel, 1, 0); + mainLayout->addWidget(passwordLineEdit, 1, 1); + mainLayout->addWidget(countryLabel, 2, 0); + mainLayout->addWidget(countryComboBox, 2, 1); + mainLayout->addWidget(professionListWidget, 3, 1, 3, 1); + mainLayout->addWidget(professionLabel, 4, 0); + mainLayout->addWidget(acceptCheckBox, 6, 0, 1, 2); + mainLayout->addWidget(buttonBox, 7, 0, 1, 2); + mainLayout->setRowMinimumHeight(3, 0); + mainLayout->setRowStretch(5, 1); + setLayout(mainLayout); + + setWindowTitle(tr("Candy")); +} diff --git a/pool/shard006/C++/0074590_TargetShooter.cpp b/pool/shard006/C++/0074590_TargetShooter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50bd124fbc27556628d5fad65027f5109ede8745 --- /dev/null +++ b/pool/shard006/C++/0074590_TargetShooter.cpp @@ -0,0 +1,52 @@ +// TargetShooter.cpp + +// AOS Includes +#include "TargetShooter.hpp" +#include "Player.hpp" +#include "Bullet.hpp" + +TargetShooter::TargetShooter(const std::string& p_Keyname) : Enemy(p_Keyname) +{ + m_PointValue = c_TargetShooterPointValue; + m_Health = c_TargetShooterHealth; + m_Speed = c_TargetShooterSpeed; + m_Target = nullptr; + m_TargetDirection = Vector2f::Zero; + m_LastFired = 0.0f; +} + +void TargetShooter::Update(float p_DeltaTime) +{ + if (m_Target == nullptr || m_Target->IsDead()) + { + m_Target = PickRandomObject(&PlayerShip::PlayerShipList); + } + + if (m_Target != nullptr) + { + m_TargetDirection = m_Target->GetPosition() - m_Position; + m_TargetDirection.Normalize(); + } + else + { + m_TargetDirection = Vector2f::Down; + } + + Enemy::Update(p_DeltaTime); + + m_LastFired += p_DeltaTime; + if (m_LastFired > c_TargetShooterFireDelay) + { + FireBullet(); + } +} + +void TargetShooter::FireBullet() +{ + Bullet* bullet = new Bullet("Slime"); + bullet->SetPosition(m_Position); + bullet->SetDirection(m_TargetDirection); + bullet->SetCollisionList(&PlayerShip::PlayerShipList); + + m_LastFired = 0.0f; +} diff --git a/pool/shard006/C++/0074591_kdmrect.cpp b/pool/shard006/C++/0074591_kdmrect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc9c24c1ea8072bbc601941c52297499ed489160 --- /dev/null +++ b/pool/shard006/C++/0074591_kdmrect.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2003 by Unai Garro + * Copyright (C) 2004 by Enrico Ros + * Copyright (C) 2004 by Stephan Kulow + * Copyright (C) 2004 by Oswald Buddenhagen + * + * 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 "kdmrect.h" +#include "kdmthemer.h" + +#include + +KdmRect::KdmRect( QObject *parent, const QDomNode &node ) + : KdmItem( parent, node ) +{ + itemType = "rect"; + + // Set default values for rect (note: strings are already Null) + rect.active.present = false; + rect.prelight.present = false; + + // A rect can have no properties (defaults to parent ones) + if (node.isNull()) + return; + + // Read RECT TAGS + QDomNodeList childList = node.childNodes(); + for (int nod = 0; nod < childList.count(); nod++) { + QDomNode child = childList.item( nod ); + QDomElement el = child.toElement(); + QString tagName = el.tagName(); + + if (tagName == "normal") { + parseColor( el, rect.normal.color ); + } else if (tagName == "active") { + rect.active.present = true; + parseColor( el, rect.active.color ); + } else if (tagName == "prelight") { + rect.prelight.present = true; + parseColor( el, rect.prelight.color ); + } + } +} + +void +KdmRect::drawContents( QPainter *p, const QRect & ) +{ + // choose the correct rect class + RectStruct::RectClass *rClass = &rect.normal; + if (state == Sactive && rect.active.present) + rClass = &rect.active; + if (state == Sprelight && rect.prelight.present) + rClass = &rect.prelight; + + if (!rClass->color.isValid()) + return; + + p->fillRect( area, QBrush( rClass->color ) ); +} + +void +KdmRect::statusChanged( bool descend ) +{ + KdmItem::statusChanged( descend ); + if (!rect.active.present && !rect.prelight.present) + return; + if ((state == Sprelight && !rect.prelight.present) || + (state == Sactive && !rect.active.present)) + return; + needUpdate(); +} + +#include "kdmrect.moc" diff --git a/pool/shard006/C++/0074593_favicon_service_impl_factory.cc b/pool/shard006/C++/0074593_favicon_service_impl_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..d77182c5ccc365edcf156c99ca028adb63e6c5d5 --- /dev/null +++ b/pool/shard006/C++/0074593_favicon_service_impl_factory.cc @@ -0,0 +1,65 @@ +// Copyright 2020 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 "weblayer/browser/favicon/favicon_service_impl_factory.h" + +#include "base/files/file_path.h" +#include "base/no_destructor.h" +#include "components/favicon/content/large_favicon_provider_getter.h" +#include "components/favicon/core/core_favicon_service.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/browser_context.h" +#include "weblayer/browser/favicon/favicon_service_impl.h" + +namespace weblayer { + +namespace { + +favicon::LargeFaviconProvider* GetLargeFaviconProvider( + content::BrowserContext* browser_context) { + return FaviconServiceImplFactory::GetForBrowserContext(browser_context); +} + +} // namespace + +// static +FaviconServiceImpl* FaviconServiceImplFactory::GetForBrowserContext( + content::BrowserContext* browser_context) { + if (!browser_context->IsOffTheRecord()) { + return static_cast( + GetInstance()->GetServiceForBrowserContext(browser_context, true)); + } + return nullptr; +} + +// static +FaviconServiceImplFactory* FaviconServiceImplFactory::GetInstance() { + static base::NoDestructor factory; + return factory.get(); +} + +FaviconServiceImplFactory::FaviconServiceImplFactory() + : BrowserContextKeyedServiceFactory( + "FaviconServiceImpl", + BrowserContextDependencyManager::GetInstance()) { + favicon::SetLargeFaviconProviderGetter( + base::BindRepeating(&GetLargeFaviconProvider)); +} + +FaviconServiceImplFactory::~FaviconServiceImplFactory() = default; + +KeyedService* FaviconServiceImplFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + DCHECK(!context->IsOffTheRecord()); + std::unique_ptr service = + std::make_unique(); + service->Init(context->GetPath().AppendASCII("Favicons")); + return service.release(); +} + +bool FaviconServiceImplFactory::ServiceIsNULLWhileTesting() const { + return true; +} + +} // namespace weblayer diff --git a/pool/shard006/C++/0074594_media_web_contents_observer_android.cc b/pool/shard006/C++/0074594_media_web_contents_observer_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..cde2d8ecbea182c0f135f15d2b1a96ead9ad6414 --- /dev/null +++ b/pool/shard006/C++/0074594_media_web_contents_observer_android.cc @@ -0,0 +1,178 @@ +// 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 "content/browser/media/android/media_web_contents_observer_android.h" + +#include + +#include "base/memory/ptr_util.h" +#include "content/browser/media/android/browser_media_player_manager.h" +#include "content/browser/media/android/browser_surface_view_manager.h" +#include "content/browser/web_contents/web_contents_impl.h" +#include "content/common/media/media_player_delegate_messages.h" +#include "content/common/media/media_player_messages_android.h" +#include "content/common/media/surface_view_manager_messages_android.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "ipc/ipc_message_macros.h" +#include "media/base/android/media_player_android.h" + +namespace content { + +static void SuspendAllMediaPlayersInRenderFrame( + RenderFrameHost* render_frame_host) { + render_frame_host->Send(new MediaPlayerDelegateMsg_SuspendAllMediaPlayers( + render_frame_host->GetRoutingID())); +} + +MediaWebContentsObserverAndroid::MediaWebContentsObserverAndroid( + WebContents* web_contents) + : MediaWebContentsObserver(web_contents) {} + +MediaWebContentsObserverAndroid::~MediaWebContentsObserverAndroid() {} + +// static +MediaWebContentsObserverAndroid* +MediaWebContentsObserverAndroid::FromWebContents(WebContents* web_contents) { + return static_cast( + static_cast(web_contents) + ->media_web_contents_observer()); +} + +BrowserMediaPlayerManager* +MediaWebContentsObserverAndroid::GetMediaPlayerManager( + RenderFrameHost* render_frame_host) { + auto it = media_player_managers_.find(render_frame_host); + if (it != media_player_managers_.end()) + return it->second; + + BrowserMediaPlayerManager* manager = + BrowserMediaPlayerManager::Create(render_frame_host); + media_player_managers_.set(render_frame_host, base::WrapUnique(manager)); + return manager; +} + +BrowserSurfaceViewManager* +MediaWebContentsObserverAndroid::GetSurfaceViewManager( + RenderFrameHost* render_frame_host) { + auto it = surface_view_managers_.find(render_frame_host); + if (it != surface_view_managers_.end()) + return it->second; + + BrowserSurfaceViewManager* manager = + new BrowserSurfaceViewManager(render_frame_host); + surface_view_managers_.set(render_frame_host, base::WrapUnique(manager)); + return manager; +} + +void MediaWebContentsObserverAndroid::SuspendAllMediaPlayers() { + web_contents()->ForEachFrame( + base::Bind(&SuspendAllMediaPlayersInRenderFrame)); +} + +bool MediaWebContentsObserverAndroid::RequestPlay( + RenderFrameHost* render_frame_host, + int delegate_id, + bool has_audio, + bool is_remote, + media::MediaContentType media_content_type) { + return session_controllers_manager()->RequestPlay( + MediaPlayerId(render_frame_host, delegate_id), has_audio, is_remote, + media_content_type); +} + +void MediaWebContentsObserverAndroid::DisconnectMediaSession( + RenderFrameHost* render_frame_host, + int delegate_id) { + session_controllers_manager()->OnEnd( + MediaPlayerId(render_frame_host, delegate_id)); +} + +void MediaWebContentsObserverAndroid::RenderFrameDeleted( + RenderFrameHost* render_frame_host) { + MediaWebContentsObserver::RenderFrameDeleted(render_frame_host); + + media_player_managers_.erase(render_frame_host); + surface_view_managers_.erase(render_frame_host); +} + +bool MediaWebContentsObserverAndroid::OnMessageReceived( + const IPC::Message& msg, + RenderFrameHost* render_frame_host) { + if (MediaWebContentsObserver::OnMessageReceived(msg, render_frame_host)) + return true; + + if (OnMediaPlayerMessageReceived(msg, render_frame_host)) + return true; + + if (OnSurfaceViewManagerMessageReceived(msg, render_frame_host)) + return true; + + return false; +} + +bool MediaWebContentsObserverAndroid::OnMediaPlayerMessageReceived( + const IPC::Message& msg, + RenderFrameHost* render_frame_host) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(MediaWebContentsObserverAndroid, msg) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_EnterFullscreen, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnEnterFullscreen) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_Initialize, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnInitialize) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_Start, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnStart) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_Seek, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnSeek) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_Pause, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnPause) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_SetVolume, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnSetVolume) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_SetPoster, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnSetPoster) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_SuspendAndRelease, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnSuspendAndReleaseResources) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_DestroyMediaPlayer, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnDestroyPlayer) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_RequestRemotePlayback, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnRequestRemotePlayback) + IPC_MESSAGE_FORWARD( + MediaPlayerHostMsg_RequestRemotePlaybackControl, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnRequestRemotePlaybackControl) + IPC_MESSAGE_FORWARD(MediaPlayerHostMsg_RequestRemotePlaybackStop, + GetMediaPlayerManager(render_frame_host), + BrowserMediaPlayerManager::OnRequestRemotePlaybackStop) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +bool MediaWebContentsObserverAndroid::OnSurfaceViewManagerMessageReceived( + const IPC::Message& msg, + RenderFrameHost* render_frame_host) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(MediaWebContentsObserverAndroid, msg) + IPC_MESSAGE_FORWARD(SurfaceViewManagerHostMsg_CreateFullscreenSurface, + GetSurfaceViewManager(render_frame_host), + BrowserSurfaceViewManager::OnCreateFullscreenSurface) + IPC_MESSAGE_FORWARD(SurfaceViewManagerHostMsg_NaturalSizeChanged, + GetSurfaceViewManager(render_frame_host), + BrowserSurfaceViewManager::OnNaturalSizeChanged) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +} // namespace content diff --git a/pool/shard006/C++/0074599_service_mgmt_collection.cc b/pool/shard006/C++/0074599_service_mgmt_collection.cc new file mode 100644 index 0000000000000000000000000000000000000000..1cb6790a1bbaadd0911f92c682bb4fa43c68f15f --- /dev/null +++ b/pool/shard006/C++/0074599_service_mgmt_collection.cc @@ -0,0 +1,233 @@ +/** +* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U +* +* This file is part of iotagent project. +* +* iotagent is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as published +* by the Free Software Foundation, either version 3 of the License, +* or (at your option) any later version. +* +* iotagent 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 Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with iotagent. If not, see http://www.gnu.org/licenses/. +* +* For those usages not covered by the GNU Affero General Public License +* please contact with iot_support at tid dot es +*/ +#include + + +#include +#include +#include "store_const.h" +#include "service_mgmt_collection.h" +#include "service_collection.h" +#include "iota_exception.h" +#include "protocol_collection.h" + + +iota::ServiceMgmtCollection::ServiceMgmtCollection() { + setBBDD(iota::store::types::MANAGER_SERVICE_TABLE); +}; + +iota::ServiceMgmtCollection::ServiceMgmtCollection(ServiceMgmtCollection& dc) { +}; + +iota::ServiceMgmtCollection::~ServiceMgmtCollection() { +}; + +/*void iota::ServiceMgmtCollection::fillSharKey(mongo::BSONObjBuilder &obj) +{ + // CLAVE DE SHARD service, name + if (_m_device._name.empty()) + { + throw std::runtime_error("ServiceMgmtCollection::fillSharKey name is needed as shardKey"); + } + obj.append("name", _m_device._name); + + if (_m_device._service.empty()) + { + throw std::runtime_error("ServiceMgmtCollection::fillSharKey service is needed as shardKey"); + } + obj.append("service", _m_device._service); + +}*/ + + +int iota::ServiceMgmtCollection::createTableAndIndex() { + + int res = 200; + //db.SERVICE_MGMT.ensureIndex({"service":1, service_path:1, iotagent:1, protocol:1},{"unique":1}) + mongo::BSONObj indexUni = BSON(iota::store::types::SERVICE << 1 << + iota::store::types::SERVICE_PATH << 1 + << iota::store::types::IOTAGENT << 1 << + iota::store::types::PROTOCOL_NAME << 1); + + return createIndex(indexUni, true); +} + +std::vector iota::ServiceMgmtCollection::get_services_by_protocol( + const std::string &protocol_name, + int limit, int skip){ + std::vector result; + + mongo::BSONObj query; + mongo::BSONObjBuilder fieldsToReturn; + fieldsToReturn.append(iota::store::types::SERVICE, 1); + fieldsToReturn.append(iota::store::types::SERVICE_PATH, 1); + + iota::Collection::find(a_queryOptions, query, + limit, skip, + BSON(iota::store::types::SERVICE << 1 << + iota::store::types::SERVICE_PATH << 1), + fieldsToReturn, 0); + + std::string ser, ser_path; + mongo::BSONObj elto; + while(more()){ + //TODO comprobar que no esta repetido + elto = next(); + ser = elto.getStringField(iota::store::types::SERVICE); + ser_path = elto.getStringField(iota::store::types::SERVICE_PATH); + result.push_back(iota::ServiceType(ser, ser_path)); + } + + + return result; +} + +std::vector iota::ServiceMgmtCollection::get_services_group_protocol( + const std::string &protocol_name, + int limit, int skip){ + std::vector result; + + std::vector pipeline; + // TODO match y sort + pipeline.push_back( BSON( "$project" << + BSON("service" << 1 << "service_path" << 1 << "protocol" <<1) + )); + pipeline.push_back( BSON("$group" << + BSON("_id" << + BSON("service" << "$service" << "service_path"<< "$service_path") << + "protocol" << BSON("$addToSet" << "$protocol" ) )) + ); + mongo::BSONObj res =iota::Collection::aggregate(pipeline, 0); + /*std::string ser, ser_path; + mongo::BSONObj elto; + while(more()){ + //TODO comprobar que no esta repetido + elto = next(); + ser = elto.getStringField(iota::store::types::SERVICE); + ser_path = elto.getStringField(iota::store::types::SERVICE_PATH); + result.push_back(iota::ServiceType(ser, ser_path)); + }*/ + + + return result; +} + +std::vector iota::ServiceMgmtCollection::get_iotagents_by_service( + const std::string & service, const std::string& service_path, + const std::string& protocol_id, + int limit, int skip){ + std::vector result; + + mongo::BSONObj query; + mongo::BSONObjBuilder fieldsToReturn; + fieldsToReturn.append(iota::store::types::IOTAGENT, 1); + + mongo::BSONObjBuilder bson_query; + bson_query.append(iota::store::types::SERVICE, service); + ServiceCollection::addServicePath(service_path, bson_query); + if (!protocol_id.empty()){ + bson_query.append(iota::store::types::PROTOCOL_NAME, protocol_id); + } + + mongo::BSONObj res = iota::Collection::distinct("iotagent" , bson_query.obj(), 0); + + int count_eltos=0; + mongo::BSONObjIterator fields (res.getObjectField ("values")); + while(fields.more()) { + result.push_back(fields.next().str ()); + count_eltos++; + } + + // if there is no limit and count is 0, then throw an exception for no data + if (count_eltos == 0 && limit ==0 && skip ==0){ + throw iota::IotaException(iota::types::RESPONSE_MESSAGE_MISSING_IOTAGENTS, + "[protocol:" + protocol_id+ + " service: " + service + + " service_path:" + service_path+"]", + iota::types::RESPONSE_CODE_DATA_NOT_FOUND); + } + + return result; +} + + +void iota::ServiceMgmtCollection::getElementsFromBSON(mongo::BSONObj &obj, + std::vector &result){ + + std::vector be = obj.getField( + iota::store::types::SERVICES).Array(); + std::mapprotocols; + iota::ProtocolCollection protocolCol; + protocolCol.fillProtocols(protocols); + std::map::iterator it; + std::string descriptionSTR; + + for (unsigned int i = 0; i proArr = protocolsObj.Array(); + for (unsigned int j = 0; jsecond; + } + mongo::BSONObjBuilder newdata; + newdata.appendElements(obj.removeField(iota::store::types::PROTOCOL_NAME)); + newdata.append(iota::store::types::PROTOCOL_NAME, protocol_id); + newdata.append(iota::store::types::PROTOCOL_DESCRIPTION, descriptionSTR); + mongo::BSONObj ddd = newdata.obj(); + result.push_back(ddd); + } + } + } +} + +void iota::ServiceMgmtCollection::fillServices(const std::string &iotagent, + const std::string &resource, + std::map &result){ + + mongo::BSONObj query = BSON( iota::store::types::IOTAGENT << + iotagent << iota::store::types::PROTOCOL << resource); + find(query); + + mongo::BSONObj elto; + while (more()){ + elto = next(); + std::string key(elto.getStringField(iota::store::types::SERVICE)); + key.append("|"); + key.append(elto.getStringField(iota::store::types::SERVICE_PATH)); + IOTA_LOG_DEBUG(m_logger, "fillServices: " + key); + result.insert( std::pair(key,elto) ); + } +} + +const std::string & iota::ServiceMgmtCollection::get_resource_name(){ + return iota::store::types::PROTOCOL; +} diff --git a/pool/shard006/C++/0074601_message_value.cc b/pool/shard006/C++/0074601_message_value.cc new file mode 100644 index 0000000000000000000000000000000000000000..890a75c44f3b3e9fc048dfbe0137071d0ec689be --- /dev/null +++ b/pool/shard006/C++/0074601_message_value.cc @@ -0,0 +1,69 @@ +/* +* Copyright 2020 Google LLC +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* https://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "proto_value.h" +#include "message_value.h" + +namespace wireless_android_play_analytics { + +std::string MessageValue::PrintToTextProtoHelper() { + // Get indents. + std::string indents; + for(int i = 0; i < this->GetIndentCount(); ++i) { + absl::StrAppend(&indents, " "); + } + // Only print name and brackets if this isn't a proto-text holder. + std::string output; + if (!this->GetName().empty()) { + const std::vector& comment_above_field = + this->GetCommentAboveField(); + for(const std::string& comment : comment_above_field) { + absl::StrAppend(&output, indents, comment, "\n"); + } + + absl::StrAppend(&output, indents, this->GetName(), " {"); + if (!this->GetCommentBehindField().empty()) { + absl::StrAppend(&output, " ", this->GetCommentBehindField()); + } + absl::StrAppend(&output, "\n"); + } + + for (const std::unique_ptr& field : fields_) { + absl::StrAppend(&output, field->PrintToTextProto()); + } + + if (!this->GetName().empty()) { + absl::StrAppend(&output, indents, "}\n"); + } + + return output; +} + +void MessageValue::AddField(std::unique_ptr field) { + fields_.push_back(std::move(field)); +} + +std::vector MessageValue::GetFieldsMutable() { + std::vector result; + + for (const std::unique_ptr& proto_value : fields_) { + result.push_back(proto_value.get()); + } + + return result; +} + +} // namespace wireless_android_play_analytics \ No newline at end of file diff --git a/pool/shard006/C++/0074607_bind_function_object_tests.cpp b/pool/shard006/C++/0074607_bind_function_object_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22ef4d5f0a67859cbee7595d425dc1707b7f3f51 --- /dev/null +++ b/pool/shard006/C++/0074607_bind_function_object_tests.cpp @@ -0,0 +1,136 @@ +/*============================================================================= + Copyright (c) 2001-2007 Joel de Guzman + + Distributed under the Boost Software License, Version 1.0. (See accompanying + file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +==============================================================================*/ +#include +#include +#include +#include +#include +#include + +namespace phoenix = boost::phoenix; +using std::cout; +using std::pow; + + struct test + { + typedef void result_type; + + void + operator()() const + { + cout << "Test lazy functions...\n"; + } + }; + + struct sqr + { + template + struct result; + + template + struct result + { + typedef Arg type; + }; + + template + Arg + operator()(Arg n) const + { + return n * n; + } + }; + + struct fact + { + template + struct result; + + template + struct result + { + typedef Arg type; + }; + + template + Arg + operator()(Arg n) const + { + return (n <= 0) ? 1 : n * (*this)(n-1); + } + }; + + struct power + { + template + struct result; + + template + struct result + { + typedef Arg1 type; + }; + + template + Arg1 + operator()(Arg1 a, Arg2 b) const + { + return pow(a, b); + } + }; + + struct add + { + template + struct result; + + template + struct result + { + typedef Arg1 type; + }; + + template + Arg1 + operator()(Arg1 a, Arg2 b, Arg3 c, Arg4 d) const + { + return a + b + c + d; + } + }; + +int +main() +{ + using phoenix::bind; + using phoenix::ref; + using phoenix::arg_names::_1; + using phoenix::arg_names::arg1; + using phoenix::arg_names::arg2; + + int i5 = 5; + double d5 = 5, d3 = 3; + + test()(); + BOOST_TEST(bind(sqr(), arg1)(i5) == (i5*i5)); + BOOST_TEST(bind(fact(), 4)() == 24); + BOOST_TEST(bind(fact(), arg1)(i5) == 120); + BOOST_TEST((int)bind(power(), arg1, arg2)(d5, d3) == (int)pow(d5, d3)); + BOOST_TEST((bind(sqr(), arg1) + 5)(i5) == ((i5*i5)+5)); + BOOST_TEST(bind(add(), arg1, arg1, arg1, arg1)(i5) == (5+5+5+5)); + + int const ic5 = 5; + // testing consts + BOOST_TEST(bind(sqr(), arg1)(ic5) == (ic5*ic5)); + + // From Steven Watanabe + sqr s; + int x = 2; + int result = bind(ref(s), _1)(x); + BOOST_TEST(result == 4); + + return boost::report_errors(); +} diff --git a/pool/shard006/C++/0074617_ImuDeviceIndicator.cpp b/pool/shard006/C++/0074617_ImuDeviceIndicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df630afba6efcc40984515c3d685578d2dbf75a2 --- /dev/null +++ b/pool/shard006/C++/0074617_ImuDeviceIndicator.cpp @@ -0,0 +1,180 @@ +#include"ImuDeviceIndicator.h" +using namespace RobotSDK_Module; + +//If you need to use extended node, please uncomment below and comment the using of default node +//USE_EXTENDED_NODE(ExtendedNodeClass[,...]) +USE_DEFAULT_NODE + +//================================================= +//Uncomment below PORT_DECL and set input node class name +PORT_DECL(0, ImuDecoder) + +//================================================= +//Original node functions + +//If you don't need to initialize node, you can delete this code segment +NODE_FUNC_DEF_EXPORT(bool, initializeNode) +{ + NOUNUSEDWARNING; + auto vars = NODE_VARS; + vars->layout->addWidget(vars->imu0); + vars->layout->addWidget(vars->imu1); + vars->layout->addWidget(vars->imu2); + vars->layout->addWidget(vars->imu3); + vars->layout->addWidget(vars->imu4); + vars->layout->addWidget(vars->imu5); + vars->widget->setLayout(vars->layout); + vars->setNodeGUIThreadFlag(1); + vars->setInputPortObtainDataBehavior(0, ObtainBehavior::GrabOldest); + return 1; +} + +//If you don't need to manually open node, you can delete this code segment +NODE_FUNC_DEF_EXPORT(bool, openNode) +{ + NOUNUSEDWARNING; + auto vars = NODE_VARS; + vars->counter.resize(6); + for(int i=0;i<6;i++) + { + vars->counter[i]=0; + } + vars->deviceidlist=vars->deviceids.split(",",QString::SkipEmptyParts); + if(vars->deviceidlist.size()!=6) + { + return 0; + } + vars->imu0->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu0->setText(vars->deviceidlist[0]); + vars->imu1->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu1->setText(vars->deviceidlist[1]); + vars->imu2->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu2->setText(vars->deviceidlist[2]); + vars->imu3->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu3->setText(vars->deviceidlist[3]); + vars->imu4->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu4->setText(vars->deviceidlist[4]); + vars->imu5->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu5->setText(vars->deviceidlist[5]); + vars->timer->start(vars->timecount); + return 1; +} + +//If you don't need to manually close node, you can delete this code segment +NODE_FUNC_DEF_EXPORT(bool, closeNode) +{ + NOUNUSEDWARNING; + auto vars = NODE_VARS; + vars->counter.resize(6); + for(int i=0;i<6;i++) + { + vars->counter[i]=0; + } + vars->imu0->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu1->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu2->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu3->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu4->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->imu5->setStyleSheet("QPushButton{ background-color : red; color : black }"); + vars->timer->stop(); + return 1; +} + +//This is original main function, you must keep it +NODE_FUNC_DEF_EXPORT(bool, main) +{ + NOUNUSEDWARNING; + auto vars = NODE_VARS; + if(IS_INTERNAL_TRIGGER) + { + for(int i=0;i<6;i++) + { + vars->counter[i]--; + if(vars->counter[i]<0) + { + vars->counter[i]=0; + switch(i) + { + case 0: + vars->imu0->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 1: + vars->imu1->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 2: + vars->imu2->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 3: + vars->imu3->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 4: + vars->imu4->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 5: + vars->imu5->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + } + } + } + return 1; + } + auto data = PORT_DATA(0,0); + for(int i=0;i<6;i++) + { + if(data->deviceid==vars->deviceidlist[i]) + { + vars->counter[i]=vars->refill; + switch(i) + { + case 0: + vars->imu0->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + case 1: + vars->imu1->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + case 2: + vars->imu2->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + case 3: + vars->imu3->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + case 4: + vars->imu4->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + case 5: + vars->imu5->setStyleSheet("QPushButton{ background-color : green; color : black }"); + break; + } + } + else + { + vars->counter[i]--; + if(vars->counter[i]<0) + { + vars->counter[i]=0; + switch(i) + { + case 0: + vars->imu0->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 1: + vars->imu1->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 2: + vars->imu2->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 3: + vars->imu3->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 4: + vars->imu4->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + case 5: + vars->imu5->setStyleSheet("QPushButton{ background-color : red; color : black }"); + break; + } + } + } + } + return 1; +} diff --git a/pool/shard006/C++/0074619_winshutdownmonitor.cpp b/pool/shard006/C++/0074619_winshutdownmonitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24cf7cb30c9fdb201a5d62658268745f2da72be2 --- /dev/null +++ b/pool/shard006/C++/0074619_winshutdownmonitor.cpp @@ -0,0 +1,70 @@ +// Copyright (c) 2014 The mitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "winshutdownmonitor.h" + +#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 +#include "init.h" +#include "util.h" + +#include + +#include + +#include + +// If we don't want a message to be processed by Qt, return true and set result to +// the value that the window procedure should return. Otherwise return false. +bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult) +{ + Q_UNUSED(eventType); + + MSG *pMsg = static_cast(pMessage); + + // Seed OpenSSL PRNG with Windows event data (e.g. mouse movements and other user interactions) + if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) { + // Warn only once as this is performance-critical + static bool warned = false; + if (!warned) { + LogPrint("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__); + warned = true; + } + } + + switch(pMsg->message) + { + case WM_QUERYENDSESSION: + { + // Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block + // Windows session end until we have finished client shutdown. + StartShutdown(); + *pnResult = FALSE; + return true; + } + + case WM_ENDSESSION: + { + *pnResult = FALSE; + return true; + } + } + + return false; +} + +void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId) +{ + typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR); + PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"); + if (shutdownBRCreate == NULL) { + qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed"; + return; + } + + if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str())) + qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason; + else + qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason; +} +#endif diff --git a/pool/shard006/C++/0074621_main.cpp b/pool/shard006/C++/0074621_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af8524e5f76cf792709c9627f5bf3a7855ac0e7e --- /dev/null +++ b/pool/shard006/C++/0074621_main.cpp @@ -0,0 +1,130 @@ +/* + * SimplePlot: a simple, lightweight plotting library for C++ + * + * Copyright (C) 2011 Simon Knapp + * + * This file is part of SimplePlot, + * + * SimplePlot 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. + * + * SimplePlot 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 SimplePlot. If not, see + */ + +#include +#include +#include + +#define INDEX_TYPE int + +#include "plot.hpp" +#include "gd_graphics_context.h" + +using namespace std; +using namespace SP; + +//const char* font = "D:/code/C/gridtool/etc/BabelSans.ttf"; +const char* font = "D:/code/C/gridtool/etc/lcdxsr.pfa"; + + +typedef int DU; +typedef double UU; + +//typedef Plot PlotType; +typedef Plot<> PlotType; +typedef Circle CircleType; +typedef Axis AxisType; + +int main(int argc, char *argv[]){ + double d; + int at; + PlotType plot(400, 350); + double* x1 = new double[101]; + double* y1 = new double[101]; + vector x; + vector y; + + for(d=0.0, at=0; d<=1.0; d+=0.1, ++at){ + x1[at] = d; + y1[at] = d; + x.push_back(d); + y.push_back(d); + } + x1[at] = 1.0; + y1[at] = 1.0; + x.push_back(1.0); + y.push_back(1.0); + + + vector xMajor, xMinor, yMajor, yMinor; + + for(d=0.0; d<=1.0; d+=0.2){ + xMajor.push_back(d); + yMajor.push_back(d); + if(d>0.0){ + xMinor.push_back(d-0.1); + yMinor.push_back(d-0.1); + } + } + + //CircleType point(4, Color::BLACK); + //LineDescriptor line(Color::BLACK); + + Range range(0.0, 1.0, 0.0, 1.0); + AxisType xaxis( + xMajor, //_majorTicks=xMajor, + range.minX, //_min=range.minX, + range.maxX, //_max=range.maxX, + //_minorTicks=xMinor, + //_lengthMajor=xMajor.size(), + //_lengthMinor=xMinor.size(), + //_majorTickSize=5, + //_minorTickSize=3, + _title="x axis" + ); + //AxisType yaxis(yMajor, yMinor, yMajor.size(), yMinor.size(), range.minY, range.maxY, 5, 3, "y axis"); + //AxisType x1axis, y1axis; + + plot.setFont(font); + //plot.addLine("first", y, x1, makeLine(Color::BLACK), 10, range); + plot.addLine("first", y, x1, range, 10); //makeLine(Color::BLACK), 10); + //plot.addPoint("second", y1, x1, point, 50, range); + //plot.addPoint("second", y, x1, point, 5, range); + plot.addPoint("second", y, x1, range, 5); + + plot.addAxis(BOTTOM, xaxis); + //plot.addAxis(LEFT, yaxis); + //plot.addAxis(TOP, xaxis); + //plot.addAxis(RIGHT, yaxis); + plot.setHeading("heading"); + + GDGraphicsContext gdgc(400, 350, Color::WHITE); + plot.draw(gdgc); + cout << "left plot.draw(gdgc)" << endl; + gdgc.writeToFile("d:/temp/test.png"); + cout << "image written" << endl; + gdgc.destroy(); + cout << "context destroyed" << endl; + + GDGraphicsContext gdgc2(400, 350, Color::WHITE); + //plot.setFont(font); + plot.draw(gdgc2); + cout << "left plot.draw(gdgc)" << endl; + gdgc2.writeToFile("d:/temp/test2.png"); + cout << "image written" << endl; + gdgc2.destroy(); + cout << "context destroyed" << endl; + + plot.clear(); + cout << "plot cleared" << endl; + system("PAUSE"); + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C++/0074623_mem_dp_boundary_mark_pass.cpp b/pool/shard006/C++/0074623_mem_dp_boundary_mark_pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d05c9ff4f9e54b392dc1dc4911576a197a494d2 --- /dev/null +++ b/pool/shard006/C++/0074623_mem_dp_boundary_mark_pass.cpp @@ -0,0 +1,120 @@ +// The ROCCC Compiler Infrastructure +// This file is distributed under the University of California Open Source +// License. See ROCCCLICENSE.TXT for details. +#include "common/system_specific.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "transforms/procedure_walker_utilities.h" +#include +#include + +#include "roccc_utils/IR_utils.h" +#include "roccc_utils/control_flow_utils.h" +#include "roccc_utils/bit_vector_data_flow_utils.h" +#include "roccc_utils/warning_utils.h" + +#include "mem_dp_boundary_mark_pass.h" + +using namespace std; + +// THIS PASS NEEDS TO BE CALLED AFTER THE SCALAR REPLACEMENT PASS AND BEFORE ARRAY FEEDBACK ANALYSIS PASS. + +/**************************** Declarations ************************************/ + +class mdbm_c_for_statement_walker: public SelectiveWalker { +public: + mdbm_c_for_statement_walker(SuifEnv *the_env) + : SelectiveWalker(the_env, CForStatement::get_class_name()) {} + Walker::ApplyStatus operator () (SuifObject *x); +}; + +/**************************** Implementations ************************************/ +MEM_DP_BoundaryMarkPass::MEM_DP_BoundaryMarkPass(SuifEnv *pEnv) : PipelinablePass(pEnv, "MEM_DP_BoundaryMarkPass"){} + +void MEM_DP_BoundaryMarkPass::do_procedure_definition(ProcedureDefinition* proc_def) +{ + OutputInformation("Memory/Datapath marking pass begins") ; + if (proc_def) + { + mdbm_c_for_statement_walker walker(get_suif_env()); + proc_def->walk(walker); + } + OutputInformation("Memory/Datapath marking pass ends") ; +} + +Walker::ApplyStatus mdbm_c_for_statement_walker::operator () (SuifObject *x) { + SuifEnv *env = get_env(); + CForStatement *c_for_stmt = to(x); + + // if(!is_stmt_within_begin_end_hw_marks(c_for_stmt)) + // return Walker::Continue; + + Statement *body = c_for_stmt->get_body(); + + if (body){ + + Iter iter_c_for = object_iterator(body); + if(iter_c_for.is_valid()) + return Walker::Continue; + + StatementList *stmt_list_body = NULL; + + if(is_a(body)) + stmt_list_body = to(body); + else{ + stmt_list_body = create_statement_list(env); + c_for_stmt->set_body(0); + stmt_list_body->append_statement(body); + c_for_stmt->set_body(stmt_list_body); + } + + Iter iter = stmt_list_body->get_statement_iterator(); + for( ; iter.is_valid(); iter.next()){ + Statement *child_stmt = iter.current(); + if(is_a(child_stmt)){ + Iter iter2 = object_iterator(child_stmt); + if(!iter2.is_valid()) + break; + }else break; + } + + MarkStatement *end_of_mem_reads_mark = create_mark_statement(env); + if(iter.is_valid()) + insert_statement_before(iter.current(), end_of_mem_reads_mark); + else + stmt_list_body->insert_statement(0, end_of_mem_reads_mark); + BrickAnnote *ba = create_brick_annote(env, "end_of_mem_reads"); + ba->append_brick(create_suif_object_brick(env, end_of_mem_reads_mark)); + c_for_stmt->append_annote(ba); + + for( ; iter.is_valid(); iter.next()){ + Statement *child_stmt = iter.current(); + if(is_a(child_stmt)) + break; + } + + MarkStatement *beg_of_mem_writes_mark = create_mark_statement(env); + if(iter.is_valid()) + insert_statement_before(iter.current(), beg_of_mem_writes_mark); + else + stmt_list_body->append_statement(beg_of_mem_writes_mark); + ba = create_brick_annote(env, "beg_of_mem_writes"); + ba->append_brick(create_suif_object_brick(env, beg_of_mem_writes_mark)); + c_for_stmt->append_annote(ba); + } + + return Walker::Continue; +} + diff --git a/pool/shard006/C++/0074624_SecretsManagerEndpoint.cpp b/pool/shard006/C++/0074624_SecretsManagerEndpoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c13c331e9da89104273a0bc7f2a27a9251a7ad3 --- /dev/null +++ b/pool/shard006/C++/0074624_SecretsManagerEndpoint.cpp @@ -0,0 +1,64 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include + +using namespace Aws; +using namespace Aws::SecretsManager; + +namespace Aws +{ +namespace SecretsManager +{ +namespace SecretsManagerEndpoint +{ + static const int CN_NORTH_1_HASH = Aws::Utils::HashingUtils::HashString("cn-north-1"); + static const int CN_NORTHWEST_1_HASH = Aws::Utils::HashingUtils::HashString("cn-northwest-1"); + static const int US_ISO_EAST_1_HASH = Aws::Utils::HashingUtils::HashString("us-iso-east-1"); + static const int US_ISOB_EAST_1_HASH = Aws::Utils::HashingUtils::HashString("us-isob-east-1"); + + + Aws::String ForRegion(const Aws::String& regionName, bool useDualStack) + { + // Fallback to us-east-1 if global endpoint does not exists. + Aws::String region = regionName == Aws::Region::AWS_GLOBAL ? Aws::Region::US_EAST_1 : regionName; + auto hash = Aws::Utils::HashingUtils::HashString(region.c_str()); + + Aws::StringStream ss; + ss << "secretsmanager" << "."; + + if(useDualStack) + { + ss << "dualstack."; + } + + ss << region; + + if (hash == CN_NORTH_1_HASH || hash == CN_NORTHWEST_1_HASH) + { + ss << ".amazonaws.com.cn"; + } + else if (hash == US_ISO_EAST_1_HASH) + { + ss << ".c2s.ic.gov"; + } + else if (hash == US_ISOB_EAST_1_HASH) + { + ss << ".sc2s.sgov.gov"; + } + else + { + ss << ".amazonaws.com"; + } + + return ss.str(); + } + +} // namespace SecretsManagerEndpoint +} // namespace SecretsManager +} // namespace Aws + diff --git a/pool/shard006/C++/0074627_main_info_charge.cpp b/pool/shard006/C++/0074627_main_info_charge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee4baa50f98222f3b77dd522148c12bcb2ff1ac0 --- /dev/null +++ b/pool/shard006/C++/0074627_main_info_charge.cpp @@ -0,0 +1,54 @@ +// Copyright (C) 2002-2014 The ProteinDF project +// see also AUTHORS and README. +// +// This file is part of ProteinDF. +// +// ProteinDF 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. +// +// ProteinDF 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 ProteinDF. If not, see . + +#include +#include +#include "DfInfo.h" +#include "Fl_Geometry.h" +#include "TlGetopt.h" +#include "TlMsgPack.h" + +int main(int argc, char* argv[]) { + TlGetopt opt(argc, argv, "hf:"); + + std::string paramPath = "pdfparam.mpac"; + if (opt["f"].empty() == false) { + paramPath = opt["f"]; + } + + // パラメータファイルの読み込み + TlMsgPack mpac; + mpac.load(paramPath); + TlSerializeData param = mpac.getSerializeData(); + + Fl_Geometry flGeom(param["coordinates"]); + DfInfo dfInfo(¶m); + + const int nuclCharge = flGeom.getTotalCharge(); + const int elecCharge = -dfInfo.getNumOfElectrons(); + + std::cout << "nucleus charge = " << nuclCharge << std::endl; + std::cout << "nucleus charge(without X) = " + << flGeom.getTotalChargeWithoutX() << std::endl; + std::cout << "electron charge = " << elecCharge << std::endl; + std::cout << "charge = " << nuclCharge + elecCharge + << std::endl; + std::cout << "formula: " << flGeom.getFormula() << std::endl; + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C++/0074628_batchprocessimagesitem.cpp b/pool/shard006/C++/0074628_batchprocessimagesitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23a91e777bef72ca8f85debc74b0ded342584bce --- /dev/null +++ b/pool/shard006/C++/0074628_batchprocessimagesitem.cpp @@ -0,0 +1,124 @@ +/* ============================================================ + * + * This file is a part of kipi-plugins project + * http://www.digikam.org + * + * Date : 2004-10-01 + * Description : a kipi plugin to batch process images + * + * Copyright (C) 2004-2009 by Gilles Caulier + * + * 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, 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. + * + * ============================================================ */ + +#include "batchprocessimagesitem.h" + +// Qt includes + +#include +#include + +// KDE includes + +#include + +namespace KIPIBatchProcessImagesPlugin +{ + +int BatchProcessImagesItem::columnOfSortKey() +{ + return 4; +} + +BatchProcessImagesItem::BatchProcessImagesItem(QTreeWidget* parent, QString const& pathSrc, + QString const& nameSrc, QString const& nameDest, QString const& result) + : QTreeWidgetItem(parent), + _overwrote(false), + _pathSrc(pathSrc), + _nameSrc(nameSrc), + _nameDest(nameDest), + _result(result) +{ + setText(0, pathSrc.section('/', -2, -2)); + setText(1, nameSrc); + setText(2, nameDest); + setText(3, result); +} + +BatchProcessImagesItem::~BatchProcessImagesItem() +{ +} + +QString BatchProcessImagesItem::pathSrc() const +{ + return _pathSrc; +} +QString BatchProcessImagesItem::nameSrc() const +{ + return _nameSrc; +} +QString BatchProcessImagesItem::nameDest() const +{ + return _nameDest; +} +QString BatchProcessImagesItem::result() const +{ + return _result; +} +QString BatchProcessImagesItem::error() const +{ + return _error; +} +QString BatchProcessImagesItem::outputMess() const +{ + return _outputMess; +} + +QString BatchProcessImagesItem::sortKey() const +{ + return _sortKey; +} + +void BatchProcessImagesItem::changeResult(const QString& text) +{ + setText(3, text); +} +void BatchProcessImagesItem::changeError(const QString& text) +{ + _error = text; +} +void BatchProcessImagesItem::changeNameDest(const QString& text) +{ + _nameDest = text; setText(2, _nameDest); +} +void BatchProcessImagesItem::changeOutputMess(const QString& text) +{ + _outputMess.append(text); +} + +void BatchProcessImagesItem::changeSortKey(const QString& text) +{ + _sortKey = text; + setText(columnOfSortKey(), text); +} + +bool BatchProcessImagesItem::overWrote() const +{ + return _overwrote; +} + +void BatchProcessImagesItem::setDidOverWrite(bool b) +{ + _overwrote = b; +} + +} // namespace KIPIBatchProcessImagesPlugin diff --git a/pool/shard006/C++/0074634_application.cpp b/pool/shard006/C++/0074634_application.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f8c2e42582eb9b0d854a4267213b12262f14487 --- /dev/null +++ b/pool/shard006/C++/0074634_application.cpp @@ -0,0 +1,74 @@ +/* + * Cantata Web + * + * Copyright (c) 2015 Craig Drummond + * + * ---- + * + * 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; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "application.h" +#include "mpd-interface/mpdconnection.h" +#include "mpd-interface/mpdparseutils.h" +#include "httpserver.h" +#include "statusapi.h" +#include "db/mpdlibrarydb.h" +#include "config.h" +#include +#include +#include + +Application::Application(int argc, char *argv[]) + : QCoreApplication(argc, argv) +{ + QCommandLineParser parser; + parser.setApplicationDescription("HTTP Interface for MPD/CantataWeb"); + parser.addHelpOption(); + parser.addVersionOption(); + QCommandLineOption configOption(QStringList() << "c" << "c", "Config file (default " PACKAGE_NAME ".conf).", "configfile", PACKAGE_NAME".conf"); + parser.addOption(configOption); + parser.process(*this); + QString cfgFile=parser.value(configOption); + + if (!QFile::exists(cfgFile)) { + qWarning() << cfgFile << "does not exist"; + ::exit(-1); + } + + QSettings *cfg=new QSettings(cfgFile, QSettings::IniFormat, this); + + MPDConnection::self()->start(); // Place in separate thread... + connect(this, SIGNAL(mpdDetails(MPDConnectionDetails)), MPDConnection::self(), SLOT(setDetails(MPDConnectionDetails))); + MPDConnectionDetails mpd; + mpd.hostname=cfg->value("mpd/host", "127.0.0.1").toString(); + mpd.port=cfg->value("mpd/port", "6600").toUInt(); + mpd.password=cfg->value("mpd/password", QString()).toString(); + mpd.dir=cfg->value("mpd/dir", "/var/lib/mpd/music").toString(); + MPDParseUtils::setSingleTracksFolder(cfg->value("mpd/singleTracksFolder", QString()).toString()); + QString dbFile(cfg->value("db", QCoreApplication::applicationDirPath()+QDir::separator()+PACKAGE_NAME".sqlite").toString()); + if (!MpdLibraryDb::self()->init(dbFile)) { + qWarning() << dbFile << "failed to initialize"; + ::exit(-1); + } + emit mpdDetails(mpd); + HttpServer *http=new HttpServer(this, cfg); + if (!http->start()) { + qWarning() << "Failed to start HTTP server"; + ::exit(-1); + } + StatusApi::self(); +} diff --git a/pool/shard006/C++/0074642_CMutex2.cpp b/pool/shard006/C++/0074642_CMutex2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6866448f770b6b741d4dc0ef549b275a043f4115 --- /dev/null +++ b/pool/shard006/C++/0074642_CMutex2.cpp @@ -0,0 +1,110 @@ +/* +Copyright (c) 2014, P.Hansson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. 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. + +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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of the FreeBSD Project. + */ +/* + * CMutex.cpp + * + * Created on: 12 mar 2014 + * Author: parhansson + */ + +#include +#include +#include + +long int owner; +int lockCount; + +long int getThreadId(); + +CMutex::CMutex() { + lock = false; + name = 0; + owner = 0; + lockCount = 0; +} + +CMutex::~CMutex() { + //delete m1; + //mutex.~recursive_timed_mutex(); +} + + +//CMutex(FALSE,"KMotionPipe",NULL) +CMutex::CMutex(int initiallyOwn,const char *name ,int n){ + this->name = name; + if(initiallyOwn){ + Lock(/*n*/); + } +} + + //Specifies the amount of time to wait for the synchronization object to be available (signaled). + //If INFINITE, Lock will wait until the object is signaled before returning. + //DWORD TimeOut_ms = INFINITE = 4294967295 + int CMutex::Lock(int TimeOut_ms/* = 4294967295*/){ + //std::condition_variable_any; + +// printf("Thread %.8x %.8x: Waiting to get lock \n", t); + + long int tid = getThreadId(); + //printf("%s:%d Mutex: %s waiting max timout %d thread %ld lockCount %d", __FILE__, __LINE__, name,TimeOut_ms,tid,lockCount); + //using Ms = std::chrono::milliseconds; + bool success = mutex.try_lock_for(std::chrono::milliseconds(TimeOut_ms)); + if(success){ + owner = tid; + lockCount++; + } + + //printf(" %s\n",success?"Success":"Failed"); + //printf(" %s lockCount %d \n",success?"Success":"Failed",lockCount); + return success?1:0; + } + + void CMutex::Lock(){ + long int tid = getThreadId(); + //return Lock(4294967295); + //printf("%s:%d Mutex: %s thread %ld lockCount %d waiting", __FILE__, __LINE__, name,tid,lockCount); + mutex.lock(); + owner = tid; + lockCount++; + + //printf(" %s lockCount %d \n","Success",lockCount); + } + + void CMutex::Unlock(){ + long int tid = getThreadId(); + + if(owner == tid && lockCount > 0){ + //printf("%s:%d Mutex: %s thread %ld lockCount %d unlock.....", __FILE__, __LINE__, name, tid,lockCount); + lockCount--; + mutex.unlock(); + //printf("unlocked\n"); + } + + } + diff --git a/pool/shard006/C++/0074647_formatID.cpp b/pool/shard006/C++/0074647_formatID.cpp new file mode 100644 index 0000000000000000000000000000000000000000..988322f305d3e7b9689041846c4ec9cdc7051821 --- /dev/null +++ b/pool/shard006/C++/0074647_formatID.cpp @@ -0,0 +1,63 @@ + +#include +#include +#include + +namespace tests { + +namespace formatIDTestSuite { + +using ::id::attribute::Base; +using ::id::type::UInt8; +using ::id::type::UInt16; + +TEST(FormatIDTestSuite, ValueCompTest) { + ValueType vT0(UInt8::value(), 1, 1, false); + AttributeType aT0(Base::value(), vT0, ScaleType(), Meter()); + EventType eT0; + eT0.add(aT0); + FormatID f0(eT0); + ValueType vT1(UInt8::value(), 1, 1, false); + AttributeType aT1(Base::value(), vT1, ScaleType(), Meter()); + EventType eT1; + eT1.add(aT1); + FormatID f1(eT1); + ValueType vT2(UInt16::value(), 1, 1, false); + AttributeType aT2(Base::value(), vT2, ScaleType(), Meter()); + EventType eT2; + eT2.add(aT2); + FormatID f2(eT2); + ValueType vT3(UInt8::value(), 2, 1, false); + AttributeType aT3(Base::value(), vT3, ScaleType(), Meter()); + EventType eT3; + eT3.add(aT3); + FormatID f3(eT3); + ValueType vT4(UInt8::value(), 1, 2, false); + AttributeType aT4(Base::value(), vT4, ScaleType(), Meter()); + EventType eT4; + eT4.add(aT4); + FormatID f4(eT4); + ValueType vT5(UInt8::value(), 1, 1, true); + AttributeType aT5(Base::value(), vT5, ScaleType(), Meter()); + EventType eT5; + eT5.add(aT5); + FormatID f5(eT5); + AttributeType aT6(Base::value(), vT0, ScaleType(1,1,1), Meter()); + EventType eT6; + eT6.add(aT6); + FormatID f6(eT6); + EXPECT_EQ(f0, f1) << "FormatID of same event types is not the same"; + EXPECT_EQ(eT0-eT1, 0U) << "EventTypes difference of same event types is not 0"; + EXPECT_NE(f0, f2) << "FormatID of events with different value types are the same"; + EXPECT_NE(eT0-eT2, 0U) << "EventTypes difference of different event types is 0"; + EXPECT_NE(f0, f3) << "FormatID of events with different value types are the same"; + EXPECT_NE(eT0-eT3, 0U) << "EventTypes difference of different event types is 0"; + EXPECT_NE(f0, f4) << "FormatID of events with different value types are the same"; + EXPECT_NE(eT0-eT4, 0U) << "EventTypes difference of different event types is 0"; + EXPECT_NE(f0, f5) << "FormatID of events with different value types are the same"; + EXPECT_NE(eT0-eT5, 0U) << "EventTypes difference of different event types is 0"; + EXPECT_NE(f0, f6) << "FormatID of events with different value types are the same"; + EXPECT_NE(eT0-eT6, 0U) << "EventTypes difference of different event types is 0"; +} + +}} diff --git a/pool/shard006/C++/0074654_Mesh.cpp b/pool/shard006/C++/0074654_Mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01931982e54aaed4e3ed339fa02dbdcdf4d1bc64 --- /dev/null +++ b/pool/shard006/C++/0074654_Mesh.cpp @@ -0,0 +1,49 @@ +#include "Mesh.h" + +Mesh::Mesh() + : m_maxLocalScale(1.0L) +{ +} + +Mesh::Mesh(const Mesh &mesh) +{ + m_vertices = mesh.m_vertices; + m_faces = mesh.m_faces; + m_maxLocalScale = mesh.m_maxLocalScale; +} + +void Mesh::addVertex(const Vertex &vertex) +{ + long double x = std::abs(vertex.x()); + long double y = std::abs(vertex.y()); + long double z = std::abs(vertex.z()); + + if (x > m_maxLocalScale) { + m_maxLocalScale = x; + } + + if (y > m_maxLocalScale) { + m_maxLocalScale = y; + } + + if (z > m_maxLocalScale) { + m_maxLocalScale = z; + } + + m_vertices.push_back(vertex); +} + +void Mesh::addFace(const Face &face) +{ + m_faces.push_back(face); +} + +void Mesh::clearVertices() +{ + m_vertices.clear(); +} + +void Mesh::clearFaces() +{ + m_faces.clear(); +} diff --git a/pool/shard006/C++/0074657_scan.cpp b/pool/shard006/C++/0074657_scan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..917608769887a07e9c5b3b212a210582610efe37 --- /dev/null +++ b/pool/shard006/C++/0074657_scan.cpp @@ -0,0 +1,68 @@ + +#include +#include +#include + +#define BOOST_FILESYSTEM_NO_DEPRECATED 1 +#include + + +int affine_image(const boost::filesystem::path& p, + const boost::filesystem::path& q); + + +int scan_file(const boost::filesystem::path& p, const boost::filesystem::path& q) +{ + using namespace boost::filesystem; + using namespace std; + + int status = EXIT_SUCCESS; + + if ( exists(p) ) // does p actually exist? + { + if ( is_regular_file(p) ) // is p a regular file? + { + if ( affine_image(p, q) != EXIT_SUCCESS ) + status = EXIT_FAILURE; + } + + else if ( is_directory(p) ) // is p a directory? + { + for ( auto it = directory_iterator(p); // iterate through directory + it != directory_iterator(); ++it ) + { + if ( is_regular_file(*it) ) // is *it a regular file? + { + if ( affine_image(*it, q) != EXIT_SUCCESS ) + status = EXIT_FAILURE; + } + + else if ( is_directory(*it) ) // is *it a directory? + { + if (scan_file(*it, q) != EXIT_SUCCESS) + status = EXIT_FAILURE; + } + + else // *it is neither a regular file nor a directory! + { + clog << *it << " exists, but is neither a regular file nor a directory\n"; + status = EXIT_FAILURE; + } + } + } + + else // p is neither a regular file nor a directory! + { + clog << p << " exists, but is neither a regular file nor a directory\n"; + return EXIT_FAILURE; + } + } + + else // p does not exists! + { + clog << p << " does not exist\n"; + return EXIT_FAILURE; + } + + return status; +} diff --git a/pool/shard006/C++/0074659_main.cpp b/pool/shard006/C++/0074659_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22eb7eac2afaa3b05ff4ab8c775810913b10294e --- /dev/null +++ b/pool/shard006/C++/0074659_main.cpp @@ -0,0 +1,168 @@ +/* Meteo-Zone Arduino application + * + * Copyright (C) 2015 Sergey Denisov. + * Rewritten by Sergey Denisov aka LittleBuster (DenisovS21@gmail.com) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public Licence + * as published by the Free Software Foundation; either version 3 + * of the Licence, or (at your option) any later version. + */ + +#include +#include +#include +#include "EtherCard.h" +#include "dht22.h" +#include "ds18b20.h" +#include "lcd1602.h" +#include "i2c.h" + + +static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; + +byte Ethernet::buffer[700]; +static uint32_t timer; + +struct dht22 dht_out; +struct ds18b20 ds; + +const char website[] PROGMEM = "www.galynsky.ru"; + +void reverse(char *str, int len) +{ + int8_t i=0, j=len-1, temp; + while (i timer) { + if (!ether.dnsLookup(website)) + Serial.println("DNS failed"); + + timer = millis() + 5000; + Serial.println(); + + float temp, hum; + char lcd_line[24]; + int8_t in_temp; + + dht_read_data(&dht_out, &temp, &hum); + //ds18b20_read_temp(&ds, &in_temp); + + char data[20]; + char out[50]; + + ftoa(temp, data, 2); + strcpy(out, "{\"Id\": 10000001, \"Temp\": "); + strcat(out, data); + strcpy(lcd_line, "T:"); + strcat(lcd_line, data); + strcat(lcd_line, " H:"); + + strcat(out, ", \"Hum\": "); + ftoa(hum, data, 2); + strcat(out, data); + strcat(out, "}"); + strcat(lcd_line, data); + strcat(lcd_line, "%"); + lcd1602_clear(); + lcd1602_send_string(lcd_line); + + lcd1602_goto_xy(0, 1); + strcpy(lcd_line, " InT:"); + sprintf(data, "%d", in_temp); + strcat(lcd_line, data); + lcd1602_send_string(lcd_line); + + Serial.println(out); + ether.sendTCP(website, out, my_callback, 6000); + //ether.httpPost(PSTR("/meteo/"), website, "additional", out, my_callback); + + PORTD |= (1 << 2); + _delay_ms(500); + PORTD &= ~(1 << 2); + _delay_ms(500); + PORTD |= (1 << 2); + _delay_ms(500); + PORTD &= ~(1 << 2); + _delay_ms(500); + } +} diff --git a/pool/shard006/C++/0074661_localTransfer.cpp b/pool/shard006/C++/0074661_localTransfer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef8ce5f5fbcb4486b531527a0dd2af796995ad31 --- /dev/null +++ b/pool/shard006/C++/0074661_localTransfer.cpp @@ -0,0 +1,209 @@ +/******************************************************************************\ +* client/src/localTransfer.cpp * +* Copyright (C) 2009 John Eric Martin * +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License version 2 as * +* published by the Free Software Foundation. * +* * +* 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 "localTransfer.h" +#include "ajax.h" +#include "json.h" + +#include +#include +#include + +#include +#include + +localTransfer::localTransfer(QObject *parent_object) : + baseTransfer(parent_object) +{ + mHaveHeader = false; + mContentLength = 0; +} + +localTransfer::~localTransfer() +{ + if(mLocal) + { + delete mLocal; + mLocal = 0; + } +} + +localTransfer* localTransfer::start(const QMap& post) +{ + localTransfer *transfer = new localTransfer; + + transfer->mLocal = new QLocalSocket; + + QHttpRequestHeader header(post.isEmpty() ? "GET" : "POST", "/backend.php"); + + QByteArray data; + if( !post.isEmpty() ) + { + QStringList post_vars; + QMapIterator i(post); + while( i.hasNext() ) + { + i.next(); + QString post_var = i.key(); + post_var += "="; + post_var += QString( QUrl::toPercentEncoding( i.value() ) ); + + post_vars << post_var; + } + + data = post_vars.join("&").toAscii(); + + header.setContentType("application/x-www-form-urlencoded; " + "charset=UTF-8"); + header.setContentLength( data.length() ); + } + + header.addValue("User-Agent", "Qt4 JSON"); + header.addValue("Host", "local"); + + connect(transfer->mLocal, SIGNAL(readyRead()), transfer, SLOT(readyRead())); + + transfer->mLocal->connectToServer("frosty_local"); + if( !transfer->mLocal->waitForConnected() ) + { + transfer->error( transfer->mLocal->errorString() ); + + return transfer; + } + + transfer->mLocal->write(header.toString().toUtf8()); + transfer->mLocal->write(data); + + return transfer; +} + +void localTransfer::error(const QString& error) +{ + mError = error; + QTimer::singleShot(0, this, SLOT(dispatchError())); +} + +void localTransfer::dispatchError() +{ + emit transferFailed(mError); +} + +void localTransfer::requestFinished(bool error) +{ + emit transferInfo(QString::fromUtf8(mContent), mResponse); + + QString content_error = QString::fromUtf8(mContent); + if( !content_error.isEmpty() ) + { + emit transferFailed(content_error); + deleteLater(); + + return; + } + + if(error) + { + emit transferFailed( tr("A network error has occurred.") ); + deleteLater(); + + return; + } + + foreach(QVariant action, mResponse) + { + QVariantMap map = action.toMap(); + + emit transferFinished(map, map.value("user_data").toString()); + } + + deleteLater(); +} + +void localTransfer::readyRead() +{ + if(!mHaveHeader) + { + while( mLocal->canReadLine() ) + { + QString line = QString::fromUtf8( mLocal->readLine() ); + mHeader += line; + + if( line.trimmed().isEmpty() ) + { + QHttpResponseHeader header(mHeader); + + mContentLength = header.contentLength(); + mHaveHeader = true; + + responseHeaderReceived(header); + + break; + } + } + } + + if(mHaveHeader) + { + mContent += mLocal->readAll(); + if(mContent.size() >= mContentLength) + requestFinished(false); + } +} + +void localTransfer::responseHeaderReceived(const QHttpResponseHeader& resp) +{ + if(resp.statusCode() != 200) + { + emit transferFailed( tr("Server returned code %1").arg( + resp.statusCode() ) ); + deleteLater(); + + return; + } + + if( !resp.hasKey("X-JSON") ) + { + emit transferFailed( tr("Response missing X-JSON header") ); + deleteLater(); + + return; + } + + QRegExp jsonResponse("\\((.*)\\)"); + QString result = resp.value("X-JSON").toAscii(); + + if( jsonResponse.exactMatch(result) ) + result = jsonResponse.cap(1); + + // TODO: Add error checking here + mResponse = json::parse(result).toList(); + + QListIterator it(mResponse); + while( it.hasNext() ) + { + QVariantMap map = it.next().toMap(); + if( map.contains("error") ) + { + emit transferFailed( map.value("error").toString() ); + deleteLater(); + + return; + } + } +} diff --git a/pool/shard006/C++/0074662_ImageIndex.cpp b/pool/shard006/C++/0074662_ImageIndex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac7302d121fe75bcb98e75aae6c61acc3006c926 --- /dev/null +++ b/pool/shard006/C++/0074662_ImageIndex.cpp @@ -0,0 +1,170 @@ +// +// Copyright 2014 The ANGLE Project Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// + +// ImageIndex.cpp: Implementation for ImageIndex methods. + +#include "libANGLE/ImageIndex.h" +#include "libANGLE/Constants.h" +#include "common/utilities.h" + +namespace gl +{ + +ImageIndex::ImageIndex(const ImageIndex &other) + : type(other.type), + mipIndex(other.mipIndex), + layerIndex(other.layerIndex) +{} + +ImageIndex &ImageIndex::operator=(const ImageIndex &other) +{ + type = other.type; + mipIndex = other.mipIndex; + layerIndex = other.layerIndex; + return *this; +} + +ImageIndex ImageIndex::Make2D(GLint mipIndex) +{ + return ImageIndex(GL_TEXTURE_2D, mipIndex, ENTIRE_LEVEL); +} + +ImageIndex ImageIndex::MakeCube(GLenum target, GLint mipIndex) +{ + ASSERT(gl::IsCubeMapTextureTarget(target)); + return ImageIndex(target, mipIndex, CubeMapTextureTargetToLayerIndex(target)); +} + +ImageIndex ImageIndex::Make2DArray(GLint mipIndex, GLint layerIndex) +{ + return ImageIndex(GL_TEXTURE_2D_ARRAY, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::Make3D(GLint mipIndex, GLint layerIndex) +{ + return ImageIndex(GL_TEXTURE_3D, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::MakeGeneric(GLenum target, GLint mipIndex) +{ + GLint layerIndex = IsCubeMapTextureTarget(target) ? CubeMapTextureTargetToLayerIndex(target) : ENTIRE_LEVEL; + return ImageIndex(target, mipIndex, layerIndex); +} + +ImageIndex ImageIndex::MakeInvalid() +{ + return ImageIndex(GL_NONE, -1, -1); +} + +bool ImageIndex::operator<(const ImageIndex &other) const +{ + if (type != other.type) + { + return type < other.type; + } + else if (mipIndex != other.mipIndex) + { + return mipIndex < other.mipIndex; + } + else + { + return layerIndex < other.layerIndex; + } +} + +ImageIndex::ImageIndex(GLenum typeIn, GLint mipIndexIn, GLint layerIndexIn) + : type(typeIn), + mipIndex(mipIndexIn), + layerIndex(layerIndexIn) +{} + +ImageIndexIterator ImageIndexIterator::Make2D(GLint minMip, GLint maxMip) +{ + return ImageIndexIterator(GL_TEXTURE_2D, rx::Range(minMip, maxMip), + rx::Range(ImageIndex::ENTIRE_LEVEL, ImageIndex::ENTIRE_LEVEL), NULL); +} + +ImageIndexIterator ImageIndexIterator::MakeCube(GLint minMip, GLint maxMip) +{ + return ImageIndexIterator(GL_TEXTURE_CUBE_MAP, rx::Range(minMip, maxMip), rx::Range(0, 6), NULL); +} + +ImageIndexIterator ImageIndexIterator::Make3D(GLint minMip, GLint maxMip, + GLint minLayer, GLint maxLayer) +{ + return ImageIndexIterator(GL_TEXTURE_3D, rx::Range(minMip, maxMip), rx::Range(minLayer, maxLayer), NULL); +} + +ImageIndexIterator ImageIndexIterator::Make2DArray(GLint minMip, GLint maxMip, + const GLsizei *layerCounts) +{ + return ImageIndexIterator(GL_TEXTURE_2D_ARRAY, rx::Range(minMip, maxMip), + rx::Range(0, IMPLEMENTATION_MAX_2D_ARRAY_TEXTURE_LAYERS), layerCounts); +} + +ImageIndexIterator::ImageIndexIterator(GLenum type, const rx::Range &mipRange, + const rx::Range &layerRange, const GLsizei *layerCounts) + : mType(type), + mMipRange(mipRange), + mLayerRange(layerRange), + mLayerCounts(layerCounts), + mCurrentMip(mipRange.start), + mCurrentLayer(layerRange.start) +{} + +GLint ImageIndexIterator::maxLayer() const +{ + return (mLayerCounts ? static_cast(mLayerCounts[mCurrentMip]) : mLayerRange.end); +} + +ImageIndex ImageIndexIterator::next() +{ + ASSERT(hasNext()); + + ImageIndex value = current(); + + // Iterate layers in the inner loop for now. We can add switchable + // layer or mip iteration if we need it. + + if (mCurrentLayer != ImageIndex::ENTIRE_LEVEL) + { + if (mCurrentLayer < maxLayer()-1) + { + mCurrentLayer++; + } + else if (mCurrentMip < mMipRange.end-1) + { + mCurrentMip++; + mCurrentLayer = mLayerRange.start; + } + } + else if (mCurrentMip < mMipRange.end-1) + { + mCurrentMip++; + mCurrentLayer = mLayerRange.start; + } + + return value; +} + +ImageIndex ImageIndexIterator::current() const +{ + ImageIndex value(mType, mCurrentMip, mCurrentLayer); + + if (mType == GL_TEXTURE_CUBE_MAP) + { + value.type = LayerIndexToCubeMapTextureTarget(mCurrentLayer); + } + + return value; +} + +bool ImageIndexIterator::hasNext() const +{ + return (mCurrentMip < mMipRange.end || mCurrentLayer < maxLayer()); +} + +} diff --git a/pool/shard006/C++/0074667_Solution.cc b/pool/shard006/C++/0074667_Solution.cc new file mode 100644 index 0000000000000000000000000000000000000000..a38f7c042e0d6386336935a7505e5d280df98025 --- /dev/null +++ b/pool/shard006/C++/0074667_Solution.cc @@ -0,0 +1,67 @@ +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int evalRPN(vector &tokens) { + stack s; + for (int i=0;i test_case0; + test_case0.push_back("2"); + test_case0.push_back("1"); + test_case0.push_back("+"); + test_case0.push_back("3"); + test_case0.push_back("*"); + + std::vector test_case1; + test_case1.push_back("4"); + test_case1.push_back("13"); + test_case1.push_back("5"); + test_case1.push_back("/"); + test_case1.push_back("+"); + + std::vector< std::vector > test_cases; + test_cases.push_back(test_case0); + test_cases.push_back(test_case1); + + for (int i=0;i +#include +#include + +using namespace Aws::RDS::Model; +using namespace Aws::Utils; + +AddTagsToResourceRequest::AddTagsToResourceRequest() : + m_resourceNameHasBeenSet(false), + m_tagsHasBeenSet(false) +{ +} + +Aws::String AddTagsToResourceRequest::SerializePayload() const +{ + Aws::StringStream ss; + ss << "Action=AddTagsToResource&"; + if(m_resourceNameHasBeenSet) + { + ss << "ResourceName=" << StringUtils::URLEncode(m_resourceName.c_str()) << "&"; + } + if(m_tagsHasBeenSet) + { + unsigned tagsCount = 1; + for(auto& item : m_tags) + { + item.OutputToStream(ss, "Tags.member.", tagsCount, ""); + tagsCount++; + } + } + ss << "Version=2014-10-31"; + return ss.str(); +} + diff --git a/pool/shard006/C++/0074674_ladderTrack.cpp b/pool/shard006/C++/0074674_ladderTrack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2542dd0f21fba32ce160bce0b268044c314b31e --- /dev/null +++ b/pool/shard006/C++/0074674_ladderTrack.cpp @@ -0,0 +1,63 @@ +// ladderTrack.cpp : Defines the class behaviors for the application. +// + +#include "stdafx.h" +#include "ladderTrack.h" +#include "ladderTrackDlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CLadderTrackApp + +BEGIN_MESSAGE_MAP(CLadderTrackApp, CWinApp) + //{{AFX_MSG_MAP(CLadderTrackApp) + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CLadderTrackApp construction + +CLadderTrackApp::CLadderTrackApp() +{ +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CLadderTrackApp object + +CLadderTrackApp theApp; + +///////////////////////////////////////////////////////////////////////////// +// CLadderTrackApp initialization + +BOOL CLadderTrackApp::InitInstance() +{ + AfxEnableControlContainer(); + + // Standard initialization +/* +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif +*/ + CLadderTrackDlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + } + else if (nResponse == IDCANCEL) + { + } + + // Since the dialog has been closed, return FALSE so that we exit the + // application, rather than start the application's message pump. + return FALSE; +} diff --git a/pool/shard006/C++/0074675_thing.cpp b/pool/shard006/C++/0074675_thing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7fa9fad58994267e9cf9033d7853d6b1a6383d25 --- /dev/null +++ b/pool/shard006/C++/0074675_thing.cpp @@ -0,0 +1,119 @@ +//////////////////////////////////////////////////////////////////////// +// OpenTibia - an opensource roleplaying game +//////////////////////////////////////////////////////////////////////// +// 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 . +//////////////////////////////////////////////////////////////////////// +#include "otpch.h" +#include "thing.h" + +#include "cylinder.h" +#include "tile.h" + +#include "item.h" +#include "creature.h" +#include "player.h" + +Cylinder* Thing::getTopParent() +{ + //tile + Cylinder* aux = getParent(); + if (!aux) + return dynamic_cast(this); + + Cylinder* prev = dynamic_cast(this); + while (aux->getParent()) + { + prev = aux; + aux = aux->getParent(); + } + + if (dynamic_cast(prev)) + return prev; + + return aux; +} + +const Cylinder* Thing::getTopParent() const +{ + //tile + const Cylinder* aux = getParent(); + if (!aux) + return dynamic_cast(this); + + const Cylinder* prev = dynamic_cast(this); + while (aux->getParent()) + { + prev = aux; + aux = aux->getParent(); + } + + if (dynamic_cast(prev)) + return prev; + + return aux; +} + +Tile* Thing::getTile() +{ + Cylinder* cylinder = getTopParent(); +#ifdef __DEBUG_MOVESYS__ + if (!cylinder) + { + std::clog << "[Failure - Thing::getTile] NULL tile" << std::endl; + return &(Tile::nullTile); + } +#endif + + if (cylinder->getParent()) + cylinder = cylinder->getParent(); + + return dynamic_cast(cylinder); +} + +const Tile* Thing::getTile() const +{ + const Cylinder* cylinder = getTopParent(); +#ifdef __DEBUG_MOVESYS__ + if (!cylinder) + { + std::clog << "[Failure - Thing::getTile] NULL tile" << std::endl; + return &(Tile::nullTile); + } +#endif + + if (cylinder->getParent()) + cylinder = cylinder->getParent(); + + return dynamic_cast(cylinder); +} + +Position Thing::getPosition() const +{ + if (const Tile* tile = getTile()) + return tile->getPosition(); + +#ifdef __DEBUG_MOVESYS__ + std::clog << "[Failure - Thing::getTile] NULL tile" << std::endl; +#endif + return Tile::nullTile.getPosition(); +} + +bool Thing::isRemoved() const +{ + const Cylinder* aux = getParent(); + if (!aux) + return true; + + return aux->isRemoved(); +} diff --git a/pool/shard006/C++/0074684_copy_backward.pass.cpp b/pool/shard006/C++/0074684_copy_backward.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6417f79463f0eb9b07bae7a768988202a977a5d --- /dev/null +++ b/pool/shard006/C++/0074684_copy_backward.pass.cpp @@ -0,0 +1,89 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// + +// Optimization for deque::iterators + +// template +// OutputIterator +// copy_backward(InputIterator first, InputIterator last, OutputIterator result); + +#include +#include + +#include "test_macros.h" +#include "test_iterators.h" +#include "min_allocator.h" + +template +C +make(int size, int start = 0 ) +{ + const int b = 4096 / sizeof(int); + int init = 0; + if (start > 0) + { + init = (start+1) / b + ((start+1) % b != 0); + init *= b; + --init; + } + C c(init, 0); + for (int i = 0; i < init-start; ++i) + c.pop_back(); + for (int i = 0; i < size; ++i) + c.push_back(i); + for (int i = 0; i < start; ++i) + c.pop_front(); + return c; +} + +template +void testN(int start, int N) +{ + typedef typename C::iterator I; + typedef typename C::const_iterator CI; + typedef random_access_iterator RAI; + typedef random_access_iterator RACI; + C c1 = make(N, start); + C c2 = make(N); + assert(std::copy_backward(c1.cbegin(), c1.cend(), c2.end()) == c2.begin()); + assert(c1 == c2); + assert(std::copy_backward(c2.cbegin(), c2.cend(), c1.end()) == c1.begin()); + assert(c1 == c2); + assert(std::copy_backward(c1.cbegin(), c1.cend(), RAI(c2.end())) == RAI(c2.begin())); + assert(c1 == c2); + assert(std::copy_backward(c2.cbegin(), c2.cend(), RAI(c1.end())) == RAI(c1.begin())); + assert(c1 == c2); + assert(std::copy_backward(RACI(c1.cbegin()), RACI(c1.cend()), c2.end()) == c2.begin()); + assert(c1 == c2); + assert(std::copy_backward(RACI(c2.cbegin()), RACI(c2.cend()), c1.end()) == c1.begin()); + assert(c1 == c2); +} + +int main(int, char**) +{ + { + int rng[] = {0, 1, 2, 3, 1023, 1024, 1025, 2047, 2048, 2049}; + const int N = sizeof(rng)/sizeof(rng[0]); + for (int i = 0; i < N; ++i) + for (int j = 0; j < N; ++j) + testN >(rng[i], rng[j]); + } +#if TEST_STD_VER >= 11 + { + int rng[] = {0, 1, 2, 3, 1023, 1024, 1025, 2047, 2048, 2049}; + const int N = sizeof(rng)/sizeof(rng[0]); + for (int i = 0; i < N; ++i) + for (int j = 0; j < N; ++j) + testN> >(rng[i], rng[j]); + } +#endif + + return 0; +} diff --git a/pool/shard006/C++/0074686_1520.cpp11.cpp b/pool/shard006/C++/0074686_1520.cpp11.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b62a7d09e2da200c94d2a736b8b766b8b80b3c4a --- /dev/null +++ b/pool/shard006/C++/0074686_1520.cpp11.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; +int m,n,arr[501][501]; +int cache[501][501]; +int pos[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; +int dp(int y, int x) { + if(y==m && x==n) return 1; + int& ret = cache[y][x]; + if(ret != -1) return ret; + ret = 0; + for(int p=0; p<4; p++) { + int px = x + pos[p][0]; + int py = y + pos[p][1]; + if(1<=px && px<=n && 1<=py && py<=m) + if(arr[py][px] < arr[y][x]) + ret += dp(py,px); + } + return ret; +} +int main() +{ + scanf("%d %d",&m,&n); + for(int i=1; i<=m; i++) + for(int j=1; j<=n; j++) + scanf("%d",&arr[i][j]); + memset(cache,-1,sizeof(cache)); + printf("%d",dp(1,1)); +} diff --git a/pool/shard006/C++/0074697_CLONE.cpp b/pool/shard006/C++/0074697_CLONE.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fbe5cb1fc39c8401c52cb8fc601a06d5f0a2c1d --- /dev/null +++ b/pool/shard006/C++/0074697_CLONE.cpp @@ -0,0 +1,72 @@ + + #include + using namespace std; + + #define pii pair + #define pip pair + #define pb push_back + #define mp make_pair + #define ff first + #define ss second + #define MOD 1000000007 + + typedef long long ll; + //int dx[]={1,-1,0,0}; + //int dy[]={0,0,1,-1}; + + int main() + { + + while(true) + { + int n,m; + scanf("%d%d",&n,&m); + + if(n==0 && m==0) + break; + + map map1; + map< int , int > map2; + string seq; + + map :: iterator it; + + for(int i=0;i>seq; + it=map1.find(seq); + if(it==map1.end())// not there + { + map1.insert(make_pair(seq,1)); + } + else + { + int val=it->ss; + map1.erase(it); + map1.insert(make_pair(seq,val+1)); + } + } + + int arr[n+1]; + for(int i=0;i<=n;i++) + arr[i]=0; + + for(it=map1.begin();it!=map1.end();it++) + { + int counter=0; + counter=it->ss; + //cout<<"counter "<GetPrintOptions( + CefBrowserCToCpp::Wrap(browser), + printOptionsObj); + + // Restore param: printOptions; type: struct_byref + if (printOptions) + printOptionsObj.DetachTo(*printOptions); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK print_handler_get_print_header_footer( + struct _cef_print_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_print_info_t* printInfo, + const cef_string_t* url, const cef_string_t* title, int currentPage, + int maxPages, cef_string_t* topLeft, cef_string_t* topCenter, + cef_string_t* topRight, cef_string_t* bottomLeft, + cef_string_t* bottomCenter, cef_string_t* bottomRight) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: printInfo; type: struct_byref_const + DCHECK(printInfo); + if (!printInfo) + return 0; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: title; type: string_byref_const + DCHECK(title); + if (!title) + return 0; + // Verify param: topLeft; type: string_byref + DCHECK(topLeft); + if (!topLeft) + return 0; + // Verify param: topCenter; type: string_byref + DCHECK(topCenter); + if (!topCenter) + return 0; + // Verify param: topRight; type: string_byref + DCHECK(topRight); + if (!topRight) + return 0; + // Verify param: bottomLeft; type: string_byref + DCHECK(bottomLeft); + if (!bottomLeft) + return 0; + // Verify param: bottomCenter; type: string_byref + DCHECK(bottomCenter); + if (!bottomCenter) + return 0; + // Verify param: bottomRight; type: string_byref + DCHECK(bottomRight); + if (!bottomRight) + return 0; + + // Translate param: printInfo; type: struct_byref_const + CefPrintInfo printInfoObj; + if (printInfo) + printInfoObj.Set(*printInfo, false); + // Translate param: topLeft; type: string_byref + CefString topLeftStr(topLeft); + // Translate param: topCenter; type: string_byref + CefString topCenterStr(topCenter); + // Translate param: topRight; type: string_byref + CefString topRightStr(topRight); + // Translate param: bottomLeft; type: string_byref + CefString bottomLeftStr(bottomLeft); + // Translate param: bottomCenter; type: string_byref + CefString bottomCenterStr(bottomCenter); + // Translate param: bottomRight; type: string_byref + CefString bottomRightStr(bottomRight); + + // Execute + bool _retval = CefPrintHandlerCppToC::Get(self)->GetPrintHeaderFooter( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + printInfoObj, + CefString(url), + CefString(title), + currentPage, + maxPages, + topLeftStr, + topCenterStr, + topRightStr, + bottomLeftStr, + bottomCenterStr, + bottomRightStr); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintHandlerCppToC::CefPrintHandlerCppToC(CefPrintHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.get_print_options = print_handler_get_print_options; + struct_.struct_.get_print_header_footer = + print_handler_get_print_header_footer; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/pool/shard006/C++/0074701_coin_selection.cpp b/pool/shard006/C++/0074701_coin_selection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd5145950bea72469fae594bf912c5bd2e4a8057 --- /dev/null +++ b/pool/shard006/C++/0074701_coin_selection.cpp @@ -0,0 +1,110 @@ +// Copyright (c) 2012-2020 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include +#include + +#include + +static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector>& wtxs) +{ + static int nextLockTime = 0; + CMutableTransaction tx; + tx.nLockTime = nextLockTime++; // so all transactions get different hashes + tx.vout.resize(1); + tx.vout[0].nValue = nValue; + wtxs.push_back(std::make_unique(MakeTransactionRef(std::move(tx)))); +} + +// Simple benchmark for wallet coin selection. Note that it maybe be necessary +// to build up more complicated scenarios in order to get meaningful +// measurements of performance. From laanwj, "Wallet coin selection is probably +// the hardest, as you need a wider selection of scenarios, just testing the +// same one over and over isn't too useful. Generating random isn't useful +// either for measurements." +// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484) +static void CoinSelection(benchmark::Bench& bench) +{ + NodeContext node; + auto chain = interfaces::MakeChain(node); + CWallet wallet(chain.get(), "", CreateDummyWalletDatabase()); + std::vector> wtxs; + LOCK(wallet.cs_wallet); + + // Add coins. + for (int i = 0; i < 1000; ++i) { + addCoin(1000 * COIN, wallet, wtxs); + } + addCoin(3 * COIN, wallet, wtxs); + + // Create coins + std::vector coins; + for (const auto& wtx : wtxs) { + coins.emplace_back(wallet, *wtx, 0 /* iIn */, 6 * 24 /* nDepthIn */, true /* spendable */, true /* solvable */, true /* safe */); + } + + const CoinEligibilityFilter filter_standard(1, 6, 0); + const CoinSelectionParams coin_selection_params(/* change_output_size= */ 34, + /* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0), + /* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0), + /* tx_noinputs_size= */ 0, /* avoid_partial= */ false); + bench.run([&] { + std::set setCoinsRet; + CAmount nValueRet; + bool success = AttemptSelection(wallet, 1003 * COIN, filter_standard, coins, setCoinsRet, nValueRet, coin_selection_params); + assert(success); + assert(nValueRet == 1003 * COIN); + assert(setCoinsRet.size() == 2); + }); +} + +typedef std::set CoinSet; + +// Copied from src/wallet/test/coinselector_tests.cpp +static void add_coin(const CAmount& nValue, int nInput, std::vector& set) +{ + CMutableTransaction tx; + tx.vout.resize(nInput + 1); + tx.vout[nInput].nValue = nValue; + CInputCoin coin(MakeTransactionRef(tx), nInput); + set.emplace_back(); + set.back().Insert(coin, 0, true, 0, 0, false); +} +// Copied from src/wallet/test/coinselector_tests.cpp +static CAmount make_hard_case(int utxos, std::vector& utxo_pool) +{ + utxo_pool.clear(); + CAmount target = 0; + for (int i = 0; i < utxos; ++i) { + target += (CAmount)1 << (utxos+i); + add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool); + add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool); + } + return target; +} + +static void BnBExhaustion(benchmark::Bench& bench) +{ + // Setup + std::vector utxo_pool; + CoinSet selection; + CAmount value_ret = 0; + + bench.run([&] { + // Benchmark + CAmount target = make_hard_case(17, utxo_pool); + SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret); // Should exhaust + + // Cleanup + utxo_pool.clear(); + selection.clear(); + }); +} + +BENCHMARK(CoinSelection); +BENCHMARK(BnBExhaustion); diff --git a/pool/shard006/C++/0074704_unix_domain_server_socket_posix_unittest.cc b/pool/shard006/C++/0074704_unix_domain_server_socket_posix_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..36d14534c924680a692317d657330d7997f3f360 --- /dev/null +++ b/pool/shard006/C++/0074704_unix_domain_server_socket_posix_unittest.cc @@ -0,0 +1,150 @@ +// Copyright 2014 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 "net/socket/unix_domain_server_socket_posix.h" + +#include +#include + +#include "base/bind.h" +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/run_loop.h" +#include "base/test/task_environment.h" +#include "build/build_config.h" +#include "net/base/io_buffer.h" +#include "net/base/net_errors.h" +#include "net/base/test_completion_callback.h" +#include "net/socket/unix_domain_client_socket_posix.h" +#include "net/test/gtest_util.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using net::test::IsError; +using net::test::IsOk; + +namespace net { +namespace { + +const char kSocketFilename[] = "socket_for_testing"; +const char kInvalidSocketPath[] = "/invalid/path"; + +bool UserCanConnectCallback(bool allow_user, + const UnixDomainServerSocket::Credentials& credentials) { + // Here peers are running in same process. +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) + EXPECT_EQ(getpid(), credentials.process_id); +#endif + EXPECT_EQ(getuid(), credentials.user_id); + EXPECT_EQ(getgid(), credentials.group_id); + return allow_user; +} + +UnixDomainServerSocket::AuthCallback CreateAuthCallback(bool allow_user) { + return base::BindRepeating(&UserCanConnectCallback, allow_user); +} + +class UnixDomainServerSocketTest : public testing::Test { + protected: + UnixDomainServerSocketTest() { + EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + socket_path_ = temp_dir_.GetPath().Append(kSocketFilename).value(); + } + + base::ScopedTempDir temp_dir_; + std::string socket_path_; +}; + +TEST_F(UnixDomainServerSocketTest, ListenWithInvalidPath) { + const bool kUseAbstractNamespace = false; + UnixDomainServerSocket server_socket(CreateAuthCallback(true), + kUseAbstractNamespace); + EXPECT_EQ(ERR_FILE_NOT_FOUND, + server_socket.BindAndListen(kInvalidSocketPath, /*backlog=*/1)); +} + +TEST_F(UnixDomainServerSocketTest, ListenWithInvalidPathWithAbstractNamespace) { + const bool kUseAbstractNamespace = true; + UnixDomainServerSocket server_socket(CreateAuthCallback(true), + kUseAbstractNamespace); +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) + EXPECT_THAT(server_socket.BindAndListen(kInvalidSocketPath, /*backlog=*/1), + IsOk()); +#else + EXPECT_EQ(ERR_ADDRESS_INVALID, + server_socket.BindAndListen(kInvalidSocketPath, /*backlog=*/1)); +#endif +} + +TEST_F(UnixDomainServerSocketTest, ListenAgainAfterFailureWithInvalidPath) { + const bool kUseAbstractNamespace = false; + UnixDomainServerSocket server_socket(CreateAuthCallback(true), + kUseAbstractNamespace); + EXPECT_EQ(ERR_FILE_NOT_FOUND, + server_socket.BindAndListen(kInvalidSocketPath, /*backlog=*/1)); + EXPECT_THAT(server_socket.BindAndListen(socket_path_, /*backlog=*/1), IsOk()); +} + +TEST_F(UnixDomainServerSocketTest, AcceptWithForbiddenUser) { + base::test::TaskEnvironment task_environment( + base::test::TaskEnvironment::MainThreadType::IO); + + const bool kUseAbstractNamespace = false; + + UnixDomainServerSocket server_socket(CreateAuthCallback(false), + kUseAbstractNamespace); + EXPECT_THAT(server_socket.BindAndListen(socket_path_, /*backlog=*/1), IsOk()); + + std::unique_ptr accepted_socket; + TestCompletionCallback accept_callback; + EXPECT_EQ(ERR_IO_PENDING, + server_socket.Accept(&accepted_socket, accept_callback.callback())); + EXPECT_FALSE(accepted_socket); + + UnixDomainClientSocket client_socket(socket_path_, kUseAbstractNamespace); + EXPECT_FALSE(client_socket.IsConnected()); + + // Connect() will return OK before the server rejects the connection. + TestCompletionCallback connect_callback; + int rv = connect_callback.GetResult( + client_socket.Connect(connect_callback.callback())); + ASSERT_THAT(rv, IsOk()); + + // Try to read from the socket. + const int read_buffer_size = 10; + scoped_refptr read_buffer = + base::MakeRefCounted(read_buffer_size); + TestCompletionCallback read_callback; + rv = read_callback.GetResult(client_socket.Read( + read_buffer.get(), read_buffer_size, read_callback.callback())); + + // The server should have disconnected gracefully, without sending any data. + ASSERT_EQ(0, rv); + EXPECT_FALSE(client_socket.IsConnected()); + + // The server socket should not have called |accept_callback| or modified + // |accepted_socket|. + EXPECT_FALSE(accept_callback.have_result()); + EXPECT_FALSE(accepted_socket); +} + +TEST_F(UnixDomainServerSocketTest, UnimplementedMethodsFail) { + const bool kUseAbstractNamespace = false; + UnixDomainServerSocket server_socket(CreateAuthCallback(true), + kUseAbstractNamespace); + + IPEndPoint ep; + EXPECT_THAT(server_socket.Listen(ep, 0), IsError(ERR_NOT_IMPLEMENTED)); + EXPECT_EQ(ERR_NOT_IMPLEMENTED, + server_socket.ListenWithAddressAndPort(kInvalidSocketPath, + 0, + /*backlog=*/1)); + + EXPECT_THAT(server_socket.GetLocalAddress(&ep), IsError(ERR_ADDRESS_INVALID)); +} + +// Normal cases including read/write are tested by UnixDomainClientSocketTest. + +} // namespace +} // namespace net diff --git a/pool/shard006/C++/0074705_value_construct.cpp b/pool/shard006/C++/0074705_value_construct.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a125696580777ff57e0fca94c5eaab9b5310fd4 --- /dev/null +++ b/pool/shard006/C++/0074705_value_construct.cpp @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2012 ciere consulting, ciere.com + * Copyright (C) 2010, 2011 Object Modeling Designs + */ + +#include +#include "json/value.hpp" +#include "json/io.hpp" +#include "json/parser/grammar_def.hpp" + +namespace json = ciere::json; + +int main() +{ + json::value value; + + BOOST_TEST( value.type() == json::null_type ); + + value = json::construct( + "{" + " \"foo\" : 42 ," + " \"bar\" : 498.5 ," + " \"gorp\" : \"ciere\"," + " \"bork\" : [\"ciere\",23,false]" + "}" + ); + + BOOST_TEST( value["foo"] == 42 ); + BOOST_TEST( value["bar"] == 498.5 ); + BOOST_TEST( value["gorp"] == "ciere" ); + BOOST_TEST( value["bork"][2] == false ); + + return boost::report_errors(); +} + diff --git a/pool/shard006/C++/0074712_scalar-unit.cpp b/pool/shard006/C++/0074712_scalar-unit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99ff7084662e0756ed749d2b01b8fc3315246ef8 --- /dev/null +++ b/pool/shard006/C++/0074712_scalar-unit.cpp @@ -0,0 +1,260 @@ +/* + * Authors: + * Bryce Harrington + * Derek P. Moore + * buliabyak@gmail.com + * + * Copyright (C) 2004-2005 Authors + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "scalar-unit.h" +#include "spinbutton.h" + +namespace Inkscape { +namespace UI { +namespace Widget { + +ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, + UnitType unit_type, + Glib::ustring const &suffix, + Glib::ustring const &icon, + UnitMenu *unit_menu, + bool mnemonic) + : Scalar(label, tooltip, suffix, icon, mnemonic), + _unit_menu(unit_menu), + _hundred_percent(0), + _absolute_is_increment(false), + _percentage_is_increment(false) +{ + if (_unit_menu == NULL) { + _unit_menu = new UnitMenu(); + g_assert(_unit_menu); + _unit_menu->setUnitType(unit_type); + pack_start(*Gtk::manage(_unit_menu), false, false, 4); + } + _unit_menu->signal_changed() + .connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); + + static_cast(_widget)->setUnitMenu(_unit_menu); + + lastUnits = _unit_menu->getUnitAbbr(); +} + +ScalarUnit::ScalarUnit(Glib::ustring const &label, Glib::ustring const &tooltip, + ScalarUnit &take_unitmenu, + Glib::ustring const &suffix, + Glib::ustring const &icon, + bool mnemonic) + : Scalar(label, tooltip, suffix, icon, mnemonic), + _unit_menu(take_unitmenu._unit_menu), + _hundred_percent(0), + _absolute_is_increment(false), + _percentage_is_increment(false) +{ + _unit_menu->signal_changed() + .connect_notify(sigc::mem_fun(*this, &ScalarUnit::on_unit_changed)); + + static_cast(_widget)->setUnitMenu(_unit_menu); + + lastUnits = _unit_menu->getUnitAbbr(); +} + + +void ScalarUnit::initScalar(double min_value, double max_value) +{ + g_assert(_unit_menu != NULL); + Scalar::setDigits(_unit_menu->getDefaultDigits()); + Scalar::setIncrements(_unit_menu->getDefaultStep(), + _unit_menu->getDefaultPage()); + Scalar::setRange(min_value, max_value); +} + +bool ScalarUnit::setUnit(Glib::ustring const &unit) +{ + g_assert(_unit_menu != NULL); + // First set the unit + if (!_unit_menu->setUnit(unit)) { + return false; + } + lastUnits = unit; + return true; +} + +void ScalarUnit::setUnitType(UnitType unit_type) +{ + g_assert(_unit_menu != NULL); + _unit_menu->setUnitType(unit_type); + lastUnits = _unit_menu->getUnitAbbr(); +} + +void ScalarUnit::resetUnitType(UnitType unit_type) +{ + g_assert(_unit_menu != NULL); + _unit_menu->resetUnitType(unit_type); + lastUnits = _unit_menu->getUnitAbbr(); +} + +Unit ScalarUnit::getUnit() const +{ + g_assert(_unit_menu != NULL); + return _unit_menu->getUnit(); +} + +UnitType ScalarUnit::getUnitType() const +{ + g_assert(_unit_menu); + return _unit_menu->getUnitType(); +} + +void ScalarUnit::setValue(double number, Glib::ustring const &units) +{ + g_assert(_unit_menu != NULL); + _unit_menu->setUnit(units); + Scalar::setValue(number); +} + +void ScalarUnit::setValueKeepUnit(double number, Glib::ustring const &units) +{ + g_assert(_unit_menu != NULL); + if (units == "") { + // set the value in the default units + Scalar::setValue(number); + } else { + double conversion = _unit_menu->getConversion(units); + Scalar::setValue(number / conversion); + } +} + +void ScalarUnit::setValue(double number) +{ + Scalar::setValue(number); +} + +double ScalarUnit::getValue(Glib::ustring const &unit_name) const +{ + g_assert(_unit_menu != NULL); + if (unit_name == "") { + // Return the value in the default units + return Scalar::getValue(); + } else { + double conversion = _unit_menu->getConversion(unit_name); + return conversion * Scalar::getValue(); + } +} + +void ScalarUnit::grabFocusAndSelectEntry() +{ + _widget->grab_focus(); + static_cast(_widget)->select_region(0, 20); +} + + +void ScalarUnit::setHundredPercent(double number) +{ + _hundred_percent = number; +} + +void ScalarUnit::setAbsoluteIsIncrement(bool value) +{ + _absolute_is_increment = value; +} + +void ScalarUnit::setPercentageIsIncrement(bool value) +{ + _percentage_is_increment = value; +} + +double ScalarUnit::PercentageToAbsolute(double value) +{ + // convert from percent to absolute + double convertedVal = 0; + double hundred_converted = _hundred_percent / _unit_menu->getConversion("px"); // _hundred_percent is in px + if (_percentage_is_increment) + value += 100; + convertedVal = 0.01 * hundred_converted * value; + if (_absolute_is_increment) + convertedVal -= hundred_converted; + + return convertedVal; +} + +double ScalarUnit::AbsoluteToPercentage(double value) +{ + double convertedVal = 0; + // convert from absolute to percent + if (_hundred_percent == 0) { + if (_percentage_is_increment) + convertedVal = 0; + else + convertedVal = 100; + } else { + double hundred_converted = _hundred_percent / _unit_menu->getConversion("px", lastUnits); // _hundred_percent is in px + if (_absolute_is_increment) + value += hundred_converted; + convertedVal = 100 * value / hundred_converted; + if (_percentage_is_increment) + convertedVal -= 100; + } + + return convertedVal; +} + +double ScalarUnit::getAsPercentage() +{ + double convertedVal = AbsoluteToPercentage(Scalar::getValue()); + return convertedVal; +} + + +void ScalarUnit::setFromPercentage(double value) +{ + double absolute = PercentageToAbsolute(value); + Scalar::setValue(absolute); +} + + +void ScalarUnit::on_unit_changed() +{ + g_assert(_unit_menu != NULL); + + Glib::ustring abbr = _unit_menu->getUnitAbbr(); + _suffix->set_label(abbr); + + Inkscape::Util::UnitTable &table = _unit_menu->getUnitTable(); + Inkscape::Util::Unit new_unit = (table.getUnit(abbr)); + Inkscape::Util::Unit old_unit = (table.getUnit(lastUnits)); + + double convertedVal = 0; + if (old_unit.type == UNIT_TYPE_DIMENSIONLESS && new_unit.type == UNIT_TYPE_LINEAR) { + convertedVal = PercentageToAbsolute(Scalar::getValue()); + } else if (old_unit.type == UNIT_TYPE_LINEAR && new_unit.type == UNIT_TYPE_DIMENSIONLESS) { + convertedVal = AbsoluteToPercentage(Scalar::getValue()); + } else { + double conversion = _unit_menu->getConversion(lastUnits); + convertedVal = Scalar::getValue() / conversion; + } + Scalar::setValue(convertedVal); + + lastUnits = abbr; +} + +} // namespace Widget +} // namespace UI +} // namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/pool/shard006/C++/0074714_nextStateMapping.cpp b/pool/shard006/C++/0074714_nextStateMapping.cpp new file mode 100644 index 0000000000000000000000000000000000000000..296d445a11f398e17686f3f8e2e04b9226c405bc --- /dev/null +++ b/pool/shard006/C++/0074714_nextStateMapping.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include + +#include "dynUtf8Parser/dfa/nextStateMapping.h" + +using namespace DeterministicFiniteAutomaton; + +#ifndef NUM_DFA_STATES_PER_BLOCK +#define NUM_DFA_STATES_PER_BLOCK 20 +#endif + +NextStateMapping::NextStateMapping(StateAllocator *anAllocator) { + allocator = anAllocator; + dfaStateProbeSize = allocator->getStateSize() + sizeof(utf8Char_t); + dfaStateProbe = (char*)calloc(dfaStateProbeSize, sizeof(uint8_t)); + nextDFAStateMap = hattrie_create(); +}; + +NextStateMapping::~NextStateMapping(void) { + allocator = NULL; + dfaStateProbeSize = 0; + if (dfaStateProbe) free(dfaStateProbe); + dfaStateProbe = NULL; + if (nextDFAStateMap) hattrie_free(nextDFAStateMap); + nextDFAStateMap = NULL; +} + +void NextStateMapping::assembleStateCharacterProbe(State *state, + utf8Char_t curChar) { + assembleStateProbe(state); + size_t stateSize = allocator->getStateSize(); + for (size_t j = 0; j < sizeof(utf8Char_t); j++) { + dfaStateProbe[stateSize+j] = curChar.c[j]; + } +} + +void NextStateMapping::assembleStateClassificationProbe(State *state, + Classifier::classSet_t classification) { + assembleStateProbe(state); + size_t stateSize = allocator->getStateSize(); + for (size_t j = 0; j < sizeof(Classifier::classSet_t); j++) { + dfaStateProbe[stateSize+j] = ((uint8_t*)(&classification))[j]; + } +} + +State *NextStateMapping::registerState(State *state) { + assembleStateProbe(state); + size_t stateSize = allocator->getStateSize(); + State **registeredValue = (State**)hattrie_get(nextDFAStateMap, + dfaStateProbe, + stateSize); + if (!registeredValue) throw ParserException("Hat-Trie failure"); + if (!*registeredValue) *registeredValue = state; + return *registeredValue; +} + diff --git a/pool/shard006/C++/0074716_PreviewArea.cpp b/pool/shard006/C++/0074716_PreviewArea.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ceece7f0a578bf25e2a9747468051d494080ff6 --- /dev/null +++ b/pool/shard006/C++/0074716_PreviewArea.cpp @@ -0,0 +1,154 @@ + +#include +#include +#include "sifedit.h" +#include "PreviewArea.h" +#include "MainWindow.h" +#include "PreviewArea.fdh" + +BEGIN_EVENT_TABLE(PreviewArea, wxPanel) + EVT_PAINT(PreviewArea::OnPaint) + EVT_LEFT_DOWN(PreviewArea::OnClick) +END_EVENT_TABLE() + +/* +void c------------------------------() {} +*/ + +PreviewArea::PreviewArea(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size) + : wxPanel(parent, id, pos, size) +{ + fSpritesheetBitmap = NULL; + fSheetNo = -1; +} + +PreviewArea::~PreviewArea() +{ +} + +/* +void c------------------------------() {} +*/ + +void PreviewArea::OnPaint(wxPaintEvent &event) +{ + wxPaintDC dc(this); + + SpriteRecord *cursprite = CurSprite(); + if (!cursprite) return; + + int required_sheetno = cursprite->spritesheet; + if (!fSpritesheetBitmap || fSheetNo != required_sheetno) + { + if (LoadSpritesheet(required_sheetno)) + return; + } + + int boxwidth = GetSize().GetWidth(); + int boxheight = GetSize().GetHeight(); + + wxBitmap bbbmp(boxwidth, boxheight); + wxMemoryDC bbdc(bbbmp); + + // clear everything + bbdc.SetPen(*wxTRANSPARENT_PEN); + + bbdc.SetBrush(wxBrush(wxColour(0, 0, 41))); + bbdc.DrawRectangle(0, 0, boxwidth, boxheight); + + wxBrush hash = wxBrush(wxColour(100, 100, 181)); + hash.SetStyle(wxCROSSDIAG_HATCH); + + bbdc.SetBrush(hash); + bbdc.DrawRectangle(0, 0, boxwidth, boxheight); + + // blit in current spritesheet + // center current sprite in it + int x, y; + + x = CurDir()->sheet_offset.x; + y = CurDir()->sheet_offset.y; + + x -= boxwidth / 2; + y -= boxheight / 2; + + x += cursprite->w / 2; + y += cursprite->h / 2; + + bbdc.DrawBitmap(*fSpritesheetBitmap, -x, -y); + + // draw guidelines for area used by sprite + /*int x1, y1, x2, y2; + + x1 = boxwidth / 2; + y1 = boxheight / 2; + + x1 -= cursprite->w / 2; + x2 = x1 + cursprite->w; + + y1 -= cursprite->h / 2; + y2 = y1 + cursprite->h; + + bbdc.SetPen(wxPen(wxColour(120, 120, 190))); + bbdc.DrawLine(x1, 0, x1, boxheight); + bbdc.DrawLine(x2, 0, x2, boxheight); + bbdc.DrawLine(0, y1, boxwidth, y1); + bbdc.DrawLine(0, y2, boxwidth, y2);*/ + + dc.Blit(0, 0, bbdc.GetSize().GetWidth(), bbdc.GetSize().GetHeight(), &bbdc, 0, 0); +} + + +bool PreviewArea::LoadSpritesheet(int sheetno) +{ + fSheetNo = -1; + delete fSpritesheetBitmap; + fSpritesheetBitmap = NULL; + + const char *filename = gd.sheetfiles.StringAt(sheetno); + if (!filename) + { + staterr("PreviewArea::LoadSpritesheet: filename unknown for sheet # %d", sheetno); + return 1; + } + + wxImage spritesheet; + if (load_spritesheet(&spritesheet, filename)) + { + staterr("PreviewArea::LoadSpritesheet: failed to load file '%s'", filename); + return 1; + } + + fSpritesheetBitmap = new wxBitmap(spritesheet); + fSheetNo = sheetno; + return 0; +} + +/* +void c------------------------------() {} +*/ + +void PreviewArea::OnClick(wxMouseEvent &event) +{ + if (save_sif(gd.openfilename)) + { + wxMessageBox(_T("Save failed! Please check command line for details."), \ + _T("Error"), wxOK | wxICON_ERROR, this); + return; + } + + mainwin->Close(true); +} + + + + + + + + + + + + + diff --git a/pool/shard006/C++/0074718_poppler-ps-converter.cc b/pool/shard006/C++/0074718_poppler-ps-converter.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e81b7097b5d6412c96365870a6888046990d0ab --- /dev/null +++ b/pool/shard006/C++/0074718_poppler-ps-converter.cc @@ -0,0 +1,275 @@ +/* poppler-ps-converter.cc: qt interface to poppler + * Copyright (C) 2007, 2009, 2010, Albert Astals Cid + * Copyright (C) 2008, Pino Toscano + * Copyright (C) 2010 Hib Eris + * Copyright (C) 2011 Glad Deschrijver + * Copyright (C) 2012 Fabio D'Urso + * Copyright (C) 2013 Thomas Freitag + * Copyright (C) 2014 Adrian Johnson + * + * 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, 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 "poppler-qt5.h" + +#include "poppler-private.h" +#include "poppler-converter-private.h" + +#include "PSOutputDev.h" + +static void outputToQIODevice(void *stream, const char *data, int len) +{ + static_cast(stream)->write(data, len); +} + +namespace Poppler { + +class PSConverterPrivate : public BaseConverterPrivate +{ + public: + PSConverterPrivate(); + + QList pageList; + QString title; + double hDPI; + double vDPI; + int rotate; + int paperWidth; + int paperHeight; + int marginRight; + int marginBottom; + int marginLeft; + int marginTop; + PSConverter::PSOptions opts; + void (* pageConvertedCallback)(int page, void *payload); + void *pageConvertedPayload; +}; + +PSConverterPrivate::PSConverterPrivate() + : BaseConverterPrivate(), + hDPI(72), vDPI(72), rotate(0), paperWidth(-1), paperHeight(-1), + marginRight(0), marginBottom(0), marginLeft(0), marginTop(0), + opts(PSConverter::Printing), pageConvertedCallback(0), + pageConvertedPayload(0) +{ +} + + +PSConverter::PSConverter(DocumentData *document) + : BaseConverter(*new PSConverterPrivate()) +{ + Q_D(PSConverter); + d->document = document; +} + +PSConverter::~PSConverter() +{ +} + +void PSConverter::setPageList(const QList &pageList) +{ + Q_D(PSConverter); + d->pageList = pageList; +} + +void PSConverter::setTitle(const QString &title) +{ + Q_D(PSConverter); + d->title = title; +} + +void PSConverter::setHDPI(double hDPI) +{ + Q_D(PSConverter); + d->hDPI = hDPI; +} + +void PSConverter::setVDPI(double vDPI) +{ + Q_D(PSConverter); + d->vDPI = vDPI; +} + +void PSConverter::setRotate(int rotate) +{ + Q_D(PSConverter); + d->rotate = rotate; +} + +void PSConverter::setPaperWidth(int paperWidth) +{ + Q_D(PSConverter); + d->paperWidth = paperWidth; +} + +void PSConverter::setPaperHeight(int paperHeight) +{ + Q_D(PSConverter); + d->paperHeight = paperHeight; +} + +void PSConverter::setRightMargin(int marginRight) +{ + Q_D(PSConverter); + d->marginRight = marginRight; +} + +void PSConverter::setBottomMargin(int marginBottom) +{ + Q_D(PSConverter); + d->marginBottom = marginBottom; +} + +void PSConverter::setLeftMargin(int marginLeft) +{ + Q_D(PSConverter); + d->marginLeft = marginLeft; +} + +void PSConverter::setTopMargin(int marginTop) +{ + Q_D(PSConverter); + d->marginTop = marginTop; +} + +void PSConverter::setStrictMargins(bool strictMargins) +{ + Q_D(PSConverter); + if (strictMargins) + d->opts |= StrictMargins; + else + d->opts &= ~StrictMargins; +} + +void PSConverter::setForceRasterize(bool forceRasterize) +{ + Q_D(PSConverter); + if (forceRasterize) + d->opts |= ForceRasterization; + else + d->opts &= ~ForceRasterization; +} + +void PSConverter::setPSOptions(PSConverter::PSOptions options) +{ + Q_D(PSConverter); + d->opts = options; +} + +PSConverter::PSOptions PSConverter::psOptions() const +{ + Q_D(const PSConverter); + return d->opts; +} + +void PSConverter::setPageConvertedCallback(void (* callback)(int page, void *payload), void *payload) +{ + Q_D(PSConverter); + d->pageConvertedCallback = callback; + d->pageConvertedPayload = payload; +} + +static GBool annotDisplayDecideCbk(Annot *annot, void *user_data) +{ + if (annot->getType() == Annot::typeWidget) + return gTrue; // Never hide forms + else + return *(GBool*)user_data; +} + +bool PSConverter::convert() +{ + Q_D(PSConverter); + d->lastError = NoError; + + Q_ASSERT(!d->pageList.isEmpty()); + Q_ASSERT(d->paperWidth != -1); + Q_ASSERT(d->paperHeight != -1); + + if (d->document->locked) + { + d->lastError = FileLockedError; + return false; + } + + QIODevice *dev = d->openDevice(); + if (!dev) + { + d->lastError = OpenOutputError; + return false; + } + + QByteArray pstitle8Bit = d->title.toLocal8Bit(); + char* pstitlechar; + if (!d->title.isEmpty()) pstitlechar = pstitle8Bit.data(); + else pstitlechar = 0; + + PSOutputDev *psOut = new PSOutputDev(outputToQIODevice, dev, + pstitlechar, + d->document->doc, + 1, + d->document->doc->getNumPages(), + (d->opts & PrintToEPS) ? psModeEPS : psModePS, + d->paperWidth, + d->paperHeight, + gFalse, + gFalse, + d->marginLeft, + d->marginBottom, + d->paperWidth - d->marginRight, + d->paperHeight - d->marginTop, + (d->opts & ForceRasterization)); + + if (d->opts & StrictMargins) + { + double xScale = ((double)d->paperWidth - (double)d->marginLeft - (double)d->marginRight) / (double)d->paperWidth; + double yScale = ((double)d->paperHeight - (double)d->marginBottom - (double)d->marginTop) / (double)d->paperHeight; + psOut->setScale(xScale, yScale); + } + + if (psOut->isOk()) + { + GBool isPrinting = (d->opts & Printing) ? gTrue : gFalse; + GBool showAnnotations = (d->opts & HideAnnotations) ? gFalse : gTrue; + foreach(int page, d->pageList) + { + d->document->doc->displayPage(psOut, + page, + d->hDPI, + d->vDPI, + d->rotate, + gFalse, + gTrue, + isPrinting, + NULL, + NULL, + annotDisplayDecideCbk, + &showAnnotations, gTrue); + if (d->pageConvertedCallback) + (*d->pageConvertedCallback)(page, d->pageConvertedPayload); + } + delete psOut; + d->closeDevice(); + return true; + } + else + { + delete psOut; + d->closeDevice(); + return false; + } +} + +} diff --git a/pool/shard006/C++/0074720_SharingInviteeInfo.cpp b/pool/shard006/C++/0074720_SharingInviteeInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d130e178bff93fe6371076ebbd1498959018809a --- /dev/null +++ b/pool/shard006/C++/0074720_SharingInviteeInfo.cpp @@ -0,0 +1,69 @@ +/********************************************************** + DO NOT EDIT + This file was generated from stone specification "sharing" + www.prokarpaty.net +***********************************************************/ + +#include "dropbox/sharing/SharingInviteeInfo.h" + +namespace dropboxQt{ + +namespace sharing{ +///InviteeInfo + +InviteeInfo::operator QJsonObject()const{ + QJsonObject js; + this->toJson(js, ""); + return js; +} + + +void InviteeInfo::toJson(QJsonObject& js, QString name)const{ + + switch(m_tag){ + case InviteeInfo_EMAIL:{ + if(!name.isEmpty()) + js[name] = QString("email"); + if(!m_email.isEmpty()) + js["email"] = QString(m_email); + }break; + case InviteeInfo_OTHER:{ + if(!name.isEmpty()) + js[name] = QString("other"); + }break; + }//switch +} + +void InviteeInfo::fromJson(const QJsonObject& js){ + + QString s = js[".tag"].toString(); + if(s.compare("email") == 0){ + m_tag = InviteeInfo_EMAIL; + m_email = js["email"].toString(); + } + else if(s.compare("other") == 0){ + m_tag = InviteeInfo_OTHER; + + } +} + +QString InviteeInfo::toString(bool multiline)const +{ + QJsonObject js; + toJson(js, "InviteeInfo"); + QJsonDocument doc(js); + QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact)); + return s; +} + +std::unique_ptr InviteeInfo::factory::create(const QByteArray& data) +{ + QJsonDocument doc = QJsonDocument::fromJson(data); + QJsonObject js = doc.object(); + std::unique_ptr rv = std::unique_ptr(new InviteeInfo); + rv->fromJson(js); + return rv; +} + +}//sharing +}//dropboxQt diff --git a/pool/shard006/C++/0074721_showgnu.cpp b/pool/shard006/C++/0074721_showgnu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf35dca157015312d696341b250bdecd3e19c846 --- /dev/null +++ b/pool/shard006/C++/0074721_showgnu.cpp @@ -0,0 +1,148 @@ +/*************************************************************************** +* Copyright (C) 2007 Eddie Carle [eddie@erctech.org] * +* * +* This file is part of fastcgi++. * +* * +* fastcgi++ 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. * +* * +* fastcgi++ 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 fastcgi++. If not, see . * +****************************************************************************/ + + +#include +#include + +#include +#include +#include + +#include +#include + +// I like to have an independent error log file to keep track of exceptions while debugging. +// You might want a different filename. I just picked this because everything has access there. +void error_log(const char* msg) +{ + using namespace std; + using namespace boost; + static ofstream error; + if(!error.is_open()) + { + error.open("/tmp/errlog", ios_base::out | ios_base::app); + error.imbue(locale(error.getloc(), new posix_time::time_facet())); + } + + error << '[' << posix_time::second_clock::local_time() << "] " << msg << endl; +} + +// Let's make our request handling class. It must do the following: +// 1) Be derived from Fastcgipp::Request +// 2) Define the virtual response() member function from Fastcgipp::Request() + +// First things first let's decide on what kind of character set we will use. +// Since we are just displaying an image, we won't need unicode so we don't +// need to use wide characters. We'll keep everything as narrow characters +// and pass the 'char' type along to the Fastcgipp::Request template. + +class ShowGnu: public Fastcgipp::Request +{ + // Now we define the actual function that sends a response to the client. + bool response() + { + using namespace std; + using namespace boost; + + // We are going to use boost::posix_time::ptime to communicate + // the images modification time for cache purposes. + posix_time::ptime modTime; + int fileSize; + int etag; + + + { + // Using the linux stat function (man 2 stat) to get the modification time and filesize beforehand. + struct stat fileStat; + stat("gnu.png", &fileStat); + fileSize = fileStat.st_size; + modTime = posix_time::from_time_t(fileStat.st_mtime); + + // We'll use the files inode as the etag + etag = fileStat.st_ino; + } + + // We need to call this to set a facet in our requests locale regarding how + // to format the date upon insertion. It needs to conform to the http standard. + setloc(locale(getloc(), new posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT"))); + + // If the modification time of the file is older or equal to the if-modified-since value + // sent to us from the client and we were actually sent an if-modified since value, + // we don't need to send the image to them. + if(!environment().ifModifiedSince.is_not_a_date_time() && etag==environment().etag && modTime<=environment().ifModifiedSince) + { + out << "Status: 304 Not Modified\r\n\r\n"; + return true; + } + + // Setup an fstream for our file. + std::ifstream image("gnu.png"); + + // Now we transmit our HTTP header to the client + // First we send the modification time of the file + out << "Last-Modified: " << modTime << '\n'; + // Then a Etag. Note that the environment().etag is an integer value. NOT an std::string. + out << "Etag: " << etag << '\n'; + // Next the size + out << "Content-Length: " << fileSize << '\n'; + // Then content type. Remember an HTTP header is supposed to be + // terminated with \r\n\r\n NOT just \n\n + out << "Content-Type: image/png\r\n\r\n"; + + // Now that the header is sent, we can transmit the actual image. + // To send raw binary data to the client, the streams have a + // dump function that bypasses the streambuffer and it's code + // conversion. The function is overloaded to either: + // out.dump(basic_istream& stream); or + // out.dump(char* data, size_t size); + // + // Remember that if we are using wide characters internally, the stream + // converts anything sent into the stream to UTF-8 before transmitting + // to the client. If we want to send binary data, we definitely don't want + // any code conversion so that is why this function exists. + out.dump(image); + + // Always return true if you are done. This will let apache know we are done + // and the manager will destroy the request and free it's resources. + // Return false if you are not finished but want to relinquish control and + // allow other requests to operate. You might do this after an SQL query + // while waiting for a reply. Passing messages to requests through the + // manager is possible but beyond the scope of this example. + return true; + } +}; + +// The main function is easy to set up +int main() +{ + try + { + // First we make a Fastcgipp::Manager object, with our request handling class + // as a template parameter. + Fastcgipp::Manager fcgi; + // Now just call the object handler function. It will sleep quietly when there + // are no requests and efficiently manage them when there are many. + fcgi.handler(); + } + catch(std::exception& e) + { + error_log(e.what()); + } +} diff --git a/pool/shard006/C++/0074728_profile_sync_auth_provider.cc b/pool/shard006/C++/0074728_profile_sync_auth_provider.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a2167413a5f5452466ccb1730fa2ce6677141f0 --- /dev/null +++ b/pool/shard006/C++/0074728_profile_sync_auth_provider.cc @@ -0,0 +1,137 @@ +// Copyright 2014 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 "components/sync_driver/profile_sync_auth_provider.h" + +#include "base/bind.h" +#include "base/location.h" +#include "base/single_thread_task_runner.h" +#include "base/thread_task_runner_handle.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "google_apis/gaia/gaia_constants.h" + +// This is thin proxy class for forwarding calls between sync and UI threads. +// The main purpose is to hide the fact that ProfileSyncAuthProvider and +// SyncThreadProxy have independent lifetimes. If ProfileSyncAuthProvider is +// destroyed first calls to RequestAccessToken will never complete. This is fine +// since sync thread is not blocked and is in the process of shutdown anyway. +class ProfileSyncAuthProvider::SyncThreadProxy + : public syncer::SyncAuthProvider, + public base::NonThreadSafe { + public: + SyncThreadProxy( + base::WeakPtr provider_impl, + scoped_refptr provider_task_runner); + + // syncer::SyncAuthProvider implementation. + void RequestAccessToken(const RequestTokenCallback& callback) override; + void InvalidateAccessToken(const std::string& token) override; + + private: + base::WeakPtr provider_impl_; + scoped_refptr provider_task_runner_; + + DISALLOW_COPY_AND_ASSIGN(SyncThreadProxy); +}; + +ProfileSyncAuthProvider::SyncThreadProxy::SyncThreadProxy( + base::WeakPtr provider_impl, + scoped_refptr provider_task_runner) + : provider_impl_(provider_impl), + provider_task_runner_(provider_task_runner) { + // SyncThreadProxy is created on UI thread but used on sync thread. + // Detach NonThreadSafe from UI thread so that it can reattach to sync thread + // on first invocation. + DetachFromThread(); +} + +void ProfileSyncAuthProvider::SyncThreadProxy::RequestAccessToken( + const RequestTokenCallback& callback) { + DCHECK(CalledOnValidThread()); + provider_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ProfileSyncAuthProvider::RequestAccessToken, + provider_impl_, + callback, + base::ThreadTaskRunnerHandle::Get())); +} + +void ProfileSyncAuthProvider::SyncThreadProxy::InvalidateAccessToken( + const std::string& token) { + DCHECK(CalledOnValidThread()); + provider_task_runner_->PostTask( + FROM_HERE, + base::Bind(&ProfileSyncAuthProvider::InvalidateAccessToken, + provider_impl_, + token)); +} + +ProfileSyncAuthProvider::ProfileSyncAuthProvider( + ProfileOAuth2TokenService* token_service, + const std::string& account_id, + const std::string& scope) + : OAuth2TokenService::Consumer("sync_auth_provider"), + token_service_(token_service), + account_id_(account_id), + weak_factory_(this) { + oauth2_scope_.insert(scope); +} + +ProfileSyncAuthProvider::~ProfileSyncAuthProvider() { + DCHECK(CalledOnValidThread()); +} + +void ProfileSyncAuthProvider::RequestAccessToken( + const syncer::SyncAuthProvider::RequestTokenCallback& callback, + scoped_refptr task_runner) { + DCHECK(CalledOnValidThread()); + if (access_token_request_ != NULL) { + // If there is already pending request report it as cancelled. + GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED); + RespondToTokenRequest(error, std::string()); + } + request_token_callback_ = callback; + callback_task_runner_ = task_runner; + access_token_request_ = + token_service_->StartRequest(account_id_, oauth2_scope_, this); +} + +void ProfileSyncAuthProvider::OnGetTokenSuccess( + const OAuth2TokenService::Request* request, + const std::string& access_token, + const base::Time& expiration_time) { + DCHECK_EQ(access_token_request_, request); + RespondToTokenRequest(GoogleServiceAuthError::AuthErrorNone(), access_token); +} + +void ProfileSyncAuthProvider::OnGetTokenFailure( + const OAuth2TokenService::Request* request, + const GoogleServiceAuthError& error) { + DCHECK_EQ(access_token_request_, request); + RespondToTokenRequest(error, std::string()); +} + +void ProfileSyncAuthProvider::RespondToTokenRequest( + const GoogleServiceAuthError& error, + const std::string& token) { + DCHECK(CalledOnValidThread()); + callback_task_runner_->PostTask( + FROM_HERE, base::Bind(request_token_callback_, error, token)); + access_token_request_.reset(); + request_token_callback_.Reset(); + callback_task_runner_ = NULL; +} + +void ProfileSyncAuthProvider::InvalidateAccessToken(const std::string& token) { + DCHECK(CalledOnValidThread()); + token_service_->InvalidateAccessToken(account_id_, oauth2_scope_, token); +} + +scoped_ptr +ProfileSyncAuthProvider::CreateProviderForSyncThread() { + DCHECK(CalledOnValidThread()); + scoped_ptr auth_provider(new SyncThreadProxy( + weak_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get())); + return auth_provider.Pass(); +} diff --git a/pool/shard006/C++/0074732_TeamListTeamAppsError.cpp b/pool/shard006/C++/0074732_TeamListTeamAppsError.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccc46f3d27fcc0a6066d74a2b4baf0e08fcd9ab2 --- /dev/null +++ b/pool/shard006/C++/0074732_TeamListTeamAppsError.cpp @@ -0,0 +1,67 @@ +/********************************************************** + DO NOT EDIT + This file was generated from stone specification "team" + www.prokarpaty.net +***********************************************************/ + +#include "dropbox/team/TeamListTeamAppsError.h" + +namespace dropboxQt{ + +namespace team{ +///ListTeamAppsError + +ListTeamAppsError::operator QJsonObject()const{ + QJsonObject js; + this->toJson(js, ""); + return js; +} + + +void ListTeamAppsError::toJson(QJsonObject& js, QString name)const{ + + switch(m_tag){ + case ListTeamAppsError_RESET:{ + if(!name.isEmpty()) + js[name] = QString("reset"); + }break; + case ListTeamAppsError_OTHER:{ + if(!name.isEmpty()) + js[name] = QString("other"); + }break; + }//switch +} + +void ListTeamAppsError::fromJson(const QJsonObject& js){ + + QString s = js[".tag"].toString(); + if(s.compare("reset") == 0){ + m_tag = ListTeamAppsError_RESET; + + } + else if(s.compare("other") == 0){ + m_tag = ListTeamAppsError_OTHER; + + } +} + +QString ListTeamAppsError::toString(bool multiline)const +{ + QJsonObject js; + toJson(js, "ListTeamAppsError"); + QJsonDocument doc(js); + QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact)); + return s; +} + +std::unique_ptr ListTeamAppsError::factory::create(const QByteArray& data) +{ + QJsonDocument doc = QJsonDocument::fromJson(data); + QJsonObject js = doc.object(); + std::unique_ptr rv = std::unique_ptr(new ListTeamAppsError); + rv->fromJson(js); + return rv; +} + +}//team +}//dropboxQt diff --git a/pool/shard006/C++/0074741_decimal_conversion_to.cpp b/pool/shard006/C++/0074741_decimal_conversion_to.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9933dacb6dde58901c0394319e930e62382cdcc1 --- /dev/null +++ b/pool/shard006/C++/0074741_decimal_conversion_to.cpp @@ -0,0 +1,166 @@ +#include "common_header.h" + +#include "number_convertion.h" + + +namespace { + +/** + * @reference Implement your own itoa() + * https://www.geeksforgeeks.org/implement-itoa/ + */ +auto DecimalTo(unsigned number, const int base, + const std::function to_digit) { + std::string result; + for (; number; number /= base) { + result.push_back(to_digit(number % base)); + } + + std::reverse(result.begin(), result.end()); + return result; +} + + +/** Program for Decimal to Octal Conversion + * + * @reference https://www.geeksforgeeks.org/program-decimal-octal-conversion/ + * @reference Decimal to octal conversion with minimum use of arithmetic operators + * https://www.geeksforgeeks.org/decimal-octal-conversion-minimum-use-arithmetic-operators/ + */ +inline auto ToOctal(const int number) { + return DecimalTo(number, 8, [](const auto digit) { + return '0' + digit; + }); +} + + +/** Program for decimal to hexadecimal conversion + * + * @reference https://www.geeksforgeeks.org/program-decimal-hexadecimal-conversion/ + * @reference Convert Decimal To Hexa-Decimal including negative numbers + * https://www.geeksforgeeks.org/convert-decimal-to-hexa-decimal-including-negative-numbers/ + * + * @reference Convert a Number to Hexadecimal + * https://leetcode.com/problems/convert-a-number-to-hexadecimal/ + * + * Given an integer num, return a string representing its hexadecimal representation. + * For negative integers, two's complement method is used. All the letters in the answer + * string should be lowercase characters, and there should not be any leading zeros in + * the answer except for the zero itself. Note: You are not allowed to use any built-in + * library method to directly solve this problem. + */ +inline auto ToHex(const int number) { + return DecimalTo(number, 16, ToHexDigit); +} + + +/** + * @reference Hexspeak + * https://www.cnblogs.com/seyjs/p/11967411.html + * + * A decimal number can be converted to its Hexspeak representation by first converting + * it to an uppercase hexadecimal string, then replacing all occurrences of the digit 0 + * with the letter O, and the digit 1 with the letter I. Such a representation is valid + * if and only if it consists only of the letters in the set + * {"A", "B", "C", "D", "E", "F", "I", "O"}. Given a string num representing a decimal + * integer N, return the Hexspeak representation of N if it is valid, otherwise return + * "ERROR". + * All answers must be in uppercase letters. + */ + + +/** + * @reference Base 7 + * https://leetcode.com/problems/base-7/ + * + * Given an integer num, return a string of its base 7 representation. + */ + + +/** + * @reference Excel Sheet Column Title + * https://leetcode.com/problems/excel-sheet-column-title/ + * + * Given an integer columnNumber, return its corresponding column title as it appears + * in an Excel sheet. + */ +auto ToColumnTitle(int number) { + std::string result; + while (number--) { + result.push_back('A' + (number % 26)); + number /= 26; + } + + std::reverse(result.begin(), result.end()); + return result; +} + + +/** + * @reference Excel Sheet Column Number + * https://leetcode.com/problems/excel-sheet-column-number/ + * + * Given a string columnTitle that represents the column title as appear in an Excel + * sheet, return its corresponding column number. + */ +constexpr auto ToColumnNumber(const std::string_view column_title) { + int result = 0; + for (const auto c : column_title) { + result *= 26; + result += c - 'A' + 1; + } + + return result; +} + + +/** + * @reference Thousand Separator + * https://leetcode.com/problems/thousand-separator/ + * + * Given an integer n, add a dot (".") as the thousands separator and return it in string + * format. + */ + +}//namespace + + +THE_BENCHMARK(ToOctal, 16); + +SIMPLE_TEST(ToOctal, TestSAMPLE1, "20", 16); +SIMPLE_TEST(ToOctal, TestSAMPLE2, "12", 10); +SIMPLE_TEST(ToOctal, TestSAMPLE3, "41", 33); + + +THE_BENCHMARK(ToHex, 942); + +SIMPLE_TEST(ToHex, TestSAMPLE1, "3AE", 942); +SIMPLE_TEST(ToHex, TestSAMPLE2, "74", 116); +SIMPLE_TEST(ToHex, TestSAMPLE3, "A", 10); +SIMPLE_TEST(ToHex, TestSAMPLE4, "21", 33); +SIMPLE_TEST(ToHex, TestSAMPLE5, "9F1", 2545); +SIMPLE_TEST(ToHex, TestSAMPLE6, "FFFFFFFF", -1); + + +THE_BENCHMARK(ToColumnTitle, 2147483647); + +SIMPLE_TEST(ToColumnTitle, TestSAMPLE1, "A", 1); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE2, "B", 2); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE3, "C", 3); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE4, "Z", 26); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE5, "AA", 27); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE6, "AB", 28); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE7, "ZY", 701); +SIMPLE_TEST(ToColumnTitle, TestSAMPLE8, "FXSHRXW", 2147483647); + + +THE_BENCHMARK(ToColumnNumber, "FXSHRXW"); + +SIMPLE_TEST(ToColumnNumber, TestSAMPLE1, 1, "A"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE2, 2, "B"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE3, 3, "C"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE4, 26, "Z"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE5, 27, "AA"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE6, 28, "AB"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE7, 701, "ZY"); +SIMPLE_TEST(ToColumnNumber, TestSAMPLE8, 2147483647, "FXSHRXW"); diff --git a/pool/shard006/C++/0074759_evaluationwindow.cpp b/pool/shard006/C++/0074759_evaluationwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5bcc3c462ce337530c1bd27b8b72d4b4f1bc7fe --- /dev/null +++ b/pool/shard006/C++/0074759_evaluationwindow.cpp @@ -0,0 +1,66 @@ +/* + Copyright 2010 Stephan Martin, Dominik Gummel + + This file is part of Multidisplay. + + Multidisplay 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. + + Multidisplay 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 Multidisplay. If not, see . +*/ + +#include +#include "evaluationwindow.h" +#include "EvalSpectrogramPlot.h" + +//EvaluationWindow::EvaluationWindow(Ui::MultidisplayUIMainWindowClass *main_ui, MdData* data, Type type) +// : QWidget(NULL), main_ui(main_ui), data(data), ep(NULL) +EvaluationWindow::EvaluationWindow(QWidget *parent, MdData* data, Type type) + : QDialog(parent), data(data), ep(NULL) + +{ + + ui.setupUi(this); + +//#ifdef Q_WS_MAEMO_5 +// setAttribute(Qt::WA_Maemo5StackedWindow); +//#endif + + switch (type) { + case BoostLambda : + ep = new EvalPlotBoostLambda ((QMainWindow*) this, (QWidget*) ui.PlotFrame); + break; + case RPMBoost : + ep = new EvalPlotRPMBoost ((QMainWindow*) this, (QWidget*) ui.PlotFrame); + break; + case SpectroBoostLambda : + ep = new EvalSpectrogramPlot ((QMainWindow*) this, (QWidget*) ui.PlotFrame); + break; + default: + ep = NULL; + } + + connect (ui.OkButton, SIGNAL(clicked()), this, SLOT(hide() ) ); +} + + + +EvaluationWindow::~EvaluationWindow() +{ + delete (ep); +} + +void EvaluationWindow::showEvent ( QShowEvent * event ) { + if ( !(event->spontaneous()) && (event->type() == QEvent::Show) ) { + ep->compute(data); + qDebug() << "void EvaluationWindow::showEvent ( QShowEvent * event ) compute called"; + } +} diff --git a/pool/shard006/C++/0074760_t_urlencode.cc b/pool/shard006/C++/0074760_t_urlencode.cc new file mode 100644 index 0000000000000000000000000000000000000000..5fbd5c9685c5d64a11de48dccf9be54d23635943 --- /dev/null +++ b/pool/shard006/C++/0074760_t_urlencode.cc @@ -0,0 +1,187 @@ +/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* + * Copyright 2012 Couchbase, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "config.h" +#include +#include +#include + +class UrlEncoding : public ::testing::Test +{ +}; + +TEST_F(UrlEncoding, plainTextTests) +{ + char *out; + lcb_size_t nout; + + std::string input("abcdef"); + std::string exp("abcdef"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(exp, output); + free(out); +} + +TEST_F(UrlEncoding, plainTextWithSlashTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a/b/c/d/e/f/g/h/i/j"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(input, output); + free(out); +} + +TEST_F(UrlEncoding, plainTextWithSpaceTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a b c d e f g"); + std::string exp("a%20b%20c%20d%20e%20f%20g"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(exp, output); + free(out); +} + +TEST_F(UrlEncoding, encodedTextWithPlusAsApaceTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a+b+c+d+e+g+h"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(input, output); + free(out); +} + +TEST_F(UrlEncoding, encodedTextWithPlusAndHexAsApaceTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a+b%20c%20d+e+g+h"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(input, output); + free(out); +} + +TEST_F(UrlEncoding, mixedLegalTextTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a/b/c/d/e f g+32%20"); + std::string exp("a/b/c/d/e%20f%20g+32%20"); + + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + + EXPECT_EQ(exp, output); + free(out); +} + +TEST_F(UrlEncoding, mixedIllegalEncodingTextTests) +{ + char *out; + lcb_size_t nout; + + std::string input("a+ "); + + EXPECT_EQ(LCB_INVALID_CHAR, lcb_urlencode_path(input.data(), + input.length(), + &out, &nout)); +} + +TEST_F(UrlEncoding, internationalTest) +{ + char *out; + lcb_size_t nout; + std::string input("_design/beer/_view/all?startkey=\"\xc3\xb8l\""); + std::string exp("_design/beer/_view/all?startkey=%22%C3%B8l%22"); + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(exp, output); + free(out); +} + +TEST_F(UrlEncoding, internationalEncodedTest) +{ + char *out; + lcb_size_t nout; + std::string input("_design/beer/_view/all?startkey=%22%C3%B8l%22"); + std::string exp("_design/beer/_view/all?startkey=%22%C3%B8l%22"); + EXPECT_EQ(LCB_SUCCESS, lcb_urlencode_path(input.data(), input.length(), + &out, &nout)); + std::string output(out, nout); + + EXPECT_EQ(exp, output); + free(out); +} + +TEST_F(UrlEncoding, testDecode) +{ + char obuf[4096]; + ASSERT_EQ(0, lcb_urldecode("%22", obuf, 3)) << "Single character"; + ASSERT_STREQ("\x22", obuf); + + ASSERT_EQ(0, lcb_urldecode("Hello World", obuf, -1)) << "No pct encode"; + ASSERT_STREQ("Hello World", obuf); + + ASSERT_EQ(0, lcb_urldecode("Hello%20World", obuf, -1)); + ASSERT_STREQ("Hello World", obuf); + + ASSERT_EQ(0, lcb_urldecode("%2Ffoo%2Fbar%2Fbaz%2F", obuf, -1)); + ASSERT_STREQ("/foo/bar/baz/", obuf); + + ASSERT_EQ(0, lcb_urldecode("%01%02%03%04", obuf, -1)) << "Multiple octets"; + ASSERT_STREQ("\x01\x02\x03\x04", obuf); + + ASSERT_EQ(0, lcb_urldecode("%FFFF", obuf, -1)) << "Recognize only first two hex digits"; + // Split the hex literal so we don't confuse the preprocessor + ASSERT_STREQ("\xff" "FF", obuf); + + // Error tests + ASSERT_EQ(-1, lcb_urldecode("%", obuf, -1)); + ASSERT_EQ(-1, lcb_urldecode("%22", obuf, 1)); + ASSERT_EQ(-1, lcb_urldecode("%22", obuf, 2)); + ASSERT_EQ(-1, lcb_urldecode("%RR", obuf, -1)) << "Invalid hex digits"; +} diff --git a/pool/shard006/C++/0074761_WebSocketExtensionDispatcher.cpp b/pool/shard006/C++/0074761_WebSocketExtensionDispatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcc9dc3d9cd3b2717ae41a9c590da5d9035d0ae7 --- /dev/null +++ b/pool/shard006/C++/0074761_WebSocketExtensionDispatcher.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2012 Google Inc. 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 Google Inc. 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 THE COPYRIGHT + * OWNER OR CONTRIBUTORS 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 "config.h" + +#include "WebSocketExtensionDispatcher.h" +#include "WebSocketExtensionParser.h" +#include +#include +#include +#include + +namespace WebCore { + +void WebSocketExtensionDispatcher::reset() +{ + m_processors.clear(); +} + +void WebSocketExtensionDispatcher::addProcessor(std::unique_ptr processor) +{ + for (auto& extensionProcessor : m_processors) { + if (extensionProcessor->extensionToken() == processor->extensionToken()) + return; + } + ASSERT(processor->handshakeString().length()); + ASSERT(!processor->handshakeString().contains('\n')); + ASSERT(!processor->handshakeString().contains(static_cast('\0'))); + m_processors.append(WTFMove(processor)); +} + +const String WebSocketExtensionDispatcher::createHeaderValue() const +{ + size_t numProcessors = m_processors.size(); + if (!numProcessors) + return String(); + + StringBuilder builder; + builder.append(m_processors[0]->handshakeString()); + for (size_t i = 1; i < numProcessors; ++i) { + builder.appendLiteral(", "); + builder.append(m_processors[i]->handshakeString()); + } + return builder.toString(); +} + +void WebSocketExtensionDispatcher::appendAcceptedExtension(const String& extensionToken, HashMap& extensionParameters) +{ + if (!m_acceptedExtensionsBuilder.isEmpty()) + m_acceptedExtensionsBuilder.appendLiteral(", "); + m_acceptedExtensionsBuilder.append(extensionToken); + // FIXME: Should use ListHashSet to keep the order of the parameters. + for (auto& parameter : extensionParameters) { + m_acceptedExtensionsBuilder.appendLiteral("; "); + m_acceptedExtensionsBuilder.append(parameter.key); + if (!parameter.value.isNull()) { + m_acceptedExtensionsBuilder.append('='); + m_acceptedExtensionsBuilder.append(parameter.value); + } + } +} + +void WebSocketExtensionDispatcher::fail(const String& reason) +{ + m_failureReason = reason; + m_acceptedExtensionsBuilder.clear(); +} + +bool WebSocketExtensionDispatcher::processHeaderValue(const String& headerValue) +{ + if (!headerValue.length()) + return true; + + // If we don't send Sec-WebSocket-Extensions header, the server should not return the header. + if (!m_processors.size()) { + fail("Received unexpected Sec-WebSocket-Extensions header"); + return false; + } + + const CString headerValueData = headerValue.utf8(); + WebSocketExtensionParser parser(headerValueData.data(), headerValueData.data() + headerValueData.length()); + while (!parser.finished()) { + String extensionToken; + HashMap extensionParameters; + if (!parser.parseExtension(extensionToken, extensionParameters)) { + fail("Sec-WebSocket-Extensions header is invalid"); + return false; + } + + size_t index = 0; + for (auto& processor : m_processors) { + if (extensionToken == processor->extensionToken()) { + if (processor->processResponse(extensionParameters)) { + appendAcceptedExtension(extensionToken, extensionParameters); + break; + } + fail(processor->failureReason()); + return false; + } + ++index; + } + // There is no extension which can process the response. + if (index == m_processors.size()) { + fail("Received unexpected extension: " + extensionToken); + return false; + } + } + return parser.parsedSuccessfully(); +} + +String WebSocketExtensionDispatcher::acceptedExtensions() const +{ + if (m_acceptedExtensionsBuilder.isEmpty()) + return String(); + return m_acceptedExtensionsBuilder.toStringPreserveCapacity(); +} + +String WebSocketExtensionDispatcher::failureReason() const +{ + return m_failureReason; +} + +} // namespace WebCore diff --git a/pool/shard006/C++/0074768_test.cpp b/pool/shard006/C++/0074768_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66519ea5fef9bd18bf936b55e7af4eccd5e13342 --- /dev/null +++ b/pool/shard006/C++/0074768_test.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2009-2014 Codership Oy + * + */ + +#include +#include "GCache.hpp" + +using namespace gcache; + +int +main (int argc, char* argv[]) +{ + int ret = 0; + std::string fname = "test.cache"; + + gu_conf_self_tstamp_on (); + gu_conf_debug_on (); + + log_info << "Start"; + log_debug << "DEBUG output enabled"; + + if (argc > 1) fname.assign(argv[1]); // take supplied file name if any + gu::Config conf; + GCache::register_params(conf); + conf.parse("gcache.name = test.cache; gcache.size = 16K"); + GCache* cache = new GCache (conf, ""); + + log_info << ""; + log_info << "...do something..."; + log_info << ""; + + delete cache; + + log_info << "Exit: " << ret; + + try { + throw gu::Exception ("My test exception", EINVAL); + } + catch (gu::Exception& e) { + log_info << "Exception caught: " << e.what() << ", errno: " + << e.get_errno(); + } + + return ret; +} diff --git a/pool/shard006/C++/0074771_workerThread.cpp b/pool/shard006/C++/0074771_workerThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99405ee626018fab21205a274950c69999b24638 --- /dev/null +++ b/pool/shard006/C++/0074771_workerThread.cpp @@ -0,0 +1,122 @@ +/* + * workerThread.cpp + * + * Created on: Feb 25, 2015 + * Author: jasonr + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#include "logging.h" +#include "exception.h" +#include "utils.h" +#include "workerThread.h" + +namespace Core +{ + +WorkerThread::WorkerThread(const std::string &threadname) : + m_done(false), + m_triggered(false), + m_shouldProcess(false), + m_threadName(threadname) +{ + LTHR0 << "WorkerThread::WorkerThread(): created thread \"" << threadname << "\""; +} + +WorkerThread::~WorkerThread() +{ + stop(); + if (m_thread) + m_thread->join(); +} + +void +WorkerThread::trigger() +{ + m_triggered = true; + std::unique_lock locker(m_conditionLock); + m_condition.notify_all(); +} + +void +WorkerThread::stop() +{ + // wait for current frame to finish before continuing + { + std::unique_lock locker(m_doneLock); + m_done = true; + } + + m_shouldProcess = false; + trigger(); +} + +void +WorkerThread::run() +{ + pthread_setname_np(pthread_self(), m_threadName.c_str()); + Log::setThreadName(m_threadName); + Tracing::setThreadName(m_threadName); + + LTHR0 << "WorkerThread::run() : started"; + + // loop until end is signaled + while(!m_done) + { + // wait for trigger conditional + { + std::unique_lock locker(m_conditionLock); + m_condition.wait(locker, [&](){ return m_triggered; }); + } + m_triggered = false; + + if (m_shouldProcess) + { + std::unique_lock locker(m_doneLock); + try + { + process(); + } + + catch (const OvExc &e) + { + std::cerr << "ov: exception: " << e.what() << std::endl; + std::cerr << dumpStack() << std::endl; + } + + catch (const Sg::SgExc &e) + { + std::cerr << "sg: exception: " << e.what() << std::endl; + std::cerr << dumpStack() << std::endl; + } + + catch (const std::system_error &e) + { + std::cerr << "ov: system error: " << e.code().message() << std::endl; + std::cerr << dumpStack() << std::endl; + } + + catch (const std::exception &e) + { + std::cerr << "ov: uncaught std::exception: " << e.what() << std::endl; + std::cerr << dumpStack() << std::endl; + } + + catch (...) + { + std::cerr << "ov: uncaught unknown exception." << std::endl; + std::cerr << dumpStack() << std::endl; + } + } + } + + LTHR0 << "WorkerThread::run() : stopping"; +} + +} // namespace Core diff --git a/pool/shard006/C++/0074773_PolicyTypeTranslator.cpp b/pool/shard006/C++/0074773_PolicyTypeTranslator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41130879a45002765428b69a637d35fad97cbe5e --- /dev/null +++ b/pool/shard006/C++/0074773_PolicyTypeTranslator.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/cyad/PolicyTypeTranslator.cpp + * @author Aleksander Zdyb + * @version 1.0 + * @brief A helper class to translate strings to PolicyType + */ + +#include +#include + +#include + +#include + +#include "PolicyTypeTranslator.h" + +namespace Cynara { + +namespace { + const std::string BUCKET_LITERAL = "bucket"; + const std::string NONE_LITERAL = "none"; +} /* namespace anonymous */ + +PolicyTypeTranslator::PolicyTypeTranslator() {} + +PolicyTypeTranslator::~PolicyTypeTranslator() {} + +void PolicyTypeTranslator::setDescriptions(cynara_admin_policy_descr **descs) { + for (int i = 0; descs[i]; ++i) { + std::string name(descs[i]->name); + std::transform(name.begin(), name.end(), name.begin(), ::tolower); + m_descs.push_back(std::make_pair(descs[i]->result, name)); + } +} + +PolicyType PolicyTypeTranslator::translate(const std::string &rawPolicy) { + + std::string policy(rawPolicy); + std::transform(policy.begin(), policy.end(), policy.begin(), ::tolower); + + auto descComp = [policy] (const PolicyDescriptions::value_type &it) -> bool { + return it.second == policy; + }; + + const auto it = std::find_if(m_descs.begin(), m_descs.end(), descComp); + + if (it != m_descs.end()) + return it->first; + + if (policy == NONE_LITERAL) + return CYNARA_ADMIN_NONE; + if (policy == BUCKET_LITERAL) + return CYNARA_ADMIN_BUCKET; + + try { + return std::stoi(policy, nullptr, 0); + } catch (const std::logic_error &) { + throw PolicyParsingException(); + } +} + +std::string PolicyTypeTranslator::humanize(int policy) { + auto descComp = [policy] (const PolicyDescriptions::value_type &it) -> bool { + return it.first == policy; + }; + + const auto it = std::find_if(m_descs.begin(), m_descs.end(), descComp); + + if (it != m_descs.end()) { + return it->second; + } + + if (policy == CYNARA_ADMIN_NONE) + return NONE_LITERAL; + if (policy == CYNARA_ADMIN_BUCKET) + return BUCKET_LITERAL; + + return std::to_string(policy); +} + +} /* namespace Cynara */ diff --git a/pool/shard006/C++/0074775_boss_emperor_dagran_thaurissan.cpp b/pool/shard006/C++/0074775_boss_emperor_dagran_thaurissan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8027ed8ad49d2b4427fb3249ddf01030f6dbd4e --- /dev/null +++ b/pool/shard006/C++/0074775_boss_emperor_dagran_thaurissan.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2008-2011 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * 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 . + */ + +/* ScriptData +SDName: Boss_Emperor_Dagran_Thaurissan +SD%Complete: 99 +SDComment: +SDCategory: Blackrock Depths +EndScriptData */ + +#include "ScriptPCH.h" + +enum Yells +{ + SAY_AGGRO = -1230001, + SAY_SLAY = -1230002 +}; + +enum Spells +{ + SPELL_HANDOFTHAURISSAN = 17492, + SPELL_AVATAROFFLAME = 15636 +}; + +class boss_emperor_dagran_thaurissan : public CreatureScript +{ +public: + boss_emperor_dagran_thaurissan() : CreatureScript("boss_emperor_dagran_thaurissan") { } + + CreatureAI* GetAI(Creature* pCreature) const + { + return new boss_draganthaurissanAI (pCreature); + } + + struct boss_draganthaurissanAI : public ScriptedAI + { + boss_draganthaurissanAI(Creature *c) : ScriptedAI(c) {} + + uint32 HandOfThaurissan_Timer; + uint32 AvatarOfFlame_Timer; + //uint32 Counter; + + void Reset() + { + HandOfThaurissan_Timer = 4000; + AvatarOfFlame_Timer = 25000; + //Counter= 0; + } + + void EnterCombat(Unit * /*who*/) + { + DoScriptText(SAY_AGGRO, me); + me->CallForHelp(VISIBLE_RANGE); + } + + void KilledUnit(Unit* /*victim*/) + { + DoScriptText(SAY_SLAY, me); + } + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + if (HandOfThaurissan_Timer <= diff) + { + if (Unit *pTarget = SelectUnit(SELECT_TARGET_RANDOM,0)) + DoCast(pTarget, SPELL_HANDOFTHAURISSAN); + + //3 Hands of Thaurissan will be casted + //if (Counter < 3) + //{ + // HandOfThaurissan_Timer = 1000; + // ++Counter; + //} + //else + //{ + HandOfThaurissan_Timer = 5000; + //Counter = 0; + //} + } else HandOfThaurissan_Timer -= diff; + + //AvatarOfFlame_Timer + if (AvatarOfFlame_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_AVATAROFFLAME); + AvatarOfFlame_Timer = 18000; + } else AvatarOfFlame_Timer -= diff; + + DoMeleeAttackIfReady(); + } + }; + +}; + + +void AddSC_boss_draganthaurissan() +{ + new boss_emperor_dagran_thaurissan(); +} diff --git a/pool/shard006/C++/0074776_convertertopdf.cpp b/pool/shard006/C++/0074776_convertertopdf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31a5d0345f959ab940ef88d4591da569bdc841f3 --- /dev/null +++ b/pool/shard006/C++/0074776_convertertopdf.cpp @@ -0,0 +1,86 @@ +#include +#include +#include "convertertoqwidget.hpp" +#include "convertertopdf.hpp" + +namespace qtreports { + namespace detail { + + ConverterToPDF::ConverterToPDF( const ReportPtr & report ) : + m_report( report ), + m_dpi( 600 ) {} + + ConverterToPDF::~ConverterToPDF() {} + + bool ConverterToPDF::convert( const QString & path ) { + return create( path ); + } + + void ConverterToPDF::setDPI( int dpi ) + { + m_dpi = dpi; + } + + int ConverterToPDF::getDPI() const + { + return m_dpi; + } + + bool ConverterToPDF::create( const QString & path ) { + if( m_report.isNull() ) { + m_lastError = "Report is empty"; + return false; + } + + ConverterToQWidget converter( m_report ); + bool result = converter.convert( ConverterToQWidget::WidgetType::Report ); + if( !result ) { + m_lastError = "Cannot convert to QWidget: " + converter.getLastError(); + return false; + } + + auto widget = converter.getQWidget(); + widget->show(); + widget->hide(); + widget->resize( m_report->getSize() ); + + QPdfWriter writer( path ); + writer.setCreator( "QReports Library" ); + writer.setTitle( m_report->getName() ); + + QPainter painter( &writer ); + + //Only for Qt 5.3+ + //auto pageSize = writer.pageLayout().pageSize(); + //auto size = pageSize.sizePixels( m_dpi ); + //auto sizeInch = pageSize.size( QPageSize::Unit::Inch ); + //widget->resize( sizeInch.width() * m_dpi, sizeInch.height() * m_dpi ); + //writer.setResolution( m_dpi ); + + //Inch 2.54, A4 inch size 8.26 x 11.69 + qreal scale = 2 * 8.26; + + //widget->resize( widget->width(), rect.height() / scale ); + painter.scale( scale, scale ); + + /* + auto height = m_printedWidget->height() * scale; + auto count = static_cast< int >( std::ceil( height / rect.height() ) ); + for( int i = 0; i < count; ++i ) + { + i != 0 ? printer->newPage() : 0; + m_printedWidget->render( &painter, QPoint( 0, -i * rect.height() / scale ) ); + } + */ + + widget->render( &painter ); + + return true; + } + + const QString ConverterToPDF::getLastError() const { + return m_lastError; + } + + } +} diff --git a/pool/shard006/C++/0074777_feed_internals_ui.cc b/pool/shard006/C++/0074777_feed_internals_ui.cc new file mode 100644 index 0000000000000000000000000000000000000000..76decc05d7e38bbf50b929ad62d9c1e246238383 --- /dev/null +++ b/pool/shard006/C++/0074777_feed_internals_ui.cc @@ -0,0 +1,51 @@ +// Copyright 2018 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/ui/webui/feed_internals/feed_internals_ui.h" + +#include + +#include "base/bind.h" +#include "base/feature_list.h" +#include "chrome/browser/feed/android/feed_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/feed_internals/feed_internals.mojom.h" +#include "chrome/common/url_constants.h" +#include "chrome/grit/dev_ui_browser_resources.h" +#include "components/feed/buildflags.h" +#include "components/feed/feed_feature_list.h" +#include "content/public/browser/web_ui_data_source.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" + +#if BUILDFLAG(ENABLE_FEED_V2) +#include "chrome/browser/ui/webui/feed_internals/feedv2_internals_page_handler.h" +#endif + +FeedInternalsUI::FeedInternalsUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui), profile_(Profile::FromWebUI(web_ui)) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost); + + source->AddResourcePath("feed_internals.js", IDR_FEED_INTERNALS_JS); + source->AddResourcePath("feed_internals.mojom-lite.js", + IDR_FEED_INTERNALS_MOJO_JS); + source->AddResourcePath("feed_internals.css", IDR_FEED_INTERNALS_CSS); + source->SetDefaultResource(IDR_FEED_INTERNALS_HTML); + + content::WebUIDataSource::Add(profile_, source); +} + +WEB_UI_CONTROLLER_TYPE_IMPL(FeedInternalsUI) + +FeedInternalsUI::~FeedInternalsUI() = default; + +void FeedInternalsUI::BindInterface( + mojo::PendingReceiver receiver) { +#if BUILDFLAG(ENABLE_FEED_V2) + v2_page_handler_ = std::make_unique( + std::move(receiver), + feed::FeedServiceFactory::GetForBrowserContext(profile_), + profile_->GetPrefs()); +#endif +} diff --git a/pool/shard006/C++/0074781_UMID.cpp b/pool/shard006/C++/0074781_UMID.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f8abb4236b8a9d646d4c09194c3ed3b2f448874 --- /dev/null +++ b/pool/shard006/C++/0074781_UMID.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c), Pierre-Anthony Lemieux (pal@palemieux.com) +* 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. +* +* 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 "UMID.h" +#include +#include + +namespace rxml { + + std::string UMID::bytesToString(const unsigned char umid[32]) { + + char str[128]; + + int r = snprintf(str, sizeof(str), "urn:smpte:umid:%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x.%02x%02x%02x%02x", + umid[0], umid[1], umid[2], umid[3], + umid[4], umid[5], umid[6], umid[7], + umid[8], umid[9], umid[10], umid[11], + umid[12], umid[13], umid[14], umid[15], + umid[16], umid[17], umid[18], umid[19], + umid[20], umid[21], umid[22], umid[23], + umid[24], umid[25], umid[26], umid[27], + umid[28], umid[29], umid[30], umid[31] + ); + + if (r < 0) throw std::runtime_error("UMID::bytesToString failed."); + + return str; + + } +} \ No newline at end of file diff --git a/pool/shard006/C++/0074788_main.cpp b/pool/shard006/C++/0074788_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14fd74bdb5834c3f2ff6e54094ad12f299b65891 --- /dev/null +++ b/pool/shard006/C++/0074788_main.cpp @@ -0,0 +1,59 @@ +#include + +#include "Env.hpp" +#include "deployment.hpp" +#include "ResourceMonitor.hpp" +#include "Aggregator.hpp" +#include "Alert.hpp" +#include "AssociationInstances.hpp" +#include "Action.hpp" +#include "EventStructures.hpp" + +int main() +{ + Env::initEnvironment(); + UsedRuntimePtr rt = UsedRuntimeType::getRuntimeInstance(); + rt->startRT(); + + Model::ResourceMonitor monitor; + Model::Aggregator aggregator; + Model::Alert alert(3); + Action::link(Model::ToAggregator.rmonitor, &monitor, Model::ToAggregator.aggregator, &aggregator); + Action::link(Model::ToAlert.rmonitor, &monitor, Model::ToAlert.alert, &alert); + Action::start(&monitor); + Action::start(&aggregator); + Action::start(&alert); + + Action::log("Testing monitoring example."); + Action::log("\tq - quit"); + Action::log("\tr - read"); + Action::log("\tw - write"); + Action::log("\tc - close"); + Action::log("\tx - print report"); + + char c; + std::cin >> c; + while (c != 'q') + { + if (c == 'r') + { + Action::send(&monitor, ES::SharedPtr(new Model::Read_EC())); + } + else if (c == 'w') + { + Action::send(&monitor, ES::SharedPtr(new Model::Write_EC())); + } + else if (c == 'c') + { + Action::send(&monitor, ES::SharedPtr(new Model::Close_EC())); + } + else if (c == 'x') + { + Action::send(&aggregator, ES::SharedPtr(new Model::PrintReport_EC())); + } + std::cin >> c; + } + + rt->stopUponCompletion(); + return 0; +} diff --git a/pool/shard006/C++/0074794_manifold_id_05.cc b/pool/shard006/C++/0074794_manifold_id_05.cc new file mode 100644 index 0000000000000000000000000000000000000000..ed5b7ff632b6ab3b4839c3ea049cfe33e0eb4810 --- /dev/null +++ b/pool/shard006/C++/0074794_manifold_id_05.cc @@ -0,0 +1,72 @@ +//---------------------------- manifold_id_05.cc --------------------------- +// Copyright (C) 2011 - 2017 by the mathLab team. +// +// This file is subject to LGPL and may not be distributed +// without copyright and license information. Please refer +// to the file deal.II/doc/license.html for the text and +// further information on this license. +// +//---------------------------- manifold_id_05.cc --------------------------- + + +// Set a manifold id on one of the boundary face, and attach the +// boundary description to it. Refine globally twice and output the mesh. + +#include "../tests.h" + + +// all include files you need here +#include +#include +#include +#include +#include +#include + +// Helper function +template +void test(unsigned int ref=1) +{ + deallog << "Testing dim=" << dim + << ", spacedim="<< spacedim << std::endl; + + Point center; + for (unsigned int i=0; i boundary(center); + Triangulation tria; + GridGenerator::hyper_cube (tria); + typename Triangulation::active_cell_iterator cell; + + tria.begin_active()->face(0)->set_manifold_id(1); + tria.set_manifold(1,boundary); + + tria.refine_global(2); + + for (cell=tria.begin_active(); cell!=tria.end(); ++cell) + { + deallog << "C: " << cell << std::endl; + for (unsigned int f=0; f::faces_per_cell; ++f) + deallog << "F: " << cell->face(f) << ", mid: " + << (int) cell->face(f)->manifold_id() << std::endl; + } + + + GridOut gridout; + gridout.write_msh(tria, deallog.get_file_stream()); +} + +int main () +{ + initlog(); + + test<1,1>(); + test<1,2>(); + test<2,2>(); + test<2,3>(); + test<3,3>(); + + return 0; +} + diff --git a/pool/shard006/C++/0074806_tallstretchedbitmaps.cpp b/pool/shard006/C++/0074806_tallstretchedbitmaps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a874981e86d65cab93c0bd6814e46af66859ae0c --- /dev/null +++ b/pool/shard006/C++/0074806_tallstretchedbitmaps.cpp @@ -0,0 +1,113 @@ +/* + * Copyright 2014 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "gm/gm.h" +#include "include/core/SkBitmap.h" +#include "include/core/SkCanvas.h" +#include "include/core/SkFilterQuality.h" +#include "include/core/SkPaint.h" +#include "include/core/SkRect.h" +#include "include/core/SkScalar.h" +#include "include/core/SkSize.h" +#include "include/core/SkString.h" +#include "include/core/SkTypes.h" +#include "include/private/SkTo.h" +#include "include/utils/SkRandom.h" + +int make_bm(SkBitmap* bm, int height) { + constexpr int kRadius = 22; + constexpr int kMargin = 8; + constexpr SkScalar kStartAngle = 0; + constexpr SkScalar kDAngle = 25; + constexpr SkScalar kSweep = 320; + constexpr SkScalar kThickness = 8; + + int count = (height / (2 * kRadius + kMargin)); + height = count * (2 * kRadius + kMargin); + + bm->allocN32Pixels(2 * (kRadius + kMargin), height); + SkRandom random; + + SkCanvas wholeCanvas(*bm); + wholeCanvas.clear(0x00000000); + + SkScalar angle = kStartAngle; + for (int i = 0; i < count; ++i) { + SkPaint paint; + // The sw rasterizer disables AA for large canvii. So we make a small canvas for each draw. + SkBitmap smallBM; + SkIRect subRect = SkIRect::MakeXYWH(0, i * (kMargin + 2 * kRadius), + 2 * kRadius + kMargin, 2 * kRadius + kMargin); + bm->extractSubset(&smallBM, subRect); + SkCanvas canvas(smallBM); + canvas.translate(kMargin + kRadius, kMargin + kRadius); + + paint.setAntiAlias(true); + paint.setColor(random.nextU() | 0xFF000000); + paint.setStyle(SkPaint::kStroke_Style); + paint.setStrokeWidth(kThickness); + paint.setStrokeCap(SkPaint::kRound_Cap); + SkScalar radius = kRadius - kThickness / 2; + SkRect bounds = SkRect::MakeLTRB(-radius, -radius, radius, radius); + + canvas.drawArc(bounds, angle, kSweep, false, paint); + angle += kDAngle; + } + bm->setImmutable(); + return count; +} + +class TallStretchedBitmapsGM : public skiagm::GM { +public: + TallStretchedBitmapsGM() {} + +protected: + SkString onShortName() override { + return SkString("tall_stretched_bitmaps"); + } + + SkISize onISize() override { + return SkISize::Make(730, 690); + } + + void onOnceBeforeDraw() override { + for (size_t i = 0; i < SK_ARRAY_COUNT(fTallBmps); ++i) { + int h = SkToInt((4 + i) * 1024); + + fTallBmps[i].fItemCnt = make_bm(&fTallBmps[i].fBmp, h); + } + } + + void onDraw(SkCanvas* canvas) override { + canvas->scale(1.3f, 1.3f); + for (size_t i = 0; i < SK_ARRAY_COUNT(fTallBmps); ++i) { + SkASSERT(fTallBmps[i].fItemCnt > 10); + SkBitmap bmp = fTallBmps[i].fBmp; + // Draw the last 10 elements of the bitmap. + int startItem = fTallBmps[i].fItemCnt - 10; + int itemHeight = bmp.height() / fTallBmps[i].fItemCnt; + SkIRect subRect = SkIRect::MakeLTRB(0, startItem * itemHeight, + bmp.width(), bmp.height()); + SkRect dstRect = SkRect::MakeWH(SkIntToScalar(bmp.width()), 10.f * itemHeight); + SkPaint paint; + paint.setFilterQuality(kLow_SkFilterQuality); + canvas->drawBitmapRect(bmp, subRect, dstRect, &paint); + canvas->translate(SkIntToScalar(bmp.width() + 10), 0); + } + } + +private: + struct { + SkBitmap fBmp; + int fItemCnt; + } fTallBmps[8]; + typedef skiagm::GM INHERITED; +}; + +////////////////////////////////////////////////////////////////////////////// + +DEF_GM(return new TallStretchedBitmapsGM;) diff --git a/pool/shard006/C++/0074815_sso_auth_session.cc b/pool/shard006/C++/0074815_sso_auth_session.cc new file mode 100644 index 0000000000000000000000000000000000000000..56d389b8ecf86d659bfd8702834b3f5e46ab0e56 --- /dev/null +++ b/pool/shard006/C++/0074815_sso_auth_session.cc @@ -0,0 +1,120 @@ +// Copyright (c) 2014 Intel Corporation. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "sso/sso_auth_session.h" + +#include + +#include "sso/sso_async_op.h" +#include "sso/sso_instance.h" +#include "sso/sso_utils.h" + +void SSOAuthSession::QueryAvailableMechanismsCb(SignonAuthSession* self, + gchar** mechanisms, const GError* error, gpointer user_data) { + SSOAsyncOp* async_op = reinterpret_cast(user_data); + SSOAuthSession* session = reinterpret_cast( + async_op->user_data()); + if (error) { + async_op->PostError(error->message, session->jsid_); + delete async_op; + return; + } + + picojson::value::object resp; + resp["mechanisms"] = picojson::value(SSOUtils::FromStringArrayToJSONArray( + reinterpret_cast(mechanisms))); + g_strfreev(mechanisms); + + async_op->PostResult(picojson::value(resp), session->jsid_); + delete async_op; +} + +void SSOAuthSession::ChallengeCb(GObject* source_object, GAsyncResult* res, + gpointer user_data) { + SSOAsyncOp* async_op = reinterpret_cast(user_data); + SSOAuthSession* session = reinterpret_cast( + async_op->user_data()); + GError* error = NULL; + SignonAuthSession* auth_session = SIGNON_AUTH_SESSION(source_object); + GVariant* v_reply = signon_auth_session_process_finish(auth_session, res, + &error); + if (error) { + async_op->PostError(error->message, session->jsid_); + delete async_op; + g_error_free(error); + return; + } + + gchar* data = json_gvariant_serialize_data(v_reply, NULL); + g_variant_unref(v_reply); + picojson::value::object resp; + resp["sessionData"] = picojson::value(std::string(data)); + g_free(data); + async_op->PostResult(picojson::value(resp), session->jsid_); + delete async_op; +} + +void SSOAuthSession::StateChangeCb(SignonAuthSession* self, gint state, + gchar* message, gpointer user_data) { + SSOAuthSession* session = reinterpret_cast(user_data); + SSOAsyncOp op(session->instance_, 0, session); + session->session_state_ = static_cast(state); + picojson::value::object info; + info["info"] = picojson::value("sessionStateChanged"); + if (message) + info["message"] = picojson::value(std::string(message)); + info["object"] = session->ToJSON(); + op.PostInfo(picojson::value(info), session->jsid_); +} + +SSOAuthSession::SSOAuthSession(common::Instance* instance, + SignonAuthSession* session, const std::string& method, int jsid) + : instance_(instance), session_(session), method_(method), + session_state_(SESSION_STATE_NOT_STARTED), jsid_(jsid) { + if (session_) { + g_signal_connect(session_, "state-changed", + G_CALLBACK(&SSOAuthSession::StateChangeCb), this); + } +} + +SSOAuthSession::~SSOAuthSession() { + if (session_) { + g_object_unref(session_); + session_ = NULL; + } +} + +void SSOAuthSession::HandleQueryAvailableMechanisms( + const picojson::value& value) { + gchar** mechs = SSOUtils::FromJSONArrayToStringArray( + value.get("wantedMechanisms").get()); + signon_auth_session_query_available_mechanisms(session_, + const_cast(mechs), + &SSOAuthSession::QueryAvailableMechanismsCb, + new SSOAsyncOp(instance_, new picojson::value(value), this)); + g_strfreev(mechs); +} + +void SSOAuthSession::HandleChallenge(const picojson::value& value) { + GVariant* vsess = json_gvariant_deserialize_data( + value.get("sessionData").serialize().c_str(), -1, NULL, NULL); + vsess = g_variant_ref_sink(vsess); + signon_auth_session_process_async(session_, vsess, + value.get("mechanism").to_str().c_str(), 0, &SSOAuthSession::ChallengeCb, + new SSOAsyncOp(instance_, new picojson::value(value), this)); +} + +void SSOAuthSession::HandleCancel(const picojson::value& value) { + SSOAsyncOp op(instance_, new picojson::value(value), this); + signon_auth_session_cancel(session_); + op.PostResult(jsid()); +} + +picojson::value SSOAuthSession::ToJSON() const { + picojson::value::object object; + object["method"] = picojson::value(method_); + object["sessionJSId"] = picojson::value(static_cast(jsid_)); + object["sessionState"] = picojson::value(static_cast(session_state_)); + return picojson::value(object); +} diff --git a/pool/shard006/C++/0074818_keyPoint.cpp b/pool/shard006/C++/0074818_keyPoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f70c295af509f754ce3b404b420e6d249ed0be1 --- /dev/null +++ b/pool/shard006/C++/0074818_keyPoint.cpp @@ -0,0 +1,51 @@ +/* Copyright 2012-2016 Ivan Senin + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + +#include "keyPoint.h" + +using namespace utils::sensorsGraph; + +KeyPoint::KeyPoint(const QColor color) + : mVisualArea(QRectF(-10, -10, 10, 10)) + , mColor(color) +{ + setCacheMode(NoCache); + setZValue(1000); +} + +QRectF KeyPoint::boundingRect() const +{ + return mVisualArea; +} + +void KeyPoint::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(option) + Q_UNUSED(widget) + + painter->save(); + painter->setPen(Qt::NoPen); + + QRadialGradient gradient(0, 0, 10); + + gradient.setCenter(0, 0); + gradient.setFocalPoint(0, 0); + gradient.setColorAt(1, mColor.light(120)); + gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); + painter->setBrush(gradient); + + painter->setPen(Qt::NoPen); + painter->drawEllipse(mVisualArea); + painter->restore(); +} diff --git a/pool/shard006/C++/0074820_KexiStandardAction.cpp b/pool/shard006/C++/0074820_KexiStandardAction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..10a9cb481a39b428b2ad127223f0030202187b19 --- /dev/null +++ b/pool/shard006/C++/0074820_KexiStandardAction.cpp @@ -0,0 +1,124 @@ +/* This file is part of the KDE project + Copyright (C) 2007 Jarosław Staniek + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU Library 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +*/ + +#include "KexiStandardAction.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace KexiStandardAction +{ + +//! @internal +struct Info { + StandardAction id; + KShortcut shortcut; + const char* psName; + const char* psText; + const char* psToolTip; + const char* psWhatsThis; + const char* psIconName; +}; + +//! @internal +static const Info g_rgActionInfo[] = { + { SortAscending, KShortcut(), "data_sort_az", I18N_NOOP("&Ascending"), + I18N_NOOP("Sort data in ascending order"), + I18N_NOOP("Sorts data in ascending order (from A to Z and from 0 to 9). Data from selected column is used for sorting."), + "view-sort-ascending" }, + { SortDescending, KShortcut(), "data_sort_za", I18N_NOOP("&Descending"), + I18N_NOOP("Sort data in descending order"), + I18N_NOOP("Sorts data in descending (from Z to A and from 9 to 0). Data from selected column is used for sorting."), + "view-sort-descending" }, + + { ActionNone, KShortcut(), 0, 0, 0, 0, 0 } +}; + +//! @internal +class ActionsInfoHash : public QHash +{ +public: + ActionsInfoHash() { + const Info* actionInfo = g_rgActionInfo; + + for (; actionInfo->id != ActionNone; actionInfo++) + insert(actionInfo->id, actionInfo); + } +}; + +K_GLOBAL_STATIC(ActionsInfoHash, g_rgActionInfoHash) + +inline const Info* infoPtr(StandardAction id) +{ + return g_rgActionInfoHash->value(id); +} + +//--------------------------------------------- + +KAction *create(StandardAction id, const QObject *recvr, const char *slot, QObject *parent) +{ + KAction *pAction = 0; + const Info* pInfo = infoPtr(id); + + if (pInfo) { + pAction = new KAction(parent); + pAction->setObjectName(pInfo->psName); + KShortcut cut(pInfo->shortcut); + if (!cut.isEmpty()) + pAction->setShortcut(cut); + pAction->setText(i18n(pInfo->psText)); + pAction->setToolTip(i18n(pInfo->psToolTip)); + pAction->setWhatsThis(i18n(pInfo->psWhatsThis)); + if (pInfo->psIconName) + pAction->setIcon(KIcon(pInfo->psIconName)); + } + + if (recvr && slot) + QObject::connect(pAction, SIGNAL(triggered(bool)), recvr, slot); + + if (pAction) { + KActionCollection *collection = qobject_cast(parent); + if (collection) + collection->addAction(pAction->objectName(), pAction); + } + return pAction; +} + +const char* name(StandardAction id) +{ + const Info* pInfo = infoPtr(id); + return (pInfo) ? pInfo->psName : 0; +} + +#define CREATE_METHOD(methodName, enumName) \ + KAction *methodName(const QObject *recvr, const char *slot, QObject *parent) \ + { \ + return KexiStandardAction::create(enumName, recvr, slot, parent); \ + } + +CREATE_METHOD(sortAscending, SortAscending) +CREATE_METHOD(sortDescending, SortDescending) + +} //KexiStandardAction diff --git a/pool/shard006/C++/0074826_scene.cpp b/pool/shard006/C++/0074826_scene.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2d03214988634976616faf09392aaa421520001 --- /dev/null +++ b/pool/shard006/C++/0074826_scene.cpp @@ -0,0 +1,26 @@ +#include "scene.hpp" +#include + +std::unique_ptr input_data_source(new InputDataSource()); + +void Scene2D::draw() +{ + sf2d_start_render(); + sf2d_set_render_screen(GFX_TOP, GFX_LEFT); + draw_top(); + sf2d_set_render_screen(GFX_BOTTOM, GFX_LEFT); + draw_bottom(); + sf2d_end_render(); +} + +void Scene3D::draw() +{ + sf2d_start_render(); + sf2d_set_render_screen(GFX_TOP, GFX_LEFT); + draw_top_left(); + sf2d_set_render_screen(GFX_TOP, GFX_RIGHT); + draw_top_right(); + sf2d_set_render_screen(GFX_BOTTOM, GFX_LEFT); + draw_bottom(); + sf2d_end_render(); +} diff --git a/pool/shard006/C++/0074833_tutorial-mb-edge-tracker.cpp b/pool/shard006/C++/0074833_tutorial-mb-edge-tracker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..172723cbcb8c7fdfc63658cff74dce96f6ec739d --- /dev/null +++ b/pool/shard006/C++/0074833_tutorial-mb-edge-tracker.cpp @@ -0,0 +1,163 @@ +//! \example tutorial-mb-edge-tracker.cpp +#include +#include +#include +#include +#include +//! [Include] +#include +//! [Include] +#include + +int main(int argc, char **argv) +{ +#if defined(VISP_HAVE_OPENCV) && (VISP_HAVE_OPENCV_VERSION >= 0x020100) + try { + std::string videoname = "teabox.mpg"; + + for (int i = 0; i < argc; i++) { + if (std::string(argv[i]) == "--name") + videoname = std::string(argv[i + 1]); + else if (std::string(argv[i]) == "--help") { + std::cout << "\nUsage: " << argv[0] << " [--name