diff --git a/pool/shard001/C++/0017002_rf24-ping.cpp b/pool/shard001/C++/0017002_rf24-ping.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7cc0d1635d47040a4dd9db5b14ecf625f0e7ce4 --- /dev/null +++ b/pool/shard001/C++/0017002_rf24-ping.cpp @@ -0,0 +1,172 @@ +/* The MIT License (MIT) + * + * Copyright (c) 2016 Jean Gressmann + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Globals.h" + +#define APPNAME "rf24-ping" + +#define ERROR(...) fprintf(stderr, "ERROR: " __VA_ARGS__) +#define LOG(...) fprintf(stdout, __VA_ARGS__) + +#if 0 +# define DEBUG(...) fprintf(stderr, __VA_ARGS__) +#else +# define DEBUG(...) +#endif + +template +static +int +UnsignedParser(const char* arg, T& value) { + char* end = NULL; + value = (T)strtoul(arg, &end, 10); + if (!end || end == arg) { + ERROR("Argument '%s' could not be converted to unsigned int\n", arg); + return -1; + } + + return 0; +} + +static const cmdlopt_arg s_Dummy_Arg[] = { + CMDLOPT_ARGUMENT_TERMINATOR +}; + +static const char* s_RF24PacketRouterSocketPath = RF24_PACKET_ROUTER_SOCKET_PATH; +static +int +RF24PacketRouterSocketPath_Parser(void*, char* arg) { + s_RF24PacketRouterSocketPath = arg; + return 0; +} + + +static unsigned s_MillisecondsToSleep = 1000; +static +int +Sleep_Parser(void*, char* arg) { + return UnsignedParser(arg, s_MillisecondsToSleep); +} + +static const cmdlopt_opt s_Options[] = { + { "rf24-packet-router-socket-path", "Path to UNIX socket. Defaults to " RF24_PACKET_ROUTER_SOCKET_PATH, 0, 0x100, s_Dummy_Arg, RF24PacketRouterSocketPath_Parser}, + { "sleep", "Milliseconds to sleep between pings. Defaults to 1000", 's', 0x101, s_Dummy_Arg, Sleep_Parser}, + CMDLOPT_COMMON_OPTIONS, + CMDLOPT_OPTION_TERMINATOR +}; + +int +main(int argc, char** argv) { + int socketFd = -1; + sockaddr_un sa; + char buffer[32]; + uint32_t counter = 0; + + cmdlopt_set_app_name(APPNAME); + cmdlopt_set_app_version("1.0\nCopyright (c) 2016 Jean Gressmann "); + cmdlopt_set_options(s_Options); + int error = cmdlopt_parse_cmdl(argc, argv, NULL); + + switch (error) { + case CMDLOPT_E_NONE: + break; + case CMDLOPT_E_HELP_REQUESTED: + case CMDLOPT_E_VERSION_REQUESTED: + error = 0; + goto Exit; + case CMDLOPT_E_UNKNOWN_OPTION: + cmdlopt_fprint_help(stderr); + goto Exit; + case CMDLOPT_E_ERRNO: + error = errno; + goto Exit; + case CMDLOPT_E_INVALID_PARAM: + fprintf(stderr, "Internal program error %d\n", error); + goto Exit; + default: + goto Exit; + } + + if (!s_RF24PacketRouterSocketPath || !*s_RF24PacketRouterSocketPath) { + fprintf(stderr, "Empty Rf24 packet router UNIX socket path.\n"); + error = -1; + goto Exit; + } + + memset(&sa, 0, sizeof(sa)); + + + socketFd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socketFd == -1) { + ERROR("Failed to create socket\n"); + error = errno; + goto Exit; + } + + sa.sun_family = AF_UNIX; + strncpy(sa.sun_path, s_RF24PacketRouterSocketPath, sizeof(sa.sun_path) - 1); + if (connect(socketFd, (sockaddr*)&sa, sizeof(sa)) < 0) { + ERROR("Failed to connect to AF_UNIX socket %s\n", s_RF24PacketRouterSocketPath); + error = errno; + goto Exit; + } + + error = 0; + + + while (1) { + snprintf(buffer, sizeof(buffer), "ping %u\n", counter++); + LOG(buffer); + write(socketFd, buffer, sizeof(buffer)); + usleep(s_MillisecondsToSleep * 1000); + } + +Exit: + if (socketFd >= 0) { + safe_close(socketFd); + } + + if (error > 0) { + fprintf(stderr, "%s (%d)\n", strerror(error), error); + } + return error; +} + + diff --git a/pool/shard001/C++/0017007_namedpipe_thread.cpp b/pool/shard001/C++/0017007_namedpipe_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4448a3026830127427d6419d70c0df85627dcf21 --- /dev/null +++ b/pool/shard001/C++/0017007_namedpipe_thread.cpp @@ -0,0 +1,244 @@ +#include +#include "namedpipe_thread.h" +#include "namedpipe.h" + +// +// 数据包 定义 +// +struct NamedPipe_Package : public package { +public: + bool head_readed; + DWORD byte_written; +}; + +NamedPipe_PackageHandler::NamedPipe_PackageHandler(NamedPipe* pipe) + : m_pipe(pipe) { +} + +void NamedPipe_PackageHandler::set_namedpipe(NamedPipe* pipe) { + m_pipe = pipe; +} + +NamedPipe* NamedPipe_PackageHandler::get_namedpipe() { + return m_pipe; +} + +// 返回 -1:错误,返回0:成功发送,返回1:发送过程中 +int NamedPipe_PackageHandler::read_package(package* pkg) { + assert(NULL != m_pipe); + if(NULL == pkg || NULL == m_pipe) { + return -1; + } + + NamedPipe_Package* pThePkg = (NamedPipe_Package*)pkg; + + // 读包头 + if(!pThePkg->head_readed) { + DWORD dwBytes = 0; + if(!::PeekNamedPipe(m_pipe->handle(), NULL, 0, NULL, &dwBytes, NULL)) { + return -1; + } + if(sizeof(DWORD) * 3 > dwBytes) { + return 1; + } + + m_pipe->read(&(pThePkg->cmd), sizeof(pThePkg->cmd)); + m_pipe->read(&(pThePkg->flag), sizeof(pThePkg->flag)); + m_pipe->read(&(pThePkg->size), sizeof(pThePkg->size)); + + delete pThePkg->data; + pThePkg->data = new char[(pThePkg->size / 16 + 1) * 16]; + + pThePkg->head_readed = true; + } + + // 读包体 + if(pThePkg->size > 0) { + DWORD dwBytes = 0; + if(!::PeekNamedPipe(m_pipe->handle(), NULL, 0, NULL, &dwBytes, NULL)) { + return -1; + } + + if(dwBytes < pThePkg->size) { + return 1; + } + + // 获取数据包体 + if(pThePkg->size != m_pipe->read(pThePkg->data, DWORD(pThePkg->size))) { + return -1; + } + } + + return 0; +} + +int NamedPipe_PackageHandler::write_package(package* pkg) { + assert(NULL != m_pipe); + if(NULL == pkg || NULL == m_pipe) { + return -1; + } + + NamedPipe_Package* pThePkg = (NamedPipe_Package*)pkg; + + DWORD dwBuffer[3]; + dwBuffer[0] = pThePkg->cmd; + dwBuffer[1] = pThePkg->flag; + dwBuffer[2] = DWORD(pThePkg->size); + if(sizeof(dwBuffer) != m_pipe->write(dwBuffer, sizeof(dwBuffer))) { + return -1; + } + + if(pThePkg->size > 0) { + int nByteWritten = m_pipe->write((char*)(pThePkg->data) + pThePkg->byte_written, DWORD(pThePkg->size) - pThePkg->byte_written); + if(nByteWritten < 0) { + return -1; + } + + pThePkg->byte_written += nByteWritten; + } + + return (pThePkg->byte_written == pThePkg->size)?0:1; +} + +package* NamedPipe_PackageHandler::create_package(int32_t cmd, const void* data, size_t size, uint32_t flag) { + NamedPipe_Package* pkg = new NamedPipe_Package; + + pkg->cmd = cmd; + pkg->flag = flag; + + pkg->byte_written = 0; + pkg->head_readed = false; + + if(NULL != data && size > 0) { + pkg->data = new char[(size/16 + 1) * 16]; + pkg->size = size; + + memcpy(pkg->data, data, size); + } else { + pkg->data = NULL; + pkg->size = 0; + } + + return pkg; +} + +void NamedPipe_PackageHandler::destroy_package(package* pkg) { + if(NULL != pkg) { + delete pkg->data; + delete (NamedPipe_Package*)pkg; + } +} + +// server reader impl. +class NamedPipe_ServerReader : public IO_ThreadReader { +public: + NamedPipe_ServerReader(NamedPipe_Server* server) + : m_client_connected(false) + , m_server(server) { + } + +protected: + virtual void do_run() { + m_client_connected = false; + if(m_server->connect()) { + m_client_connected = true; + + { + __super::do_run(); + } + + m_server->disconnect(); + m_client_connected = false; + } + } + + virtual bool do_stop(bool bKillOnTimeout, UINT uTimeout) { + if(is_running() && !m_client_connected) { + NamedPipe_Client client; + client.open(m_server->pipename()); + client.close(); + } + + return IO_ThreadReader::do_stop(bKillOnTimeout, uTimeout); + } + +private: + NamedPipe_Server* m_server; + volatile bool m_client_connected; +}; + +// server writer impl. +class NamedPipe_ServerWriter : public IO_ThreadWriter { +}; + +// client reader impl. +class NamedPipe_ClientReader : public IO_ThreadReader { +}; + +// client writer impl. +class NamedPipe_ClientWriter : public IO_ThreadWriter { +}; + +NamedPipe_ThreadServer::NamedPipe_ThreadServer() { + m_pkg_handler.set_namedpipe(&m_pipe); + this->set_reader(new NamedPipe_ServerReader(&m_pipe)); + this->set_writer(new NamedPipe_ServerWriter()); + this->set_package_handler(&m_pkg_handler); +} + +bool NamedPipe_ThreadServer::start(const char* pipename, DWORD dwInBuffer, DWORD dwOutBuffer, SECURITY_ATTRIBUTES* pSecAttrs, DWORD* pErrCode) { + if(!m_pipe.open(pipename, dwInBuffer, dwOutBuffer, pSecAttrs, pErrCode)) { + return false; + } + + return IO_ThreadWorker::start(); +} + +bool NamedPipe_ThreadServer::do_start() { + if(NULL == m_pipe.handle()) { + return false; + } + + return IO_ThreadWorker::do_start(); +} + +bool NamedPipe_ThreadServer::do_stop(bool bKillOnTimeout, UINT uTimeout) { + bool ret = IO_ThreadWorker::do_stop(bKillOnTimeout, uTimeout); + m_pipe.close(); + return ret; +} + +NamedPipe_ThreadServer::~NamedPipe_ThreadServer() { +} + +NamedPipe_ThreadClient::NamedPipe_ThreadClient() { + m_pkg_handler.set_namedpipe(&m_pipe); + this->set_reader(new NamedPipe_ClientReader()); + this->set_writer(new NamedPipe_ClientWriter()); + this->set_package_handler(&m_pkg_handler); +} + +bool NamedPipe_ThreadClient::start(const char* pipename) { + if(!m_pipe.open(pipename)) { + return false; + } + + return IO_ThreadWorker::start(); +} + +bool NamedPipe_ThreadClient::do_start() { + if(NULL == m_pipe.handle()) { + return false; + } + + return IO_ThreadWorker::do_start(); +} + +bool NamedPipe_ThreadClient::do_stop(bool bKillOnTimeout, UINT uTimeout) { + bool ret = IO_ThreadWorker::do_stop(bKillOnTimeout, uTimeout); + m_pipe.close(); + return ret; +} + +NamedPipe_ThreadClient::~NamedPipe_ThreadClient() { +} diff --git a/pool/shard001/C++/0017013_modality-eval.cpp b/pool/shard001/C++/0017013_modality-eval.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c24874453513b921b479c0d88a817aee58d2a5d9 --- /dev/null +++ b/pool/shard001/C++/0017013_modality-eval.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include "eval.hpp" + + +int main(int argc, char *argv[]) { + boost::program_options::options_description opt("Usage"); + opt.add_options() + ("help,h", "Show help messages") + ("version,v", "Show version informaion"); + + boost::program_options::variables_map argmap; + boost::program_options::store(parse_command_line(argc, argv, opt), argmap); + boost::program_options::notify(argmap); + + evaluator _evaluator; + + std::string buf; + while( getline(std::cin, buf) ) { + std::vector l; + boost::algorithm::split(l, buf, boost::algorithm::is_any_of(",")); + + if (l.size() == 3) { + _evaluator.add( l[0], l[1], l[2] ); + } + else { + std::cerr << "WARN: invalid format " << buf << std::endl; + } + } + + _evaluator.eval(); + + std::cout << "* confusion matrix" << std::endl; + _evaluator.print_confusion_matrix(); + + std::cout << "* Precision and Recall" << std::endl; + _evaluator.print_prec_rec(); + + double acc = _evaluator.accuracy(); + std::cout << "* Accuracy" << std::endl; + std::cout << acc << std::endl; + + return true; +} + diff --git a/pool/shard001/C++/0017014_cflow-hand.cc b/pool/shard001/C++/0017014_cflow-hand.cc new file mode 100644 index 0000000000000000000000000000000000000000..1fb787223b94e5f1f7b79fcf99de3548d338bad3 --- /dev/null +++ b/pool/shard001/C++/0017014_cflow-hand.cc @@ -0,0 +1,22 @@ +// Copyright (C) 2012 Gustav Munkby, Hamburg University of Technology (TUHH) +#define likely(x) __builtin_expect((x),1) +#define unlikely(x) __builtin_expect((x),0) +#include "handler.hh" +#include "protected_clone.hh" + +int basic(int input) +{ + static unsigned int block = 0; + int x = input; + if (likely(x <= 2)) + { + if (unlikely(sihft::protected_clone(block) != 0)) + sihft::fault_detected(); + block = 1; + x += 1; + } + if (unlikely(sihft::protected_clone(block) > 1)) + sihft::fault_detected(); + block = 0; + return x; +} diff --git a/pool/shard001/C++/0017018_gen_random.cc b/pool/shard001/C++/0017018_gen_random.cc new file mode 100644 index 0000000000000000000000000000000000000000..94b5234240be37170c32288b0e5d5a19e6708f8f --- /dev/null +++ b/pool/shard001/C++/0017018_gen_random.cc @@ -0,0 +1,66 @@ +/** + * This program generates random graphs for use by book-embedder. + * + * Program for minimizing the number of crossings in a book embedding of a given + * graph to a given number of pages. + * + * Author: Josef Cibulka + * License: see the file LICENSE + */ + +#include +#include +#include +#include + +#define MAXP 1000000 +#define MAXN 1000000 + +const std::string usage = + "Exactly three arguments are required -- the number of the pages provided for the drawing, " + "the number of vertices of the graph and the probability, in percents, of each edge. " + "The edges are created independently.\n" + "E.g. a graph with 10 vertices and edge probability 20% (will have 9 vertices on average) " + "to be drawn in a book with 3 pages: \"gen_random 3 10 20\".\n"; + +void print_usage_and_exit() +{ + fprintf(stderr, usage.c_str()); + exit(0); +} + +int main(int argc, char *argv[]) +{ + if (argc != 4) + print_usage_and_exit(); + + int p = -1; + p = atoi(argv[1]); + if (p <= 0 || p > MAXP) + print_usage_and_exit(); + + int n = -1; + n = atoi(argv[2]); + if (n <= 0 || n > MAXN) + print_usage_and_exit(); + + double prob = -1; + prob = atof(argv[3]); + if (prob <= 0.0 || prob > 100.0) + print_usage_and_exit(); + + printf("%d\n", n); + printf("%d\n", p); + + int thr = prob * RAND_MAX / 100.0; + + srand(time(nullptr)); + for (int i = 0; i < n; i++) + printf("%d\n", i); + + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + if (rand() < thr) + printf("%d %d [0]\n", i, j); + return 0; +} diff --git a/pool/shard001/C++/0017019_op_+.pass.cpp b/pool/shard001/C++/0017019_op_+.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0f10147ee8936edd0bb14a0c15f85e0df52f945 --- /dev/null +++ b/pool/shard001/C++/0017019_op_+.pass.cpp @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// + +// duration + +// duration operator+() const; + +#include +#include + +int main() +{ + { + const std::chrono::minutes m(3); + std::chrono::minutes m2 = +m; + assert(m.count() == m2.count()); + } +#ifndef _LIBCPP_HAS_NO_CONSTEXPR + { + constexpr std::chrono::minutes m(3); + constexpr std::chrono::minutes m2 = +m; + static_assert(m.count() == m2.count(), ""); + } +#endif +} diff --git a/pool/shard001/C++/0017021_qwaylandglcontext.cpp b/pool/shard001/C++/0017021_qwaylandglcontext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7a4b5a2bfa3fe7e4a5c90bc4e0270aa586803f8 --- /dev/null +++ b/pool/shard001/C++/0017021_qwaylandglcontext.cpp @@ -0,0 +1,265 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the plugins 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 "qwaylandglcontext.h" + +#include +#include +#include +#include "qwaylandeglwindow.h" + +#include +#include +#include +#include + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share) + : QPlatformOpenGLContext() + , m_eglDisplay(eglDisplay) + , m_config(q_configFromGLFormat(m_eglDisplay, format, true)) + , m_format(q_glFormatFromConfig(m_eglDisplay, m_config)) + , m_blitProgram(0) + , m_textureCache(0) + , mUseNativeDefaultFbo(false) +{ + m_shareEGLContext = share ? static_cast(share)->eglContext() : EGL_NO_CONTEXT; + + switch (m_format.renderableType()) { + case QSurfaceFormat::OpenVG: + eglBindAPI(EGL_OPENVG_API); + break; +#ifdef EGL_VERSION_1_4 +# if !defined(QT_OPENGL_ES_2) + case QSurfaceFormat::DefaultRenderableType: +# endif + case QSurfaceFormat::OpenGL: + eglBindAPI(EGL_OPENGL_API); + break; +#endif + case QSurfaceFormat::OpenGLES: + default: + eglBindAPI(EGL_OPENGL_ES_API); + break; + } + + QVector eglContextAttrs; + eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); + eglContextAttrs.append(format.majorVersion() == 1 ? 1 : 2); + eglContextAttrs.append(EGL_NONE); + + m_context = eglCreateContext(m_eglDisplay, m_config, m_shareEGLContext, eglContextAttrs.constData()); + + if (m_context == EGL_NO_CONTEXT) { + m_context = eglCreateContext(m_eglDisplay, m_config, EGL_NO_CONTEXT, eglContextAttrs.constData()); + m_shareEGLContext = EGL_NO_CONTEXT; + } +} + +QWaylandGLContext::~QWaylandGLContext() +{ + delete m_blitProgram; + delete m_textureCache; + eglDestroyContext(m_eglDisplay, m_context); +} + +bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface) +{ + QWaylandEglWindow *window = static_cast(surface); + + window->setCanResize(false); + + EGLSurface eglSurface = window->eglSurface(); + if (!eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context)) { + qWarning("QEGLPlatformContext::makeCurrent: eglError: %x, this: %p \n", eglGetError(), this); + return false; + } + + window->bindContentFBO(); + + return true; +} + +void QWaylandGLContext::doneCurrent() +{ + eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); +} + +void QWaylandGLContext::swapBuffers(QPlatformSurface *surface) +{ + QWaylandEglWindow *window = static_cast(surface); + + EGLSurface eglSurface = window->eglSurface(); + + if (window->decoration()) { + makeCurrent(surface); + if (!m_blitProgram) { + initializeOpenGLFunctions(); + m_blitProgram = new QOpenGLShaderProgram(); + m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute vec4 position;\n\ + attribute vec4 texCoords;\n\ + varying vec2 outTexCoords;\n\ + void main()\n\ + {\n\ + gl_Position = position;\n\ + outTexCoords = texCoords.xy;\n\ + }"); + m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, "varying highp vec2 outTexCoords;\n\ + uniform sampler2D texture;\n\ + void main()\n\ + {\n\ + gl_FragColor = texture2D(texture, outTexCoords);\n\ + }"); + + if (!m_blitProgram->link()) { + qDebug() << "Shader Program link failed."; + qDebug() << m_blitProgram->log(); + } + } + + if (!m_textureCache) { + m_textureCache = new QOpenGLTextureCache(this->context()); + } + + QRect windowRect = window->window()->frameGeometry(); + glViewport(0, 0, windowRect.width(), windowRect.height()); + + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + mUseNativeDefaultFbo = true; + glBindFramebuffer(GL_FRAMEBUFFER, 0); + mUseNativeDefaultFbo = false; + + static const GLfloat squareVertices[] = { + -1.f, -1.f, + 1.0f, -1.f, + -1.f, 1.0f, + 1.0f, 1.0f + }; + + static const GLfloat inverseSquareVertices[] = { + -1.f, 1.f, + 1.f, 1.f, + -1.f, -1.f, + 1.f, -1.f + }; + + static const GLfloat textureVertices[] = { + 0.0f, 0.0f, + 1.0f, 0.0f, + 0.0f, 1.0f, + 1.0f, 1.0f, + }; + + m_blitProgram->bind(); + + m_blitProgram->setUniformValue("texture", 0); + + m_blitProgram->enableAttributeArray("position"); + m_blitProgram->enableAttributeArray("texCoords"); + m_blitProgram->setAttributeArray("texCoords", textureVertices, 2); + + glActiveTexture(GL_TEXTURE0); + + //Draw Decoration + m_blitProgram->setAttributeArray("position", inverseSquareVertices, 2); + QImage decorationImage = window->decoration()->contentImage(); + m_textureCache->bindTexture(context(), decorationImage); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + if (!context()->functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat)) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + //Draw Content + m_blitProgram->setAttributeArray("position", squareVertices, 2); + glBindTexture(GL_TEXTURE_2D, window->contentTexture()); + QRect r = window->contentsRect(); + glViewport(r.x(), r.y(), r.width(), r.height()); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + //Cleanup + m_blitProgram->disableAttributeArray("position"); + m_blitProgram->disableAttributeArray("texCoords"); + m_blitProgram->release(); + } + + eglSwapBuffers(m_eglDisplay, eglSurface); + + window->setCanResize(true); +} + +GLuint QWaylandGLContext::defaultFramebufferObject(QPlatformSurface *surface) const +{ + if (mUseNativeDefaultFbo) + return 0; + + return static_cast(surface)->contentFBO(); +} + +bool QWaylandGLContext::isSharing() const +{ + return m_shareEGLContext != EGL_NO_CONTEXT; +} + +bool QWaylandGLContext::isValid() const +{ + return m_context != EGL_NO_CONTEXT; +} + +void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) () +{ + return eglGetProcAddress(procName.constData()); +} + +EGLConfig QWaylandGLContext::eglConfig() const +{ + return m_config; +} + +QT_END_NAMESPACE diff --git a/pool/shard001/C++/0017023_pathdat.cpp b/pool/shard001/C++/0017023_pathdat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a576c2ce638f880433cda5af9796cc331eafb76 --- /dev/null +++ b/pool/shard001/C++/0017023_pathdat.cpp @@ -0,0 +1,78 @@ +#include "ctdl.h" +#pragma hdrstop + +#include "auxtab.h" +#include "pathdat.h" +#include "msg.h" +#include "extmsg.h" + +void CreatePathDat(void) + { +#ifndef WINCIT +#ifndef AUXMEM +#ifndef REGULAR + Message *Msg = new Message; + + if (Msg) + { + FILE *fl; + + mPrintfCR(getsysmsg(266)); + + char fullPathToPathDat[128]; + sprintf(fullPathToPathDat, sbs, cfg.homepath, getsysmsg(8)); + + if ((fl = fopen(fullPathToPathDat, FO_W)) != NULL) + { + for (m_index mcnt = cfg.OldestMsgTab; mcnt <= cfg.NewestMsg; mcnt++) + { + long loc = MsgTab.GetLocation(mcnt); + int i, j; + label lastlocID; + + Msg->ReadHeader(RMC_NORMAL, NULL, loc, NULL); + + if (*Msg->GetFromPath()) + { + fprintf(fl, pcts, Msg->GetFromPath()); + + // Get last locID, this stuff probably not necessary + for (i = strlen(Msg->GetFromPath()); i && Msg->GetFromPath()[i] != '.'; i--); + + for (j = 0, i++; Msg->GetFromPath()[i] && Msg->GetFromPath()[i] != '!' && j < 4; i++, j++) + { + lastlocID[j] = Msg->GetFromPath()[i]; + } + lastlocID[j] = 0; + + /* if last locID was same as current locID just use alias */ + if (SameString(lastlocID, cfg.locID)) + { + fprintf(fl, getmsg(2), cfg.alias); + } + else + { + fprintf(fl, getmsg(2), cfg.Address); + } + + fprintf(fl, bn); + } + } + + fclose(fl); + } + else + { + mPrintf(getmsg(78), fullPathToPathDat); + } + + delete Msg; + } + else + { + OutOfMemory(90); + } +#endif +#endif +#endif + } diff --git a/pool/shard001/C++/0017033_SphericalScanlineTextureMapper.cpp b/pool/shard001/C++/0017033_SphericalScanlineTextureMapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0d5aae5938984291c8ff3af87c03a30a486a5f9 --- /dev/null +++ b/pool/shard001/C++/0017033_SphericalScanlineTextureMapper.cpp @@ -0,0 +1,260 @@ +// +// This file is part of the Marble Virtual Globe. +// +// This program is free software licensed under the GNU LGPL. You can +// find a copy of this license in LICENSE.txt in the top directory of +// the source code. +// +// Copyright 2007 Torsten Rahn +// Copyright 2011 Bernhard Beschow +// + + +#include "SphericalScanlineTextureMapper.h" + +#include + +#include + +#include "MarbleGlobal.h" +#include "GeoPainter.h" +#include "GeoDataPolygon.h" +#include "GeoDataDocument.h" +#include "MarbleDebug.h" +#include "Quaternion.h" +#include "ScanlineTextureMapperContext.h" +#include "StackedTileLoader.h" +#include "StackedTile.h" +#include "TextureColorizer.h" +#include "ViewportParams.h" +#include "MathHelper.h" + + +using namespace Marble; + +class SphericalScanlineTextureMapper::RenderJob : public QRunnable +{ +public: + RenderJob( StackedTileLoader *tileLoader, int tileLevel, QImage *canvasImage, const ViewportParams *viewport, MapQuality mapQuality, int yTop, int yBottom ); + + virtual void run(); + +private: + StackedTileLoader *const m_tileLoader; + const int m_tileLevel; + QImage *const m_canvasImage; + const ViewportParams *const m_viewport; + const MapQuality m_mapQuality; + int const m_yTop; + int const m_yBottom; +}; + +SphericalScanlineTextureMapper::RenderJob::RenderJob( StackedTileLoader *tileLoader, int tileLevel, QImage *canvasImage, const ViewportParams *viewport, MapQuality mapQuality, int yTop, int yBottom ) + : m_tileLoader( tileLoader ), + m_tileLevel( tileLevel ), + m_canvasImage( canvasImage ), + m_viewport( viewport ), + m_mapQuality( mapQuality ), + m_yTop( yTop ), + m_yBottom( yBottom ) +{ +} + +QRect SphericalScanlineTextureMapper::rect( const ViewportParams *viewport ) const +{ + const int radius = viewport->radius(); + + return QRect( viewport->width() / 2 - radius, viewport->height() / 2 - radius, + 2 * radius, 2 * radius); +} + +void SphericalScanlineTextureMapper::mapTexture( QImage *canvasImage, StackedTileLoader *tileLoader, const ViewportParams *viewport, int tileZoomLevel, MapQuality mapQuality ) +{ + // Reset backend + tileLoader->resetTilehash(); + + // Initialize needed constants: + + const int imageHeight = canvasImage->height(); + const qint64 radius = viewport->radius(); + + // Calculate the actual y-range of the map on the screen + const int skip = ( mapQuality == LowQuality ) ? 1 + : 0; + const int yTop = ( imageHeight / 2 - radius >= 0 ) ? imageHeight / 2 - radius + : 0; + const int yBottom = ( yTop == 0 ) ? imageHeight - skip + : yTop + radius + radius - skip; + + const int numThreads = m_threadPool.maxThreadCount(); + const int yStep = ( yBottom - yTop ) / numThreads; + for ( int i = 0; i < numThreads; ++i ) { + const int yStart = yTop + i * yStep; + const int yEnd = yTop + (i + 1) * yStep; + QRunnable *const job = new RenderJob( tileLoader, tileZoomLevel, canvasImage, viewport, mapQuality, yStart, yEnd ); + m_threadPool.start( job ); + } + + m_threadPool.waitForDone(); + + tileLoader->cleanupTilehash(); +} + +void SphericalScanlineTextureMapper::RenderJob::run() +{ + const int imageHeight = m_canvasImage->height(); + const int imageWidth = m_canvasImage->width(); + const qint64 radius = m_viewport->radius(); + const qreal inverseRadius = 1.0 / (qreal)(radius); + + const bool interlaced = ( m_mapQuality == LowQuality ); + const bool highQuality = ( m_mapQuality == HighQuality + || m_mapQuality == PrintQuality ); + const bool printQuality = ( m_mapQuality == PrintQuality ); + + // Evaluate the degree of interpolation + const int n = ScanlineTextureMapperContext::interpolationStep( m_viewport, m_mapQuality ); + + // Calculate north pole position to decrease pole distortion later on + Quaternion northPole = Quaternion::fromSpherical( 0.0, M_PI * 0.5 ); + northPole.rotateAroundAxis( m_viewport->planetAxis().inverse() ); + const int northPoleX = imageWidth / 2 + (int)( radius * northPole.v[Q_X] ); + const int northPoleY = imageHeight / 2 - (int)( radius * northPole.v[Q_Y] ); + + // Calculate axis matrix to represent the planet's rotation. + matrix planetAxisMatrix; + m_viewport->planetAxis().toMatrix( planetAxisMatrix ); + + // initialize needed variables that are modified during texture mapping: + + ScanlineTextureMapperContext context( m_tileLoader, m_tileLevel ); + qreal lon = 0.0; + qreal lat = 0.0; + + // Scanline based algorithm to texture map a sphere + for ( int y = m_yTop; y < m_yBottom ; ++y ) { + + // Evaluate coordinates for the 3D position vector of the current pixel + const qreal qy = inverseRadius * (qreal)( imageHeight / 2 - y ); + const qreal qr = 1.0 - qy * qy; + + // rx is the radius component in x direction + const int rx = (int)sqrt( (qreal)( radius * radius + - ( ( y - imageHeight / 2 ) + * ( y - imageHeight / 2 ) ) ) ); + + // Calculate the actual x-range of the map within the current scanline. + // + // If the circular border of the earth disk is still visible then xLeft + // equals the scanline position of the most left pixel that gets covered + // by the earth disk. In terms of math this equals the half image width minus + // the radius component on the current scanline in x direction ("rx"). + // + // If the zoom factor is high enough then the whole screen gets covered + // by the earth and the border of the earth disk isn't visible anymore. + // In that situation xLeft equals zero. + // For xRight the situation is similar. + + const int xLeft = ( imageWidth / 2 - rx > 0 ) ? imageWidth / 2 - rx + : 0; + const int xRight = ( imageWidth / 2 - rx > 0 ) ? xLeft + rx + rx + : imageWidth; + + QRgb * scanLine = (QRgb*)( m_canvasImage->scanLine( y ) ) + xLeft; + + const int xIpLeft = ( imageWidth / 2 - rx > 0 ) ? n * (int)( xLeft / n + 1 ) + : 1; + const int xIpRight = ( imageWidth / 2 - rx > 0 ) ? n * (int)( xRight / n - 1 ) + : n * (int)( xRight / n - 1 ) + 1; + + // Decrease pole distortion due to linear approximation ( y-axis ) + bool crossingPoleArea = false; + if ( northPole.v[Q_Z] > 0 + && northPoleY - ( n * 0.75 ) <= y + && northPoleY + ( n * 0.75 ) >= y ) + { + crossingPoleArea = true; + } + + int ncount = 0; + + for ( int x = xLeft; x < xRight; ++x ) { + // Prepare for interpolation + + const int leftInterval = xIpLeft + ncount * n; + + bool interpolate = false; + if ( x >= xIpLeft && x <= xIpRight ) { + + // Decrease pole distortion due to linear approximation ( x-axis ) +// mDebug() << QString("NorthPole X: %1, LeftInterval: %2").arg( northPoleX ).arg( leftInterval ); + if ( crossingPoleArea + && northPoleX >= leftInterval + n + && northPoleX < leftInterval + 2 * n + && x < leftInterval + 3 * n ) + { + interpolate = false; + } + else { + x += n - 1; + interpolate = !printQuality; + ++ncount; + } + } + else + interpolate = false; + + // Evaluate more coordinates for the 3D position vector of + // the current pixel. + const qreal qx = (qreal)( x - imageWidth / 2 ) * inverseRadius; + const qreal qr2z = qr - qx * qx; + const qreal qz = ( qr2z > 0.0 ) ? sqrt( qr2z ) : 0.0; + + // Create Quaternion from vector coordinates and rotate it + // around globe axis + Quaternion qpos( 0.0, qx, qy, qz ); + qpos.rotateAroundAxis( planetAxisMatrix ); + + qpos.getSpherical( lon, lat ); +// mDebug() << QString("lon: %1 lat: %2").arg(lon).arg(lat); + // Approx for n-1 out of n pixels within the boundary of + // xIpLeft to xIpRight + + if ( interpolate ) { + if (highQuality) + context.pixelValueApproxF( lon, lat, scanLine, n ); + else + context.pixelValueApprox( lon, lat, scanLine, n ); + + scanLine += ( n - 1 ); + } + +// Comment out the pixelValue line and run Marble if you want +// to understand the interpolation: + +// Uncomment the crossingPoleArea line to check precise +// rendering around north pole: + +// if ( !crossingPoleArea ) + if ( x < imageWidth ) { + if ( highQuality ) + context.pixelValueF( lon, lat, scanLine ); + else + context.pixelValue( lon, lat, scanLine ); + } + + ++scanLine; + } + + // copy scanline to improve performance + if ( interlaced && y + 1 < m_yBottom ) { + + const int pixelByteSize = m_canvasImage->bytesPerLine() / imageWidth; + + memcpy( m_canvasImage->scanLine( y + 1 ) + xLeft * pixelByteSize, + m_canvasImage->scanLine( y ) + xLeft * pixelByteSize, + ( xRight - xLeft ) * pixelByteSize ); + ++y; + } + } +} diff --git a/pool/shard001/C++/0017039_ui_resource_layer.cc b/pool/shard001/C++/0017039_ui_resource_layer.cc new file mode 100644 index 0000000000000000000000000000000000000000..59fbe8307b2097186e9dd97dfee238fcedcfb7cc --- /dev/null +++ b/pool/shard001/C++/0017039_ui_resource_layer.cc @@ -0,0 +1,167 @@ +// 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 "cc/layers/ui_resource_layer.h" + +#include "cc/layers/ui_resource_layer_impl.h" +#include "cc/resources/prioritized_resource.h" +#include "cc/resources/resource_update.h" +#include "cc/resources/resource_update_queue.h" +#include "cc/resources/scoped_ui_resource.h" +#include "cc/resources/ui_resource_bitmap.h" +#include "cc/trees/layer_tree_host.h" + +namespace cc { + + +namespace { + +class ScopedUIResourceHolder : public UIResourceLayer::UIResourceHolder { + public: + static scoped_ptr Create(LayerTreeHost* host, + const SkBitmap& skbitmap) { + return make_scoped_ptr(new ScopedUIResourceHolder(host, skbitmap)); + } + virtual UIResourceId id() OVERRIDE { return resource_->id(); } + + private: + ScopedUIResourceHolder(LayerTreeHost* host, const SkBitmap& skbitmap) { + resource_ = ScopedUIResource::Create(host, UIResourceBitmap(skbitmap)); + } + + scoped_ptr resource_; +}; + +class SharedUIResourceHolder : public UIResourceLayer::UIResourceHolder { + public: + static scoped_ptr Create(UIResourceId id) { + return make_scoped_ptr(new SharedUIResourceHolder(id)); + } + + virtual UIResourceId id() OVERRIDE { return id_; } + + private: + explicit SharedUIResourceHolder(UIResourceId id) : id_(id) {} + + UIResourceId id_; +}; + +} // anonymous namespace + +UIResourceLayer::UIResourceHolder::~UIResourceHolder() {} + +scoped_refptr UIResourceLayer::Create() { + return make_scoped_refptr(new UIResourceLayer()); +} + +UIResourceLayer::UIResourceLayer() + : Layer(), + uv_top_left_(0.f, 0.f), + uv_bottom_right_(1.f, 1.f) { + vertex_opacity_[0] = 1.0f; + vertex_opacity_[1] = 1.0f; + vertex_opacity_[2] = 1.0f; + vertex_opacity_[3] = 1.0f; +} + +UIResourceLayer::~UIResourceLayer() {} + +scoped_ptr UIResourceLayer::CreateLayerImpl( + LayerTreeImpl* tree_impl) { + return UIResourceLayerImpl::Create(tree_impl, id()).PassAs(); +} + +void UIResourceLayer::SetUV(const gfx::PointF& top_left, + const gfx::PointF& bottom_right) { + if (uv_top_left_ == top_left && uv_bottom_right_ == bottom_right) + return; + uv_top_left_ = top_left; + uv_bottom_right_ = bottom_right; + SetNeedsCommit(); +} + +void UIResourceLayer::SetVertexOpacity(float bottom_left, + float top_left, + float top_right, + float bottom_right) { + // Indexing according to the quad vertex generation: + // 1--2 + // | | + // 0--3 + if (vertex_opacity_[0] == bottom_left && + vertex_opacity_[1] == top_left && + vertex_opacity_[2] == top_right && + vertex_opacity_[3] == bottom_right) + return; + vertex_opacity_[0] = bottom_left; + vertex_opacity_[1] = top_left; + vertex_opacity_[2] = top_right; + vertex_opacity_[3] = bottom_right; + SetNeedsCommit(); +} + +void UIResourceLayer::SetLayerTreeHost(LayerTreeHost* host) { + if (host == layer_tree_host()) + return; + + Layer::SetLayerTreeHost(host); + + // Recreate the resource hold against the new LTH. + RecreateUIResourceHolder(); +} + +void UIResourceLayer::RecreateUIResourceHolder() { + ui_resource_holder_.reset(); + if (layer_tree_host() && !bitmap_.empty()) { + ui_resource_holder_ = + ScopedUIResourceHolder::Create(layer_tree_host(), bitmap_); + } + UpdateDrawsContent(HasDrawableContent()); +} + +void UIResourceLayer::SetBitmap(const SkBitmap& skbitmap) { + bitmap_ = skbitmap; + + RecreateUIResourceHolder(); + SetNeedsCommit(); +} + +void UIResourceLayer::SetUIResourceId(UIResourceId resource_id) { + if (ui_resource_holder_ && ui_resource_holder_->id() == resource_id) + return; + + if (resource_id) { + ui_resource_holder_ = SharedUIResourceHolder::Create(resource_id); + } else { + ui_resource_holder_.reset(); + } + + UpdateDrawsContent(HasDrawableContent()); + SetNeedsCommit(); +} + +bool UIResourceLayer::HasDrawableContent() const { + return ui_resource_holder_ && ui_resource_holder_->id() && + Layer::HasDrawableContent(); +} + +void UIResourceLayer::PushPropertiesTo(LayerImpl* layer) { + Layer::PushPropertiesTo(layer); + UIResourceLayerImpl* layer_impl = static_cast(layer); + + if (!ui_resource_holder_) { + layer_impl->SetUIResourceId(0); + } else { + DCHECK(layer_tree_host()); + + gfx::Size image_size = + layer_tree_host()->GetUIResourceSize(ui_resource_holder_->id()); + layer_impl->SetUIResourceId(ui_resource_holder_->id()); + layer_impl->SetImageBounds(image_size); + layer_impl->SetUV(uv_top_left_, uv_bottom_right_); + layer_impl->SetVertexOpacity(vertex_opacity_); + } +} + +} // namespace cc diff --git a/pool/shard001/C++/0017040_gunsms.cpp b/pool/shard001/C++/0017040_gunsms.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68c08717bd9ab68fce6f3046cecf4ed5c0b4da2e --- /dev/null +++ b/pool/shard001/C++/0017040_gunsms.cpp @@ -0,0 +1,75 @@ +#include "stdhdr.h" +#include "SmsDraw.h" +#include "fcc.h" +#include "guns.h" +#include "Graphics\Include\display.h" +#include "hardpnt.h" +#include "simveh.h" +#include "Sms.h" +#include "aircrft.h" +#include "simdrive.h" + +void SmsDrawable::GunDisplay (void) +{ + char tmpStr[12]; + int station, numRounds; + FireControlComputer *FCC = Sms->ownship->GetFCC(); + + // JPO - moved a lot of it into these two routines. + TopRow(0); + BottomRow(); + + //MI + if(g_bRealisticAvionics && FCC && FCC->GetSubMode() == + FireControlComputer::EEGS) + { + char tempstr[4] = ""; + sprintf(tempstr,"%s", Sms->FEDS == TRUE ? "ON" : "OFF"); + LabelButton (19, "SCOR", tempstr); + } + else if(g_bRealisticAvionics) + LabelButton(19,""); + else + LabelButton (19, "SCOR", "OFF"); + + if (Sms->ownship) + { + if (FCC->GetMasterMode() == FireControlComputer::Dogfight) + station = 0; + else + station = Sms->curHardpoint; + + GunClass *gun = Sms->GetGun(station); + if (gun) + numRounds = gun->numRoundsRemaining / 10; + else + numRounds = 0; + } + else + numRounds = 0; + + //MI I think this should only show RDY when we are in ARM, like all the other weapons + if (numRounds) + { + if(!g_bRealisticAvionics) + { + + sprintf (tmpStr, "%02dGUN", numRounds); + display->TextCenter (0.3F, 0.6F, "RDY"); + } + else + { + float x,y = 0; + GetButtonPos(5, &x, &y); //button for Gun + sprintf (tmpStr, "%02dGUN", numRounds); + if(Sms->MasterArm() == SMSBaseClass::Arm) + display->TextCenter (0.3F, y, "RDY"); + else if(Sms->MasterArm() == SMSBaseClass::Sim) + display->TextCenter (0.3F, y, "SIM"); + } + } + else + sprintf (tmpStr, "00GUN"); + + LabelButton (5, tmpStr); +} diff --git a/pool/shard001/C++/0017050_copy-renderer.cpp b/pool/shard001/C++/0017050_copy-renderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efd904dc53469b7d01cbef9c0b88323a87f4b07e --- /dev/null +++ b/pool/shard001/C++/0017050_copy-renderer.cpp @@ -0,0 +1,56 @@ +/* + * Copyright © 2012 Linaro Limited + * + * This file is part of the glmark2 OpenGL (ES) 2.0 benchmark. + * + * glmark2 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. + * + * glmark2 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 + * glmark2. If not, see . + * + * Authors: + * Alexandros Frantzis + */ +#include "options.h" +#include "scene.h" +#include "renderer.h" +#include "shader-source.h" + +CopyRenderer::CopyRenderer(const LibMatrix::vec2 &size) : + TextureRenderer(size, *copy_program(true)) +{ + copy_program_ = copy_program(false); +} + +Program * +CopyRenderer::copy_program(bool create_new) +{ + static Program *copy_program(0); + if (create_new) + copy_program = 0; + + if (!copy_program) { + copy_program = new Program(); + ShaderSource vtx_shader(Options::data_path + "/shaders/terrain-texture.vert"); + ShaderSource frg_shader(Options::data_path + "/shaders/terrain-overlay.frag"); + + Scene::load_shaders_from_strings(*copy_program, vtx_shader.str(), frg_shader.str()); + + copy_program->start(); + (*copy_program)["tDiffuse"] = 0; + (*copy_program)["opacity"] = 1.0f; + (*copy_program)["uvOffset"] = LibMatrix::vec2(0.0f, 0.0f); + (*copy_program)["uvScale"] = LibMatrix::vec2(1.0f, 1.0f); + copy_program->stop(); + } + + return copy_program; +} diff --git a/pool/shard001/C++/0017065_extension_gallery_install_apitest.cc b/pool/shard001/C++/0017065_extension_gallery_install_apitest.cc new file mode 100644 index 0000000000000000000000000000000000000000..efb11f1c2015e2fbe3b770c0688bd555a98a6054 --- /dev/null +++ b/pool/shard001/C++/0017065_extension_gallery_install_apitest.cc @@ -0,0 +1,85 @@ +// 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 "base/stringprintf.h" +#if defined (OS_WIN) +#include "base/win/windows_version.h" +#endif // defined (OS_WIN) + +#include "chrome/browser/extensions/extension_apitest.h" +#include "chrome/browser/extensions/extension_webstore_private_api.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/test/ui_test_utils.h" +#include "net/base/mock_host_resolver.h" + +class ExtensionGalleryInstallApiTest : public ExtensionApiTest { + public: + void SetUpCommandLine(CommandLine* command_line) { + ExtensionApiTest::SetUpCommandLine(command_line); + command_line->AppendSwitchASCII(switches::kAppsGalleryURL, + "http://www.example.com"); + } + + bool RunInstallTest(const std::string& page) { + std::string base_url = base::StringPrintf( + "http://www.example.com:%u/files/extensions/", + test_server()->host_port_pair().port()); + + std::string testing_install_base_url = base_url; + testing_install_base_url += "good.crx"; + + CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kAppsGalleryUpdateURL, testing_install_base_url); + + std::string page_url = base_url; + page_url += "api_test/extension_gallery_install/" + page; + + return RunPageTest(page_url.c_str()); + } +}; + +namespace { + +bool RunningOnXP() { +#if defined (OS_WIN) + return GetVersion() < base::win::VERSION_VISTA; +#else + return false; +#endif // defined (OS_WIN) +} + +} // namespace + +// TODO(asargent) - for some reason this test occasionally fails on XP, +// but not other versions of windows. http://crbug.com/55642 +#if defined (OS_WIN) +#define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall +#else +#define MAYBE_InstallAndUninstall InstallAndUninstall +#endif +IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, + MAYBE_InstallAndUninstall) { + if (RunningOnXP()) { + LOG(INFO) << "Adding host resolver rule"; + } + host_resolver()->AddRule("www.example.com", "127.0.0.1"); + if (RunningOnXP()) { + LOG(INFO) << "Starting test server"; + } + ASSERT_TRUE(test_server()->Start()); + + if (RunningOnXP()) { + LOG(INFO) << "Starting tests without user gesture checking"; + } + BeginInstallFunction::SetIgnoreUserGestureForTests(true); + ASSERT_TRUE(RunInstallTest("test.html")); + ASSERT_TRUE(RunInstallTest("complete_without_begin.html")); + ASSERT_TRUE(RunInstallTest("invalid_begin.html")); + + if (RunningOnXP()) { + LOG(INFO) << "Starting tests with user gesture checking"; + } + BeginInstallFunction::SetIgnoreUserGestureForTests(false); + ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); +} diff --git a/pool/shard001/C++/0017071_kastentoolviewwidget.cpp b/pool/shard001/C++/0017071_kastentoolviewwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62674a9c7fd4f3e33baf5885b1a6ceb44a645721 --- /dev/null +++ b/pool/shard001/C++/0017071_kastentoolviewwidget.cpp @@ -0,0 +1,82 @@ +/* + This file is part of the KDevelop Okteta module, part of the KDE project. + + Copyright 2010 Friedrich W. H. Kossebau + + 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.), 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 . +*/ + +#include "kastentoolviewwidget.h" + +// plugin +#include "oktetaview.h" +// Okteta Kasten +#include "kasten/okteta/bytearrayview.h" +// Kasten +#include +#include +// KDev +#include +#include +#include +#include +// Qt +#include + +namespace KDevelop +{ + +// TODO: find if hiddden, than unset target model +KastenToolViewWidget::KastenToolViewWidget( Kasten::AbstractToolView* toolView, QWidget* parent ) + : QWidget( parent ), + mToolView( toolView ) +{ + Sublime::Controller* controller = ICore::self()->uiController()->controller(); + connect( controller, &Sublime::Controller::mainWindowAdded, + this, &KastenToolViewWidget::onMainWindowAdded ); + const QList& mainWindows = controller->mainWindows(); + foreach( Sublime::MainWindow* mainWindow, mainWindows ) + onMainWindowAdded( mainWindow ); + + QVBoxLayout* layout = new QVBoxLayout( this ); + layout->setMargin( 0 ); + layout->addWidget( mToolView->widget() ); +} + +void KastenToolViewWidget::onMainWindowAdded( Sublime::MainWindow* mainWindow ) +{ + connect( mainWindow, &Sublime::MainWindow::activeViewChanged, + this, &KastenToolViewWidget::onActiveViewChanged ); + onActiveViewChanged( mainWindow->activeView() ); +} + +void KastenToolViewWidget::onActiveViewChanged( Sublime::View* view ) +{ + // TODO: check if own mainWindow + OktetaView* oktetaView = qobject_cast( view ); + Kasten::ByteArrayView* byteArrayView = oktetaView ? oktetaView->byteArrayView() : 0; + mToolView->tool()->setTargetModel( byteArrayView ); +} + +KastenToolViewWidget::~KastenToolViewWidget() +{ + Kasten::AbstractTool* tool = mToolView->tool(); + delete mToolView; + delete tool; +} + +} diff --git a/pool/shard001/C++/0017072_vme.cc b/pool/shard001/C++/0017072_vme.cc new file mode 100644 index 0000000000000000000000000000000000000000..72421b50b58b2a65a4003dad3fef79192e8cc15c --- /dev/null +++ b/pool/shard001/C++/0017072_vme.cc @@ -0,0 +1,192 @@ +#include "equipmentList_common.hh" +#include "globals.h" +#include "vme.h" +#include "maroc.h" + +extern int32_t BHandle; +extern int addr_conn_out; + +void InitVme() +{ + fprintf(stdout,"\n-----------------\nInit VME\n---\n"); + std::cout << "addr_conn_out: " << addr_conn_out << std::endl; + CVBoardTypes VMEBoard; + short Link; + short Device; + + // Initialize the Board + VMEBoard = cvV2718; + Link = 0; + Device = 0; + if( CAENVME_Init(VMEBoard, Link, Device, &BHandle) != cvSuccess ) { + printf("\n\n Error opening the device\n"); + exit(1); } + else fprintf(stdout,"---\nVME initialised\n-----------------\n"); +} + +/* Routine to read from VME bus (24 bit addr and 16 bit data) */ +unsigned short read_vme(int *data, int address) +{ + /* + unsigned short value_16; + int read_size; + if (lseek(ifile_map,(off_t)address,SEEK_SET)==-1) { + perror("read_vme lseek(): "); + exit(EXIT_FAILURE); + } + if ((read_size=read(ifile_map,(void*)(&value_16),2))==-1) { + perror("read_vme read(): "); + exit(EXIT_FAILURE); + } + *data_ptr = value_16; + */ + CVErrorCodes ret; + ret = CAENVME_ReadCycle(BHandle,(uint32_t)address,data,cvA24_U_DATA,cvD16); + if (ret==cvSuccess) ;//printf(" Cycle(s) completed normally\n"); + else if (ret==cvBusError){ printf(" Bus Error !!!"); return(1);} + else if (ret==cvCommError){ printf(" Communication Error !!!"); return(1);} + else{ printf(" Unknown Error !!!"); return(1);} + return(0); +} + +/* Routine to write on VME bus (24 bit addr and 16 bit data) */ +unsigned short write_vme(int data, int address) +{ + /* + unsigned short value_16=data; + int written_size; + if (lseek(ifile_map,(off_t)address,SEEK_SET)==-1) { + perror("write_vme lseek(): "); + exit(EXIT_FAILURE); + } + if ((written_size=write(ifile_map,&value_16,2))==-1) { + perror("write_vme write(): "); + exit(EXIT_FAILURE); + } + */ + CVErrorCodes ret; + ret = CAENVME_WriteCycle(BHandle,(uint32_t)address,&data,cvA24_U_DATA,cvD16); + if (ret==cvSuccess) ;//printf(" Cycle(s) completed normally\n"); + else if (ret==cvBusError){ printf(" Bus Error !!!"); return(1);} + else if (ret==cvCommError){ printf(" Communication Error !!!"); return(1);} + else{ printf(" Unknown Error !!!"); return(1);} + return(0); +} + +/* Clear one bit */ +void clear_bit(int *dataptr, int mode_bit) +{ + *dataptr = *dataptr & (~(1<> (15-ibit)) & 0x1; + if (xbit==1) { + set_bit(&local_reg,2); + write_vme(local_reg,addr_conn_out); + } else { + clear_bit(&local_reg,2); + write_vme(local_reg,addr_conn_out); + } + clock_bus_pulse(); + } + for (ibit=0; ibit<16; ibit++) { + xbit = (data >> (15-ibit)) & 0x1; + if (xbit==1) { + set_bit(&local_reg,2); + write_vme(local_reg,addr_conn_out); + } else { + clear_bit(&local_reg,2); + write_vme(local_reg,addr_conn_out); + } + clock_bus_pulse(); + } + clear_bit(&local_reg,1); + write_vme(local_reg,addr_conn_out); + clock_bus_pulse(); +} + + diff --git a/pool/shard001/C++/0017076_jsonfile.cpp b/pool/shard001/C++/0017076_jsonfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ab5543a1e68bba4062680cfd91e4418abd2fdf8 --- /dev/null +++ b/pool/shard001/C++/0017076_jsonfile.cpp @@ -0,0 +1,260 @@ +/* +This file is part of WebTooth-Extractor and for personal use the +GPL3 license applies. For any kind of commercial usage, you have to +acquire a commercial license before use. The copyright of the WebTooth +application and source code remains with Patrick Scheller and any +contributor to the project agrees with his commits to renounce to the +copyright of his parts completely. + +WebTooth-Extractor 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. + +WebTooth-Extractor 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 WebTooth-Extractor. If not, see http://www.gnu.org/licenses/ . +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +#include "jsonfile.h" + +JSONFile::JSONFile(QObject *parent) : QObject(parent) +{ + +} + +JSONFile::~JSONFile() +{ + +} + +bool JSONFile::readJsonFile(t_filterdata& filterlist, QHash& projectdata, const QString &prjfilepath) +{ + bool bRes = false; + + QJsonParseError jerror; + QFile projFile(prjfilepath); + if (!projFile.exists()) + { + qDebug() << "Error: File" << prjfilepath << "does not exist!"; + return(bRes); + } + else + { + //qDebug() << "File" << prjfilepath << "exists"; + } + QJsonDocument jdoc; + if (projFile.open(QIODevice::ReadOnly | QIODevice::Text)) + { + //qDebug() << "JSON-File could be opened"; + jdoc = QJsonDocument::fromJson(projFile.readAll(),&jerror); + if(jerror.error != QJsonParseError::NoError) + { + qDebug() << "ERROR-JSON-Read:" << jerror.errorString() << "at position:" << jerror.offset; + projFile.close(); + return (bRes); + } + else + { + //qDebug() << "QJsonDocument::fromJson() succeeded"; + } + } + else + { + qDebug() << "ERROR-JSON: File could not be opened"; + projFile.close(); + return(bRes); + } + QJsonObject rootObj = jdoc.object(); + projFile.close(); + + //QHashIterator itPrjData(projectdata); + projectdata.insert("projectapp", "WebTooth-Extractor"); + projectdata.insert("projectname", rootObj["projectname"].toString()); + projectdata.insert("projectauthor", rootObj["projectauthor"].toString()); + projectdata.insert("projectmodified", rootObj["projectmodified"].toString()); + projectdata.insert("cropthumb", rootObj["cropthumb"].toString()); + projectdata.insert("projecnotes", rootObj["projecnotes"].toString()); + projectdata.insert("projecturl", rootObj["projecturl"].toString()); + projectdata.insert("thumbheight", rootObj["thumbheight"].toString()); + projectdata.insert("thumbwidth", rootObj["thumbwidth"].toString()); + + // typedef QHash*> t_filterdata; + QJsonArray filters = rootObj["projectdata"].toArray(); + qDebug() << "No. of filters found in the project file:" << filters.size(); + int ideb = 0; // For Debug purpose + for(auto&& filterItem: filters) + { + //qDebug() << "XXX - filterItem"; + const QJsonObject& filter = filterItem.toObject(); + //filterlist.insert("filtername", new QVector(){filter["filtername"].toString()} ); + //filterlist.insert("filtertype", new QVector(){filter["filtertype"].toString()} ); + + QJsonArray arrProperties = filter["filterdata"].toArray(); + QVector* vattrlist= new QVector(); + for (auto&& item: arrProperties) + { + const QJsonObject& attrProp = item.toObject(); + if (filter["filtertype"].toString() == "tag") + { + //qDebug() << "Filtertype:" << filter["filtertype"].toString(); +// qDebug() << " > Filter-Sizes:" << attrProp["H Tag Name"].toString().size() << "," << attrProp["H ID Name"].toString().size() << "," << attrProp["H Class Name"].toString().size() +// << "," << attrProp["P Tag Name"].toString().size() << "," << attrProp["P Attribute Name"].toString().size() << "," << attrProp["P ID Name"].toString().size() +// << "," << attrProp["P Class Name"].toString().size(); + vattrlist->push_back(filter["filtertype"].toString()); + vattrlist->push_back(attrProp["H Tag Name"].toString()); + vattrlist->push_back(attrProp["H Attribute Name"].toString()); + vattrlist->push_back(attrProp["H ID Name"].toString()); + vattrlist->push_back(attrProp["H Class Name"].toString()); + vattrlist->push_back(attrProp["P Tag Name"].toString()); + vattrlist->push_back(attrProp["P Attribute Name"].toString()); + vattrlist->push_back(attrProp["P ID Name"].toString()); + vattrlist->push_back(attrProp["P Class Name"].toString()); + vattrlist->push_back(attrProp["Occurrence Amount"].toString()); + vattrlist->push_back(attrProp["Occurrence Function"].toString()); + } + else if (filter["filtertype"].toString() == "reg") + { + //qDebug() << "XXX - RegExpr"; + vattrlist->push_back(filter["filtertype"].toString()); + vattrlist->push_back(attrProp["Regular Expression"].toString()); + } + } + qDebug() << "vattrList contains no. of elements:" << vattrlist->size(); + filterlist.insert(filter["filtername"].toString(), vattrlist); + //qDebug() << "YYY - End of JSON-Read"; + bRes = true; + ideb++; + } + qDebug() << "iDeb count of loops:" << ideb; + qDebug() << "No. of elements in Filterlist:" << filterlist.size(); + return(bRes); +} + +bool JSONFile::writeJsonFile(const t_filterdata& filterlist, const QHash& projectdata, const QString &prjfilepath) +{ + qDebug() << "Entering writeJsonFile"; + bool bRes = false; + QDir dir; + qDebug() << "Current Path: " << dir.currentPath() << flush; + //QFileInfo myfileInfo; + QFile projFile(prjfilepath); + if (!projFile.open(QIODevice::WriteOnly | QIODevice::Text)) + { + qWarning("Couldn't open the project file."); + return(bRes); + } + + // ******************************* + QJsonObject rootObj;//root object + QHashIterator itPrjData(projectdata); + while (itPrjData.hasNext()) + { + itPrjData.next(); +// if (itPrjData.key() == "projectauthor") +// qDebug() << "ProjectAuthor will be written to JSON:" << itPrjData.value(); + rootObj[itPrjData.key()] = itPrjData.value(); + } + //rootObj["projectapp"] = "WebTooth-Extractor"; + //rootObj["projectname"] = "usertest"; + //rootObj["projectauthor"] = "Lunix Sdlavrot"; + //QDateTime now = QDateTime::currentDateTime(); + //rootObj["projectmodified"] = now.toString(Qt::ISODate); + + QJsonArray filters; + auto itFList = filterlist.constBegin(); + while (itFList != filterlist.constEnd()) + { + QJsonObject filter; + filter["filtername"] = itFList.key(); + auto myvec = itFList.value(); + filter["filtertype"] = myvec->at(0); + + QJsonArray arrProperties; + QJsonObject objProperties; + if (myvec->at(0) == "tag") + { + objProperties["H Tag Name"] = myvec->at(1); + objProperties["H Attribute Name"] = myvec->at(2); + objProperties["H ID Name"] = myvec->at(3); + objProperties["H Class Name"] = myvec->at(4); + + objProperties["P Tag Name"] = myvec->at(5); + objProperties["P Attribute Name"] = myvec->at(6); + objProperties["P ID Name"] = myvec->at(7); + objProperties["P Class Name"] = myvec->at(8); + + objProperties["Occurrence Amount"] = myvec->at(9); + objProperties["Occurrence Function"] = myvec->at(10); + } + else if (myvec->at(0) == "reg") + { + objProperties["Regular Expression"] = myvec->at(1); + } + arrProperties.append(objProperties); + filter["filterdata"] = arrProperties; + + filters.append(filter); + itFList++; + + } + rootObj["projectdata"] = filters; + + //qDebug() << "writeJsonFile: Before write to file."; + qint64 byteswritten = projFile.write( QJsonDocument(rootObj).toJson(/*QJsonDocument::Compact*/) ); + //qDebug() << "writeJsonFile: After write to file."; + projFile.close(); + + if (byteswritten == -1) + { + qDebug() << "No Bytes written to the JsonFile :("; + qWarning("Error: Could not write to the project file."); + } + else + { + qDebug() << byteswritten << "Bytes have been written to the file"; + bRes = true; + } + + return(bRes); +} + +bool JSONFile::openJsonFile() +{ + bool bRes = false; + return(bRes); +} + +QString JSONFile::getJsonFilePath(void) +{ + QString sRes = ""; + return(sRes); +} + +qint64 JSONFile::getJsonFileSize(void) +{ + qint64 iRes = 0; + return(iRes); +} + +bool JSONFile::checkJsonFile() +{ + bool bRes = false; + return(bRes); +} diff --git a/pool/shard001/C++/0017084_object_rep.cpp b/pool/shard001/C++/0017084_object_rep.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afc6d9800ea971c19e6f4569ea36277d85696d47 --- /dev/null +++ b/pool/shard001/C++/0017084_object_rep.cpp @@ -0,0 +1,273 @@ +// Copyright (c) 2003 Daniel Wallin and Arvid Norberg + +// 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. + +#define LUABIND_BUILDING + +#include +#include +#include + +namespace luabind { namespace detail +{ + + // dest is a function that is called to delete the c++ object this struct holds + object_rep::object_rep(instance_holder* instance, class_rep* crep) + : m_instance(instance) + , m_classrep(crep) + , m_dependency_cnt(0) + {} + + object_rep::~object_rep() + { + if (!m_instance) + return; + m_instance->~instance_holder(); + deallocate(m_instance); + } + + void object_rep::add_dependency(lua_State* L, int index) + { + assert(m_dependency_cnt < sizeof(object_rep)); + + void* key = (char*)this + m_dependency_cnt; + + lua_pushlightuserdata(L, key); + lua_pushvalue(L, index); + lua_rawset(L, LUA_REGISTRYINDEX); + + ++m_dependency_cnt; + } + + void object_rep::release_dependency_refs(lua_State* L) + { + for (std::size_t i = 0; i < m_dependency_cnt; ++i) + { + void* key = (char*)this + i; + lua_pushlightuserdata(L, key); + lua_pushnil(L); + lua_rawset(L, LUA_REGISTRYINDEX); + } + } + + int destroy_instance(lua_State* L) + { + object_rep* instance = static_cast(lua_touserdata(L, 1)); + + lua_pushstring(L, "__finalize"); + lua_gettable(L, 1); + + if (lua_isnil(L, -1)) + { + lua_pop(L, 1); + } + else + { + lua_pushvalue(L, 1); + lua_call(L, 1, 0); + } + + instance->release_dependency_refs(L); + instance->~object_rep(); + return 0; + } + + namespace + { + + int set_instance_value(lua_State* L) + { + lua_getfenv(L, 1); + lua_pushvalue(L, 2); + lua_rawget(L, -2); + + if (lua_isnil(L, -1) && lua_getmetatable(L, -2)) + { + lua_pushvalue(L, 2); + lua_rawget(L, -2); + lua_replace(L, -3); + lua_pop(L, 1); + } + + if (lua_tocfunction(L, -1) == &property_tag) + { + // this member is a property, extract the "set" function and call it. + lua_getupvalue(L, -1, 2); + + if (lua_isnil(L, -1)) + { + lua_pushfstring(L, "property '%s' is read only", lua_tostring(L, 2)); + lua_error(L); + } + + lua_pushvalue(L, 1); + lua_pushvalue(L, 3); + lua_call(L, 2, 0); + return 0; + } + + lua_pop(L, 1); + + if (!lua_getmetatable(L, 4)) + { + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setfenv(L, 1); + lua_pushvalue(L, 4); + lua_setmetatable(L, -2); + } + else + { + lua_pop(L, 1); + } + + lua_pushvalue(L, 2); + lua_pushvalue(L, 3); + lua_rawset(L, -3); + + return 0; + } + + int get_instance_value(lua_State* L) + { + lua_getfenv(L, 1); + lua_pushvalue(L, 2); + lua_rawget(L, -2); + + if (lua_isnil(L, -1) && lua_getmetatable(L, -2)) + { + lua_pushvalue(L, 2); + lua_rawget(L, -2); + } + + if (lua_tocfunction(L, -1) == &property_tag) + { + // this member is a property, extract the "get" function and call it. + lua_getupvalue(L, -1, 1); + lua_pushvalue(L, 1); + lua_call(L, 1, 1); + } + + return 1; + } + + int dispatch_operator(lua_State* L) + { + for (int i = 0; i < 2; ++i) + { + if (get_instance(L, 1 + i)) + { + int nargs = lua_gettop(L); + + lua_pushvalue(L, lua_upvalueindex(1)); + lua_gettable(L, 1 + i); + + if (lua_isnil(L, -1)) + { + lua_pop(L, 1); + continue; + } + + lua_insert(L, 1); // move the function to the bottom + + nargs = lua_toboolean(L, lua_upvalueindex(2)) ? 1 : nargs; + + if (lua_toboolean(L, lua_upvalueindex(2))) // remove trailing nil + lua_remove(L, 3); + + lua_call(L, nargs, 1); + return 1; + } + } + + lua_pop(L, lua_gettop(L)); + lua_pushstring(L, "No such operator defined"); + lua_error(L); + + return 0; + } + + } // namespace unnamed + + LUABIND_API void push_instance_metatable(lua_State* L) + { + lua_newtable(L); + + // just indicate that this really is a class and not just + // any user data + lua_pushboolean(L, 1); + lua_setfield(L, -2, "__luabind_class"); + + // This is used as a tag to determine if a userdata is a luabind + // instance. We use a numeric key and a cclosure for fast comparision. + lua_pushnumber(L, 1); + lua_pushcclosure(L, get_instance_value, 0); + lua_rawset(L, -3); + + lua_pushcclosure(L, destroy_instance, 0); + lua_setfield(L, -2, "__gc"); + + lua_pushcclosure(L, get_instance_value, 0); + lua_setfield(L, -2, "__index"); + + lua_pushcclosure(L, set_instance_value, 0); + lua_setfield(L, -2, "__newindex"); + + for (int op = 0; op < number_of_operators; ++op) + { + lua_pushstring(L, get_operator_name(op)); + lua_pushvalue(L, -1); + lua_pushboolean(L, op == op_unm || op == op_len); + lua_pushcclosure(L, &dispatch_operator, 2); + lua_settable(L, -3); + } + } + + LUABIND_API object_rep* get_instance(lua_State* L, int index) + { + object_rep* result = static_cast(lua_touserdata(L, index)); + + if (!result || !lua_getmetatable(L, index)) + return 0; + + lua_rawgeti(L, -1, 1); + + if (lua_tocfunction(L, -1) != &get_instance_value) + result = 0; + + lua_pop(L, 2); + + return result; + } + + LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls) + { + void* storage = lua_newuserdata(L, sizeof(object_rep)); + object_rep* result = new (storage) object_rep(0, cls); + cls->get_table(L); + lua_setfenv(L, -2); + lua_rawgeti(L, LUA_REGISTRYINDEX, cls->metatable_ref()); + lua_setmetatable(L, -2); + return result; + } + +}} + diff --git a/pool/shard001/C++/0017088_trajectory_builder_stub.cc b/pool/shard001/C++/0017088_trajectory_builder_stub.cc new file mode 100644 index 0000000000000000000000000000000000000000..b12caa86b808eb94aac351f2d890edc74f1f1530 --- /dev/null +++ b/pool/shard001/C++/0017088_trajectory_builder_stub.cc @@ -0,0 +1,173 @@ +/* + * Copyright 2017 The Cartographer Authors + * + * 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 "cartographer/cloud/internal/client/trajectory_builder_stub.h" + +#include "cartographer/cloud/internal/sensor/serialization.h" +#include "cartographer/cloud/proto/map_builder_service.pb.h" +#include "cartographer/mapping/internal/local_slam_result_data.h" +#include "cartographer/transform/transform.h" +#include "glog/logging.h" + +namespace cartographer { +namespace cloud { + +TrajectoryBuilderStub::TrajectoryBuilderStub( + std::shared_ptr<::grpc::Channel> client_channel, const int trajectory_id, + const std::string& client_id, + LocalSlamResultCallback local_slam_result_callback) + : client_channel_(client_channel), + trajectory_id_(trajectory_id), + client_id_(client_id), + receive_local_slam_results_client_(client_channel_) { + if (local_slam_result_callback) { + proto::ReceiveLocalSlamResultsRequest request; + request.set_trajectory_id(trajectory_id); + receive_local_slam_results_client_.Write(request); + auto* receive_local_slam_results_client_ptr = + &receive_local_slam_results_client_; + receive_local_slam_results_thread_ = absl::make_unique( + [receive_local_slam_results_client_ptr, local_slam_result_callback]() { + RunLocalSlamResultsReader(receive_local_slam_results_client_ptr, + local_slam_result_callback); + }); + } +} + +TrajectoryBuilderStub::~TrajectoryBuilderStub() { + if (receive_local_slam_results_thread_) { + receive_local_slam_results_thread_->join(); + } + if (add_rangefinder_client_) { + CHECK(add_rangefinder_client_->StreamWritesDone()); + CHECK(add_rangefinder_client_->StreamFinish().ok()); + } + if (add_imu_client_) { + CHECK(add_imu_client_->StreamWritesDone()); + CHECK(add_imu_client_->StreamFinish().ok()); + } + if (add_odometry_client_) { + CHECK(add_odometry_client_->StreamWritesDone()); + CHECK(add_odometry_client_->StreamFinish().ok()); + } + if (add_landmark_client_) { + CHECK(add_landmark_client_->StreamWritesDone()); + CHECK(add_landmark_client_->StreamFinish().ok()); + } + if (add_fixed_frame_pose_client_) { + CHECK(add_fixed_frame_pose_client_->StreamWritesDone()); + CHECK(add_fixed_frame_pose_client_->StreamFinish().ok()); + } +} + +void TrajectoryBuilderStub::AddSensorData( + const std::string& sensor_id, + const sensor::TimedPointCloudData& timed_point_cloud_data) { + if (!add_rangefinder_client_) { + add_rangefinder_client_ = absl::make_unique< + async_grpc::Client>( + client_channel_); + } + proto::AddRangefinderDataRequest request; + CreateAddRangeFinderDataRequest(sensor_id, trajectory_id_, client_id_, + sensor::ToProto(timed_point_cloud_data), + &request); + add_rangefinder_client_->Write(request); +} + +void TrajectoryBuilderStub::AddSensorData(const std::string& sensor_id, + const sensor::ImuData& imu_data) { + if (!add_imu_client_) { + add_imu_client_ = + absl::make_unique>( + client_channel_); + } + proto::AddImuDataRequest request; + CreateAddImuDataRequest(sensor_id, trajectory_id_, client_id_, + sensor::ToProto(imu_data), &request); + add_imu_client_->Write(request); +} + +void TrajectoryBuilderStub::AddSensorData( + const std::string& sensor_id, const sensor::OdometryData& odometry_data) { + if (!add_odometry_client_) { + add_odometry_client_ = absl::make_unique< + async_grpc::Client>( + client_channel_); + } + proto::AddOdometryDataRequest request; + CreateAddOdometryDataRequest(sensor_id, trajectory_id_, client_id_, + sensor::ToProto(odometry_data), &request); + add_odometry_client_->Write(request); +} + +void TrajectoryBuilderStub::AddSensorData( + const std::string& sensor_id, + const sensor::FixedFramePoseData& fixed_frame_pose) { + if (!add_fixed_frame_pose_client_) { + add_fixed_frame_pose_client_ = absl::make_unique< + async_grpc::Client>( + client_channel_); + } + proto::AddFixedFramePoseDataRequest request; + CreateAddFixedFramePoseDataRequest(sensor_id, trajectory_id_, client_id_, + sensor::ToProto(fixed_frame_pose), + &request); + add_fixed_frame_pose_client_->Write(request); +} + +void TrajectoryBuilderStub::AddSensorData( + const std::string& sensor_id, const sensor::LandmarkData& landmark_data) { + if (!add_landmark_client_) { + add_landmark_client_ = absl::make_unique< + async_grpc::Client>( + client_channel_); + } + proto::AddLandmarkDataRequest request; + CreateAddLandmarkDataRequest(sensor_id, trajectory_id_, client_id_, + sensor::ToProto(landmark_data), &request); + add_landmark_client_->Write(request); +} + +void TrajectoryBuilderStub::AddLocalSlamResultData( + std::unique_ptr local_slam_result_data) { + LOG(FATAL) << "Not implemented"; +} + +void TrajectoryBuilderStub::RunLocalSlamResultsReader( + async_grpc::Client* client, + LocalSlamResultCallback local_slam_result_callback) { + proto::ReceiveLocalSlamResultsResponse response; + while (client->StreamRead(&response)) { + int trajectory_id = response.trajectory_id(); + common::Time time = common::FromUniversal(response.timestamp()); + transform::Rigid3d local_pose = transform::ToRigid3(response.local_pose()); + sensor::RangeData range_data = sensor::FromProto(response.range_data()); + auto insertion_result = + response.has_insertion_result() + ? absl::make_unique( + InsertionResult{mapping::NodeId{ + response.insertion_result().node_id().trajectory_id(), + response.insertion_result().node_id().node_index()}}) + : nullptr; + local_slam_result_callback(trajectory_id, time, local_pose, range_data, + std::move(insertion_result)); + } + client->StreamFinish(); +} + +} // namespace cloud +} // namespace cartographer diff --git a/pool/shard001/C++/0017090_unnest-node.cc b/pool/shard001/C++/0017090_unnest-node.cc new file mode 100644 index 0000000000000000000000000000000000000000..9444276f296dec40e3a0b544ae54ad76446dfe4c --- /dev/null +++ b/pool/shard001/C++/0017090_unnest-node.cc @@ -0,0 +1,173 @@ +// Copyright 2015 Cloudera 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 "common/status.h" +#include "exec/unnest-node.h" +#include "exec/subplan-node.h" +#include "exprs/expr-context.h" +#include "exprs/slot-ref.h" +#include "runtime/runtime-state.h" +#include "util/runtime-profile.h" + +namespace impala { + +const ArrayValue UnnestNode::EMPTY_ARRAY_VALUE; + +UnnestNode::UnnestNode(ObjectPool* pool, const TPlanNode& tnode, + const DescriptorTbl& descs) + : ExecNode(pool, tnode, descs), + item_byte_size_(0), + array_expr_ctx_(NULL), + array_slot_desc_(NULL), + array_tuple_idx_(-1), + array_value_(NULL), + item_idx_(0), + num_collections_(0), + total_collection_size_(0), + max_collection_size_(-1), + min_collection_size_(-1), + avg_collection_size_counter_(NULL), + max_collection_size_counter_(NULL), + min_collection_size_counter_(NULL), + num_collections_counter_(NULL) { +} + +Status UnnestNode::Init(const TPlanNode& tnode) { + RETURN_IF_ERROR(ExecNode::Init(tnode)); + DCHECK(tnode.__isset.unnest_node); + Expr::CreateExprTree(pool_, tnode.unnest_node.collection_expr, &array_expr_ctx_); + return Status::OK(); +} + +Status UnnestNode::Prepare(RuntimeState* state) { + SCOPED_TIMER(runtime_profile_->total_time_counter()); + DCHECK(containing_subplan_ != NULL) << "set_containing_subplan() must be called"; + RETURN_IF_ERROR(ExecNode::Prepare(state)); + + avg_collection_size_counter_ = + ADD_COUNTER(runtime_profile_, "AvgCollectionSize", TUnit::DOUBLE_VALUE); + max_collection_size_counter_ = + ADD_COUNTER(runtime_profile_, "MaxCollectionSize", TUnit::UNIT); + min_collection_size_counter_ = + ADD_COUNTER(runtime_profile_, "MinCollectionSize", TUnit::UNIT); + num_collections_counter_ = + ADD_COUNTER(runtime_profile_, "NumCollections", TUnit::UNIT); + + DCHECK_EQ(1, row_desc().tuple_descriptors().size()); + const TupleDescriptor* item_tuple_desc = row_desc().tuple_descriptors()[0]; + DCHECK(item_tuple_desc != NULL); + item_byte_size_ = item_tuple_desc->byte_size(); + RETURN_IF_ERROR(array_expr_ctx_->Prepare( + state, containing_subplan_->child(0)->row_desc(), expr_mem_tracker())); + + // Set the array_slot_desc_ and the corresponding tuple index used for manually + // evaluating the array SlotRef and for projection. + DCHECK(array_expr_ctx_->root()->is_slotref()); + const SlotRef* slot_ref = static_cast(array_expr_ctx_->root()); + array_slot_desc_ = state->desc_tbl().GetSlotDescriptor(slot_ref->slot_id()); + DCHECK(array_slot_desc_ != NULL); + const RowDescriptor& row_desc = containing_subplan_->child(0)->row_desc(); + array_tuple_idx_ = row_desc.GetTupleIdx(array_slot_desc_->parent()->id()); + + return Status::OK(); +} + +Status UnnestNode::Open(RuntimeState* state) { + SCOPED_TIMER(runtime_profile_->total_time_counter()); + RETURN_IF_ERROR(ExecNode::Open(state)); + RETURN_IF_ERROR(array_expr_ctx_->Open(state)); + + DCHECK(containing_subplan_->current_row() != NULL); + Tuple* tuple = containing_subplan_->current_input_row_->GetTuple(array_tuple_idx_); + if (tuple != NULL) { + // Retrieve the array value to be unnested directly from the tuple. We purposely + // ignore the null bit of the slot because we may have set it in a previous Open() + // of this same unnest node for projection. + array_value_ = reinterpret_cast( + tuple->GetSlot(array_slot_desc_->tuple_offset())); + // Projection: Set the slot containing the array value to NULL. + tuple->SetNull(array_slot_desc_->null_indicator_offset()); + } else { + array_value_ = &EMPTY_ARRAY_VALUE; + DCHECK_EQ(array_value_->num_tuples, 0); + } + + ++num_collections_; + COUNTER_SET(num_collections_counter_, num_collections_); + total_collection_size_ += array_value_->num_tuples; + COUNTER_SET(avg_collection_size_counter_, + static_cast(total_collection_size_) / num_collections_); + if (max_collection_size_ == -1 || array_value_->num_tuples > max_collection_size_) { + max_collection_size_ = array_value_->num_tuples; + COUNTER_SET(max_collection_size_counter_, max_collection_size_); + } + if (min_collection_size_ == -1 || array_value_->num_tuples < min_collection_size_) { + min_collection_size_ = array_value_->num_tuples; + COUNTER_SET(min_collection_size_counter_, min_collection_size_); + } + return Status::OK(); +} + +Status UnnestNode::GetNext(RuntimeState* state, RowBatch* row_batch, bool* eos) { + SCOPED_TIMER(runtime_profile_->total_time_counter()); + // Avoid expensive query maintenance overhead for small arrays. + if (item_idx_ > 0) { + RETURN_IF_CANCELLED(state); + RETURN_IF_ERROR(QueryMaintenance(state)); + } + *eos = false; + + // Populate the output row_batch with tuples from the array. + DCHECK(array_value_ != NULL); + while (item_idx_ < array_value_->num_tuples) { + Tuple* item = + reinterpret_cast(array_value_->ptr + item_idx_ * item_byte_size_); + ++item_idx_; + int row_idx = row_batch->AddRow(); + TupleRow* row = row_batch->GetRow(row_idx); + row->SetTuple(0, item); + // TODO: Ideally these should be evaluated by the parent scan node. + if (EvalConjuncts(&conjunct_ctxs_[0], conjunct_ctxs_.size(), row)) { + row_batch->CommitLastRow(); + // The limit is handled outside of this loop. + if (row_batch->AtCapacity()) break; + } + } + num_rows_returned_ += row_batch->num_rows(); + + // Checking the limit here is simpler/cheaper than doing it in the loop above. + if (ReachedLimit()) { + *eos = true; + row_batch->set_num_rows(row_batch->num_rows() - (num_rows_returned_ - limit_)); + num_rows_returned_ = limit_; + } else if (item_idx_ == array_value_->num_tuples) { + *eos = true; + } + COUNTER_SET(rows_returned_counter_, num_rows_returned_); + return Status::OK(); +} + +Status UnnestNode::Reset(RuntimeState* state) { + item_idx_ = 0; + return ExecNode::Reset(state); +} + +void UnnestNode::Close(RuntimeState* state) { + if (is_closed()) return; + DCHECK(array_expr_ctx_ != NULL); + array_expr_ctx_->Close(state); + ExecNode::Close(state); +} + +} diff --git a/pool/shard001/C++/0017105_dtb_object.cc b/pool/shard001/C++/0017105_dtb_object.cc new file mode 100644 index 0000000000000000000000000000000000000000..841db8c1263fa9d2ea6f76d8eff8ae49cf018a77 --- /dev/null +++ b/pool/shard001/C++/0017105_dtb_object.cc @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2013 The Regents of The University of Michigan + * 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 holders 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. + * + * Authors: Anthony Gutierrez + */ + +#include +#include +#include + +#include + +#include "base/loader/dtb_object.hh" +#include "sim/byteswap.hh" +#include "fdt.h" +#include "libfdt.h" + +ObjectFile * +DtbObject::tryFile(const std::string &fname, size_t len, uint8_t *data) +{ + // Check if this is a FDT file by looking for magic number + if (fdt_magic((void*)data) == FDT_MAGIC) { + return new DtbObject(fname, len, data, + ObjectFile::UnknownArch, ObjectFile::UnknownOpSys); + } else { + return NULL; + } +} + +DtbObject::DtbObject(const std::string &_filename, size_t _len, uint8_t *_data, + Arch _arch, OpSys _opSys) + : ObjectFile(_filename, _len, _data, _arch, _opSys) +{ + text.baseAddr = 0; + text.size = len; + text.fileImage = fileData; + + data.baseAddr = 0; + data.size = 0; + data.fileImage = NULL; + + bss.baseAddr = 0; + bss.size = 0; + bss.fileImage = NULL; + + fileDataMmapped = true; +} + +DtbObject::~DtbObject() +{ + // Make sure to clean up memory properly depending + // on how buffer was allocated. + if (fileData && !fileDataMmapped) { + delete [] fileData; + fileData = NULL; + } else if (fileData) { + munmap(fileData, len); + fileData = NULL; + } +} + +bool +DtbObject::addBootCmdLine(const char* _args, size_t len) +{ + const char* root_path = "/"; + const char* node_name = "chosen"; + const char* full_path_node_name = "/chosen"; + const char* property_name = "bootargs"; + + // Make a new buffer that has extra space to add nodes/properties + int newLen = 2*this->len; + uint8_t* fdt_buf_w_space = new uint8_t[newLen]; + // Copy and unpack flattened device tree into new buffer + int ret = fdt_open_into((void*)fileData, (void*)fdt_buf_w_space, (newLen)); + if (ret < 0) { + warn("Error resizing buffer of flattened device tree, " + "errno: %d\n", ret); + delete [] fdt_buf_w_space; + return false; + } + + // First try finding the /chosen node in the dtb + int offset = fdt_path_offset((void*)fdt_buf_w_space, full_path_node_name); + if (offset < 0) { + // try adding the node by walking dtb tree to proper insertion point + offset = fdt_path_offset((void*)fdt_buf_w_space, root_path); + offset = fdt_add_subnode((void*)fdt_buf_w_space, offset, node_name); + offset = fdt_path_offset((void*)fdt_buf_w_space, full_path_node_name); + if (offset < 0) { + warn("Error finding or adding \"chosen\" subnode to flattened " + "device tree, errno: %d\n", offset); + delete [] fdt_buf_w_space; + return false; + } + } + + // Set the bootargs property in the /chosen node + ret = fdt_setprop((void*)fdt_buf_w_space, offset, property_name, + (const void*)_args, len+1); + if (ret < 0) { + warn("Error setting \"bootargs\" property to flattened device tree, " + "errno: %d\n", ret); + delete [] fdt_buf_w_space; + return false; + } + + // Repack the dtb for kernel use + ret = fdt_pack((void*)fdt_buf_w_space); + if (ret < 0) { + warn("Error re-packing flattened device tree structure, " + "errno: %d\n", ret); + delete [] fdt_buf_w_space; + return false; + } + + text.size = newLen; + text.fileImage = fdt_buf_w_space; + + // clean up old buffer and set to new fdt blob + munmap(fileData, this->len); + fileData = fdt_buf_w_space; + fileDataMmapped = false; + this->len = newLen; + + return true; +} + +Addr +DtbObject::findReleaseAddr() +{ + void *fd = (void*)fileData; + + int offset = fdt_path_offset(fd, "/cpus/cpu@0"); + int len; + + const void* temp = fdt_getprop(fd, offset, "cpu-release-addr", &len); + Addr rel_addr = 0; + + if (len > 3) + rel_addr = betoh(*static_cast(temp)); + if (len == 8) + rel_addr = (rel_addr << 32) | betoh(*(static_cast(temp)+1)); + + return rel_addr; +} + + +bool +DtbObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask) +{ + // nothing to do here + return false; +} + +bool +DtbObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask) +{ + // nothing to do here + return false; +} diff --git a/pool/shard001/C++/0017113_Claw.cpp b/pool/shard001/C++/0017113_Claw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b7527fa97def936c30a1f2e25a550bc276d5406 --- /dev/null +++ b/pool/shard001/C++/0017113_Claw.cpp @@ -0,0 +1,175 @@ +// Copyright (c) 2014-2021 FRC Team 3512. All Rights Reserved. + +#include "subsystems/Claw.hpp" + +#include +#include +#include + +Claw::Claw() { + // Sets degrees rotated per pulse of encoder + m_angleEncoder.SetDistancePerPulse((1.0 / 71.0) * 14.0 / 44.0); + + m_ballShooter.emplace_back(8); + m_ballShooter.emplace_back(2); + m_ballShooter.emplace_back(3); + m_ballShooter.emplace_back(6); +} + +void Claw::SetAngleReference(units::degree_t shooterAngle) { + m_controller.SetSetpoint(shooterAngle.to()); +} + +units::degree_t Claw::GetAngleReference() const { + return units::degree_t{m_controller.GetSetpoint()}; +} + +void Claw::SetWheel(double speed) { m_intakeWheel.Set(speed); } + +void Claw::Shoot() { + if (m_shooterState == ShooterState::kIdle) { + m_collectorArm.Set(true); + m_shooterState = ShooterState::kArmIsLifting; + m_shootTimer.Start(); + m_shootTimer.Reset(); + } +} + +bool Claw::IsShooting() const { return m_shooterState != ShooterState::kIdle; } + +void Claw::RobotPeriodic() { + static frc::Joystick driveStick2{2}; + static frc::Joystick shootStick{3}; + + if (driveStick2.GetRawButtonPressed(7)) { + SetAngleReference(190_deg); + } + + if (driveStick2.GetRawButtonPressed(9)) { + SetAngleReference(106_deg); + } + + if (driveStick2.GetRawButtonPressed(8)) { + SetAngleReference(57_deg); + } + + if (driveStick2.GetRawButtonPressed(11)) { + // Collector should always be retracted when resetting encoder + m_collectorArm.Set(false); + SetAngleReference(0_deg); + } + + if (driveStick2.GetRawButtonPressed(10)) { + SetAngleReference(GetAngleReference() + 3_deg); + } + + if (driveStick2.GetRawButtonPressed(12)) { + SetAngleReference(GetAngleReference() - 3_deg); + } + + // Engage collector + if (driveStick2.GetRawButtonPressed(2)) { + m_collectorArm.Set(!m_collectorArm.Get()); + } + + // Shoots a ball + if ((shootStick.GetRawButtonPressed(1) || + driveStick2.GetRawButtonPressed(1)) && + !IsShooting()) { + Shoot(); + } + + if (shootStick.GetRawButtonPressed(3)) { + SetWheel(-1.0); + } else if (shootStick.GetRawButtonPressed(4)) { + SetWheel(1.0); + } else { + SetWheel(0.0); + } + + double ff = 0.0; + if (m_controller.GetSetpoint() > 0.0) { + ff = kK * + std::cos((m_angleEncoder.GetDistance() + kL) * wpi::math::pi / + 180.0) / + m_controller.GetSetpoint(); + } + double fb = m_controller.Calculate(m_angleEncoder.GetDistance()); + + m_clawRotator.Set(ff + fb); + + if (m_shooterState == ShooterState::kArmIsLifting && + m_shootTimer.HasPeriodPassed(0.5_s)) { + for (auto& solenoid : m_ballShooter) { + solenoid.Set(true); + } + m_shootTimer.Reset(); + m_shooterState = ShooterState::kShooting; + } + if (m_shooterState == ShooterState::kShooting && + m_shootTimer.HasPeriodPassed(2.0_s)) { + for (auto& solenoid : m_ballShooter) { + solenoid.Set(false); + } + m_vacuum.Set(frc::Relay::kOn); + m_shootTimer.Reset(); + m_shooterState = ShooterState::kVacuuming; + } + if (m_shooterState == ShooterState::kVacuuming && + m_shootTimer.HasPeriodPassed(3.0_s)) { + m_vacuum.Set(frc::Relay::kOff); + m_collectorArm.Set(false); + + m_shootTimer.Reset(); + m_shooterState = ShooterState::kIdle; + } + + // Spins intake wheel to keep ball in while rotating claw at high speeds + if (std::abs(m_angleEncoder.GetRate()) > 35.0) { + SetWheel(-1.0); + } + + /* Fixes arm, when at reset angle, not touching zeroSwitch due to gradual + * encoder error. If limit switch isn't pressed but arm is supposedly at + * zeroing point or farther: + */ + if (m_zeroSwitch.Get() && GetAngleReference() <= 1_deg) { + SetAngleReference(GetAngleReference() - 5_deg); + } + + // If wasn't pressed last time and is now + if (!m_zeroSwitch.Get() && GetAngleReference() <= 0_deg) { + SetAngleReference(0_deg); + m_controller.Reset(); + m_angleEncoder.Reset(); + } + + // Close claw if zero switch is pressed + if (m_zeroSwitch.Get() && !IsShooting()) { + m_collectorArm.Set(false); + } + + m_lastZeroSwitch = m_zeroSwitch.Get(); +} + +void Claw::TestClaw() { + auto& ds = frc::DriverStation::GetInstance(); + + for (auto& solenoid : m_ballShooter) { + solenoid.Set(true); + frc2::Wait(1.5_s); + + solenoid.Set(false); + frc2::Wait(1.5_s); + + m_vacuum.Set(frc::Relay::kOn); + frc2::Wait(1.5_s); + + m_vacuum.Set(frc::Relay::kOff); + frc2::Wait(1.5_s); + + if (ds.IsDisabled()) { + return; + } + } +} diff --git a/pool/shard001/C++/0017115_target_anim_ctrl.cpp b/pool/shard001/C++/0017115_target_anim_ctrl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea1eeeca0360ecf4322ae432c83ce242cb571279 --- /dev/null +++ b/pool/shard001/C++/0017115_target_anim_ctrl.cpp @@ -0,0 +1,227 @@ +// NeL - MMORPG Framework +// Copyright (C) 2010 Winch Gate Property Limited +// +// This program 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. +// +// 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +#include "std3d.h" +#include "nel/misc/common.h" +#include "nel/3d/target_anim_ctrl.h" +#include "nel/3d/bone.h" +#include "nel/3d/skeleton_model.h" +#include "nel/3d/scene.h" + +using namespace std; +using namespace NLMISC; + +namespace NL3D { + + +// *************************************************************************** +CTargetAnimCtrl::CTargetAnimCtrl() +{ + Mode= DirectionMode; + WorldTarget= CVector::Null; + EyePos= CVector::Null; + // Default Direction to "LookBack". + DefaultWorldDirection.set(0,0,1,0); + MaxAngle= (float)Pi/3; + MaxAngularVelocity= (float)(2*Pi); + Enabled= true; + _EnableToDisableTransition= false; + _LastEnabled= true; +} + + +// *************************************************************************** +CTargetAnimCtrl::~CTargetAnimCtrl() +{ +} + + +// *************************************************************************** +void CTargetAnimCtrl::execute(CSkeletonModel *model, CBone *bone) +{ + // no op if req not met + if(!bone || !model || bone->getTransformMode()!=ITransformable::RotQuat) + return; + + // If the user changed the Enabled state, must do a transition. + if(_LastEnabled!=Enabled) + { + _LastEnabled= Enabled; + // if re-enable the control while completely disabled before + if(Enabled && !_EnableToDisableTransition) + { + // set the LastLSRotation so that it match the current anim ones. + _LastLSRotation= getCurrentLSRotationFromBone(model, bone); + } + // if disable the ctrl, then do a transition first + if(!Enabled) + { + _EnableToDisableTransition= true; + } + } + + // If not enabled, and not in transition, no op. + if( !Enabled && !_EnableToDisableTransition) + return; + + // If Target mode, compute CurrentWorldDirection + // *********** + // NB: does need to compute direction if disabled (even if in transition) + if(Mode==TargetMode && Enabled) + { + // get the eye pos in world. + CVector worldEye= bone->getWorldMatrix()*EyePos; + // get the world dir + CVector worldDir= (WorldTarget - worldEye).normed(); + // get the associated quat + CMatrix mat; + mat.setRot(CVector::I, worldDir, CVector::K); + mat.normalize(CMatrix::YZX); + CurrentWorldDirection= mat.getRot(); + } + + + // compute rotation to apply In LocalSkeleton Space + // *********** + CQuat currentLSRotation; + + /* Get the Skeleton default WorldMatrix (bind pos). used later + TRICK: to get the default Skeleton WorldMatrix, get it from Bone[0] (ie "Bip01") + We cannot use the Default Pos/Rot of the skeleton model because of export bug (not exported...) + So, since Bip01 as no Local Rot (yes, its true, exporter report all Bip01 rots on Skeleton), + we are sure that Bip01 BindPos is the default Skeleton World Matrix. + */ + CQuat rootInvBP= model->Bones[0].getBoneBase().InvBindPos.getRot(); + + // If ctrl not enabled, take the LSRotation from the animation + if(!Enabled) + { + currentLSRotation= getCurrentLSRotationFromBone(model, bone); + } + else + { + // Get the wanted direction in LocalSkeleton Space. + CQuat currentLSDirection; + + // Get the current wanted WorldDirection into LocalSkeleton space (hence using current skeleton WorldMatrix). + CMatrix toLSSpace= model->getWorldMatrix(); + currentLSDirection= toLSSpace.getRot().conjugate() * CurrentWorldDirection; + + // Get the default WorldDirection into LocalSkeleton space (hence using default skeleton WorldMatrix). + CQuat defaultLSDirection= rootInvBP * DefaultWorldDirection; + + /* get the rotation to apply to the bone when it is in bind Pos. If this quat is identity, + then the bone will be in default (or bind) pos. + It is in essence the "rotation to apply to defaultDirection in LS space, in order to get + the wanted current direction in LS space". + The makeClosest() is here just to ensure that the resulting angle do not clamp + if(Enabled) + { + // to AngleAxis. + CAngleAxis angleAxis= currentLSRotation.getAngleAxis(); + // Clamp the angle + clamp(angleAxis.Angle, -MaxAngle, MaxAngle); + // back To Quat. + currentLSRotation.setAngleAxis(angleAxis); + } + + // get the dt of the scene. + CScene *scene= model->getOwnerScene(); + float sceneDt= scene->getEllapsedTime(); + float maxDeltaAngle= MaxAngularVelocity*sceneDt; + // get the quat that change from LastRotation to CurrentRotation + CQuat rotMod= _LastLSRotation.conjugate() * currentLSRotation; + // compute how many rotation we are allowed to do. + float rotModAngle= (float)fabs(rotMod.getAngle()); + bool rotSpeedClamped= false; + if(rotModAngle) + { + float factor= (float)fabs(maxDeltaAngle) / rotModAngle; + // If cannot do all the rotation this frame + if(factor<1) + { + // then slerp between last and current rotation + currentLSRotation.makeClosest(_LastLSRotation); + currentLSRotation= CQuat::slerp(_LastLSRotation, currentLSRotation, factor); + rotSpeedClamped= true; + } + } + + // if the rotation has not been clamped for speed consideration, and if !Enabed, it's mean we have ended + // the transition => no more compute next time + if(!Enabled && !rotSpeedClamped) + _EnableToDisableTransition= false; + + // bkup last rotation + _LastLSRotation= currentLSRotation; + + // Apply the weighted Rotation to the bone + // *********** + // Get the bone Bind Pos in LocalSkeleton space (hence using Default Skeleton WorldMatrix) + CQuat boneBindPosInWorld= bone->getBoneBase().InvBindPos.getRot().conjugate(); + CQuat boneBindPosInLS= rootInvBP * boneBindPosInWorld; + // rotate it to match our wanted direction. + boneBindPosInLS= currentLSRotation * boneBindPosInLS; + + // get it in bone local space. + // get the Bone Parent LocalSkeletonMatrix + CBone *boneParent= bone->getFatherId()==-1? NULL : &model->Bones[bone->getFatherId()]; + CQuat currentLocalQuat; + if(!boneParent) + currentLocalQuat= boneBindPosInLS; + else + { + // compute the rotation to apply, in local space + CQuat qp= boneParent->getLocalSkeletonMatrix().getRot(); + currentLocalQuat= qp.conjugate() * boneBindPosInLS; + } + + // set the new LocalRotQuat + bone->setRotQuat(currentLocalQuat); + // and recompute the bone (but without AnimCtrl of course :) ) + bone->compute(boneParent, model->getWorldMatrix(), NULL); + +} + + +// *************************************************************************** +CQuat CTargetAnimCtrl::getCurrentLSRotationFromBone(CSkeletonModel *model, CBone *bone) +{ + // get the current rotation matrix (qmat) of this bone, in LS space + CQuat currentLSRot= bone->getLocalSkeletonMatrix().getRot(); + + // get the default bindPos (qb) rotation of this bone, in LS space. + CQuat boneBindPosInWorld= bone->getBoneBase().InvBindPos.getRot().conjugate(); + CQuat rootInvBP= model->Bones[0].getBoneBase().InvBindPos.getRot(); + CQuat boneBindPosInLS= rootInvBP * boneBindPosInWorld; + + // The rotation (qrot) is computed such that qmat= qrot * qb + currentLSRot.makeClosest(boneBindPosInLS); + return currentLSRot * boneBindPosInLS.conjugate(); +} + + + +} // NL3D diff --git a/pool/shard001/C++/0017116_cellcolors.cpp b/pool/shard001/C++/0017116_cellcolors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8058db0bd3e767f9acfd289cbefafa16fe33dc32 --- /dev/null +++ b/pool/shard001/C++/0017116_cellcolors.cpp @@ -0,0 +1,122 @@ +/* +Dwarf Therapist +Copyright (c) 2009 Trey Stout (chmod) + +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 "cellcolors.h" +#include "viewcolumn.h" +#include "dwarftherapist.h" +#include "cellcolordef.h" + +CellColors::CellColors(QObject *parent) + : QObject(parent) + , m_override_cell_colors(false) +{ +} + +CellColors::CellColors(const CellColors &cc) + : QObject(cc.parent()) +{ + m_color_defs = cc.m_color_defs; + m_override_cell_colors = cc.m_override_cell_colors; +} + +CellColors::~CellColors(){ + m_color_defs.clear(); +} + +void CellColors::load_settings(QSettings &s){ + m_override_cell_colors = s.value("overrides_cell_colors",false).toBool(); + if(m_override_cell_colors){ + set_color(0,s.value("active_labor").value()); + set_color(1,s.value("pending_color").value()); + set_color(2,s.value("disabled_color").value()); + } +} + +void CellColors::inherit_colors(const CellColors &cc){ + int idx = 0; + foreach(QSharedPointer c, cc.m_color_defs){ + //if we're not overridding or this specific color isn't overridden, then inherit + if(!m_override_cell_colors || !c->is_overridden()){ + m_color_defs[idx].swap(c); + } + idx++; + } +} + +void CellColors::use_defaults(){ + //by default use the global color scheme + m_color_defs.clear(); + m_color_defs.append(DT->get_global_color(GCOL_ACTIVE)); + m_color_defs.append(DT->get_global_color(GCOL_PENDING)); + m_color_defs.append(DT->get_global_color(GCOL_DISABLED)); +} + +QColor CellColors::get_default_color(int idx) const{ + return DT->get_global_color(static_cast(idx))->color(); +} + +QSharedPointer CellColors::get_default_color_def(int idx){ + return DT->get_global_color(static_cast(idx)); +} + +void CellColors::write_to_ini(QSettings &s){ + //only write values if they've overridden the defaults + if(m_override_cell_colors){ + s.setValue("overrides_cell_colors",m_override_cell_colors); + foreach(QSharedPointer c, m_color_defs){ + s.setValue(c->key(),c->color()); + } + } +} + +QColor CellColors::get_color(int idx) const { + return m_color_defs.at(idx)->color(); +} + +QVector > CellColors::get_color_defs(){ + return m_color_defs; +} + +void CellColors::set_color(int idx, QColor c){ + if(c.isValid()){ + if(c != get_default_color(idx)){ + //new color is valid and not the default color + if(m_color_defs.at(idx)->is_overridden()){ + //current color def is already custom, update the color def's color + m_color_defs.at(idx)->set_color(c); + }else{ + //current color def is not custom, so it's the default. create a new def by copying the existing one + QSharedPointer cpy = QSharedPointer(new CellColorDef(*m_color_defs.at(idx))); + cpy->set_color(c); + cpy->set_overridden(true); + m_color_defs[idx].swap(cpy); + } + }else{ + //new color is the default color + if(m_color_defs.at(idx)->is_overridden()){ + //current color def is custom, replace it with the default color def + QSharedPointer def = get_default_color_def(idx); + m_color_defs[idx].swap(def); + } + } + } +} diff --git a/pool/shard001/C++/0017123_GrProcessor.cpp b/pool/shard001/C++/0017123_GrProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29482ccc63f90a154cd5bc5bc025c34721e82e22 --- /dev/null +++ b/pool/shard001/C++/0017123_GrProcessor.cpp @@ -0,0 +1,143 @@ +/* + * Copyright 2012 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "GrProcessor.h" +#include "GrContext.h" +#include "GrGeometryProcessor.h" +#include "GrInvariantOutput.h" +#include "GrMemoryPool.h" +#include "GrXferProcessor.h" +#include "SkSpinlock.h" + +#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS + +class GrFragmentProcessor; +class GrGeometryProcessor; + +/* + * Originally these were both in the processor unit test header, but then it seemed to cause linker + * problems on android. + */ +template<> +SkTArray*, true>* +GrProcessorTestFactory::GetFactories() { + static SkTArray*, true> gFactories; + return &gFactories; +} + +template<> +SkTArray*, true>* +GrProcessorTestFactory::GetFactories() { + static SkTArray*, true> gFactories; + return &gFactories; +} + +template<> +SkTArray*, true>* +GrProcessorTestFactory::GetFactories() { + static SkTArray*, true> gFactories; + return &gFactories; +} + +/* + * To ensure we always have successful static initialization, before creating from the factories + * we verify the count is as expected. If a new factory is added, then these numbers must be + * manually adjusted. + */ +static const int kFPFactoryCount = 40; +static const int kGPFactoryCount = 14; +static const int kXPFactoryCount = 6; + +template<> +void GrProcessorTestFactory::VerifyFactoryCount() { + if (kFPFactoryCount != GetFactories()->count()) { + SkFAIL("Wrong number of fragment processor factories!"); + } +} + +template<> +void GrProcessorTestFactory::VerifyFactoryCount() { + if (kGPFactoryCount != GetFactories()->count()) { + SkFAIL("Wrong number of geometry processor factories!"); + } +} + +template<> +void GrProcessorTestFactory::VerifyFactoryCount() { + if (kXPFactoryCount != GetFactories()->count()) { + SkFAIL("Wrong number of xp factory factories!"); + } +} + +#endif + + +// We use a global pool protected by a mutex(spinlock). Chrome may use the same GrContext on +// different threads. The GrContext is not used concurrently on different threads and there is a +// memory barrier between accesses of a context on different threads. Also, there may be multiple +// GrContexts and those contexts may be in use concurrently on different threads. +namespace { +static SkSpinlock gProcessorSpinlock; +class MemoryPoolAccessor { +public: + MemoryPoolAccessor() { gProcessorSpinlock.acquire(); } + + ~MemoryPoolAccessor() { gProcessorSpinlock.release(); } + + GrMemoryPool* pool() const { + static GrMemoryPool gPool(4096, 4096); + return &gPool; + } +}; +} + +int32_t GrProcessor::gCurrProcessorClassID = GrProcessor::kIllegalProcessorClassID; + +/////////////////////////////////////////////////////////////////////////////// + +GrProcessor::~GrProcessor() {} + +void GrProcessor::addTextureAccess(const GrTextureAccess* access) { + fTextureAccesses.push_back(access); + this->addGpuResource(access->getProgramTexture()); +} + +void GrProcessor::addBufferAccess(const GrBufferAccess* access) { + fBufferAccesses.push_back(access); + this->addGpuResource(access->getProgramBuffer()); +} + +void* GrProcessor::operator new(size_t size) { + return MemoryPoolAccessor().pool()->allocate(size); +} + +void GrProcessor::operator delete(void* target) { + return MemoryPoolAccessor().pool()->release(target); +} + +bool GrProcessor::hasSameSamplers(const GrProcessor& that) const { + if (this->numTextures() != that.numTextures() || this->numBuffers() != that.numBuffers()) { + return false; + } + for (int i = 0; i < this->numTextures(); ++i) { + if (this->textureAccess(i) != that.textureAccess(i)) { + return false; + } + } + for (int i = 0; i < this->numBuffers(); ++i) { + if (this->bufferAccess(i) != that.bufferAccess(i)) { + return false; + } + } + return true; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// Initial static variable from GrXPFactory +int32_t GrXPFactory::gCurrXPFClassID = + GrXPFactory::kIllegalXPFClassID; diff --git a/pool/shard001/C++/0017143_binarycontourimagefilter.cpp b/pool/shard001/C++/0017143_binarycontourimagefilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3be051bc28be96c12176d0fb3e131a9a38291341 --- /dev/null +++ b/pool/shard001/C++/0017143_binarycontourimagefilter.cpp @@ -0,0 +1,168 @@ +/*********************************************************************************** + * * + * Voreen - The Volume Rendering Engine * + * * + * Copyright (C) 2005-2013 University of Muenster, Germany. * + * Visualization and Computer Graphics Group * + * For a list of authors please refer to the file "CREDITS.txt". * + * * + * This file is part of the Voreen software package. Voreen 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. * + * * + * Voreen 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 in the file * + * "LICENSE.txt" along with this file. If not, see . * + * * + * For non-commercial academic use see the license exception specified in the file * + * "LICENSE-academic.txt". To get information about commercial licensing please * + * contact the authors. * + * * + ***********************************************************************************/ + +#include "binarycontourimagefilter.h" +#include "voreen/core/datastructures/volume/volumeram.h" +#include "voreen/core/datastructures/volume/volume.h" +#include "voreen/core/datastructures/volume/volumeatomic.h" +#include "voreen/core/ports/conditions/portconditionvolumetype.h" +#include "modules/itk/utils/itkwrapper.h" +#include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h" +#include "itkImage.h" + +#include "itkBinaryContourImageFilter.h" + +#include + +namespace voreen { + +const std::string BinaryContourImageFilterITK::loggerCat_("voreen.BinaryContourImageFilterITK"); + +BinaryContourImageFilterITK::BinaryContourImageFilterITK() + : ITKProcessor(), + inport1_(Port::INPORT, "InputImage"), + outport1_(Port::OUTPORT, "OutputImage"), + enableProcessing_("enabled", "Enable", false), + fullyConnected_("fullyConnected", "FullyConnected", false), + backgroundValue_("backgroundValue", "BackgroundValue"), + foregroundValue_("foregroundValue", "ForegroundValue") +{ + addPort(inport1_); + PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr(); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat()); + orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble()); + inport1_.addCondition(orCondition1); + addPort(outport1_); + + addProperty(enableProcessing_); + addProperty(fullyConnected_); + addProperty(backgroundValue_); + addProperty(foregroundValue_); + +} + +Processor* BinaryContourImageFilterITK::create() const { + return new BinaryContourImageFilterITK(); +} + +template +void BinaryContourImageFilterITK::binaryContourImageFilterITK() { + backgroundValue_.setVolume(inport1_.getData()); + foregroundValue_.setVolume(inport1_.getData()); + + if (!enableProcessing_.get()) { + outport1_.setData(inport1_.getData(), false); + return; + } + + typedef itk::Image InputImageType1; + typedef itk::Image OutputImageType1; + + typename InputImageType1::Pointer p1 = voreenToITK(inport1_.getData()); + + + //Filter define + typedef itk::BinaryContourImageFilter FilterType; + typename FilterType::Pointer filter = FilterType::New(); + + filter->SetInput(p1); + + filter->SetFullyConnected(fullyConnected_.get()); + filter->SetBackgroundValue(backgroundValue_.getValue()); + filter->SetForegroundValue(foregroundValue_.getValue()); + + + observe(filter.GetPointer()); + + try + { + filter->Update(); + + } + catch (itk::ExceptionObject &e) + { + LERROR(e); + } + + + Volume* outputVolume1 = 0; + outputVolume1 = ITKToVoreenCopy(filter->GetOutput()); + + if (outputVolume1) { + transferRWM(inport1_.getData(), outputVolume1); + transferTransformation(inport1_.getData(), outputVolume1); + outport1_.setData(outputVolume1); + } else + outport1_.setData(0); + + + +} + + + + +void BinaryContourImageFilterITK::process() { + const VolumeBase* inputHandle1 = inport1_.getData(); + const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation(); + + if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else if (dynamic_cast(inputVolume1)) { + binaryContourImageFilterITK(); + } + else { + LERROR("Inputformat of Volume 1 is not supported!"); + } + +} + + +} // namespace diff --git a/pool/shard001/C++/0017150_pow_valarray_value.pass.cpp b/pool/shard001/C++/0017150_pow_valarray_value.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..145ce85ecb4dd007fe93f23fa494b76376ef4f94 --- /dev/null +++ b/pool/shard001/C++/0017150_pow_valarray_value.pass.cpp @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// + +// template class valarray; + +// template +// valarray +// pow(const valarray& x, const T& y); + +#include +#include +#include +#include + +#include "test_macros.h" + +bool is_about(double x, double y, int p) +{ + std::ostringstream o; + o.precision(p); + scientific(o); + o << x; + std::string a = o.str(); + o.str(""); + o << y; + return a == o.str(); +} + +int main(int, char**) +{ + { + typedef double T; + T a1[] = {.9, .5, 0., .5, .75}; + T a3[] = {8.1000000000000005e-01, + 2.5000000000000000e-01, + 0.0000000000000000e+00, + 2.5000000000000000e-01, + 5.6250000000000000e-01}; + const unsigned N = sizeof(a1)/sizeof(a1[0]); + std::valarray v1(a1, N); + std::valarray v3 = pow(v1, 2.0); + assert(v3.size() == v1.size()); + for (std::size_t i = 0; i < v3.size(); ++i) + assert(is_about(v3[i], a3[i], 10)); + } + + return 0; +} diff --git a/pool/shard001/C++/0017153_optimized_test.cpp b/pool/shard001/C++/0017153_optimized_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fcb8c5b393a23f33e20009f67d90782b5a21be5 --- /dev/null +++ b/pool/shard001/C++/0017153_optimized_test.cpp @@ -0,0 +1,82 @@ +// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. + +#include +#include + +using namespace vespalib; + +class Test : public vespalib::TestApp +{ +private: + template + void testMsbIdx(); + template + void testLsbIdx(); + template + void testPopCount(); +public: + int Main() override; +}; + +template +void Test::testMsbIdx() +{ + EXPECT_EQUAL(Optimized::msbIdx(T(0)), 0); + EXPECT_EQUAL(Optimized::msbIdx(T(1)), 0); + EXPECT_EQUAL(Optimized::msbIdx(T(-1)), int(sizeof(T)*8 - 1)); + T v(static_cast(-1)); + for (size_t i(0); i < sizeof(T); i++) { + for (size_t j(0); j < 8; j++) { + EXPECT_EQUAL(Optimized::msbIdx(v), int(sizeof(T)*8 - (i*8+j) - 1)); + v = v >> 1; + } + } +} + +template +void Test::testLsbIdx() +{ + EXPECT_EQUAL(Optimized::lsbIdx(T(0)), 0); + EXPECT_EQUAL(Optimized::lsbIdx(T(1)), 0); + EXPECT_EQUAL(Optimized::lsbIdx(T(T(1)<<(sizeof(T)*8 - 1))), int(sizeof(T)*8 - 1)); + EXPECT_EQUAL(Optimized::lsbIdx(T(-1)), 0); + T v(static_cast(-1)); + for (size_t i(0); i < sizeof(T); i++) { + for (size_t j(0); j < 8; j++) { + EXPECT_EQUAL(Optimized::lsbIdx(v), int(i*8+j)); + v = v << 1; + } + } +} + +template +void Test::testPopCount() +{ + EXPECT_EQUAL(0, Optimized::popCount(T(0))); + EXPECT_EQUAL(1, Optimized::popCount(T(1))); + EXPECT_EQUAL(int(8 * sizeof(T)), Optimized::popCount(T(-1))); +} + +int Test::Main() +{ + TEST_INIT("optimized_test"); + + testMsbIdx(); + testMsbIdx(); + testMsbIdx(); + + TEST_FLUSH(); + testLsbIdx(); + testLsbIdx(); + testLsbIdx(); + + TEST_FLUSH(); + testPopCount(); + testPopCount(); + testPopCount(); + + TEST_FLUSH(); + TEST_DONE(); +} + +TEST_APPHOOK(Test) diff --git a/pool/shard001/C++/0017155_ir_function_detect_recursion.cpp b/pool/shard001/C++/0017155_ir_function_detect_recursion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b39f9724e70a1432f15945920e1110d6c3f2ce0 --- /dev/null +++ b/pool/shard001/C++/0017155_ir_function_detect_recursion.cpp @@ -0,0 +1,375 @@ +/* + * Copyright © 2011 Intel Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * 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. + */ + +/** + * \file ir_function_detect_recursion.cpp + * Determine whether a shader contains static recursion. + * + * Consider the (possibly disjoint) graph of function calls in a shader. If a + * program contains recursion, this graph will contain a cycle. If a function + * is part of a cycle, it will have a caller and it will have a callee (it + * calls another function). + * + * To detect recursion, the function call graph is constructed. The graph is + * repeatedly reduced by removing any function that either has no callees + * (leaf functions) or has no caller. Eventually the only functions that + * remain will be the functions in the cycles. + * + * The GLSL spec is a bit wishy-washy about recursion. + * + * From page 39 (page 45 of the PDF) of the GLSL 1.10 spec: + * + * "Behavior is undefined if recursion is used. Recursion means having any + * function appearing more than once at any one time in the run-time stack + * of function calls. That is, a function may not call itself either + * directly or indirectly. Compilers may give diagnostic messages when + * this is detectable at compile time, but not all such cases can be + * detected at compile time." + * + * From page 79 (page 85 of the PDF): + * + * "22) Should recursion be supported? + * + * DISCUSSION: Probably not necessary, but another example of limiting + * the language based on how it would directly map to hardware. One + * thought is that recursion would benefit ray tracing shaders. On the + * other hand, many recursion operations can also be implemented with the + * user managing the recursion through arrays. RenderMan doesn't support + * recursion. This could be added at a later date, if it proved to be + * necessary. + * + * RESOLVED on September 10, 2002: Implementations are not required to + * support recursion. + * + * CLOSED on September 10, 2002." + * + * From page 79 (page 85 of the PDF): + * + * "56) Is it an error for an implementation to support recursion if the + * specification says recursion is not supported? + * + * ADDED on September 10, 2002. + * + * DISCUSSION: This issues is related to Issue (22). If we say that + * recursion (or some other piece of functionality) is not supported, is + * it an error for an implementation to support it? Perhaps the + * specification should remain silent on these kind of things so that they + * could be gracefully added later as an extension or as part of the + * standard. + * + * RESOLUTION: Languages, in general, have programs that are not + * well-formed in ways a compiler cannot detect. Portability is only + * ensured for well-formed programs. Detecting recursion is an example of + * this. The language will say a well-formed program may not recurse, but + * compilers are not forced to detect that recursion may happen. + * + * CLOSED: November 29, 2002." + * + * In GLSL 1.10 the behavior of recursion is undefined. Compilers don't have + * to reject shaders (at compile-time or link-time) that contain recursion. + * Instead they could work, or crash, or kill a kitten. + * + * From page 44 (page 50 of the PDF) of the GLSL 1.20 spec: + * + * "Recursion is not allowed, not even statically. Static recursion is + * present if the static function call graph of the program contains + * cycles." + * + * This langauge clears things up a bit, but it still leaves a lot of + * questions unanswered. + * + * - Is the error generated at compile-time or link-time? + * + * - Is it an error to have a recursive function that is never statically + * called by main or any function called directly or indirectly by main? + * Technically speaking, such a function is not in the "static function + * call graph of the program" at all. + * + * \bug + * If a shader has multiple cycles, this algorithm may erroneously complain + * about functions that aren't in any cycle, but are in the part of the call + * tree that connects them. For example, if the call graph consists of a + * cycle between A and B, and a cycle between D and E, and B also calls C + * which calls D, then this algorithm will report C as a function which "has + * static recursion" even though it is not part of any cycle. + * + * A better algorithm for cycle detection that doesn't have this drawback can + * be found here: + * + * http://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm + * + * \author Ian Romanick + */ +#include "main/core.h" +#include "ir.h" +#include "glsl_parser_extras.h" +#include "linker.h" +#include "program/hash_table.h" +#include "program.h" + +struct call_node : public exec_node { + class function *func; +}; + +class function { +public: + function(ir_function_signature *sig) + : sig(sig) + { + /* empty */ + } + + + /* Callers of this ralloc-based new need not call delete. It's + * easier to just ralloc_free 'ctx' (or any of its ancestors). */ + static void* operator new(size_t size, void *ctx) + { + void *node; + + node = ralloc_size(ctx, size); + assert(node != NULL); + + return node; + } + + /* If the user *does* call delete, that's OK, we will just + * ralloc_free in that case. */ + static void operator delete(void *node) + { + ralloc_free(node); + } + + ir_function_signature *sig; + + /** List of functions called by this function. */ + exec_list callees; + + /** List of functions that call this function. */ + exec_list callers; +}; + +class has_recursion_visitor : public ir_hierarchical_visitor { +public: + has_recursion_visitor() + : current(NULL) + { + progress = false; + this->mem_ctx = ralloc_context(NULL); + this->function_hash = hash_table_ctor(0, hash_table_pointer_hash, + hash_table_pointer_compare); + } + + ~has_recursion_visitor() + { + hash_table_dtor(this->function_hash); + ralloc_free(this->mem_ctx); + } + + function *get_function(ir_function_signature *sig) + { + function *f = (function *) hash_table_find(this->function_hash, sig); + if (f == NULL) { + f = new(mem_ctx) function(sig); + hash_table_insert(this->function_hash, f, sig); + } + + return f; + } + + virtual ir_visitor_status visit_enter(ir_function_signature *sig) + { + this->current = this->get_function(sig); + return visit_continue; + } + + virtual ir_visitor_status visit_leave(ir_function_signature *sig) + { + (void) sig; + this->current = NULL; + return visit_continue; + } + + virtual ir_visitor_status visit_enter(ir_call *call) + { + /* At global scope this->current will be NULL. Since there is no way to + * call global scope, it can never be part of a cycle. Don't bother + * adding calls from global scope to the graph. + */ + if (this->current == NULL) + return visit_continue; + + function *const target = this->get_function(call->callee); + + /* Create a link from the caller to the callee. + */ + call_node *node = new(mem_ctx) call_node; + node->func = target; + this->current->callees.push_tail(node); + + /* Create a link from the callee to the caller. + */ + node = new(mem_ctx) call_node; + node->func = this->current; + target->callers.push_tail(node); + return visit_continue; + } + + function *current; + struct hash_table *function_hash; + void *mem_ctx; + bool progress; +}; + +static void +destroy_links(exec_list *list, function *f) +{ + foreach_list_safe(node, list) { + struct call_node *n = (struct call_node *) node; + + /* If this is the right function, remove it. Note that the loop cannot + * terminate now. There can be multiple links to a function if it is + * either called multiple times or calls multiple times. + */ + if (n->func == f) + n->remove(); + } +} + + +/** + * Remove a function if it has either no in or no out links + */ +static void +remove_unlinked_functions(const void *key, void *data, void *closure) +{ + has_recursion_visitor *visitor = (has_recursion_visitor *) closure; + function *f = (function *) data; + + if (f->callers.is_empty() || f->callees.is_empty()) { + while (!f->callers.is_empty()) { + struct call_node *n = (struct call_node *) f->callers.pop_head(); + destroy_links(& n->func->callees, f); + } + + while (!f->callees.is_empty()) { + struct call_node *n = (struct call_node *) f->callees.pop_head(); + destroy_links(& n->func->callers, f); + } + + hash_table_remove(visitor->function_hash, key); + visitor->progress = true; + } +} + + +static void +emit_errors_unlinked(const void *key, void *data, void *closure) +{ + struct _mesa_glsl_parse_state *state = + (struct _mesa_glsl_parse_state *) closure; + function *f = (function *) data; + YYLTYPE loc; + + (void) key; + + char *proto = prototype_string(f->sig->return_type, + f->sig->function_name(), + &f->sig->parameters); + + memset(&loc, 0, sizeof(loc)); + _mesa_glsl_error(&loc, state, + "function `%s' has static recursion.", + proto); + ralloc_free(proto); +} + + +static void +emit_errors_linked(const void *key, void *data, void *closure) +{ + struct gl_shader_program *prog = + (struct gl_shader_program *) closure; + function *f = (function *) data; + + (void) key; + + char *proto = prototype_string(f->sig->return_type, + f->sig->function_name(), + &f->sig->parameters); + + linker_error(prog, "function `%s' has static recursion.\n", proto); + ralloc_free(proto); + prog->LinkStatus = false; +} + + +void +detect_recursion_unlinked(struct _mesa_glsl_parse_state *state, + exec_list *instructions) +{ + has_recursion_visitor v; + + /* Collect all of the information about which functions call which other + * functions. + */ + v.run(instructions); + + /* Remove from the set all of the functions that either have no caller or + * call no other functions. Repeat until no functions are removed. + */ + do { + v.progress = false; + hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v); + } while (v.progress); + + + /* At this point any functions still in the hash must be part of a cycle. + */ + hash_table_call_foreach(v.function_hash, emit_errors_unlinked, state); +} + + +void +detect_recursion_linked(struct gl_shader_program *prog, + exec_list *instructions) +{ + has_recursion_visitor v; + + /* Collect all of the information about which functions call which other + * functions. + */ + v.run(instructions); + + /* Remove from the set all of the functions that either have no caller or + * call no other functions. Repeat until no functions are removed. + */ + do { + v.progress = false; + hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v); + } while (v.progress); + + + /* At this point any functions still in the hash must be part of a cycle. + */ + hash_table_call_foreach(v.function_hash, emit_errors_linked, prog); +} diff --git a/pool/shard001/C++/0017157_print_string.cpp b/pool/shard001/C++/0017157_print_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6154f1cf6be7644b98232c7bbd4d6386f05db75 --- /dev/null +++ b/pool/shard001/C++/0017157_print_string.cpp @@ -0,0 +1,91 @@ +/*************************************************************************/ +/* print_string.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ +/* */ +/* 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 "print_string.h" +#include "os/os.h" +#include + +static PrintHandlerList *print_handler_list=NULL; +bool _print_line_enabled=true; +bool _print_error_enabled = true; + +void add_print_handler(PrintHandlerList *p_handler) { + + _global_lock(); + p_handler->next=print_handler_list; + print_handler_list=p_handler; + _global_unlock(); +} + +void remove_print_handler(PrintHandlerList *p_handler) { + + _global_lock(); + + PrintHandlerList *prev = NULL; + PrintHandlerList *l = print_handler_list; + + while(l) { + + if (l==p_handler) { + + if (prev) + prev->next=l->next; + else + print_handler_list=l->next; + break; + } + prev=l; + l=l->next; + + } + //OS::get_singleton()->print("print handler list is %p\n",print_handler_list); + + ERR_FAIL_COND(l==NULL); + _global_unlock(); + +} + + +void print_line(String p_string) { + + if (!_print_line_enabled) + return; + + OS::get_singleton()->print("%s\n",p_string.utf8().get_data()); + + _global_lock(); + PrintHandlerList *l = print_handler_list; + while(l) { + + l->printfunc(l->userdata,p_string); + l=l->next; + } + + _global_unlock(); + +} diff --git a/pool/shard001/C++/0017164_quic_sent_packet_manager_peer.cc b/pool/shard001/C++/0017164_quic_sent_packet_manager_peer.cc new file mode 100644 index 0000000000000000000000000000000000000000..a5f63fcbdd087f23ff1715d5202fa7f8b559c5fe --- /dev/null +++ b/pool/shard001/C++/0017164_quic_sent_packet_manager_peer.cc @@ -0,0 +1,180 @@ +// 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 "net/quic/test_tools/quic_sent_packet_manager_peer.h" + +#include "base/stl_util.h" +#include "net/quic/congestion_control/loss_detection_interface.h" +#include "net/quic/congestion_control/send_algorithm_interface.h" +#include "net/quic/quic_flags.h" +#include "net/quic/quic_protocol.h" +#include "net/quic/quic_sent_packet_manager.h" + +namespace net { +namespace test { + +// static +size_t QuicSentPacketManagerPeer::GetMaxTailLossProbes( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->max_tail_loss_probes_; +} + +// static +void QuicSentPacketManagerPeer::SetMaxTailLossProbes( + QuicSentPacketManager* sent_packet_manager, + size_t max_tail_loss_probes) { + sent_packet_manager->max_tail_loss_probes_ = max_tail_loss_probes; +} + +// static +bool QuicSentPacketManagerPeer::GetEnableHalfRttTailLossProbe( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->enable_half_rtt_tail_loss_probe_; +} + +// static +bool QuicSentPacketManagerPeer::GetUseNewRto( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->use_new_rto_; +} + +// static +QuicByteCount QuicSentPacketManagerPeer::GetReceiveWindow( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->receive_buffer_bytes_; +} + +// static +void QuicSentPacketManagerPeer::SetPerspective( + QuicSentPacketManager* sent_packet_manager, + Perspective perspective) { + sent_packet_manager->perspective_ = perspective; +} + +// static +const SendAlgorithmInterface* QuicSentPacketManagerPeer::GetSendAlgorithm( + const QuicSentPacketManager& sent_packet_manager) { + return sent_packet_manager.send_algorithm_.get(); +} + +// static +void QuicSentPacketManagerPeer::SetSendAlgorithm( + QuicSentPacketManager* sent_packet_manager, + SendAlgorithmInterface* send_algorithm) { + sent_packet_manager->send_algorithm_.reset(send_algorithm); +} + +// static +const LossDetectionInterface* QuicSentPacketManagerPeer::GetLossAlgorithm( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->loss_algorithm_.get(); +} + +// static +void QuicSentPacketManagerPeer::SetLossAlgorithm( + QuicSentPacketManager* sent_packet_manager, + LossDetectionInterface* loss_detector) { + sent_packet_manager->loss_algorithm_.reset(loss_detector); +} + +// static +RttStats* QuicSentPacketManagerPeer::GetRttStats( + QuicSentPacketManager* sent_packet_manager) { + return &sent_packet_manager->rtt_stats_; +} + +// static +bool QuicSentPacketManagerPeer::HasPendingPackets( + const QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->unacked_packets_.HasInFlightPackets(); +} + +// static +QuicTime QuicSentPacketManagerPeer::GetSentTime( + const QuicSentPacketManager* sent_packet_manager, + QuicPacketNumber packet_number) { + DCHECK(sent_packet_manager->unacked_packets_.IsUnacked(packet_number)); + + return sent_packet_manager->unacked_packets_.GetTransmissionInfo( + packet_number) + .sent_time; +} + +// static +bool QuicSentPacketManagerPeer::IsRetransmission( + QuicSentPacketManager* sent_packet_manager, + QuicPacketNumber packet_number) { + DCHECK(sent_packet_manager->HasRetransmittableFrames(packet_number)); + if (FLAGS_quic_track_single_retransmission) { + if (!sent_packet_manager->HasRetransmittableFrames(packet_number)) { + return false; + } + for (auto transmission_info : sent_packet_manager->unacked_packets_) { + if (transmission_info.retransmission == packet_number) { + return true; + } + } + return false; + } + return sent_packet_manager->HasRetransmittableFrames(packet_number) && + sent_packet_manager->unacked_packets_.GetTransmissionInfo( + packet_number) + .all_transmissions != nullptr; +} + +// static +void QuicSentPacketManagerPeer::MarkForRetransmission( + QuicSentPacketManager* sent_packet_manager, + QuicPacketNumber packet_number, + TransmissionType transmission_type) { + sent_packet_manager->MarkForRetransmission(packet_number, transmission_type); +} + +// static +QuicTime::Delta QuicSentPacketManagerPeer::GetRetransmissionDelay( + const QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->GetRetransmissionDelay(); +} + +// static +bool QuicSentPacketManagerPeer::HasUnackedCryptoPackets( + const QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->unacked_packets_.HasPendingCryptoPackets(); +} + +// static +size_t QuicSentPacketManagerPeer::GetNumRetransmittablePackets( + const QuicSentPacketManager* sent_packet_manager) { + size_t num_unacked_packets = 0; + for (QuicUnackedPacketMap::const_iterator it = + sent_packet_manager->unacked_packets_.begin(); + it != sent_packet_manager->unacked_packets_.end(); ++it) { + if (it->retransmittable_frames != nullptr) { + ++num_unacked_packets; + } + } + return num_unacked_packets; +} + +// static +QuicByteCount QuicSentPacketManagerPeer::GetBytesInFlight( + const QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->unacked_packets_.bytes_in_flight(); +} + +// static +QuicSentPacketManager::NetworkChangeVisitor* +QuicSentPacketManagerPeer::GetNetworkChangeVisitor( + const QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->network_change_visitor_; +} + +// static +QuicSustainedBandwidthRecorder& QuicSentPacketManagerPeer::GetBandwidthRecorder( + QuicSentPacketManager* sent_packet_manager) { + return sent_packet_manager->sustained_bandwidth_recorder_; +} + +} // namespace test +} // namespace net diff --git a/pool/shard001/C++/0017166_profile_window.cc b/pool/shard001/C++/0017166_profile_window.cc new file mode 100644 index 0000000000000000000000000000000000000000..9cdcf4de0ff84aae50f075e76c98aa4858dc600b --- /dev/null +++ b/pool/shard001/C++/0017166_profile_window.cc @@ -0,0 +1,191 @@ +// 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/profiles/profile_window.h" + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_dialogs.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/user_metrics.h" + +#if !defined(OS_IOS) +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/ui/browser_list_observer.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/startup/startup_browser_creator.h" +#endif // !defined (OS_IOS) + +using content::BrowserThread; +using content::UserMetricsAction; + +namespace { + +// Handles running a callback when a new Browser has been completely created. +class BrowserAddedObserver : public chrome::BrowserListObserver { + public: + explicit BrowserAddedObserver( + profiles::ProfileSwitchingDoneCallback callback) : callback_(callback) { + BrowserList::AddObserver(this); + } + virtual ~BrowserAddedObserver() { + BrowserList::RemoveObserver(this); + } + + private: + // Overridden from BrowserListObserver: + virtual void OnBrowserAdded(Browser* browser) OVERRIDE { + DCHECK(!callback_.is_null()); + callback_.Run(); + } + + profiles::ProfileSwitchingDoneCallback callback_; + + DISALLOW_COPY_AND_ASSIGN(BrowserAddedObserver); +}; + +void OpenBrowserWindowForProfile( + profiles::ProfileSwitchingDoneCallback callback, + bool always_create, + bool is_new_profile, + chrome::HostDesktopType desktop_type, + Profile* profile, + Profile::CreateStatus status) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + + if (status != Profile::CREATE_STATUS_INITIALIZED) + return; + + chrome::startup::IsProcessStartup is_process_startup = + chrome::startup::IS_NOT_PROCESS_STARTUP; + chrome::startup::IsFirstRun is_first_run = chrome::startup::IS_NOT_FIRST_RUN; + + // If this is a brand new profile, then start a first run window. + if (is_new_profile) { + is_process_startup = chrome::startup::IS_PROCESS_STARTUP; + is_first_run = chrome::startup::IS_FIRST_RUN; + } + + // If we are not showing any browsers windows (we could be showing the + // desktop User Manager, for example), then this is a process startup browser. + if (BrowserList::GetInstance(desktop_type)->size() == 0) + is_process_startup = chrome::startup::IS_PROCESS_STARTUP; + + // If there is a callback, create an observer to make sure it is only + // run when the browser has been completely created. + scoped_ptr browser_added_observer; + if (!callback.is_null()) + browser_added_observer.reset(new BrowserAddedObserver(callback)); + + profiles::FindOrCreateNewWindowForProfile( + profile, + is_process_startup, + is_first_run, + desktop_type, + always_create); +} + +} // namespace + +namespace profiles { + +void FindOrCreateNewWindowForProfile( + Profile* profile, + chrome::startup::IsProcessStartup process_startup, + chrome::startup::IsFirstRun is_first_run, + chrome::HostDesktopType desktop_type, + bool always_create) { +#if defined(OS_IOS) + NOTREACHED(); +#else + DCHECK(profile); + + if (!always_create) { + Browser* browser = chrome::FindTabbedBrowser(profile, false, desktop_type); + if (browser) { + browser->window()->Activate(); + return; + } + } + + content::RecordAction(UserMetricsAction("NewWindow")); + CommandLine command_line(CommandLine::NO_PROGRAM); + int return_code; + StartupBrowserCreator browser_creator; + browser_creator.LaunchBrowser(command_line, profile, base::FilePath(), + process_startup, is_first_run, &return_code); +#endif // defined(OS_IOS) +} + +void SwitchToProfile( + const base::FilePath& path, + chrome::HostDesktopType desktop_type, + bool always_create, + ProfileSwitchingDoneCallback callback) { + g_browser_process->profile_manager()->CreateProfileAsync( + path, + base::Bind(&OpenBrowserWindowForProfile, + callback, + always_create, + false, + desktop_type), + base::string16(), + base::string16(), + std::string()); +} + +void SwitchToGuestProfile(chrome::HostDesktopType desktop_type, + ProfileSwitchingDoneCallback callback) { + g_browser_process->profile_manager()->CreateProfileAsync( + ProfileManager::GetGuestProfilePath(), + base::Bind(&OpenBrowserWindowForProfile, + callback, + false, + false, + desktop_type), + base::string16(), + base::string16(), + std::string()); +} + +void CreateAndSwitchToNewProfile(chrome::HostDesktopType desktop_type, + ProfileSwitchingDoneCallback callback) { + ProfileManager::CreateMultiProfileAsync( + base::string16(), + base::string16(), + base::Bind(&OpenBrowserWindowForProfile, + callback, + true, + true, + desktop_type), + std::string()); +} + +void CloseGuestProfileWindows() { + ProfileManager* profile_manager = g_browser_process->profile_manager(); + Profile* profile = profile_manager->GetProfileByPath( + ProfileManager::GetGuestProfilePath()); + + if (profile) { + BrowserList::CloseAllBrowsersWithProfile(profile); + } +} + +void LockProfile(Profile* profile) { + DCHECK(profile); + ProfileInfoCache& cache = + g_browser_process->profile_manager()->GetProfileInfoCache(); + + size_t index = cache.GetIndexOfProfileWithPath(profile->GetPath()); + cache.SetProfileSigninRequiredAtIndex(index, true); + chrome::ShowUserManager(profile->GetPath()); + BrowserList::CloseAllBrowsersWithProfile(profile); +} + +} // namespace profiles diff --git a/pool/shard001/C++/0017170_S3_wrap.cpp b/pool/shard001/C++/0017170_S3_wrap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de5a894bd8e5b885e3c730dd7817e52fda84edd8 --- /dev/null +++ b/pool/shard001/C++/0017170_S3_wrap.cpp @@ -0,0 +1,42 @@ +#include "S3_wrap.h" +#include "S3.h" + +#ifdef __cplusplus + extern "C" { +#endif + + void init_pd_client(struct PDClient * client, char* name_bucket) { + S3 s3; + client->s3 = (void *)(&s3); + client->name_bucket = name_bucket; + } + + void get(struct PDClient *client, char *output) { + std::string str_output = ((S3*)(client->s3))->getObjects(client->name_bucket); + output = const_cast(str_output.c_str()); + + } + void put(struct PDClient *client, const char* directory_to_upload_char) { + std::string directory_to_upload(directory_to_upload_char); + std::vector storage; + Helper::getFilesInDirectory(storage, directory_to_upload); + for (auto string_to_upload: storage) { + ((S3*)(client->s3))->putObject(string_to_upload, (*client).name_bucket); + } + + } + + void hello_world() { + std::cout << "hello world\n"; + } + + void hello(const char *example_text) { + std::string tex(example_text); + std::cout << "Hello "< +* Program URL : http://biord-software.org/qdevelop/ +* +*/ +#include +#include "shortcutsimpl.h" +#include "ui_main.h" +#include "mainimpl.h" +#include "misc.h" + +// +ShortcutsImpl::ShortcutsImpl(QWidget * parent) + : QDialog(parent), m_mainImpl((MainImpl *)parent) +{ + setupUi(this); + initTable( m_mainImpl ); + connect(okButton, SIGNAL(clicked()), this, SLOT(slotAccept()) ); + connect(defaultButton, SIGNAL(clicked()), this, SLOT(slotDefault()) ); +} + +// +void ShortcutsImpl::initTable(MainImpl *main) +{ + QList childrens = main->children(); + QListIterator iterator(childrens); + int row = 0; + + while( iterator.hasNext() ) + { + QObject *object = iterator.next(); + QAction *action = qobject_cast(object); + + if (action) + { + QString text = action->text().remove("&"); + + if ( !text.isEmpty() && !(action->data().toString().contains("Recent|")) ) + { + QString shortcut = action->shortcut(); + QTableWidgetItem *newItem = new QTableWidgetItem(text); + + newItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); + newItem->setData(Qt::UserRole, addressToVariant(object)); + newItem->setIcon(action->icon()); + table->setRowCount(row+1); + table->setItem(row, 0, newItem); + table->setItem(row++, 1, new QTableWidgetItem(shortcut)); + } + } + table->sortItems( 0 ); + } + + QHeaderView *header = table->horizontalHeader(); + header->resizeSection( 0, 230 ); + table->verticalHeader()->hide(); +} + +// +void ShortcutsImpl::slotAccept() +{ + for(int row=0; rowrowCount(); row++ ) + { + QTableWidgetItem *item = table->item(row, 0); + QAction *action = (QAction *)variantToAction( item->data(Qt::UserRole) ); + QString shortcut = table->item(row, 1)->text(); + action->setShortcut( shortcut ); + } +} + +// +void ShortcutsImpl::slotDefault() +{ + QMainWindow *dial = new QMainWindow; + Ui::Main ui; + ui.setupUi(dial); + + QList childrens = dial->children(); + QListIterator iterator(childrens); + + while( iterator.hasNext() ) + { + QObject *object = iterator.next(); + QAction *action = qobject_cast(object); + + if (action) + { + QString text = action->text().remove("&"); + QString shortcut = action->shortcut(); + QList listFind = table->findItems(text , Qt::MatchExactly); + if( listFind.count() ) + table->item(table->row(listFind.first()), 1)->setText(shortcut); + } + } + + delete dial; +} diff --git a/pool/shard001/C++/0017189_render_view_context_menu_unittest.cc b/pool/shard001/C++/0017189_render_view_context_menu_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ad057de1cd093c52c9d4434bad429fd6fe2855b --- /dev/null +++ b/pool/shard001/C++/0017189_render_view_context_menu_unittest.cc @@ -0,0 +1,239 @@ +// 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 + +#include "chrome/browser/tab_contents/render_view_context_menu.h" + +#include "chrome/browser/extensions/extension_prefs.h" +#include "chrome/common/extensions/url_pattern.h" +#include "googleurl/src/gurl.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "webkit/glue/context_menu.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" + +class RenderViewContextMenuTest : public testing::Test { + public: + RenderViewContextMenuTest() { } + + protected: + // Proxy defined here to minimize friend classes in RenderViewContextMenu + static bool ExtensionContextAndPatternMatch( + const ContextMenuParams& params, + ExtensionMenuItem::ContextList contexts, + const URLPatternSet& patterns) { + return RenderViewContextMenu::ExtensionContextAndPatternMatch(params, + contexts, patterns); + } + + private: + DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuTest); +}; + +// Generates a ContextMenuParams that matches the specified contexts. +static ContextMenuParams CreateParams(int contexts) { + ContextMenuParams rv; + rv.is_editable = false; + rv.media_type = WebKit::WebContextMenuData::MediaTypeNone; + rv.page_url = GURL("http://test.page/"); + + static const char16 selected_text[] = { 's', 'e', 'l', 0 }; + if (contexts & ExtensionMenuItem::SELECTION) + rv.selection_text = selected_text; + + if (contexts & ExtensionMenuItem::LINK) + rv.link_url = GURL("http://test.link/"); + + if (contexts & ExtensionMenuItem::EDITABLE) + rv.is_editable = true; + + if (contexts & ExtensionMenuItem::IMAGE) { + rv.src_url = GURL("http://test.image/"); + rv.media_type = WebKit::WebContextMenuData::MediaTypeImage; + } + + if (contexts & ExtensionMenuItem::VIDEO) { + rv.src_url = GURL("http://test.video/"); + rv.media_type = WebKit::WebContextMenuData::MediaTypeVideo; + } + + if (contexts & ExtensionMenuItem::AUDIO) { + rv.src_url = GURL("http://test.audio/"); + rv.media_type = WebKit::WebContextMenuData::MediaTypeAudio; + } + + if (contexts & ExtensionMenuItem::FRAME) + rv.frame_url = GURL("http://test.frame/"); + + return rv; +} + +// Generates a URLPatternSet with a single pattern +static URLPatternSet CreatePatternSet(const std::string& pattern) { + URLPattern target(URLPattern::SCHEME_HTTP); + target.Parse(pattern); + + URLPatternSet rv; + rv.AddPattern(target); + + return rv; +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForPage) { + ContextMenuParams params = CreateParams(0); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::PAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetCheckedForLink) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::LINK); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::PAGE); + contexts.Add(ExtensionMenuItem::LINK); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetCheckedForImage) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::PAGE); + contexts.Add(ExtensionMenuItem::IMAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetCheckedForVideo) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::VIDEO); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::PAGE); + contexts.Add(ExtensionMenuItem::VIDEO); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetCheckedForAudio) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::AUDIO); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::PAGE); + contexts.Add(ExtensionMenuItem::AUDIO); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesTarget) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE | + ExtensionMenuItem::LINK); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::LINK); + contexts.Add(ExtensionMenuItem::IMAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.link/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesSource) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE | + ExtensionMenuItem::LINK); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::LINK); + contexts.Add(ExtensionMenuItem::IMAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.image/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, NoMatchWhenLinkedImageMatchesNeither) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE | + ExtensionMenuItem::LINK); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::LINK); + contexts.Add(ExtensionMenuItem::IMAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForFrame) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::FRAME); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::FRAME); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForEditable) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::EDITABLE); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::EDITABLE); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelection) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::SELECTION); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnLink) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION | + ExtensionMenuItem::LINK); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::SELECTION); + contexts.Add(ExtensionMenuItem::LINK); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} + +TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnImage) { + ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION | + ExtensionMenuItem::IMAGE); + + ExtensionMenuItem::ContextList contexts; + contexts.Add(ExtensionMenuItem::SELECTION); + contexts.Add(ExtensionMenuItem::IMAGE); + + URLPatternSet patterns = CreatePatternSet("*://test.none/*"); + + EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); +} diff --git a/pool/shard001/C++/0017193_socket_util.cc b/pool/shard001/C++/0017193_socket_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e6226d38d8d6f11e3e25962fef3796a706e935f --- /dev/null +++ b/pool/shard001/C++/0017193_socket_util.cc @@ -0,0 +1,47 @@ +// Copyright 2021 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 "chromecast/net/socket_util.h" + +#include + +#include + +#include "base/logging.h" +#include "net/base/net_errors.h" +#include "net/base/sockaddr_storage.h" +#include "net/socket/socket_posix.h" +#include "net/socket/stream_socket.h" +#include "net/socket/unix_domain_client_socket_posix.h" + +namespace chromecast { + +bool CreateUnnamedSocketPair(base::ScopedFD* fd1, base::ScopedFD* fd2) { + int raw_socks[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_socks) == -1) { + return false; + } + fd1->reset(raw_socks[0]); + fd2->reset(raw_socks[1]); + return true; +} + +std::unique_ptr AdoptUnnamedSocketHandle( + base::ScopedFD socket_fd) { + if (!socket_fd.is_valid()) { + LOG(ERROR) << "Received invalid socket descriptor: " << socket_fd.get(); + return nullptr; + } + + net::SockaddrStorage address; + auto socket_posix = std::make_unique(); + if (socket_posix->AdoptConnectedSocket(socket_fd.release(), address) != + net::OK) { + LOG(ERROR) << "Cannot adopt connected socket."; + return nullptr; + } + return std::make_unique(std::move(socket_posix)); +} + +} // namespace chromecast diff --git a/pool/shard001/C++/0017201_BPFTargetMachine.cpp b/pool/shard001/C++/0017201_BPFTargetMachine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d42e741407517306bbd7f03d4f3a1ff64cf12ad --- /dev/null +++ b/pool/shard001/C++/0017201_BPFTargetMachine.cpp @@ -0,0 +1,131 @@ +//===-- BPFTargetMachine.cpp - Define TargetMachine for BPF ---------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// Implements the info about BPF target spec. +// +//===----------------------------------------------------------------------===// + +#include "BPFTargetMachine.h" +#include "BPF.h" +#include "MCTargetDesc/BPFMCAsmInfo.h" +#include "TargetInfo/BPFTargetInfo.h" +#include "llvm/CodeGen/Passes.h" +#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" +#include "llvm/CodeGen/TargetPassConfig.h" +#include "llvm/IR/LegacyPassManager.h" +#include "llvm/Support/FormattedStream.h" +#include "llvm/Support/TargetRegistry.h" +#include "llvm/Target/TargetOptions.h" +using namespace llvm; + +static cl:: +opt DisableMIPeephole("disable-bpf-peephole", cl::Hidden, + cl::desc("Disable machine peepholes for BPF")); + +extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeBPFTarget() { + // Register the target. + RegisterTargetMachine X(getTheBPFleTarget()); + RegisterTargetMachine Y(getTheBPFbeTarget()); + RegisterTargetMachine Z(getTheBPFTarget()); + + PassRegistry &PR = *PassRegistry::getPassRegistry(); + initializeBPFAbstractMemberAccessPass(PR); + initializeBPFMIPeepholePass(PR); + initializeBPFMIPeepholeTruncElimPass(PR); +} + +// DataLayout: little or big endian +static std::string computeDataLayout(const Triple &TT) { + if (TT.getArch() == Triple::bpfeb) + return "E-m:e-p:64:64-i64:64-i128:128-n32:64-S128"; + else + return "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128"; +} + +static Reloc::Model getEffectiveRelocModel(Optional RM) { + if (!RM.hasValue()) + return Reloc::PIC_; + return *RM; +} + +BPFTargetMachine::BPFTargetMachine(const Target &T, const Triple &TT, + StringRef CPU, StringRef FS, + const TargetOptions &Options, + Optional RM, + Optional CM, + CodeGenOpt::Level OL, bool JIT) + : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options, + getEffectiveRelocModel(RM), + getEffectiveCodeModel(CM, CodeModel::Small), OL), + TLOF(std::make_unique()), + Subtarget(TT, std::string(CPU), std::string(FS), *this) { + initAsmInfo(); + + BPFMCAsmInfo *MAI = + static_cast(const_cast(AsmInfo.get())); + MAI->setDwarfUsesRelocationsAcrossSections(!Subtarget.getUseDwarfRIS()); +} + +namespace { +// BPF Code Generator Pass Configuration Options. +class BPFPassConfig : public TargetPassConfig { +public: + BPFPassConfig(BPFTargetMachine &TM, PassManagerBase &PM) + : TargetPassConfig(TM, PM) {} + + BPFTargetMachine &getBPFTargetMachine() const { + return getTM(); + } + + void addIRPasses() override; + bool addInstSelector() override; + void addMachineSSAOptimization() override; + void addPreEmitPass() override; +}; +} + +TargetPassConfig *BPFTargetMachine::createPassConfig(PassManagerBase &PM) { + return new BPFPassConfig(*this, PM); +} + +void BPFPassConfig::addIRPasses() { + + addPass(createBPFAbstractMemberAccess(&getBPFTargetMachine())); + + TargetPassConfig::addIRPasses(); +} + +// Install an instruction selector pass using +// the ISelDag to gen BPF code. +bool BPFPassConfig::addInstSelector() { + addPass(createBPFISelDag(getBPFTargetMachine())); + + return false; +} + +void BPFPassConfig::addMachineSSAOptimization() { + addPass(createBPFMISimplifyPatchablePass()); + + // The default implementation must be called first as we want eBPF + // Peephole ran at last. + TargetPassConfig::addMachineSSAOptimization(); + + const BPFSubtarget *Subtarget = getBPFTargetMachine().getSubtargetImpl(); + if (!DisableMIPeephole) { + if (Subtarget->getHasAlu32()) + addPass(createBPFMIPeepholePass()); + addPass(createBPFMIPeepholeTruncElimPass()); + } +} + +void BPFPassConfig::addPreEmitPass() { + addPass(createBPFMIPreEmitCheckingPass()); + if (getOptLevel() != CodeGenOpt::None) + if (!DisableMIPeephole) + addPass(createBPFMIPreEmitPeepholePass()); +} diff --git a/pool/shard001/C++/0017203_atom_menu_model.cc b/pool/shard001/C++/0017203_atom_menu_model.cc new file mode 100644 index 0000000000000000000000000000000000000000..83e23c42ed8984abaa6abc6f18fa76ace5a3f157 --- /dev/null +++ b/pool/shard001/C++/0017203_atom_menu_model.cc @@ -0,0 +1,65 @@ +// Copyright (c) 2015 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/ui/atom_menu_model.h" + +#include "base/stl_util.h" + +namespace atom { + +bool AtomMenuModel::Delegate::GetAcceleratorForCommandId(int command_id, + ui::Accelerator* accelerator) const { + return GetAcceleratorForCommandIdWithParams( + command_id, false, accelerator); +} + +AtomMenuModel::AtomMenuModel(Delegate* delegate) + : ui::SimpleMenuModel(delegate), delegate_(delegate) {} + +AtomMenuModel::~AtomMenuModel() {} + +void AtomMenuModel::SetRole(int index, const base::string16& role) { + int command_id = GetCommandIdAt(index); + roles_[command_id] = role; +} + +base::string16 AtomMenuModel::GetRoleAt(int index) { + int command_id = GetCommandIdAt(index); + if (base::ContainsKey(roles_, command_id)) + return roles_[command_id]; + else + return base::string16(); +} + +bool AtomMenuModel::GetAcceleratorAtWithParams( + int index, + bool use_default_accelerator, + ui::Accelerator* accelerator) const { + if (delegate_) { + return delegate_->GetAcceleratorForCommandIdWithParams( + GetCommandIdAt(index), use_default_accelerator, accelerator); + } + return false; +} + +void AtomMenuModel::MenuWillClose() { + ui::SimpleMenuModel::MenuWillClose(); + for (Observer& observer : observers_) { + observer.OnMenuWillClose(); + } +} + +void AtomMenuModel::MenuWillShow() { + ui::SimpleMenuModel::MenuWillShow(); + for (Observer& observer : observers_) { + observer.OnMenuWillShow(); + } +} + +AtomMenuModel* AtomMenuModel::GetSubmenuModelAt(int index) { + return static_cast( + ui::SimpleMenuModel::GetSubmenuModelAt(index)); +} + +} // namespace atom diff --git a/pool/shard001/C++/0017205_isobarAmplitude_py.cc b/pool/shard001/C++/0017205_isobarAmplitude_py.cc new file mode 100644 index 0000000000000000000000000000000000000000..c19a9a50de4dacfc368626e2206b840c8335711d --- /dev/null +++ b/pool/shard001/C++/0017205_isobarAmplitude_py.cc @@ -0,0 +1,118 @@ +#include "isobarAmplitude_py.h" + +#include + +#include "isobarAmplitude.h" +#include "rootConverters_py.h" + +namespace bp = boost::python; + + +namespace { + + struct isobarAmplitudeWrapper : public rpwa::isobarAmplitude, + bp::wrapper + { + + void init() { + if(bp::override init = this->get_override("init")) { + init(); + } + rpwa::isobarAmplitude::init(); + } + + void default_init() { + rpwa::isobarAmplitude::init(); + } + + std::string name() const { + if(bp::override name = this->get_override("name")) { + return name(); + } + return rpwa::isobarAmplitude::name(); + } + + std::string default_name() const { + return rpwa::isobarAmplitude::name(); + } + + std::string printParameters__() const { + std::stringstream sstr; + if(bp::override printParameters = this->get_override("printParameters")) { + printParameters(sstr); + } else { + rpwa::isobarAmplitude::printParameters(sstr); + } + return sstr.str(); + } + + std::string default_printParameters__() const { + std::stringstream sstr; + rpwa::isobarAmplitude::printParameters(sstr); + return sstr.str(); + } + + }; + + rpwa::isobarDecayTopology& isobarAmplitude_decayTopology(const rpwa::isobarAmplitude& self) { + return *(self.decayTopology()); + } + + PyObject* isobarAmplitude_gjTransform(PyObject* pyBeamLv, PyObject* pyXLv) { + TLorentzVector* beamLv = rpwa::py::convertFromPy(pyBeamLv); + TLorentzVector* XLv = rpwa::py::convertFromPy(pyXLv); + if((beamLv == NULL) || (XLv == NULL)) { + printErr<<"Got invalid input when executing rpwa::isobarAmplitude::gjTransform()."<(rpwa::isobarAmplitude::gjTransform(*beamLv, *XLv)); + } + + std::string isobarAmplitude_printParameters(const rpwa::isobarAmplitude& self) { + std::stringstream sstr; + self.printParameters(sstr); + return sstr.str(); + } + +} + +void rpwa::py::exportIsobarAmplitude() { + + bp::class_("isobarAmplitude", bp::no_init) + + .def(bp::self_ns::str(bp::self)) + + .def( + "decayTopology" + , &isobarAmplitude_decayTopology + , bp::return_internal_reference<>() + ) + + .def("setDecayTopology", &rpwa::isobarAmplitude::setDecayTopology) + + .def("init", &isobarAmplitudeWrapper::init, &isobarAmplitudeWrapper::default_init) + .def("init", &rpwa::isobarAmplitude::init) + + .add_property("reflectivityBasis", &rpwa::isobarAmplitude::reflectivityBasis, &rpwa::isobarAmplitude::enableReflectivityBasis) + .add_property("boseSymmetrization", &rpwa::isobarAmplitude::boseSymmetrization, &rpwa::isobarAmplitude::enableBoseSymmetrization) + .add_property("isospinSymmetrization", &rpwa::isobarAmplitude::isospinSymmetrization, &rpwa::isobarAmplitude::enableIsospinSymmetrization) + .add_property("doSpaceInversion", &rpwa::isobarAmplitude::doSpaceInversion, &rpwa::isobarAmplitude::enableSpaceInversion) + .add_property("doReflection", &rpwa::isobarAmplitude::doReflection, &rpwa::isobarAmplitude::enableReflection) + + .def("gjTransform", &isobarAmplitude_gjTransform) + .staticmethod("gjTransform") + + .def("amplitude", &rpwa::isobarAmplitude::amplitude) + + .def("__call__", &rpwa::isobarAmplitude::operator()) + + .def("name", &isobarAmplitudeWrapper::name, &isobarAmplitudeWrapper::default_name) + .def("name", &isobarAmplitude::name) + .def("printParameters", &isobarAmplitudeWrapper::printParameters__, &isobarAmplitudeWrapper::default_printParameters__) + .def("printParameters", &isobarAmplitude_printParameters) + + .add_static_property("debugIsobarAmplitude", &rpwa::isobarAmplitude::debug, &rpwa::isobarAmplitude::setDebug); + + bp::register_ptr_to_python(); + +} diff --git a/pool/shard001/C++/0017208_subscriber_test.cc b/pool/shard001/C++/0017208_subscriber_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b8dd1f9486e3f228c5d9b915922d91de71ff0d76 --- /dev/null +++ b/pool/shard001/C++/0017208_subscriber_test.cc @@ -0,0 +1,159 @@ +/* + * + * Copyright 2015, 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "examples/pubsub/subscriber.h" +#include "test/core/util/port.h" +#include "test/core/util/test_config.h" + +namespace grpc { +namespace testing { +namespace { + +const char kTopic[] = "test topic"; +const char kSubscriptionName[] = "subscription name"; +const char kData[] = "Message data"; + +class SubscriberServiceImpl : public tech::pubsub::SubscriberService::Service { + public: + Status CreateSubscription( + ServerContext* context, const tech::pubsub::Subscription* request, + tech::pubsub::Subscription* response) GRPC_OVERRIDE { + EXPECT_EQ(request->topic(), kTopic); + EXPECT_EQ(request->name(), kSubscriptionName); + return Status::OK; + } + + Status GetSubscription(ServerContext* context, + const tech::pubsub::GetSubscriptionRequest* request, + tech::pubsub::Subscription* response) GRPC_OVERRIDE { + EXPECT_EQ(request->subscription(), kSubscriptionName); + response->set_topic(kTopic); + return Status::OK; + } + + Status DeleteSubscription( + ServerContext* context, + const tech::pubsub::DeleteSubscriptionRequest* request, + proto2::Empty* response) GRPC_OVERRIDE { + EXPECT_EQ(request->subscription(), kSubscriptionName); + return Status::OK; + } + + Status Pull(ServerContext* context, const tech::pubsub::PullRequest* request, + tech::pubsub::PullResponse* response) GRPC_OVERRIDE { + EXPECT_EQ(request->subscription(), kSubscriptionName); + response->set_ack_id("1"); + response->mutable_pubsub_event()->mutable_message()->set_data(kData); + return Status::OK; + } + + Status Acknowledge(ServerContext* context, + const tech::pubsub::AcknowledgeRequest* request, + proto2::Empty* response) GRPC_OVERRIDE { + return Status::OK; + } + +}; + +class SubscriberTest : public ::testing::Test { + protected: + // Setup a server and a client for SubscriberService. + void SetUp() GRPC_OVERRIDE { + int port = grpc_pick_unused_port_or_die(); + server_address_ << "localhost:" << port; + ServerBuilder builder; + builder.AddListeningPort(server_address_.str(), grpc::InsecureServerCredentials()); + builder.RegisterService(&service_); + server_ = builder.BuildAndStart(); + + channel_ = CreateChannel(server_address_.str(), grpc::InsecureCredentials(), ChannelArguments()); + + subscriber_.reset(new grpc::examples::pubsub::Subscriber(channel_)); + } + + void TearDown() GRPC_OVERRIDE { + server_->Shutdown(); + subscriber_->Shutdown(); + } + + std::ostringstream server_address_; + std::unique_ptr server_; + SubscriberServiceImpl service_; + + std::shared_ptr channel_; + + std::unique_ptr subscriber_; +}; + +TEST_F(SubscriberTest, TestSubscriber) { + EXPECT_TRUE(subscriber_->CreateSubscription(kTopic, + kSubscriptionName).IsOk()); + + grpc::string topic; + EXPECT_TRUE(subscriber_->GetSubscription(kSubscriptionName, + &topic).IsOk()); + EXPECT_EQ(topic, kTopic); + + grpc::string data; + EXPECT_TRUE(subscriber_->Pull(kSubscriptionName, + &data).IsOk()); + + EXPECT_TRUE(subscriber_->DeleteSubscription(kSubscriptionName).IsOk()); +} + +} // namespace +} // namespace testing +} // namespace grpc + +int main(int argc, char** argv) { + grpc_test_init(argc, argv); + grpc_init(); + ::testing::InitGoogleTest(&argc, argv); + gpr_log(GPR_INFO, "Start test ..."); + int result = RUN_ALL_TESTS(); + grpc_shutdown(); + return result; +} diff --git a/pool/shard001/C++/0017218_vix_iniwriter.cpp b/pool/shard001/C++/0017218_vix_iniwriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..650b931337f5293a7ac8d556ba8780f37eda728c --- /dev/null +++ b/pool/shard001/C++/0017218_vix_iniwriter.cpp @@ -0,0 +1,38 @@ +#include +#include + +namespace Vixen { + + INIWriter::INIWriter() + { + _values["TEST_SECTION"].push_back("bFixed"); + _values["TEST_SECTION"].push_back("iWidth"); + _values["TEST_SECTION"].push_back("iHeight"); + _values["TEST_SECTION"].push_back("fScale"); + _values["TEST_SECTION"].push_back("fDepth"); + } + + void INIWriter::Write(std::string outname) + { + File* file = FileManager::OpenFile(UStringFromCharArray(outname.c_str()), Vixen::FileMode::WriteBinary); + if(file) + { + for(auto& key : _values) + { + //Write section + std::string section = "[" + key.first + "]\n"; + + file->Write((BYTE*)section.c_str(), section.size()); + + std::vector _map = key.second; + for(int i = 0; i < _map.size(); i++) + { + std::string name = _map[i]; + name += "\n"; + file->Write((BYTE*)name.c_str(), name.size()); + } + } + } + } + +} diff --git a/pool/shard001/C++/0017221_3.cpp b/pool/shard001/C++/0017221_3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83f2ffdac037565765627ea73fdf6410be0199f2 --- /dev/null +++ b/pool/shard001/C++/0017221_3.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include + +using namespace std; + +int main(){ + int n; + char c[101]; + scanf("%d", &n); + for(int i=0;iThemeEngine()->GetOverlayScrollbarStyle(&style); + DCHECK(style.thumb_thickness); + initialized = true; + } + return style; +} + +ScrollbarThemeOverlayMobile& ScrollbarThemeOverlayMobile::GetInstance() { + // For unit tests which don't have Platform::Current()->ThemeEngine(). + if (MockScrollbarsEnabled()) { + DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, theme, ()); + return theme; + } + + DEFINE_STATIC_LOCAL( + ScrollbarThemeOverlayMobile, theme, + (ScrollbarStyle().thumb_thickness, ScrollbarStyle().scrollbar_margin, + ScrollbarStyle().thumb_thickness_thin, + ScrollbarStyle().scrollbar_margin_thin, ScrollbarStyle().color)); + return theme; +} + +ScrollbarThemeOverlayMobile::ScrollbarThemeOverlayMobile( + int thumb_thickness_default, + int scrollbar_margin_default, + int thumb_thickness_thin, + int scrollbar_margin_thin, + Color color) + : ScrollbarThemeOverlay(thumb_thickness_default, + scrollbar_margin_default, + thumb_thickness_thin, + scrollbar_margin_thin), + color_(color) {} + +void ScrollbarThemeOverlayMobile::PaintThumb(GraphicsContext& context, + const Scrollbar& scrollbar, + const IntRect& rect) { + if (!scrollbar.Enabled()) + return; + + if (DrawingRecorder::UseCachedDrawingIfPossible(context, scrollbar, + DisplayItem::kScrollbarThumb)) + return; + + DrawingRecorder recorder(context, scrollbar, DisplayItem::kScrollbarThumb, + ToGfxRect(rect)); + + const auto* box = scrollbar.GetScrollableArea()->GetLayoutBox(); + AutoDarkMode auto_dark_mode(PaintAutoDarkMode( + box->StyleRef(), DarkModeFilter::ElementRole::kBackground)); + context.FillRect(rect, color_, auto_dark_mode); +} + +} // namespace blink diff --git a/pool/shard001/C++/0017229_boss_shazzrah.cpp b/pool/shard001/C++/0017229_boss_shazzrah.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36619cfa909e343747a10ede358287b99da00f20 --- /dev/null +++ b/pool/shard001/C++/0017229_boss_shazzrah.cpp @@ -0,0 +1,148 @@ +/* Copyright (C) 2006 - 2010 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, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Boss_Shazzrah +SD%Complete: 75 +SDComment: Teleport NYI +SDCategory: Molten Core +EndScriptData */ + +#include "scriptPCH.h" +#include "molten_core.h" + +enum +{ + SPELL_ARCANEEXPLOSION = 19712, + SPELL_SHAZZRAHCURSE = 19713, + SPELL_DEADENMAGIC = 19714, + SPELL_COUNTERSPELL = 19715, + SPELL_GATE_DUMMY = 23138 // effect spell: 23139 +}; + +struct boss_shazzrahAI : public ScriptedAI +{ + boss_shazzrahAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + Reset(); + } + + uint32 ArcaneExplosion_Timer; + uint32 ShazzrahCurse_Timer; + uint32 DeadenMagic_Timer; + uint32 Countspell_Timer; + uint32 Blink_Timer; + + ScriptedInstance* m_pInstance; + + void Reset() + { + ArcaneExplosion_Timer = 2000; + ShazzrahCurse_Timer = 10000; + DeadenMagic_Timer = 5000; + Countspell_Timer = 15000; + Blink_Timer = urand(25000, 30000); + + if (m_pInstance && m_creature->isAlive()) + m_pInstance->SetData(TYPE_SHAZZRAH, NOT_STARTED); + } + + void Aggro(Unit* pWho) + { + if (m_pInstance) + m_pInstance->SetData(TYPE_SHAZZRAH, IN_PROGRESS); + } + + void JustDied(Unit* pKiller) + { + if (m_pInstance) + m_pInstance->SetData(TYPE_SHAZZRAH, DONE); + } + + void UpdateAI(const uint32 diff) + { + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + + //ArcaneExplosion_Timer + if (ArcaneExplosion_Timer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ARCANEEXPLOSION) == CAST_OK) + ArcaneExplosion_Timer = urand(3000, 5000); + } + else ArcaneExplosion_Timer -= diff; + + //ShazzrahCurse_Timer + if (ShazzrahCurse_Timer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SHAZZRAHCURSE, CAST_AURA_NOT_PRESENT) == CAST_OK) + ShazzrahCurse_Timer = 20000; + } + else ShazzrahCurse_Timer -= diff; + + //DeadenMagic_Timer + if (DeadenMagic_Timer < diff) + { + if (DoCastSpellIfCan(m_creature, SPELL_DEADENMAGIC) == CAST_OK) + DeadenMagic_Timer = urand(7000, 14000); + } + else DeadenMagic_Timer -= diff; + + //Countspell_Timer + if (Countspell_Timer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_COUNTERSPELL) == CAST_OK) + Countspell_Timer = urand(16000, 18000); + } + else Countspell_Timer -= diff; + + //Blink_Timer + if (Blink_Timer < diff) + { + // Teleporting him to a random gamer and casting Arcane Explosion after that. + if (DoCastSpellIfCan(m_creature, SPELL_GATE_DUMMY, CAST_TRIGGERED) == CAST_OK) + { + // manual, until added effect of dummy properly + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) + { + DoResetThreat(); + //if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) + m_creature->NearTeleportTo(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), m_creature->GetOrientation()); + m_creature->Attack(pTarget, true); + } + + Blink_Timer = urand(25000, 35000); + } + } + else Blink_Timer -= diff; + + DoMeleeAttackIfReady(); + } +}; +CreatureAI* GetAI_boss_shazzrah(Creature* pCreature) +{ + return new boss_shazzrahAI(pCreature); +} + +void AddSC_boss_shazzrah() +{ + Script *newscript; + newscript = new Script; + newscript->Name = "boss_shazzrah"; + newscript->GetAI = &GetAI_boss_shazzrah; + newscript->RegisterSelf(); +} diff --git a/pool/shard001/C++/0017230_base_run_loop.cc b/pool/shard001/C++/0017230_base_run_loop.cc new file mode 100644 index 0000000000000000000000000000000000000000..df78561b27de3d8cb57de74d3b9a4278334976d8 --- /dev/null +++ b/pool/shard001/C++/0017230_base_run_loop.cc @@ -0,0 +1,81 @@ +// 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 "mojo/android/system/base_run_loop.h" + +#include + +#include "base/android/base_jni_registrar.h" +#include "base/android/jni_android.h" +#include "base/android/jni_registrar.h" +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "jni/BaseRunLoop_jni.h" +#include "mojo/message_pump/message_pump_mojo.h" + +namespace mojo { +namespace android { + +static jlong CreateBaseRunLoop(JNIEnv* env, + const JavaParamRef& jcaller) { + base::MessageLoop* message_loop = + new base::MessageLoop(common::MessagePumpMojo::Create()); + return reinterpret_cast(message_loop); +} + +static void Run(JNIEnv* env, + const JavaParamRef& jcaller, + jlong runLoopID) { + reinterpret_cast(runLoopID)->Run(); +} + +static void RunUntilIdle(JNIEnv* env, + const JavaParamRef& jcaller, + jlong runLoopID) { + reinterpret_cast(runLoopID)->RunUntilIdle(); +} + +static void Quit(JNIEnv* env, + const JavaParamRef& jcaller, + jlong runLoopID) { + reinterpret_cast(runLoopID)->Quit(); +} + +static void RunJavaRunnable( + const base::android::ScopedJavaGlobalRef& runnable_ref) { + Java_BaseRunLoop_runRunnable(base::android::AttachCurrentThread(), + runnable_ref.obj()); +} + +static void PostDelayedTask(JNIEnv* env, + const JavaParamRef& jcaller, + jlong runLoopID, + const JavaParamRef& runnable, + jlong delay) { + base::android::ScopedJavaGlobalRef runnable_ref; + // ScopedJavaGlobalRef do not hold onto the env reference, so it is safe to + // use it across threads. |RunJavaRunnable| will acquire a new JNIEnv before + // running the Runnable. + runnable_ref.Reset(env, runnable); + reinterpret_cast(runLoopID)->PostDelayedTask( + FROM_HERE, base::Bind(&RunJavaRunnable, runnable_ref), + base::TimeDelta::FromMicroseconds(delay)); +} + +static void DeleteMessageLoop(JNIEnv* env, + const JavaParamRef& jcaller, + jlong runLoopID) { + base::MessageLoop* message_loop = + reinterpret_cast(runLoopID); + delete message_loop; +} + +bool RegisterBaseRunLoop(JNIEnv* env) { + return RegisterNativesImpl(env); +} + +} // namespace android +} // namespace mojo + + diff --git a/pool/shard001/C++/0017243_publisherinfoservice.cpp b/pool/shard001/C++/0017243_publisherinfoservice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5057133ddc1f6cd17b995e830b20bc09ca2d59a --- /dev/null +++ b/pool/shard001/C++/0017243_publisherinfoservice.cpp @@ -0,0 +1,36 @@ +#include "publisherinfoservice.h" + +PublisherInfoService::PublisherInfoService(QSqlDatabase *db, QObject *parent):DataServiceBase(db, parent) +{ + +} + +QStringList PublisherInfoService::getAllPublisherNames() +{ + QString queryString = "SELECT publisher_name FROM publisher_info ORDER BY publisher_name ASC"; + return this->getStringListFromDatabase(queryString); +} + +int PublisherInfoService::getPublisherCount() +{ + QString queryString = "SELECT COUNT(*) FROM publisher_info"; + return this->getCountFromDatabase(queryString); +} + +QString PublisherInfoService::getPublisherCountry(QString publisher) +{ + QString queryString = "SELECT publisher_country FROM publisher_info WHERE publisher_name = ?"; + return this->getStringFromDatabase(queryString, publisher); +} + +QString PublisherInfoService::getPublisherWebsite(QString publisher) +{ + QString queryString = "SELECT publisher_website FROM publisher_info WHERE publisher_name = ?"; + return this->getStringFromDatabase(queryString, publisher); +} + +QString PublisherInfoService::getPublisherNote(QString publisher) +{ + QString queryString = "SELECT publisher_note FROM publisher_info WHERE publisher_name = ?"; + return this->getStringFromDatabase(queryString, publisher); +} diff --git a/pool/shard001/C++/0017245_StringTokenizer.cpp b/pool/shard001/C++/0017245_StringTokenizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7636e56c4c5f479adf885ff79ee510272f629b9c --- /dev/null +++ b/pool/shard001/C++/0017245_StringTokenizer.cpp @@ -0,0 +1,154 @@ +/********************************************************************** + * + * GEOS - Geometry Engine Open Source + * http://geos.osgeo.org + * + * Copyright (C) 2005-2006 Refractions Research Inc. + * 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. + * + ********************************************************************** + * + * Last port: ORIGINAL WORK + * + **********************************************************************/ + +#include + +#include +#include + +using namespace std; + +namespace geos { +namespace io { // geos.io + +/*public*/ +StringTokenizer::StringTokenizer(const string &txt) + : + str(txt) +{ + stok=""; + ntok=0.0; + iter=str.begin(); +} + +/*public*/ +int +StringTokenizer::nextToken() +{ + string tok=""; + if (iter==str.end()) + return StringTokenizer::TT_EOF; + switch(*iter) { + case '(': + case ')': + case ',': + return *iter++; + case '\n': + case '\r': + case '\t': + case ' ': + string::size_type pos=str.find_first_not_of(" \n\r\t", + iter-str.begin()); + if (pos==string::npos) { + return StringTokenizer::TT_EOF; + } else { + iter=str.begin()+pos; + return nextToken(); + } + } + string::size_type pos=str.find_first_of("\n\r\t() ,", + iter-str.begin()); + if (pos==string::npos) { + if (iter!=str.end()) { + tok.assign(iter,str.end()); + iter=str.end(); + } else { + return StringTokenizer::TT_EOF; + } + } else { + tok.assign(iter, str.begin()+pos); + iter=str.begin()+pos; + } + char *stopstring; + double dbl=strtod(tok.c_str(),&stopstring); + if (*stopstring=='\0') { + ntok=dbl; + stok=""; + return StringTokenizer::TT_NUMBER; + } else { + ntok=0.0; + stok=tok; + return StringTokenizer::TT_WORD; + } +} + +/*public*/ +int +StringTokenizer::peekNextToken() +{ + + string::size_type pos; + string tok=""; + if (iter==str.end()) + return StringTokenizer::TT_EOF; + + pos=str.find_first_not_of(" \r\n\t", iter-str.begin()); + + if (pos==string::npos) return StringTokenizer::TT_EOF; + switch(str[pos]) { + case '(': + case ')': + case ',': + return str[pos]; + } + + // It's either a Number or a Word, let's + // see when it ends + + pos=str.find_first_of("\n\r\t() ,", iter-str.begin()); + + if (pos==string::npos) { + if (iter!=str.end()) { + tok.assign(iter,str.end()); + } else { + return StringTokenizer::TT_EOF; + } + } else { + tok.assign(iter, str.begin()+pos); //str.end()); + } + + char *stopstring; + double dbl=strtod(tok.c_str(),&stopstring); + if (*stopstring=='\0') { + ntok=dbl; + stok=""; + return StringTokenizer::TT_NUMBER; + } else { + ntok=0.0; + stok=tok; + return StringTokenizer::TT_WORD; + } +} + +/*public*/ +double +StringTokenizer::getNVal() +{ + return ntok; +} + +/*public*/ +string +StringTokenizer::getSVal() +{ + return stok; +} + +} // namespace geos.io +} // namespace geos diff --git a/pool/shard001/C++/0017252_play_game.cpp b/pool/shard001/C++/0017252_play_game.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33ebd7f439b81637360c1e26e254a03895816993 --- /dev/null +++ b/pool/shard001/C++/0017252_play_game.cpp @@ -0,0 +1,55 @@ +#include + +#include + +#include +#include +#include + +namespace konig { + +PlayResult play_game( + const Ruleset& rules, + const Players& players, + Deal deal, + std::ostream* debug_stream +) +{ + std::array hands; + std::array talon; + deal.copy_hands(hands.begin()); + deal.copy_talon(talon.begin()); + + for (PlayPosition i=position_forehand; i(r); + PlayPosition declarer = boost::tuples::get<1>(r); + assert(declarer < 4); + + if (debug_stream) { + *debug_stream << "contract is " << contract.name() << + " by " << declarer << std::endl; + } + + return contract.play(hands, talon, players, declarer, debug_stream); +} + +PlayResult play_game( + const Ruleset& rules, + Oracle& oracle +) +{ + BiddingSequence bids(rules.contracts()); + auto const r = bids.get_bids(oracle); + Contract const& contract = boost::tuples::get<0>(r); + PlayPosition declarer = boost::tuples::get<1>(r); + assert(declarer < 4); + + return contract.play(oracle, declarer); +} + +} + diff --git a/pool/shard001/C++/0017253_window_demo.cc b/pool/shard001/C++/0017253_window_demo.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d01d16a961f3be5bfcf445070b69751d6e7764d --- /dev/null +++ b/pool/shard001/C++/0017253_window_demo.cc @@ -0,0 +1,144 @@ +// Copyright 2017 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 "xrtl/testing/demo_main.h" + +#include "xrtl/base/logging.h" +#include "xrtl/base/threading/event.h" +#include "xrtl/base/threading/thread.h" +#include "xrtl/ui/window.h" + +namespace xrtl { +namespace ui { +namespace { + +class WindowDemo : private Control::Listener, private Control::InputListener { + public: + WindowDemo() { + message_loop_ = MessageLoop::Create(); + done_event_ = Event::CreateFence(); + } + + ~WindowDemo() { Thread::Wait(message_loop_->Exit()); } + + ref_ptr Run() { + window_ = Window::Create(message_loop_); + window_->set_title("Window Demo"); + + auto control = window_->root_control(); + control->set_listener(this); + control->set_input_listener(this); + control->set_size({640, 480}); + control->set_background_color({255, 0, 0, 255}); + + Thread::Wait(window_->Open()); + + return done_event_; + } + + private: + void OnError(ref_ptr target) override { + LOG(INFO) << "OnError"; + done_event_->Set(); + } + + void OnCreating(ref_ptr target) override { + LOG(INFO) << "OnCreating"; + } + + void OnCreated(ref_ptr target) override { LOG(INFO) << "OnCreated"; } + + void OnDestroying(ref_ptr target) override { + LOG(INFO) << "OnDestroying"; + } + + void OnDestroyed(ref_ptr target) override { + LOG(INFO) << "OnDestroyed"; + done_event_->Set(); + } + + void OnSystemThemeChanged(ref_ptr target) override { + LOG(INFO) << "OnSystemThemeChanged"; + } + + void OnSuspendChanged(ref_ptr target, bool is_suspended) override { + LOG(INFO) << "OnSuspendChanged: " << is_suspended; + } + + void OnFocusChanged(ref_ptr target, bool is_focused) override { + LOG(INFO) << "OnFocusChanged: " << is_focused; + } + + void OnResized(ref_ptr target, Rect2D bounds) override { + LOG(INFO) << "OnResized: " << bounds.origin.x << "," << bounds.origin.y + << " " << bounds.size.width << "x" << bounds.size.height; + } + + void OnKeyDown(ref_ptr target, const KeyboardEvent& ev) override { + LOG(INFO) << "OnKeyDown: " << ev.key_code(); + } + + void OnKeyUp(ref_ptr target, const KeyboardEvent& ev) override { + LOG(INFO) << "OnKeyUp: " << ev.key_code(); + } + + void OnKeyPress(ref_ptr target, const KeyboardEvent& ev) override { + LOG(INFO) << "OnKeyPress: " << ev.key_code(); + } + + void OnMouseDown(ref_ptr target, const MouseEvent& ev) override { + LOG(INFO) << "OnMouseDown: " << ev.control_offset_px().x << "," + << ev.control_offset_px().y << " b" + << static_cast(ev.action_button()); + } + + void OnMouseUp(ref_ptr target, const MouseEvent& ev) override { + LOG(INFO) << "OnMouseUp: " << ev.control_offset_px().x << "," + << ev.control_offset_px().y << " b" + << static_cast(ev.action_button()); + } + + void OnMouseOut(ref_ptr target, const MouseEvent& ev) override { + LOG(INFO) << "OnMouseOut: " << ev.control_offset_px().x << "," + << ev.control_offset_px().y; + } + + void OnMouseMove(ref_ptr target, const MouseEvent& ev) override { + LOG(INFO) << "OnMouseMove: " << ev.control_offset_px().x << "," + << ev.control_offset_px().y; + } + + void OnMouseWheel(ref_ptr target, const MouseEvent& ev) override { + LOG(INFO) << "OnMouseWheel: " << ev.control_offset_px().x << "," + << ev.control_offset_px().y << " d" << ev.wheel_delta(); + } + + ref_ptr message_loop_; + ref_ptr window_; + ref_ptr done_event_; +}; + +int MyEntry(int argc, char** argv) { + auto demo = absl::make_unique(); + Thread::Wait(demo->Run()); + demo.reset(); + LOG(INFO) << "Clean exit!"; + return 0; +} + +} // namespace +} // namespace ui +} // namespace xrtl + +DECLARE_ENTRY_POINT(xrtl::ui::MyEntry); diff --git a/pool/shard001/C++/0017255_Shader.cpp b/pool/shard001/C++/0017255_Shader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f5f878af0f7711c8ee8ca6547529838ecbf8113 --- /dev/null +++ b/pool/shard001/C++/0017255_Shader.cpp @@ -0,0 +1,228 @@ +#include "Shader.hpp" + +#include +#include +#include + +static std::string +getStringFromFile(const std::string &filename) +{ + std::string s; + + if (filename == "") { + //no shader specified + return ""; + } + + std::ifstream in(filename.c_str()); + if (!in) { + std::cerr << "ERROR: unable to read filename: " << filename << "\n"; + return s; + } + + std::string line; + while (std::getline(in, line)) { + s += line + "\n"; + } + + return s; +} + +static void +printInfoLog(GLuint object, const std::string &msg) +{ + GLint logLength = 0; + if (glIsShader(object) != 0u) { + glGetShaderiv(object, GL_INFO_LOG_LENGTH, &logLength); + } + else if (glIsProgram(object) != 0u) { + glGetProgramiv(object, GL_INFO_LOG_LENGTH, &logLength); + } + else { + std::cerr << "Error: Not a shader or a program\n"; + return; + } + + if (logLength > 0) { + + auto log = new GLchar[logLength]; + if (glIsShader(object) != 0u) { + glGetShaderInfoLog(object, logLength, nullptr, log); + } + else if (glIsProgram(object) != 0u) { + glGetProgramInfoLog(object, logLength, nullptr, log); + } + + std::cerr << msg << " info: \n" << log << "\n"; + + delete[] log; + } +} + +static GLuint +createShader(const std::string &src, GLenum type, const std::string &msg) +{ + GLuint res = glCreateShader(type); + + const GLchar *s_src = src.c_str(); + + //B : take GL_ES into account ? + /* + + const GLchar* sources[] = { + // Define GLSL version +#ifdef GL_ES_VERSION_2_0 + "#version 100\n" +#else + "#version 120\n" +#endif + , + // GLES2 precision specifiers +#ifdef GL_ES_VERSION_2_0 + // Define default float precision for fragment shaders: + (type == GL_FRAGMENT_SHADER) ? + "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" + "precision highp float; \n" + "#else \n" + "precision mediump float; \n" + "#endif \n" + : "" + // Note: OpenGL ES automatically defines this: + // #define GL_ES +#else + // Ignore GLES 2 precision specifiers: + "#define lowp \n" + "#define mediump\n" + "#define highp \n" +#endif + , + source }; + + glShaderSource(res, 3, sources, NULL); + + */ + + GL_CHECK_ERROR_ALWAYS(); + + glShaderSource(res, 1, static_cast(&s_src), nullptr); + + GL_CHECK_ERROR_ALWAYS(); + + glCompileShader(res); + + GL_CHECK_ERROR_ALWAYS(); + + GLint compile_ok = GL_FALSE; + glGetShaderiv(res, GL_COMPILE_STATUS, &compile_ok); + if (compile_ok == GL_FALSE) { + std::cerr << "Error in " << msg << " shader\n"; + printInfoLog(res, msg); + glDeleteShader(res); + return 0; + } + + return res; +} + +bool +Shader::loadFromFiles(const std::string &vertexFilename, + const std::string &fragmentFilename) +{ + const std::string v = getStringFromFile(vertexFilename); + const std::string s = getStringFromFile(fragmentFilename); + + return loadFromStrings(v, s); +} + +bool +Shader::loadFromStrings(const std::string &vertexString, + const std::string &fragmentString) +{ + + GLuint program = glCreateProgram(); + + if (vertexString != "") { + GLuint shader = createShader(vertexString, GL_VERTEX_SHADER, "vertex"); + if (shader == 0u) { + return false; + } + glAttachShader(program, shader); + //std::cerr << "attach vertex shader " << shader << "\n"; + } + + if (fragmentString != "") { + GLuint shader = + createShader(fragmentString, GL_FRAGMENT_SHADER, "fragment"); + if (shader == 0u) { + return false; + } + glAttachShader(program, shader); + //std::cerr << "attach fragment shader " << shader << "\n"; + } + + glLinkProgram(program); + GLint link_ok = GL_FALSE; + glGetProgramiv(program, GL_LINK_STATUS, &link_ok); + if (link_ok == 0) { + std::cerr << "ERROR: unable to link program\n"; + printInfoLog(program, "program"); + glDeleteProgram(program); + return false; + } + + m_programId = program; + + m_isValid = true; + + return true; +} + +void +Shader::activate() const +{ + assert(m_isValid); + + glUseProgram(m_programId); +} + +GLint +Shader::getUniformLocation(const char *name) const +{ + assert(m_isValid); + + return glGetUniformLocation(m_programId, name); +} + +GLint +Shader::getAttribLocation(const char *name) const +{ + assert(m_isValid); + + return glGetAttribLocation(m_programId, name); +} + +void +Shader::setSamplerUnit(const char *sampler, int unit) const +{ + assert(m_isValid); + + glUniform1i(getUniformLocation(sampler), unit); +} + +void +Shader::dumpInfos() const +{ + GLint nbAttrs; + glGetProgramiv(m_programId, GL_ACTIVE_ATTRIBUTES, &nbAttrs); + + const size_t SIZE = 1024; + GLchar name[SIZE]; + + GLint size; + GLenum type; + for (GLint i = 0; i < nbAttrs; ++i) { + glGetActiveAttrib(m_programId, i, SIZE, nullptr, &size, &type, name); + std::cerr << "Attrib " << glGetAttribLocation(m_programId, name) << ": " + << name << ", " << size << ", " << type << "\n"; + } +} diff --git a/pool/shard001/C++/0017258_JSONVariantParser.cpp b/pool/shard001/C++/0017258_JSONVariantParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a690df397b8d35c0ea32f96c780bbb784344c24b --- /dev/null +++ b/pool/shard001/C++/0017258_JSONVariantParser.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (C) 2005-2015 Team Kodi + * http://kodi.tv + * + * 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 Kodi; see the file COPYING. If not, see + * . + * + */ + +#include "JSONVariantParser.h" + +#include + +class CJSONVariantParserHandler +{ +public: + CJSONVariantParserHandler(CVariant& parsedObject); + + bool Null(); + bool Bool(bool b); + bool Int(int i); + bool Uint(unsigned u); + bool Int64(int64_t i); + bool Uint64(uint64_t u); + bool Double(double d); + bool RawNumber(const char* str, rapidjson::SizeType length, bool copy); + bool String(const char* str, rapidjson::SizeType length, bool copy); + bool StartObject(); + bool Key(const char* str, rapidjson::SizeType length, bool copy); + bool EndObject(rapidjson::SizeType memberCount); + bool StartArray(); + bool EndArray(rapidjson::SizeType elementCount); + +private: + template + bool Primitive(TArgs... args) + { + PushObject(CVariant(std::forward(args)...)); + PopObject(); + + return true; + } + + void PushObject(CVariant variant); + void PopObject(); + + CVariant& m_parsedObject; + std::vector m_parse; + std::string m_key; + + enum class PARSE_STATUS + { + Variable, + Array, + Object + }; + PARSE_STATUS m_status; +}; + +CJSONVariantParserHandler::CJSONVariantParserHandler(CVariant& parsedObject) + : m_parsedObject(parsedObject), + m_parse(), + m_key(), + m_status(PARSE_STATUS::Variable) +{ } + +bool CJSONVariantParserHandler::Null() +{ + PushObject(CVariant::ConstNullVariant); + PopObject(); + + return true; +} + +bool CJSONVariantParserHandler::Bool(bool b) +{ + return Primitive(b); +} + +bool CJSONVariantParserHandler::Int(int i) +{ + return Primitive(i); +} + +bool CJSONVariantParserHandler::Uint(unsigned u) +{ + return Primitive(u); +} + +bool CJSONVariantParserHandler::Int64(int64_t i) +{ + return Primitive(i); +} + +bool CJSONVariantParserHandler::Uint64(uint64_t u) +{ + return Primitive(u); +} + +bool CJSONVariantParserHandler::Double(double d) +{ + return Primitive(d); +} + +bool CJSONVariantParserHandler::RawNumber(const char* str, rapidjson::SizeType length, bool copy) +{ + return Primitive(str, length); +} + +bool CJSONVariantParserHandler::String(const char* str, rapidjson::SizeType length, bool copy) +{ + return Primitive(str, length); +} + +bool CJSONVariantParserHandler::StartObject() +{ + PushObject(CVariant::VariantTypeObject); + + return true; +} + +bool CJSONVariantParserHandler::Key(const char* str, rapidjson::SizeType length, bool copy) +{ + m_key = std::string(str, 0, length); + + return true; +} + +bool CJSONVariantParserHandler::EndObject(rapidjson::SizeType memberCount) +{ + PopObject(); + + return true; +} + +bool CJSONVariantParserHandler::StartArray() +{ + PushObject(CVariant::VariantTypeArray); + + return true; +} + +bool CJSONVariantParserHandler::EndArray(rapidjson::SizeType elementCount) +{ + PopObject(); + + return true; +} + +void CJSONVariantParserHandler::PushObject(CVariant variant) +{ + if (m_status == PARSE_STATUS::Object) + { + (*m_parse[m_parse.size() - 1])[m_key] = variant; + m_parse.push_back(&(*m_parse[m_parse.size() - 1])[m_key]); + } + else if (m_status == PARSE_STATUS::Array) + { + CVariant *temp = m_parse[m_parse.size() - 1]; + temp->push_back(variant); + m_parse.push_back(&(*temp)[temp->size() - 1]); + } + else if (m_parse.empty()) + m_parse.push_back(new CVariant(variant)); + + if (variant.isObject()) + m_status = PARSE_STATUS::Object; + else if (variant.isArray()) + m_status = PARSE_STATUS::Array; + else + m_status = PARSE_STATUS::Variable; +} + +void CJSONVariantParserHandler::PopObject() +{ + CVariant *variant = m_parse[m_parse.size() - 1]; + m_parse.pop_back(); + + if (!m_parse.empty()) + { + variant = m_parse[m_parse.size() - 1]; + if (variant->isObject()) + m_status = PARSE_STATUS::Object; + else if (variant->isArray()) + m_status = PARSE_STATUS::Array; + else + m_status = PARSE_STATUS::Variable; + } + else + { + m_parsedObject = *variant; + delete variant; + + m_status = PARSE_STATUS::Variable; + } +} + +bool CJSONVariantParser::Parse(const char* json, CVariant& data) +{ + if (json == nullptr) + return false; + + rapidjson::Reader reader; + rapidjson::StringStream stringStream(json); + + CJSONVariantParserHandler handler(data); + if (reader.Parse(stringStream, handler)) + return true; + + return false; +} + +bool CJSONVariantParser::Parse(const std::string& json, CVariant& data) +{ + return Parse(json.c_str(), data); +} diff --git a/pool/shard001/C++/0017268_qxsdschematypesfactory.cpp b/pool/shard001/C++/0017268_qxsdschematypesfactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89eff3fee25db908e59ac42a35ed037c58088a16 --- /dev/null +++ b/pool/shard001/C++/0017268_qxsdschematypesfactory.cpp @@ -0,0 +1,126 @@ +/**************************************************************************** +** +** Copyright (C) 2014 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 "qxsdschematypesfactory_p.h" + +#include "qbasictypesfactory_p.h" +#include "qbuiltintypes_p.h" +#include "qderivedinteger_p.h" +#include "qderivedstring_p.h" +#include "qcommonnamespaces_p.h" +#include "qxsdschematoken_p.h" +#include "qxsdsimpletype_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +XsdSchemaTypesFactory::XsdSchemaTypesFactory(const NamePool::Ptr &namePool) + : m_namePool(namePool) +{ + m_types.reserve(3); + + const XsdFacet::Ptr whiteSpaceFacet(new XsdFacet()); + whiteSpaceFacet->setType(XsdFacet::WhiteSpace); + whiteSpaceFacet->setFixed(true); + whiteSpaceFacet->setValue(DerivedString::fromLexical(m_namePool, XsdSchemaToken::toString(XsdSchemaToken::Collapse))); + + const XsdFacet::Ptr minLengthFacet(new XsdFacet()); + minLengthFacet->setType(XsdFacet::MinimumLength); + minLengthFacet->setValue(DerivedInteger::fromLexical(namePool, QLatin1String("1"))); + + XsdFacet::Hash facets; + facets.insert(whiteSpaceFacet->type(), whiteSpaceFacet); + facets.insert(minLengthFacet->type(), minLengthFacet); + + { + const QXmlName typeName = m_namePool->allocateQName(CommonNamespaces::WXS, QLatin1String("NMTOKENS")); + const XsdSimpleType::Ptr type(new XsdSimpleType()); + type->setName(typeName); + type->setWxsSuperType(BuiltinTypes::xsAnySimpleType); + type->setCategory(XsdSimpleType::SimpleTypeList); + type->setItemType(BuiltinTypes::xsNMTOKEN); + type->setDerivationMethod(XsdSimpleType::DerivationRestriction); + type->setFacets(facets); + m_types.insert(typeName, type); + } + { + const QXmlName typeName = m_namePool->allocateQName(CommonNamespaces::WXS, QLatin1String("IDREFS")); + const XsdSimpleType::Ptr type(new XsdSimpleType()); + type->setName(typeName); + type->setWxsSuperType(BuiltinTypes::xsAnySimpleType); + type->setCategory(XsdSimpleType::SimpleTypeList); + type->setItemType(BuiltinTypes::xsIDREF); + type->setDerivationMethod(XsdSimpleType::DerivationRestriction); + type->setFacets(facets); + m_types.insert(typeName, type); + } + { + const QXmlName typeName = m_namePool->allocateQName(CommonNamespaces::WXS, QLatin1String("ENTITIES")); + const XsdSimpleType::Ptr type(new XsdSimpleType()); + type->setName(typeName); + type->setWxsSuperType(BuiltinTypes::xsAnySimpleType); + type->setCategory(XsdSimpleType::SimpleTypeList); + type->setItemType(BuiltinTypes::xsENTITY); + type->setDerivationMethod(XsdSimpleType::DerivationRestriction); + type->setFacets(facets); + m_types.insert(typeName, type); + } +} + +SchemaType::Ptr XsdSchemaTypesFactory::createSchemaType(const QXmlName name) const +{ + if (m_types.contains(name)) { + return m_types.value(name); + } else { + if (!m_basicTypesFactory) + m_basicTypesFactory = BasicTypesFactory::self(m_namePool); + + return m_basicTypesFactory->createSchemaType(name); + } +} + +SchemaType::Hash XsdSchemaTypesFactory::types() const +{ + return m_types; +} + +QT_END_NAMESPACE diff --git a/pool/shard001/C++/0017271_board_difference.cc b/pool/shard001/C++/0017271_board_difference.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b6553b57602da0438d684406c03c2aa694900be --- /dev/null +++ b/pool/shard001/C++/0017271_board_difference.cc @@ -0,0 +1,30 @@ +#include "board_difference.h" + +namespace foolgo { + +void BoardDifference::ModifyToCurrentState( + PositionIndex ko_position_index, PositionIndex move_position_index, + bool is_last_move_suicide, + const std::vector &removed_pieces_index) { + last_force_difference_.current_state = OppositeForce( + last_force_difference_.old_state); + ko_index_difference_.current_state = ko_position_index; + int removed_pieces_count = removed_pieces_index.size(); + indexes_difference_.resize(removed_pieces_count + 1); + + PointState removed_pieces_color = + is_last_move_suicide ? + last_force_difference_.current_state : + last_force_difference_.old_state; + + for (int i = 0; i < removed_pieces_count; ++i) { + PositionIndex removed_index = removed_pieces_index[i]; + indexes_difference_[i].Init(removed_index, removed_pieces_color, + EMPTY_POINT); + } + + indexes_difference_[removed_pieces_count].Init( + move_position_index, EMPTY_POINT, last_force_difference_.current_state); +} + +} diff --git a/pool/shard001/C++/0017283_bitcoin-cli.cpp b/pool/shard001/C++/0017283_bitcoin-cli.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b6f14a9f3f6561c2e288d58423716b5ec9a2d39 --- /dev/null +++ b/pool/shard001/C++/0017283_bitcoin-cli.cpp @@ -0,0 +1,87 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "util.h" +#include "init.h" +#include "rpcclient.h" +#include "rpcprotocol.h" +#include "ui_interface.h" /* for _(...) */ +#include "chainparams.h" + +#include + +////////////////////////////////////////////////////////////////////////////// +// +// Start +// +static bool AppInitRPC(int argc, char* argv[]) +{ + // + // Parameters + // + ParseParameters(argc, argv); + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); + return false; + } + try { + ReadConfigFile(mapArgs, mapMultiArgs); + } catch(std::exception &e) { + fprintf(stderr,"Error reading configuration file: %s\n", e.what()); + return false; + } + // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause) + if (!SelectParamsFromCommandLine()) { + fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + return false; + } + + if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help")) + { + // First part of help message is specific to RPC client + std::string strUsage = _("UnattainiumV2 Core RPC client version") + " " + FormatFullVersion() + "\n\n" + + _("Usage:") + "\n" + + " XXname-cliXX [options] [params] " + _("Send command to UnattainiumV2 Core") + "\n" + + " XXname-cliXX [options] help " + _("List commands") + "\n" + + " XXname-cliXX [options] help " + _("Get help for a command") + "\n"; + + strUsage += "\n" + HelpMessageCli(true); + + fprintf(stdout, "%s", strUsage.c_str()); + return false; + } + return true; +} + +int main(int argc, char* argv[]) +{ + SetupEnvironment(); + + try + { + if(!AppInitRPC(argc, argv)) + return abs(RPC_MISC_ERROR); + } + catch (std::exception& e) { + PrintExceptionContinue(&e, "AppInitRPC()"); + return abs(RPC_MISC_ERROR); + } catch (...) { + PrintExceptionContinue(NULL, "AppInitRPC()"); + return abs(RPC_MISC_ERROR); + } + + int ret = abs(RPC_MISC_ERROR); + try + { + ret = CommandLineRPC(argc, argv); + } + catch (std::exception& e) { + PrintExceptionContinue(&e, "CommandLineRPC()"); + } catch (...) { + PrintExceptionContinue(NULL, "CommandLineRPC()"); + } + return ret; +} diff --git a/pool/shard001/C++/0017284_consoleLogger.cpp b/pool/shard001/C++/0017284_consoleLogger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc2095eae7434c25980d7bdb1481eeae2676e633 --- /dev/null +++ b/pool/shard001/C++/0017284_consoleLogger.cpp @@ -0,0 +1,268 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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 "console/consoleLogger.h" +#include "console/consoleTypes.h" +#include "console/engineAPI.h" + +Vector ConsoleLogger::mActiveLoggers; +bool ConsoleLogger::smInitialized = false; + +IMPLEMENT_CONOBJECT( ConsoleLogger ); +ConsoleDocClass( ConsoleLogger, + "A class designed to be used as a console consumer and log the data it receives to a file.\n\n" + + "@see dumpConsoleFunctions\n" + "@see dumpConsoleClasses\n" + "@ingroup Logging\n" +); +//----------------------------------------------------------------------------- + +ConsoleLogger::ConsoleLogger() +{ + mFilename = NULL; + mLogging = false; + mAppend = false; + + mLevel = ConsoleLogEntry::Normal; +} + +//----------------------------------------------------------------------------- + +ConsoleLogger::ConsoleLogger( const char *fileName, bool append ) +{ + mLogging = false; + + mLevel = ConsoleLogEntry::Normal; + mFilename = StringTable->insert( fileName ); + mAppend = append; + + init(); +} + +//----------------------------------------------------------------------------- + +ImplementEnumType( LogLevel, + "@brief Priority levels for logging entries\n\n" + "@ingroup Logging") + { ConsoleLogEntry::Normal, "normal", "Lowest priority level, no highlighting." }, + { ConsoleLogEntry::Warning, "warning", "Mid level priority, tags and highlights possible issues in blue." }, + { ConsoleLogEntry::Error, "error", "Highest priority level, extreme emphasis on this entry. Highlighted in red." }, +EndImplementEnumType; + +void ConsoleLogger::initPersistFields() +{ + addGroup( "Logging" ); + addField( "level", TYPEID< ConsoleLogEntry::Level >(), Offset( mLevel, ConsoleLogger ), "Determines the priority level and attention the logged entry gets when recorded\n\n" ); + endGroup( "Logging" ); + + Parent::initPersistFields(); +} + +//----------------------------------------------------------------------------- + +bool ConsoleLogger::processArguments( S32 argc, ConsoleValueRef *argv ) +{ + if( argc == 0 ) + return false; + + bool append = false; + + if( argc == 2 ) + append = dAtob( argv[1] ); + + mAppend = append; + mFilename = StringTable->insert( argv[0] ); + + if( init() ) + { + attach(); + return true; + } + + return false; +} + +//----------------------------------------------------------------------------- + +ConsoleLogger::~ConsoleLogger() +{ + detach(); +} + +//----------------------------------------------------------------------------- + +bool ConsoleLogger::init() +{ + if( smInitialized ) + return true; + + Con::addConsumer( ConsoleLogger::logCallback ); + smInitialized = true; + + return true; +} + +//----------------------------------------------------------------------------- + +bool ConsoleLogger::attach() +{ + if( mFilename == NULL ) + { + Con::errorf( "ConsoleLogger failed to attach: no filename supplied." ); + return false; + } + + // Check to see if this is initialized before using it + if( !smInitialized ) + { + if( !init() ) + { + Con::errorf( "ConsoleLogger failed to initalize." ); + return false; + } + } + + if( mLogging ) + return false; + + // Open the filestream + mStream.open( mFilename, ( mAppend ? Torque::FS::File::WriteAppend : Torque::FS::File::Write ) ); + + // Add this to list of active loggers + mActiveLoggers.push_back( this ); + mLogging = true; + + return true; +} + +//----------------------------------------------------------------------------- + +bool ConsoleLogger::detach() +{ + + // Make sure this is valid before messing with it + if( !smInitialized ) + { + if( !init() ) + { + return false; + } + } + + if( !mLogging ) + return false; + + // Close filestream + mStream.close(); + + // Remove this object from the list of active loggers + for( S32 i = 0; i < mActiveLoggers.size(); i++ ) + { + if( mActiveLoggers[i] == this ) + { + mActiveLoggers.erase( i ); + mLogging = false; + return true; + } + } + + return false; // If this happens, it's bad... +} + +//----------------------------------------------------------------------------- + +void ConsoleLogger::logCallback( U32 level, const char *consoleLine ) +{ + + ConsoleLogger *curr; + + // Loop through active consumers and send them the message + for( int i = 0; i < mActiveLoggers.size(); i++ ) + { + curr = mActiveLoggers[i]; + + // If the log level is within the log threshhold, log it + if( curr->mLevel <= level ) + curr->log( consoleLine ); + } +} + +//----------------------------------------------------------------------------- + +void ConsoleLogger::log( const char *consoleLine ) +{ + // Check to see if this is intalized before using it + if( !smInitialized ) + { + if( !init() ) + { + Con::errorf( "I don't know how this happened, but log called on this without it being initialized" ); + return; + } + } + + mStream.writeLine( (U8 *)consoleLine ); +} + +//----------------------------------------------------------------------------- + +DefineEngineMethod( ConsoleLogger, attach, bool, (), , "() Attaches the logger to the console and begins writing to file" + "@tsexample\n" + "// Create the logger\n" + "// Will automatically start writing to testLogging.txt with normal priority\n" + "new ConsoleLogger(logger, \"testLogging.txt\", false);\n\n" + "// Send something to the console, with the logger consumes and writes to file\n" + "echo(\"This is logged to the file\");\n\n" + "// Stop logging, but do not delete the logger\n" + "logger.detach();\n\n" + "echo(\"This is not logged to the file\");\n\n" + "// Attach the logger to the console again\n" + "logger.attach();\n\n" + "// Logging has resumed\n" + "echo(\"Logging has resumed\");" + "@endtsexample\n\n") +{ + ConsoleLogger *logger = static_cast( object ); + return logger->attach(); +} + +//----------------------------------------------------------------------------- + +DefineEngineMethod( ConsoleLogger, detach, bool, (), , "() Detaches the logger from the console and stops writing to file" + "@tsexample\n" + "// Create the logger\n" + "// Will automatically start writing to testLogging.txt with normal priority\n" + "new ConsoleLogger(logger, \"testLogging.txt\", false);\n\n" + "// Send something to the console, with the logger consumes and writes to file\n" + "echo(\"This is logged to the file\");\n\n" + "// Stop logging, but do not delete the logger\n" + "logger.detach();\n\n" + "echo(\"This is not logged to the file\");\n\n" + "// Attach the logger to the console again\n" + "logger.attach();\n\n" + "// Logging has resumed\n" + "echo(\"Logging has resumed\");" + "@endtsexample\n\n") +{ + ConsoleLogger *logger = static_cast( object ); + return logger->detach(); +} diff --git a/pool/shard001/C++/0017292_main.cpp b/pool/shard001/C++/0017292_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df48fc3eeb2f188220e85578d1edc97415ccda9d --- /dev/null +++ b/pool/shard001/C++/0017292_main.cpp @@ -0,0 +1,34 @@ +#include +#include "StringUtil.hpp" +#include "Format.hpp" + +int main() +{ + std::string str = "Hello world"; + std::cout << StringUtil::trimLeft(str, "Hello") << std::endl; + std::cout << StringUtil::trimRight(str, "world") << std::endl; + str = " nihao "; + std::cout << StringUtil::trim(str) << std::endl; + std::cout << StringUtil::toUpper(str) << std::endl; + std::cout << StringUtil::toLower(StringUtil::toUpper(str)) << std::endl; + str = "Hello world"; + std::cout << StringUtil::startsWith(str, "Hello") << std::endl; + std::cout << StringUtil::endsWith(str, "a") << std::endl; + std::vector result = StringUtil::split(str, " "); + for (auto& iter : result) + { + std::cout << iter << std::endl; + } + + try + { + std::string str = "a = {0}, b = {1}"; + std::cout << format(const_cast(str.c_str()), 10.23, 200) << std::endl; + } + catch (std::exception& e) + { + std::cout << e.what() << std::endl; + } + + return 0; +} diff --git a/pool/shard001/C++/0017296_prediction_component.cc b/pool/shard001/C++/0017296_prediction_component.cc new file mode 100644 index 0000000000000000000000000000000000000000..ffee79e76cf7a82f3d4620edc31888b8c8501244 --- /dev/null +++ b/pool/shard001/C++/0017296_prediction_component.cc @@ -0,0 +1,184 @@ +/****************************************************************************** + * Copyright 2018 The Apollo Authors. 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. + *****************************************************************************/ + +#include "modules/prediction/prediction_component.h" + +#include +#include + +#include "cyber/common/file.h" +#include "cyber/record/record_reader.h" +#include "modules/common/adapters/adapter_gflags.h" +#include "modules/common/util/message_util.h" + +#include "modules/prediction/common/feature_output.h" +#include "modules/prediction/common/junction_analyzer.h" +#include "modules/prediction/common/prediction_gflags.h" +#include "modules/prediction/common/prediction_system_gflags.h" +#include "modules/prediction/common/validation_checker.h" +#include "modules/prediction/evaluator/evaluator_manager.h" +#include "modules/prediction/predictor/predictor_manager.h" +#include "modules/prediction/proto/offline_features.pb.h" +#include "modules/prediction/scenario/scenario_manager.h" +#include "modules/prediction/util/data_extraction.h" + +namespace apollo { +namespace prediction { + +using apollo::common::adapter::AdapterConfig; +using apollo::common::time::Clock; +using apollo::localization::LocalizationEstimate; +using apollo::perception::PerceptionObstacle; +using apollo::perception::PerceptionObstacles; +using apollo::planning::ADCTrajectory; + +PredictionComponent::~PredictionComponent() {} + +std::string PredictionComponent::Name() const { + return FLAGS_prediction_module_name; +} + +void PredictionComponent::OfflineProcessFeatureProtoFile( + const std::string& features_proto_file_name) { + auto obstacles_container_ptr = + ContainerManager::Instance()->GetContainer( + AdapterConfig::PERCEPTION_OBSTACLES); + obstacles_container_ptr->Clear(); + Features features; + apollo::cyber::common::GetProtoFromBinaryFile(features_proto_file_name, + &features); + for (const Feature& feature : features.feature()) { + obstacles_container_ptr->InsertFeatureProto(feature); + Obstacle* obstacle_ptr = obstacles_container_ptr->GetObstacle(feature.id()); + EvaluatorManager::Instance()->EvaluateObstacle(obstacle_ptr); + } +} + +bool PredictionComponent::Init() { + component_start_time_ = Clock::NowInSeconds(); + + if (!MessageProcess::Init()) { + return false; + } + + planning_reader_ = node_->CreateReader( + FLAGS_planning_trajectory_topic, nullptr); + + localization_reader_ = + node_->CreateReader( + FLAGS_localization_topic, nullptr); + + prediction_writer_ = + node_->CreateWriter(FLAGS_prediction_topic); + + return true; +} + +bool PredictionComponent::Proc( + const std::shared_ptr& perception_obstacles) { + if (FLAGS_prediction_test_mode && + (Clock::NowInSeconds() - component_start_time_ > + FLAGS_prediction_test_duration)) { + ADEBUG << "Prediction finished running in test mode"; + } + + // Update relative map if needed + if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) { + AERROR << "Relative map is empty."; + return false; + } + + frame_start_time_ = Clock::NowInSeconds(); + auto end_time1 = std::chrono::system_clock::now(); + + // Read localization info. and call OnLocalization to update + // the PoseContainer. + localization_reader_->Observe(); + auto ptr_localization_msg = localization_reader_->GetLatestObserved(); + if (ptr_localization_msg == nullptr) { + AERROR << "Prediction: cannot receive any localization message."; + return false; + } + auto localization_msg = *ptr_localization_msg; + MessageProcess::OnLocalization(localization_msg); + auto end_time2 = std::chrono::system_clock::now(); + std::chrono::duration diff = end_time2 - end_time1; + ADEBUG << "Time for updating PoseContainer: " << diff.count() * 1000 + << " msec."; + + // Read planning info. of last frame and call OnPlanning to update + // the ADCTrajectoryContainer + planning_reader_->Observe(); + auto ptr_trajectory_msg = planning_reader_->GetLatestObserved(); + if (ptr_trajectory_msg != nullptr) { + auto trajectory_msg = *ptr_trajectory_msg; + MessageProcess::OnPlanning(trajectory_msg); + } + auto end_time3 = std::chrono::system_clock::now(); + diff = end_time3 - end_time2; + ADEBUG << "Time for updating ADCTrajectoryContainer: " << diff.count() * 1000 + << " msec."; + + // Get all perception_obstacles of this frame and call OnPerception to + // process them all. + auto perception_msg = *perception_obstacles; + PredictionObstacles prediction_obstacles; + MessageProcess::OnPerception(perception_msg, &prediction_obstacles); + auto end_time4 = std::chrono::system_clock::now(); + diff = end_time4 - end_time3; + ADEBUG << "Time for updating PerceptionContainer: " << diff.count() * 1000 + << " msec."; + + // Postprocess prediction obstacles message + prediction_obstacles.set_start_timestamp(frame_start_time_); + prediction_obstacles.set_end_timestamp(Clock::NowInSeconds()); + prediction_obstacles.mutable_header()->set_lidar_timestamp( + perception_msg.header().lidar_timestamp()); + prediction_obstacles.mutable_header()->set_camera_timestamp( + perception_msg.header().camera_timestamp()); + prediction_obstacles.mutable_header()->set_radar_timestamp( + perception_msg.header().radar_timestamp()); + + prediction_obstacles.set_perception_error_code(perception_msg.error_code()); + + if (FLAGS_prediction_test_mode) { + for (auto const& prediction_obstacle : + prediction_obstacles.prediction_obstacle()) { + for (auto const& trajectory : prediction_obstacle.trajectory()) { + for (auto const& trajectory_point : trajectory.trajectory_point()) { + if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) { + AERROR << "Invalid trajectory point [" + << trajectory_point.ShortDebugString() << "]"; + break; + } + } + } + } + } + + auto end_time5 = std::chrono::system_clock::now(); + diff = end_time5 - end_time1; + ADEBUG << "End to end time elapsed: " << diff.count() * 1000 << " msec."; + + // Publish output + common::util::FillHeader(node_->Name(), &prediction_obstacles); + prediction_writer_->Write( + std::make_shared(prediction_obstacles)); + return true; +} + +} // namespace prediction +} // namespace apollo diff --git a/pool/shard001/C++/0017298_ap_gen.cpp b/pool/shard001/C++/0017298_ap_gen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac941216d4ee09cd3a0260feabefc70ded3080db --- /dev/null +++ b/pool/shard001/C++/0017298_ap_gen.cpp @@ -0,0 +1,144 @@ +/* +Provided by IBEX UK LTD http://www.ibexuk.com +Electronic Product Design Specialists +RELEASED SOFTWARE + +The MIT License (MIT) + +Copyright (c) 2013, IBEX UK Ltd, http://ibexuk.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. +*/ +//Visit http://www.arduino-developer.com/arduino/ide/arduino-ide/arduino-for-c-programmers for more information +// +//Project Name: Arduino Template Project Example + + + +#include + + +#include "global.h" //Global definitions +#define GEN_C //Define for my header file +#include "ap_gen.h" //My header file + +//Header file used by this file: +#include "ap__main.h" + + + + + +//*********************************** +//*********************************** +//********** READ SWITCHES ********** +//*********************************** +//*********************************** +void read_switches (void) +{ + BYTE switches_1_read; + static BYTE switches_1_last = 0; + static BYTE switches_1_debounced_last = 0; + + //RESET THE NEW SWITCH PRESS REGISTER + switches_1_new = 0; + + //GET THE SWITCH INPUTS + switches_1_read = 0; + //if (!digitalRead(5)) + // switches_1_read |= 0x01; + //if (!digitalRead(4)) + // switches_1_read |= 0x02; + //if (!digitalRead(3)) + // switches_1_read |= 0x04; + + //DEBOUNCE + switches_1_debounced = switches_1_last & switches_1_read; + + //FLAG NEW BUTTON PRESSES + switches_1_new = switches_1_debounced ^ switches_1_debounced_last; + switches_1_new &= switches_1_debounced; + + //STORE LAST REGISTERS FOR NEXT TIME + switches_1_debounced_last = switches_1_debounced; + switches_1_last = switches_1_read; +} + + + + + +//*************************************** +//*************************************** +//********** READ NON VOLATILE ********** +//*************************************** +//*************************************** +#define EEPROM_FACTORY_START_SIGNATURE 0x55 + +void read_non_volatile (void) +{ + BYTE value; + BYTE address; + + value = EEPROM.read(0); + if (value != EEPROM_FACTORY_START_SIGNATURE) + { + //------------------------------------------------ + //----- FACTORY START - STORE DEFAULT VALUES ----- + //------------------------------------------------ + + //>>>>>>>>>> + address = 1; + //EEPROM.write(address++, 0x00); + //EEPROM.write(address++, 0x00); + //<<<<<<<<<< + + //Store the factory start done signature + EEPROM.write(0, EEPROM_FACTORY_START_SIGNATURE); + } + + //>>>>>>>>>> + address = 1; + // = EEPROM.read(address++); + // = EEPROM.read(address++); + //<<<<<<<<<< +} + + +//**************************************** +//**************************************** +//********** STORE NON VOLATILE ********** +//**************************************** +//**************************************** +void write_non_volatile (void) +{ + BYTE value; + BYTE address; + + //>>>>>>>>>> + address = 1; + //EEPROM.write(address++, ); + //EEPROM.write(address++, ); + //<<<<<<<<<< +} + + + + + + diff --git a/pool/shard001/C++/0017299_Messages.cpp b/pool/shard001/C++/0017299_Messages.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a25aef76e2505b2acf8a9ca5e70ef726b449156d --- /dev/null +++ b/pool/shard001/C++/0017299_Messages.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. + * All rights reserved. Use is subject to license terms. + * + * This file is available and licensed under the following license: + * + * 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 Oracle 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 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 "Messages.h" +#include "Platform.h" +#include "Lock.h" +#include "FilePath.h" +#include "Helpers.h" +#include "Macros.h" +#include "JavaVirtualMachine.h" + + +Messages::Messages(void) { + FMessages.SetReadOnly(false); + FMessages.SetValue(LIBRARY_NOT_FOUND, _T("Failed to find library.")); + FMessages.SetValue(FAILED_CREATING_JVM, _T("Failed to create JVM")); + FMessages.SetValue(FAILED_LOCATING_JVM_ENTRY_POINT, _T("Failed to locate JLI_Launch")); + FMessages.SetValue(NO_MAIN_CLASS_SPECIFIED, _T("No main class specified")); + FMessages.SetValue(METHOD_NOT_FOUND, _T("No method %s in class %s.")); + FMessages.SetValue(CLASS_NOT_FOUND, _T("Class %s not found.")); + FMessages.SetValue(ERROR_INVOKING_METHOD, _T("Error invoking method.")); + //FMessages.SetValue(CONFIG_FILE_NOT_FOUND, _T("Configuration file %s is not found.")); + //FMessages.SetValue(BUNDLED_JVM_NOT_FOUND, _T("$JAVAVMLIBRARYNAME is not found in the bundled runtime.")); + FMessages.SetValue(APPCDS_CACHE_FILE_NOT_FOUND, _T("Error: AppCDS cache does not exists:\n%s\n")); +} + +Messages& Messages::GetInstance() { + //Lock lock; + static Messages instance; // Guaranteed to be destroyed. Instantiated on first use. + return instance; +} + +Messages::~Messages(void) { +} + +TString Messages::GetMessage(const TString Key) { + TString result; + FMessages.GetValue(Key, result); + Macros& macros = Macros::GetInstance(); + result = macros.ExpandMacros(result); + return result; +} diff --git a/pool/shard001/C++/0017308_vtkMDLineFactory.cpp b/pool/shard001/C++/0017308_vtkMDLineFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3379a5bf4a51a0d2e2d2ed3cc3b3c96e7aba6c42 --- /dev/null +++ b/pool/shard001/C++/0017308_vtkMDLineFactory.cpp @@ -0,0 +1,189 @@ +#include "MantidVatesAPI/vtkMDLineFactory.h" +#include "MantidVatesAPI/Common.h" +#include "MantidVatesAPI/ProgressAction.h" +#include "MantidVatesAPI/vtkNullUnstructuredGrid.h" +#include "MantidAPI/IMDWorkspace.h" +#include "MantidAPI/IMDEventWorkspace.h" +#include "MantidAPI/IMDIterator.h" +#include "MantidAPI/CoordTransform.h" +#include +#include +#include +#include +#include +#include +#include +#include "MantidKernel/ReadLock.h" +#include "MantidKernel/Logger.h" +#include "MantidKernel/make_unique.h" + +#include + +using namespace Mantid::API; + +namespace { +Mantid::Kernel::Logger g_log("vtkMDLineFactory"); +} + +namespace Mantid { +namespace VATES { +/** +Constructor +@param normalizationOption : Normalization option to use +*/ +vtkMDLineFactory::vtkMDLineFactory( + const VisualNormalization normalizationOption) + : m_normalizationOption(normalizationOption) {} + +/// Destructor +vtkMDLineFactory::~vtkMDLineFactory() {} + +/** +Create the vtkStructuredGrid from the provided workspace +@param progressUpdating: Reporting object to pass progress information up the +stack. +@return fully constructed vtkDataSet. +*/ +vtkSmartPointer +vtkMDLineFactory::create(ProgressAction &progressUpdating) const { + auto product = tryDelegatingCreation(m_workspace, + progressUpdating); + if (product != nullptr) { + return product; + } else { + g_log.warning() << "Factory " << this->getFactoryTypeName() + << " is being used. You are viewing data with less than " + "three dimensions in the VSI. \n"; + + IMDEventWorkspace_sptr imdws = + doInitialize(m_workspace); + // Acquire a scoped read-only lock to the workspace (prevent segfault from + // algos modifying ws) + Mantid::Kernel::ReadLock lock(*imdws); + + const size_t nDims = imdws->getNumDims(); + size_t nNonIntegrated = imdws->getNonIntegratedDimensions().size(); + + /* + Write mask array with correct order for each internal dimension. + */ + auto masks = Mantid::Kernel::make_unique(nDims); + for (size_t i_dim = 0; i_dim < nDims; ++i_dim) { + bool bIntegrated = imdws->getDimension(i_dim)->getIsIntegrated(); + masks[i_dim] = + !bIntegrated; // TRUE for unmaksed, integrated dimensions are masked. + } + + // Ensure destruction in any event. + boost::scoped_ptr it( + createIteratorWithNormalization(m_normalizationOption, imdws.get())); + + // Create 2 points per box. + vtkNew points; + points->SetNumberOfPoints(it->getDataSize() * 2); + + // One scalar per box + vtkNew signals; + signals->Allocate(it->getDataSize()); + signals->SetName(vtkDataSetFactory::ScalarName.c_str()); + signals->SetNumberOfComponents(1); + + size_t nVertexes; + + auto visualDataSet = vtkSmartPointer::New(); + visualDataSet->Allocate(it->getDataSize()); + + vtkNew linePointList; + linePointList->SetNumberOfIds(2); + + Mantid::API::CoordTransform const *transform = nullptr; + if (m_useTransform) { + transform = imdws->getTransformToOriginal(); + } + + Mantid::coord_t out[1]; + auto useBox = std::vector(it->getDataSize()); + + double progressFactor = 0.5 / double(it->getDataSize()); + double progressOffset = 0.5; + + size_t iBox = 0; + do { + progressUpdating.eventRaised(double(iBox) * progressFactor); + + Mantid::signal_t signal_normalized = it->getNormalizedSignal(); + if (std::isfinite(signal_normalized)) { + useBox[iBox] = true; + signals->InsertNextValue(static_cast(signal_normalized)); + + auto coords = std::unique_ptr( + it->getVertexesArray(nVertexes, nNonIntegrated, masks.get())); + + // Iterate through all coordinates. Candidate for speed improvement. + for (size_t v = 0; v < nVertexes; ++v) { + coord_t *coord = coords.get() + v * 1; + size_t id = iBox * 2 + v; + if (m_useTransform) { + transform->apply(coord, out); + points->SetPoint(id, out[0], 0, 0); + } else { + points->SetPoint(id, coord[0], 0, 0); + } + } + } // valid number of vertexes returned + else { + useBox[iBox] = false; + } + ++iBox; + } while (it->next()); + + for (size_t ii = 0; ii < it->getDataSize(); ++ii) { + progressUpdating.eventRaised((double(ii) * progressFactor) + + progressOffset); + + if (useBox[ii] == true) { + vtkIdType pointIds = ii * 2; + + linePointList->SetId(0, pointIds + 0); // xyx + linePointList->SetId(1, pointIds + 1); // dxyz + visualDataSet->InsertNextCell(VTK_LINE, linePointList.GetPointer()); + } // valid number of vertexes returned + } + + signals->Squeeze(); + points->Squeeze(); + + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signals.GetPointer()); + visualDataSet->Squeeze(); + + // Hedge against empty data sets + if (visualDataSet->GetNumberOfPoints() <= 0) { + vtkNullUnstructuredGrid nullGrid; + visualDataSet = nullGrid.createNullData(); + } + + vtkSmartPointer dataset = visualDataSet; + return dataset; + } +} + +/// Initalize with a target workspace. +void vtkMDLineFactory::initialize(const Mantid::API::Workspace_sptr &ws) { + m_workspace = doInitialize(ws); +} + +/// Get the name of the type. +std::string vtkMDLineFactory::getFactoryTypeName() const { + return "vtkMDLineFactory"; +} + +/// Template Method pattern to validate the factory before use. +void vtkMDLineFactory::validate() const { + if (!m_workspace) { + throw std::runtime_error( + "vtkMDLineFactory has no workspace to run against"); + } +} +} +} diff --git a/pool/shard001/C++/0017310_Crypto.cpp b/pool/shard001/C++/0017310_Crypto.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46d126f66986b1bbf60a1333998bfb4cd81af848 --- /dev/null +++ b/pool/shard001/C++/0017310_Crypto.cpp @@ -0,0 +1,170 @@ +/* +This file is a part of MonaSolutions Copyright 2017 +mathieu.poux[a]gmail.com +jammetthomas[a]gmail.com + +This program is free software: you can redistribute it and/or +modify it under the terms of the the Mozilla Public License v2.0. + +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 +Mozilla Public License v. 2.0 received along this program for more +details (or else see http://mozilla.org/MPL/2.0/). + +*/ + +#include "Base/Crypto.h" + +using namespace std; + +namespace Base { + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +static HMAC_CTX* HMAC_CTX_new() { + HMAC_CTX* ctx = new HMAC_CTX(); + HMAC_CTX_init(ctx); + return ctx; +} +static void HMAC_CTX_free(HMAC_CTX* ctx) { + HMAC_CTX_cleanup(ctx); + delete ctx; +} +#define EVP_MD_CTX_new EVP_MD_CTX_create +#define EVP_MD_CTX_free EVP_MD_CTX_destroy +#endif + +UInt8 Crypto::Rotate8(UInt8 value) { + value = ((value >> 1) & 0x5555) | ((value & 0x5555) << 1); + value = ((value >> 2) & 0x3333) | ((value & 0x3333) << 2); + return (value >> 4) | (value << 4); +} +UInt16 Crypto::Rotate16(UInt16 value) { + value = ((value >> 1) & 0x5555) | ((value & 0x5555) << 1); + value = ((value >> 2) & 0x3333) | ((value & 0x3333) << 2); + value = ((value >> 4) & 0x0F0F) | ((value & 0x0F0F) << 4); + return (value >> 8) | (value << 8); +} +UInt32 Crypto::Rotate24(UInt32 value) { + value = ((value >> 1) & 0x00555555) | ((value & 0x00555555) << 1); + value = ((value >> 2) & 0x00333333) | ((value & 0x00333333) << 2); + value = ((value >> 4) & 0x000F0F0F) | ((value & 0x000F0F0F) << 4); + return Byte::Flip24(value); +} +UInt32 Crypto::Rotate32(UInt32 value) { + value = ((value >> 1) & 0x55555555) | ((value & 0x55555555) << 1); // swap odd and even bits + value = ((value >> 2) & 0x33333333) | ((value & 0x33333333) << 2); // swap consecutive pairs + value = ((value >> 4) & 0x0F0F0F0F) | ((value & 0x0F0F0F0F) << 4); // swap nibbles ... + value = ((value >> 8) & 0x00FF00FF) | ((value & 0x00FF00FF) << 8); // swap bytes + return (value >> 16) | (value << 16); // swap 2-byte long pairs +} +UInt64 Crypto::Rotate64(UInt64 value) { + value = ((value >> 1) & 0x5555555555555555) | ((value & 0x5555555555555555) << 1); + value = ((value >> 2) & 0x3333333333333333) | ((value & 0x3333333333333333) << 2); + value = ((value >> 4) & 0x0F0F0F0F0F0F0F0F) | ((value & 0x0F0F0F0F0F0F0F0F) << 4); + value = ((value >> 8) & 0x00FF00FF00FF00FF) | ((value & 0x00FF00FF00FF00FF) << 8); + value = ((value >> 16) & 0x0000FFFF0000FFFF) | ((value & 0x0000FFFF0000FFFF) << 16); + return (value >> 32) | (value << 32); +} + +UInt8* Crypto::Hash::Compute(const EVP_MD* evp, const void* data, size_t size, UInt8* value) { + thread_local struct CTX { + CTX() : _ctx(EVP_MD_CTX_new()) {} + ~CTX() { EVP_MD_CTX_free(_ctx); } + EVP_MD_CTX* operator&() { return _ctx; } + private: + EVP_MD_CTX* _ctx; + } CTX; + EVP_DigestInit_ex(&CTX, evp, NULL); + EVP_DigestUpdate(&CTX, data, size); + EVP_DigestFinal_ex(&CTX, value, NULL); + return value; +} + +UInt8* Crypto::HMAC::Compute(const EVP_MD* evp, const void* key, int keySize, const void* data, size_t size, UInt8* value) { + thread_local struct CTX { + CTX() : _ctx(HMAC_CTX_new()) {} + ~CTX() { HMAC_CTX_free(_ctx); } + HMAC_CTX* operator&() { return _ctx; } + private: + HMAC_CTX* _ctx; + } CTX; + HMAC_Init_ex(&CTX, key, keySize, evp, NULL); + HMAC_Update(&CTX, BIN data, size); + HMAC_Final(&CTX, value, NULL); + return value; +} + +UInt16 Crypto::ComputeChecksum(BinaryReader& reader) { + UInt32 sum = 0; + UInt32 pos(reader.position()); + while(reader.available()>0) + sum += reader.available()==1 ? reader.read8() : reader.read16(); + reader.reset(pos); + + /* add back carry outs from top 16 bits to low 16 bits */ + sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ + sum += (sum >> 16); /* add carry */ + return ~sum; /* truncate to 16 bits */ +} + + +UInt32 Crypto::ComputeCRC32(const UInt8* data, UInt32 size, ROTATE_OPTIONS options) { + static const UInt32 CRC32[256] = { + 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, + 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, + 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, + 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, + 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, + 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, + 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, + 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, + 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, + 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, + 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, + 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, + 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, + 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, + 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, + 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, + 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, + 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, + 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, + 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, + 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, + 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, + 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, + 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, + 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, + 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, + 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, + 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, + 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, + 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, + 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, + 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, + 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, + 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, + 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, + 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, + 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 + }; + + UInt32 crc(0xffffffff); + for (UInt32 i = 0; i < size; ++i) { + if (options&ROTATE_INPUT) + crc = (crc << 8) ^ CRC32[(crc >> 24) ^ Rotate8(*data++)]; + else + crc = (crc << 8) ^ CRC32[(crc >> 24) ^ *data++]; + } + return options&ROTATE_OUTPUT ? Rotate32(crc) : crc; +} + + +} // namespace Base diff --git a/pool/shard001/C++/0017312_media_param_traits.cc b/pool/shard001/C++/0017312_media_param_traits.cc new file mode 100644 index 0000000000000000000000000000000000000000..43d505e2c213fd2784fa265c0526d434dc7b0660 --- /dev/null +++ b/pool/shard001/C++/0017312_media_param_traits.cc @@ -0,0 +1,90 @@ +// 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 "content/common/media/media_param_traits.h" + +#include "base/strings/stringprintf.h" +#include "media/audio/audio_parameters.h" +#include "media/base/limits.h" +#include "media/video/capture/video_capture_types.h" + +using media::AudioParameters; +using media::ChannelLayout; +using media::VideoCaptureFormat; +using media::VideoPixelFormat; + +namespace IPC { + +void ParamTraits::Write(Message* m, + const AudioParameters& p) { + m->WriteInt(static_cast(p.format())); + m->WriteInt(static_cast(p.channel_layout())); + m->WriteInt(p.sample_rate()); + m->WriteInt(p.bits_per_sample()); + m->WriteInt(p.frames_per_buffer()); + m->WriteInt(p.channels()); + m->WriteInt(p.effects()); +} + +bool ParamTraits::Read(const Message* m, + PickleIterator* iter, + AudioParameters* r) { + int format, channel_layout, sample_rate, bits_per_sample, + frames_per_buffer, channels, effects; + + if (!iter->ReadInt(&format) || + !iter->ReadInt(&channel_layout) || + !iter->ReadInt(&sample_rate) || + !iter->ReadInt(&bits_per_sample) || + !iter->ReadInt(&frames_per_buffer) || + !iter->ReadInt(&channels) || + !iter->ReadInt(&effects)) + return false; + + AudioParameters params(static_cast(format), + static_cast(channel_layout), channels, + sample_rate, bits_per_sample, frames_per_buffer, effects); + *r = params; + if (!r->IsValid()) + return false; + return true; +} + +void ParamTraits::Log(const AudioParameters& p, + std::string* l) { + l->append(base::StringPrintf("")); +} + +void ParamTraits::Write(Message* m, + const VideoCaptureFormat& p) { + // Crash during Send rather than have a failure at the message handler. + m->WriteInt(p.frame_size.width()); + m->WriteInt(p.frame_size.height()); + m->WriteFloat(p.frame_rate); + m->WriteInt(static_cast(p.pixel_format)); +} + +bool ParamTraits::Read(const Message* m, + PickleIterator* iter, + VideoCaptureFormat* r) { + int frame_size_width, frame_size_height, pixel_format; + if (!iter->ReadInt(&frame_size_width) || + !iter->ReadInt(&frame_size_height) || + !iter->ReadFloat(&r->frame_rate) || + !iter->ReadInt(&pixel_format)) + return false; + + r->frame_size.SetSize(frame_size_width, frame_size_height); + r->pixel_format = static_cast(pixel_format); + if (!r->IsValid()) + return false; + return true; +} + +void ParamTraits::Log(const VideoCaptureFormat& p, + std::string* l) { + l->append(base::StringPrintf("")); +} + +} diff --git a/pool/shard001/C++/0017313_cl_precipitation.cpp b/pool/shard001/C++/0017313_cl_precipitation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a40aba1e4c97da62cd3e0530ca84e38dd0151586 --- /dev/null +++ b/pool/shard001/C++/0017313_cl_precipitation.cpp @@ -0,0 +1,170 @@ +#include "cl_precipitation.hpp" +#include "application.hpp" +#include "applicationFlags.hpp" +#include "toolbox.hpp" +#include "world.hpp" +#include "gui.hpp" +#include "spriteutils.hpp" +#include "datastorage.hpp" +#include "cl_blur.hpp" + +CL_Precipitation::CL_Precipitation(std::string s) : CL_Program(s) +{ +} + +void CL_Precipitation::init() +{ + try + { + kernel = cl::Kernel(program, "precipitation", &error); + print_errors("kernel()", error); + } + catch (cl::Error err) + { + std::cout << "-OpenCL Exception: " << err.what() << ", " << err.err() << std::endl; + print_errors("kernel()", error); + } + + + cl::ImageFormat format; + format.image_channel_data_type = CL_FLOAT; + format.image_channel_order = CL_LUMINANCE; + + cl::ImageFormat format2; + format2.image_channel_data_type = CL_FLOAT; + format2.image_channel_order = CL_RGBA; + + int image_size = 1024*1024; + + regions = new float[image_size]; + winds = new float[image_size]; + precipitation = new float[image_size]; + row_pitch = 1024 * sizeof(float); + origin.push_back(0); + origin.push_back(0); + origin.push_back(0); + + region.push_back(1024); + region.push_back(1024); + region.push_back(1); + + int** worldregions = app.getWorld()->getRegionMap(); + auto windsimage = app.getDataStorage()->getImage("windblurred"); + + int count = 0; + for (int y = 0; y < 1024; y++) + { + for (int x = 0; x < 1024; x++) + { + regions[count] = worldregions[x][y]; + winds[count] = windsimage->getPixel(x, y).b / 50.0; + count++; + } + } + + try + { + cl_regions = new cl::Image2D(context, CL_MEM_READ_ONLY, format, 1024, 1024, 0); + cl_winds = new cl::Image2D(context, CL_MEM_READ_ONLY, format, 1024, 1024, 0); + cl_precipitation = new cl::Image2D(context, CL_MEM_WRITE_ONLY, format2, 1024, 1024, 0); + } + catch (cl::Error e) + { + std::cout << "!OpenCL: Error at creating buffers: " << e.what() << ", " << e.err() << std::endl; + } + + try + { + error = commandQueue.enqueueWriteImage(*cl_regions, CL_TRUE, origin, region, row_pitch, 0, (void*) regions); + error = commandQueue.enqueueWriteImage(*cl_winds, CL_TRUE, origin, region, row_pitch, 0, (void*) winds); + } + catch (cl::Error e) + { + std::cout << "!OpenCL: Error pushing data in the device buffers: " << e.what() << ", " << e.err() << std::endl; + print_errors("commandQueue.enqueueWriteBuffer", error); + } + + try + { + error = kernel.setArg(0, *cl_regions); + error = kernel.setArg(1, *cl_winds); + error = kernel.setArg(2, *cl_precipitation); + } + catch (cl::Error err) + { + std::cout << "-OpenCL: Error setting kernel arguments: " << err.what() << ", " << err.err() << std::endl; + print_errors("kernel.setArg", error); + } +} + +void CL_Precipitation::runKernel() +{ + error = commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(1024, 1024), cl::NullRange, NULL, &event); + print_errors("commandQueue.enqueueNDRangeKernel", error); + + commandQueue.finish(); + + float* map_done = new float[1024*1024*4]; + row_pitch = 1024 * 4 * sizeof(float); + error = commandQueue.enqueueReadImage(*cl_precipitation, CL_TRUE, origin, region, row_pitch, 0, map_done); + print_errors("commandQueue.enqueueReadImage", error); + + if (outputTarget == nullptr) + { + delete[] map_done; + return; + } + + app.getSpriteUtils()->setPixels(outputTarget, outputName, map_done, 1024, 1024); + + // Blur rainfall a bit + std::shared_ptr temp = std::dynamic_pointer_cast(app.getProgram("blur")); + temp->setBlurSize(50); + temp->setInputBuffer(map_done); + temp->setOutputTarget(app.getDataStorage()->getSprite("precipitation_blurred"), "precipitation_blurred"); + temp->runKernel(); + temp->resetInputBuffer(); + + + delete[] map_done; +} + +void CL_Precipitation::cleanup() +{ + CL_Program::cleanup(); + delete[] regions; + delete[] winds; + delete[] precipitation; +} + +void CL_Precipitation::event1() +{ +} + +void CL_Precipitation::event2() +{ +} + +void CL_Precipitation::event3() +{ +} + +void CL_Precipitation::event4() +{ +} + +void CL_Precipitation::event5() +{ +} + +void CL_Precipitation::event6() +{ +} + +void CL_Precipitation::event7() +{ +} + +void CL_Precipitation::event8() +{ +} diff --git a/pool/shard001/C++/0017316_libLink_start.cpp b/pool/shard001/C++/0017316_libLink_start.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bac354d792172143254117dc1d55e5bbf1bfce6 --- /dev/null +++ b/pool/shard001/C++/0017316_libLink_start.cpp @@ -0,0 +1,260 @@ + +#include + +#include "caffe/caffe.hpp" +#include "WolframLibrary.h" + +#include "build_utils.hpp" +#include "caffeLink.hpp" +#include "libLink_inputs.hpp" + + +/* Necessary for Mathematica library link. */ +extern "C" DLLEXPORT mint WolframLibrary_getVersion() +{ + return WolframLibraryVersion; +} + +/* Necessary for Mathematica library link. */ +extern "C" DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData) +{ + return 0; +} + +/* Necessary for Mathematica library link. */ +extern "C" DLLEXPORT void WolframLibrary_uninitialize(WolframLibraryData libData) +{ +} + +/** Mathematica librarylink wrapper for \c initCaffeLink_.*/ +extern "C" DLLEXPORT int initCaffeLink(LIB_LINK_ARGS) +{ + mbool useDoubles; + mbool useGPU; + mint devID; + + if(Argc != 3){ + printf("ERR: %s takes 3 arguments: \"Boolean\" (True for net using " + "doubles, false for floats), \"Boolean\" (True for GPU, false " + "for CPU mode) and Integer (device ID in case of GPU mode)\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + useDoubles = MArgument_getBoolean(Args[0]); + useGPU = MArgument_getBoolean(Args[1]); + devID = MArgument_getInteger(Args[2]); + + initCaffeLink_(useDoubles, useGPU, devID); + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c prepareNetFile_.*/ +extern "C" DLLEXPORT int prepareNetFile(LIB_LINK_ARGS) +{ + char* path; + + if (Argc != 1) { + printf("ERR: %s takes 1 argument: UTF8String path to net protobuffer file\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + path = MArgument_getUTF8String(Args[0]); + + if(isUsingDouble()) + freeParamDataMT(libData); + + if(!prepareNetFile_(path)) + return LIBRARY_FUNCTION_ERROR; + + if(isUsingDouble()) + initParamDataMT(); + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c prepareNetString_.*/ +extern "C" DLLEXPORT int prepareNetString(LIB_LINK_ARGS) +{ + char* str; + + if (Argc != 1) { + printf("ERR: %s takes 1 argument: UTF8String net protobuffer parameters\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + + if (isUsingDouble()) + freeParamDataMT(libData); + + if (!prepareNetString_(str)) + return LIBRARY_FUNCTION_ERROR; + + if (isUsingDouble()) + initParamDataMT(); + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c loadNet_.*/ +extern "C" DLLEXPORT int loadNet(LIB_LINK_ARGS) +{ + char* path; + + if (Argc != 1) { + printf("ERR: %s takes 1 arguments: UTF8String path to net data\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + path = MArgument_getUTF8String(Args[0]); + loadNet_(path); + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c testNet_.*/ +extern "C" DLLEXPORT int testNet(LIB_LINK_ARGS) +{ + if (Argc != 0) { + printf("WRN: %s takes 0 arguments\n", __FUNCTION__); + } + + testNet_(); + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_NEW version.*/ +extern "C" DLLEXPORT int trainNetString(LIB_LINK_ARGS) +{ + char* str; + + if (Argc != 1) { + printf("WRN: %s takes 1 argument: UTF8String solver " + "protobuffer parameters\n", __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + if(!trainNet_(str, false, TRAIN_NEW, (char*) "")) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_NEW version.*/ +extern "C" DLLEXPORT int trainNetFile(LIB_LINK_ARGS) +{ + char* str; + + if (Argc != 1) { + printf("WRN: %s takes 1 argument: UTF8String path to solver " + "protobuffer file\n", __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + if(!trainNet_(str, true, TRAIN_NEW, (char*) "")) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_SNAPSHOT version.*/ +extern "C" DLLEXPORT int trainNetSnapshotString(LIB_LINK_ARGS) +{ + char* str; + char* path; + + if (Argc != 2) { + printf("WRN: %s takes 2 argument: UTF8String solver " + "protobuffer parameters and UTF8String path to snapshot\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + path = MArgument_getUTF8String(Args[1]); + if(!trainNet_(str, false, TRAIN_SNAPSHOT, path)) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_SNAPSHOT version.*/ +extern "C" DLLEXPORT int trainNetSnapshotFile(LIB_LINK_ARGS) +{ + char* str; + char* path; + + if (Argc != 2) { + printf("WRN: %s takes 2 argument: UTF8String path to solver " + "protobuffer file and UTF8String path to snapshot\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + path = MArgument_getUTF8String(Args[1]); + if(!trainNet_(str, true, TRAIN_SNAPSHOT, path)) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_WEIGHTS version.*/ +extern "C" DLLEXPORT int trainNetWeightsString(LIB_LINK_ARGS) +{ + char* str; + char* path; + + if (Argc != 2) { + printf("WRN: %s takes 2 argument: UTF8String solver " + "protobuffer parameters and UTF8String path to weights\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + path = MArgument_getUTF8String(Args[1]); + if(!trainNet_(str, false, TRAIN_WEIGHTS, path)) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} + +/** Mathematica librarylink wrapper for \c trainNet_, TRAIN_WEIGHTS version.*/ +extern "C" DLLEXPORT int trainNetWeightsFile(LIB_LINK_ARGS) +{ + char* str; + char* path; + + if (Argc != 2) { + printf("WRN: %s takes 2 argument: UTF8String to solver " + "protobuffer file and UTF8String path to weights\n", + __FUNCTION__); + libData->Message(MSG_WRONG_ARGS); + return LIBRARY_FUNCTION_ERROR; + } + + str = MArgument_getUTF8String(Args[0]); + path = MArgument_getUTF8String(Args[1]); + if(!trainNet_(str, true, TRAIN_WEIGHTS, path)) + return LIBRARY_FUNCTION_ERROR; + + return LIBRARY_NO_ERROR; +} diff --git a/pool/shard001/C++/0017323_DescribeDhcpOptionsResponse.cpp b/pool/shard001/C++/0017323_DescribeDhcpOptionsResponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50b4f86864ebf36229427c30d0f65a4820abe86b --- /dev/null +++ b/pool/shard001/C++/0017323_DescribeDhcpOptionsResponse.cpp @@ -0,0 +1,68 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file 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 + +using namespace Aws::EC2::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +DescribeDhcpOptionsResponse::DescribeDhcpOptionsResponse() +{ +} + +DescribeDhcpOptionsResponse::DescribeDhcpOptionsResponse(const AmazonWebServiceResult& result) +{ + *this = result; +} + +DescribeDhcpOptionsResponse& DescribeDhcpOptionsResponse::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "DescribeDhcpOptionsResponse") + { + resultNode = rootNode.FirstChild("DescribeDhcpOptionsResponse"); + } + + if(!resultNode.IsNull()) + { + XmlNode dhcpOptionsNode = resultNode.FirstChild("dhcpOptionsSet"); + if(!dhcpOptionsNode.IsNull()) + { + XmlNode dhcpOptionsMember = dhcpOptionsNode.FirstChild("item"); + while(!dhcpOptionsMember.IsNull()) + { + m_dhcpOptions.push_back(dhcpOptionsMember); + dhcpOptionsMember = dhcpOptionsMember.NextNode("item"); + } + + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::DescribeDhcpOptionsResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard001/C++/0017325_t_base64.cc b/pool/shard001/C++/0017325_t_base64.cc new file mode 100644 index 0000000000000000000000000000000000000000..4400ce86b159fa492277980cfa1967ad6cc066c2 --- /dev/null +++ b/pool/shard001/C++/0017325_t_base64.cc @@ -0,0 +1,148 @@ +/** + * This file is part of the CernVM File System. + */ + +#include + +#include + +#include + +#include "util/string.h" + +class T_Base64 : public ::testing::Test { + protected: + virtual void SetUp() { + } + + protected: + std::string enc; + std::string dec; +}; + + +TEST_F(T_Base64, Basics) { + enc = Base64("Man"); + EXPECT_EQ(enc, "TWFu"); + + enc = Base64("any carnal pleasure."); + EXPECT_EQ(enc, "YW55IGNhcm5hbCBwbGVhc3VyZS4="); + + enc = Base64("any carnal pleasure"); + EXPECT_EQ(enc, "YW55IGNhcm5hbCBwbGVhc3VyZQ=="); + + enc = Base64("any carnal pleasur"); + EXPECT_EQ(enc, "YW55IGNhcm5hbCBwbGVhc3Vy"); + + enc = Base64("any carnal pleasu"); + EXPECT_EQ(enc, "YW55IGNhcm5hbCBwbGVhc3U="); + + enc = Base64("any carnal pleas"); + EXPECT_EQ(enc, "YW55IGNhcm5hbCBwbGVhcw=="); +} + + +TEST_F(T_Base64, MoreBasics) { + enc = Base64( + "Man is distinguished, not only by his reason, but by this singular passion" + " from other animals, which is a lust of the mind, that by a perseverance " + "of delight in the continued and indefatigable generation of knowledge, " + "exceeds the short vehemence of any carnal pleasure."); + EXPECT_EQ(enc, + "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz" + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg" + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu" + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo" + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="); +} + + +TEST_F(T_Base64, Decode) { + bool retval; + + retval = Debase64("", &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("", dec); + + retval = Debase64(Base64("Man"), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("Man", dec); + + retval = Debase64(Base64("any carnal pleasure."), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("any carnal pleasure.", dec); + + retval = Debase64(Base64("any carnal pleasure"), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("any carnal pleasure", dec); + + retval = Debase64(Base64("any carnal pleasur"), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("any carnal pleasur", dec); + + retval = Debase64(Base64("any carnal pleasu"), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("any carnal pleasu", dec); + + retval = Debase64(Base64("any carnal pleas"), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ("any carnal pleas", dec); + + retval = Debase64(Base64( + "Man is distinguished, not only by his reason, but by this singular passion" + " from other animals, which is a lust of the mind, that by a perseverance " + "of delight in the continued and indefatigable generation of knowledge, " + "exceeds the short vehemence of any carnal pleasure."), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ( + "Man is distinguished, not only by his reason, but by this singular passion" + " from other animals, which is a lust of the mind, that by a perseverance " + "of delight in the continued and indefatigable generation of knowledge, " + "exceeds the short vehemence of any carnal pleasure.", dec); + + std::string all_chars; + for (unsigned i = 0; i < 255; ++i) + all_chars.push_back(i); + retval = Debase64(Base64(all_chars), &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ(all_chars, dec); +} + + +TEST_F(T_Base64, UrlSafe) { + std::string all_chars; + for (unsigned i = 0; i < 255; ++i) + all_chars.push_back(i); + + std::string enc_normal = Base64(all_chars); + std::string enc_url = Base64Url(all_chars); + + bool unsafe_char_found = false; + for (unsigned i = 0; i < enc_normal.length(); ++i) { + if ((enc_normal[i] == '/') || (enc_normal[i] == '+')) + unsafe_char_found = true; + } + EXPECT_TRUE(unsafe_char_found); + unsafe_char_found = false; + for (unsigned i = 0; i < enc_url.length(); ++i) { + if ((enc_url[i] == '/') || (enc_url[i] == '+')) + unsafe_char_found = true; + } + EXPECT_FALSE(unsafe_char_found); + + bool retval = Debase64(enc_url, &dec); + EXPECT_EQ(retval, true); + EXPECT_EQ(all_chars, dec); +} + + +TEST_F(T_Base64, Invalid) { + bool retval; + + retval = Debase64("ABC", &dec); + EXPECT_EQ(retval, false); + retval = Debase64("ABCDE", &dec); + EXPECT_EQ(retval, false); + retval = Debase64("^&*A", &dec); + EXPECT_EQ(retval, false); +} diff --git a/pool/shard001/C++/0017326_CreateDBInstanceResult.cpp b/pool/shard001/C++/0017326_CreateDBInstanceResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16d8bd6bdf0ec0714d72f97ee74fc845c84d8ceb --- /dev/null +++ b/pool/shard001/C++/0017326_CreateDBInstanceResult.cpp @@ -0,0 +1,63 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file 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 + +using namespace Aws::RDS::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +CreateDBInstanceResult::CreateDBInstanceResult() +{ +} + +CreateDBInstanceResult::CreateDBInstanceResult(const AmazonWebServiceResult& result) +{ + *this = result; +} + +CreateDBInstanceResult& CreateDBInstanceResult::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "CreateDBInstanceResult") + { + resultNode = rootNode.FirstChild("CreateDBInstanceResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode dBInstanceNode = resultNode.FirstChild("DBInstance"); + if(!dBInstanceNode.IsNull()) + { + m_dBInstance = dBInstanceNode; + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::CreateDBInstanceResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard001/C++/0017335_TestFile.cpp b/pool/shard001/C++/0017335_TestFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecfae328421b4d41e2832114d1c94ddfc0a4369c --- /dev/null +++ b/pool/shard001/C++/0017335_TestFile.cpp @@ -0,0 +1,199 @@ +/** + * \file TestFile.cpp + * \brief Enscapsulates an XML file in the test-data/ directory + * \author Ben Bornstein + * + * */ + +#include + +#if defined(WIN32) && !defined(CYGWIN) +# include "../../../../validator/test/tps/dirent.h" +# include "../../../../validator/test/tps/dirent.c" +#else +# include +# include +#endif /* WIN32 */ + +#include +#include "TestFile.h" + +/** @cond doxygenIgnored */ + +using namespace std; + +/** @endcond */ + + +/** + * TestFiles (e.g. in the test-data/ directory) have the following naming + * convention: + * + * ccccccc-pass-00-nn.xml, or + * ccccccc-fail-ff-nn.xml + * + * ccccccc-fail-ff-nn-xxxxx.xml + * + * Where: + * + * ccccccc is the seven digit constraint id the file is designed to test + * + * pass indicates the file must pass validation without error + * + * fail indicates the file must fail validation with extactly ff errors + * all with constraint id ccccc. + * + * nn is the sequence id (to allow multiple test files per constraint). + * + * xxxxx is the number of an additional constraint that this test fails + * + * + * Offsets within mFilename: + * + * 1 1 + * 012345678901234567890123456 + * ccccccc-pass-00-nn.xml + * ccccccc-fail-ff-nn.xml + * ccccccc-fail-ff-nn-xxxxx.xml + */ + + +std::string +TestFile::getFullname () const +{ + return mDirectory + "/" + mFilename; +} + + +unsigned int +TestFile::getConstraintId () const +{ + return atol( mFilename.substr(0, 7).c_str() ); +} + + +unsigned int +TestFile::getSequenceId () const +{ + return atol( mFilename.substr(16, 2).c_str() ); +} + + +unsigned int +TestFile::getNumFailures () const +{ + unsigned num = atol( mFilename.substr(13, 2).c_str() ); + if (mFilename.length() > 22) + return num+1; + else + return num; +} + +unsigned int +TestFile::getAdditionalFailId () const +{ + if (mFilename.length() > 22) + return atol( mFilename.substr(19, 7).c_str() ); + else + return 0; + +} + + +/** + * @return true if filename adheres to the TestFile naming convention, + * false otherwise. + */ +bool +TestFile::isValid (const string& filename) +{ + return ((filename.length() == 22 && filename.substr(18, 4) == ".xml") + || (filename.length() == 30 && filename.substr(26, 4) == ".xml")); +} + + +/** + * @return the set of TestFiles in the given directory. + * + * You may optionally limit to the TestFiles returned to only those with + * ConstraintIds in the range [begin, end] (if begin == end == 0, all + * TestFiles in the given directory will be returned). + */ +set +TestFile::getFilesIn ( const string& directory, + unsigned int begin, + unsigned int end, + unsigned int library) +{ + DIR* dir; + struct dirent* entry; + set result; + + dir = opendir( directory.c_str() ); + + if (dir == NULL) + { + cerr << "Could not obtain a list of files in directory " + << "[" << directory << "]." << endl; + return result; + } + + for (entry = readdir(dir); entry != NULL; entry = readdir(dir)) + { + string filename(entry->d_name); + + if ( TestFile::isValid(filename) ) + { + TestFile file(directory, filename); + unsigned int id = file.getConstraintId(); + + //// leave out the following tests dependent on parser + //if (library == 0) + //{ + // // xerces bug in reading multibyte chars + // if (id == 10309) continue; + + // libxml bug for 2.6.16 on a Mac +#ifdef BUGGY_APPLE_LIBXML + // unsigned int num = file.getSequenceId(); + + if (id == 1013) continue; + if (id == 1014) continue; +#endif + + // leave out model constraints moved to units + if (id == 20702 || id == 20616 + || id == 20511 || id == 20512 || id == 20513 + || id == 20518) + continue; + //} + + if ((begin == 0 && end == 0) || (id >= begin && id <= end)) + { + result.insert( TestFile(directory, filename) ); + } + } + } + + closedir(dir); + + return result; +} diff --git a/pool/shard001/C++/0017338_tnp.cpp b/pool/shard001/C++/0017338_tnp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03cd0b8615e9a25bbbfbb8ab33e795f87f88070e --- /dev/null +++ b/pool/shard001/C++/0017338_tnp.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2012 uebb.tu-berlin.de. + * + * This file is part of tnp + * + * tnp 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. + * + * tnp 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 tnp. If not, see . + */ + +#include +#include +#include +#include + +using namespace tnp; + +extern "C" { + + struct tnp_number : public NPNumber {}; + + struct tnp_number* tnp_number_create(int params, int order) { + return static_cast(new NPNumber(params, order)); + } + + struct tnp_number* tnp_number_create_variable(double val, int nr, int params, int order) { + const int width = (params+1); + return static_cast(new NPNumber(width, variable(val, nr, width * (order+1)))); + } + + struct tnp_number* tnp_number_create_constant(double val, int params, int order) { + const int width = (params+1); + return static_cast(new NPNumber(width, constant(val, width * (order+1)))); + } + + void tnp_number_delete(struct tnp_number* nr) { + delete nr; + } + + int tnp_number_params(struct tnp_number* nr) { + return nr->params(); + } + + int tnp_number_order(struct tnp_number* nr) { + return nr->order(); + } + + double tnp_number_value(struct tnp_number* nr) { + return nr->data()[0]; + } + + double tnp_number_total_derivative(struct tnp_number* nr, int order) { + return nr->der(0, order); + } + + double tnp_number_partial_derivative(struct tnp_number* nr, int param) { + return nr->der(param, 0); + } + + double tnp_number_mixed_derivative(struct tnp_number* nr, int order, int param) { + return nr->der(param, order); + } + + struct tnp_number* tnp_number_add(struct tnp_number* a, struct tnp_number* b) { + return static_cast(new NPNumber((*a) + (*b))); + } + + struct tnp_number* tnp_number_dadd(struct tnp_number* a, double b) { + return static_cast(new NPNumber((*a) + b)); + } + + struct tnp_number* tnp_number_mult(struct tnp_number* a, struct tnp_number* b) { + return static_cast(new NPNumber((*a) * (*b))); + } + + struct tnp_number* tnp_number_dmult(struct tnp_number* a, double b) { + return static_cast(new NPNumber((*a) * b)); + } + + struct tnp_number* tnp_number_sub(struct tnp_number* a, struct tnp_number* b) { + return static_cast(new NPNumber((*a) - (*b))); + } + + struct tnp_number* tnp_number_dsub(struct tnp_number* a, double b) { + return static_cast(new NPNumber((*a) - b)); + } + +/* + struct tnp_number* tnp_number_div(struct tnp_number* a, struct tnp_number* b) { + return static_cast(new NPNumber((*a) / (*b))); + } + + struct tnp_number* tnp_number_ddiv(struct tnp_number* a, double b) { + return static_cast(new NPNumber((*a) / b)); + } +*/ + + struct tnp_number* tnp_number_pow(struct tnp_number* a, int power) { + return static_cast(new NPNumber(a -> pow(power))); + } + +} diff --git a/pool/shard001/C++/0017342_main.cpp b/pool/shard001/C++/0017342_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6df33dfd5b8d4bd4d1873b9a924e15d2421c52e --- /dev/null +++ b/pool/shard001/C++/0017342_main.cpp @@ -0,0 +1,92 @@ +#include +#include +#include + +#include + +#include "t4test.h" +#include "osg_test.h" + +void RunOsgTest() +{ + viewer = SetupViewer(); + root = new osg::Group(); + + //Add stat handler + osg::ref_ptr statsHandler = new osgViewer::StatsHandler; + statsHandler->setKeyEventTogglesOnScreenStats(osgGA::GUIEventAdapter::KEY_F3); + viewer->addEventHandler(statsHandler); + + root->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); + + PyramidComponentManager pm; + PyramidComponent pc = pm.create(0,0,0); + PyramidComponent pc2 = pm.create(15,0,0); + + pm.addToScene(root); + + //Setup viewer + viewer->setSceneData( root ); + viewer->setCameraManipulator(new osgGA::TrackballManipulator()); + viewer->realize(); + + osg::Timer frameTimer; + double simulationTime = 0.0; + while( !viewer->done() ) + { + double dt = frameTimer.time_s(); + frameTimer.setStartTick(); + dt = std::min(dt, 0.2); + simulationTime += dt; + + viewer->advance(simulationTime); + viewer->eventTraversal(); + viewer->updateTraversal(); + viewer->renderingTraversals(); + } +} + +unsigned int get_now() { + auto now = std::chrono::high_resolution_clock::now(); + return std::chrono::duration_cast(now.time_since_epoch()).count(); +} + +int main(int ArgC,const char* ArgV[]) +{ + opent4::scene::EntityManager em; + + const uint32_t NUM_ENTITIES = 512; + opent4::scene::Entity entities[NUM_ENTITIES]; + float before_create = get_now(); + for(int i = 0; i < NUM_ENTITIES; i++) + { + entities[i] = em.create(); + printf("Created entity %d, gen %d\n", entities[i].index(), entities[i].generation()); + } + float after_create = get_now(); + + //em.destroy(entities[NUM_ENTITIES-1]); + //entities[NUM_ENTITIES-1] = em.create(); + + float before_alive = get_now(); + uint32_t count_alive = 0; + for(int i = 0; i < NUM_ENTITIES; i++) + { + opent4::scene::Entity e = entities[i]; + count_alive++; + if(em.alive(e)) { + //printf("Entity w/ idx: %d generation: %d is ALIVE!\n", e.index(), e.generation()); + } else { + //printf("Entity w/ idx: %d generation: %d is DEAD!\n", e.index(), e.generation()); + } + } + float after_alive = get_now(); + + printf("Create took %f ns\n", (after_create-before_create)); + printf("Checking alive status of %d entities took %f ns\n", count_alive, (after_alive-before_alive)); + printf("Total time taken %f ns\n", (after_alive-before_create)); + + RunOsgTest(); + return 0; +} + diff --git a/pool/shard001/C++/0017343_dataref_edit_panel.cpp b/pool/shard001/C++/0017343_dataref_edit_panel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06bcce9b766615f49b62401368fb038b513f8f64 --- /dev/null +++ b/pool/shard001/C++/0017343_dataref_edit_panel.cpp @@ -0,0 +1,197 @@ +#include "dataref_edit_panel.h" + +#include "widgets/button.h" +#include "widgets/spacer.h" + +#include "search/dataref.h" + +#include "../drt_plugin.h" + + +bool checkValueOK(DataRefRecord * drr, const std::string & new_value) { + if(drr->isDouble()) { + try { + std::stold(new_value); + } catch(std::exception &) { + return false; + } + } else if(drr->isFloat() || drr->isFloatArray()) { + try { + std::stof(new_value); + } catch(std::exception &) { + return false; + } + } else if(drr->isInt() || drr->isIntArray()) { + try { + std::stoi(new_value); + } catch(std::exception &) { + return false; + } + } else if(drr->isData()) { + } + + return true; +} + +void setValue(DataRefRecord * drr, const std::string & new_value, std::optional index) { + if(drr->isDouble()) { + assert(!index); + try { + double d = std::stold(new_value); + drr->setDouble(d); + } catch(std::exception &) { + return; + } + } else if(drr->isFloat()) { + assert(!index); + try { + float f = std::stof(new_value); + drr->setFloat(f); + } catch(std::exception &) { + return; + } + } else if(drr->isInt()) { + assert(!index); + try { + int i = std::stoi(new_value); + drr->setInt(i); + } catch(std::exception &) { + return; + } + } else if(drr->isFloatArray()) { + assert(index); + try { + float f = std::stof(new_value); + drr->setFloatArrayElement(f, *index); + } catch(std::exception &) { + return; + } + } else if(drr->isIntArray()) { + assert(index); + try { + int i = std::stoi(new_value); + drr->setIntArrayElement(i, *index); + } catch(std::exception &) { + return; + } + } else if(drr->isData()) { + assert(!index); + drr->setData(new_value); + } +} + +void DatarefEditField::draw(Rect visible_bounds) { + if(false == hasKeyboardFocus() && displayed_values_updated != drr->getLastUpdateTime()) { + setContents(drr->getArrayElementEditString(element_index)); + displayed_values_updated = drr->getLastUpdateTime(); + } + + Widget11TextField::draw(visible_bounds); +} + +DatarefEditField::DatarefEditField(DataRefRecord * drr, int element_index) +: drr(drr) +, element_index(element_index) +{ + setPlaceholder("New value"); + + setContents(drr->getArrayElementEditString(element_index)); + + setTypeAction([this, drr]() { + if(checkValueOK(drr, getContents())) { + } else { + } + }); + + std::optional index_in_array_if_array; + if(drr->isArray()) { + index_in_array_if_array = element_index; + } + + std::function set_value_edit_done = [element_index, this, drr, index_in_array_if_array]() { + setValue(drr, getContents(), index_in_array_if_array); + + // This might seem like a great time to update the displayed value, but + // at this time, we haven't actually read the DR's value back yet to know if it + // changed. We can trigger a read by updating all DRs now, and then update the + //displayed value. + + plugin->getRefs().update(); + setContents(drr->getArrayElementEditString(element_index)); + selectAll(); + }; + + setSubmitAction(set_value_edit_done); + setEnabled(drr->writable()); +} + +DatarefEditPanel::DatarefEditPanel(DataRefRecord * drr, int element_index) +: SingleAxisLayoutContainer(SingleAxisLayoutContainer::LayoutAxis::HORIZONTAL) +, drr(drr) +, element_index(element_index) +{ + std::shared_ptr index_label; + if(drr->isArray()) { + index_label = std::make_shared(); + index_label->setText(std::to_string(element_index)); + index_label->setMinimumSize({30, 0}); + } + + edit_field = std::make_shared(); + edit_field->setPlaceholder("New value"); + + edit_field->setContents(drr->getArrayElementEditString(element_index)); + + std::shared_ptr edit_spacer = std::make_shared(Size{20, 1}); + + std::shared_ptr set_button; + set_button = std::make_shared(); + set_button->setLabel("Set"); + set_button->setMinimumSize({40, 0}); + + edit_field->setTypeAction([this, set_button, drr]() { + if(checkValueOK(drr, edit_field->getContents())) { + set_button->setEnabled(true); + } else { + set_button->setEnabled(false); + } + }); + + std::optional index_in_array_if_array; + if(drr->isArray()) { + index_in_array_if_array = element_index; + } + + std::function set_value_edit_done = [element_index, this, drr, index_in_array_if_array]() { + setValue(drr, edit_field->getContents(), index_in_array_if_array); + + // This might seem like a great time to update the displayed value, but + // at this time, we haven't actually read the DR's value back yet to know if it + // changed. We can trigger a read by updating all DRs now, and then update the + //displayed value. + + plugin->getRefs().update(); + edit_field->setContents(drr->getArrayElementEditString(element_index)); + edit_field->selectAll(); + }; + + edit_field->setSubmitAction(set_value_edit_done); + set_button->setAction(set_value_edit_done); + + edit_field->setEnabled(drr->writable()); + + if(index_label) { + this->add(index_label, false, false); + } + this->add(edit_field, true, true); + this->add(edit_spacer, false, false); + if(drr->writable()) { + this->add(set_button, false, false); + } +} + +void DatarefEditPanel::update() { + if(false == edit_field->hasKeyboardFocus()) { + edit_field->setContents(drr->getArrayElementEditString(element_index)); + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0017346_tuple.cc b/pool/shard001/C++/0017346_tuple.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e1a55454395b5b0db73e1cf56750da36cc6dd49 --- /dev/null +++ b/pool/shard001/C++/0017346_tuple.cc @@ -0,0 +1,83 @@ + +#include "cg-operator-common.h" +#include + +using namespace spicy; +using namespace spicy::codegen; + +void CodeBuilder::visit(constant::Tuple* t) +{ + hilti::builder::tuple::element_list elems; + + for ( auto e : t->value() ) { + if ( ! e->usesTryAttribute() ) { + elems.push_back(cg()->hiltiExpression(e)); + continue; + } + + // Wrap it into an exception handler that return an unset optional if + // an SpicyHilti::AttributeNotSet is thrown. + + auto tmp = cg()->builder()->addTmp("opt", cg()->hiltiTypeOptional(e->type())); + + cg()->builder()->beginTryCatch(); + + auto he = cg()->hiltiConstantOptional(e); + cg()->builder()->addInstruction(tmp, ::hilti::instruction::operator_::Assign, he); + + cg()->builder()->pushCatch(hilti::builder::reference::type( + hilti::builder::type::byName("SpicyHilti::AttributeNotSet")), + hilti::builder::id::node("e")); + + // Nothing to do, default of tmp is right. + + cg()->builder()->popCatch(); + + cg()->builder()->endTryCatch(); + + elems.push_back(tmp); + } + + auto result = hilti::builder::tuple::create(elems, t->location()); + setResult(result); +} + +void CodeBuilder::visit(expression::operator_::tuple::CoerceTuple* t) +{ + auto op1 = cg()->hiltiExpression(t->op1()); + + // For now we cheat here and rely on HILTI to do the coercion right. + // Otherwise, we'd have to split the tuple apart, coerce each element + // individually, and then put it back together; something which is + // probably always unnecessary. However, I'm not sure we'll eventually + // get around that ... + + setResult(op1); +} + +void CodeBuilder::visit(expression::operator_::tuple::Equal* i) +{ + auto result = builder()->addTmp("equal", hilti::builder::boolean::type()); + auto op1 = cg()->hiltiExpression(i->op1()); + auto op2 = cg()->hiltiExpression(i->op2()); + cg()->builder()->addInstruction(result, hilti::instruction::tuple::Equal, op1, op2); + setResult(result); +} + +void CodeBuilder::visit(expression::operator_::tuple::Index* i) +{ + auto tuple = ast::rtti::checkedCast(i->op1()->type()); + auto types = tuple->typeList(); + + auto idx = ast::rtti::checkedCast(i->op2()); + auto const_ = ast::rtti::checkedCast(idx->constant()); + + auto t = types.begin(); + std::advance(t, const_->value()); + + auto result = builder()->addTmp("elem", cg()->hiltiType(*t)); + auto op1 = cg()->hiltiExpression(i->op1()); + auto op2 = cg()->hiltiExpression(i->op2()); + cg()->builder()->addInstruction(result, hilti::instruction::tuple::Index, op1, op2); + setResult(result); +} diff --git a/pool/shard001/C++/0017352_DXVADecoderMpeg2.cpp b/pool/shard001/C++/0017352_DXVADecoderMpeg2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c19868cc9f3c66286b1f2fc05207563a20533ee --- /dev/null +++ b/pool/shard001/C++/0017352_DXVADecoderMpeg2.cpp @@ -0,0 +1,238 @@ +/* + * $Id$ + * + * (C) 2006-2012 see Authors.txt + * + * This file is part of MPC-HC. + * + * MPC-HC 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. + * + * MPC-HC 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 "stdafx.h" +#include "DXVADecoderMpeg2.h" +#include "MPCVideoDecFilter.h" + +extern "C" +{ +#include "FfmpegContext.h" +} + +#if 0 + #define TRACE_MPEG2 TRACE +#else + #define TRACE_MPEG2(...) +#endif + +CDXVADecoderMpeg2::CDXVADecoderMpeg2 (CMPCVideoDecFilter* pFilter, IAMVideoAccelerator* pAMVideoAccelerator, DXVAMode nMode, int nPicEntryNumber) + : CDXVADecoder (pFilter, pAMVideoAccelerator, nMode, nPicEntryNumber) +{ + Init(); +} + +CDXVADecoderMpeg2::CDXVADecoderMpeg2 (CMPCVideoDecFilter* pFilter, IDirectXVideoDecoder* pDirectXVideoDec, DXVAMode nMode, int nPicEntryNumber, DXVA2_ConfigPictureDecode* pDXVA2Config) + : CDXVADecoder (pFilter, pDirectXVideoDec, nMode, nPicEntryNumber, pDXVA2Config) +{ + Init(); +} + +CDXVADecoderMpeg2::~CDXVADecoderMpeg2(void) +{ + Flush(); +} + +void CDXVADecoderMpeg2::Init() +{ + memset (&m_PictureParams, 0, sizeof(m_PictureParams)); + memset (&m_SliceInfo, 0, sizeof(m_SliceInfo)); + memset (&m_QMatrixData, 0, sizeof(m_QMatrixData)); + + m_nMaxWaiting = 5; + m_wRefPictureIndex[0] = NO_REF_FRAME; + m_wRefPictureIndex[1] = NO_REF_FRAME; + m_nSliceCount = 0; + + switch (GetMode()) { + case MPEG2_VLD : + AllocExecuteParams (4); + break; + default : + ASSERT(FALSE); + } +} + +// === Public functions +HRESULT CDXVADecoderMpeg2::DecodeFrame (BYTE* pDataIn, UINT nSize, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop) +{ + HRESULT hr; + int nSurfaceIndex; + CComPtr pSampleToDeliver; + int nFieldType; + int nSliceType; + + FFMpeg2DecodeFrame (&m_PictureParams, &m_QMatrixData, m_SliceInfo, &m_nSliceCount, m_pFilter->GetAVCtx(), + m_pFilter->GetFrame(), &m_nNextCodecIndex, &nFieldType, &nSliceType, pDataIn, nSize); + + // Wait I frame after a flush + if (m_bFlushed && ! m_PictureParams.bPicIntra) { + return S_FALSE; + } + + hr = GetFreeSurfaceIndex (nSurfaceIndex, &pSampleToDeliver, rtStart, rtStop); + if (FAILED (hr)) { + ASSERT (hr == VFW_E_NOT_COMMITTED); // Normal when stop playing + return hr; + } + + CHECK_HR (BeginFrame(nSurfaceIndex, pSampleToDeliver)); + + UpdatePictureParams(nSurfaceIndex); + + TRACE_MPEG2 ("CDXVADecoderMpeg2::DecodeFrame() : PictureType = %d, rtStart = %I64d, Surf = %d\n", nSliceType, rtStart, nSurfaceIndex); + + TRACE_MPEG2 ("CDXVADecoderMpeg2::DecodeFrame() : Decode frame %i\n", m_PictureParams.bPicScanMethod); + + CHECK_HR (AddExecuteBuffer (DXVA2_PictureParametersBufferType, sizeof(m_PictureParams), &m_PictureParams)); + + CHECK_HR (AddExecuteBuffer (DXVA2_InverseQuantizationMatrixBufferType, sizeof(m_QMatrixData), &m_QMatrixData)); + + // Send bitstream to accelerator + CHECK_HR (AddExecuteBuffer (DXVA2_SliceControlBufferType, sizeof (DXVA_SliceInfo)*m_nSliceCount, &m_SliceInfo)); + CHECK_HR (AddExecuteBuffer (DXVA2_BitStreamDateBufferType, nSize, pDataIn, &nSize)); + + // Decode frame + CHECK_HR (Execute()); + CHECK_HR (EndFrame(nSurfaceIndex)); + + AddToStore (nSurfaceIndex, pSampleToDeliver, (m_PictureParams.bPicBackwardPrediction != 1), rtStart, rtStop, + false,(FF_FIELD_TYPE)nFieldType, (FF_SLICE_TYPE)nSliceType, FFGetCodedPicture(m_pFilter->GetAVCtx())); + m_bFlushed = false; + + return DisplayNextFrame(); +} + +void CDXVADecoderMpeg2::UpdatePictureParams(int nSurfaceIndex) +{ + DXVA2_ConfigPictureDecode* cpd = GetDXVA2Config(); // Ok for DXVA1 too (parameters have been copied) + + m_PictureParams.wDecodedPictureIndex = nSurfaceIndex; + + // Manage reference picture list + if (!m_PictureParams.bPicBackwardPrediction) { + if (m_wRefPictureIndex[0] != NO_REF_FRAME) { + RemoveRefFrame (m_wRefPictureIndex[0]); + } + m_wRefPictureIndex[0] = m_wRefPictureIndex[1]; + m_wRefPictureIndex[1] = nSurfaceIndex; + } + m_PictureParams.wForwardRefPictureIndex = (m_PictureParams.bPicIntra == 0) ? m_wRefPictureIndex[0] : NO_REF_FRAME; + m_PictureParams.wBackwardRefPictureIndex = (m_PictureParams.bPicBackwardPrediction == 1) ? m_wRefPictureIndex[1] : NO_REF_FRAME; + + // Shall be 0 if bConfigResidDiffHost is 0 or if BPP > 8 + if (cpd->ConfigResidDiffHost == 0 || m_PictureParams.bBPPminus1 > 7) { + m_PictureParams.bPicSpatialResid8 = 0; + } else { + if (m_PictureParams.bBPPminus1 == 7 && m_PictureParams.bPicIntra && cpd->ConfigResidDiffHost) + // Shall be 1 if BPP is 8 and bPicIntra is 1 and bConfigResidDiffHost is 1 + { + m_PictureParams.bPicSpatialResid8 = 1; + } else + // Shall be 1 if bConfigSpatialResid8 is 1 + { + m_PictureParams.bPicSpatialResid8 = cpd->ConfigSpatialResid8; + } + } + + // Shall be 0 if bConfigResidDiffHost is 0 or if bConfigSpatialResid8 is 0 or if BPP > 8 + if (cpd->ConfigResidDiffHost == 0 || cpd->ConfigSpatialResid8 == 0 || m_PictureParams.bBPPminus1 > 7) { + m_PictureParams.bPicOverflowBlocks = 0; + } + + // Shall be 1 if bConfigHostInverseScan is 1 or if bConfigResidDiffAccelerator is 0. + + if (cpd->ConfigHostInverseScan == 1 || cpd->ConfigResidDiffAccelerator == 0) { + m_PictureParams.bPicScanFixed = 1; + + if (cpd->ConfigHostInverseScan != 0) { + m_PictureParams.bPicScanMethod = 3; // 11 = Arbitrary scan with absolute coefficient address. + } else if (FFGetAlternateScan(m_pFilter->GetAVCtx())) { + m_PictureParams.bPicScanMethod = 1; // 00 = Zig-zag scan (MPEG-2 Figure 7-2) + } else { + m_PictureParams.bPicScanMethod = 0; // 01 = Alternate-vertical (MPEG-2 Figure 7-3), + } + } +} + +void CDXVADecoderMpeg2::CopyBitstream(BYTE* pDXVABuffer, BYTE* pBuffer, UINT& nSize) +{ + while (*((DWORD*)pBuffer) != 0x01010000) { + pBuffer++; + nSize--; + + if (nSize <= 0) { + return; + } + } + + memcpy (pDXVABuffer, pBuffer, nSize); +} + +void CDXVADecoderMpeg2::Flush() +{ + m_nNextCodecIndex = INT_MIN; + + if (m_wRefPictureIndex[0] != NO_REF_FRAME) { + RemoveRefFrame (m_wRefPictureIndex[0]); + } + if (m_wRefPictureIndex[1] != NO_REF_FRAME) { + RemoveRefFrame (m_wRefPictureIndex[1]); + } + + m_wRefPictureIndex[0] = NO_REF_FRAME; + m_wRefPictureIndex[1] = NO_REF_FRAME; + + m_rtLastStart = 0; + + __super::Flush(); +} + +int CDXVADecoderMpeg2::FindOldestFrame() +{ + int nPos = -1; + + for (int i=0; iGetAvrTimePerFrame() / m_pFilter->GetRate(); + + m_rtLastStart = rtStop; +} diff --git a/pool/shard001/C++/0017353_mimserver.cpp b/pool/shard001/C++/0017353_mimserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..464bf4a9136bdc40a16ec85adbca7f3c738cc7d8 --- /dev/null +++ b/pool/shard001/C++/0017353_mimserver.cpp @@ -0,0 +1,70 @@ +/* * This file is part of Maliit framework * + * + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + * All rights reserved. + * + * Contact: maliit-discuss@lists.maliit.org + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License version 2.1 as published by the Free Software Foundation + * and appearing in the file LICENSE.LGPL included in the packaging + * of this file. + */ + +#include "mimserver.h" + +#include "mimpluginmanager.h" +#include "mimsettings.h" + +class MImServerPrivate +{ +public: + explicit MImServerPrivate(); + + // Manager for loading and handling all plugins + MIMPluginManager *pluginManager; + + // Connection to application side (input-context) + QSharedPointer icConnection; + +private: + Q_DISABLE_COPY(MImServerPrivate) +}; + +MImServerPrivate::MImServerPrivate() +{} + +MImServer::MImServer(const QSharedPointer &icConnection, + const QSharedPointer &platform, + QObject *parent) + : QObject(parent) + , d_ptr(new MImServerPrivate) +{ + Q_D(MImServer); + + d->icConnection = icConnection; + d->pluginManager = new MIMPluginManager(d->icConnection, platform); +} + +MImServer::~MImServer() +{ +} + +void MImServer::configureSettings(MImServer::SettingsType settingsType) +{ + switch (settingsType) { + + case TemporarySettings: + MImSettings::setPreferredSettingsType(MImSettings::TemporarySettings); + break; + + case PersistentSettings: + MImSettings::setPreferredSettingsType(MImSettings::PersistentSettings); + break; + + default: + qCritical() << __PRETTY_FUNCTION__ << + "Invalid value for preferredSettingType." << settingsType; + } +} diff --git a/pool/shard001/C++/0017357_ut_configdata.cpp b/pool/shard001/C++/0017357_ut_configdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9c7cc0f903836300cb3f8a0d7ad95ee47c1dca4 --- /dev/null +++ b/pool/shard001/C++/0017357_ut_configdata.cpp @@ -0,0 +1,65 @@ +#include "ut_configdata.h" + +Ut_ConfigData::Ut_ConfigData() +{} + +Ut_ConfigData::~Ut_ConfigData() +{} + +void Ut_ConfigData::initTestCase() +{} + +void Ut_ConfigData::cleanupTestCase() +{ + m_subject.reset(); +} + +void Ut_ConfigData::testDefaults() +{ + m_subject.reset(new ConfigData); + QVERIFY(m_subject->defaultCPULoadThreshold() == 25); + QVERIFY(m_subject->cpuLoadPollingDelay() == 1); + QVERIFY(m_subject->rePrestartDelay() == 3 * 3600); + QVERIFY(m_subject->defaultRePrestartTrigger() == 3); +} + +void Ut_ConfigData::testCPULoadThreshold() +{ + m_subject.reset(new ConfigData); + m_subject->setDefaultCPULoadThreshold(50); + QVERIFY(m_subject->defaultCPULoadThreshold() == 50); +} + +void Ut_ConfigData::testCPULoadPollingDelay() +{ + m_subject.reset(new ConfigData); + m_subject->setCPULoadPollingDelay(1); + QVERIFY(m_subject->cpuLoadPollingDelay() == 1); +} + +void Ut_ConfigData::testRePrestartDelay() +{ + m_subject.reset(new ConfigData); + m_subject->setRePrestartDelay(1000); + QVERIFY(m_subject->rePrestartDelay() == 1000); +} + +void Ut_ConfigData::testRePrestartTrigger() +{ + m_subject.reset(new ConfigData); + m_subject->setDefaultRePrestartTrigger(10); + QVERIFY(m_subject->defaultRePrestartTrigger() == 10); +} + +void Ut_ConfigData::testAddPrestartApp() +{ + m_subject.reset(new ConfigData); + PrestartApp foo("foo", "foo", 0); + m_subject->addPrestartApp(&foo); + PrestartApp bar("bar", "bar", 0); + m_subject->addPrestartApp(&bar); + QVERIFY(m_subject->prestartApps().contains(&foo)); + QVERIFY(m_subject->prestartApps().contains(&bar)); +} + +QTEST_MAIN(Ut_ConfigData); diff --git a/pool/shard001/C++/0017361_networking_private_credentials_getter_win.cc b/pool/shard001/C++/0017361_networking_private_credentials_getter_win.cc new file mode 100644 index 0000000000000000000000000000000000000000..4832eb68161b46c096598457f73ab64db2b3e01c --- /dev/null +++ b/pool/shard001/C++/0017361_networking_private_credentials_getter_win.cc @@ -0,0 +1,155 @@ +// 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 "chrome/browser/extensions/api/networking_private/networking_private_credentials_getter.h" + +#include "base/base64.h" +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "base/threading/sequenced_worker_pool.h" +#include "chrome/common/extensions/api/networking_private/networking_private_crypto.h" +#include "chrome/common/extensions/chrome_utility_extensions_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/utility_process_host.h" + +using content::BrowserThread; +using content::UtilityProcessHost; +using extensions::NetworkingPrivateCredentialsGetter; + +namespace { + +class CredentialsGetterHostClient : public content::UtilityProcessHostClient { + public: + explicit CredentialsGetterHostClient(const std::string& public_key); + + virtual ~CredentialsGetterHostClient(); + + // UtilityProcessHostClient + virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; + virtual void OnProcessCrashed(int exit_code) OVERRIDE; + virtual void OnProcessLaunchFailed() OVERRIDE; + + // IPC message handlers. + void OnGotCredentials(const std::string& key_data, bool success); + + // Starts the utility process that gets wifi passphrase from system. + void StartProcessOnIOThread( + const std::string& network_guid, + const extensions::NetworkingPrivateServiceClient::CryptoVerify:: + VerifyAndEncryptCredentialsCallback& callback); + + private: + // Public key used to encrypt results + std::vector public_key_; + + // Callback for reporting the result. + extensions::NetworkingPrivateServiceClient::CryptoVerify:: + VerifyAndEncryptCredentialsCallback callback_; + + DISALLOW_COPY_AND_ASSIGN(CredentialsGetterHostClient); +}; + +CredentialsGetterHostClient::CredentialsGetterHostClient( + const std::string& public_key) + : public_key_(public_key.begin(), public_key.end()) { +} + +CredentialsGetterHostClient::~CredentialsGetterHostClient() {} + +bool CredentialsGetterHostClient::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(CredentialsGetterHostClient, message) + IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_GotWiFiCredentials, OnGotCredentials) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void CredentialsGetterHostClient::OnProcessCrashed(int exit_code) { + callback_.Run("", "Process Crashed"); +} + +void CredentialsGetterHostClient::OnProcessLaunchFailed() { + callback_.Run("", "Process Launch Failed"); +} + +void CredentialsGetterHostClient::OnGotCredentials(const std::string& key_data, + bool success) { + if (success) { + std::vector ciphertext; + if (!networking_private_crypto::EncryptByteString( + public_key_, key_data, &ciphertext)) { + callback_.Run("", "Encrypt Credentials Failed"); + return; + } + + std::string base64_encoded_key_data; + base::Base64Encode(std::string(ciphertext.begin(), ciphertext.end()), + &base64_encoded_key_data); + callback_.Run(base64_encoded_key_data, ""); + } else { + callback_.Run("", "Get Credentials Failed"); + } +} + +void CredentialsGetterHostClient::StartProcessOnIOThread( + const std::string& network_guid, + const extensions::NetworkingPrivateServiceClient::CryptoVerify:: + VerifyAndEncryptCredentialsCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + UtilityProcessHost* host = + UtilityProcessHost::Create(this, base::MessageLoopProxy::current()); + callback_ = callback; + host->ElevatePrivileges(); + host->Send(new ChromeUtilityHostMsg_GetWiFiCredentials(network_guid)); +} + +} // namespace + +namespace extensions { + +class NetworkingPrivateCredentialsGetterWin + : public NetworkingPrivateCredentialsGetter { + public: + NetworkingPrivateCredentialsGetterWin(); + + virtual void Start( + const std::string& network_guid, + const std::string& public_key, + const extensions::NetworkingPrivateServiceClient::CryptoVerify:: + VerifyAndEncryptCredentialsCallback& callback) OVERRIDE; + + private: + virtual ~NetworkingPrivateCredentialsGetterWin(); + + DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateCredentialsGetterWin); +}; + +NetworkingPrivateCredentialsGetterWin::NetworkingPrivateCredentialsGetterWin() { +} + +void NetworkingPrivateCredentialsGetterWin::Start( + const std::string& network_guid, + const std::string& public_key, + const extensions::NetworkingPrivateServiceClient::CryptoVerify:: + VerifyAndEncryptCredentialsCallback& callback) { + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind(&CredentialsGetterHostClient::StartProcessOnIOThread, + new CredentialsGetterHostClient(public_key), + network_guid, + callback)); +} + +NetworkingPrivateCredentialsGetterWin:: + ~NetworkingPrivateCredentialsGetterWin() {} + +NetworkingPrivateCredentialsGetter* +NetworkingPrivateCredentialsGetter::Create() { + return new NetworkingPrivateCredentialsGetterWin(); +} + +} // namespace extensions diff --git a/pool/shard001/C++/0017364_ogrwalkselectlayer.cpp b/pool/shard001/C++/0017364_ogrwalkselectlayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7bc6e2e553f91535fda9fea2e896a4d5d6bc67b --- /dev/null +++ b/pool/shard001/C++/0017364_ogrwalkselectlayer.cpp @@ -0,0 +1,139 @@ +/****************************************************************************** + * $Id: ogrwalkselectlayer.cpp + * + * Project: OpenGIS Simple Features Reference Implementation + * Purpose: Implements OGRWalkSelectLayer class, layer access to the results + * of a SELECT statement executed via ExecuteSQL(). + * Author: Xian Chen, chenxian at walkinfo.com.cn + * + ****************************************************************************** + * Copyright (c) 2013, ZJU Walkinfo Technology Corp., 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 "cpl_conv.h" +#include "ogrwalk.h" + +/************************************************************************/ +/* OGRWalkSelectLayer() */ +/************************************************************************/ + +OGRWalkSelectLayer::OGRWalkSelectLayer( OGRWalkDataSource *poDSIn, + CPLODBCStatement * poStmtIn ) + +{ + poDS = poDSIn; + + iNextShapeId = 0; + poFeatureDefn = NULL; + + poStmt = poStmtIn; + pszBaseStatement = CPLStrdup( poStmtIn->GetCommand() ); + + BuildFeatureDefn( "SELECT", poStmt ); +} + +/************************************************************************/ +/* ~OGRWalkSelectLayer() */ +/************************************************************************/ + +OGRWalkSelectLayer::~OGRWalkSelectLayer() + +{ + ClearStatement(); +} + +/************************************************************************/ +/* ClearStatement() */ +/************************************************************************/ + +void OGRWalkSelectLayer::ClearStatement() + +{ + if( poStmt != NULL ) + { + delete poStmt; + poStmt = NULL; + } +} + +/************************************************************************/ +/* GetStatement() */ +/************************************************************************/ + +CPLODBCStatement *OGRWalkSelectLayer::GetStatement() + +{ + if( poStmt == NULL ) + ResetStatement(); + + return poStmt; +} + +/************************************************************************/ +/* ResetStatement() */ +/************************************************************************/ + +OGRErr OGRWalkSelectLayer::ResetStatement() + +{ + ClearStatement(); + + iNextShapeId = 0; + + CPLDebug( "Walk", "Recreating statement." ); + poStmt = new CPLODBCStatement( poDS->GetSession() ); + poStmt->Append( pszBaseStatement ); + + if( poStmt->ExecuteSQL() ) + return OGRERR_NONE; + else + { + delete poStmt; + poStmt = NULL; + return OGRERR_FAILURE; + } +} + +/************************************************************************/ +/* ResetReading() */ +/************************************************************************/ + +void OGRWalkSelectLayer::ResetReading() + +{ + if( iNextShapeId != 0 ) + ClearStatement(); + + OGRWalkLayer::ResetReading(); +} + +/************************************************************************/ +/* GetExtent() */ +/* */ +/* Since SELECT layers currently cannot ever have geometry, we */ +/* can optimize the GetExtent() method! */ +/************************************************************************/ + +OGRErr OGRWalkSelectLayer::GetExtent(OGREnvelope *, int ) + +{ + return OGRERR_FAILURE; +} diff --git a/pool/shard001/C++/0017373_LongestSubstringWithoutRepeatingCharacters.cpp b/pool/shard001/C++/0017373_LongestSubstringWithoutRepeatingCharacters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b78fd880124b5e9bfdcdd3de4ccdd7a57f01173a --- /dev/null +++ b/pool/shard001/C++/0017373_LongestSubstringWithoutRepeatingCharacters.cpp @@ -0,0 +1,43 @@ +// +// LongestSubstringWithoutRepeatingCharacters.cpp +// c++ +// +// Created by sure on 1/22/15. +// Copyright (c) 2015 Shuo Li. All rights reserved. +// + +#include +#include +#include + +class Solution { +public: + int lengthOfLongestSubstring(std::string s) { + int result = 0; + int start = 0; + std::map dict; + for (int i = 0; i < s.length(); i ++) { + std::map::const_iterator it = dict.find(s.at(i)); + if (it != dict.end()) { + int temp = dict.at(s.at(i)); + while (start <= temp) { + dict.erase(s.at(start)); + start ++; + } + } + dict.insert(std::pair(s.at(i), i)); + if ((i - start + 1) > result) { + result = i - start + 1; + } + } + return result; + + } +}; + + +int main() { + Solution *s = new Solution(); + int result = s->lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"); + std::cout< + +// Include some support code for loading pngs. It assumes there's an +// Image type, so we'll pull the one from Halide namespace; +using Halide::Image; +#include "../apps/support/image_io.h" + +int main(int argc, char **argv) { + + // This program defines a single-stage imaging pipeline that + // brightens an image. + + // First we'll load the input image we wish to brighten. + Halide::Image input = load("../apps/images/rgb.png"); + + // Next we define our Func object that represents our one pipeline + // stage. + Halide::Func brighter; + + // Our Func will have three arguments, representing the position + // in the image and the color channel. Halide treats color + // channels as an extra dimension of the image. + Halide::Var x, y, c; + + // Normally we'd probably write the whole function definition on + // one line. Here we'll break it apart so we can explain what + // we're doing at every step. + + // For each pixel of the input image. + Halide::Expr value = input(x, y, c); + + // Cast it to a floating point value. + value = Halide::cast(value); + + // Multiply it by 1.5 to brighten it. Halide represents real + // numbers as floats, not doubles, so we stick an 'f' on the end + // of our constant. + value = value * 1.5f; + + // Clamp it to be less than 255, so we don't get overflow when we + // cast it back to an 8-bit unsigned int. + value = Halide::min(value, 255.0f); + + // Cast it back to an 8-bit unsigned integer. + value = Halide::cast(value); + + // Define the function. + brighter(x, y, c) = value; + + // The equivalent one-liner to all of the above is: + // + // brighter(x, y, c) = Halide::cast(min(input(x, y, c) * 1.5f, 255)); + // + // In the shorter version: + // - I skipped the cast to float, because multiplying by 1.5f does + // that automatically. + // - I also used integer constants in clamp, because they get cast + // to match the type of the first argument. + // - I left the Halide:: off clamp. It's unnecessary due to Koenig + // lookup. + + // Remember. All we've done so far is build a representation of a + // Halide program in memory. We haven't actually processed any + // pixels yet. We haven't even compiled that Halide program yet. + + // So now we'll realize the Func. The size of the output image + // should match the size of the input image. If we just wanted to + // brighten a portion of the input image we could request a + // smaller size. If we request a larger size Halide will throw an + // error at runtime telling us we're trying to read out of bounds + // on the input image. + Halide::Image output = brighter.realize(input.width(), input.height(), input.channels()); + + // Save the output for inspection. It should look like a bright parrot. + save(output, "brighter.png"); + + printf("Success!\n"); + return 0; +} diff --git a/pool/shard001/C++/0017385_JoystickBinder.cpp b/pool/shard001/C++/0017385_JoystickBinder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..903424b40aaeca5c90ae670706be3e1a9b506200 --- /dev/null +++ b/pool/shard001/C++/0017385_JoystickBinder.cpp @@ -0,0 +1,148 @@ +/** +* Provides a mouse binding interface +* +* @file src/GQE/Entity/classes/JoystickBinder.cpp +* @author Jacob Dix +* @date 20140423 - Initial Release +*/ +#include + +namespace GQE +{ + JoystickBinder::JoystickBinder(IApp& theApp) : + mApp(theApp) + { + + } + void JoystickBinder::HandleEvents(sf::Event theEvent) + { + if(theEvent.type==sf::Event::JoystickButtonPressed|| + theEvent.type==sf::Event::JoystickButtonReleased) + { + typeJoystickList::iterator anListIter; + anListIter = mButtonBindings.find(theEvent.joystickButton.joystickId); + if (anListIter != mButtonBindings.end()) + { + std::map::iterator anEntityIter=mEntitys.find(theEvent.joystickButton.joystickId); + typeInputDataList anJoystick = anListIter->second; + typeInputDataList::iterator anButtonIter = anJoystick.find(theEvent.joystickButton.button); + if(anButtonIter!=anJoystick.end() && anEntityIter!=mEntitys.end()) + { + if (((anButtonIter->second.Type == INPUT_PRESSED && theEvent.type == sf::Event::JoystickButtonPressed) || + (anButtonIter->second.Type == INPUT_RELEASED &&theEvent.type == sf::Event::JoystickButtonReleased))&& + anButtonIter->second.EventID!="") + { + PropertyManager anContext; + anContext.Add("Entity",mEntitys[theEvent.joystickButton.joystickId]); + anContext.Add("InputData", anButtonIter->second); + anContext.Add("vInputPosition", sf::Vector2f(0, 0)); + mApp.mEventManager.DoEvent(anButtonIter->second.EventID, &anContext); + } + } + } + } + if(theEvent.type==sf::Event::JoystickMoved) + { + typeJoystickList::iterator anListIter; + anListIter = mAxisBindings.find(theEvent.joystickMove.joystickId); + if (anListIter != mAxisBindings.end()) + { + std::map::iterator anEntityIter=mEntitys.find(theEvent.joystickButton.joystickId); + std::map anJoystick = anListIter->second; + typeInputDataList::iterator anMovmentIter = anJoystick.find(theEvent.joystickMove.axis); + if(anMovmentIter!=anJoystick.end() && anEntityIter!=mEntitys.end()) + { + if ((anMovmentIter->second.Type == INPUT_MOTION && theEvent.type == sf::Event::JoystickMoved) && + anMovmentIter->second.EventID!="") + { + PropertyManager anContext; + + anContext.Add("Entity",mEntitys[theEvent.joystickMove.joystickId]); + anContext.Add("InputData", anMovmentIter->second); + float anAxisPosition = theEvent.joystickMove.position; + sf::Vector2f anPosition(0, 0); + if ((anMovmentIter->second.Axis & AXIS_HORZ) == AXIS_HORZ) + { + anPosition.x = anAxisPosition; + } + if ((anMovmentIter->second.Axis & AXIS_VERT) == AXIS_VERT) + { + anPosition.y = anAxisPosition; + } + anContext.Add("vInputPosition", anPosition); + mApp.mEventManager.DoEvent(anMovmentIter->second.EventID, &anContext); + } + } + } + } + } + void JoystickBinder::UpdateFixed() + { + typeJoystickList::iterator anListIter; + for (anListIter = mButtonBindings.begin(); anListIter != mButtonBindings.end(); ++anListIter) + { + typeInputDataList::iterator anButtonIter; + for (anButtonIter = anListIter->second.begin(); anButtonIter != anListIter->second.end(); ++anButtonIter) + { + if (anButtonIter->second.Type == INPUT_REALTIME && sf::Joystick::isButtonPressed(anListIter->first, anButtonIter->first)) + { + PropertyManager anContext; + anContext.Add("Entity", mEntitys[anListIter->first]); + anContext.Add("InputData", anButtonIter->second); + anContext.Add("vInputPosition", sf::Vector2f(0, 0)); + mApp.mEventManager.DoEvent(anButtonIter->second.EventID, &anContext); + } + } + } + for (anListIter = mAxisBindings.begin(); anListIter != mAxisBindings.end(); ++anListIter) + { + std::map::iterator anMovmentIter; + for (anMovmentIter = anListIter->second.begin(); anMovmentIter != anListIter->second.end(); ++anMovmentIter) + { + if (anMovmentIter->second.Type == INPUT_REALTIME) + { + PropertyManager anContext; + anContext.Add("Entity", mEntitys[anListIter->first]); + anContext.Add("InputData", anMovmentIter->second); + float anAxisPosition = sf::Joystick::getAxisPosition(anListIter->first, (sf::Joystick::Axis)anMovmentIter->first); + sf::Vector2f anPosition(0, 0); + if ((anMovmentIter->second.Axis & AXIS_HORZ) == AXIS_HORZ) + { + anPosition.x = anAxisPosition; + } + if ((anMovmentIter->second.Axis & AXIS_VERT) == AXIS_VERT) + { + anPosition.y = anAxisPosition; + } + anContext.Add("vInputPosition", anPosition); + mApp.mEventManager.DoEvent(anMovmentIter->second.EventID, &anContext); + } + } + } + } + void JoystickBinder::RegisterButton(GQE::Uint32 theJoystick,GQE::Uint32 theButton, typeEventID theEventID, Uint8 theType, Uint32 theAction) + { + InputData anCommand; + anCommand.EventID=theEventID; + anCommand.Type=theType; + anCommand.Action = theAction; + anCommand.Axis = AXIS_NONE; + mButtonBindings[theJoystick][theButton]=anCommand; + } + void JoystickBinder::RegisterAxis(GQE::Uint32 theJoystick,GQE::Uint32 theAxis, typeEventID theEventID, Uint8 theType, Uint32 theAction, Uint32 theMoveAxis) + { + InputData anCommand; + anCommand.EventID = theEventID; + anCommand.Type = theType; + anCommand.Action = theAction; + anCommand.Axis = theMoveAxis; + mAxisBindings[theJoystick][theAxis] = anCommand; + } + void JoystickBinder::RegisterEntity(Uint32 theJoystickID,IEntity* theEntity) + { + if (theEntity!=NULL) + { + mEntitys[theJoystickID]=theEntity; + } + } +} diff --git a/pool/shard001/C++/0017391_UIWizardNewVMPageBasic1.tmp.cpp b/pool/shard001/C++/0017391_UIWizardNewVMPageBasic1.tmp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65f66704c7d9cf05629b502920ade5ac87c0e6f5 --- /dev/null +++ b/pool/shard001/C++/0017391_UIWizardNewVMPageBasic1.tmp.cpp @@ -0,0 +1,131 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'UIWizardNewVMPageBasic1.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../../../../../../src/VBox/Frontends/VirtualBox/src/wizards/newvm/UIWizardNewVMPageBasic1.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'UIWizardNewVMPageBasic1.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.6. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_UIWizardNewVMPageBasic1[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 2, 14, // methods + 2, 24, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + // slots: signature, parameters, type, tag, flags + 36, 25, 24, 24, 0x08, + 60, 24, 24, 24, 0x08, + + // properties: name, type, flags + 87, 79, 0x0a095103, + 101, 79, 0x0a095103, + + 0 // eod +}; + +static const char qt_meta_stringdata_UIWizardNewVMPageBasic1[] = { + "UIWizardNewVMPageBasic1\0\0strNewText\0" + "sltNameChanged(QString)\0sltOsTypeChanged()\0" + "QString\0machineFolder\0machineBaseName\0" +}; + +void UIWizardNewVMPageBasic1::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + UIWizardNewVMPageBasic1 *_t = static_cast(_o); + switch (_id) { + case 0: _t->sltNameChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; + case 1: _t->sltOsTypeChanged(); break; + default: ; + } + } +} + +const QMetaObjectExtraData UIWizardNewVMPageBasic1::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject UIWizardNewVMPageBasic1::staticMetaObject = { + { &UIWizardPage::staticMetaObject, qt_meta_stringdata_UIWizardNewVMPageBasic1, + qt_meta_data_UIWizardNewVMPageBasic1, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &UIWizardNewVMPageBasic1::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *UIWizardNewVMPageBasic1::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *UIWizardNewVMPageBasic1::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_UIWizardNewVMPageBasic1)) + return static_cast(const_cast< UIWizardNewVMPageBasic1*>(this)); + if (!strcmp(_clname, "UIWizardNewVMPage1")) + return static_cast< UIWizardNewVMPage1*>(const_cast< UIWizardNewVMPageBasic1*>(this)); + return UIWizardPage::qt_metacast(_clname); +} + +int UIWizardNewVMPageBasic1::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = UIWizardPage::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 2) + qt_static_metacall(this, _c, _id, _a); + _id -= 2; + } +#ifndef QT_NO_PROPERTIES + else if (_c == QMetaObject::ReadProperty) { + void *_v = _a[0]; + switch (_id) { + case 0: *reinterpret_cast< QString*>(_v) = machineFolder(); break; + case 1: *reinterpret_cast< QString*>(_v) = machineBaseName(); break; + } + _id -= 2; + } else if (_c == QMetaObject::WriteProperty) { + void *_v = _a[0]; + switch (_id) { + case 0: setMachineFolder(*reinterpret_cast< QString*>(_v)); break; + case 1: setMachineBaseName(*reinterpret_cast< QString*>(_v)); break; + } + _id -= 2; + } else if (_c == QMetaObject::ResetProperty) { + _id -= 2; + } else if (_c == QMetaObject::QueryPropertyDesignable) { + _id -= 2; + } else if (_c == QMetaObject::QueryPropertyScriptable) { + _id -= 2; + } else if (_c == QMetaObject::QueryPropertyStored) { + _id -= 2; + } else if (_c == QMetaObject::QueryPropertyEditable) { + _id -= 2; + } else if (_c == QMetaObject::QueryPropertyUser) { + _id -= 2; + } +#endif // QT_NO_PROPERTIES + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard001/C++/0017398_GrStrokeRectBatch.cpp b/pool/shard001/C++/0017398_GrStrokeRectBatch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..766302bf5b5b251b52a0163b2a224099ec432a67 --- /dev/null +++ b/pool/shard001/C++/0017398_GrStrokeRectBatch.cpp @@ -0,0 +1,140 @@ +/* + * Copyright 2015 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "GrStrokeRectBatch.h" +#include "GrBatchTest.h" +#include "GrBatchFlushState.h" +#include "SkRandom.h" + +GrStrokeRectBatch::GrStrokeRectBatch(const Geometry& geometry, bool snapToPixelCenters) { + this->initClassID(); + + fBatch.fHairline = geometry.fStrokeWidth == 0; + + fGeoData.push_back(geometry); + + // setup bounds + fBounds = geometry.fRect; + SkScalar rad = SkScalarHalf(geometry.fStrokeWidth); + fBounds.outset(rad, rad); + geometry.fViewMatrix.mapRect(&fBounds); + + // If our caller snaps to pixel centers then we have to round out the bounds + if (snapToPixelCenters) { + fBounds.roundOut(); + } +} + +void GrStrokeRectBatch::initBatchTracker(const GrPipelineOptimizations& opt) { + // Handle any color overrides + if (!opt.readsColor()) { + fGeoData[0].fColor = GrColor_ILLEGAL; + } + opt.getOverrideColorIfSet(&fGeoData[0].fColor); + + // setup batch properties + fBatch.fColorIgnored = !opt.readsColor(); + fBatch.fColor = fGeoData[0].fColor; + fBatch.fUsesLocalCoords = opt.readsLocalCoords(); + fBatch.fCoverageIgnored = !opt.readsCoverage(); +} + +/* create a triangle strip that strokes the specified rect. There are 8 + unique vertices, but we repeat the last 2 to close up. Alternatively we + could use an indices array, and then only send 8 verts, but not sure that + would be faster. + */ +static void init_stroke_rect_strip(SkPoint verts[10], const SkRect& rect, SkScalar width) { + const SkScalar rad = SkScalarHalf(width); + // TODO we should be able to enable this assert, but we'd have to filter these draws + // this is a bug + //SkASSERT(rad < rect.width() / 2 && rad < rect.height() / 2); + + verts[0].set(rect.fLeft + rad, rect.fTop + rad); + verts[1].set(rect.fLeft - rad, rect.fTop - rad); + verts[2].set(rect.fRight - rad, rect.fTop + rad); + verts[3].set(rect.fRight + rad, rect.fTop - rad); + verts[4].set(rect.fRight - rad, rect.fBottom - rad); + verts[5].set(rect.fRight + rad, rect.fBottom + rad); + verts[6].set(rect.fLeft + rad, rect.fBottom - rad); + verts[7].set(rect.fLeft - rad, rect.fBottom + rad); + verts[8] = verts[0]; + verts[9] = verts[1]; +} + +void GrStrokeRectBatch::onPrepareDraws(Target* target) { + SkAutoTUnref gp; + { + using namespace GrDefaultGeoProcFactory; + Color color(this->color()); + Coverage coverage(this->coverageIgnored() ? Coverage::kSolid_Type : + Coverage::kNone_Type); + LocalCoords localCoords(this->usesLocalCoords() ? LocalCoords::kUsePosition_Type : + LocalCoords::kUnused_Type); + gp.reset(GrDefaultGeoProcFactory::Create(color, coverage, localCoords, + this->viewMatrix())); + } + + target->initDraw(gp, this->pipeline()); + + size_t vertexStride = gp->getVertexStride(); + + SkASSERT(vertexStride == sizeof(GrDefaultGeoProcFactory::PositionAttr)); + + Geometry& args = fGeoData[0]; + + int vertexCount = kVertsPerHairlineRect; + if (args.fStrokeWidth > 0) { + vertexCount = kVertsPerStrokeRect; + } + + const GrVertexBuffer* vertexBuffer; + int firstVertex; + + void* verts = target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer, &firstVertex); + + if (!verts) { + SkDebugf("Could not allocate vertices\n"); + return; + } + + SkPoint* vertex = reinterpret_cast(verts); + + GrPrimitiveType primType; + + if (args.fStrokeWidth > 0) {; + primType = kTriangleStrip_GrPrimitiveType; + args.fRect.sort(); + init_stroke_rect_strip(vertex, args.fRect, args.fStrokeWidth); + } else { + // hairline + primType = kLineStrip_GrPrimitiveType; + vertex[0].set(args.fRect.fLeft, args.fRect.fTop); + vertex[1].set(args.fRect.fRight, args.fRect.fTop); + vertex[2].set(args.fRect.fRight, args.fRect.fBottom); + vertex[3].set(args.fRect.fLeft, args.fRect.fBottom); + vertex[4].set(args.fRect.fLeft, args.fRect.fTop); + } + + GrVertices vertices; + vertices.init(primType, vertexBuffer, firstVertex, vertexCount); + target->draw(vertices); +} + +#ifdef GR_TEST_UTILS + +DRAW_BATCH_TEST_DEFINE(GrStrokeRectBatch) { + GrStrokeRectBatch::Geometry geometry; + geometry.fViewMatrix = GrTest::TestMatrix(random); + geometry.fColor = GrRandomColor(random); + geometry.fRect = GrTest::TestRect(random); + geometry.fStrokeWidth = random->nextBool() ? 0.0f : 1.0f; + + return GrStrokeRectBatch::Create(geometry, random->nextBool()); +} + +#endif diff --git a/pool/shard001/C++/0017402_tm700_demo_test.cpp b/pool/shard001/C++/0017402_tm700_demo_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6279ad0f19e6a8cc2589ea406ca75c7b9b316e9f --- /dev/null +++ b/pool/shard001/C++/0017402_tm700_demo_test.cpp @@ -0,0 +1,301 @@ +/********************************************************************* + * tm700_demo_node.cpp + * + * Copyright 2016 Copyright 2016 Techman Robot 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. + ********************************************************************* + * + * Author: Yun-Hsuan Tsai + */ + +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "tm_msgs/SetIO.h" +//#include "tm_msgs/SetIORequest.h" +//#include "tm_msgs/SetIOResponse.h" + + + +//get current joint values of TM5 +void get_current_joint_values(moveit::planning_interface::MoveGroup& group, + moveit::planning_interface::MoveGroup::Plan& plan, + std::vector& record_joint + ){ + //if(!ros::ok()) return false; + bool success = false; + + std::vector joint_value; + joint_value = group.getCurrentJointValues(); + record_joint = group.getCurrentJointValues(); + + ROS_INFO("In get_current_joint_values()"); + for(int i = 0; i& joint_target, + unsigned int max_try_times = 1 + ) { + if(!ros::ok()) return false; + bool success = false; + + for(unsigned int i = 0; i < max_try_times; i++) { + + group.setJointValueTarget(joint_target); + + if(group.move()) { + success = true; + break; + } + else { + if(!ros::ok()) break; + sleep(1); + } + } +} + +int main(int argc, char **argv) +{ + + ros::init(argc, argv, "tm700_demo_test"); + ros::NodeHandle node_handle; + ros::ServiceClient set_io_client = node_handle.serviceClient("tm_driver/set_io"); + tm_msgs::SetIO io_srv; + io_srv.request.fun = 2;//tm_msgs::SetIORequest::FUN_SET_EE_DIGITAL_OUT; + io_srv.request.ch = 0; + io_srv.request.value = 0.0; + + // start a background "spinner", so our node can process ROS messages + // - this lets us know when the move is completed + ros::AsyncSpinner spinner(1); + spinner.start(); + + sleep(1); + + // Setup + // ^^^^^ + // The :move_group_interface:`MoveGroup` class can be easily + // setup using just the name + // of the group you would like to control and plan for. + moveit::planning_interface::MoveGroup group("manipulator"); + // We will use the :planning_scene_interface:`PlanningSceneInterface` + // class to deal directly with the world. + moveit::planning_interface::PlanningSceneInterface planning_scene_interface; + // (Optional) Create a publisher for visualizing plans in Rviz. + //ros::Publisher display_publisher = node_handle.advertise("/move_group/display_planned_path", 1, true); + //moveit_msgs::DisplayTrajectory display_trajectory; + + // Getting Basic Information + // ^^^^^^^^^^^^^^^^^^^^^^^^^ + // We can print the name of the reference frame for this robot. + ROS_INFO("Reference frame: %s", group.getPlanningFrame().c_str()); + // We can also print the name of the end-effector link for this group. + ROS_INFO("Reference frame: %s", group.getEndEffectorLink().c_str()); + + moveit::planning_interface::MoveGroup::Plan my_plan; + + set_io_client.call(io_srv); + + group.setPlanningTime(30.0); + + //try_move_to_named_target(group, my_plan, "home", 100); + + std::vector joint_target_1; + std::vector joint_target_2; + + std::vector record_joint_1; + std::vector record_joint_2; + std::vector record_joint_3; + + double joint_value = 0; + + joint_target_1.assign(6, 0.0f); + joint_target_1[0] = 0.0174533*( 30.0); + joint_target_1[1] = 0.0174533*( 15.0); + joint_target_1[2] = 0.0174533*(105.0); + joint_target_1[3] = 0.0174533*(-30.0); + joint_target_1[4] = 0.0174533*( 90.0); + joint_target_1[5] = 0.0174533*( 30.0); + + joint_target_2.assign(6, 0.0f); + joint_target_2[0] = 0.0174533*(-30.0); + joint_target_2[1] = 0.0174533*(-15.0); + joint_target_2[2] = 0.0174533*( 90.0); + joint_target_2[3] = 0.0174533*(-75.0); + joint_target_2[4] = 0.0174533*(120.0); + + int step = 0; + int flag = 0; + + while (ros::ok()) { + switch (5) { + + case 0: //gripper off + io_srv.request.fun = 2; + io_srv.request.ch = 0; + io_srv.request.value = 0.0; + + if (set_io_client.call(io_srv)) + ROS_INFO("Set IO success"); + else + ROS_WARN("Failed to call service set_io"); + break; + + case 1: //move to ready + ROS_INFO("move..."); + //try_move_to_named_target(group, my_plan, "ready", 100); + break; + + case 2: //light on + /* + io_srv.request.fun = 2; + io_srv.request.ch = 3; + io_srv.request.value = 1.0; + */ + if (set_io_client.call(io_srv)) + ROS_INFO("Set IO success"); + else + ROS_WARN("Failed to call service set_io"); + break; + + case 3: //wait 3 sec + sleep(3); + break; + + case 4: //light off + io_srv.request.fun = 2; + io_srv.request.ch = 3; + io_srv.request.value = 0.0; + if (set_io_client.call(io_srv)) + ROS_INFO("Set IO success"); + else + ROS_WARN("Failed to call service set_io"); + break; + + case 5: //move 1 + //ROS_INFO("move..."); + //try_move_to_joint_target(group, my_plan, joint_target_1, 100); + ROS_INFO("Teaching Pose 1..."); + while(flag == 0){ + printf("Finish Teaching? Yes: 1, No:0\n"); + scanf("%d", &flag); + get_current_joint_values(group, my_plan, record_joint_1); + } + flag = 0; + + ROS_INFO("Teaching Pose 2..."); + while(flag == 0){ + printf("Finish Teaching? Yes: 1, No:0\n"); + scanf("%d", &flag); + get_current_joint_values(group, my_plan, record_joint_2); + } + flag = 0; + + ROS_INFO("Teaching Pose 3..."); + while(flag == 0){ + printf("Finish Teaching? Yes: 1, No:0\n"); + scanf("%d", &flag); + get_current_joint_values(group, my_plan, record_joint_3); + } + + //ROS_INFO("Teaching Pose 1..."); + for(int i = 0; i + +#define _(x) std::string(x) /* Keep the _() around in case gettext or such will be used later to translate non-UI */ + +using namespace std; +using namespace boost; +using namespace boost::asio; +using namespace json_spirit; + +std::string HelpMessageCli() +{ + string strUsage; + strUsage += _("Options:") + "\n"; + strUsage += " -? " + _("This help message") + "\n"; + strUsage += " -conf= " + strprintf(_("Specify configuration file (default: %s)"), "joulecoin.conf") + "\n"; + strUsage += " -datadir= " + _("Specify data directory") + "\n"; + strUsage += " -testnet " + _("Use the test network") + "\n"; + strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " + "solved instantly. This is intended for regression testing tools and app development.") + "\n"; + strUsage += " -rpcconnect= " + strprintf(_("Send commands to node running on (default: %s)"), "127.0.0.1") + "\n"; + strUsage += " -rpcport= " + strprintf(_("Connect to JSON-RPC on (default: %u or testnet: %u)"), 8332, 18332) + "\n"; + strUsage += " -rpcwait " + _("Wait for RPC server to start") + "\n"; + strUsage += " -rpcuser= " + _("Username for JSON-RPC connections") + "\n"; + strUsage += " -rpcpassword= " + _("Password for JSON-RPC connections") + "\n"; + + strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; + strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; + + return strUsage; +} + +////////////////////////////////////////////////////////////////////////////// +// +// Start +// + +// +// Exception thrown on connection error. This error is used to determine +// when to wait if -rpcwait is given. +// +class CConnectionFailed : public std::runtime_error +{ +public: + + explicit inline CConnectionFailed(const std::string& msg) : + std::runtime_error(msg) + {} + +}; + +static bool AppInitRPC(int argc, char* argv[]) +{ + // + // Parameters + // + ParseParameters(argc, argv); + if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { + std::string strUsage = _("Joulecoin Core RPC client version") + " " + FormatFullVersion() + "\n"; + if (!mapArgs.count("-version")) { + strUsage += "\n" + _("Usage:") + "\n" + + " joulecoin-cli [options] [params] " + _("Send command to Joulecoin Core") + "\n" + + " joulecoin-cli [options] help " + _("List commands") + "\n" + + " joulecoin-cli [options] help " + _("Get help for a command") + "\n"; + + strUsage += "\n" + HelpMessageCli(); + } + + fprintf(stdout, "%s", strUsage.c_str()); + return false; + } + if (!boost::filesystem::is_directory(GetDataDir(false))) { + fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); + return false; + } + try { + ReadConfigFile(mapArgs, mapMultiArgs); + } catch(std::exception &e) { + fprintf(stderr,"Error reading configuration file: %s\n", e.what()); + return false; + } + // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) + if (!SelectBaseParamsFromCommandLine()) { + fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + return false; + } + return true; +} + +Object CallRPC(const string& strMethod, const Array& params) +{ + if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") + throw runtime_error(strprintf( + _("You must set rpcpassword= in the configuration file:\n%s\n" + "If the file does not exist, create it with owner-readable-only file permissions."), + GetConfigFile().string().c_str())); + + // Connect to localhost + bool fUseSSL = GetBoolArg("-rpcssl", false); + asio::io_service io_service; + ssl::context context(io_service, ssl::context::sslv23); + context.set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3); + asio::ssl::stream sslStream(io_service, context); + SSLIOStreamDevice d(sslStream, fUseSSL); + iostreams::stream< SSLIOStreamDevice > stream(d); + + const bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(BaseParams().RPCPort()))); + if (!fConnected) + throw CConnectionFailed("couldn't connect to server"); + + // HTTP basic authentication + string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); + map mapRequestHeaders; + mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; + + // Send request + string strRequest = JSONRPCRequest(strMethod, params, 1); + string strPost = HTTPPost(strRequest, mapRequestHeaders); + stream << strPost << std::flush; + + // Receive HTTP reply status + int nProto = 0; + int nStatus = ReadHTTPStatus(stream, nProto); + + // Receive HTTP reply message headers and body + map mapHeaders; + string strReply; + ReadHTTPMessage(stream, mapHeaders, strReply, nProto, std::numeric_limits::max()); + + if (nStatus == HTTP_UNAUTHORIZED) + throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); + else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) + throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); + else if (strReply.empty()) + throw runtime_error("no response from server"); + + // Parse reply + Value valReply; + if (!read_string(strReply, valReply)) + throw runtime_error("couldn't parse reply from server"); + const Object& reply = valReply.get_obj(); + if (reply.empty()) + throw runtime_error("expected reply to have result, error and id properties"); + + return reply; +} + +int CommandLineRPC(int argc, char *argv[]) +{ + string strPrint; + int nRet = 0; + try { + // Skip switches + while (argc > 1 && IsSwitchChar(argv[1][0])) { + argc--; + argv++; + } + + // Method + if (argc < 2) + throw runtime_error("too few parameters"); + string strMethod = argv[1]; + + // Parameters default to strings + std::vector strParams(&argv[2], &argv[argc]); + Array params = RPCConvertValues(strMethod, strParams); + + // Execute and handle connection failures with -rpcwait + const bool fWait = GetBoolArg("-rpcwait", false); + do { + try { + const Object reply = CallRPC(strMethod, params); + + // Parse reply + const Value& result = find_value(reply, "result"); + const Value& error = find_value(reply, "error"); + + if (error.type() != null_type) { + // Error + const int code = find_value(error.get_obj(), "code").get_int(); + if (fWait && code == RPC_IN_WARMUP) + throw CConnectionFailed("server in warmup"); + strPrint = "error: " + write_string(error, false); + nRet = abs(code); + } else { + // Result + if (result.type() == null_type) + strPrint = ""; + else if (result.type() == str_type) + strPrint = result.get_str(); + else + strPrint = write_string(result, true); + } + + // Connection succeeded, no need to retry. + break; + } + catch (const CConnectionFailed& e) { + if (fWait) + MilliSleep(1000); + else + throw; + } + } while (fWait); + } + catch (boost::thread_interrupted) { + throw; + } + catch (std::exception& e) { + strPrint = string("error: ") + e.what(); + nRet = EXIT_FAILURE; + } + catch (...) { + PrintExceptionContinue(NULL, "CommandLineRPC()"); + throw; + } + + if (strPrint != "") { + fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); + } + return nRet; +} + +int main(int argc, char* argv[]) +{ + SetupEnvironment(); + + try { + if(!AppInitRPC(argc, argv)) + return EXIT_FAILURE; + } + catch (std::exception& e) { + PrintExceptionContinue(&e, "AppInitRPC()"); + return EXIT_FAILURE; + } catch (...) { + PrintExceptionContinue(NULL, "AppInitRPC()"); + return EXIT_FAILURE; + } + + int ret = EXIT_FAILURE; + try { + ret = CommandLineRPC(argc, argv); + } + catch (std::exception& e) { + PrintExceptionContinue(&e, "CommandLineRPC()"); + } catch (...) { + PrintExceptionContinue(NULL, "CommandLineRPC()"); + } + return ret; +} diff --git a/pool/shard001/C++/0017404_ColorAnimation.cpp b/pool/shard001/C++/0017404_ColorAnimation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa3fc8ffa2bcf5ff03df4859cb9d4e7cd2bb57c3 --- /dev/null +++ b/pool/shard001/C++/0017404_ColorAnimation.cpp @@ -0,0 +1,53 @@ +#include "ColorAnimation.h" +#include +#include + +#define M_PI 3.14159265358979323846f + + +sf::Color ColorAnimation::getColorByIndex(uint8_t idx) const{ + switch (idx){ + case 0: return sf::Color::Red; + case 1: return sf::Color::Yellow; + case 2: return sf::Color::Green; + case 3: return sf::Color::Cyan; + case 4: return sf::Color::Blue; + case 5: return sf::Color::Magenta; + default: assert(false); return sf::Color::White; + } +} + +ColorAnimation::ColorAnimation(float animationSpeed, uint8_t colorPosition){ + init(animationSpeed, colorPosition); +} + +void ColorAnimation::init(float animationSpeed, uint8_t colorPosition){ + this->animationSpeed = animationSpeed; + assert(colorPosition < 100); //0..99 + nextColor = static_cast(colorPosition / (100.f / 6.f)); //0..5 + assert(nextColor >= 0 && nextColor <= 5); + progress = (100.f / 6.f) / (100.f - (100 / 6 * nextColor)); + assert(progress >= 0 && progress <= 1); +} + +void ColorAnimation::animate(float elapsedTime){ + progress += animationSpeed * elapsedTime; + + uint8_t overflow = static_cast(progress); + progress -= overflow; + nextColor = (nextColor + overflow) % 6; +} + +void ColorAnimation::setSpeed(float animationSpeed){ + this->animationSpeed = animationSpeed; +} + +sf::Color ColorAnimation::getColor(sf::Uint8 alpha) const{ + assert(progress <= 1); + sf::Color f = getColorByIndex(nextColor - 1 >= 0 ? nextColor - 1 : 5); //from + sf::Color t = getColorByIndex(nextColor); //to + float from = progress; + float to = 1.f - from; + return sf::Color(static_cast(f.r * to + t.r * from), static_cast(f.g * to + t.g * from), static_cast(f.b * to + t.b * from), alpha); + +} diff --git a/pool/shard001/C++/0017405_DragDropAction_StoryGraph.cpp b/pool/shard001/C++/0017405_DragDropAction_StoryGraph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc3941543e6c8f21807e38f2cbd7c43ec5794c71 --- /dev/null +++ b/pool/shard001/C++/0017405_DragDropAction_StoryGraph.cpp @@ -0,0 +1,149 @@ +// Copyright 2016 Dmitriy Pavlov + +#include "DragDropAction_StoryGraph.h" +#include "StoryGraphObject.h" +#include "CustomNods.h" +#include "GraphSchema_StoryGraph.h" +#include "EdGraph/EdGraph.h" + + +void FDragDropAction_StoryGraph::HoverTargetChanged() +{ + UEdGraph* HoveredGraph = GetHoveredGraph(); + const UEdGraphSchema_Base* HoveredSchema = NULL; + bool CanCreateNode = false; + + FSlateColor IconColor = FLinearColor::White; + const FSlateBrush* StatusSymbol = FEditorStyle::GetBrush(TEXT("Graph.ConnectorFeedback.Error")); + FText Message = FText::FromString("Cannot create node"); + + if (HoveredGraph) + { + + HoveredSchema = Cast(HoveredGraph->GetSchema()); + + + for (int i = 0; i < DraggedObject->DependetNodes.Num(); i++) + { + if (HoveredSchema && UCustomNodeBase::GetIncertNodeType(DraggedObject->DependetNodes[i]) == HoveredSchema->SuitableDependetNodesType) + { + CanCreateNode = true; + } + } + + } + + + if (CanCreateNode) + { + StatusSymbol = FEditorStyle::GetBrush(TEXT("Graph.ConnectorFeedback.OK")); + Message = FText::FromString("Can create node"); + } + + + + SetSimpleFeedbackMessage(StatusSymbol, IconColor, Message); +} + +FReply FDragDropAction_StoryGraph::DroppedOnPin(FVector2D ScreenPosition, FVector2D GraphPosition) +{ + //UE_LOG(StoryGraphEditor, Warning, TEXT("Dropped On Pin")); + + return FReply::Handled(); +} + +FReply FDragDropAction_StoryGraph::DroppedOnNode(FVector2D ScreenPosition, FVector2D GraphPosition) +{ + //UE_LOG(StoryGraphEditor, Warning, TEXT("Dropped On Node")); + + return FReply::Unhandled(); +} + + + + +FReply FDragDropAction_StoryGraph::DroppedOnPanel( const TSharedRef< SWidget >& Panel, FVector2D ScreenPosition, FVector2D GraphPosition, UEdGraph& Graph) +{ + + FNodeConstructionParams NewNodeParams; + int MenuEntryCounter = 0; + + NewNodeParams.Graph = &Graph; + NewNodeParams.DraggedObject = DraggedObject; + NewNodeParams.GraphPosition = GraphPosition; + + const UEdGraphSchema_Base* GraphSchema = Cast(Graph.GetSchema()); + + EIncertNodeType SuitableDependetNodesType = GraphSchema->SuitableDependetNodesType; + + + FMenuBuilder MenuBuilder(true, NULL); + const FText VariableNameText = FText::FromString("Dependent nods"); + + MenuBuilder.BeginSection("BPVariableDroppedOn", VariableNameText ); + + FText MenuDesc; + FText ToolTip; + + for (int i = 0; i < DraggedObject->DependetNodes.Num(); i++) + { + if (UCustomNodeBase::GetIncertNodeType(DraggedObject->DependetNodes[i]) == SuitableDependetNodesType) + { + NewNodeParams.NodeType = DraggedObject->DependetNodes[i]; + + MenuDesc = FText::FromString(UCustomNodeBase::GetActionNameFromNodeType(DraggedObject->DependetNodes[i])); + ToolTip = FText::FromString(UCustomNodeBase::GetToolTipFromNodeType(DraggedObject->DependetNodes[i])); + + MenuBuilder.AddMenuEntry( + MenuDesc, + ToolTip, + FSlateIcon(), + FUIAction(FExecuteAction::CreateStatic(&FDragDropAction_StoryGraph::SpawnNode, NewNodeParams)) + ); + MenuEntryCounter++; + } + } + + if (MenuEntryCounter > 0) + { + TSharedRef< SWidget > PanelWidget = Panel; + // Show dialog to choose getter vs setter + FSlateApplication::Get().PushMenu( + PanelWidget, + FWidgetPath(), + MenuBuilder.MakeWidget(), + ScreenPosition, + FPopupTransitionEffect(FPopupTransitionEffect::ContextMenu) + ); + + MenuBuilder.EndSection(); + } + + return FReply::Handled(); +} + + + +FReply FDragDropAction_StoryGraph::DroppedOnAction(TSharedRef Action) +{ + //UE_LOG(StoryGraphEditor, Warning, TEXT("Dropped On Action")); + + return FReply::Unhandled(); +} + +FReply FDragDropAction_StoryGraph::DroppedOnCategory(FText Category) +{ + //UE_LOG(StoryGraphEditor, Log, TEXT("Dropped on Category")); + + + + return FReply::Handled(); +} + + +void FDragDropAction_StoryGraph::SpawnNode(FNodeConstructionParams InParams) +{ + + FCustomSchemaAction_NewNode::SpawnNode(InParams.NodeType, InParams.DraggedObject, InParams.Graph, NULL, InParams.GraphPosition); + +} diff --git a/pool/shard001/C++/0017419_router_ratelimit.cc b/pool/shard001/C++/0017419_router_ratelimit.cc new file mode 100644 index 0000000000000000000000000000000000000000..4713f6e467e0fffbf39466edcb00929dbb7c54f1 --- /dev/null +++ b/pool/shard001/C++/0017419_router_ratelimit.cc @@ -0,0 +1,155 @@ +#include "common/router/router_ratelimit.h" + +#include +#include +#include +#include + +#include "common/common/assert.h" +#include "common/common/empty_string.h" +#include "common/protobuf/utility.h" + +namespace Envoy { +namespace Router { + +const uint64_t RateLimitPolicyImpl::MAX_STAGE_NUMBER = 10UL; + +bool SourceClusterAction::populateDescriptor(const Router::RouteEntry&, + RateLimit::Descriptor& descriptor, + const std::string& local_service_cluster, + const Http::HeaderMap&, + const Network::Address::Instance&) const { + descriptor.entries_.push_back({"source_cluster", local_service_cluster}); + return true; +} + +bool DestinationClusterAction::populateDescriptor(const Router::RouteEntry& route, + RateLimit::Descriptor& descriptor, + const std::string&, const Http::HeaderMap&, + const Network::Address::Instance&) const { + descriptor.entries_.push_back({"destination_cluster", route.clusterName()}); + return true; +} + +bool RequestHeadersAction::populateDescriptor(const Router::RouteEntry&, + RateLimit::Descriptor& descriptor, const std::string&, + const Http::HeaderMap& headers, + const Network::Address::Instance&) const { + const Http::HeaderEntry* header_value = headers.get(header_name_); + if (!header_value) { + return false; + } + + descriptor.entries_.push_back({descriptor_key_, header_value->value().c_str()}); + return true; +} + +bool RemoteAddressAction::populateDescriptor( + const Router::RouteEntry&, RateLimit::Descriptor& descriptor, const std::string&, + const Http::HeaderMap&, const Network::Address::Instance& remote_address) const { + if (remote_address.type() != Network::Address::Type::Ip) { + return false; + } + + descriptor.entries_.push_back({"remote_address", remote_address.ip()->addressAsString()}); + return true; +} + +bool GenericKeyAction::populateDescriptor(const Router::RouteEntry&, + RateLimit::Descriptor& descriptor, const std::string&, + const Http::HeaderMap&, + const Network::Address::Instance&) const { + descriptor.entries_.push_back({"generic_key", descriptor_value_}); + return true; +} + +HeaderValueMatchAction::HeaderValueMatchAction( + const envoy::api::v2::route::RateLimit::Action::HeaderValueMatch& action) + : descriptor_value_(action.descriptor_value()), + expect_match_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(action, expect_match, true)) { + for (const auto& header_matcher : action.headers()) { + action_headers_.push_back(header_matcher); + } +} + +bool HeaderValueMatchAction::populateDescriptor(const Router::RouteEntry&, + RateLimit::Descriptor& descriptor, + const std::string&, const Http::HeaderMap& headers, + const Network::Address::Instance&) const { + if (expect_match_ == Http::HeaderUtility::matchHeaders(headers, action_headers_)) { + descriptor.entries_.push_back({"header_match", descriptor_value_}); + return true; + } else { + return false; + } +} + +RateLimitPolicyEntryImpl::RateLimitPolicyEntryImpl(const envoy::api::v2::route::RateLimit& config) + : disable_key_(config.disable_key()), + stage_(static_cast(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, stage, 0))) { + for (const auto& action : config.actions()) { + switch (action.action_specifier_case()) { + case envoy::api::v2::route::RateLimit::Action::kSourceCluster: + actions_.emplace_back(new SourceClusterAction()); + break; + case envoy::api::v2::route::RateLimit::Action::kDestinationCluster: + actions_.emplace_back(new DestinationClusterAction()); + break; + case envoy::api::v2::route::RateLimit::Action::kRequestHeaders: + actions_.emplace_back(new RequestHeadersAction(action.request_headers())); + break; + case envoy::api::v2::route::RateLimit::Action::kRemoteAddress: + actions_.emplace_back(new RemoteAddressAction()); + break; + case envoy::api::v2::route::RateLimit::Action::kGenericKey: + actions_.emplace_back(new GenericKeyAction(action.generic_key())); + break; + case envoy::api::v2::route::RateLimit::Action::kHeaderValueMatch: + actions_.emplace_back(new HeaderValueMatchAction(action.header_value_match())); + break; + default: + NOT_REACHED; + } + } +} + +void RateLimitPolicyEntryImpl::populateDescriptors( + const Router::RouteEntry& route, std::vector& descriptors, + const std::string& local_service_cluster, const Http::HeaderMap& headers, + const Network::Address::Instance& remote_address) const { + RateLimit::Descriptor descriptor; + bool result = true; + for (const RateLimitActionPtr& action : actions_) { + result = result && action->populateDescriptor(route, descriptor, local_service_cluster, headers, + remote_address); + if (!result) { + break; + } + } + + if (result) { + descriptors.emplace_back(descriptor); + } +} + +RateLimitPolicyImpl::RateLimitPolicyImpl( + const Protobuf::RepeatedPtrField& rate_limits) + : rate_limit_entries_reference_(RateLimitPolicyImpl::MAX_STAGE_NUMBER + 1) { + for (const auto& rate_limit : rate_limits) { + std::unique_ptr rate_limit_policy_entry( + new RateLimitPolicyEntryImpl(rate_limit)); + uint64_t stage = rate_limit_policy_entry->stage(); + ASSERT(stage < rate_limit_entries_reference_.size()); + rate_limit_entries_reference_[stage].emplace_back(*rate_limit_policy_entry); + rate_limit_entries_.emplace_back(std::move(rate_limit_policy_entry)); + } +} + +const std::vector>& +RateLimitPolicyImpl::getApplicableRateLimit(uint64_t stage) const { + ASSERT(stage < rate_limit_entries_reference_.size()); + return rate_limit_entries_reference_[stage]; +} + +} // namespace Router +} // namespace Envoy diff --git a/pool/shard001/C++/0017421_encryption_key_validation.cc b/pool/shard001/C++/0017421_encryption_key_validation.cc new file mode 100644 index 0000000000000000000000000000000000000000..4980ce32029dfcd84b4f302b50935b3fb3d0242c --- /dev/null +++ b/pool/shard001/C++/0017421_encryption_key_validation.cc @@ -0,0 +1,128 @@ +/** + * @file encryption_key_validation.h + * + * @section LICENSE + * + * The MIT License + * + * @copyright Copyright (c) 2018-2021 TileDB, Inc. + * + * 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. + * + * @section DESCRIPTION + * + * This file defines a class for encryption key validation. + */ + +#include "tiledb/sm/crypto/encryption_key_validation.h" +#include "tiledb/common/logger.h" +#include "tiledb/sm/crypto/crypto.h" +#include "tiledb/sm/crypto/encryption_key.h" +#include "tiledb/sm/enums/encryption_type.h" + +using namespace tiledb::common; + +namespace tiledb { +namespace sm { + +const std::string EncryptionKeyValidation::ENCRYPTION_KEY_CHECK_DATA = + "TILEDB_ENCRYPTION_KEY_CHECK_DATA"; + +Status EncryptionKeyValidation::check_encryption_key( + const EncryptionKey& encryption_key) { + // First time: encrypt the check data. + if (encryption_key_check_data_.size() == 0) + RETURN_NOT_OK(init_encryption_key_check_data(encryption_key)); + + // Decrypt the data and check that it is the same. + Buffer output; + ConstBuffer input( + encryption_key_check_data_.data(), encryption_key_check_data_.size()); + switch (encryption_key.encryption_type()) { + case EncryptionType::NO_ENCRYPTION: + RETURN_NOT_OK(output.write(&input, input.size())); + break; + case EncryptionType::AES_256_GCM: { + ConstBuffer iv( + encryption_key_check_data_iv_.data(), + encryption_key_check_data_iv_.size()); + ConstBuffer tag( + encryption_key_check_data_tag_.data(), + encryption_key_check_data_tag_.size()); + ConstBuffer key = encryption_key.key(); + RETURN_NOT_OK( + Crypto::decrypt_aes256gcm(&key, &iv, &tag, &input, &output)); + break; + } + default: + return LOG_STATUS(Status_EncryptionError( + "Invalid encryption key; invalid encryption type.")); + } + + if (output.size() != ENCRYPTION_KEY_CHECK_DATA.size()) + return LOG_STATUS(Status_EncryptionError("Invalid encryption key.")); + for (uint64_t i = 0; i < output.size(); i++) { + if (output.value(i * sizeof(char)) != ENCRYPTION_KEY_CHECK_DATA[i]) + return LOG_STATUS(Status_EncryptionError("Invalid encryption key.")); + } + + return Status::Ok(); +} + +Status EncryptionKeyValidation::init_encryption_key_check_data( + const EncryptionKey& encryption_key) { + encryption_key_check_data_.clear(); + encryption_key_check_data_tag_.clear(); + encryption_key_check_data_iv_.clear(); + + ConstBuffer input( + ENCRYPTION_KEY_CHECK_DATA.data(), ENCRYPTION_KEY_CHECK_DATA.size()); + + switch (encryption_key.encryption_type()) { + case EncryptionType::NO_ENCRYPTION: + RETURN_NOT_OK(encryption_key_check_data_.write(&input, input.size())); + break; + case EncryptionType::AES_256_GCM: { + RETURN_NOT_OK( + encryption_key_check_data_iv_.realloc(Crypto::AES256GCM_IV_BYTES)); + RETURN_NOT_OK( + encryption_key_check_data_tag_.realloc(Crypto::AES256GCM_TAG_BYTES)); + ConstBuffer key = encryption_key.key(); + PreallocatedBuffer iv( + encryption_key_check_data_iv_.data(), + encryption_key_check_data_iv_.alloced_size()); + PreallocatedBuffer tag( + encryption_key_check_data_tag_.data(), + encryption_key_check_data_tag_.alloced_size()); + RETURN_NOT_OK(Crypto::encrypt_aes256gcm( + &key, nullptr, &input, &encryption_key_check_data_, &iv, &tag)); + encryption_key_check_data_iv_.advance_size(Crypto::AES256GCM_IV_BYTES); + encryption_key_check_data_tag_.advance_size(Crypto::AES256GCM_TAG_BYTES); + break; + } + default: + return LOG_STATUS(Status_EncryptionError( + "Invalid encryption key; invalid encryption type.")); + } + + return Status::Ok(); +} + +} // namespace sm +} // namespace tiledb diff --git a/pool/shard001/C++/0017423_addroletoinstanceprofileresponse.cpp b/pool/shard001/C++/0017423_addroletoinstanceprofileresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee4fba4769df7593941172c394b3f4dcb68c24c7 --- /dev/null +++ b/pool/shard001/C++/0017423_addroletoinstanceprofileresponse.cpp @@ -0,0 +1,107 @@ +/* + 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 "addroletoinstanceprofileresponse.h" +#include "addroletoinstanceprofileresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace IAM { + +/*! + * \class QtAws::IAM::AddRoleToInstanceProfileResponse + * \brief The AddRoleToInstanceProfileResponse class provides an interace for IAM AddRoleToInstanceProfile responses. + * + * \inmodule QtAwsIAM + * + * AWS Identity and Access Management + * + * AWS Identity and Access Management (IAM) is a web service for securely controlling access to AWS services. With IAM, you + * can centrally manage users, security credentials such as access keys, and permissions that control which AWS resources + * users and applications can access. For more information about IAM, see AWS Identity + * and Access Management (IAM) and the AWS Identity and + * Access Management User + * + * \sa IamClient::addRoleToInstanceProfile + */ + +/*! + * Constructs a AddRoleToInstanceProfileResponse object for \a reply to \a request, with parent \a parent. + */ +AddRoleToInstanceProfileResponse::AddRoleToInstanceProfileResponse( + const AddRoleToInstanceProfileRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : IamResponse(new AddRoleToInstanceProfileResponsePrivate(this), parent) +{ + setRequest(new AddRoleToInstanceProfileRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const AddRoleToInstanceProfileRequest * AddRoleToInstanceProfileResponse::request() const +{ + Q_D(const AddRoleToInstanceProfileResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful IAM AddRoleToInstanceProfile \a response. + */ +void AddRoleToInstanceProfileResponse::parseSuccess(QIODevice &response) +{ + //Q_D(AddRoleToInstanceProfileResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::IAM::AddRoleToInstanceProfileResponsePrivate + * \brief The AddRoleToInstanceProfileResponsePrivate class provides private implementation for AddRoleToInstanceProfileResponse. + * \internal + * + * \inmodule QtAwsIAM + */ + +/*! + * Constructs a AddRoleToInstanceProfileResponsePrivate object with public implementation \a q. + */ +AddRoleToInstanceProfileResponsePrivate::AddRoleToInstanceProfileResponsePrivate( + AddRoleToInstanceProfileResponse * const q) : IamResponsePrivate(q) +{ + +} + +/*! + * Parses a IAM AddRoleToInstanceProfile response element from \a xml. + */ +void AddRoleToInstanceProfileResponsePrivate::parseAddRoleToInstanceProfileResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("AddRoleToInstanceProfileResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace IAM +} // namespace QtAws diff --git a/pool/shard001/C++/0017424_menu_button.cc b/pool/shard001/C++/0017424_menu_button.cc new file mode 100644 index 0000000000000000000000000000000000000000..29271cea51f3d5d9f9ac96ae61759a2452267a07 --- /dev/null +++ b/pool/shard001/C++/0017424_menu_button.cc @@ -0,0 +1,290 @@ +// 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 "ui/views/controls/button/menu_button.h" + +#include "base/strings/utf_string_conversions.h" +#include "grit/ui_resources.h" +#include "grit/ui_strings.h" +#include "ui/accessibility/ax_view_state.h" +#include "ui/base/dragdrop/drag_drop_types.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/events/event.h" +#include "ui/events/event_constants.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/image/image.h" +#include "ui/gfx/screen.h" +#include "ui/gfx/text_constants.h" +#include "ui/views/controls/button/button.h" +#include "ui/views/controls/button/menu_button_listener.h" +#include "ui/views/mouse_constants.h" +#include "ui/views/widget/root_view.h" +#include "ui/views/widget/widget.h" + +using base::TimeTicks; +using base::TimeDelta; + +namespace views { + +// Default menu offset. +static const int kDefaultMenuOffsetX = -2; +static const int kDefaultMenuOffsetY = -4; + +// static +const char MenuButton::kViewClassName[] = "MenuButton"; +const int MenuButton::kMenuMarkerPaddingLeft = 3; +const int MenuButton::kMenuMarkerPaddingRight = -1; + +//////////////////////////////////////////////////////////////////////////////// +// +// MenuButton - constructors, destructors, initialization +// +//////////////////////////////////////////////////////////////////////////////// + +MenuButton::MenuButton(ButtonListener* listener, + const base::string16& text, + MenuButtonListener* menu_button_listener, + bool show_menu_marker) + : LabelButton(listener, text), + menu_visible_(false), + menu_offset_(kDefaultMenuOffsetX, kDefaultMenuOffsetY), + listener_(menu_button_listener), + show_menu_marker_(show_menu_marker), + menu_marker_(ui::ResourceBundle::GetSharedInstance().GetImageNamed( + IDR_MENU_DROPARROW).ToImageSkia()), + destroyed_flag_(NULL) { + SetHorizontalAlignment(gfx::ALIGN_LEFT); +} + +MenuButton::~MenuButton() { + if (destroyed_flag_) + *destroyed_flag_ = true; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// MenuButton - Public APIs +// +//////////////////////////////////////////////////////////////////////////////// + +bool MenuButton::Activate() { + SetState(STATE_PRESSED); + if (listener_) { + gfx::Rect lb = GetLocalBounds(); + + // The position of the menu depends on whether or not the locale is + // right-to-left. + gfx::Point menu_position(lb.right(), lb.bottom()); + if (base::i18n::IsRTL()) + menu_position.set_x(lb.x()); + + View::ConvertPointToScreen(this, &menu_position); + if (base::i18n::IsRTL()) + menu_position.Offset(-menu_offset_.x(), menu_offset_.y()); + else + menu_position.Offset(menu_offset_.x(), menu_offset_.y()); + + int max_x_coordinate = GetMaximumScreenXCoordinate(); + if (max_x_coordinate && max_x_coordinate <= menu_position.x()) + menu_position.set_x(max_x_coordinate - 1); + + // We're about to show the menu from a mouse press. By showing from the + // mouse press event we block RootView in mouse dispatching. This also + // appears to cause RootView to get a mouse pressed BEFORE the mouse + // release is seen, which means RootView sends us another mouse press no + // matter where the user pressed. To force RootView to recalculate the + // mouse target during the mouse press we explicitly set the mouse handler + // to NULL. + static_cast(GetWidget()->GetRootView())-> + SetMouseHandler(NULL); + + menu_visible_ = true; + + bool destroyed = false; + destroyed_flag_ = &destroyed; + + listener_->OnMenuButtonClicked(this, menu_position); + + if (destroyed) { + // The menu was deleted while showing. Don't attempt any processing. + return false; + } + + destroyed_flag_ = NULL; + + menu_visible_ = false; + menu_closed_time_ = TimeTicks::Now(); + + // Now that the menu has closed, we need to manually reset state to + // "normal" since the menu modal loop will have prevented normal + // mouse move messages from getting to this View. We set "normal" + // and not "hot" because the likelihood is that the mouse is now + // somewhere else (user clicked elsewhere on screen to close the menu + // or selected an item) and we will inevitably refresh the hot state + // in the event the mouse _is_ over the view. + SetState(STATE_NORMAL); + + // We must return false here so that the RootView does not get stuck + // sending all mouse pressed events to us instead of the appropriate + // target. + return false; + } + return true; +} + +void MenuButton::OnPaint(gfx::Canvas* canvas) { + LabelButton::OnPaint(canvas); + + if (show_menu_marker_) + PaintMenuMarker(canvas); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// MenuButton - Events +// +//////////////////////////////////////////////////////////////////////////////// + +gfx::Size MenuButton::GetPreferredSize() const { + gfx::Size prefsize = LabelButton::GetPreferredSize(); + if (show_menu_marker_) { + prefsize.Enlarge(menu_marker_->width() + kMenuMarkerPaddingLeft + + kMenuMarkerPaddingRight, + 0); + } + return prefsize; +} + +const char* MenuButton::GetClassName() const { + return kViewClassName; +} + +bool MenuButton::OnMousePressed(const ui::MouseEvent& event) { + RequestFocus(); + if (state() != STATE_DISABLED) { + // If we're draggable (GetDragOperations returns a non-zero value), then + // don't pop on press, instead wait for release. + if (event.IsOnlyLeftMouseButton() && + HitTestPoint(event.location()) && + GetDragOperations(event.location()) == ui::DragDropTypes::DRAG_NONE) { + TimeDelta delta = TimeTicks::Now() - menu_closed_time_; + if (delta.InMilliseconds() > kMinimumMsBetweenButtonClicks) + return Activate(); + } + } + return true; +} + +void MenuButton::OnMouseReleased(const ui::MouseEvent& event) { + // Explicitly test for left mouse button to show the menu. If we tested for + // !IsTriggerableEvent it could lead to a situation where we end up showing + // the menu and context menu (this would happen if the right button is not + // triggerable and there's a context menu). + if (GetDragOperations(event.location()) != ui::DragDropTypes::DRAG_NONE && + state() != STATE_DISABLED && !InDrag() && event.IsOnlyLeftMouseButton() && + HitTestPoint(event.location())) { + Activate(); + } else { + LabelButton::OnMouseReleased(event); + } +} + +// The reason we override View::OnMouseExited is because we get this event when +// we display the menu. If we don't override this method then +// BaseButton::OnMouseExited will get the event and will set the button's state +// to STATE_NORMAL instead of keeping the state BM_PUSHED. This, in turn, will +// cause the button to appear depressed while the menu is displayed. +void MenuButton::OnMouseExited(const ui::MouseEvent& event) { + if ((state_ != STATE_DISABLED) && (!menu_visible_) && (!InDrag())) { + SetState(STATE_NORMAL); + } +} + +void MenuButton::OnGestureEvent(ui::GestureEvent* event) { + if (state() != STATE_DISABLED && event->type() == ui::ET_GESTURE_TAP && + !Activate()) { + // When |Activate()| returns |false|, it means that a menu is shown and + // has handled the gesture event. So, there is no need to further process + // the gesture event here. + return; + } + LabelButton::OnGestureEvent(event); +} + +bool MenuButton::OnKeyPressed(const ui::KeyEvent& event) { + switch (event.key_code()) { + case ui::VKEY_SPACE: + // Alt-space on windows should show the window menu. + if (event.IsAltDown()) + break; + case ui::VKEY_RETURN: + case ui::VKEY_UP: + case ui::VKEY_DOWN: { + // WARNING: we may have been deleted by the time Activate returns. + Activate(); + // This is to prevent the keyboard event from being dispatched twice. If + // the keyboard event is not handled, we pass it to the default handler + // which dispatches the event back to us causing the menu to get displayed + // again. Return true to prevent this. + return true; + } + default: + break; + } + return false; +} + +bool MenuButton::OnKeyReleased(const ui::KeyEvent& event) { + // Override CustomButton's implementation, which presses the button when + // you press space and clicks it when you release space. For a MenuButton + // we always activate the menu on key press. + return false; +} + +void MenuButton::GetAccessibleState(ui::AXViewState* state) { + CustomButton::GetAccessibleState(state); + state->role = ui::AX_ROLE_POP_UP_BUTTON; + state->default_action = l10n_util::GetStringUTF16(IDS_APP_ACCACTION_PRESS); + state->AddStateFlag(ui::AX_STATE_HASPOPUP); +} + +void MenuButton::PaintMenuMarker(gfx::Canvas* canvas) { + gfx::Insets insets = GetInsets(); + + // We can not use the views' mirroring infrastructure for mirroring a + // MenuButton control (see TextButton::OnPaint() for a detailed explanation + // regarding why we can not flip the canvas). Therefore, we need to + // manually mirror the position of the down arrow. + gfx::Rect arrow_bounds(width() - insets.right() - + menu_marker_->width() - kMenuMarkerPaddingRight, + height() / 2 - menu_marker_->height() / 2, + menu_marker_->width(), + menu_marker_->height()); + arrow_bounds.set_x(GetMirroredXForRect(arrow_bounds)); + canvas->DrawImageInt(*menu_marker_, arrow_bounds.x(), arrow_bounds.y()); +} + +gfx::Rect MenuButton::GetChildAreaBounds() { + gfx::Size s = size(); + + if (show_menu_marker_) { + s.set_width(s.width() - menu_marker_->width() - kMenuMarkerPaddingLeft - + kMenuMarkerPaddingRight); + } + + return gfx::Rect(s); +} + +int MenuButton::GetMaximumScreenXCoordinate() { + if (!GetWidget()) { + NOTREACHED(); + return 0; + } + + gfx::Rect monitor_bounds = GetWidget()->GetWorkAreaBoundsInScreen(); + return monitor_bounds.right() - 1; +} + +} // namespace views diff --git a/pool/shard001/C++/0017427_dram_cntlr.cc b/pool/shard001/C++/0017427_dram_cntlr.cc new file mode 100644 index 0000000000000000000000000000000000000000..90d6fc15067018f28fcd5ddbe4aaf80938dcff30 --- /dev/null +++ b/pool/shard001/C++/0017427_dram_cntlr.cc @@ -0,0 +1,54 @@ +#include "dram_cntlr.h" +#include "memory_manager.h" +#include "log.h" + +namespace PrL1ShL2SpDirMSI +{ + +DramCntlr::DramCntlr(MemoryManager* memory_manager, + float dram_access_cost, float dram_bandwidth, + bool dram_queue_model_enabled, string dram_queue_model_type, + UInt32 cache_line_size) + : ::DramCntlr(memory_manager->getTile(), dram_access_cost, dram_bandwidth, dram_queue_model_enabled, dram_queue_model_type, cache_line_size) + , _memory_manager(memory_manager) +{} + +DramCntlr::~DramCntlr() +{} + +void +DramCntlr::handleMsgFromL2Cache(tile_id_t sender, ShmemMsg* shmem_msg) +{ + ShmemMsg::Type shmem_msg_type = shmem_msg->getType(); + IntPtr address = shmem_msg->getAddress(); + tile_id_t requester = shmem_msg->getRequester(); + bool msg_modeled = shmem_msg->isModeled(); + LOG_PRINT("handleMsgFromL2Cache(%i, %#lx, %s)", sender, address, msg_modeled ? "TRUE" : "FALSE"); + + switch (shmem_msg_type) + { + case ShmemMsg::DRAM_FETCH_REQ: + { + Byte data_buf[_cache_line_size]; + getDataFromDram(address, data_buf, msg_modeled); + LOG_PRINT("Finished fetching data from DRAM_CNTLR, sending reply"); + ShmemMsg dram_reply(ShmemMsg::DRAM_FETCH_REP, MemComponent::DRAM_CNTLR, MemComponent::L2_CACHE, + requester, false, address, + data_buf, _cache_line_size, + msg_modeled); + _memory_manager->sendMsg(sender, dram_reply); + LOG_PRINT("Sent reply"); + } + break; + + case ShmemMsg::DRAM_STORE_REQ: + putDataToDram(address, shmem_msg->getDataBuf(), msg_modeled); + break; + + default: + LOG_PRINT_ERROR("Unrecgonized Msg From L2 Cache(%u)", shmem_msg_type); + break; + } +} + +} diff --git a/pool/shard001/C++/0017430_RemoveTopic.cpp b/pool/shard001/C++/0017430_RemoveTopic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88be1fe5657acebbfab31994db5e4309c96c433a --- /dev/null +++ b/pool/shard001/C++/0017430_RemoveTopic.cpp @@ -0,0 +1,192 @@ +/* + * RebeccaAIML, Artificial Intelligence Markup Language + * C++ api and engine. + * + * Copyright (C) 2005,2006,2007 Frank Hassanabad + * + * This file is part of RebeccaAIML. + * + * RebeccaAIML 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. + * + * RebeccaAIML 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 . + */ + +//rebecca includes +#include +#include +#include +#include +#include +#include +#include +using namespace rebecca::impl; + +/* Disable Windows VC 7.x warning about + * it ignoring the throw specification + */ +#ifdef _WIN32 +# pragma warning( disable : 4290 ) +#endif + +namespace rebecca +{ +namespace framework +{ +namespace impl +{ + +class RemoveTopicImpl +{ + public: + RemoveTopicImpl() + : m_rootNodeMapper(static_cast(FrameworkFactory::getInstance()->getGraphBuilderFramework())->getRootNodeMapper()) + { + } + + NodeMapper &m_rootNodeMapper; +}; + +RemoveTopic::RemoveTopic() + throw(InternalProgrammerErrorException &) + : m_pimpl(new RemoveTopicImpl()), + Topic() +{ + addInstanceOf("RemoveTopic"); +} + +void RemoveTopic::handleInnerTag(Tag *tag) + throw(InternalProgrammerErrorException &) +{ + queue wordStack; + StringPimpl stringCopy; + + if(tag->instanceOf("Category")) + { + Category *category = static_cast(tag); + const StringPimpl &patternString = category->getPatternString(); + stringCopy.clear(); + + for(unsigned int i = 0; i < getTopic().length(); ++i) + { + char c = getTopic().at(i); + //If space push it onto the stack + if(c == ' ') + { + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + stringCopy.transformByTrimmingWhiteSpace(); + wordStack.push(stringCopy); + stringCopy.clear(); + } + } + else + { + //Haven't found the full word yet. + //Just add the character and keep going. + //convert it to upper case + stringCopy.push_back(toupper(c)); + } + } + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + wordStack.push(stringCopy); + stringCopy.clear(); + } + wordStack.push(""); + + const StringPimpl &thatString = category->getThatString(); + for(unsigned int i = 0; i < thatString.length(); ++i) + { + char c = thatString.at(i); + //If space push it onto the stack + if(c == ' ') + { + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + wordStack.push(stringCopy); + stringCopy.clear(); + } + } + else + { + //Haven't found the full word yet. + //Just add the character and keep going. + //convert it to upper case + stringCopy.push_back(toupper(c)); + } + } + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + wordStack.push(stringCopy); + stringCopy.clear(); + } + wordStack.push(""); + + for(unsigned int i = 0; i < patternString.length(); ++i) + { + char c = patternString.at(i); + //If space push it onto the stack + if(c == ' ') + { + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + wordStack.push(stringCopy); + stringCopy.clear(); + } + } + else + { + //Haven't found the full word yet. + //Just add the character and keep going. + //Convert it to upper case + stringCopy.push_back(toupper(c)); + } + } + stringCopy.transformByTrimmingWhiteSpace(); + if(!stringCopy.empty()) + { + wordStack.push(stringCopy); + } + + //push the user id and the bot id onto the stack + wordStack.push(""); + wordStack.push(IdentificationManager::getInstance()->getUserId()); + wordStack.push(""); + wordStack.push(IdentificationManager::getInstance()->getBotId()); + m_pimpl->m_rootNodeMapper.remove(wordStack); + } + else if(tag->instanceOf("Topic")) + { + //We have encountered a topic tag. Ignoring it + } + else + { + //Internal programmer error. Bad cast, this is not a Category or Topic + throw InternalProgrammerErrorExceptionImpl( + "[void RemoveTopic::handleInnerTag(Tag *tag)], Bad cast, this is not a Category or Topic" + ); + } +} + +RemoveTopic::~RemoveTopic() +{ + delete m_pimpl; +} + +} //end of namespace impl +} //end of namespace framework +} //end of namespace rebecca diff --git a/pool/shard001/C++/0017440_Position.cpp b/pool/shard001/C++/0017440_Position.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30b737bd6a26b64ed60bc62d4a874655fe5243a0 --- /dev/null +++ b/pool/shard001/C++/0017440_Position.cpp @@ -0,0 +1,60 @@ +/* + ------------------------------------------------------------------------------- + This file is part of simple-chess. + Copyright (C) 2021 Dirk Stolle + + 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 "Position.hpp" +#include "../io-utils.hpp" +#include "../Engine.hpp" +#include "../../libsimple-chess/data/ForsythEdwardsNotation.hpp" + +namespace simplechess::uci +{ + +Position::Position(const std::string& fen) +: fen(fen) +{ +} + +bool Position::process() +{ + Board& board = Engine::get().board(); + // Reset the board to the standard chess starting position. + if (!board.fromFEN(fen)) + { + sendCommand("Error: invalid FEN given"); + return false; + } + // Leave force mode... + Engine::get().setForceMode(false); + // ... and set the engine to play the side that is to move. + Engine::get().setPlayer(board.toMove()); + // Reset clocks and time controls to the start of a new game. + Timing& timing = Engine::get().timing(); + timing.self().reset(); + timing.opponent().reset(); + // Use wall clock for time measurement. Stop clocks. + timing.self().stop(); + timing.opponent().stop(); + // TODO: Do not ponder on this move, even if pondering is on. + // Reset previously set limit on search depth. + Engine::get().setSearchDepth(100); + return true; +} + +} // namespace diff --git a/pool/shard001/C++/0017449_checker.cpp b/pool/shard001/C++/0017449_checker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..08fcd3c7cb0627d18f848ebe72eba2b0a878e849 --- /dev/null +++ b/pool/shard001/C++/0017449_checker.cpp @@ -0,0 +1,77 @@ +/* +ID: vistasw2 +PROG: checker +LANG: C++11 +*/ +#include +#include +#include + +using namespace std; + +ifstream fin; +ofstream fout; + +int n; +int map[13][13]; +int rowUsed[13] = {0}; +int coord1Used[27] = {0}; +int coord2Used[27] = {0}; +int seq[13] = {0}; + +int ret = 0; + +inline int getCoordIndex1(int i, int j) +{ + return (i + j); +} + +inline int getCoordIndex2(int i, int j) +{ + return (n - i - 1) + j; +} + +void search(int index) +{ + if (index >= n) { + ret++; + if (ret <= 3) { + for (int i = 0; i < n - 1; ++i) { + fout << seq[i] + 1 << " "; + } + fout << seq[n -1] + 1 << endl; + } + return; + } + + for (int i = 0; i < n; ++i) { + if (rowUsed[i] == 1) continue; + int coord1 = getCoordIndex1(index, i); + if (coord1Used[coord1] == 1) continue; + int coord2 = getCoordIndex2(index, i); + if (coord2Used[coord2] == 1) continue; + + coord1Used[coord1] = 1; + coord2Used[coord2] = 1; + rowUsed[i] = 1; + seq[index] = i; + + search(index + 1); + + rowUsed[i] = 0; + coord1Used[coord1] = 0; + coord2Used[coord2] = 0; + } +} + +int main() +{ + fin.open("checker.in"); + fout.open("checker.out"); + + fin >> n; + search(0); + fout << ret << endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard001/C++/0017450_HardwareMonitorMain.cc b/pool/shard001/C++/0017450_HardwareMonitorMain.cc new file mode 100644 index 0000000000000000000000000000000000000000..d8d7a688456fb93e805debd5e2e3faeb6ca6a032 --- /dev/null +++ b/pool/shard001/C++/0017450_HardwareMonitorMain.cc @@ -0,0 +1,109 @@ +//# HardwareMonitor.cc: Main entry for the HardwareMonitor. +//# +//# Copyright (C) 2006 +//# ASTRON (Netherlands Foundation for Research in Astronomy) +//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands, softwaresupport@astron.nl +//# +//# 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 +//# +//# $Id$ +//# +#include +#include +#include +#include +#include +#include +#include +#include "RSPMonitor.h" +#include "TBBMonitor.h" +#include "ECMonitor.h" +#include + +using namespace LOFAR; +using namespace LOFAR::GCF; +using namespace LOFAR::GCF::TM; +using namespace LOFAR::StationCU; +using namespace LOFAR::RSP_Protocol; +using namespace LOFAR::DP_Protocol; + +// Use a terminate handler that can produce a backtrace. +Exception::TerminateHandler t(Exception::terminate); + +int main(int argc, char* argv[]) +{ + // args: cntlrname, parentHost, parentService + GCFScheduler::instance()->init(argc, argv, "HardwareMonitor"); + + LOG_INFO("MACProcessScope: LOFAR_PermSW_HardwareMonitor"); + LOG_INFO(Version::getInfo("HardwareMonitor")); + + // for debugging purposes + registerProtocol (RSP_PROTOCOL, RSP_PROTOCOL_STRINGS); + registerProtocol (TBB_PROTOCOL, TBB_PROTOCOL_STRINGS); + registerProtocol (DP_PROTOCOL, DP_PROTOCOL_STRINGS); + + // Create tasks and call initial routines + RSPMonitor* rsp(0); + TBBMonitor* tbb(0); + ECMonitor* ec(0); + + // monitor RSP? + if (globalParameterSet()->getUint32("WatchRSPboards",0)) { + rsp = new RSPMonitor("RSPMonitor"); + rsp->start(); + LOG_INFO("Monitoring the RSP boards"); + } + + // monitor TBB? + if (globalParameterSet()->getUint32("WatchTBboards",0)) { + tbb = new TBBMonitor("TBBMonitor"); + tbb->start(); + LOG_INFO("Monitoring the TB boards"); + } + + // monitor EC? + if (globalParameterSet()->getUint32("WatchEnvCntrl",0)) { + ec = new ECMonitor("ECMonitor"); + ec->start(); + LOG_INFO("Monitoring the Environment Controller"); + } + + // sanity check + if (!tbb && !rsp && !ec) { + LOG_FATAL_STR("Non of the monitortask (WatchRSPboards, WatchTBboards, WatchEnvCntrl) " + "was switched on in the configfile, terminating program"); + return (0); + } + + // ok, we have something to do, do it. + GCFScheduler::instance()->setDelayedQuit(true); // we need a clean shutdown + GCFScheduler::instance()->run(); // until stop was called + + if (rsp) { + rsp->quit(); // let task quit nicely + } + if (tbb) { + tbb->quit(); // let task quit nicely + } + if (ec) { + ec->quit(); // let task quit nicely + } + double postRunTime = globalParameterSet()->getDouble("closingDelay", 1.5); + GCFScheduler::instance()->run(postRunTime); // let processes die. + + return (0); +} + diff --git a/pool/shard001/C++/0017455_suggestions_internals_ui_handler.cc b/pool/shard001/C++/0017455_suggestions_internals_ui_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3257ece2a33bd28582ff43ce3c0a23dbc808a12 --- /dev/null +++ b/pool/shard001/C++/0017455_suggestions_internals_ui_handler.cc @@ -0,0 +1,45 @@ +// 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/ui/webui/suggestions_internals/suggestions_internals_ui_handler.h" + +#include "base/bind.h" +#include "base/values.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/ntp/suggestions_combiner.h" +#include "content/public/browser/web_ui.h" + +namespace { + +const size_t kSuggestionsCount = 100; + +} // namespace + +SuggestionsInternalsUIHandler::SuggestionsInternalsUIHandler(Profile* profile) + : profile_(profile) {} + +SuggestionsInternalsUIHandler::~SuggestionsInternalsUIHandler() {} + +void SuggestionsInternalsUIHandler::OnSuggestionsReady() { + if (suggestions_combiner_->GetPageValues()) { + web_ui()->CallJavascriptFunction("suggestionsInternals.setSuggestions", + *suggestions_combiner_->GetPageValues()); + } +} + +void SuggestionsInternalsUIHandler::RegisterMessages() { + // Setup the suggestions sources. + suggestions_combiner_.reset(SuggestionsCombiner::Create(this, profile_)); + suggestions_combiner_->SetSuggestionsCount(kSuggestionsCount); + suggestions_combiner_->EnableDebug(true); + + web_ui()->RegisterMessageCallback("getSuggestions", + base::Bind(&SuggestionsInternalsUIHandler::HandleGetSuggestions, + base::Unretained(this))); +} + +void SuggestionsInternalsUIHandler::HandleGetSuggestions( + const base::ListValue* one_element_input_string) { + suggestions_combiner_->FetchItems(Profile::FromWebUI(web_ui())); +} diff --git a/pool/shard001/C++/0017460_remote_device_provider_impl.cc b/pool/shard001/C++/0017460_remote_device_provider_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..87bf6d12e25a9c7d37c76ba4a8ef3bc802c2951e --- /dev/null +++ b/pool/shard001/C++/0017460_remote_device_provider_impl.cc @@ -0,0 +1,258 @@ +// 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 "chromeos/services/device_sync/remote_device_provider_impl.h" + +#include + +#include "ash/constants/ash_features.h" +#include "base/bind.h" +#include "base/feature_list.h" +#include "base/memory/ptr_util.h" +#include "base/metrics/histogram_functions.h" +#include "chromeos/components/multidevice/logging/logging.h" +#include "chromeos/components/multidevice/secure_message_delegate_impl.h" +#include "chromeos/services/device_sync/remote_device_loader.h" +#include "chromeos/services/device_sync/remote_device_v2_loader_impl.h" + +namespace chromeos { + +namespace device_sync { + +namespace { + +const int kMaxNumberOfDevicesToLog = 50; + +// Only used while v1 and v2 DeviceSync are running in parallel. +void LogRemoteDeviceCountMetrics( + const multidevice::RemoteDeviceList& v1_devices, + const multidevice::RemoteDeviceList& v2_devices, + size_t num_v2_devices_with_decrypted_public_key, + size_t num_v1_devices_replaced_by_v2_devices) { + // At a minimum, the local device should always be returned from a successful + // v1 or v2 DeviceSync. Only log metrics if v1 and v2 devices are available, + // in other words, if a v1 *and* v2 DeviceSync has previously occurred. + if (v1_devices.empty() || v2_devices.empty()) + return; + + base::UmaHistogramExactLinear( + "CryptAuth.DeviceSyncV2.RemoteDeviceProvider.NumV1Devices", + v1_devices.size(), kMaxNumberOfDevicesToLog); + base::UmaHistogramExactLinear( + "CryptAuth.DeviceSyncV2.RemoteDeviceProvider.NumV2Devices", + v2_devices.size(), kMaxNumberOfDevicesToLog); + + // Note: By CryptAuth server design, v2 devices should always be a subset of + // v1 devices. Race conditions might occur when a user adds a new device + // because v1 and v2 devices are retrieved in different RPC calls; however, + // this is only meant to be a rough estimate. + base::UmaHistogramPercentageObsoleteDoNotUse( + "CryptAuth.DeviceSyncV2.RemoteDeviceProvider.RatioOfV2ToV1Devices", + (v2_devices.size() * 100) / v1_devices.size()); + + base::UmaHistogramPercentageObsoleteDoNotUse( + "CryptAuth.DeviceSyncV2.RemoteDeviceProvider." + "PercentageOfV2DevicesWithDecryptedPublicKey", + (num_v2_devices_with_decrypted_public_key * 100) / v2_devices.size()); + + base::UmaHistogramPercentageObsoleteDoNotUse( + "CryptAuth.DeviceSyncV2.RemoteDeviceProvider." + "PercentageOfV1DevicesReplacedByV2Devices", + (num_v1_devices_replaced_by_v2_devices * 100) / v1_devices.size()); +} + +} // namespace + +// static +RemoteDeviceProviderImpl::Factory* + RemoteDeviceProviderImpl::Factory::factory_instance_ = nullptr; + +// static +std::unique_ptr RemoteDeviceProviderImpl::Factory::Create( + CryptAuthDeviceManager* v1_device_manager, + CryptAuthV2DeviceManager* v2_device_manager, + const std::string& user_email, + const std::string& user_private_key) { + if (factory_instance_) { + return factory_instance_->CreateInstance( + v1_device_manager, v2_device_manager, user_email, user_private_key); + } + + return base::WrapUnique(new RemoteDeviceProviderImpl( + v1_device_manager, v2_device_manager, user_email, user_private_key)); +} + +// static +void RemoteDeviceProviderImpl::Factory::SetFactoryForTesting(Factory* factory) { + factory_instance_ = factory; +} + +RemoteDeviceProviderImpl::Factory::~Factory() = default; + +RemoteDeviceProviderImpl::RemoteDeviceProviderImpl( + CryptAuthDeviceManager* v1_device_manager, + CryptAuthV2DeviceManager* v2_device_manager, + const std::string& user_email, + const std::string& user_private_key) + : v1_device_manager_(v1_device_manager), + v2_device_manager_(v2_device_manager), + user_email_(user_email), + user_private_key_(user_private_key) { + if (features::ShouldUseV1DeviceSync()) { + DCHECK(v1_device_manager_); + v1_device_manager_->AddObserver(this); + LoadV1RemoteDevices(); + } + + if (features::ShouldUseV2DeviceSync()) { + DCHECK(v2_device_manager_); + v2_device_manager_->AddObserver(this); + LoadV2RemoteDevices(); + } +} + +RemoteDeviceProviderImpl::~RemoteDeviceProviderImpl() { + if (v1_device_manager_) + v1_device_manager_->RemoveObserver(this); + + if (v2_device_manager_) + v2_device_manager_->RemoveObserver(this); +} + +void RemoteDeviceProviderImpl::OnSyncFinished( + CryptAuthDeviceManager::SyncResult sync_result, + CryptAuthDeviceManager::DeviceChangeResult device_change_result) { + DCHECK(features::ShouldUseV1DeviceSync()); + + if (sync_result == CryptAuthDeviceManager::SyncResult::SUCCESS && + device_change_result == + CryptAuthDeviceManager::DeviceChangeResult::CHANGED) { + LoadV1RemoteDevices(); + } +} + +void RemoteDeviceProviderImpl::OnDeviceSyncFinished( + const CryptAuthDeviceSyncResult& device_sync_result) { + DCHECK(features::ShouldUseV2DeviceSync()); + + if (device_sync_result.IsSuccess() && + device_sync_result.did_device_registry_change()) { + LoadV2RemoteDevices(); + } +} + +void RemoteDeviceProviderImpl::LoadV1RemoteDevices() { + remote_device_v1_loader_ = RemoteDeviceLoader::Factory::Create( + v1_device_manager_->GetSyncedDevices(), user_email_, user_private_key_, + multidevice::SecureMessageDelegateImpl::Factory::Create()); + remote_device_v1_loader_->Load( + base::BindOnce(&RemoteDeviceProviderImpl::OnV1RemoteDevicesLoaded, + weak_ptr_factory_.GetWeakPtr())); +} + +void RemoteDeviceProviderImpl::LoadV2RemoteDevices() { + remote_device_v2_loader_ = RemoteDeviceV2LoaderImpl::Factory::Create(); + remote_device_v2_loader_->Load( + v2_device_manager_->GetSyncedDevices(), user_email_, user_private_key_, + base::BindOnce(&RemoteDeviceProviderImpl::OnV2RemoteDevicesLoaded, + weak_ptr_factory_.GetWeakPtr())); +} + +void RemoteDeviceProviderImpl::OnV1RemoteDevicesLoaded( + const multidevice::RemoteDeviceList& synced_v1_remote_devices) { + // If we are only using v1 DeviceSync, the complete list of RemoteDevices + // is |synced_v1_remote_devices|. + if (!features::ShouldUseV2DeviceSync()) { + synced_remote_devices_ = synced_v1_remote_devices; + remote_device_v1_loader_.reset(); + + // Notify observers of change. Note that there is no need to check if + // |synced_remote_devices_| has changed here because the fetch is only + // started if the change result passed to OnSyncFinished() is CHANGED. + RemoteDeviceProvider::NotifyObserversDeviceListChanged(); + return; + } + + synced_v1_remote_devices_to_be_merged_ = synced_v1_remote_devices; + remote_device_v1_loader_.reset(); + MergeV1andV2SyncedDevices(); +} + +void RemoteDeviceProviderImpl::OnV2RemoteDevicesLoaded( + const multidevice::RemoteDeviceList& synced_v2_remote_devices) { + // If we are only using v2 DeviceSync, the complete list of RemoteDevices + // is |synced_v2_remote_devices|. + if (!features::ShouldUseV1DeviceSync()) { + synced_remote_devices_ = synced_v2_remote_devices; + remote_device_v2_loader_.reset(); + + // Notify observers of change. Note that there is no need to check if + // |synced_remote_devices_| has changed here because the fetch is only + // started if the DeviceSync result passed to OnDeviceSyncFinished() + // indicates that the device registry changed. + RemoteDeviceProvider::NotifyObserversDeviceListChanged(); + return; + } + + synced_v2_remote_devices_to_be_merged_ = synced_v2_remote_devices; + remote_device_v2_loader_.reset(); + MergeV1andV2SyncedDevices(); +} + +void RemoteDeviceProviderImpl::MergeV1andV2SyncedDevices() { + DCHECK(features::ShouldUseV1DeviceSync()); + DCHECK(features::ShouldUseV2DeviceSync()); + + multidevice::RemoteDeviceList previous_synced_remote_devices = + synced_remote_devices_; + + synced_remote_devices_ = synced_v1_remote_devices_to_be_merged_; + size_t num_v2_devices_with_decrypted_public_key = 0; + size_t num_v1_devices_replaced_by_v2_devices = 0; + for (const auto& v2_device : synced_v2_remote_devices_to_be_merged_) { + // Ignore v2 devices without a decrypted public key. + if (v2_device.public_key.empty()) + continue; + + ++num_v2_devices_with_decrypted_public_key; + + std::string v2_public_key = v2_device.public_key; + auto it = std::find_if( + synced_remote_devices_.begin(), synced_remote_devices_.end(), + [&v2_public_key](const multidevice::RemoteDevice& v1_device) { + return v1_device.public_key == v2_public_key; + }); + + // If a v1 device has the same public key as the v2 device, replace the + // v1 device with the v2 device; otherwise, append the v2 device to the + // synced-device list. + if (it != synced_remote_devices_.end()) { + *it = v2_device; + ++num_v1_devices_replaced_by_v2_devices; + } else { + synced_remote_devices_.push_back(v2_device); + } + } + + LogRemoteDeviceCountMetrics(synced_v1_remote_devices_to_be_merged_, + synced_v2_remote_devices_to_be_merged_, + num_v2_devices_with_decrypted_public_key, + num_v1_devices_replaced_by_v2_devices); + + // We need to explicitly check for changes to the synced-device list. It + // is possible that the v1 and/or v2 device lists changed but the merged + // list didn't change, for example, if a new v2 device appears in the + // device registry but it doesn't have a decrypted public key. + if (synced_remote_devices_ != previous_synced_remote_devices) + RemoteDeviceProvider::NotifyObserversDeviceListChanged(); +} + +const multidevice::RemoteDeviceList& +RemoteDeviceProviderImpl::GetSyncedDevices() const { + return synced_remote_devices_; +} + +} // namespace device_sync + +} // namespace chromeos diff --git a/pool/shard001/C++/0017466_SVGPaintServer.cpp b/pool/shard001/C++/0017466_SVGPaintServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1608f7b257bfe250d769535c8a542cb7ccdcd0a5 --- /dev/null +++ b/pool/shard001/C++/0017466_SVGPaintServer.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2006 Nikolas Zimmermann + * 2007 Rob Buis + * + * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "wtf/Platform.h" + +#if ENABLE(SVG) +#include "SVGPaintServer.h" + +#include "RenderObject.h" +#include "RenderStyle.h" +#include "SVGPaintServerSolid.h" +#include "SVGStyledElement.h" +#include "SVGURIReference.h" + +namespace WebCore { + +SVGPaintServer::SVGPaintServer() +{ +} + +SVGPaintServer::~SVGPaintServer() +{ +} + +/*TextStream& operator<<(TextStream& ts, const SVGPaintServer& paintServer) +{ + return paintServer.externalRepresentation(ts); +}*/ + +SVGPaintServer* getPaintServerById(Document* document, const AtomicString& id) +{ + SVGResource* resource = getResourceById(document, id); + if (resource && resource->isPaintServer()) + return static_cast(resource); + + return 0; +} + +SVGPaintServerSolid* SVGPaintServer::sharedSolidPaintServer() +{ + static SVGPaintServerSolid* _sharedSolidPaintServer = SVGPaintServerSolid::create().releaseRef(); + + return _sharedSolidPaintServer; +} + +SVGPaintServer* SVGPaintServer::fillPaintServer(const RenderStyle* style, const RenderObject* item) +{ + if (!style->svgStyle()->hasFill()) + return 0; + + SVGPaintImpl* fill = style->svgStyle()->fillPaint(); + + SVGPaintServer* fillPaintServer = 0; + SVGPaintImpl::SVGPaintType paintType = fill->paintType(); + if (paintType == SVGPaintImpl::SVG_PAINTTYPE_URI || + paintType == SVGPaintImpl::SVG_PAINTTYPE_URI_RGBCOLOR) { + AtomicString id(SVGURIReference::getTarget(fill->uri())); + fillPaintServer = getPaintServerById(item->document(), id); + SVGElement* svgElement = static_cast(item->element()); + ASSERT(svgElement && svgElement->document() && svgElement->isStyled()); + + if (item->isRenderPath() && fillPaintServer) + fillPaintServer->addClient(static_cast(svgElement)); + else if (!fillPaintServer && paintType == SVGPaintImpl::SVG_PAINTTYPE_URI) + svgElement->document()->accessSVGExtensions()->addPendingResource(id, static_cast(svgElement)); + } + if (paintType != SVGPaintImpl::SVG_PAINTTYPE_URI && !fillPaintServer) { + fillPaintServer = sharedSolidPaintServer(); + SVGPaintServerSolid* fillPaintServerSolid = static_cast(fillPaintServer); + if (paintType == SVGPaintImpl::SVG_PAINTTYPE_CURRENTCOLOR) + fillPaintServerSolid->setColor(style->color()); + else + fillPaintServerSolid->setColor(fill->color()); + // FIXME: Ideally invalid colors would never get set on the RenderStyle and this could turn into an ASSERT + if (!fillPaintServerSolid->color().isValid()) + fillPaintServer = 0; + } + if (!fillPaintServer) { + // default value (black), see bug 11017 + fillPaintServer = sharedSolidPaintServer(); + static_cast(fillPaintServer)->setColor(/*Color::black*/Qt::black); + } + return fillPaintServer; +} + +SVGPaintServer* SVGPaintServer::strokePaintServer(const RenderStyle* style, const RenderObject* item) +{ + if (!style->svgStyle()->hasStroke()) + return 0; + + SVGPaintImpl* stroke = style->svgStyle()->strokePaint(); + + SVGPaintServer* strokePaintServer = 0; + SVGPaintImpl::SVGPaintType paintType = stroke->paintType(); + if (paintType == SVGPaintImpl::SVG_PAINTTYPE_URI || + paintType == SVGPaintImpl::SVG_PAINTTYPE_URI_RGBCOLOR) { + AtomicString id(SVGURIReference::getTarget(stroke->uri())); + strokePaintServer = getPaintServerById(item->document(), id); + + SVGElement* svgElement = static_cast(item->element()); + ASSERT(svgElement && svgElement->document() && svgElement->isStyled()); + + if (item->isRenderPath() && strokePaintServer) + strokePaintServer->addClient(static_cast(svgElement)); + else if (!strokePaintServer && paintType == SVGPaintImpl::SVG_PAINTTYPE_URI) + svgElement->document()->accessSVGExtensions()->addPendingResource(id, static_cast(svgElement)); + } + if (paintType != SVGPaintImpl::SVG_PAINTTYPE_URI && !strokePaintServer) { + strokePaintServer = sharedSolidPaintServer(); + SVGPaintServerSolid* strokePaintServerSolid = static_cast(strokePaintServer); + if (paintType == SVGPaintImpl::SVG_PAINTTYPE_CURRENTCOLOR) + strokePaintServerSolid->setColor(style->color()); + else + strokePaintServerSolid->setColor(stroke->color()); + // FIXME: Ideally invalid colors would never get set on the RenderStyle and this could turn into an ASSERT + if (!strokePaintServerSolid->color().isValid()) + strokePaintServer = 0; + } + + return strokePaintServer; +} + +DashArray dashArrayFromRenderingStyle(const RenderStyle* style) +{ + Q_UNUSED(style); + DashArray array; + + /*CSSValueList* dashes = style->svgStyle()->strokeDashArray(); + if (dashes) { + CSSPrimitiveValue* dash = 0; + unsigned long len = dashes->length(); + for (unsigned long i = 0; i < len; i++) { + dash = static_cast(dashes->itemWithoutBoundsCheck(i)); + if (!dash) + continue; + + array.append((float) dash->computeLengthFloat(const_cast(style))); + } + }*/ + + return array; +} + +} // namespace WebCore + +#endif diff --git a/pool/shard001/C++/0017469_boss_cyanigosa.cpp b/pool/shard001/C++/0017469_boss_cyanigosa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebbccac003f6eb1248496bee21d264d498706c8d --- /dev/null +++ b/pool/shard001/C++/0017469_boss_cyanigosa.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2005-2012 MaNGOS + * Copyright (C) 2008-2012 Trinity + * Copyright (C) 2010-2012 Project SkyFire + * Copyright (C) 2011-2012 Darkpeninsula Project + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "ScriptPCH.h" +#include "violet_hold.h" + +enum Spells +{ + SPELL_ARCANE_VACUUM = 58694, + SPELL_BLIZZARD = 58693, + H_SPELL_BLIZZARD = 59369, + SPELL_MANA_DESTRUCTION = 59374, + SPELL_TAIL_SWEEP = 58690, + H_SPELL_TAIL_SWEEP = 59283, + SPELL_UNCONTROLLABLE_ENERGY = 58688, + H_SPELL_UNCONTROLLABLE_ENERGY = 59281, + SPELL_TRANSFORM = 58668 +}; + +enum Yells +{ + SAY_AGGRO = -1608000, + SAY_SLAY_1 = -1608001, + SAY_SLAY_2 = -1608002, + SAY_SLAY_3 = -1608003, + SAY_DEATH = -1608004, + SAY_SPAWN = -1608005, + SAY_DISRUPTION = -1608006, + SAY_BREATH_ATTACK = -1608007, + SAY_SPECIAL_ATTACK_1 = -1608008, + SAY_SPECIAL_ATTACK_2 = -1608009 +}; + +class boss_cyanigosa : public CreatureScript +{ +public: + boss_cyanigosa() : CreatureScript("boss_cyanigosa") { } + + CreatureAI* GetAI(Creature* pCreature) const + { + return new boss_cyanigosaAI (pCreature); + } + + struct boss_cyanigosaAI : public ScriptedAI + { + boss_cyanigosaAI(Creature *c) : ScriptedAI(c) + { + pInstance = c->GetInstanceScript(); + me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); + me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); + } + + uint32 uiArcaneVacuumTimer; + uint32 uiBlizzardTimer; + uint32 uiManaDestructionTimer; + uint32 uiTailSweepTimer; + uint32 uiUncontrollableEnergyTimer; + + InstanceScript* pInstance; + + void Reset() + { + uiArcaneVacuumTimer = 10000; + uiBlizzardTimer = 15000; + uiManaDestructionTimer = 30000; + uiTailSweepTimer = 20000; + uiUncontrollableEnergyTimer = 25000; + if (pInstance) + pInstance->SetData(DATA_CYANIGOSA_EVENT, NOT_STARTED); + } + + void EnterCombat(Unit* /*who*/) + { + DoScriptText(SAY_AGGRO, me); + + if (pInstance) + pInstance->SetData(DATA_CYANIGOSA_EVENT, IN_PROGRESS); + } + + void MoveInLineOfSight(Unit* /*who*/) {} + + void UpdateAI(const uint32 diff) + { + if (pInstance && pInstance->GetData(DATA_REMOVE_NPC) == 1) + { + me->ForcedDespawn(); + pInstance->SetData(DATA_REMOVE_NPC, 0); + } + + //Return since we have no target + if (!UpdateVictim()) + return; + + if (uiArcaneVacuumTimer <= diff) + { + DoCast(SPELL_ARCANE_VACUUM); + uiArcaneVacuumTimer = 10000; + } else uiArcaneVacuumTimer -= diff; + + if (uiBlizzardTimer <= diff) + { + if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) + DoCast(pTarget, SPELL_BLIZZARD); + uiBlizzardTimer = 15000; + } else uiBlizzardTimer -= diff; + + if (uiTailSweepTimer <= diff) + { + DoCast(SPELL_TAIL_SWEEP); + uiTailSweepTimer = 20000; + } else uiTailSweepTimer -= diff; + + if (uiUncontrollableEnergyTimer <= diff) + { + DoCastVictim(SPELL_UNCONTROLLABLE_ENERGY); + uiUncontrollableEnergyTimer = 25000; + } else uiUncontrollableEnergyTimer -= diff; + + if (IsHeroic()) + { + if (uiManaDestructionTimer <= diff) + { + if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) + DoCast(pTarget, SPELL_MANA_DESTRUCTION); + uiManaDestructionTimer = 30000; + } else uiManaDestructionTimer -= diff; + } + + DoMeleeAttackIfReady(); + } + + void JustDied(Unit* /*killer*/) + { + DoScriptText(SAY_DEATH, me); + + if (pInstance) + pInstance->SetData(DATA_CYANIGOSA_EVENT, DONE); + } + + void KilledUnit(Unit * victim) + { + if (victim == me) + return; + DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); + } + }; +}; + +void AddSC_boss_cyanigosa() +{ + new boss_cyanigosa(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0017498_DwarfEHPrepare.cpp b/pool/shard001/C++/0017498_DwarfEHPrepare.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7c1752665647683829418825e02b7898cd94249 --- /dev/null +++ b/pool/shard001/C++/0017498_DwarfEHPrepare.cpp @@ -0,0 +1,179 @@ +//===-- DwarfEHPrepare - Prepare exception handling for code generation ---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass mulches exception handling code into a form adapted to code +// generation. Required if using dwarf exception handling. +// +//===----------------------------------------------------------------------===// + +#define DEBUG_TYPE "dwarfehprepare" +#include "llvm/CodeGen/Passes.h" +#include "llvm/ADT/Statistic.h" +#include "llvm/Analysis/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Module.h" +#include "llvm/MC/MCAsmInfo.h" +#include "llvm/Pass.h" +#include "llvm/Support/CallSite.h" +#include "llvm/Target/TargetLowering.h" +#include "llvm/Transforms/Utils/BasicBlockUtils.h" +#include "llvm/Transforms/Utils/SSAUpdater.h" +using namespace llvm; + +STATISTIC(NumResumesLowered, "Number of resume calls lowered"); + +namespace { + class DwarfEHPrepare : public FunctionPass { + const TargetMachine *TM; + + // RewindFunction - _Unwind_Resume or the target equivalent. + Constant *RewindFunction; + + bool InsertUnwindResumeCalls(Function &Fn); + Value *GetExceptionObject(ResumeInst *RI); + + public: + static char ID; // Pass identification, replacement for typeid. + DwarfEHPrepare(const TargetMachine *TM) : + FunctionPass(ID), TM(TM), RewindFunction(0) { + initializeDominatorTreePass(*PassRegistry::getPassRegistry()); + } + + virtual bool runOnFunction(Function &Fn); + + virtual void getAnalysisUsage(AnalysisUsage &AU) const { } + + const char *getPassName() const { + return "Exception handling preparation"; + } + }; +} // end anonymous namespace + +char DwarfEHPrepare::ID = 0; + +FunctionPass *llvm::createDwarfEHPass(const TargetMachine *TM) { + return new DwarfEHPrepare(TM); +} + +/// GetExceptionObject - Return the exception object from the value passed into +/// the 'resume' instruction (typically an aggregate). Clean up any dead +/// instructions, including the 'resume' instruction. +Value *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) { + Value *V = RI->getOperand(0); + Value *ExnObj = 0; + InsertValueInst *SelIVI = dyn_cast(V); + LoadInst *SelLoad = 0; + InsertValueInst *ExcIVI = 0; + bool EraseIVIs = false; + + if (SelIVI) { + if (SelIVI->getNumIndices() == 1 && *SelIVI->idx_begin() == 1) { + ExcIVI = dyn_cast(SelIVI->getOperand(0)); + if (ExcIVI && isa(ExcIVI->getOperand(0)) && + ExcIVI->getNumIndices() == 1 && *ExcIVI->idx_begin() == 0) { + ExnObj = ExcIVI->getOperand(1); + SelLoad = dyn_cast(SelIVI->getOperand(1)); + EraseIVIs = true; + } + } + } + + if (!ExnObj) + ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI); + + RI->eraseFromParent(); + + if (EraseIVIs) { + if (SelIVI->getNumUses() == 0) + SelIVI->eraseFromParent(); + if (ExcIVI->getNumUses() == 0) + ExcIVI->eraseFromParent(); + if (SelLoad && SelLoad->getNumUses() == 0) + SelLoad->eraseFromParent(); + } + + return ExnObj; +} + +/// InsertUnwindResumeCalls - Convert the ResumeInsts that are still present +/// into calls to the appropriate _Unwind_Resume function. +bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) { + SmallVector Resumes; + for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { + TerminatorInst *TI = I->getTerminator(); + if (ResumeInst *RI = dyn_cast(TI)) + Resumes.push_back(RI); + } + + if (Resumes.empty()) + return false; + + // Find the rewind function if we didn't already. + const TargetLowering *TLI = TM->getTargetLowering(); + if (!RewindFunction) { + LLVMContext &Ctx = Resumes[0]->getContext(); + FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), + Type::getInt8PtrTy(Ctx), false); + const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME); + RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy); + } + + // Create the basic block where the _Unwind_Resume call will live. + LLVMContext &Ctx = Fn.getContext(); + unsigned ResumesSize = Resumes.size(); + + if (ResumesSize == 1) { + // Instead of creating a new BB and PHI node, just append the call to + // _Unwind_Resume to the end of the single resume block. + ResumeInst *RI = Resumes.front(); + BasicBlock *UnwindBB = RI->getParent(); + Value *ExnObj = GetExceptionObject(RI); + + // Call the _Unwind_Resume function. + CallInst *CI = CallInst::Create(RewindFunction, ExnObj, "", UnwindBB); + CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME)); + + // We never expect _Unwind_Resume to return. + new UnreachableInst(Ctx, UnwindBB); + return true; + } + + BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &Fn); + PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesSize, + "exn.obj", UnwindBB); + + // Extract the exception object from the ResumeInst and add it to the PHI node + // that feeds the _Unwind_Resume call. + for (SmallVectorImpl::iterator + I = Resumes.begin(), E = Resumes.end(); I != E; ++I) { + ResumeInst *RI = *I; + BasicBlock *Parent = RI->getParent(); + BranchInst::Create(UnwindBB, Parent); + + Value *ExnObj = GetExceptionObject(RI); + PN->addIncoming(ExnObj, Parent); + + ++NumResumesLowered; + } + + // Call the function. + CallInst *CI = CallInst::Create(RewindFunction, PN, "", UnwindBB); + CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME)); + + // We never expect _Unwind_Resume to return. + new UnreachableInst(Ctx, UnwindBB); + return true; +} + +bool DwarfEHPrepare::runOnFunction(Function &Fn) { + bool Changed = InsertUnwindResumeCalls(Fn); + return Changed; +} diff --git a/pool/shard001/C++/0017499_BarWidget.cpp b/pool/shard001/C++/0017499_BarWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b13f67b620c01c16f75ab5171cfb89ab378be7f9 --- /dev/null +++ b/pool/shard001/C++/0017499_BarWidget.cpp @@ -0,0 +1,100 @@ +#include + +#include + +namespace ginkgo +{ +namespace gtkWidgets +{ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// +// BarWidget +// +//////////////////////////////////////////////////////////////////////////////////////////////////// + +BarWidget::BarWidget(const Style &style) +: m_style(style) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +void BarWidget::setData(Data data) +{ + m_data = data; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +void BarWidget::setYMax(double yMax) +{ + m_yMax = yMax; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +bool BarWidget::on_draw(const::Cairo::RefPtr &context) +{ + std::function roundToPixels; + + if (m_style.roundToPixels) + roundToPixels = [](double x){return std::round(x) + 0.5;}; + else + roundToPixels = [](double x){return x;}; + + context->save(); + + context->set_source_rgb(m_data.color.get_red(), m_data.color.get_green(), m_data.color.get_blue()); + + const double width = get_allocation().get_width(); + const double maxHeight = get_allocation().get_height(); + + const double height = m_data.value / m_yMax * maxHeight; + + context->rectangle(0, maxHeight - height, width, height); + context->fill(); + + const auto errorBarY1 = roundToPixels(m_data.ciLow / m_yMax * maxHeight); + const auto errorBarY2 = roundToPixels(m_data.ciHigh / m_yMax * maxHeight); + + const auto color = m_style.colorPositiveLight; + + context->set_source_rgba(color.get_red(), color.get_green(), color.get_blue(), color.get_alpha()); + context->set_line_width(m_style.lineWidthNormal); + + const auto centerX = roundToPixels(width / 2.0); + const auto leftX = roundToPixels(width / 3.0); + const auto rightX = roundToPixels(width * 2.0 / 3.0) + 2 * roundToPixels(0.0); + + context->move_to(centerX, maxHeight - errorBarY1); + context->line_to(centerX, maxHeight - errorBarY2); + context->stroke(); + + // Do not draw error bar ending strokes if too small + if (width >= 6.0) + { + if (m_data.ciLow < m_data.value) + { + context->move_to(leftX, maxHeight - errorBarY1); + context->line_to(rightX, maxHeight - errorBarY1); + context->stroke(); + } + + if (m_data.ciHigh > m_data.value) + { + context->move_to(leftX, maxHeight - errorBarY2); + context->line_to(rightX, maxHeight - errorBarY2); + context->stroke(); + } + } + + context->restore(); + + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +} +} diff --git a/pool/shard001/C++/0017501_BaseIdString.cpp b/pool/shard001/C++/0017501_BaseIdString.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79ef77251351ce23ded5f24c4ac0ce20ae457910 --- /dev/null +++ b/pool/shard001/C++/0017501_BaseIdString.cpp @@ -0,0 +1,101 @@ +#include "BaseIdString.h" + +#include +#include + +#include "BaseIdBehavior.h" + +BaseIdString::BaseIdString(void) + : _behavior(0) +{ +} + +BaseIdString::BaseIdString(BaseIdBehavior * behavior, + QString string) + : _behavior(behavior) +{ + set(string); +} + + +bool BaseIdString::operator == (const BaseIdString & other) const +{ + return Sortable(QString(*this)) == Sortable(QString(other)); +} + +bool BaseIdString::isNull(void) const +{ + return QString::isEmpty() || ! _behavior; +} + +bool BaseIdString::isSectioned(void) const +{ + return ! _behavior->sectionSeparator().isEmpty(); +} + +void BaseIdString::set(const QString & string) +{ + QString::operator = (_behavior->ingest(string)); +} + +void BaseIdString::append(const QString & section) +{ + QString append = _behavior->ingest(section, true); + if ( ! append.isEmpty()) + QString::operator += (_behavior->sectionSeparator() + append); +} + +void BaseIdString::append(const BaseIdString & section) +{ + if ( ! section.isNull()) + QString::append(QString(_behavior->sectionSeparator()).append(section)); +} + +void BaseIdString::prepend(const QString & section) +{ + QString prepend = _behavior->ingest(section, true); + if ( ! prepend.isEmpty()) + QString::prepend(prepend + _behavior->sectionSeparator()); +} + +QString BaseIdString::sectionSeparator(void) const +{ + return _behavior->sectionSeparator(); +} + +QString BaseIdString::section(int index, int repeatQutoed) const +{ + if (repeatQutoed) + { + QString s(QString::section(_behavior->sectionSeparator(), index, index)); + QStringList qsl; + while (repeatQutoed--) qsl << s; + return "\"" + qsl.join("\",\"") + "\""; + } + else + return QString::section(_behavior->sectionSeparator(), index, index); +} + +QStringList BaseIdString::sectionList(int first, int last) const +{ + return QString::section(_behavior->sectionSeparator(), first, last) + .split(_behavior->sectionSeparator()); +} + +QString BaseIdString::sections(int first, int last) const +{ + return QString::section(_behavior->sectionSeparator(), first, last); +} + +int BaseIdString::sectionCount(void) const +{ + if (isSectioned() && ! isNull()) + return QString::count(_behavior->sectionSeparator()) + 1; + else + return 0; +} + +bool BaseIdString::startsWith(const BaseIdString & section) const +{ + return QString::startsWith(QString(section).append(_behavior->sectionSeparator())); +} diff --git a/pool/shard001/C++/0017504_graph_hmm_silent.cpp b/pool/shard001/C++/0017504_graph_hmm_silent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..866b7f9d2d0596db11eb458e92e7ea250f79c73c --- /dev/null +++ b/pool/shard001/C++/0017504_graph_hmm_silent.cpp @@ -0,0 +1,113 @@ +///A tutorial about HMMs with silent states +#include +#include +#include +#include + +using namespace seqan; + +int main() { +///HMM creation + typedef LogProb<> TProbability; + typedef Dna TAlphabet; + typedef Size::Type TSize; + typedef Graph > THmm; + typedef VertexDescriptor::Type TVertexDescriptor; + typedef EdgeDescriptor::Type TEdgeDescriptor; + + Dna dnaA = Dna('A'); + Dna dnaC = Dna('C'); + Dna dnaG = Dna('G'); + Dna dnaT = Dna('T'); + + THmm hmm; + +///Begin state + TVertexDescriptor begState = addVertex(hmm); + assignBeginState(hmm, begState); + +///Emission states + TVertexDescriptor emitState1 = addVertex(hmm); + emissionProbability(hmm, emitState1, dnaA) = 0.0; + emissionProbability(hmm, emitState1, dnaC) = 0.8; + emissionProbability(hmm, emitState1, dnaG) = 0.1; + emissionProbability(hmm, emitState1, dnaT) = 0.1; + + TVertexDescriptor emitState2 = addVertex(hmm); + emissionProbability(hmm, emitState2, dnaA) = 0.0; + emissionProbability(hmm, emitState2, dnaC) = 0.2; + emissionProbability(hmm, emitState2, dnaG) = 0.2; + emissionProbability(hmm, emitState2, dnaT) = 0.6; + + TVertexDescriptor emitState3 = addVertex(hmm); + emissionProbability(hmm, emitState3, dnaA) = 0.7; + emissionProbability(hmm, emitState3, dnaC) = 0.1; + emissionProbability(hmm, emitState3, dnaG) = 0.1; + emissionProbability(hmm, emitState3, dnaT) = 0.1; + + TVertexDescriptor emitState4 = addVertex(hmm); + emissionProbability(hmm, emitState4, dnaA) = 0.25; + emissionProbability(hmm, emitState4, dnaC) = 0.25; + emissionProbability(hmm, emitState4, dnaG) = 0.25; + emissionProbability(hmm, emitState4, dnaT) = 0.25; + +///Silent states (deletion states) + TVertexDescriptor delState1 = addVertex(hmm, true); + TVertexDescriptor delState2 = addVertex(hmm, true); + TVertexDescriptor delState3 = addVertex(hmm, true); + TVertexDescriptor delState4 = addVertex(hmm, true); + +///End state + TVertexDescriptor eState = addVertex(hmm); + assignEndState(hmm, eState); + +///Transitions + addEdge(hmm, begState, emitState1, 0.5); + addEdge(hmm, begState, delState1, 0.5); + addEdge(hmm, emitState1, emitState2, 0.5); + addEdge(hmm, emitState1, delState2, 0.5); + addEdge(hmm, delState1, emitState2, 0.5); + addEdge(hmm, delState1, delState2, 0.5); + addEdge(hmm, emitState2, emitState3, 0.5); + addEdge(hmm, emitState2, delState3, 0.5); + addEdge(hmm, delState2, emitState3, 0.5); + addEdge(hmm, delState2, delState3, 0.5); + addEdge(hmm, emitState3, emitState4, 0.5); + addEdge(hmm, emitState3, delState4, 0.5); + addEdge(hmm, delState3, emitState4, 0.5); + addEdge(hmm, delState3, delState4, 0.5); + addEdge(hmm, emitState4, eState, 1.0); + addEdge(hmm, delState4, eState, 1.0); + +///Print the whole model + ::std::cout << hmm << ::std::endl; + +///Viterbi algorithm + String sequence = "CA"; + String path; + TProbability p = viterbiAlgorithm(hmm, sequence, path); + ::std::cout << "Viterbi algorithm" << ::std::endl; + ::std::cout << "Probability of the best path: " << p << ::std::endl; + ::std::cout << "Sequence: " << ::std::endl; + for(TSize i = 0; i. + * + */ + + +#include "stdafx.h" +#include "UpdateCheckerDlg.h" +#include "mpc-hc_config.h" +#include + +IMPLEMENT_DYNAMIC(UpdateCheckerDlg, CDialog) + +UpdateCheckerDlg::UpdateCheckerDlg(Update_Status updateStatus, const Version& latestVersion, CWnd* pParent /*=nullptr*/) + : CDialog(UpdateCheckerDlg::IDD, pParent) + , m_updateStatus(updateStatus) +{ + switch (updateStatus) { + case UPDATER_UPDATE_AVAILABLE: + case UPDATER_UPDATE_AVAILABLE_IGNORED: + m_text.Format(IDS_NEW_UPDATE_AVAILABLE, + latestVersion.ToString(), + UpdateChecker::MPC_HC_VERSION.ToString()); + break; + case UPDATER_LATEST_STABLE: + m_text.LoadString(IDS_USING_LATEST_STABLE); + break; + case UPDATER_NEWER_VERSION: + m_text.Format(IDS_USING_NEWER_VERSION, + UpdateChecker::MPC_HC_VERSION.ToString(), + latestVersion.ToString()); + break; + case UPDATER_ERROR: + m_text.LoadString(IDS_UPDATE_ERROR); + break; + default: + ASSERT(0); // should never happen + } +} + +UpdateCheckerDlg::~UpdateCheckerDlg() +{ +} + +void UpdateCheckerDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + DDX_Text(pDX, IDC_UPDATE_DLG_TEXT, m_text); + DDX_Control(pDX, IDC_UPDATE_ICON, m_icon); + DDX_Control(pDX, IDC_UPDATE_DL_BUTTON, m_dlButton); + DDX_Control(pDX, IDC_UPDATE_LATER_BUTTON, m_laterButton); + DDX_Control(pDX, IDC_UPDATE_IGNORE_BUTTON, m_ignoreButton); +} + + +BEGIN_MESSAGE_MAP(UpdateCheckerDlg, CDialog) + ON_BN_CLICKED(IDC_UPDATE_DL_BUTTON, OnOpenDownloadPage) + ON_BN_CLICKED(IDC_UPDATE_LATER_BUTTON, OnUpdateLater) + ON_BN_CLICKED(IDC_UPDATE_IGNORE_BUTTON, OnIgnoreUpdate) +END_MESSAGE_MAP() + +BOOL UpdateCheckerDlg::OnInitDialog() +{ + BOOL ret = __super::OnInitDialog(); + + switch (m_updateStatus) { + case UPDATER_UPDATE_AVAILABLE: + case UPDATER_UPDATE_AVAILABLE_IGNORED: + m_icon.SetIcon(LoadIcon(nullptr, IDI_QUESTION)); + break; + case UPDATER_LATEST_STABLE: + case UPDATER_NEWER_VERSION: + case UPDATER_ERROR: { + m_icon.SetIcon(LoadIcon(nullptr, (m_updateStatus == UPDATER_ERROR) ? IDI_WARNING : IDI_INFORMATION)); + m_dlButton.ShowWindow(SW_HIDE); + m_laterButton.ShowWindow(SW_HIDE); + m_ignoreButton.SetWindowText(ResStr(IDS_UPDATE_CLOSE)); + + CRect buttonRect, windowRect; + m_ignoreButton.GetWindowRect(&buttonRect); + ScreenToClient(&buttonRect); + // Reduce the button width + buttonRect.left += 30; + // Center the button + GetWindowRect(&windowRect); + buttonRect.MoveToX((windowRect.Width() - buttonRect.Width()) / 2); + m_ignoreButton.MoveWindow(&buttonRect); + + // Change the default button + SetDefID(IDC_UPDATE_IGNORE_BUTTON); + ret = FALSE; // Focus has been set explicitly + } + break; + default: + ASSERT(0); // should never happen + } + + return ret; +} + +void UpdateCheckerDlg::OnOpenDownloadPage() +{ + ShellExecute(nullptr, _T("open"), DOWNLOAD_URL, nullptr, nullptr, SW_SHOWNORMAL); + + EndDialog(IDC_UPDATE_DL_BUTTON); +} + +void UpdateCheckerDlg::OnUpdateLater() +{ + EndDialog(IDC_UPDATE_LATER_BUTTON); +} + +void UpdateCheckerDlg::OnIgnoreUpdate() +{ + EndDialog((m_updateStatus == UPDATER_UPDATE_AVAILABLE) ? IDC_UPDATE_IGNORE_BUTTON : 0); +} diff --git a/pool/shard001/C++/0017512_scenerule.cpp b/pool/shard001/C++/0017512_scenerule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72b3331ff1c4d2463d857da556d769996333cd4f --- /dev/null +++ b/pool/shard001/C++/0017512_scenerule.cpp @@ -0,0 +1,54 @@ +/******************************************************************** + Copyright (c) 2013-2015 - Mogara + + This file is part of QSanguosha-Hegemony. + + This game 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.0 + 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. + + See the LICENSE file for more details. + + Mogara + *********************************************************************/ + +#include "settings.h" +#include "engine.h" +#include "scenerule.h" + +SceneRule::SceneRule(QObject *parent) : GameRule(parent) +{ + events << GameStart; +} + +int SceneRule::getPriority() const +{ + return -2; +} + +bool SceneRule::effect(TriggerEvent triggerEvent, Room* room, ServerPlayer *player, QVariant &data, ServerPlayer *) const +{ + QStringList extensions = Sanguosha->getExtensions(); + QSet ban_packages = Config.BanPackages.toSet(); + + if (!player && triggerEvent == GameStart) { + foreach (const QString &extension, extensions) { + bool forbid_package = Config.value("ForbidPackages").toStringList().contains(extension); + if (ban_packages.contains(extension) || forbid_package) continue; + + QString skill = QString("#%1").arg(extension); + if (extension.startsWith("scene") && Sanguosha->getSkill(skill)) { + foreach(ServerPlayer *p, room->getPlayers()) + room->acquireSkill(p, skill); + } + } + } + + return GameRule::effect(triggerEvent, room, player, data, player); +} diff --git a/pool/shard001/C++/0017519_TypedUnstackArrayFactory.cpp b/pool/shard001/C++/0017519_TypedUnstackArrayFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24d7e1b258c629da431d3bae92069aa238befd2c --- /dev/null +++ b/pool/shard001/C++/0017519_TypedUnstackArrayFactory.cpp @@ -0,0 +1,48 @@ +/** + * @file src/modules/control/TypedUnstackArrayFactory.cpp + * @date Jul. 2017 + * @author PhRG - opticalp.fr + */ + +/* + Copyright (c) 2017 Ph. Renaud-Goud / Opticalp + + 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 "TypedUnstackArrayFactory.h" +#include "UnstackArray.h" +#include "core/DataItem.h" + +std::string TypedUnstackArrayFactory::description() +{ + std::string descr("Factory of unstacking array modules for array elements \nof "); + + descr += DataItem::dataTypeStr(DataItem::getTypeFromShortStr(getSelector())); + descr += " data"; + + return descr; +} + +Module* TypedUnstackArrayFactory::newChildModule(std::string customName) +{ + int datatype = DataItem::getTypeFromShortStr(getSelector()); + + return new UnstackArray(this, customName, datatype); +} diff --git a/pool/shard001/C++/0017520_10567.cpp b/pool/shard001/C++/0017520_10567.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cb93ffa3337027eb58b0d7655fd8f4bb42aecb1 --- /dev/null +++ b/pool/shard001/C++/0017520_10567.cpp @@ -0,0 +1,45 @@ +#include +#include +using namespace std; + +char line[1000017], + qs[3517][117], + ch, nch; + +int aw[127][3517], n, + deg[127], index[3517], + strt[3517], endd[3517]; + + +int main(){ + cin>>line>>n; + + for (int i=0; i>qs[i]; ch=qs[i][0]; + aw[ch][deg[ch]++] = i; + endd[i]=-1; + } + + for (int k=0; (ch=line[k]); k++) { + int j=deg[ch]; + deg[ch] = 0; + for (int i=0; iname(); + QMap::iterator it = m_compilers.find(name); + if(it != m_compilers.end()) return false; + m_compilers[name] = compiler; + return true; +} + +void Compilers::removeCompiler(const QString& name) +{ + m_compilers.remove(name); +} + +QStringList Compilers::compilerNames() const +{ + return QStringList(m_compilers.keys()); +} + +const Base *Compilers::compiler(const QString& name) const +{ + QMap::const_iterator it = m_compilers.find(name); + if(it != m_compilers.end()) return 0; + return *it; +} + +QList Compilers::compilers() const +{ + return m_compilers.values(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0017528_BZOJ4781.cpp b/pool/shard001/C++/0017528_BZOJ4781.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e732ee79a31fe645a3615dae0df893a3903e3c75 --- /dev/null +++ b/pool/shard001/C++/0017528_BZOJ4781.cpp @@ -0,0 +1,215 @@ +/******************************************************************************* + * Copyright (c) 2016-2017, xehoth + * 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 xehoth, 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 XEHOTH 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 XEHOTH AND 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. + ******************************************************************************/ +#ifndef DBG + +#define NDEBUG + +#endif + +#include + +namespace IO { +/** + * T1 28-05-2017 + * 贪心 + * O(n \log n) + * @author xehoth + */ +inline char read() { + static const int IN_LEN = 1000000; + static char buf[IN_LEN], *s, *t; + s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0; + return s == t ? -1 : *s++; +} + +template +inline void read(T &x) { + static char c; + static bool iosig; + for (c = read(), iosig = false; !isdigit(c); c = read()) { + if (c == -1) return; + c == '-' ? iosig = true : 0; + } + for (x = 0; isdigit(c); c = read()) x = (x + (x << 2) << 1) + (c ^ '0'); + iosig ? x = -x : 0; +} + +inline int read(char *buf) { + register int s = 0; + register char c; + while (c = read(), isspace(c) && c != -1) + ; + if (c == -1) { + *buf = '\0'; + return -1; + } + do + buf[s++] = c; + while (c = read(), !isspace(c) && c != -1); + buf[s] = '\0'; + return s; +} + +inline void read(double &x) { + static char buf[30]; + read(buf), x = atof(buf); +} + +template +inline void read(T1 &a, T2 &b) { + read(a), read(b); +} + +template +inline void read(T1 &a, T2 &b, T3 &c) { + read(a), read(b), read(c); +} + +template +inline void read(T1 &a, T2 &b, T3 &c, T4 &d) { + read(a), read(b), read(c), read(d); +} + +template +inline void read(T1 &a, T2 &b, T3 &c, T4 &d, T5 &e) { + read(a), read(b), read(c), read(d), read(e); +} + +const int OUT_LEN = 1000000; + +char obuf[OUT_LEN], *oh = obuf; + +inline void print(char c) { + oh == obuf + OUT_LEN ? (fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf) : 0; + *oh++ = c; +} + +template +inline void print(T x) { + static int buf[30], cnt; + if (x == 0) { + print('0'); + } else { + x < 0 ? (print('-'), x = -x) : 0; + for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48; + while (cnt) print((char)buf[cnt--]); + } +} + +inline void print(const char *s) { + for (; *s; s++) print(*s); +} + +template +inline void println(T x) { + print(x), print('\n'); +} + +template +inline void print(T1 a, T2 b) { + print(a), print(b); +} + +template +inline void print(T1 a, T2 b, T3 c) { + print(a), print(b), print(c); +} + +template +inline void print(T1 a, T2 b, T3 c, T4 d) { + print(a), print(b), print(c), print(d); +} + +template +inline void print(T1 a, T2 b, T3 c, T4 d, T5 e) { + print(a), print(b), print(c), print(d), print(e); +} + +template +inline void println(T1 a, T2 b) { + print(a), print(b), print('\n'); +} + +template +inline void println(T1 a, T2 b, T3 c) { + print(a), print(b), print(c), print('\n'); +} + +template +inline void println(T1 a, T2 b, T3 c, T4 d) { + print(a), print(b), print(c), print(d), print('\n'); +} + +template +inline void println(T1 a, T2 b, T3 c, T4 d, T5 e) { + print(a), print(b), print(c), print(d), print(e), print('\n'); +} + +inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); } +} // namespace IO + +namespace Task { + +typedef std::pair Pair; + +inline void solve() { + using namespace IO; + register int n; + read(n); + static std::deque q(n); + for (register int i = 0; i < n; i++) read(q[i].second, q[i].first); + std::sort(q.begin(), q.end()); + register int ans = 0; + while (q.size() > 1) { + ans = std::max(ans, q.front().first + q.back().first); + register int tmp = std::min(q.front().second, q.back().second); + q.front().second -= tmp; + if (!q.front().second) q.pop_front(); + q.back().second -= tmp; + if (!q.back().second) q.pop_back(); + } + if (q.size() == 1) ans = std::max(ans, q.front().first + q.back().first); + print(ans); +} +} // namespace Task + +int main() { +#ifndef ONLINE_JUDGE +#ifdef DBG + freopen("in.in", "r", stdin); + freopen("out.out", "w", stdout); + freopen("debug.log", "w", stderr); +#else + freopen("pairup.in", "r", stdin); + freopen("pairup.out", "w", stdout); +#endif +#endif + Task::solve(); + IO::flush(); + return 0; +} \ No newline at end of file diff --git a/pool/shard001/C++/0017530_main.cpp b/pool/shard001/C++/0017530_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f9093f1fe9d47891a0e055452978f3211cc871c --- /dev/null +++ b/pool/shard001/C++/0017530_main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +struct big_object { + void prepare_data(int value) { + data = value; + } + int data; +}; + + +void process_big_object(std::unique_ptr p) +{ + std::cout << p->data << std::endl; +} + +int main() { + std::unique_ptr p(new big_object); + p->prepare_data(42); + std::thread t(process_big_object, std::move(p)); + t.join(); + + return 0; +} diff --git a/pool/shard001/C++/0017532_ProtocolXml.cpp b/pool/shard001/C++/0017532_ProtocolXml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1bc10ba565c7364cbd96f014689a2bcf2c0c972 --- /dev/null +++ b/pool/shard001/C++/0017532_ProtocolXml.cpp @@ -0,0 +1,161 @@ +// ===================================================================================== +// +// Filename: ProtocolXml.cpp +// +// Description: Xml格式解析 +// +// Version: 1.0 +// Created: 2014年03月17日 9时18分23秒 +// Revision: none +// Compiler: g++ +// +// Author: Hurley (LiuHuan), liuhuan1992@gmail.com +// Company: Class 1107 of Computer Science and Technology +// +// ===================================================================================== + +#include +#include +#include + +#include "ProtocolXml.h" +#include "ProtocolType.h" + +/* + + // 消息类型 0 + xxx.xxx.xxx.xxx // 服务器端IP + x // 服务器端TCP端口 + + +*/ +QByteArray ProtocolXml::CreateBroadcastInfoXml(QString ip, QString port) +{ + QByteArray strXml; + QXmlStreamWriter stream(&strXml); + + stream.setAutoFormatting(true); + + stream.writeStartDocument(); + stream.writeStartElement("wiidroid"); + stream.writeAttribute("type", QString::number(PROTO_SERVERINFO)); + + stream.writeTextElement("ip", ip); + stream.writeTextElement("port", port); + + stream.writeEndElement(); + stream.writeEndDocument(); + + return strXml; +} + +int ProtocolXml::getXmlInfoType(QByteArray &recvPacket) +{ + QXmlStreamReader reader(recvPacket); + + while (!reader.atEnd()) { + QXmlStreamReader::TokenType type = reader.readNext(); + + if (type == QXmlStreamReader::StartElement) { + if (reader.name() == "wiidroid" && reader.attributes().hasAttribute("type")) { + return reader.attributes().value("type").toString().toInt(); + } + } + } + + if (reader.hasError()) { + qDebug() << "XML Format Error:" << reader.errorString() << "\r\n"; + } + + return -1; +} + +/* + + // 消息类型 10 + x // 键盘按下的键的编码 + 0 // 状态 按下为 1,松开为 0 + + */ +void ProtocolXml::parseKeyInfo(QByteArray &recvPacket, KeyPressInfo &keyPressInfo) +{ + QXmlStreamReader reader(recvPacket); + + while (!reader.atEnd()) { + QXmlStreamReader::TokenType type = reader.readNext(); + + if (type == QXmlStreamReader::StartElement) { + if (reader.name() == "key") { + keyPressInfo.key = reader.readElementText(QXmlStreamReader::SkipChildElements).toInt(); + } else if (reader.name() == "status") { + keyPressInfo.isPress = (bool)reader.readElementText(QXmlStreamReader::SkipChildElements).toInt(); + } + } + } + + if (reader.hasError()) { + qDebug() << "XML Format Error:" << reader.errorString() << "\r\n"; + } +} + +/* + + // 消息类型 11 + x // x, y, z 三轴数据 + y + z + + */ +void ProtocolXml::parseASpeedInfo(QByteArray &recvPacket, ASpeedInfo &aSpeedInfo) +{ + QXmlStreamReader reader(recvPacket); + + while (!reader.atEnd()) { + QXmlStreamReader::TokenType type = reader.readNext(); + + if (type == QXmlStreamReader::StartElement) { + if (reader.name() == "coord-x") { + aSpeedInfo.x = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } else if (reader.name() == "coord-y") { + aSpeedInfo.y = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } else if (reader.name() == "coord-z") { + aSpeedInfo.z = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } + } + } + + if (reader.hasError()) { + qDebug() << "XML Format Error:" << reader.errorString() << "\r\n"; + } +} + +/* + + // 消息类型 12 + x // x, y, z 三轴数据 + y + z + +*/ +void ProtocolXml::parseGyroscopeInfo(QByteArray &recvPacket, GyroscopeInfo &gyroscopeInfo) +{ + QXmlStreamReader reader(recvPacket); + + while (!reader.atEnd()) { + QXmlStreamReader::TokenType type = reader.readNext(); + + if (type == QXmlStreamReader::StartElement) { + if (reader.name() == "coord-x") { + gyroscopeInfo.x = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } else if (reader.name() == "coord-y") { + gyroscopeInfo.y = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } else if (reader.name() == "coord-z") { + gyroscopeInfo.z = reader.readElementText(QXmlStreamReader::SkipChildElements).toDouble(); + } + } + } + + if (reader.hasError()) { + qDebug() << "XML Format Error:" << reader.errorString() << "\r\n"; + } +} diff --git a/pool/shard001/C++/0017534_RenderableAttribute.cpp b/pool/shard001/C++/0017534_RenderableAttribute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40b3f66ca2bfd9be12ee54c3dd29b6bf3b908417 --- /dev/null +++ b/pool/shard001/C++/0017534_RenderableAttribute.cpp @@ -0,0 +1,92 @@ +#include "RenderableAttribute.h" +#include +#include + +namespace Frame +{ + +void CRenderableAttribute::UpdateInSPS(Scene::CSPS& SPS) +{ + n_assert_dbg(IsActive()); + + CAABB AABB; + const bool AABBIsValid = GetLocalAABB(AABB); + const bool SPSChanged = (pSPS != &SPS); + + // Remove record, if AABB is invalid or object is moved to another SPS (one scene - one SPS for now) + if (pSPS && (SPSChanged || !AABBIsValid)) + { + if (pSPSRecord) + { + pSPS->RemoveRecord(pSPSRecord); + pSPSRecord = nullptr; + } + else pSPS->OversizedObjects.RemoveByValue(this); + } + + // If AABB is valid, add/update SPS record + if (AABBIsValid) + { + pSPS = &SPS; + + if (AABB.IsEmpty()) + { + if (SPSChanged) SPS.OversizedObjects.Add(this); + } + else + { + if (!pSPSRecord) + { + AABB.Transform(_pNode->GetWorldMatrix()); + pSPSRecord = SPS.AddRecord(AABB, this); + } + else if (_pNode->GetTransformVersion() != LastTransformVersion) //!!! || LocalBox changed! + { + AABB.Transform(_pNode->GetWorldMatrix(), pSPSRecord->GlobalBox); + SPS.UpdateRecord(pSPSRecord); + } + + LastTransformVersion = _pNode->GetTransformVersion(); + } + } + else pSPS = nullptr; +} +//--------------------------------------------------------------------- + +bool CRenderableAttribute::GetGlobalAABB(CAABB& OutBox, UPTR LOD) const +{ + if (!_pNode) FAIL; + + if (pSPSRecord && _pNode->GetTransformVersion() == LastTransformVersion) //!!! && LocalBox not changed! + { + OutBox = pSPSRecord->GlobalBox; + } + else + { + if (GetLocalAABB(OutBox, LOD)) FAIL; + OutBox.Transform(_pNode->GetWorldMatrix()); + } + + OK; +} +//--------------------------------------------------------------------- + +void CRenderableAttribute::OnActivityChanged(bool Active) +{ + if (!Active && pSPS) + { + if (pSPSRecord) + { + pSPS->RemoveRecord(pSPSRecord); + pSPSRecord = nullptr; + } + else + { + pSPS->OversizedObjects.RemoveByValue(this); + } + pSPS = nullptr; + } +} +//--------------------------------------------------------------------- + +} diff --git a/pool/shard001/C++/0017541_segMessaging.cpp b/pool/shard001/C++/0017541_segMessaging.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9222af2f25ec4f6b47ec1ecaa998cb433c9e1fda --- /dev/null +++ b/pool/shard001/C++/0017541_segMessaging.cpp @@ -0,0 +1,19 @@ +#include +#include +#include "segMessaging.h" + +segMessaging::segMessaging(QWidget* _win) { + win = _win; +} + +void segMessaging::info(const char* text) { + QMessageBox::information(win, QString("Segmentor"), QString(text)); +} + +void segMessaging::error(const char* text) { + QMessageBox::critical(win, QString("Segmentor"), QString(text)); +} + +void segMessaging::debug(const char* text) { + qDebug() << text; +} diff --git a/pool/shard001/C++/0017546_commandbutton.cpp b/pool/shard001/C++/0017546_commandbutton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f4f5b7a13021f1cd76243c0680354d8f1bccaed --- /dev/null +++ b/pool/shard001/C++/0017546_commandbutton.cpp @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Konstantin Tokarev. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "commandbutton.h" +#include "actionmanager.h" +#include "command.h" +#include "../id.h" + +#include + +using namespace Core; + +/*! + \class Core::CommandButton + + \brief The CommandButton class is a tool button associated with one of + the registered Command objects. + + Tooltip of this button consists of toolTipBase property value and Command's + key sequence which is automatically updated when user changes it. + */ + +CommandButton::CommandButton(QWidget *parent) + : QToolButton(parent) + , m_command(nullptr) +{ +} + +CommandButton::CommandButton(Id id, QWidget *parent) + : QToolButton(parent) + , m_command(nullptr) +{ + setCommandId(id); +} + +void CommandButton::setCommandId(Id id) +{ + if (m_command) + disconnect(m_command.data(), &Command::keySequenceChanged, this, &CommandButton::updateToolTip); + + m_command = ActionManager::command(id); + + if (m_toolTipBase.isEmpty()) + m_toolTipBase = m_command->description(); + + updateToolTip(); + connect(m_command.data(), &Command::keySequenceChanged, this, &CommandButton::updateToolTip); +} + +QString CommandButton::toolTipBase() const +{ + return m_toolTipBase; +} + +void CommandButton::setToolTipBase(const QString &toolTipBase) +{ + m_toolTipBase = toolTipBase; + updateToolTip(); +} + +void CommandButton::updateToolTip() +{ + if (m_command) + setToolTip(Utils::ProxyAction::stringWithAppendedShortcut(m_toolTipBase, + m_command->keySequence())); +} diff --git a/pool/shard001/C++/0017547_ConfigWriter.cpp b/pool/shard001/C++/0017547_ConfigWriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6607f45eb45907cd4c3a70bbaf7d09bef5b3d77f --- /dev/null +++ b/pool/shard001/C++/0017547_ConfigWriter.cpp @@ -0,0 +1,89 @@ +/* +* Simpatico - Simulation Package for Polymeric and Molecular Liquids +* +* Copyright 2010 - 2017, The Regents of the University of Minnesota +* Distributed under the terms of the GNU General Public License. +*/ + +#include "ConfigWriter.h" +#include +#include + +#include + +namespace DdMd +{ + + using namespace Util; + + /* + * Constructor. + */ + ConfigWriter::ConfigWriter(Simulation& simulation) + : Analyzer(simulation), + nSample_(0), + isInitialized_(false) + { setClassName("ConfigWriter"); } + + /* + * Read interval and outputFileName. + */ + void ConfigWriter::readParameters(std::istream& in) + { + readInterval(in); + readOutputFileName(in); + isInitialized_ = true; + } + + /* + * Load internal state from an archive. + */ + void ConfigWriter::loadParameters(Serializable::IArchive &ar) + { + loadInterval(ar); + loadOutputFileName(ar); + + MpiLoader loader(*this, ar); + loader.load(nSample_); + + isInitialized_ = true; + } + + /* + * Save internal state to an archive. + */ + void ConfigWriter::save(Serializable::OArchive &ar) + { + saveInterval(ar); + saveOutputFileName(ar); + ar << nSample_; + } + + /* + * Read interval and outputFileName. + */ + void ConfigWriter::clear() + { nSample_ = 0; } + + /* + * Dump configuration to file + */ + void ConfigWriter::sample(long iStep) + { + if (isAtInterval(iStep)) { + + // Construct new fileName: outputFileName + toString(nSample) + std::string filename; + filename = outputFileName(); + filename += toString(nSample_); + + // Open output file, write data, and close file + //simulation().fileMaster().openOutputFile(filename, outputFile_); + simulation().writeConfig(filename); + //outputFile_.close(); + ++nSample_; + + } + } + +} diff --git a/pool/shard001/C++/0017553_bitcoin.cpp b/pool/shard001/C++/0017553_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cda1f6877451bb0f16e24831e56d6552b538ece8 --- /dev/null +++ b/pool/shard001/C++/0017553_bitcoin.cpp @@ -0,0 +1,271 @@ +/* + * W.J. van der Laan 2011-2012 + */ +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" + +#include "init.h" +#include "ui_interface.h" +#include "qtipcserver.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static QSplashScreen *splashref; + +static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + // in case of modal message, use blocking connection to wait for user to click OK + QMetaObject::invokeMethod(guiref, "error", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(bool, modal)); + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + } +} + +static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) +{ + if(!guiref) + return false; + if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) + return true; + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void ThreadSafeHandleURI(const std::string& strURI) +{ + if(!guiref) + return; + + QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(QString, QString::fromStdString(strURI))); +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,255)); + QApplication::instance()->processEvents(); + } +} + +static void QueueShutdown() +{ + QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. PosCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Do this early as we don't want to bother initializing if we are just calling IPC + ipcScanRelay(argc, argv); + +#if QT_VERSION < 0x050000 + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); +#endif + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // Command-line options take precedence: + ParseParameters(argc, argv); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "PosCoin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + app.setOrganizationName("PosCoin"); + //XXX app.setOrganizationDomain(""); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + app.setApplicationName("PosCoin-Qt-testnet"); + else + app.setApplicationName("PosCoin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.QueueShutdown.connect(QueueShutdown); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + + QSplashScreen splash(QPixmap(":/images/splash"), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splashref = &splash; + } + + app.processEvents(); + + app.setQuitOnLastWindowClosed(false); + + try + { + // Regenerate startup link, to fix links to old versions + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); + + BitcoinGUI window; + guiref = &window; + if(AppInit2()) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.setWalletModel(&walletModel); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Place this here as guiref has to be defined if we don't want to lose URIs + ipcInit(argc, argv); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.setWalletModel(0); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + Shutdown(NULL); + } + else + { + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard001/C++/0017555_Lsm9ds1.cpp b/pool/shard001/C++/0017555_Lsm9ds1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56ca5540899729a598046ccdb49286c0422a91a3 --- /dev/null +++ b/pool/shard001/C++/0017555_Lsm9ds1.cpp @@ -0,0 +1,108 @@ +#include "Lsm9ds1.h" +#include "Config.h" +#include "Param.h" +#include +#include + +const uint8_t lsm9ds1I2cAddr = 0x6b; +const uint8_t OUT_X_XL = 0x28; +const uint8_t OUT_Y_XL = 0x2A; +const uint8_t OUT_Z_XL = 0x2C; +const uint8_t WHO_AM_I = 0x0f; + + +Lsm9ds1::Lsm9ds1(const std::string& i2cPath, Config config) : + _i2cDevice(i2cPath, lsm9ds1I2cAddr), + _config(config) +{ + uint8_t r = _i2cDevice.read(WHO_AM_I); + std::cout << "Who am I? " << std::hex << static_cast(r) << std::endl; + _config = config; + applyConfig(); +} + +Lsm9ds1::Lsm9ds1(const std::string& i2cPath) : + Lsm9ds1(i2cPath, Config{}) +{} + +Lsm9ds1::~Lsm9ds1() +{ + _config = Config{}; + applyConfig(); +} + +float Lsm9ds1::registerToXl(int16_t regValue) +{ + return 9.81 * static_cast(_config.fsXl()) * + static_cast(regValue) / std::numeric_limits::max(); +} + +void Lsm9ds1::applyConfig() +{ + for(auto reg: _config.registers()) { + _i2cDevice.write({reg.first, reg.second}); + } +} + +void Lsm9ds1::config(Config config) +{ + _config = config; + applyConfig(); +} + +std::vector Lsm9ds1::l() +{ + auto l = _i2cDevice.read>(OUT_X_XL); + std::vector v{ + registerToXl(l[0]), + registerToXl(l[1]), + registerToXl(l[2])}; + return v; +} + +float Lsm9ds1::lx() +{ + return registerToXl(_i2cDevice.read(OUT_X_XL)); +} + +float Lsm9ds1::ly() +{ + return registerToXl(_i2cDevice.read(OUT_Y_XL)); +} + +float Lsm9ds1::lz() +{ + return registerToXl(_i2cDevice.read(OUT_Z_XL)); +} + +float Lsm9ds1::gx() +{ + return 0.0; +} + +float Lsm9ds1::gy() +{ + return 0.0; +} + +float Lsm9ds1::gz() +{ + return 0.0; +} + + +float Lsm9ds1::mx() +{ + return 0.0; +} + +float Lsm9ds1::my() +{ + return 0.0; +} + +float Lsm9ds1::mz() +{ + return 0.0; +} + diff --git a/pool/shard001/C++/0017559_HAP01-13531454.cpp b/pool/shard001/C++/0017559_HAP01-13531454.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4b6ee4a8471b318e2fdbc5ab0d7df5dc9b84a65 --- /dev/null +++ b/pool/shard001/C++/0017559_HAP01-13531454.cpp @@ -0,0 +1,45 @@ +#include +#include +using namespace std; +int main() +{ + int t; + cin>>t; + while(t--) + { + long long int q,n,m,o=0,e=0,k,r=0,i,l; + cin>>m>>n>>k; + for(i=m;i<=n;i++) + { + q=i; + l=0; + e=0; + o=0; + while(q) + { + l++; + if(l%2==0) + { + if(q%2!=0) + { + e++; + } + } + else + { + if(q%2!=0) + { + o++; + } + } + q/=2; + } + if(max(o,e)-min(o,e)==k) + { + r++; + } + } + cout<. + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(MIXING_EXTRUDER) + +#include "../../gcode.h" +#include "../../../feature/mixing.h" + +/** + * M163: Set a single mix factor for a mixing extruder + * This is called "weight" by some systems. + * + * S[index] The channel index to set + * P[float] The mix value + * + */ +void GcodeSuite::M163() { + const int mix_index = parser.intval('S'); + if (mix_index < MIXING_STEPPERS) { + float mix_value = parser.floatval('P'); + NOLESS(mix_value, 0.0); + mixing_factor[mix_index] = RECIPROCAL(mix_value); + } +} + +#if MIXING_VIRTUAL_TOOLS > 1 + + /** + * M164: Store the current mix factors as a virtual tool. + * + * S[index] The virtual tool to store + * + */ + void GcodeSuite::M164() { + const int tool_index = parser.intval('S'); + if (tool_index < MIXING_VIRTUAL_TOOLS) { + normalize_mix(); + for (uint8_t i = 0; i < MIXING_STEPPERS; i++) + mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i]; + } + } + +#endif // MIXING_VIRTUAL_TOOLS > 1 + +#if ENABLED(DIRECT_MIXING_IN_G1) + + /** + * M165: Set multiple mix factors for a mixing extruder. + * Factors that are left out will be set to 0. + * All factors together must add up to 1.0. + * + * A[factor] Mix factor for extruder stepper 1 + * B[factor] Mix factor for extruder stepper 2 + * C[factor] Mix factor for extruder stepper 3 + * D[factor] Mix factor for extruder stepper 4 + * H[factor] Mix factor for extruder stepper 5 + * I[factor] Mix factor for extruder stepper 6 + * + */ + void GcodeSuite::M165() { gcode_get_mix(); } + +#endif // DIRECT_MIXING_IN_G1 + +#endif // MIXING_EXTRUDER diff --git a/pool/shard001/C++/0017568_Bus.cpp b/pool/shard001/C++/0017568_Bus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4551258ca783bec7d983ddbe3dc6496581d9865e --- /dev/null +++ b/pool/shard001/C++/0017568_Bus.cpp @@ -0,0 +1,30 @@ +#include "Bus.hpp" +#include + +using namespace std; + +shared_ptr Bus::at(const uint32_t addr) { + // cout << "Accessing address: " << "0x" << setfill('0') << setw(8) << hex << addr << endl; + for (auto &device: devices) { + if (device.first.compare(addr) == 0) { + uint32_t relativeAddr = device.first.getRelativeAddr(addr); + device.second->setAddress(relativeAddr); + return device.second; + } + } + throw runtime_error("No IO address found for: " + to_string(addr)); +} + +void Bus::updateInterruptingDevice() { + uint32_t interrupts = 0; + for (int i = 0; i < devices.size(); ++i) { + if (devices[i].second->interrupting) { + interrupts |= (1 << i); + } + } + interrupts &= (cp0->regs[12] >> 8); + + static uint32_t interruptClearMask = 0xFFFF00FF; + auto cause = cp0->regs[13]; + cp0->regs[13] = (cause & interruptClearMask) | (interrupts << 8); +} diff --git a/pool/shard001/C++/0017573_BufferParameters.cpp b/pool/shard001/C++/0017573_BufferParameters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b66a59cf261edb6ee26440bde776bd7c235bf46 --- /dev/null +++ b/pool/shard001/C++/0017573_BufferParameters.cpp @@ -0,0 +1,135 @@ +/********************************************************************** + * + * GEOS - Geometry Engine Open Source + * http://geos.osgeo.org + * + * Copyright (C) 2009 Sandro Santilli + * + * 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. + * + ********************************************************************** + * + * Last port: operation/buffer/BufferParameters.java r278 (JTS-1.12) + * + **********************************************************************/ + +#include // for std::abs() +#include // for cos + +#include +#include + + +namespace geos { +namespace operation { // geos.operation +namespace buffer { // geos.operation.buffer + +// public static const +const double BufferParameters::DEFAULT_MITRE_LIMIT = 5.0; + +// public +BufferParameters::BufferParameters() + : + quadrantSegments(DEFAULT_QUADRANT_SEGMENTS), + endCapStyle(CAP_ROUND), + joinStyle(JOIN_ROUND), + mitreLimit(DEFAULT_MITRE_LIMIT), + _isSingleSided(false) +{} + +// public +BufferParameters::BufferParameters(int p_quadrantSegments) + : + quadrantSegments(DEFAULT_QUADRANT_SEGMENTS), + endCapStyle(CAP_ROUND), + joinStyle(JOIN_ROUND), + mitreLimit(DEFAULT_MITRE_LIMIT), + _isSingleSided(false) +{ + setQuadrantSegments(p_quadrantSegments); +} + +// public +BufferParameters::BufferParameters(int p_quadrantSegments, + EndCapStyle p_endCapStyle) + : + quadrantSegments(DEFAULT_QUADRANT_SEGMENTS), + endCapStyle(CAP_ROUND), + joinStyle(JOIN_ROUND), + mitreLimit(DEFAULT_MITRE_LIMIT), + _isSingleSided(false) +{ + setQuadrantSegments(p_quadrantSegments); + setEndCapStyle(p_endCapStyle); +} + +// public +BufferParameters::BufferParameters(int p_quadrantSegments, + EndCapStyle p_endCapStyle, + JoinStyle p_joinStyle, + double p_mitreLimit) + : + quadrantSegments(DEFAULT_QUADRANT_SEGMENTS), + endCapStyle(CAP_ROUND), + joinStyle(JOIN_ROUND), + mitreLimit(DEFAULT_MITRE_LIMIT), + _isSingleSided(false) +{ + setQuadrantSegments(p_quadrantSegments); + setEndCapStyle(p_endCapStyle); + setJoinStyle(p_joinStyle); + setMitreLimit(p_mitreLimit); +} + +// public +void +BufferParameters::setQuadrantSegments(int quadSegs) +{ + quadrantSegments = quadSegs; + + /* + * Indicates how to construct fillets. + * If qs >= 1, fillet is round, and qs indicates number of + * segments to use to approximate a quarter-circle. + * If qs = 0, fillet is bevelled flat (i.e. no filleting is performed) + * If qs < 0, fillet is mitred, and absolute value of qs + * indicates maximum length of mitre according to + * + * mitreLimit = |qs| + */ + if(quadrantSegments == 0) { + joinStyle = JOIN_BEVEL; + } + if(quadrantSegments < 0) { + joinStyle = JOIN_MITRE; + mitreLimit = std::abs(quadrantSegments); + } + + if(quadSegs <= 0) { + quadrantSegments = 1; + } + + /* + * If join style was set by the quadSegs value, + * use the default for the actual quadrantSegments value. + */ + if(joinStyle != JOIN_ROUND) { + quadrantSegments = DEFAULT_QUADRANT_SEGMENTS; + } +} + +// public static +double +BufferParameters::bufferDistanceError(int quadSegs) +{ + double alpha = MATH_PI / 2.0 / quadSegs; + return 1 - cos(alpha / 2.0); +} + +} // namespace geos.operation.buffer +} // namespace geos.operation +} // namespace geos + diff --git a/pool/shard001/C++/0017597_batch_resource_base_test.cc b/pool/shard001/C++/0017597_batch_resource_base_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..17682f372bbdc494ffb02864b949ec3cde9fcf7c --- /dev/null +++ b/pool/shard001/C++/0017597_batch_resource_base_test.cc @@ -0,0 +1,169 @@ +/* Copyright 2021 The TensorFlow Authors. 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. +==============================================================================*/ + +#include "tensorflow/core/kernels/batching_util/batch_resource_base.h" + +#include "absl/time/time.h" +#include "tensorflow/core/common_runtime/cost_measurement.h" +#include "tensorflow/core/common_runtime/cost_measurement_registry.h" +#include "tensorflow/core/common_runtime/no_op_cost_measurement.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace serving { +namespace { + +using ::testing::Pair; +using ::testing::UnorderedElementsAre; + +class TestTpuCostMeasurement : public CostMeasurement { + public: + using CostMeasurement::CostMeasurement; + + absl::Duration GetTotalCost() override { return absl::Milliseconds(100); } + absl::string_view GetCostType() const override { return "test_tpu"; } +}; +REGISTER_COST_MEASUREMENT("test_tpu", TestTpuCostMeasurement); + +class TestGcuCostMeasurement : public CostMeasurement { + public: + using CostMeasurement::CostMeasurement; + + absl::Duration GetTotalCost() override { return absl::Milliseconds(200); } + absl::string_view GetCostType() const override { return "test_gcu"; } +}; +REGISTER_COST_MEASUREMENT("test_gcu", TestGcuCostMeasurement); + +std::unique_ptr MakeBatchTask( + const int64_t task_size, RequestCost* request_cost) { + auto task = absl::make_unique(); + task->inputs.push_back(Tensor(DT_DOUBLE, TensorShape({task_size, 1}))); + task->request_cost = request_cost; + return task; +} + +TEST(SplitBatchCostTest, SkipOnNoCostMeasurement) { + BatchResourceBase::BatchT batch; + RequestCost cost; + batch.AddTask(MakeBatchTask(/*task_size=*/1, &cost)); + batch.Close(); + + std::vector> batch_cost_measurements; + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/16, batch); + EXPECT_TRUE(batch.task(0).request_cost->GetCosts().empty()); +} + +TEST(SplitBatchCostTest, SkipOnZeroCost) { + BatchResourceBase::BatchT batch; + RequestCost cost; + batch.AddTask(MakeBatchTask(/*task_size=*/1, &cost)); + batch.Close(); + + CostMeasurement::Context context{/*is_per_query=*/false}; + std::vector> batch_cost_measurements; + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("no_op", context)); + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/16, batch); + EXPECT_TRUE(batch.task(0).request_cost->GetCosts().empty()); +} + +TEST(SplitBatchCostTest, SkipOnZeroBatchSize) { + BatchResourceBase::BatchT batch; + batch.Close(); + + CostMeasurement::Context context{/*is_per_query=*/false}; + std::vector> batch_cost_measurements; + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("test_tpu", context)); + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/0, batch); +} + +TEST(SplitBatchCostTest, SkipOnNoRequestCost) { + BatchResourceBase::BatchT batch; + batch.AddTask(MakeBatchTask(/*task_size=*/1, nullptr)); + batch.AddTask(MakeBatchTask(/*task_size=*/9, nullptr)); + batch.Close(); + + CostMeasurement::Context context{/*is_per_query=*/false}; + std::vector> batch_cost_measurements; + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("test_tpu", context)); + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/16, batch); + + EXPECT_EQ(batch.task(0).request_cost, nullptr); + EXPECT_EQ(batch.task(1).request_cost, nullptr); +} + +TEST(SplitBatchCostTest, SplitSingleCostType) { + BatchResourceBase::BatchT batch; + RequestCost cost1, cost2; + batch.AddTask(MakeBatchTask(/*task_size=*/1, &cost1)); + batch.AddTask(MakeBatchTask(/*task_size=*/9, &cost2)); + batch.Close(); + + CostMeasurement::Context context{/*is_per_query=*/false}; + std::vector> batch_cost_measurements; + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("test_tpu", context)); + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/20, batch); + + EXPECT_THAT( + batch.task(0).request_cost->GetCosts(), + UnorderedElementsAre(Pair("test_tpu_with_smear", absl::Milliseconds(10)), + Pair("test_tpu_no_smear", absl::Milliseconds(5)))); + EXPECT_THAT( + batch.task(1).request_cost->GetCosts(), + UnorderedElementsAre(Pair("test_tpu_with_smear", absl::Milliseconds(90)), + Pair("test_tpu_no_smear", absl::Milliseconds(45)))); +} + +TEST(SplitBatchCostTest, SplitMultiCostTypes) { + BatchResourceBase::BatchT batch; + RequestCost cost1, cost2; + batch.AddTask(MakeBatchTask(/*task_size=*/1, &cost1)); + batch.AddTask(MakeBatchTask(/*task_size=*/9, &cost2)); + batch.Close(); + + CostMeasurement::Context context{/*is_per_query=*/false}; + std::vector> batch_cost_measurements; + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("test_tpu", context)); + batch_cost_measurements.push_back( + CostMeasurementRegistry::CreateByNameOrNull("test_gcu", context)); + BatchResourceBase::SplitBatchCosts(batch_cost_measurements, + /*processed_size=*/20, batch); + + EXPECT_THAT( + batch.task(0).request_cost->GetCosts(), + UnorderedElementsAre(Pair("test_tpu_with_smear", absl::Milliseconds(10)), + Pair("test_tpu_no_smear", absl::Milliseconds(5)), + Pair("test_gcu_with_smear", absl::Milliseconds(20)), + Pair("test_gcu_no_smear", absl::Milliseconds(10)))); + EXPECT_THAT( + batch.task(1).request_cost->GetCosts(), + UnorderedElementsAre(Pair("test_tpu_with_smear", absl::Milliseconds(90)), + Pair("test_tpu_no_smear", absl::Milliseconds(45)), + Pair("test_gcu_with_smear", absl::Milliseconds(180)), + Pair("test_gcu_no_smear", absl::Milliseconds(90)))); +} + +} // namespace +} // namespace serving +} // namespace tensorflow diff --git a/pool/shard001/C++/0017598_DebugClient.cc b/pool/shard001/C++/0017598_DebugClient.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0280ac4ad8c8c929ff9665ddab77aa039cc0c80 --- /dev/null +++ b/pool/shard001/C++/0017598_DebugClient.cc @@ -0,0 +1,167 @@ +// Copyright (c) 2011-2012 Ryan Prichard +// +// 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 "DebugClient.h" + +#include +#include +#include +#include + +#include +#include + +#include "winpty_snprintf.h" + +const wchar_t *const kPipeName = L"\\\\.\\pipe\\DebugServer"; + +void *volatile g_debugConfig; + +static void sendToDebugServer(const char *message) +{ + HANDLE tracePipe = INVALID_HANDLE_VALUE; + + do { + // The default impersonation level is SECURITY_IMPERSONATION, which allows + // a sufficiently authorized named pipe server to impersonate the client. + // There's no need for impersonation in this debugging system, so reduce + // the impersonation level to SECURITY_IDENTIFICATION, which allows a + // server to merely identify us. + tracePipe = CreateFileW( + kPipeName, + GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, + SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, + NULL); + } while (tracePipe == INVALID_HANDLE_VALUE && + GetLastError() == ERROR_PIPE_BUSY && + WaitNamedPipeW(kPipeName, NMPWAIT_WAIT_FOREVER)); + + if (tracePipe != INVALID_HANDLE_VALUE) { + DWORD newMode = PIPE_READMODE_MESSAGE; + SetNamedPipeHandleState(tracePipe, &newMode, NULL, NULL); + char response[16]; + DWORD actual = 0; + TransactNamedPipe(tracePipe, + const_cast(message), strlen(message), + response, sizeof(response), &actual, NULL); + CloseHandle(tracePipe); + } +} + +// Get the current UTC time as milliseconds from the epoch (ignoring leap +// seconds). Use the Unix epoch for consistency with DebugClient.py. There +// are 134774 days between 1601-01-01 (the Win32 epoch) and 1970-01-01 (the +// Unix epoch). +static long long unixTimeMillis() +{ + FILETIME fileTime; + GetSystemTimeAsFileTime(&fileTime); + long long msTime = (((long long)fileTime.dwHighDateTime << 32) + + fileTime.dwLowDateTime) / 10000; + return msTime - 134774LL * 24 * 3600 * 1000; +} + +static const char *getDebugConfig() +{ + if (g_debugConfig == NULL) { + const int bufSize = 256; + char buf[bufSize]; + DWORD actualSize = + GetEnvironmentVariableA("WINPTY_DEBUG", buf, bufSize); + if (actualSize == 0 || actualSize >= static_cast(bufSize)) { + buf[0] = '\0'; + } + const size_t len = strlen(buf) + 1; + char *newConfig = new char[len]; + std::copy(buf, buf + len, newConfig); + void *oldValue = InterlockedCompareExchangePointer( + &g_debugConfig, newConfig, NULL); + if (oldValue != NULL) { + delete [] newConfig; + } + } + return static_cast(g_debugConfig); +} + +bool isTracingEnabled() +{ + static bool disabled, enabled; + if (disabled) { + return false; + } else if (enabled) { + return true; + } else { + // Recognize WINPTY_DEBUG=1 for backwards compatibility. + bool value = hasDebugFlag("trace") || hasDebugFlag("1"); + disabled = !value; + enabled = value; + return value; + } +} + +bool hasDebugFlag(const char *flag) +{ + if (strchr(flag, ',') != NULL) { + trace("INTERNAL ERROR: hasDebugFlag flag has comma: '%s'", flag); + abort(); + } + const char *const configCStr = getDebugConfig(); + if (configCStr[0] == '\0') { + return false; + } + std::string config(configCStr); + std::string flagStr(flag); + config = "," + config + ","; + flagStr = "," + flagStr + ","; + return config.find(flagStr) != std::string::npos; +} + +void trace(const char *format, ...) +{ + if (!isTracingEnabled()) + return; + + char message[1024]; + + va_list ap; + va_start(ap, format); + winpty_vsnprintf(message, format, ap); + message[sizeof(message) - 1] = '\0'; + va_end(ap); + + const int currentTime = (int)(unixTimeMillis() % (100000 * 1000)); + + char moduleName[1024]; + moduleName[0] = '\0'; + GetModuleFileNameA(NULL, moduleName, sizeof(moduleName)); + const char *baseName = strrchr(moduleName, '\\'); + baseName = (baseName != NULL) ? baseName + 1 : moduleName; + + char fullMessage[1024]; + winpty_snprintf(fullMessage, + "[%05d.%03d %s,p%04d,t%04d]: %s", + currentTime / 1000, currentTime % 1000, + baseName, (int)GetCurrentProcessId(), (int)GetCurrentThreadId(), + message); + fullMessage[sizeof(fullMessage) - 1] = '\0'; + + sendToDebugServer(fullMessage); +} diff --git a/pool/shard001/C++/0017605_AttributeValue.cpp b/pool/shard001/C++/0017605_AttributeValue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00b553d482931321464e93f893d72cbd56885391 --- /dev/null +++ b/pool/shard001/C++/0017605_AttributeValue.cpp @@ -0,0 +1,68 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file 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 + +using namespace Aws::EC2::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +AttributeValue::AttributeValue() : + m_valueHasBeenSet(false) +{ +} + +AttributeValue::AttributeValue(const XmlNode& xmlNode) : + m_valueHasBeenSet(false) +{ + *this = xmlNode; +} + +AttributeValue& AttributeValue::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode valueNode = resultNode.FirstChild("value"); + if(!valueNode.IsNull()) + { + m_value = StringUtils::Trim(valueNode.GetText().c_str()); + m_valueHasBeenSet = true; + } + } + + return *this; +} + +void AttributeValue::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_valueHasBeenSet) + { + oStream << location << index << locationValue << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; + } +} + +void AttributeValue::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_valueHasBeenSet) + { + oStream << location << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; + } +} diff --git a/pool/shard001/C++/0017606_CandidateMapUtils.cpp b/pool/shard001/C++/0017606_CandidateMapUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa56f0db9f03eecfbfb564f359fe4b0d42ed61c4 --- /dev/null +++ b/pool/shard001/C++/0017606_CandidateMapUtils.cpp @@ -0,0 +1,204 @@ +// Copyright 2014 The Souper Authors. 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. + +#include "souper/Tool/CandidateMapUtils.h" + +#include "llvm/IR/Constants.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Module.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include "souper/KVStore/KVStore.h" +#include "souper/SMTLIB2/Solver.h" + +using namespace llvm; + +void souper::AddToCandidateMap(CandidateMap &M, + const CandidateReplacement &CR) { + M.emplace_back(CR); +} + +void souper::AddModuleToCandidateMap(InstContext &IC, ExprBuilderContext &EBC, + CandidateMap &CandMap, llvm::Module *M) { + for (auto &F : *M) { + FunctionCandidateSet CS = ExtractCandidates(&F, IC, EBC); + for (auto &B : CS.Blocks) { + for (auto &R : B->Replacements) { + AddToCandidateMap(CandMap, R); + } + } + } +} + +namespace souper { + +bool SolveCandidateMap(llvm::raw_ostream &OS, CandidateMap &M, + Solver *S, InstContext &IC, KVStore *KVForStaticProfile) { + if (S) { + OS << "; Listing valid replacements.\n"; + OS << "; Using solver: " << S->getName() << '\n'; + + std::vector Profile; + std::map Index; + for (int I=0; I < M.size(); ++I) { + auto &Cand = M[I]; + ReplacementContext Context; + auto S = GetReplacementLHSString(Cand.BPCs, Cand.PCs, + Cand.Mapping.LHS, Context); + if (Index.find(S) == Index.end()) { + Index[S] = I; + Profile.push_back(1); + } else { + ++Profile[Index[S]]; + Profile.push_back(0); + } + } + + for (int I=0; I < M.size(); ++I) { + if (Profile[I] == 0) + continue; + auto &Cand = M[I]; + + if (KVForStaticProfile) { + std::string Str; + llvm::raw_string_ostream Loc(Str); + Instruction *I = Cand.Origin.getInstruction(); + I->getDebugLoc().print(Loc); + std::string HField = "sprofile " + Loc.str(); + ReplacementContext Context; + KVForStaticProfile->hIncrBy(GetReplacementLHSString(Cand.BPCs, + Cand.PCs, Cand.Mapping.LHS, Context), HField, 1); + } + + Inst *RHS; + if (std::error_code EC = + S->infer(Cand.BPCs, Cand.PCs, Cand.Mapping.LHS, RHS, IC)) { + llvm::errs() << "Unable to query solver: " << EC.message() << '\n'; + return false; + } + if (RHS) { + OS << '\n'; + OS << "; Static profile " << Profile[I] << '\n'; + Cand.Mapping.RHS = RHS; + Cand.printFunction(OS); + Cand.print(OS); + } + } + } else { + OS << "; No solver specified; listing all candidate replacements.\n"; + for (auto &Cand : M) { + OS << '\n'; + Cand.printFunction(OS); + ReplacementContext Context; + Cand.printLHS(OS, Context); + } + } + + return true; +} + +bool CheckCandidateMap(llvm::Module &Mod, CandidateMap &M, Solver *S, + InstContext &IC) { + if (!S) { + llvm::errs() << "Solver required in -check mode\n"; + return false; + } + + unsigned ExpectedID = Mod.getContext().getMDKindID("expected"); + + bool OK = true; + for (auto &Cand : M) { + Inst *RHS; + if (std::error_code EC = + S->infer(Cand.BPCs, Cand.PCs, Cand.Mapping.LHS, RHS, IC)) { + llvm::errs() << "Unable to query solver: " << EC.message() << '\n'; + return false; + } + if (RHS) { + Cand.Mapping.RHS = RHS; + if (Cand.Mapping.RHS->K != Inst::Const) { + llvm::errs() << "found replacement:\n"; + Cand.printFunction(llvm::errs()); + Cand.print(llvm::errs()); + llvm::errs() << "but cannot yet analyze non-constant replacements\n"; + OK = false; + continue; + } + llvm::APInt ActualVal = Cand.Mapping.RHS->Val; + + llvm::Instruction *Inst = Cand.Origin.getInstruction(); + llvm::MDNode *ExpectedMD = Inst->getMetadata(ExpectedID); + if (!ExpectedMD) { + llvm::errs() << "instruction:\n"; + Inst->print(llvm::errs(), /*IsForDebug=*/true); + llvm::errs() << "\n"; + llvm::errs() << "unexpected simplification:\n"; + Cand.printFunction(llvm::errs()); + Cand.print(llvm::errs()); + OK = false; + continue; + } + if (ExpectedMD->getNumOperands() != 1 || + !mdconst::hasa(ExpectedMD->getOperand(0))) { + llvm::errs() << "instruction:\n"; + Inst->print(llvm::errs(), /*IsForDebug=*/true); + llvm::errs() << "\n"; + llvm::errs() << "invalid metadata\n"; + OK = false; + continue; + } + llvm::APInt ExpectedVal = + mdconst::extract(ExpectedMD->getOperand(0))->getValue(); + Inst->setMetadata(ExpectedID, 0); + if (ExpectedVal.getBitWidth() != ActualVal.getBitWidth()) { + llvm::errs() << "metadata width doesn't match value width\n"; + OK = false; + continue; + } + if (ExpectedVal != ActualVal) { + llvm::errs() << "instruction:\n"; + Inst->print(llvm::errs(), /*IsForDebug=*/true); + llvm::errs() << "\n"; + llvm::errs() << "unexpected simplification, wanted " << ExpectedVal + << ":\n"; + Cand.printFunction(llvm::errs()); + Cand.print(llvm::errs()); + OK = false; + continue; + } + } + } + + for (const auto &F : Mod) { + for (const auto &BB : F) { + for (const auto &Inst : BB) { + llvm::MDNode *ExpectedMD = Inst.getMetadata(ExpectedID); + if (ExpectedMD) { + llvm::errs() << "instruction:\n"; + Inst.print(llvm::errs(), /*IsForDebug=*/true); + llvm::errs() << "\n"; + llvm::errs() << "expected simplification, none found\n"; + OK = false; + continue; + } + } + } + } + + return OK; +} + +} diff --git a/pool/shard001/C++/0017609_RIDecayCalculation.cc b/pool/shard001/C++/0017609_RIDecayCalculation.cc new file mode 100644 index 0000000000000000000000000000000000000000..9bf7462ff6907b5616d54e96a521aa36029f60dd --- /dev/null +++ b/pool/shard001/C++/0017609_RIDecayCalculation.cc @@ -0,0 +1,226 @@ +/** + * @file RIDecayCalculation.cc + * @brief source file of class RIDecayCalculation + * @author Hirokazu Odaka + * @date 2016-05-04 + */ + +#include "RIDecayCalculation.hh" + +#include + +#include "G4RunManager.hh" +#include "Shielding.hh" +#include "DummyDetectorConstruction.hh" +#include "G4ParticleDefinition.hh" +#include "G4ParticleTable.hh" +#include "G4IonTable.hh" +#include "G4Ions.hh" +#include "G4RadioactiveDecay.hh" + +#include "AstroUnits.hh" +#include "TimeProfile.hh" +#include "RateData.hh" +#include "RIDecayProperties.hh" +#include "RIDecayChains.hh" + +namespace unit = anlgeant4::unit; + +namespace comptonsoft +{ + +RIDecayCalculation::RIDecayCalculation() + : verbose_level_(0), + filename_production_rate_("production_rate.dat"), + filename_irradiation_("irradiation.dat"), + average_mode_(false), + measurement_time_(0.0), + count_threshold_(0.0), + decay_constant_threshold_(0.0), + branching_ratio_threshold_(1.0e-6), + filename_decay_rate_("decay_rate.dat"), + geant4_run_manager_(new G4RunManager), + irradiation_profile_(new TimeProfile), + production_rate_data_(new RateData), + decay_rate_data_(new RateData) +{ +} + +RIDecayCalculation::~RIDecayCalculation() = default; + +void RIDecayCalculation::setMeasurementTime(double t) +{ + average_mode_ = false; + measurement_time_ = t*unit::second; +} + +double RIDecayCalculation::MeasurememtTime() const +{ + return measurement_time_/unit::second; +} + +void RIDecayCalculation::addMeasurementWindow(double t1, double t2) +{ + average_mode_ = true; + measurement_windows_.emplace_back(t1*unit::second, t2*unit::second); +} + +double RIDecayCalculation::getStartingTimeOfWindow(std::size_t i) const +{ + return measurement_windows_[i].first/unit::second; +} + +double RIDecayCalculation::getEndingTimeOfWindow(std::size_t i) const +{ + return measurement_windows_[i].second/unit::second; +} + +void RIDecayCalculation::setDecayConstantThreshold(double v) +{ + decay_constant_threshold_ = v * (1.0/unit::second); +} + +double RIDecayCalculation::DecayConstantThreshold() const +{ + return decay_constant_threshold_/(1.0/unit::second); +} + +bool RIDecayCalculation::initialize() +{ + if (verbose_level_ > 0) { + std::cout << '\n' + << "RIDecayCalculation: Initialization started.\n" << std::endl; + } + + initialize_geant4(); + + if (verbose_level_ > 0) { + std::cout << '\n' + << "Loading irradiation file: " << filename_irradiation_ + << std::endl; + } + if (!irradiation_profile_->readFile(filename_irradiation_)) { + return false; + } + + if (verbose_level_ > 0) { + std::cout << '\n' + << "Loading production rate file: " << filename_production_rate_ + << std::endl; + } + production_rate_data_->setCountThreshold(count_threshold_); + if (!production_rate_data_->readFile(filename_production_rate_)) { + return false; + } + + return true; +} + +void RIDecayCalculation::initialize_geant4() +{ + geant4_run_manager_->SetUserInitialization(new comptonsoft::DummyDetectorConstruction); + geant4_run_manager_->SetUserInitialization(new Shielding); + geant4_run_manager_->Initialize(); + +#if 0 /* probably not necessary */ + geant4_run_manager_->BeamOn(0); +#endif +} + +void RIDecayCalculation::perform() +{ + G4RadioactiveDecay* decayProcess = new G4RadioactiveDecay; + + const std::size_t NumberOfVolumes + = production_rate_data_->NumberOfVolumes(); + + for (std::size_t iVolume=0; iVolumegetVolumeName(iVolume); + const RateVector rateVector = production_rate_data_->getRateVector(iVolume); + + if (verbose_level_ > 0) { + std::cout << "\n################################\n" + << "Decay calculation for \n" + << "Volume[" << iVolume << "] " << volumeName + << std::endl; + } + + std::map accumulation; + + for (const IsotopeInfo& isotope: rateVector) { + const double productionEfficiency = isotope.Rate(); + std::unique_ptr chains(new RIDecayChains(isotope)); + chains->setVerboseLevel(verbose_level_); + chains->setDecayConstantThreshold(decay_constant_threshold_); + chains->setBranchingRatioThreshold(branching_ratio_threshold_); + chains->setDecayProcess(decayProcess); + chains->build(); + chains->prepareSolutions(); + if (!average_mode_) { + chains->solve(*irradiation_profile_, measurement_time_); + } + else { + chains->solve(*irradiation_profile_, measurement_windows_); + } + + const std::map& results = chains->getResults(); + for (auto& pair: results) { + const int64_t isotopeID = pair.first; + const double solution = pair.second; + const double isotopeAmount = productionEfficiency * solution; + if (accumulation.count(isotopeID)==0) { + accumulation[isotopeID] = isotopeAmount; + } + else { + accumulation[isotopeID] += isotopeAmount; + } + } + } + + RateVector decayRateVector = makeDecayRateVector(accumulation); + decay_rate_data_->pushData(volumeName, decayRateVector); + } +} + +RateVector RIDecayCalculation:: +makeDecayRateVector(const std::map& accumulation) +{ + RateVector rateVector; + for (auto& pair: accumulation) { + const int64_t isotopeID = pair.first; + const double isotopeAmount = pair.second; + IsotopeInfo isotope(isotopeID); + G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); + + if (isotope.Z() == 0) { + // to avoid an error by G4IonTable::GetIon() with Z=0, A=1 + continue; + } + + const G4ParticleDefinition* nucleus + = particleTable->GetIonTable()->GetIon(isotope.Z(), + isotope.A(), + isotope.Energy(), + G4Ions::FloatLevelBase(isotope.FloatingLevel())); + const double lifetime = nucleus->GetPDGLifeTime(); + const double decayConstant = invert_lifetime(lifetime); + const double decayRate = decayConstant * isotopeAmount; + isotope.setRate(decayRate); + rateVector.push_back(isotope); + } + return rateVector; +} + +void RIDecayCalculation::output() +{ + if (verbose_level_ > 0) { + std::cout << '\n' + << "RIDecayCalculation: Saving results to " + << filename_decay_rate_ + << ".\n" << std::endl; + } + + decay_rate_data_->writeFile(filename_decay_rate_); +} + +} /* namespace comptonsoft */ diff --git a/pool/shard001/C++/0017612_debugger.cpp b/pool/shard001/C++/0017612_debugger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55243c4bc7e9dce275091049061751fcb2045b0a --- /dev/null +++ b/pool/shard001/C++/0017612_debugger.cpp @@ -0,0 +1,163 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "sherlock/debugger.h" +#include "sherlock/sherlock.h" +#include "sherlock/music.h" +#include "sherlock/scalpel/scalpel.h" +#include "sherlock/scalpel/scalpel_debugger.h" +#include "sherlock/tattoo/tattoo_debugger.h" +#include "common/str-array.h" + +namespace Sherlock { + +Debugger *Debugger::init(SherlockEngine *vm) { + if (vm->getGameID() == GType_RoseTattoo) + return new Tattoo::TattooDebugger(vm); + else + return new Scalpel::ScalpelDebugger(vm); +} + +Debugger::Debugger(SherlockEngine *vm) : GUI::Debugger(), _vm(vm) { + _showAllLocations = LOC_DISABLED; + + registerCmd("continue", WRAP_METHOD(Debugger, cmdExit)); + registerCmd("scene", WRAP_METHOD(Debugger, cmdScene)); + registerCmd("song", WRAP_METHOD(Debugger, cmdSong)); + registerCmd("songs", WRAP_METHOD(Debugger, cmdListSongs)); + registerCmd("listfiles", WRAP_METHOD(Debugger, cmdListFiles)); + registerCmd("dumpfile", WRAP_METHOD(Debugger, cmdDumpFile)); + registerCmd("locations", WRAP_METHOD(Debugger, cmdLocations)); +} + +void Debugger::postEnter() { + if (!_3doPlayMovieFile.empty()) { + static_cast(_vm)->play3doMovie(_3doPlayMovieFile, Common::Point(0, 0)); + + _3doPlayMovieFile.clear(); + } + + _vm->pauseEngine(false); +} + +int Debugger::strToInt(const char *s) { + if (!*s) + // No string at all + return 0; + else if (toupper(s[strlen(s) - 1]) != 'H') + // Standard decimal string + return atoi(s); + + // Hexadecimal string + uint tmp = 0; + int read = sscanf(s, "%xh", &tmp); + if (read < 1) + error("strToInt failed on string \"%s\"", s); + return (int)tmp; +} + +bool Debugger::cmdScene(int argc, const char **argv) { + if (argc != 2) { + debugPrintf("Format: scene \n"); + return true; + } else { + _vm->_scene->_goToScene = strToInt(argv[1]); + return false; + } +} + +bool Debugger::cmdSong(int argc, const char **argv) { + if (argc != 2) { + debugPrintf("Format: song \n"); + return true; + } + + Common::StringArray songs; + _vm->_music->getSongNames(songs); + + for (uint i = 0; i < songs.size(); i++) { + if (songs[i].equalsIgnoreCase(argv[1])) { + _vm->_music->loadSong(songs[i]); + return false; + } + } + + debugPrintf("Invalid song. Use the 'songs' command to see which ones are available.\n"); + return true; +} + +bool Debugger::cmdListSongs(int argc, const char **argv) { + Common::StringArray songs; + _vm->_music->getSongNames(songs); + debugPrintColumns(songs); + return true; +} + +bool Debugger::cmdListFiles(int argc, const char **argv) { + if (argc != 2) { + debugPrintf("Format: listfiles \n"); + return true; + } + Common::StringArray files; + _vm->_res->getResourceNames(Common::String(argv[1]), files); + debugPrintColumns(files); + return true; +} + +bool Debugger::cmdDumpFile(int argc, const char **argv) { + if (argc != 2) { + debugPrintf("Format: dumpfile \n"); + return true; + } + + Common::SeekableReadStream *s = _vm->_res->load(argv[1]); + if (!s) { + debugPrintf("Invalid resource.\n"); + return true; + } + + byte *buffer = new byte[s->size()]; + s->read(buffer, s->size()); + + Common::DumpFile dumpFile; + dumpFile.open(argv[1]); + + dumpFile.write(buffer, s->size()); + dumpFile.flush(); + dumpFile.close(); + + delete[] buffer; + + debugPrintf("Resource %s has been dumped to disk.\n", argv[1]); + + return true; +} + +bool Debugger::cmdLocations(int argc, const char **argv) { + _showAllLocations = LOC_REFRESH; + + debugPrintf("Now showing all map locations\n"); + return false; +} + + +} // End of namespace Sherlock diff --git a/pool/shard001/C++/0017617_VMapFactory.cpp b/pool/shard001/C++/0017617_VMapFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8f18b58b52d44f62338032962c64a5388cac0ba --- /dev/null +++ b/pool/shard001/C++/0017617_VMapFactory.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2005-2010 MaNGOS + * Copyright (C) 2008-2014 Hellground + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include "VMapFactory.h" +#include "VMapManager2.h" + +using namespace G3D; + +namespace VMAP +{ + void chompAndTrim(std::string& str) + { + while(str.length() >0) + { + char lc = str[str.length()-1]; + if(lc == '\r' || lc == '\n' || lc == ' ' || lc == '"' || lc == '\'') + { + str = str.substr(0,str.length()-1); + } + else + { + break; + } + } + while(str.length() >0) + { + char lc = str[0]; + if(lc == ' ' || lc == '"' || lc == '\'') + { + str = str.substr(1,str.length()-1); + } + else + { + break; + } + } + } + + IVMapManager *gVMapManager = 0; + Table* iIgnoreSpellIds=0; + + //=============================================== + // result false, if no more id are found + + bool getNextId(const std::string& pString, unsigned int& pStartPos, unsigned int& pId) + { + bool result = false; + unsigned int i; + for(i=pStartPos;ipStartPos) + { + std::string idString = pString.substr(pStartPos, i-pStartPos); + pStartPos = i+1; + chompAndTrim(idString); + pId = atoi(idString.c_str()); + result = true; + } + return(result); + } + + //=============================================== + /** + parameter: String of map ids. Delimiter = "," + */ + + void VMapFactory::preventSpellsFromBeingTestedForLoS(const char* pSpellIdString) + { + if(!iIgnoreSpellIds) + iIgnoreSpellIds = new Table(); + if(pSpellIdString != NULL) + { + unsigned int pos =0; + unsigned int id; + std::string confString(pSpellIdString); + chompAndTrim(confString); + while(getNextId(confString, pos, id)) + { + iIgnoreSpellIds->set(id, true); + } + } + } + + //=============================================== + + bool VMapFactory::checkSpellForLoS(unsigned int pSpellId) + { + return(!iIgnoreSpellIds->containsKey(pSpellId)); + } + + //=============================================== + // just return the instance + IVMapManager* VMapFactory::createOrGetVMapManager() + { + if(gVMapManager == 0) + gVMapManager= new VMapManager2(); // should be taken from config ... Please change if you like :-) + return gVMapManager; + } + + //=============================================== + // delete all internal data structures + void VMapFactory::clear() + { + delete iIgnoreSpellIds; + iIgnoreSpellIds = NULL; + + delete gVMapManager; + gVMapManager = NULL; + } +} diff --git a/pool/shard001/C++/0017624_two-sum.cpp b/pool/shard001/C++/0017624_two-sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da037ec223823b87ecd83c8643cdc91cfe9338f3 --- /dev/null +++ b/pool/shard001/C++/0017624_two-sum.cpp @@ -0,0 +1,48 @@ +class Solution { + public: + vector twoSum(vector &numbers, int target) { + std::vector index; + std::map::size_type> >index_map; + std::map::size_type> >::iterator iter; + + for(std::vector::size_type i = 0; i != numbers.size(); ++i){ + iter = index_map.find(numbers[i]); + if(iter == index_map.end()){ + std::vector::size_type> tmp; + tmp.push_back(i); + index_map[numbers[i]] = tmp; + } + else{ + iter->second.push_back(i); + } + } + + std::sort(numbers.begin(), numbers.end()); + std::vector::size_type i = 0, j = numbers.size() - 1; + while(i != j){ + if(numbers[i] + numbers[j] > target) --j; + else if(numbers[i] + numbers[j] < target) ++i; + else{ + std::vector::size_type index1 = 0, index2 = 0; + if(numbers[i] == numbers[j]){ + index1 = index_map.find(numbers[i])->second[0] + 1; + index2 = index_map.find(numbers[i])->second[1] + 1; + } + else + { + index1 = index_map.find(numbers[i])->second[0] + 1; + index2 = index_map.find(numbers[j])->second[0] + 1; + if(index1 > index2){ + std::vector::size_type tmp = index1; + index1 = index2; + index2 = tmp; + } + } + index.push_back(index1); + index.push_back(index2); + break; + } + } + return index; + } +}; diff --git a/pool/shard001/C++/0017630_24803.cc b/pool/shard001/C++/0017630_24803.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a327ea5b377fc420e956326ab0617e434ee6449 --- /dev/null +++ b/pool/shard001/C++/0017630_24803.cc @@ -0,0 +1,80 @@ +// { dg-options "-std=gnu++11" } +// { dg-do compile } + +// Copyright (C) 2008-2014 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 +// . + + +#include + +struct test_type +{ + int member(); + int cmember()const; + int member2(char); + int cmember2(char)const; +}; + +struct functor1 : public std::unary_function +{ + double operator()(int) const; +}; + +struct functor2 : public std::binary_function +{ + double operator()(int, char) const; +}; + +template +void verify_return_type(T, T) +{ +} + +void test01() +{ + test_type* null_tt = 0; + const test_type* null_ttc = 0; + int zero; + + std::reference_wrapper* pr1(0); + verify_return_type((*pr1)(0), double()); + std::reference_wrapper* pr2(0); + verify_return_type((*pr2)(0), double()); + std::reference_wrapper* pr3(0); + verify_return_type((*pr3)(null_tt), int()); + std::reference_wrapper* pr4(0); + verify_return_type((*pr4)(null_ttc), int()); + std::reference_wrapper* pr5(0); + + // libstdc++/24803 + verify_return_type((*pr5)(0), double()); + verify_return_type((*pr5)(zero), double()); + + std::reference_wrapper* pr1b(0); + verify_return_type((*pr1b)(0, 0), double()); + std::reference_wrapper* pr2b(0); + verify_return_type((*pr2b)(0, 0), double()); + std::reference_wrapper* pr3b(0); + verify_return_type((*pr3b)(null_tt,zero), int()); + std::reference_wrapper* pr4b(0); + verify_return_type((*pr4b)(null_ttc), int()); + std::reference_wrapper* pr5b(0); + + // libstdc++/24803 + verify_return_type((*pr5b)(0, 0), double()); + verify_return_type((*pr5b)(zero, zero), double()); +} diff --git a/pool/shard001/C++/0017636_jsound.cpp b/pool/shard001/C++/0017636_jsound.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1329f4081f1adba1a44a9856ed667e5f38185e96 --- /dev/null +++ b/pool/shard001/C++/0017636_jsound.cpp @@ -0,0 +1,104 @@ +/* + * Copyright 2006-2012 The FLWOR Foundation. + * + * 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. + */ + +// ****************************************** +// * * +// * THIS IS A GENERATED FILE. DO NOT EDIT! * +// * SEE .xml FILE WITH SAME NAME * +// * * +// ****************************************** + + +#include "stdafx.h" +#include "zorbatypes/rchandle.h" +#include "zorbatypes/zstring.h" +#include "runtime/visitors/planiter_visitor.h" +#include "runtime/jsound/jsound.h" +#include "system/globalenv.h" + + +#include "store/api/iterator.h" + +namespace zorba { + +// +SERIALIZABLE_CLASS_VERSIONS(JSoundAnnotateIterator) + +void JSoundAnnotateIterator::serialize(::zorba::serialization::Archiver& ar) +{ + serialize_baseclass(ar, + (NaryBaseIterator*)this); +} + + +void JSoundAnnotateIterator::accept(PlanIterVisitor& v) const +{ + v.beginVisit(*this); + + std::vector::const_iterator lIter = theChildren.begin(); + std::vector::const_iterator lEnd = theChildren.end(); + for ( ; lIter != lEnd; ++lIter ){ + (*lIter)->accept(v); + } + + v.endVisit(*this); +} + +JSoundAnnotateIterator::~JSoundAnnotateIterator() {} + + +zstring JSoundAnnotateIterator::getNameAsString() const { + return "fn-zorba-jsound:annotate"; +} +// + + +// +SERIALIZABLE_CLASS_VERSIONS(JSoundValidateIterator) + +void JSoundValidateIterator::serialize(::zorba::serialization::Archiver& ar) +{ + serialize_baseclass(ar, + (NaryBaseIterator*)this); +} + + +void JSoundValidateIterator::accept(PlanIterVisitor& v) const +{ + v.beginVisit(*this); + + std::vector::const_iterator lIter = theChildren.begin(); + std::vector::const_iterator lEnd = theChildren.end(); + for ( ; lIter != lEnd; ++lIter ){ + (*lIter)->accept(v); + } + + v.endVisit(*this); +} + +JSoundValidateIterator::~JSoundValidateIterator() {} + + +zstring JSoundValidateIterator::getNameAsString() const { + return "fn-zorba-jsound:validate"; +} +// + + + +} + + diff --git a/pool/shard001/C++/0017640_windowmanager.cpp b/pool/shard001/C++/0017640_windowmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86a2da73e6b712c0c98244d87ba69a0992ea0147 --- /dev/null +++ b/pool/shard001/C++/0017640_windowmanager.cpp @@ -0,0 +1,172 @@ +/* Copyright (C) 2012 John Brooks + * + * You may use this file under the terms of the BSD license as follows: + * + * 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 Nemo Mobile 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 "windowmanager.h" +#include "dbusadaptor.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static WindowManager *wmInstance = 0; + +WindowManager *WindowManager::instance() +{ + if (!wmInstance) + wmInstance = new WindowManager(qApp); + return wmInstance; +} + +WindowManager::WindowManager(QObject *parent) + : QObject(parent), mEngine(0) +{ + createScene(); + + new DBusAdaptor(this); + QDBusConnection::sessionBus().registerService("org.nemomobile.qmlmessages"); + if (!QDBusConnection::sessionBus().registerObject("/", this)) { + qWarning() << "Cannot register DBus object!"; + } +} + +WindowManager::~WindowManager() +{ + delete mWindow; + delete mEngine; + delete mScene; +} + +void WindowManager::createScene() +{ + if (mEngine) + return; + + mEngine = new QDeclarativeEngine; + mEngine->rootContext()->setContextProperty("windowManager", + QVariant::fromValue(this)); + + mScene = new QGraphicsScene; + // From QDeclarativeView + mScene->setItemIndexMethod(QGraphicsScene::NoIndex); + mScene->setStickyFocus(true); + + QDeclarativeComponent component(mEngine, QUrl("qrc:qml/main.qml")); + if (!component.isReady()) { + qWarning() << component.errors(); + } + mRootObject = static_cast(component.create()); + mScene->addItem(mRootObject); +} + +void WindowManager::ensureWindow() +{ + if (mWindow) + return; + + createScene(); + + //QWeakPointer mWindow; + mWindow = new QGraphicsView; + + QGraphicsView *w = mWindow; + + // mWindow is a QWeakPointer, so it'll be cleared on delete + w->setAttribute(Qt::WA_DeleteOnClose); + w->setWindowTitle(tr("Messages")); + w->setAttribute(Qt::WA_OpaquePaintEvent); + w->setAttribute(Qt::WA_NoSystemBackground); + w->viewport()->setAttribute(Qt::WA_OpaquePaintEvent); + w->viewport()->setAttribute(Qt::WA_NoSystemBackground); + // From QDeclarativeView + w->setFrameStyle(0); + w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + w->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + w->setOptimizationFlags(QGraphicsView::DontSavePainterState); + w->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + w->viewport()->setFocusPolicy(Qt::NoFocus); + w->setFocusPolicy(Qt::StrongFocus); + + w->setScene(mScene); + + QDeclarativeItem *i = qobject_cast(mRootObject); + w->resize(i->width(), i->height()); + w->setSceneRect(QRectF(0, 0, i->width(), i->height())); +} + +void WindowManager::showGroupsWindow() +{ + ensureWindow(); + + Q_ASSERT(mRootObject); + bool ok = mRootObject->metaObject()->invokeMethod(mRootObject, "showGroupsList"); + if (!ok) + qWarning() << Q_FUNC_INFO << "showGroupsList call failed"; + + mWindow->showFullScreen(); + mWindow->activateWindow(); + mWindow->raise(); +} + +void WindowManager::showConversation(const QString &localUid, const QString &remoteUid, unsigned type) +{ + Q_UNUSED(type); + ensureWindow(); + + Q_ASSERT(mRootObject); + bool ok = mRootObject->metaObject()->invokeMethod(mRootObject, "showConversation", + Q_ARG(QVariant, localUid), Q_ARG(QVariant, remoteUid)); + if (!ok) + qWarning() << Q_FUNC_INFO << "showConversation call failed"; + + mWindow->showFullScreen(); + mWindow->activateWindow(); + mWindow->raise(); +} + +void WindowManager::emitToForeground() { + emit toForeground(); +} + + +void WindowManager::notifyHistoryPageAccess() { + QDBusConnection connection = QDBusConnection::sessionBus(); + if (connection.isConnected()) { + //Send notification to desktop's notification manager + QDBusInterface* indicatorIface = new QDBusInterface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", "org.freedesktop.Notifications", connection); + indicatorIface->call(QDBus::NoBlock, "clearCalls"); + } +} + + diff --git a/pool/shard001/C++/0017646_test.cpp b/pool/shard001/C++/0017646_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..356d1633e637001cc5c455d169c17670a4ae181d --- /dev/null +++ b/pool/shard001/C++/0017646_test.cpp @@ -0,0 +1,62 @@ +#include +#include +#include + +using namespace std; + +int main() +{ + int fd = open("a.c", O_RDWR | O_APPEND); + if(-1 == fd) + { + cout << "open error" << endl; + return 0; + } + + char buf = 'm'; + if(write(fd, &buf, 1) == -1) + { + cout << "write error" << endl; + close(fd); + return 0; + } + + off_t CurrentPosition = lseek(fd, 0, SEEK_CUR); + if(CurrentPosition == -1) + { + cout << "lseek error" << endl; + close(fd); + return 0; + } + + cout << "CurrentPosition: " << CurrentPosition << endl; + + if(lseek(fd, 0, SEEK_SET) == -1) + { + cout << "lseek error" << endl; + close(fd); + return 0; + } + + off_t NewCurrentPosition = lseek(fd, 0, SEEK_CUR); + if(NewCurrentPosition == -1) + { + cout << "lseek error" << endl; + close(fd); + return 0; + } + + cout << "NewCurrentPosition: " << NewCurrentPosition << endl; + + char buf1 = 'P'; + if(write(fd, &buf1, 1) == -1) + { + cout << "write error" << endl; + close(fd); + return 0; + } + + close(fd); + + return 0; +} diff --git a/pool/shard001/C++/0017647_key_manager.cpp b/pool/shard001/C++/0017647_key_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2530fc946da23a0dbfc9130cbb2644beb7a9f46c --- /dev/null +++ b/pool/shard001/C++/0017647_key_manager.cpp @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2016, The OpenThread Authors. + * 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. + * 3. Neither the name of the copyright holder 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 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 + * This file implements Thread security material generation. + */ + +#include "key_manager.hpp" + +#include "common/code_utils.hpp" +#include "common/instance.hpp" +#include "common/owner-locator.hpp" +#include "common/timer.hpp" +#include "crypto/hmac_sha256.hpp" +#include "thread/mle_router.hpp" +#include "thread/thread_netif.hpp" + +namespace ot { + +static const uint8_t kThreadString[] = { + 'T', 'h', 'r', 'e', 'a', 'd', +}; + +static const otMasterKey kDefaultMasterKey = {{ + 0x00, + 0x11, + 0x22, + 0x33, + 0x44, + 0x55, + 0x66, + 0x77, + 0x88, + 0x99, + 0xaa, + 0xbb, + 0xcc, + 0xdd, + 0xee, + 0xff, +}}; + +KeyManager::KeyManager(Instance &aInstance) + : InstanceLocator(aInstance) + , mMasterKey(kDefaultMasterKey) + , mKeySequence(0) + , mMacFrameCounter(0) + , mMleFrameCounter(0) + , mStoredMacFrameCounter(0) + , mStoredMleFrameCounter(0) + , mHoursSinceKeyRotation(0) + , mKeyRotationTime(kDefaultKeyRotationTime) + , mKeySwitchGuardTime(kDefaultKeySwitchGuardTime) + , mKeySwitchGuardEnabled(false) + , mKeyRotationTimer(aInstance, &KeyManager::HandleKeyRotationTimer, this) + , mKekFrameCounter(0) + , mSecurityPolicyFlags(0xff) +{ + ComputeKey(mKeySequence, mKey); +} + +void KeyManager::Start(void) +{ + mKeySwitchGuardEnabled = false; + StartKeyRotationTimer(); +} + +void KeyManager::Stop(void) +{ + mKeyRotationTimer.Stop(); +} + +#if OPENTHREAD_MTD || OPENTHREAD_FTD +const uint8_t *KeyManager::GetPSKc(void) const +{ + return mPSKc; +} + +void KeyManager::SetPSKc(const uint8_t *aPSKc) +{ + VerifyOrExit(memcmp(mPSKc, aPSKc, sizeof(mPSKc)) != 0, GetNotifier().SignalIfFirst(OT_CHANGED_PSKC)); + memcpy(mPSKc, aPSKc, sizeof(mPSKc)); + GetNotifier().Signal(OT_CHANGED_PSKC); + +exit: + return; +} +#endif // OPENTHREAD_MTD || OPENTHREAD_FTD + +const otMasterKey &KeyManager::GetMasterKey(void) const +{ + return mMasterKey; +} + +otError KeyManager::SetMasterKey(const otMasterKey &aKey) +{ + Mle::MleRouter &mle = GetNetif().GetMle(); + otError error = OT_ERROR_NONE; + Router * routers; + + VerifyOrExit(memcmp(&mMasterKey, &aKey, sizeof(mMasterKey)) != 0, + GetNotifier().SignalIfFirst(OT_CHANGED_MASTER_KEY)); + + mMasterKey = aKey; + mKeySequence = 0; + ComputeKey(mKeySequence, mKey); + + // reset parent frame counters + routers = mle.GetParent(); + routers->SetKeySequence(0); + routers->SetLinkFrameCounter(0); + routers->SetMleFrameCounter(0); + + // reset router frame counters + for (RouterTable::Iterator iter(GetInstance()); !iter.IsDone(); iter++) + { + iter.GetRouter()->SetKeySequence(0); + iter.GetRouter()->SetLinkFrameCounter(0); + iter.GetRouter()->SetMleFrameCounter(0); + } + + // reset child frame counters + for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateAnyExceptInvalid); !iter.IsDone(); iter++) + { + iter.GetChild()->SetKeySequence(0); + iter.GetChild()->SetLinkFrameCounter(0); + iter.GetChild()->SetMleFrameCounter(0); + } + + GetNotifier().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER | OT_CHANGED_MASTER_KEY); + +exit: + return error; +} + +otError KeyManager::ComputeKey(uint32_t aKeySequence, uint8_t *aKey) +{ + Crypto::HmacSha256 hmac; + uint8_t keySequenceBytes[4]; + + hmac.Start(mMasterKey.m8, sizeof(mMasterKey.m8)); + + keySequenceBytes[0] = (aKeySequence >> 24) & 0xff; + keySequenceBytes[1] = (aKeySequence >> 16) & 0xff; + keySequenceBytes[2] = (aKeySequence >> 8) & 0xff; + keySequenceBytes[3] = aKeySequence & 0xff; + hmac.Update(keySequenceBytes, sizeof(keySequenceBytes)); + hmac.Update(kThreadString, sizeof(kThreadString)); + + hmac.Finish(aKey); + + return OT_ERROR_NONE; +} + +void KeyManager::SetCurrentKeySequence(uint32_t aKeySequence) +{ + VerifyOrExit(aKeySequence != mKeySequence, GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER)); + + // Check if the guard timer has expired if key rotation is requested. + if ((aKeySequence == (mKeySequence + 1)) && (mKeySwitchGuardTime != 0) && mKeyRotationTimer.IsRunning() && + mKeySwitchGuardEnabled) + { + VerifyOrExit(mHoursSinceKeyRotation >= mKeySwitchGuardTime); + } + + mKeySequence = aKeySequence; + ComputeKey(mKeySequence, mKey); + + mMacFrameCounter = 0; + mMleFrameCounter = 0; + + if (mKeyRotationTimer.IsRunning()) + { + mKeySwitchGuardEnabled = true; + StartKeyRotationTimer(); + } + + GetNotifier().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); + +exit: + return; +} + +const uint8_t *KeyManager::GetTemporaryMacKey(uint32_t aKeySequence) +{ + ComputeKey(aKeySequence, mTemporaryKey); + return mTemporaryKey + kMacKeyOffset; +} + +const uint8_t *KeyManager::GetTemporaryMleKey(uint32_t aKeySequence) +{ + ComputeKey(aKeySequence, mTemporaryKey); + return mTemporaryKey; +} + +void KeyManager::IncrementMacFrameCounter(void) +{ + mMacFrameCounter++; + + if (mMacFrameCounter >= mStoredMacFrameCounter) + { + GetNetif().GetMle().Store(); + } +} + +void KeyManager::IncrementMleFrameCounter(void) +{ + mMleFrameCounter++; + + if (mMleFrameCounter >= mStoredMleFrameCounter) + { + GetNetif().GetMle().Store(); + } +} + +void KeyManager::SetKek(const uint8_t *aKek) +{ + memcpy(mKek, aKek, sizeof(mKek)); + mKekFrameCounter = 0; +} + +otError KeyManager::SetKeyRotation(uint32_t aKeyRotation) +{ + otError result = OT_ERROR_NONE; + + VerifyOrExit(aKeyRotation >= static_cast(kMinKeyRotationTime), result = OT_ERROR_INVALID_ARGS); + + mKeyRotationTime = aKeyRotation; + +exit: + return result; +} + +void KeyManager::SetSecurityPolicyFlags(uint8_t aSecurityPolicyFlags) +{ + Notifier ¬ifier = GetNotifier(); + + if (!notifier.HasSignaled(OT_CHANGED_SECURITY_POLICY) || (mSecurityPolicyFlags != aSecurityPolicyFlags)) + { + mSecurityPolicyFlags = aSecurityPolicyFlags; + notifier.Signal(OT_CHANGED_SECURITY_POLICY); + } +} + +void KeyManager::StartKeyRotationTimer(void) +{ + mHoursSinceKeyRotation = 0; + mKeyRotationTimer.Start(kOneHourIntervalInMsec); +} + +void KeyManager::HandleKeyRotationTimer(Timer &aTimer) +{ + aTimer.GetOwner().HandleKeyRotationTimer(); +} + +void KeyManager::HandleKeyRotationTimer(void) +{ + mHoursSinceKeyRotation++; + + // Order of operations below is important. We should restart the timer (from + // last fire time for one hour interval) before potentially calling + // `SetCurrentKeySequence()`. `SetCurrentKeySequence()` uses the fact that + // timer is running to decide to check for the guard time and to reset the + // rotation timer (and the `mHoursSinceKeyRotation`) if it updates the key + // sequence. + + mKeyRotationTimer.StartAt(mKeyRotationTimer.GetFireTime(), kOneHourIntervalInMsec); + + if (mHoursSinceKeyRotation >= mKeyRotationTime) + { + SetCurrentKeySequence(mKeySequence + 1); + } +} + +} // namespace ot diff --git a/pool/shard001/C++/0017648_nsGfxFactoryBeOS.cpp b/pool/shard001/C++/0017648_nsGfxFactoryBeOS.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6702890f576ec5be6602d07bb8b78235ce643bc --- /dev/null +++ b/pool/shard001/C++/0017648_nsGfxFactoryBeOS.cpp @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is mozilla.org code. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsIGenericFactory.h" +#include "nsIModule.h" +#include "nsCOMPtr.h" +#include "nsGfxCIID.h" + +#include "nsBlender.h" +#include "nsFontMetricsBeOS.h" +#include "nsRenderingContextBeOS.h" +#include "nsScriptableRegion.h" +#include "nsDeviceContextBeOS.h" +#include "nsImageBeOS.h" +#include "gfxImageFrame.h" + +// objects that just require generic constructors + +NS_GENERIC_FACTORY_CONSTRUCTOR(nsFontMetricsBeOS) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceContextBeOS) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsRenderingContextBeOS) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsImageBeOS) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsBlender) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsRegionBeOS) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsFontEnumeratorBeOS) + +NS_GENERIC_FACTORY_CONSTRUCTOR(gfxImageFrame) + +// our custom constructors + +static NS_IMETHODIMP nsScriptableRegionConstructor(nsISupports *aOuter, REFNSIID aIID, void **aResult) +{ + nsresult rv; + + nsIScriptableRegion *inst; + + if ( !aResult ) + { + rv = NS_ERROR_NULL_POINTER; + return rv; + } + *aResult = nsnull; + if (aOuter) + { + rv = NS_ERROR_NO_AGGREGATION; + return rv; + } + // create an nsRegionBeOS and get the scriptable region from it + nsCOMPtr rgn; + NS_NEWXPCOM(rgn, nsRegionBeOS); + nsCOMPtr scriptableRgn; + if (rgn != nsnull) + { + scriptableRgn = new nsScriptableRegion(rgn); + inst = scriptableRgn; + } + if (!inst) + { + rv = NS_ERROR_OUT_OF_MEMORY; + return rv; + } + NS_ADDREF(inst); + // release our variable above now that we have created our owning + // reference - we don't want this to go out of scope early! + scriptableRgn = nsnull; + rv = inst->QueryInterface(aIID, aResult); + NS_RELEASE(inst); + + return rv; +} + +static const nsModuleComponentInfo components[] = +{ + { "BeOS Font Metrics", + NS_FONT_METRICS_CID, + // "@mozilla.org/gfx/font_metrics/beos;1", + "@mozilla.org/gfx/fontmetrics;1", + nsFontMetricsBeOSConstructor }, + { "BeOS Device Context", + NS_DEVICE_CONTEXT_CID, + // "@mozilla.org/gfx/device_context/beos;1", + "@mozilla.org/gfx/devicecontext;1", + nsDeviceContextBeOSConstructor }, + { "BeOS Rendering Context", + NS_RENDERING_CONTEXT_CID, + // "@mozilla.org/gfx/rendering_context/beos;1", + "@mozilla.org/gfx/renderingcontext;1", + nsRenderingContextBeOSConstructor }, + { "BeOS Image", + NS_IMAGE_CID, + // "@mozilla.org/gfx/image/beos;1", + "@mozilla.org/gfx/image;1", + nsImageBeOSConstructor }, + { "BeOS Region", + NS_REGION_CID, + "@mozilla.org/gfx/region/beos;1", + nsRegionBeOSConstructor }, + { "Scriptable Region", + NS_SCRIPTABLE_REGION_CID, + // "@mozilla.org/gfx/scriptable_region;1", + "@mozilla.org/gfx/region;1", + nsScriptableRegionConstructor }, + { "Blender", + NS_BLENDER_CID, + // "@mozilla.org/gfx/blender;1", + "@mozilla.org/gfx/blender;1", + nsBlenderConstructor }, + { "BeOS Font Enumerator", + NS_FONT_ENUMERATOR_CID, + // "@mozilla.org/gfx/font_enumerator/beos;1", + "@mozilla.org/gfx/fontenumerator;1", + nsFontEnumeratorBeOSConstructor }, + { "windows image frame", + GFX_IMAGEFRAME_CID, + "@mozilla.org/gfx/image/frame;2", + gfxImageFrameConstructor, }, +}; + +NS_IMPL_NSGETMODULE(nsGfxBeOSModule, components) diff --git a/pool/shard001/C++/0017655_dcpsheetapplet.cpp b/pool/shard001/C++/0017655_dcpsheetapplet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..628aebe79d8186597a521c36b5e7734687063db9 --- /dev/null +++ b/pool/shard001/C++/0017655_dcpsheetapplet.cpp @@ -0,0 +1,56 @@ +/*************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Karoliina T. Salminen +** +** This file is part of duicontrolpanel. +** +** +** This program is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation +** and appearing in the file LICENSE.LGPL included in the packaging +** of this file. +** +****************************************************************************/ + +#include +#include "dcpsheetapplet.h" + +#include +#include +#include +#include +#include + +M_LIBRARY +Q_EXPORT_PLUGIN2(sheetapplet, SheetApplet) + +MSheet* SheetApplet::constructSheet (int widgetId) +{ + Q_UNUSED (widgetId); + + MSheet* sheet = new MSheet(); + MBasicSheetHeader* header = new MBasicSheetHeader(); + header->setPositiveAction (new MAction("Ok", header)); + header->setNegativeAction (new MAction("Cancel", header)); + connect(header->positiveAction(), SIGNAL(triggered()), sheet, SLOT(dismiss())); + connect(header->negativeAction(), SIGNAL(triggered()), sheet, SLOT(dismiss())); + sheet->setHeaderWidget (header); + sheet->setCentralWidget ( + new MLabel ("This is a sheet, please accept or refuse. Do you accept?")); + + return sheet; +} + +QString SheetApplet::title() const +{ + return QString(); +} + +QVector SheetApplet::viewMenuItems() +{ + return QVector(); +} + diff --git a/pool/shard001/C++/0017657_ClientCertificateRevocationListStatus.cpp b/pool/shard001/C++/0017657_ClientCertificateRevocationListStatus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aafd2b2e0ae1264ac18ddbceac59dc6c0c35b566 --- /dev/null +++ b/pool/shard001/C++/0017657_ClientCertificateRevocationListStatus.cpp @@ -0,0 +1,89 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +#include + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace EC2 +{ +namespace Model +{ + +ClientCertificateRevocationListStatus::ClientCertificateRevocationListStatus() : + m_code(ClientCertificateRevocationListStatusCode::NOT_SET), + m_codeHasBeenSet(false), + m_messageHasBeenSet(false) +{ +} + +ClientCertificateRevocationListStatus::ClientCertificateRevocationListStatus(const XmlNode& xmlNode) : + m_code(ClientCertificateRevocationListStatusCode::NOT_SET), + m_codeHasBeenSet(false), + m_messageHasBeenSet(false) +{ + *this = xmlNode; +} + +ClientCertificateRevocationListStatus& ClientCertificateRevocationListStatus::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode codeNode = resultNode.FirstChild("code"); + if(!codeNode.IsNull()) + { + m_code = ClientCertificateRevocationListStatusCodeMapper::GetClientCertificateRevocationListStatusCodeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(codeNode.GetText()).c_str()).c_str()); + m_codeHasBeenSet = true; + } + XmlNode messageNode = resultNode.FirstChild("message"); + if(!messageNode.IsNull()) + { + m_message = Aws::Utils::Xml::DecodeEscapedXmlText(messageNode.GetText()); + m_messageHasBeenSet = true; + } + } + + return *this; +} + +void ClientCertificateRevocationListStatus::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_codeHasBeenSet) + { + oStream << location << index << locationValue << ".Code=" << ClientCertificateRevocationListStatusCodeMapper::GetNameForClientCertificateRevocationListStatusCode(m_code) << "&"; + } + + if(m_messageHasBeenSet) + { + oStream << location << index << locationValue << ".Message=" << StringUtils::URLEncode(m_message.c_str()) << "&"; + } + +} + +void ClientCertificateRevocationListStatus::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_codeHasBeenSet) + { + oStream << location << ".Code=" << ClientCertificateRevocationListStatusCodeMapper::GetNameForClientCertificateRevocationListStatusCode(m_code) << "&"; + } + if(m_messageHasBeenSet) + { + oStream << location << ".Message=" << StringUtils::URLEncode(m_message.c_str()) << "&"; + } +} + +} // namespace Model +} // namespace EC2 +} // namespace Aws diff --git a/pool/shard001/C++/0017661_atsci_root_raised_cosine_bandpass.cc b/pool/shard001/C++/0017661_atsci_root_raised_cosine_bandpass.cc new file mode 100644 index 0000000000000000000000000000000000000000..84f9f22cab2598e6a7dccf5fe7d24d05ab9e9984 --- /dev/null +++ b/pool/shard001/C++/0017661_atsci_root_raised_cosine_bandpass.cc @@ -0,0 +1,51 @@ +/* -*- c++ -*- */ +/* + * Copyright 2002 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * GNU Radio 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. + * + * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#include +#include +#include + +using std::vector; +using std::cerr; +using std::endl; + + +vector +atsc_root_raised_cosine_bandpass::taps (double sampling_freq) +{ + + vector t = atsc_root_raised_cosine::taps (sampling_freq); + + cerr << "atsc_root_raised_cosine_bandpass::taps -- " << t.size () << endl; + + // heterodyne the low pass coefficients up to the specified bandpass + // center frequency. Note that when we do this, the filter bandwidth + // is effectively twice the low pass (2.69 * 2 = 5.38) and hence + // matches the diagram in the ATSC spec. + + double arg = 2 * M_PI * _center_freq / sampling_freq; + for (unsigned int i = 0; i < t.size (); i++) + // the factor of 2 keeps the gain of the passband normalized to 1 + t[i] *= 2 * cos (arg * (double) i); + + return t; +} diff --git a/pool/shard001/C++/0017668_GfxHelper.cpp b/pool/shard001/C++/0017668_GfxHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f52f7e64c00b7154427ba41ed9e2f3dbef7a046 --- /dev/null +++ b/pool/shard001/C++/0017668_GfxHelper.cpp @@ -0,0 +1,38 @@ +#include "GfxHelper.h" +#include "GfxBase.h" + +int Screenshot(SDL_Surface *screen, const char *filename) +{ + SDL_Surface *temp; + unsigned char *pixels; + int i; + + temp = SDL_CreateRGBSurface(SDL_SWSURFACE, + screen->w, screen->h, 24, +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + 0x000000FF, 0x0000FF00, 0x00FF0000, 0 +#else + 0x00FF0000, 0x0000FF00, 0x000000FF, 0 +#endif + ); + if (temp == NULL) return -1; + + pixels = (unsigned char*)malloc(3 * screen->w * screen->h); + if (pixels == NULL) { + SDL_FreeSurface(temp); + return -1; + } + + glReadPixels(0, 0, screen->w, screen->h, + GL_RGB, GL_UNSIGNED_BYTE, pixels); + + for (i=0; ih; i++) + memcpy(((char *) temp->pixels) + temp->pitch * i, + pixels + 3*screen->w * (screen->h-i-1), + screen->w*3); + free(pixels); + + SDL_SaveBMP(temp, filename); + SDL_FreeSurface(temp); + return 0; +} diff --git a/pool/shard001/C++/0017675_mywcl.cpp b/pool/shard001/C++/0017675_mywcl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54e4b9988c6246891ae95d405e977a7fdd99f19b --- /dev/null +++ b/pool/shard001/C++/0017675_mywcl.cpp @@ -0,0 +1,45 @@ +// ////////////////////////////////////////////////////////// +// mywcl.cpp +// Copyright (c) 2013 Stephan Brumme. All rights reserved. +// + +// g++ MemoryMapped.cpp mywcl.cpp -o mywcl -O3 -fopenmp + +#include "MemoryMapped.h" +#include + +int main(int argc, char* argv[]) +{ + // syntax check + if (argc > 2) + { + printf("Syntax: ./mywcl filename\n"); + return -1; + } + + // map file to memory + MemoryMapped data(argv[1], MemoryMapped::WholeFile, MemoryMapped::SequentialScan); + if (!data.isValid()) + { + printf("File not found\n"); + return -2; + } + + // raw pointer to mapped memory + char* buffer = (char*)data.getData(); + // store result here + uint64_t numLines = 0; + + // OpenMP spreads work across CPU cores +#pragma omp parallel for reduction(+:numLines) + for (uint64_t i = 0; i < data.size(); i++) + numLines += (buffer[i] == '\n'); + + // show result +#ifdef _MSC_VER + printf("%I64d\n", numLines); +#else + printf("%lld\n", numLines); +#endif + return 0; +} diff --git a/pool/shard001/C++/0017691_test_bitcoin.cpp b/pool/shard001/C++/0017691_test_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2e2a2868a826960c416b7bd16d8c6ab8b039fe4 --- /dev/null +++ b/pool/shard001/C++/0017691_test_bitcoin.cpp @@ -0,0 +1,160 @@ +// Copyright (c) 2011-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#define BOOST_TEST_MODULE bridgecoin Test Suite + +#include "test_bitcoin.h" + +#include "chainparams.h" +#include "consensus/consensus.h" +#include "consensus/validation.h" +#include "key.h" +#include "main.h" +#include "miner.h" +#include "pubkey.h" +#include "random.h" +#include "txdb.h" +#include "txmempool.h" +#include "ui_interface.h" +#include "rpc/server.h" +#include "rpc/register.h" + +#include "test/testutil.h" + +#include +#include +#include + +extern bool fPrintToConsole; +extern void noui_connect(); + +BasicTestingSetup::BasicTestingSetup(const std::string& chainName) +{ + ECC_Start(); + SetupEnvironment(); + SetupNetworking(); + fPrintToDebugLog = false; // don't want to write to debug.log file + fCheckBlockIndex = true; + SelectParams(chainName); + noui_connect(); +} + +BasicTestingSetup::~BasicTestingSetup() +{ + ECC_Stop(); +} + +TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName) +{ + const CChainParams& chainparams = Params(); + // Ideally we'd move all the RPC tests to the functional testing framework + // instead of unit tests, but for now we need these here. + RegisterAllCoreRPCCommands(tableRPC); + ClearDatadirCache(); + pathTemp = GetTempPath() / strprintf("test_bridgecoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); + boost::filesystem::create_directories(pathTemp); + mapArgs["-datadir"] = pathTemp.string(); + mempool.setSanityCheck(1.0); + pblocktree = new CBlockTreeDB(1 << 20, true); + pcoinsdbview = new CCoinsViewDB(1 << 23, true); + pcoinsTip = new CCoinsViewCache(pcoinsdbview); + InitBlockIndex(chainparams); + { + CValidationState state; + bool ok = ActivateBestChain(state, chainparams); + BOOST_CHECK(ok); + } + nScriptCheckThreads = 3; + for (int i=0; i < nScriptCheckThreads-1; i++) + threadGroup.create_thread(&ThreadScriptCheck); + RegisterNodeSignals(GetNodeSignals()); +} + +TestingSetup::~TestingSetup() +{ + UnregisterNodeSignals(GetNodeSignals()); + threadGroup.interrupt_all(); + threadGroup.join_all(); + UnloadBlockIndex(); + delete pcoinsTip; + delete pcoinsdbview; + delete pblocktree; + boost::filesystem::remove_all(pathTemp); +} + +TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST) +{ + // Generate a 100-block chain: + coinbaseKey.MakeNewKey(true); + CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; + for (int i = 0; i < COINBASE_MATURITY; i++) + { + std::vector noTxns; + CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey); + coinbaseTxns.push_back(b.vtx[0]); + } +} + +// +// Create a new block with just given transactions, coinbase paying to +// scriptPubKey, and try to add it to the current chain. +// +CBlock +TestChain100Setup::CreateAndProcessBlock(const std::vector& txns, const CScript& scriptPubKey) +{ + const CChainParams& chainparams = Params(); + CBlockTemplate *pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey); + CBlock& block = pblocktemplate->block; + + // Replace mempool-selected txns with just coinbase plus passed-in txns: + block.vtx.resize(1); + BOOST_FOREACH(const CMutableTransaction& tx, txns) + block.vtx.push_back(tx); + // IncrementExtraNonce creates a valid coinbase and merkleRoot + unsigned int extraNonce = 0; + IncrementExtraNonce(&block, chainActive.Tip(), extraNonce); + + while (!CheckProofOfWork(block.GetPoWHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; + + CValidationState state; + ProcessNewBlock(state, chainparams, NULL, &block, true, NULL, false); + + CBlock result = block; + delete pblocktemplate; + return result; +} + +TestChain100Setup::~TestChain100Setup() +{ +} + + +CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(CMutableTransaction &tx, CTxMemPool *pool) { + CTransaction txn(tx); + return FromTx(txn, pool); +} + +CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(CTransaction &txn, CTxMemPool *pool) { + bool hasNoDependencies = pool ? pool->HasNoInputsOf(txn) : hadNoDependencies; + // Hack to assume either its completely dependent on other mempool txs or not at all + CAmount inChainValue = hasNoDependencies ? txn.GetValueOut() : 0; + + return CTxMemPoolEntry(txn, nFee, nTime, dPriority, nHeight, + hasNoDependencies, inChainValue, spendsCoinbase, sigOpCost, lp); +} + +void Shutdown(void* parg) +{ + exit(0); +} + +void StartShutdown() +{ + exit(0); +} + +bool ShutdownRequested() +{ + return false; +} diff --git a/pool/shard001/C++/0017692_c_system_fxaa.cpp b/pool/shard001/C++/0017692_c_system_fxaa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a99b40e0bd8e47c9a813f08ab227d739e9b30303 --- /dev/null +++ b/pool/shard001/C++/0017692_c_system_fxaa.cpp @@ -0,0 +1,286 @@ +/* + Yelo: Open Sauce SDK + Halo 1 (CE) Edition + + See license\OpenSauce\Halo1_CE for specific license information +*/ +#include "Common/Precompile.hpp" +#include "Rasterizer/PostProcessing/FXAA/c_system_fxaa.hpp" + +#if !PLATFORM_IS_DEDI +#include "Rasterizer/PostProcessing/c_post_processing_main.hpp" + +#include "Rasterizer/PostProcessing/FXAA/c_settings_fxaa.hpp" +#include "Rasterizer/PostProcessing/FXAA/c_shader_fxaa.hpp" +#include "Rasterizer/PostProcessing/c_shader_instance.hpp" +#include "Rasterizer/PostProcessing/c_effect_postprocess.hpp" +#include "Rasterizer/PostProcessing/c_effect_instance.hpp" + +namespace Yelo +{ + namespace Rasterizer { namespace PostProcessing { namespace FXAA + { + ///////////////////////////////////////////////// + // static members + c_system_fxaa c_system_fxaa::g_fxaa_system; + +#include "Rasterizer/PostProcessing/FXAA/FXAADefinitions.inl" + + static c_shader_fxaa g_shader_fxaa; + static c_shader_instance g_shader_instance_fxaa; + static c_effect_postprocess g_effect_fxaa; + static c_effect_instance g_effect_instance_fxaa; + + ///////////////////////////////////////////////// + // static member accessors + c_system_fxaa& c_system_fxaa::Instance() + { + return g_fxaa_system; + } + + ///////////////////////////////////////////////// + // member accessors + bool& c_system_fxaa::Enabled() + { + return m_members.m_flags.is_enabled; + } + + bool c_system_fxaa::IsReady() + { + return m_members.m_flags.is_ready; + } + + bool c_system_fxaa::IsUnloaded() + { + return m_members.m_flags.is_unloaded; + } + + ////////////////////////////////////////////////////////////////////// + // IPostProcessingComponent + void c_system_fxaa::Initialize() + { + c_settings_fxaa::Register(Settings::Manager()); + + m_members.status = Enums::pp_component_status_uninitialised; + + m_members.m_flags.is_ready = false; + m_members.m_flags.is_unloaded = false; + + g_shader_fxaa_definition.runtime.flags.valid_shader_bit = false; + g_shader_fxaa_definition.techniques.Count = NUMBEROF(g_shader_techniques); + g_shader_fxaa_definition.techniques.Address = &g_shader_techniques[0]; + + // initialise the effect definition + g_effect_fxaa_definition.quad_definition.tessellation.x = 4; + g_effect_fxaa_definition.quad_definition.tessellation.y = 4; + g_effect_fxaa_definition.quad_definition.x_bounds.lower = 0; + g_effect_fxaa_definition.quad_definition.x_bounds.upper = 1; + g_effect_fxaa_definition.quad_definition.y_bounds.lower = 0; + g_effect_fxaa_definition.quad_definition.y_bounds.upper = 1; + g_effect_fxaa_definition.runtime.flags.valid_effect_bit = false; + g_effect_fxaa_definition.runtime.flags.is_active_bit = true; + + // initialise the fxaa shader + g_shader_fxaa.Ctor(); + g_shader_fxaa.SetShaderDefinition(&g_shader_fxaa_definition); + g_shader_fxaa.SetupShader(); + + // initialise the shader instance + g_shader_instance_fxaa.Ctor(); + g_shader_instance_fxaa.SetShader(&g_shader_fxaa); + g_shader_instance_fxaa.SetupShaderInstance(); + + // initialise the effect + g_effect_fxaa.Ctor(); + g_effect_fxaa.SetEffectDefinition(&g_effect_fxaa_definition); + g_effect_fxaa.AddShaderInstance(&g_shader_instance_fxaa); + g_effect_fxaa.SetupEffect(); + + // initialise the effect instance + g_effect_instance_fxaa.Ctor(); + g_effect_instance_fxaa.SetEffect(&g_effect_fxaa); + g_effect_instance_fxaa.SetQuadDefinition(&g_effect_fxaa_definition.quad_definition); + g_effect_instance_fxaa.SetupEffectInstance(); + } + + void c_system_fxaa::Dispose() + { + m_members.status = Enums::pp_component_status_uninitialised; + + m_members.m_flags.is_ready = false; + m_members.m_flags.is_unloaded = false; + + g_effect_instance_fxaa.Dtor(); + g_effect_fxaa.Dtor(); + g_shader_instance_fxaa.Dtor(); + g_shader_fxaa.Dtor(); + + c_settings_fxaa::Unregister(Settings::Manager()); + } + + void c_system_fxaa::InitializeResources_Base(IDirect3DDevice9* device, D3DPRESENT_PARAMETERS* parameters) + { + HRESULT hr = E_FAIL; + // create the direct3d resources of the shader + do + { + if(FAILED(hr = CreateShader())) break; + if(FAILED(hr = CreateEffect())) break; + }while(false); + + Validate(); + + if(SUCCEEDED(hr)) { m_members.status = Enums::pp_component_status_initialised; } + else { m_members.status = Enums::pp_component_status_initialisation_failed; } + + UpdateStatus(); + } + + void c_system_fxaa::OnLostDevice_Base() + { + // call on device lost on the shaders effect + if(!m_members.m_flags.is_unloaded) + SetDeviceLost(); + Validate(); + + UpdateStatus(); + } + + void c_system_fxaa::OnResetDevice_Base(D3DPRESENT_PARAMETERS* parameters) + { + // call on device reset on the shaders effect + HRESULT hr = E_FAIL; + if(!m_members.m_flags.is_unloaded) + hr = SetDeviceReset(); + Validate(); + + if(SUCCEEDED(hr)) { m_members.status = Enums::pp_component_status_initialised; } + else { m_members.status = Enums::pp_component_status_initialisation_failed; } + + UpdateStatus(); + } + + void c_system_fxaa::ReleaseResources_Base() + { + // release the direct 3d resources + DestroyShader(); + DestroyEffect(); + Validate(); + + m_members.status = Enums::pp_component_status_uninitialised; + + UpdateStatus(); + } + + void c_system_fxaa::Unload() + { + // release the direct3d resources of the shader + DestroyShader(); + DestroyEffect(); + Validate(); + + m_members.status = Enums::pp_component_status_uninitialised; + m_members.m_flags.is_unloaded = true; + + UpdateStatus(); + } + + void c_system_fxaa::Load() + { + HRESULT hr = E_FAIL; + // create the direct3d resources of the shader + if(m_members.m_flags.is_unloaded) + { + do + { + if(FAILED(hr = CreateShader())) break; + if(FAILED(hr = CreateEffect())) break; + }while(false); + + Validate(); + + if(SUCCEEDED(hr)) { m_members.status = Enums::pp_component_status_initialised; } + else { m_members.status = Enums::pp_component_status_initialisation_failed; } + + m_members.m_flags.is_unloaded = false; + } + + UpdateStatus(); + } + + ///////////////////////////////////////////////// + // IPostProcessingRenderable + bool c_system_fxaa::Render(Enums::postprocess_render_stage render_stage) + { + if(!m_members.m_flags.is_enabled || (render_stage != Enums::_postprocess_render_stage_pre_hud)) + return false; + + return Render(c_post_processing_main::Instance().Globals().render_device); + } + + ///////////////////////////////////////////////// + // system setup + HRESULT c_system_fxaa::CreateShader() + { + return g_shader_fxaa.LoadShader(c_post_processing_main::Instance().Globals().render_device); + } + + void c_system_fxaa::DestroyShader() + { + // release the shader effect + g_shader_fxaa.UnloadShader(); + } + + HRESULT c_system_fxaa::CreateEffect() + { + g_effect_fxaa.SetupEffectPostCreation(); + return g_effect_instance_fxaa.LoadEffectInstance(); + } + + void c_system_fxaa::DestroyEffect() + { + // release the shader effect + g_effect_instance_fxaa.UnloadEffectInstance(); + } + + void c_system_fxaa::SetDeviceLost() + { + // call OnDeviceLost on the shader effect + g_shader_fxaa.OnDeviceLost(); + } + + HRESULT c_system_fxaa::SetDeviceReset() + { + // call OnDeviceReset on the shader effect + return g_shader_fxaa.OnDeviceReset(); + } + + void c_system_fxaa::Validate() + { + g_shader_fxaa.Validate(); + g_shader_instance_fxaa.Validate(); + g_effect_fxaa.Validate(); + g_effect_instance_fxaa.Validate(); + } + + void c_system_fxaa::UpdateStatus() + { + m_members.m_flags.is_ready = false; + do + { + if(m_members.status != Enums::pp_component_status_initialised) break; + if(!g_effect_instance_fxaa.IsValid()) break; + + m_members.m_flags.is_ready = true; + }while(false); + } + + ///////////////////////////////////////////////// + // system application + bool c_system_fxaa::Render(IDirect3DDevice9* render_device) + { + return SUCCEEDED(g_effect_instance_fxaa.Render(render_device)); + } + };};}; +}; +#endif \ No newline at end of file diff --git a/pool/shard001/C++/0017696_MenuBar.cpp b/pool/shard001/C++/0017696_MenuBar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43ae560a1c305821e0ce72104e9b7594999affbc --- /dev/null +++ b/pool/shard001/C++/0017696_MenuBar.cpp @@ -0,0 +1,252 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +// $NoKeywords: $ +//=============================================================================// + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +// memdbgon must be the last include file in a .cpp file!!! +#include + +using namespace vgui; + + +enum +{ + MENUBARINDENT = 4, // indent from top and bottom of panel. +}; + +DECLARE_BUILD_FACTORY( MenuBar ); + +//----------------------------------------------------------------------------- +// Purpose: Constructor +//----------------------------------------------------------------------------- +MenuBar::MenuBar(Panel *parent, const char *panelName) : + Panel(parent, panelName), + m_nRightEdge( 0 ) +{ +} + +//----------------------------------------------------------------------------- +// Purpose: Destructor +//----------------------------------------------------------------------------- +MenuBar::~MenuBar() +{ +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void MenuBar::AddButton(MenuButton *button) +{ + button->SetParent(this); + button->AddActionSignalTarget(this); + m_pMenuButtons.AddToTail(button); +} + +//----------------------------------------------------------------------------- +// This will add the menu to the menu bar +//----------------------------------------------------------------------------- +void MenuBar::AddMenu( const char *pButtonName, Menu *pMenu ) +{ + MenuButton *pMenuButton = new MenuButton(this, pButtonName, pButtonName); + pMenuButton->SetMenu(pMenu); + AddButton(pMenuButton); +} + + +//----------------------------------------------------------------------------- +// Purpose: Handle key presses, Activate shortcuts +//----------------------------------------------------------------------------- +void MenuBar::OnKeyCodeTyped(KeyCode code) +{ + switch(code) + { + case KEY_RIGHT: + { + // iterate the menu items looking for one that is open + // if we find one open, open the one to the right + for (int i = 0; i < m_pMenuButtons.Count() - 1; i++) + { + MenuButton *panel = m_pMenuButtons[i]; + if (panel->IsDepressed()) + { + m_pMenuButtons[i]->DoClick(); + m_pMenuButtons[i+1]->DoClick(); + break; + } + } + break; + } + case KEY_LEFT: + { + // iterate the menu items looking for one that is open + // if we find one open, open the one to the left + for (int i = 1; i < m_pMenuButtons.Count(); i++) + { + MenuButton *panel = m_pMenuButtons[i]; + if (panel->IsDepressed()) + { + m_pMenuButtons[i]->DoClick(); + m_pMenuButtons[i-1]->DoClick(); + break; + } + } + break; + } + default: + { + break; + } + } + + // don't chain back +} + +//----------------------------------------------------------------------------- +// Purpose: Handle key presses, Activate shortcuts +// Input : code - +//----------------------------------------------------------------------------- +void MenuBar::OnKeyTyped(wchar_t unichar) +{ + if (unichar) + { + // iterate the menu items looking for one with the matching hotkey + for (int i = 0; i < m_pMenuButtons.Count(); i++) + { + MenuButton *panel = m_pMenuButtons[i]; + if (panel->IsVisible()) + { + Panel *hot = panel->HasHotkey(unichar); + if (hot) + { + // post a message to the menuitem telling it it's hotkey was pressed + PostMessage(hot, new KeyValues("Hotkey")); + return; + } + } + } + } + + // don't chain back +} + +void MenuBar::Paint() +{ + IScheme *pScheme = scheme()->GetIScheme( GetScheme() ); + for ( int i = 0; i < m_pMenuButtons.Count(); i++) + { + if (!m_pMenuButtons[i]->IsArmed()) + m_pMenuButtons[i]->SetDefaultBorder(NULL); + else + { + m_pMenuButtons[i]->SetDefaultBorder(pScheme->GetBorder( "ButtonBorder")); + } + } +} + +//----------------------------------------------------------------------------- +// Purpose: Message map +//----------------------------------------------------------------------------- +void MenuBar::ApplySchemeSettings(IScheme *pScheme) +{ + BaseClass::ApplySchemeSettings(pScheme); + + // get the borders we need + SetBorder(pScheme->GetBorder("ButtonBorder")); + + // get the background color + SetBgColor(pScheme->GetColor( "MenuBar.BgColor", GetBgColor() )); + +} + + + +//----------------------------------------------------------------------------- +// Purpose: Reformat according to the new layout +//----------------------------------------------------------------------------- +void MenuBar::PerformLayout() +{ + int nBarWidth, nBarHeight; + GetSize( nBarWidth, nBarHeight ); + + // Now position + resize all buttons + int x = MENUBARINDENT; + for ( int i = 0; i < m_pMenuButtons.Count(); ++i ) + { + int nWide, nTall; + + m_pMenuButtons[i]->GetContentSize(nWide, nTall); + m_pMenuButtons[i]->SetPos( x, MENUBARINDENT ); + m_pMenuButtons[i]->SetSize( nWide + Label::Content, nBarHeight - 2 * MENUBARINDENT ); + + x += nWide + MENUBARINDENT; + } + + m_nRightEdge = x; +} + +//----------------------------------------------------------------------------- +// Purpose: Get the size of the menus in the bar (so other children can be added to menu bar) +// Input : w - +// int&h - +//----------------------------------------------------------------------------- +void MenuBar::GetContentSize( int& w, int&h ) +{ + w = m_nRightEdge + 2; + h = GetTall(); +} + +//----------------------------------------------------------------------------- +// Purpose: Message map +//----------------------------------------------------------------------------- +void MenuBar::OnMenuClose() +{ + RequestFocus(); +} + +//----------------------------------------------------------------------------- +// Purpose: Message map +//----------------------------------------------------------------------------- +void MenuBar::OnCursorEnteredMenuButton(int VPanel) +{ + VPANEL menuButton = (VPANEL)VPanel; + // see if we had a menu open + for ( int i = 0; i < m_pMenuButtons.Count(); i++) + { + // one of our buttons was pressed. + if (m_pMenuButtons[i]->IsDepressed()) + { + int oldbutton = i; + // now see if menuButton is one of ours. + for ( int j = 0; j < m_pMenuButtons.Count(); j++) + { + MenuButton *button = static_cast(ipanel()->GetPanel(menuButton, GetModuleName())); + // it is one of ours. + if ( button == m_pMenuButtons[j]) + { + // if its a different button than the one we already had open, + if (j != oldbutton) + { + // close this menu and open the one we just entered + m_pMenuButtons[oldbutton]->DoClick(); + button->DoClick(); + } + } + } + } + } +} diff --git a/pool/shard001/C++/0017711_TffdshowDecVideoAllocator.cpp b/pool/shard001/C++/0017711_TffdshowDecVideoAllocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfdaee8578465edcb9d4d2a921ffc06a48122f79 --- /dev/null +++ b/pool/shard001/C++/0017711_TffdshowDecVideoAllocator.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2004-2006 Milan Cutka + * based on CDirectVobSubInputPin by Gabest + * + * 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 "stdafx.h" +#include "TffdshowDecVideoAllocator.h" +#include "dsutil.h" +#include "ffdshow_mediaguids.h" +#include "TffDecoderVideo.h" +#include "TffdshowVideoInputPin.h" + +TffdshowDecVideoAllocator::TffdshowDecVideoAllocator(CBaseFilter* Ifilter, HRESULT* phr): + CMemAllocator(NAME("TffdshowDecVideoAllocator"), NULL, phr), + filter(Ifilter), + mtChanged(false) +{ +} + +STDMETHODIMP TffdshowDecVideoAllocator::GetBuffer(IMediaSample** ppBuffer, REFERENCE_TIME *pStartTime, REFERENCE_TIME *pEndTime, DWORD dwFlags) +{ + if (!m_bCommitted) { + return VFW_E_NOT_COMMITTED; + } + + if (mtChanged) { + ALLOCATOR_PROPERTIES Properties, Actual; + if (FAILED(GetProperties(&Properties))) { + return E_FAIL; + } + + BITMAPINFOHEADER bih; + ExtractBIH(mt, &bih); + unsigned int biSizeImage = (bih.biWidth * abs(bih.biHeight) * bih.biBitCount) >> 3; + + if (bih.biSizeImage < biSizeImage) { + // bugus intervideo mpeg2 decoder doesn't seem to adjust biSizeImage to the really needed buffer size + bih.biSizeImage = biSizeImage; + } + + if ((DWORD)Properties.cbBuffer < bih.biSizeImage || !m_bCommitted) { + Properties.cbBuffer = bih.biSizeImage; + if (FAILED(Decommit())) { + return E_FAIL; + } + if (FAILED(SetProperties(&Properties, &Actual))) { + return E_FAIL; + } + if (FAILED(Commit())) { + return E_FAIL; + } + ASSERT(Actual.cbBuffer >= Properties.cbBuffer); + if (Actual.cbBuffer < Properties.cbBuffer) { + return E_FAIL; + } + } + } + + HRESULT hr = CMemAllocator::GetBuffer(ppBuffer, pStartTime, pEndTime, dwFlags); + + if (mtChanged && SUCCEEDED(hr)) { + mtChanged = false; + } + return hr; +} + +void TffdshowDecVideoAllocator::NotifyMediaType(const CMediaType &Imt) +{ + mt = Imt; + mtChanged = true; +} + +int TffdshowDecVideoAllocator::get_biWidth() const +{ + // make sure to check the return value is not zero. + BITMAPINFOHEADER *bi = get_BITMAPINFOHEADER_ptr(); + if (bi) { + return bi->biWidth; + } + return 0; +} + +int TffdshowDecVideoAllocator::get_biHeight() const +{ + // make sure to check the return value is not zero. + BITMAPINFOHEADER *bi = get_BITMAPINFOHEADER_ptr(); + if (bi) { + return bi->biHeight; + } + return 0; +} + +// Extract pointer to BITMAPINFOHEADER from raw formats. +BITMAPINFOHEADER* TffdshowDecVideoAllocator::get_BITMAPINFOHEADER_ptr() const +{ + // return non-NULL value for raw formats. + if (mt.IsValid() && mt.bFixedSizeSamples) { + BITMAPINFOHEADER *bi = NULL; + if (mt.formattype == FORMAT_VideoInfo) { + VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)mt.pbFormat; + bi = &vih->bmiHeader; + } else if (mt.formattype == FORMAT_VideoInfo2) { + VIDEOINFOHEADER2* vih = (VIDEOINFOHEADER2*)mt.pbFormat; + bi = &vih->bmiHeader; + } + return bi; + } + return NULL; +} diff --git a/pool/shard001/C++/0017716_HRTFKernel.cpp b/pool/shard001/C++/0017716_HRTFKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8c29e26a05960dbec53a8031f20fb8c174ac699 --- /dev/null +++ b/pool/shard001/C++/0017716_HRTFKernel.cpp @@ -0,0 +1,142 @@ +/* + * 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: + * + * 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE 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. + */ + +#include "platform/audio/HRTFKernel.h" + +#include "platform/audio/AudioChannel.h" +#include "wtf/MathExtras.h" +#include "wtf/PtrUtil.h" +#include +#include + +namespace blink { + +// Takes the input AudioChannel as an input impulse response and calculates the +// average group delay. This represents the initial delay before the most +// energetic part of the impulse response. The sample-frame delay is removed +// from the impulseP impulse response, and this value is returned. The length +// of the passed in AudioChannel must be a power of 2. +static float extractAverageGroupDelay(AudioChannel* channel, + size_t analysisFFTSize) { + ASSERT(channel); + + float* impulseP = channel->mutableData(); + + bool isSizeGood = channel->length() >= analysisFFTSize; + ASSERT(isSizeGood); + if (!isSizeGood) + return 0; + + // Check for power-of-2. + ASSERT(1UL << static_cast(log2(analysisFFTSize)) == + analysisFFTSize); + + FFTFrame estimationFrame(analysisFFTSize); + estimationFrame.doFFT(impulseP); + + float frameDelay = clampTo(estimationFrame.extractAverageGroupDelay()); + estimationFrame.doInverseFFT(impulseP); + + return frameDelay; +} + +HRTFKernel::HRTFKernel(AudioChannel* channel, size_t fftSize, float sampleRate) + : m_frameDelay(0), m_sampleRate(sampleRate) { + ASSERT(channel); + + // Determine the leading delay (average group delay) for the response. + m_frameDelay = extractAverageGroupDelay(channel, fftSize / 2); + + float* impulseResponse = channel->mutableData(); + size_t responseLength = channel->length(); + + // We need to truncate to fit into 1/2 the FFT size (with zero padding) in + // order to do proper convolution. + // Truncate if necessary to max impulse response length allowed by FFT. + size_t truncatedResponseLength = std::min(responseLength, fftSize / 2); + + // Quick fade-out (apply window) at truncation point + unsigned numberOfFadeOutFrames = static_cast( + sampleRate / 4410); // 10 sample-frames @44.1KHz sample-rate + ASSERT(numberOfFadeOutFrames < truncatedResponseLength); + if (numberOfFadeOutFrames < truncatedResponseLength) { + for (unsigned i = truncatedResponseLength - numberOfFadeOutFrames; + i < truncatedResponseLength; ++i) { + float x = 1.0f - + static_cast( + i - (truncatedResponseLength - numberOfFadeOutFrames)) / + numberOfFadeOutFrames; + impulseResponse[i] *= x; + } + } + + m_fftFrame = makeUnique(fftSize); + m_fftFrame->doPaddedFFT(impulseResponse, truncatedResponseLength); +} + +std::unique_ptr HRTFKernel::createImpulseResponse() { + std::unique_ptr channel = + wrapUnique(new AudioChannel(fftSize())); + FFTFrame fftFrame(*m_fftFrame); + + // Add leading delay back in. + fftFrame.addConstantGroupDelay(m_frameDelay); + fftFrame.doInverseFFT(channel->mutableData()); + + return channel; +} + +// Interpolates two kernels with x: 0 -> 1 and returns the result. +std::unique_ptr HRTFKernel::createInterpolatedKernel( + HRTFKernel* kernel1, + HRTFKernel* kernel2, + float x) { + ASSERT(kernel1 && kernel2); + if (!kernel1 || !kernel2) + return nullptr; + + ASSERT(x >= 0.0 && x < 1.0); + x = clampTo(x, 0.0f, 1.0f); + + float sampleRate1 = kernel1->sampleRate(); + float sampleRate2 = kernel2->sampleRate(); + ASSERT(sampleRate1 == sampleRate2); + if (sampleRate1 != sampleRate2) + return nullptr; + + float frameDelay = + (1 - x) * kernel1->frameDelay() + x * kernel2->frameDelay(); + + std::unique_ptr interpolatedFrame = + FFTFrame::createInterpolatedFrame(*kernel1->fftFrame(), + *kernel2->fftFrame(), x); + return HRTFKernel::create(std::move(interpolatedFrame), frameDelay, + sampleRate1); +} + +} // namespace blink diff --git a/pool/shard001/C++/0017719_mainwindowsnippet.cpp b/pool/shard001/C++/0017719_mainwindowsnippet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..983eb1be4429f07014fb2e1a63c96c30eb4cf8ac --- /dev/null +++ b/pool/shard001/C++/0017719_mainwindowsnippet.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation 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$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +MainWindow::MainWindow() +{ + createMenus(); + createToolBars(); + createDockWidgets(); + //setMenuWidget(new QPushButton("Hello")); +} + +void MainWindow::createMenus() +{ + //setMenuWidget(new QPushButton("Hello")); + QMenu *menu = new QMenu("File"); + menu->addAction("Save &As"); + + QMenuBar *bar = new QMenuBar; + bar->addMenu(menu); + + setMenuWidget(new QWidget()); +} + +void MainWindow::createToolBars() +{ + setToolButtonStyle(Qt::ToolButtonTextOnly); + QToolBar *t1 = new QToolBar; + t1->addAction(new QAction("t1", this)); + + QToolBar *t2 = new QToolBar; + t2->addAction(new QAction("t2", this)); + + addToolBar(Qt::LeftToolBarArea, t1); + addToolBar(Qt::LeftToolBarArea, t2); +} + +void MainWindow::createDockWidgets() +{ + QWidget *dockWidgetContents = new QWidget; + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(new QPushButton("My Button.")); + dockWidgetContents->setLayout(layout); + +//! [0] + QDockWidget *dockWidget = new QDockWidget(tr("Dock Widget"), this); + dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | + Qt::RightDockWidgetArea); + dockWidget->setWidget(dockWidgetContents); + addDockWidget(Qt::LeftDockWidgetArea, dockWidget); +//! [0] +} diff --git a/pool/shard001/C++/0017726_restriction_parser.cpp b/pool/shard001/C++/0017726_restriction_parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c466a5363c24a59e80ddf5d0bd920d7deb6fd83 --- /dev/null +++ b/pool/shard001/C++/0017726_restriction_parser.cpp @@ -0,0 +1,191 @@ +#include "extractor/restriction_parser.hpp" +#include "extractor/profile_properties.hpp" +#include "extractor/scripting_environment.hpp" + +#include "extractor/external_memory_node.hpp" + +#include "util/simple_logger.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace osrm +{ +namespace extractor +{ + +RestrictionParser::RestrictionParser(ScriptingEnvironment &scripting_environment) + : use_turn_restrictions(scripting_environment.GetProfileProperties().use_turn_restrictions) +{ + if (use_turn_restrictions) + { + restrictions = scripting_environment.GetRestrictions(); + const unsigned count = restrictions.size(); + if (count > 0) + { + util::SimpleLogger().Write() << "Found " << count << " turn restriction tags:"; + for (const std::string &str : restrictions) + { + util::SimpleLogger().Write() << " " << str; + } + } + else + { + util::SimpleLogger().Write() << "Found no turn restriction tags"; + } + } +} + +/** + * Tries to parse a relation as a turn restriction. This can fail for a number of + * reasons. The return type is a boost::optional. + * + * Some restrictions can also be ignored: See the ```get_restrictions``` function + * in the corresponding profile. We use it for both namespacing restrictions, as in + * restriction:motorcar as well as whitelisting if its in except:motorcar. + */ +boost::optional +RestrictionParser::TryParse(const osmium::Relation &relation) const +{ + // return if turn restrictions should be ignored + if (!use_turn_restrictions) + { + return {}; + } + + osmium::tags::KeyFilter filter(false); + filter.add(true, "restriction"); + + // Not only use restriction= but also e.g. restriction:motorcar= + for (const auto &namespaced : restrictions) + filter.add(true, "restriction:" + namespaced); + + const osmium::TagList &tag_list = relation.tags(); + + osmium::tags::KeyFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); + osmium::tags::KeyFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); + + // if it's not a restriction, continue; + if (std::distance(fi_begin, fi_end) == 0) + { + return {}; + } + + // check if the restriction should be ignored + const char *except = relation.get_value_by_key("except"); + if (except != nullptr && ShouldIgnoreRestriction(except)) + { + return {}; + } + + bool is_only_restriction = false; + + for (; fi_begin != fi_end; ++fi_begin) + { + const std::string key(fi_begin->key()); + const std::string value(fi_begin->value()); + + // documented OSM restriction tags start either with only_* or no_*; + // check and return on these values, and ignore unrecognized values + if (value.find("only_") == 0) + { + is_only_restriction = true; + } + else if (value.find("no_") == 0) + { + is_only_restriction = false; + } + else // unrecognized value type + { + return {}; + } + } + + InputRestrictionContainer restriction_container(is_only_restriction); + + for (const auto &member : relation.members()) + { + const char *role = member.role(); + if (strcmp("from", role) != 0 && strcmp("to", role) != 0 && strcmp("via", role) != 0) + { + continue; + } + + switch (member.type()) + { + case osmium::item_type::node: + // Make sure nodes appear only in the role if a via node + if (0 == strcmp("from", role) || 0 == strcmp("to", role)) + { + continue; + } + BOOST_ASSERT(0 == strcmp("via", role)); + + // set via node id + restriction_container.restriction.via.node = member.ref(); + break; + + case osmium::item_type::way: + BOOST_ASSERT(0 == strcmp("from", role) || 0 == strcmp("to", role) || + 0 == strcmp("via", role)); + if (0 == strcmp("from", role)) + { + restriction_container.restriction.from.way = member.ref(); + } + else if (0 == strcmp("to", role)) + { + restriction_container.restriction.to.way = member.ref(); + } + // else if (0 == strcmp("via", role)) + // { + // not yet suppported + // restriction_container.restriction.via.way = member.ref(); + // } + break; + case osmium::item_type::relation: + // not yet supported, but who knows what the future holds... + break; + default: + // shouldn't ever happen + break; + } + } + return boost::make_optional(std::move(restriction_container)); +} + +bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const +{ + // should this restriction be ignored? yes if there's an overlap between: + // a) the list of modes in the except tag of the restriction + // (except_tag_string), eg: except=bus;bicycle + // b) the lua profile defines a hierarchy of modes, + // eg: [access, vehicle, bicycle] + + if (except_tag_string.empty()) + { + return false; + } + + // Be warned, this is quadratic work here, but we assume that + // only a few exceptions are actually defined. + std::vector exceptions; + boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*")); + + return std::any_of( + std::begin(exceptions), std::end(exceptions), [&](const std::string ¤t_string) { + return std::end(restrictions) != + std::find(std::begin(restrictions), std::end(restrictions), current_string); + }); +} +} +} diff --git a/pool/shard001/C++/0017730_spotlightsourceprocessor.cpp b/pool/shard001/C++/0017730_spotlightsourceprocessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c6c8bfe23579a306535706de0ca7141fe287820 --- /dev/null +++ b/pool/shard001/C++/0017730_spotlightsourceprocessor.cpp @@ -0,0 +1,109 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2014-2019 Inviwo Foundation + * 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. + * + *********************************************************************************/ + +#include +#include + +namespace inviwo { + +const ProcessorInfo SpotLightSourceProcessor::processorInfo_{ + "org.inviwo.Spotlightsource", // Class identifier + "Spot light source", // Display name + "Light source", // Category + CodeState::Experimental, // Code state + Tags::CPU, // Tags +}; +const ProcessorInfo SpotLightSourceProcessor::getProcessorInfo() const { return processorInfo_; } + +SpotLightSourceProcessor::SpotLightSourceProcessor() + : Processor() + , outport_("SpotLightSource") + , camera_("camera", "Camera", vec3(0.0f, 0.0f, -2.0f), vec3(0.0f, 0.0f, 0.0f), + vec3(0.0f, 1.0f, 0.0f), nullptr, InvalidationLevel::Valid) + , lightPosition_( + "lightPosition", "Light Source Position", + FloatVec3Property("position", "Position", vec3(100.f), vec3(-100.f), vec3(100.f)), + &camera_) + , lighting_("lighting", "Light Parameters") + , lightPowerProp_("lightPower", "Light power (%)", 50.f, 0.f, 100.f) + , lightSize_("lightSize", "Light size", vec2(1.5f, 1.5f), vec2(0.0f, 0.0f), vec2(3.0f, 3.0f)) + , lightDiffuse_("lightDiffuse", "Color", vec3(1.0f)) + , lightConeRadiusAngle_("lightConeRadiusAngle", "Light Cone Radius Angle", 30.f, 1.f, 90.f) + , lightFallOffAngle_("lightFallOffAngle", "Light Fall Off Angle", 5.f, 0.f, 30.f) + , lightSource_{std::make_shared()} { + + addPort(outport_); + + addProperty(lightPosition_); + lighting_.addProperty(lightConeRadiusAngle_); + lighting_.addProperty(lightFallOffAngle_); + lighting_.addProperty(lightDiffuse_); + lighting_.addProperty(lightPowerProp_); + lighting_.addProperty(lightSize_); + addProperty(lighting_); + addProperty(camera_); + + lightDiffuse_.setSemantics(PropertySemantics::Color); + lightDiffuse_.setCurrentStateAsDefault(); +} + +void SpotLightSourceProcessor::process() { + updateSpotLightSource(lightSource_.get()); + outport_.setData(lightSource_); +} + +void SpotLightSourceProcessor::updateSpotLightSource(SpotLight* lightSource) { + vec3 lightPos = lightPosition_.get(); + vec3 dir; + switch ( + static_cast(lightPosition_.referenceFrame_.getSelectedValue())) { + case PositionProperty::Space::VIEW: { + dir = glm::normalize(camera_.getLookTo() - lightPos); + break; + } + case PositionProperty::Space::WORLD: + [[fallthrough]]; + default: { + dir = glm::normalize(vec3(0.f) - lightPos); + break; + } + } + mat4 transformationMatrix = getLightTransformationMatrix(lightPos, dir); + // Offset by 0.5 to get to texture coordinates + lightSource->setModelMatrix(glm::translate(vec3(0.5f))); + lightSource->setWorldMatrix(transformationMatrix); + + lightSource->setSize(lightSize_.get()); + lightSource->setIntensity(lightPowerProp_.get() * lightDiffuse_.get()); + lightSource->setDirection(dir); + lightSource->setConeRadiusAngle(lightConeRadiusAngle_.get()); + lightSource->setConeFallOffAngle(lightFallOffAngle_.get()); +} + +} // namespace inviwo diff --git a/pool/shard001/C++/0017743_Window.cpp b/pool/shard001/C++/0017743_Window.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0788e607b53d3027c195bf76b9d1ee0a131bdd0c --- /dev/null +++ b/pool/shard001/C++/0017743_Window.cpp @@ -0,0 +1,99 @@ +// Copyright (c) 2015, Matthew Malensek. +// Distributed under the BSD 2-Clause License (see LICENSE.txt for details) + +#include "Window.h" + +#include "Error.h" + +Window::Window(LPCWSTR className, LPCWSTR title, HINSTANCE hInstance, + int x, int y, int width, int height, + UINT classStyle, DWORD style, DWORD exStyle, + HWND parent, HMENU menu, + HICON icon, HCURSOR cursor, HBRUSH background) : +_className(className), +_title(title) { + + if (hInstance == NULL) { + hInstance = (HINSTANCE) GetModuleHandle(NULL); + } + _hInstance = hInstance; + + if (cursor == NULL) { + cursor = LoadCursor(NULL, IDC_ARROW); + } + + WNDCLASSEX wcex = { 0 }; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = classStyle; + wcex.lpfnWndProc = &Window::StaticWndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = icon; + wcex.hCursor = cursor; + wcex.hbrBackground = background; + wcex.lpszClassName = _className.c_str(); + wcex.hIconSm = NULL; + + if (!RegisterClassEx(&wcex)) { + Error::ErrorMessage(Error::SYSERR_REGISTERCLASS, _className); + } + + if (_title == L"") { + _title = std::wstring(className); + } + + _hWnd = CreateWindowEx( + exStyle, className, _title.c_str(), style, + x, y, width, height, + parent, + menu, + hInstance, + this); + + if (_hWnd == NULL) { + Error::ErrorMessage(Error::SYSERR_CREATEWINDOW, _title); + } +} + +Window::~Window() { + DestroyWindow(_hWnd); + UnregisterClass(_className.c_str(), _hInstance); +} + +LPCWSTR Window::ClassName() { + return _className.c_str(); +} + +HWND Window::Handle() { + return _hWnd; +} + +HINSTANCE Window::InstanceHandle() { + return _hInstance; +} + +LPCWSTR Window::Title() { + return _title.c_str(); +} + +LRESULT CALLBACK +Window::StaticWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { + Window *window; + + if (message == WM_CREATE) { + window = (Window *) ((LPCREATESTRUCT) lParam)->lpCreateParams; + SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) window); + } else { + window = (Window *) GetWindowLongPtr(hWnd, GWLP_USERDATA); + if (!window) { + return DefWindowProc(hWnd, message, wParam, lParam); + } + } + + return window->WndProc(hWnd, message, wParam, lParam); +} + +LRESULT Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd, message, wParam, lParam); +} diff --git a/pool/shard001/C++/0017744_io.cpp b/pool/shard001/C++/0017744_io.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8e9302083b701fae75488da6c5cdfd59ef4a94b --- /dev/null +++ b/pool/shard001/C++/0017744_io.cpp @@ -0,0 +1,49 @@ +/* +Some of this code began its life as a part of GTA V SCRIPT HOOK SDK. +http://dev-c.com +(C) Alexander Blade 2015 + +It is now part of the Enhanced Native Trainer project. +https://github.com/gtav-ent/GTAV-EnhancedNativeTrainer +(C) Rob Pridham and fellow contributors 2015 +*/ + +#include "io.h" +#include "config_io.h" +#include +#include + +DWORD trainerResetTime = 0; + +bool trainer_switch_pressed() +{ + return IsKeyJustUp( config->get_key_config()->key_toggle_main_menu ); +} + +void get_button_state(bool *a, bool *b, bool *up, bool *down, bool *l, bool *r) +{ + KeyInputConfig *keyConf = config->get_key_config(); + + if (a) *a = IsKeyDown(keyConf->key_menu_confirm); + if (b) *b = IsKeyDown(keyConf->key_menu_back); + if (up) *up = IsKeyDown(keyConf->key_menu_up); + if (down) *down = IsKeyDown(keyConf->key_menu_down); + if (r) *r = IsKeyDown(keyConf->key_menu_right); + if (l) *l = IsKeyDown(keyConf->key_menu_left); +} + +bool get_key_pressed(int nVirtKey) +{ + //return (GetKeyState(nVirtKey) & 0x8000) != 0; + return (GetAsyncKeyState(nVirtKey) & 0x8000) != 0; +} + +bool airbrake_switch_pressed() +{ + return IsKeyJustUp(get_config()->get_key_config()->key_toggle_airbrake); +} + +void reset_trainer_switch() +{ + trainerResetTime = GetTickCount(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0017755_VirtualStackFrame_i386.cpp b/pool/shard001/C++/0017755_VirtualStackFrame_i386.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65c8e5c5ba87d5d07e1f87c7e2dcaaae8e6c4f9c --- /dev/null +++ b/pool/shard001/C++/0017755_VirtualStackFrame_i386.cpp @@ -0,0 +1,120 @@ +/* + * + * + * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version + * 2 only, 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 version 2 for more details (a copy is + * included at /legal/license.txt). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this work; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa + * Clara, CA 95054 or visit www.sun.com if you need additional + * information or have any questions. + */ + +#include "incls/_precompiled.incl" +#include "incls/_VirtualStackFrame_i386.cpp.incl" + +#if ENABLE_COMPILER + +// Special casing of float/double constants 0.0 and 1.0 +// Watch out for negative zero and nan + +bool is_zero_float(jfloat f) { + return jint_cast(f) == jint_cast(0.0f); +} + +bool is_one_float(jfloat f) { + return !g_isnan(f) && g_isfinite(f) && f == 1.0f; +} + +bool is_zero_double(jdouble d) { + return jlong_cast(d) == jlong_cast(0.0); +} + +bool is_one_double(jdouble d) { + return !g_isnan(d) && g_isfinite(d) && d == 1.0; +} + +// Loading of float and double constants. +// On x86 loading float/double constants from a fixed address +// is much faster than materializing the constant on the stack. +// Since compiled methods may move at GC time, storing the constants +// inside the compiled method requires appropriate relocation info +// and fixup. For now, we just have two small global tables holding +// constants, and revert to slow case (materialize on stack) if the +// tables overflow. Most programs contain no or very few float/double +// constants. + +const int max_float_constants = 16; +const int max_double_constants = 16; +static int float_constants_index = 0; +static int double_constants_index = 0; +static jint float_constants [max_float_constants ]; +static jlong double_constants[max_double_constants]; + +address lookup_float_constant(jfloat value) { + // Use raw bits as key + jint v = jint_cast(value); + // Search for existing float constant + for (int i = 0; i < float_constants_index; i++) { + if (v == float_constants[i]) { + return (address) &float_constants[i]; + } + } + // Add new float constant to table + if (float_constants_index < max_float_constants) { + float_constants[float_constants_index] = v; + return (address) &float_constants[float_constants_index++]; + } + // Table overflow, revert to slow case + return NULL; +} + +address lookup_double_constant(jdouble value) { + // Use raw bits as key + jlong v = jlong_cast(value); + // Search for existing double constant + for (int i = 0; i < double_constants_index; i++) { + if (v == double_constants[i]) { + return (address) &double_constants[i]; + } + } + // Add new double constant to table + if (double_constants_index < max_double_constants) { + double_constants[double_constants_index] = v; + return (address) &double_constants[double_constants_index++]; + } + // Table overflow, revert to slow case + return NULL; +} + +bool VirtualStackFrame::flush_quick() { + // not supported on x86 + return false; +} + +#ifndef PRODUCT +void VirtualStackFrame::dump_fp_registers(bool as_comment) { + FPURegisterMap fpu_map = fpu_register_map(); + if (!as_comment || !fpu_map.is_empty()) { + // No need including a code comment when the FPU is empty + fpu_map.dump(as_comment); + } +} + +#endif + +#endif diff --git a/pool/shard001/C++/0017761_AstarTest.cpp b/pool/shard001/C++/0017761_AstarTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0659716f1681179bf83ad2cdc66b5fc4125ac779 --- /dev/null +++ b/pool/shard001/C++/0017761_AstarTest.cpp @@ -0,0 +1,102 @@ +/****************************************************************************** +* MIT License +* +* Copyright (c) 2017 Senthil Hariharan Arul +* +* 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. +*******************************************************************************/ + +/** + * @file AstarTest.cpp + * @author Senthil Hariharan Arul + * @copyright MIT License + * @brief Test cases for class Astar + */ + +#include +#include +#include +#include +#include "Astar.hpp" + + +std::shared_ptr testAstar = std::make_shared(); +std::vector testMapArray {1, 1, 1, 1, 0, 1, 0, + 0, 0, 0, 1, 1, 0, 0, + 0, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 0}; +/** + *@brief Case to test for out of bound start and end point + *@param none + *@return none + */ +TEST(AstarCreateNodeTest1, testCreateNodeForOutOfBoundStartandEndPt) { + Map testMap; + testMap.storeMap(testMapArray); + int startPt = -1; + int endPt = 111; + ASSERT_FALSE(testAstar->createNodeList(testMap, startPt, endPt)); +} + +/** + *@brief Case to test successful working for inrange + * start and end point + *@param none + *@return none + */ +TEST(AstarCreateNodeTest2, testCreateNodeForInBoundStartandEndPt) { + Map testMap; + testMap.storeMap(testMapArray); + int startPt = 1; + int endPt = 11; + ASSERT_TRUE(testAstar->createNodeList(testMap, startPt, endPt)); +} + +/** + *@brief Case to test for removal of obstacle coordinate + *@param none + *@return none + */ +TEST(AstarIdentifyNodeTest1, testIdentfyNodeForObstacleCoOrdinate) { + ASSERT_EQ(testAstar->identifyNode(0, 4), 9999); +} + +/** + *@brief Case to test for successful identification of nodeindex + * from node coordinates. + *@param none + *@return none + */ +TEST(AstarIdentifyNodeTest2, testIdentfyNodeForNodeCoOrdinate) { + ASSERT_EQ(testAstar->identifyNode(0, 2), 2); +} + +/** + *@brief Case to test successful calculation of shortest path + *@param none + *@return none + */ +TEST(AstarPlanPathTest, testShortestPathForKnownMap) { + Map testMap; + testMap.storeMap(testMapArray); + testAstar->setStartPoint(2); + testAstar->setEndPoint(17); + ASSERT_EQ(testAstar->planPath(), 6); +} + diff --git a/pool/shard001/C++/0017764_Slider.cpp b/pool/shard001/C++/0017764_Slider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecf15e591052e0741368e2053c1ed8196b4c21bc --- /dev/null +++ b/pool/shard001/C++/0017764_Slider.cpp @@ -0,0 +1,169 @@ +#include "HaxeAPI.h" + +// DECL: void addListener(Control::Listener* listener, int eventFlags); +void hx_Slider_addListener(value thisObj, value listener, value eventFlags) +{ + Slider *_thisObj; + Control::Listener *_listener; + int _eventFlags = val_get_int(eventFlags); + ValueToObject(thisObj, _thisObj); + ValueToObject(listener, _listener); + _thisObj->addListener(_listener, _eventFlags); +} +DEFINE_PRIM(hx_Slider_addListener, 3); + +// DECL: static Slider* create(const char* id, Theme::Style* style); +value hx_Slider_static_create(value id, value style) +{ + const char *_id = ValueToString(id); + Theme::Style *_style; + ValueToObject(style, _style); + return ReferenceToValue(Slider::create(_id, _style)); +} +DEFINE_PRIM(hx_Slider_static_create, 2); + +// DECL: float getMax() const; +value hx_Slider_getMax(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_float(_thisObj->getMax()); +} +DEFINE_PRIM(hx_Slider_getMax, 1); + +// DECL: float getMin() const; +value hx_Slider_getMin(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_float(_thisObj->getMin()); +} +DEFINE_PRIM(hx_Slider_getMin, 1); + +// DECL: float getStep() const; +value hx_Slider_getStep(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_float(_thisObj->getStep()); +} +DEFINE_PRIM(hx_Slider_getStep, 1); + +// DECL: const char* getType() const; +value hx_Slider_getType(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return StringToValue(_thisObj->getType()); +} +DEFINE_PRIM(hx_Slider_getType, 1); + +// DECL: float getValue() const; +value hx_Slider_getValue(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_float(_thisObj->getValue()); +} +DEFINE_PRIM(hx_Slider_getValue, 1); + +// DECL: Font::Justify getValueTextAlignment() const; +value hx_Slider_getValueTextAlignment(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return EnumToValue(_thisObj->getValueTextAlignment()); +} +DEFINE_PRIM(hx_Slider_getValueTextAlignment, 1); + +// DECL: unsigned int getValueTextPrecision() const; +value hx_Slider_getValueTextPrecision(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_int(_thisObj->getValueTextPrecision()); +} +DEFINE_PRIM(hx_Slider_getValueTextPrecision, 1); + +// DECL: bool isValueTextVisible() const; +value hx_Slider_isValueTextVisible(value thisObj) +{ + Slider *_thisObj; + ValueToObject(thisObj, _thisObj); + return alloc_bool(_thisObj->isValueTextVisible()); +} +DEFINE_PRIM(hx_Slider_isValueTextVisible, 1); + +// DECL: void setMax(float max); +void hx_Slider_setMax(value thisObj, value max) +{ + Slider *_thisObj; + float _max = ValueToFloat(max); + ValueToObject(thisObj, _thisObj); + _thisObj->setMax(_max); +} +DEFINE_PRIM(hx_Slider_setMax, 2); + +// DECL: void setMin(float min); +void hx_Slider_setMin(value thisObj, value min) +{ + Slider *_thisObj; + float _min = ValueToFloat(min); + ValueToObject(thisObj, _thisObj); + _thisObj->setMin(_min); +} +DEFINE_PRIM(hx_Slider_setMin, 2); + +// DECL: void setStep(float step); +void hx_Slider_setStep(value thisObj, value step) +{ + Slider *_thisObj; + float _step = ValueToFloat(step); + ValueToObject(thisObj, _thisObj); + _thisObj->setStep(_step); +} +DEFINE_PRIM(hx_Slider_setStep, 2); + +// DECL: void setValue(float value); +void hx_Slider_setValue(value thisObj, value value) +{ + Slider *_thisObj; + float _value = ValueToFloat(value); + ValueToObject(thisObj, _thisObj); + _thisObj->setValue(_value); +} +DEFINE_PRIM(hx_Slider_setValue, 2); + +// DECL: void setValueTextAlignment(Font::Justify alignment); +void hx_Slider_setValueTextAlignment(value thisObj, value alignment) +{ + Slider *_thisObj; + Font::Justify _alignment; + ValueToObject(thisObj, _thisObj); + ValueToEnum(alignment, _alignment); + _thisObj->setValueTextAlignment(_alignment); +} +DEFINE_PRIM(hx_Slider_setValueTextAlignment, 2); + +// DECL: void setValueTextPrecision(unsigned int precision); +void hx_Slider_setValueTextPrecision(value thisObj, value precision) +{ + Slider *_thisObj; + unsigned int _precision = ValueToUint(precision); + ValueToObject(thisObj, _thisObj); + _thisObj->setValueTextPrecision(_precision); +} +DEFINE_PRIM(hx_Slider_setValueTextPrecision, 2); + +// DECL: void setValueTextVisible(bool visible); +void hx_Slider_setValueTextVisible(value thisObj, value visible) +{ + Slider *_thisObj; + bool _visible = val_get_bool(visible); + ValueToObject(thisObj, _thisObj); + _thisObj->setValueTextVisible(_visible); +} +DEFINE_PRIM(hx_Slider_setValueTextVisible, 2); + +// END +// diff --git a/pool/shard001/C++/0017773_source-collection.cpp b/pool/shard001/C++/0017773_source-collection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3470d082aede6a41907dde41c418ec9badd4c6c --- /dev/null +++ b/pool/shard001/C++/0017773_source-collection.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2011 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 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, see . + * + * Authors: + * Jim Nelson + */ + +#include "source-collection.h" +#include "data-source.h" + +/*! + * \brief SourceCollection::SourceCollection + * \param name + */ +SourceCollection::SourceCollection(const QString& name) + : DataCollection(name) +{ +} + +/*! + * \brief SourceCollection::destroyAll + * \param destroy_backing + * \param delete_objects + */ +void SourceCollection::destroyAll(bool destroy_backing, bool delete_objects) +{ + if (count() == 0) + return; + + // obtain a copy of all objects + QSet all(getAsSet()); + + // must be done before destruction and removal + notifyDestroying(&all); + + // remove before destroying + clear(); + + // destroy and optionally delete all objects + destroyObjects(all, destroy_backing, delete_objects); +} + +/*! + * \brief SourceCollection::destroyMany + * \param objects + * \param destroy_backing + * \param delete_objects + */ +void SourceCollection::destroyMany(const QSet& objects, + bool destroy_backing, bool delete_objects) +{ + QSet intersection(getAsSet()); + intersection.intersect(objects); + + if (intersection.count() == 0) + return; + + notifyDestroying(&intersection); + + removeMany(intersection, true); + + destroyObjects(intersection, destroy_backing, delete_objects); +} + +/*! + * \brief SourceCollection::destroy + * \param object + * \param destroy_backing + * \param delete_object + */ +void SourceCollection::destroy(DataSource* object, bool destroy_backing, + bool delete_object) +{ + if (object == NULL || !contains(object)) + return; + + // Encapsulate the object in a set for the signals below. + QSet object_set; + object_set.insert(object); + + // must be done before destruction and removal + notifyDestroying(&object_set); + + // remove before destroying + remove(object, true); + + object->destroy(destroy_backing); + if (delete_object) + delete object; +} + +/*! + * \brief SourceCollection::notifyDestroying + * \param objects + */ +void SourceCollection::notifyDestroying(const QSet* objects) +{ + emit destroying(objects); +} + +/*! + * \brief SourceCollection::notifyContentsChanged + * \param added + * \param removed + */ +void SourceCollection::notifyContentsChanged(const QSet* added, + const QSet* removed, + bool notify) +{ + if (added != NULL) { + // set membership of DataSource to this collection + DataObject* object; + foreach (object, *added) { + DataSource *source = qobject_cast(object); + source->setMembership(this); + } + } + + if (removed != NULL) { + // remove membership of DataSource from this collection + DataObject* object; + foreach (object, *removed) { + DataSource *source = qobject_cast(object); + Q_ASSERT(source->memberOf() == this); + source->setMembership(NULL); + } + } + + DataCollection::notifyContentsChanged(added, removed, true); +} + +/*! + * \brief SourceCollection::destroyObjects + * \param objects + * \param destroy_backing + * \param delete_objects + */ +void SourceCollection::destroyObjects(const QSet& objects, + bool destroy_backing, bool delete_objects) +{ + DataObject* object; + foreach (object, objects) { + DataSource* source = qobject_cast(object); + Q_ASSERT(source != NULL); + + source->destroy(destroy_backing); + if (delete_objects) + delete source; + } +} diff --git a/pool/shard001/C++/0017774_PngTextureLoader.cpp b/pool/shard001/C++/0017774_PngTextureLoader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b3bf3f85504ec3c02546310adf75818c7478071 --- /dev/null +++ b/pool/shard001/C++/0017774_PngTextureLoader.cpp @@ -0,0 +1,200 @@ +/********************************** +* SCAENA FRAMEWORK +* Author: Marco Andrés Lotto +* License: MIT - 2016 +**********************************/ + +#include "png.h" +#include "TextureLoadException.h" +#include "PngTextureLoader.h" +#include "WindowConnector.h" +#include +using namespace std; + +TextureDataTransfer* PngTextureLoader::loadTexture(string filename) +{ + // Primero consigo la ruta completa del archivo + string fullFileName = WindowConnector::getBaseApplicationPath() + filename; + + // Abro el archivo de textura + FILE *fp = fopen(fullFileName.c_str(), "rb"); + if (!fp){ + throw new TextureLoadException("No se puede abrir el archivo " + fullFileName); + } + + // El archivo de encabezado del png tiene siempre 8 bytes por convencion + unsigned char sig[8]; + + // Controlo que sea v�lido el encabezado del png + fread(sig, 1, 8, fp); + if (!png_check_sig(sig, 8)){ + throw new TextureLoadException("El archivo " + fullFileName + " no es un formato PNG valido"); + } + + // Se realizan validaciones sobre el archivo png + png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!png_ptr) + throw new TextureLoadException("El archivo " + fullFileName + " no se ha podido cargar"); + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) { + png_destroy_read_struct(&png_ptr, NULL, NULL); + throw new TextureLoadException("El archivo " + fullFileName + " no se ha podido cargar"); + } + if (setjmp(png_jmpbuf(png_ptr))) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + throw new TextureLoadException("El archivo " + fullFileName + " no se ha podido cargar"); + } + + png_init_io(png_ptr, fp); + png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ + png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ + + // Creo la estructura para contener los datos de la textura y cargo el encabezado + TextureDataTransfer* textureDt = new TextureDataTransfer(); + textureDt->filename = fullFileName; + + png_get_IHDR(png_ptr, info_ptr, &textureDt->width, &textureDt->height, &textureDt->bitDepth, &textureDt->colorType, NULL, NULL, NULL); + + // Handler de errores + if (setjmp(png_jmpbuf(png_ptr))) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + return NULL; + } + + /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, + * transparency chunks to full alpha channel; strip 16-bit-per-sample + * images to 8 bits per sample; and convert grayscale to RGB[A] */ + + if (textureDt->colorType == PNG_COLOR_TYPE_PALETTE) + png_set_expand(png_ptr); + if (textureDt->colorType == PNG_COLOR_TYPE_GRAY && textureDt->bitDepth < 8) + png_set_expand(png_ptr); + if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) + png_set_expand(png_ptr); + if (textureDt->bitDepth == 16) + png_set_strip_16(png_ptr); + if (textureDt->colorType == PNG_COLOR_TYPE_GRAY || + textureDt->colorType == PNG_COLOR_TYPE_GRAY_ALPHA) + png_set_gray_to_rgb(png_ptr); + + + // Reservo memoria para guardar la textura + png_read_update_info(png_ptr, info_ptr); + + unsigned int rowbytes = png_get_rowbytes(png_ptr, info_ptr); + textureDt->numberOfChannels = (int)png_get_channels(png_ptr, info_ptr); + textureDt->data = new unsigned char[rowbytes*textureDt->height]; + + if (textureDt->data == NULL) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + return NULL; + } + png_bytepp row_pointers; + if ((row_pointers = (png_bytepp)malloc(textureDt->height*sizeof(png_bytep))) == NULL) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + delete textureDt; + textureDt = NULL; + return NULL; + } + for (unsigned int i = 0; i < textureDt->height; ++i) + row_pointers[textureDt->height - i - 1] = textureDt->data + i*rowbytes; + + + // Leemos la imagen completa + png_read_image(png_ptr, row_pointers); + png_read_end(png_ptr, NULL); + + // Borramos la data intermedia y terminamos + free(row_pointers); + row_pointers = NULL; + + if (png_ptr && info_ptr) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + png_ptr = NULL; + info_ptr = NULL; + } + fclose(fp); + + return textureDt; +} + + + +void PngTextureLoader::writeTexture(string filename, TextureDataTransfer* textureDt) +{ + // Primero consigo la ruta completa del archivo + string fullFileName = WindowConnector::getBaseApplicationPath() + filename; + + // Creo el archivo y lo abro + FILE *fp = fopen(fullFileName.c_str(), "wb"); + if (!fp){ + throw new TextureLoadException("El archivo " + fullFileName + " no se puede abrir/crear para escritura"); + } + + // Inicializo todo + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!png_ptr){ + throw new TextureLoadException("Error preparando para escribir el archivo " + fullFileName); + } + + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr){ + throw new TextureLoadException("Error preparando para escribir el archivo " + fullFileName); + } + + if (setjmp(png_jmpbuf(png_ptr))){ + throw new TextureLoadException("Error preparando para escribir el archivo " + fullFileName); + } + + png_init_io(png_ptr, fp); + + + // Se escribe el header + if (setjmp(png_jmpbuf(png_ptr))){ + throw new TextureLoadException("Error al escribir el header del archivo " + fullFileName); + } + + png_set_IHDR(png_ptr, info_ptr, textureDt->width, textureDt->height, + textureDt->bitDepth, textureDt->colorType, PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + png_write_info(png_ptr, info_ptr); + + + // Se escriben los datos en si + if (setjmp(png_jmpbuf(png_ptr))){ + throw new TextureLoadException("Error en la escritura del archivo " + fullFileName); + } + + //Mapeo los datos en formato que espera libpng + png_bytepp row_pointers; + if ((row_pointers = (png_bytepp)malloc(textureDt->height*sizeof(png_bytep))) == NULL) { + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); + throw new TextureLoadException("No hay suficiente memoria principal para escribir el archivo " + fullFileName); + } + unsigned int rowbytes = textureDt->width * textureDt->numberOfChannels * (textureDt->bitDepth / 8); + for (unsigned int i = 0; i < textureDt->height; ++i){ + row_pointers[i] = textureDt->data + i*rowbytes; + } + + // Escribo el archivo + png_write_image(png_ptr, row_pointers); + + + // Se escribe el fin de archivo + if (setjmp(png_jmpbuf(png_ptr))){ + throw new TextureLoadException("Error terminando la escritura del archivo " + fullFileName); + } + + png_write_end(png_ptr, NULL); + fclose(fp); + + // Limpio la data temporal + if (png_ptr && info_ptr) { + png_destroy_write_struct(&png_ptr, &info_ptr); + png_ptr = NULL; + info_ptr = NULL; + } + free(row_pointers); +} + diff --git a/pool/shard001/C++/0017776_TCP_NSC_Connection.cc b/pool/shard001/C++/0017776_TCP_NSC_Connection.cc new file mode 100644 index 0000000000000000000000000000000000000000..836c7bd0045a2d9aa7095501127d1faa6cbaf68b --- /dev/null +++ b/pool/shard001/C++/0017776_TCP_NSC_Connection.cc @@ -0,0 +1,223 @@ +// +// Copyright (C) 2006 Sam Jansen, Andras Varga +// Copyright (C) 2009 Zoltan Bojthe +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// + +#include "inet/transportlayer/tcp_nsc/TCP_NSC_Connection.h" + +#include // NSC header +#include "inet/common/serializer/tcp/headers/tcphdr.h" +#include "inet/transportlayer/tcp_nsc/TCP_NSC.h" +#include "inet/transportlayer/tcp_nsc/queues/TCP_NSC_Queues.h" +#include "inet/transportlayer/contract/tcp/TCPCommand_m.h" +#include "inet/common/serializer/TCPIPchecksum.h" +#include "inet/transportlayer/tcp_common/TCPSegment.h" +#include "inet/common/serializer/tcp/TCPSerializer.h" + +#include +#include +#include + +namespace inet { + +namespace tcp { + +struct nsc_iphdr +{ +#if BYTE_ORDER == LITTLE_ENDIAN + unsigned int ihl : 4; + unsigned int version : 4; +#elif BYTE_ORDER == BIG_ENDIAN + unsigned int version : 4; + unsigned int ihl : 4; +#else // if BYTE_ORDER == LITTLE_ENDIAN +# error "Please check BYTE_ORDER declaration" +#endif // if BYTE_ORDER == LITTLE_ENDIAN + uint8_t tos; + uint16_t tot_len; + uint16_t id; + uint16_t frag_off; + uint8_t ttl; + uint8_t protocol; + uint16_t check; + uint32_t saddr; + uint32_t daddr; + /*The options start here. */ +} __attribute__((packed)); + +TCP_NSC_Connection::TCP_NSC_Connection() + : + connIdM(-1), + appGateIndexM(-1), + pNscSocketM(NULL), + sentEstablishedM(false), + onCloseM(false), + disconnectCalledM(false), + isListenerM(false), + tcpWinSizeM(65536), + tcpNscM(NULL), + receiveQueueM(NULL), + sendQueueM(NULL) +{ +} + +// create a TCP_I_ESTABLISHED msg +cMessage *TCP_NSC_Connection::createEstablishedMsg() +{ + if (sentEstablishedM) + return NULL; + + cMessage *msg = new cMessage("TCP_I_ESTABLISHED"); + msg->setKind(TCP_I_ESTABLISHED); + + TCPConnectInfo *tcpConnectInfo = new TCPConnectInfo(); + + tcpConnectInfo->setConnId(connIdM); + tcpConnectInfo->setLocalAddr(inetSockPairM.localM.ipAddrM); + tcpConnectInfo->setRemoteAddr(inetSockPairM.remoteM.ipAddrM); + tcpConnectInfo->setLocalPort(inetSockPairM.localM.portM); + tcpConnectInfo->setRemotePort(inetSockPairM.remoteM.portM); + + msg->setControlInfo(tcpConnectInfo); + //tcpMain->send(estmsg, "appOut", appGateIndex); + return msg; +} + +void TCP_NSC_Connection::connect(INetStack& stackP, SockPair& inetSockPairP, SockPair& nscSockPairP) +{ + ASSERT(!pNscSocketM); + pNscSocketM = stackP.new_tcp_socket(); + ASSERT(pNscSocketM); + + // TODO NSC not yet implements bind (for setting localport) + + ASSERT(sendQueueM); + ASSERT(receiveQueueM); + + sendQueueM->setConnection(this); + receiveQueueM->setConnection(this); + + onCloseM = false; + + pNscSocketM->connect(nscSockPairM.remoteM.ipAddrM.str().c_str(), nscSockPairM.remoteM.portM); + + struct sockaddr_in sockAddr; + size_t sockAddrLen = sizeof(sockAddr); + pNscSocketM->getsockname((sockaddr *)&sockAddr, &sockAddrLen); + nscSockPairP.localM.ipAddrM.set(IPv4Address(sockAddr.sin_addr.s_addr)); + nscSockPairP.localM.portM = ntohs(sockAddr.sin_port); +/* + // TODO: getpeername generate an assert!!! + pNscSocketM->getpeername((sockaddr*)&sockAddr, &sockAddrLen); + nscSockPairP.remoteM.ipAddrM.set(sockAddr.sin_addr.s_addr); + nscSockPairP.remoteM.portM = ntohs(sockAddr.sin_port); + */ +} + +void TCP_NSC_Connection::listen(INetStack& stackP, SockPair& inetSockPairP, SockPair& nscSockPairP) +{ + ASSERT(nscSockPairP.localM.portM != -1); + ASSERT(!pNscSocketM); + ASSERT(sendQueueM); + ASSERT(receiveQueueM); + + isListenerM = true; + pNscSocketM = stackP.new_tcp_socket(); + ASSERT(pNscSocketM); + + // TODO NSC not yet implements bind (for setting remote addr) + + sendQueueM->setConnection(this); + receiveQueueM->setConnection(this); + + onCloseM = false; + + pNscSocketM->listen(nscSockPairP.localM.portM); + + struct sockaddr_in sockAddr; + size_t sockAddrLen = sizeof(sockAddr); + pNscSocketM->getsockname((sockaddr *)&sockAddr, &sockAddrLen); + + nscSockPairP.localM.ipAddrM.set(IPv4Address(sockAddr.sin_addr.s_addr)); + nscSockPairP.localM.portM = ntohs(sockAddr.sin_port); + nscSockPairP.remoteM.ipAddrM = L3Address(); + nscSockPairP.remoteM.portM = -1; +} + +void TCP_NSC_Connection::send(cPacket *msgP) +{ + ASSERT(sendQueueM); + sendQueueM->enqueueAppData(msgP); +} + +void TCP_NSC_Connection::do_SEND() +{ + if (pNscSocketM) { + ASSERT(sendQueueM); + + char buffer[4096]; + int allsent = 0; + + while (1) { + int bytes = sendQueueM->getBytesForTcpLayer(buffer, sizeof(buffer)); + + if (0 == bytes) + break; + + int sent = pNscSocketM->send_data(buffer, bytes); + + if (sent > 0) { + sendQueueM->dequeueTcpLayerMsg(sent); + allsent += sent; + } + else { + EV_WARN << "TCP_NSC connection: " << connIdM << ": Error do sending, err is " << sent << "\n"; + break; + } + } + + EV_DEBUG << "do_SEND(): " << connIdM << " sent:" << allsent << ", unsent:" << sendQueueM->getBytesAvailable() << "\n"; + + if (onCloseM && sendQueueM->getBytesAvailable() == 0 && !disconnectCalledM) { + disconnectCalledM = true; + pNscSocketM->disconnect(); + cMessage *msg = new cMessage("CLOSED"); + msg->setKind(TCP_I_CLOSED); + TCPCommand *ind = new TCPCommand(); + ind->setConnId(connIdM); + msg->setControlInfo(ind); + tcpNscM->send(msg, "appOut", appGateIndexM); + //FIXME this connection never will be deleted, stayed in tcpNscM. Should delete later! + } + } +} + +void TCP_NSC_Connection::close() +{ + onCloseM = true; +} + +void TCP_NSC_Connection::abort() +{ + sendQueueM->dequeueTcpLayerMsg(sendQueueM->getBytesAvailable()); + close(); +} + +} // namespace tcp + +} // namespace inet + diff --git a/pool/shard001/C++/0017783_dirdlg.cpp b/pool/shard001/C++/0017783_dirdlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ea8bb06e121acca0b0b21cd64322489e10b035c --- /dev/null +++ b/pool/shard001/C++/0017783_dirdlg.cpp @@ -0,0 +1,144 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: dirdlg.cpp +// Purpose: wxDirDialog +// Author: Stefan Csomor +// Modified by: +// Created: 1998-01-01 +// RCS-ID: $Id: dirdlg.cpp,v 1.4 2005/07/28 22:08:21 VZ Exp $ +// Copyright: (c) Stefan Csomor +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +#ifdef __GNUG__ +#pragma implementation "dirdlg.h" +#endif + +#include "wx/defs.h" +#include "wx/utils.h" +#include "wx/dialog.h" +#include "wx/dirdlg.h" + +#include "wx/cmndata.h" + +#include "wx/mac/private.h" + +#ifdef __DARWIN__ + #include +#else + #include +#endif + +IMPLEMENT_CLASS(wxDirDialog, wxDialog) + +wxDirDialog::wxDirDialog(wxWindow *parent, + const wxString& message, + const wxString& defaultPath, + long style, + const wxPoint& WXUNUSED(pos), + const wxSize& WXUNUSED(size), + const wxString& WXUNUSED(name)) +{ + wxASSERT_MSG( NavServicesAvailable() , wxT("Navigation Services are not running") ) ; + m_message = message; + m_dialogStyle = style; + m_parent = parent; + m_path = defaultPath; +} + +int wxDirDialog::ShowModal() +{ + NavDialogOptions mNavOptions; + NavObjectFilterUPP mNavFilterUPP = NULL; + NavPreviewUPP mNavPreviewUPP = NULL ; + NavReplyRecord mNavReply; + AEDesc* mDefaultLocation = NULL ; + bool mSelectDefault = false ; + + ::NavGetDefaultDialogOptions(&mNavOptions); + + mNavFilterUPP = nil; + mNavPreviewUPP = nil; + mSelectDefault = false; + mNavReply.validRecord = false; + mNavReply.replacing = false; + mNavReply.isStationery = false; + mNavReply.translationNeeded = false; + mNavReply.selection.descriptorType = typeNull; + mNavReply.selection.dataHandle = nil; + mNavReply.keyScript = smSystemScript; + mNavReply.fileTranslation = nil; + + // Set default location, the location + // that's displayed when the dialog + // first appears + + if ( mDefaultLocation ) { + + if (mSelectDefault) { + mNavOptions.dialogOptionFlags |= kNavSelectDefaultLocation; + } else { + mNavOptions.dialogOptionFlags &= ~kNavSelectDefaultLocation; + } + } + + OSErr err = ::NavChooseFolder( + mDefaultLocation, + &mNavReply, + &mNavOptions, + NULL, + mNavFilterUPP, + 0L); // User Data + + if ( (err != noErr) && (err != userCanceledErr) ) { + m_path = wxT("") ; + return wxID_CANCEL ; + } + + if (mNavReply.validRecord) { // User chose a folder + + FSSpec folderInfo; + FSSpec outFileSpec ; + AEDesc specDesc ; + + OSErr err = ::AECoerceDesc( &mNavReply.selection , typeFSS, &specDesc); + if ( err != noErr ) { + m_path = wxT("") ; + return wxID_CANCEL ; + } + folderInfo = **(FSSpec**) specDesc.dataHandle; + if (specDesc.dataHandle != nil) { + ::AEDisposeDesc(&specDesc); + } + +// mNavReply.GetFileSpec(folderInfo); + + // The FSSpec from NavChooseFolder is NOT the file spec + // for the folder. The parID field is actually the DirID + // of the folder itself, not the folder's parent, and + // the name field is empty. We must call PBGetCatInfo + // to get the parent DirID and folder name + + Str255 name; + CInfoPBRec thePB; // Directory Info Parameter Block + thePB.dirInfo.ioCompletion = nil; + thePB.dirInfo.ioVRefNum = folderInfo.vRefNum; // Volume is right + thePB.dirInfo.ioDrDirID = folderInfo.parID; // Folder's DirID + thePB.dirInfo.ioNamePtr = name; + thePB.dirInfo.ioFDirIndex = -1; // Lookup using Volume and DirID + + err = ::PBGetCatInfoSync(&thePB); + if ( err != noErr ) { + m_path = wxT("") ; + return wxID_CANCEL ; + } + // Create cannonical FSSpec + ::FSMakeFSSpec(thePB.dirInfo.ioVRefNum, thePB.dirInfo.ioDrParID, + name, &outFileSpec); + + // outFolderDirID = thePB.dirInfo.ioDrDirID; + m_path = wxMacFSSpec2MacFilename( &outFileSpec ) ; + return wxID_OK ; + } + return wxID_CANCEL; +} + diff --git a/pool/shard001/C++/0017785_autobaud.cpp b/pool/shard001/C++/0017785_autobaud.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f414863acbb1faff127ef6b7b55931d7dfb9e85 --- /dev/null +++ b/pool/shard001/C++/0017785_autobaud.cpp @@ -0,0 +1,30 @@ +#include +#include "defines.h" + +/* Attempts to determine the baud rate using the autobaud feature in the CAN peripheral */ +void autobaud(CANRaw *device) +{ + uint32_t reg_val; + + device->disable(); + device->enable_autobaud_listen_mode(); + + for(int i = 1; i < NUM_BAUD_RATES; i++) + { + device->init(baud_rates_table[i]); + delay(10); + reg_val = device->get_status(); + + // Check that the status register indicates that the bus is running and no errors + if(((reg_val & 0xFFFFFF00) != 0) && ((reg_val & 0x0F000000) == 0)) + { + char baud_msg[128]; + sprintf(baud_msg, "Found baudrate: %4dKBPS", baud_rates_table[i] / 1000); + log(baud_msg, 24); + device->disable_autobaud_listen_mode(); + break; + } + } +} + + diff --git a/pool/shard001/C++/0017789_poj_1269_Intersecting_Lines.cpp b/pool/shard001/C++/0017789_poj_1269_Intersecting_Lines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e51846f97afdf9bf393f174e5b582b5c8616aa0 --- /dev/null +++ b/pool/shard001/C++/0017789_poj_1269_Intersecting_Lines.cpp @@ -0,0 +1,109 @@ +//Fri Mar 11 20:27:29 CST 2011 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +const double ERR = 0.000001; + +/* + * ax + by = c + * + */ +class Line +{ +public: + double a; + double b; + double c; + + Line(double x1, double y1, double x2, double y2) + { + if (x1 != x2 && y1 == y2) + { + a = 0.0; + b = 1.0; + c = y1; + } + else if (x1 == x2 && y1 != y2) + { + a = 1.0; + b = 0.0; + c = x1; + } + else + { + a = (y1 - y2) / (x1 - x2); + b = -1.0; + c = x1 * (y2 - y1) / (x2 - x1) - y1; + } + } + + void check(Line other) + { + //Same slope; + if (fabs(this->a * other.b - this->b * other.a) <= ERR) + { + + if ((fabs(this->a * other.c - other.a * this->c) <= ERR) && (fabs(other.c * this->b - this->c * other.b) <= ERR)) + { + cout << "LINE" << endl; + return; + } + else + { + cout << "NONE" << endl; + return; + } + } + double x = (this->c * other.b - other.c * this->b) / (this->a * other.b - other.a * this->b); + double y = (this->c * other.a - other.c * this->a) / (other.a * this->b - this->a * other.b); + cout << setiosflags(ios::fixed) << setprecision(2) << "POINT " << setprecision(2) << x << " " << y << endl; + return; + } +}; + +int main(int argc, const char* argv[]) +{ + //freopen("input.in", "r", stdin); + //freopen("output.out", "w", stdout); + cout << "INTERSECTING LINES OUTPUT" << endl; + int N; + cin >> N; + while (N--) + { + double x1, x2, x3, x4; + double y1, y2, y3, y4; + cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4; + Line a(x1, y1, x2, y2); + Line b(x3, y3, x4, y4); + a.check(b); + } + cout << "END OF OUTPUT" << endl; + //fclose(stdin); + //fclose(stdout); + return 0; +} diff --git a/pool/shard001/C++/0017790_audio_buffer.cc b/pool/shard001/C++/0017790_audio_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..8b2d5c744f116310f24d9453ae9da02b2a3f2547 --- /dev/null +++ b/pool/shard001/C++/0017790_audio_buffer.cc @@ -0,0 +1,70 @@ +/* + Copyright (C) 2006-2007 Paul Davis + + 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 + +#include "ardour/audio_buffer.h" +#include "pbd/error.h" +#include "pbd/malign.h" + +#include "i18n.h" + +using namespace PBD; +using namespace ARDOUR; + +AudioBuffer::AudioBuffer(size_t capacity) + : Buffer(DataType::AUDIO, capacity) + , _owns_data (false) + , _data (0) +{ + if (_capacity > 0) { + _owns_data = true; // prevent resize() from gagging + resize (_capacity); + _silent = false; // force silence on the intial buffer state + silence (_capacity); + } +} + +AudioBuffer::~AudioBuffer() +{ + if (_owns_data) + free(_data); +} + +void +AudioBuffer::resize (size_t size) +{ + if (!_owns_data) { + return; + } + + if (size < _capacity) { + _size = size; + return; + } + + free (_data); + + _capacity = size; + _size = size; + _silent = false; + + cache_aligned_malloc ((void**) &_data, sizeof (Sample) * _capacity); +} + + diff --git a/pool/shard001/C++/0017812_IfcLogger.cpp b/pool/shard001/C++/0017812_IfcLogger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaf731fd45ad7041d91480d12c5becad569f5859 --- /dev/null +++ b/pool/shard001/C++/0017812_IfcLogger.cpp @@ -0,0 +1,73 @@ +/******************************************************************************** + * * + * This file is part of IfcOpenShell. * + * * + * IfcOpenShell is free software: you can redistribute it and/or modify * + * it under the terms of the Lesser GNU General Public License as published by * + * the Free Software Foundation, either version 3.0 of the License, or * + * (at your option) any later version. * + * * + * IfcOpenShell 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 * + * Lesser GNU General Public License for more details. * + * * + * You should have received a copy of the Lesser GNU General Public License * + * along with this program. If not, see . * + * * + ********************************************************************************/ + +#include "IfcLogger.h" +#include "../ifcparse/IfcException.h" + +#include +#include + +#include +#include + + +void Logger::SetProduct(boost::optional product) { + current_product = product; +} +void Logger::SetOutput(std::ostream* l1, std::ostream* l2) { + log1 = l1; + log2 = l2; + if ( ! log2 ) { + log2 = &log_stream; + } +} +void Logger::Message(Logger::Severity type, const std::string& message, IfcAbstractEntity* entity) { + if ( log2 && type >= verbosity ) { + (*log2) << "[" << severity_strings[type] << "] "; + if ( current_product ) { + (*log2) << "{" << (*current_product)->GlobalId() << "} "; + } + (*log2) << message << std::endl; + if ( entity ) (*log2) << entity->toString() << std::endl; + } +} +void Logger::Status(const std::string& message, bool new_line) { + if ( log1 ) { + (*log1) << message; + if ( new_line ) (*log1) << std::endl; + else (*log1) << std::flush; + } +} +void Logger::ProgressBar(int progress) { + if ( log1 ) { + Status("\r[" + std::string(progress,'#') + std::string(50 - progress,' ') + "]", false); + } +} +std::string Logger::GetLog() { + return log_stream.str(); +} +void Logger::Verbosity(Logger::Severity v) { verbosity = v; } +Logger::Severity Logger::Verbosity() { return verbosity; } + +std::ostream* Logger::log1 = 0; +std::ostream* Logger::log2 = 0; +std::stringstream Logger::log_stream; +Logger::Severity Logger::verbosity = Logger::LOG_NOTICE; +const char* Logger::severity_strings[] = { "Notice","Warning","Error" }; +boost::optional Logger::current_product; \ No newline at end of file diff --git a/pool/shard001/C++/0017828_LifecycleContextTest.cpp b/pool/shard001/C++/0017828_LifecycleContextTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f29b9a3888c4d6b80c5cddfaea48b5b521d19652 --- /dev/null +++ b/pool/shard001/C++/0017828_LifecycleContextTest.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2013 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: + * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "platform/LifecycleNotifier.h" +#include "platform/LifecycleObserver.h" +#include "platform/heap/Handle.h" +#include + +namespace blink { + +class TestingObserver; + +class DummyContext final : public NoBaseWillBeGarbageCollectedFinalized, public LifecycleNotifier { + WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(DummyContext); +public: + static PassOwnPtrWillBeRawPtr create() + { + return adoptPtrWillBeNoop(new DummyContext()); + } + + DEFINE_INLINE_TRACE() + { + LifecycleNotifier::trace(visitor); + } +}; + +class TestingObserver final : public NoBaseWillBeGarbageCollectedFinalized, public LifecycleObserver { + WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(TestingObserver); +public: + static PassOwnPtrWillBeRawPtr create(DummyContext* context) + { + return adoptPtrWillBeNoop(new TestingObserver(context)); + } + + void contextDestroyed() override + { + LifecycleObserver::contextDestroyed(); + if (m_observerToRemoveOnDestruct) { + lifecycleContext()->removeObserver(m_observerToRemoveOnDestruct.get()); + m_observerToRemoveOnDestruct.clear(); + } + m_contextDestroyedCalled = true; + } + + DEFINE_INLINE_TRACE() + { + visitor->trace(m_observerToRemoveOnDestruct); + LifecycleObserver::trace(visitor); + } + + void unobserve() { setContext(nullptr); } + + void setObserverToRemoveAndDestroy(PassOwnPtrWillBeRawPtr observerToRemoveOnDestruct) + { + ASSERT(!m_observerToRemoveOnDestruct); + m_observerToRemoveOnDestruct = observerToRemoveOnDestruct; + } + + TestingObserver* innerObserver() const { return m_observerToRemoveOnDestruct.get(); } + bool contextDestroyedCalled() const { return m_contextDestroyedCalled; } + +private: + explicit TestingObserver(DummyContext* context) + : LifecycleObserver(context) + , m_contextDestroyedCalled(false) + { + } + + OwnPtrWillBeMember m_observerToRemoveOnDestruct; + bool m_contextDestroyedCalled; +}; + +TEST(LifecycleContextTest, shouldObserveContextDestroyed) +{ + OwnPtrWillBeRawPtr context = DummyContext::create(); + OwnPtrWillBePersistent observer = TestingObserver::create(context.get()); + + EXPECT_EQ(observer->lifecycleContext(), context.get()); + EXPECT_FALSE(observer->contextDestroyedCalled()); + context->notifyContextDestroyed(); + context = nullptr; + Heap::collectAllGarbage(); + EXPECT_EQ(observer->lifecycleContext(), static_cast(0)); + EXPECT_TRUE(observer->contextDestroyedCalled()); +} + +TEST(LifecycleContextTest, shouldNotObserveContextDestroyedIfUnobserve) +{ + OwnPtrWillBeRawPtr context = DummyContext::create(); + OwnPtrWillBePersistent observer = TestingObserver::create(context.get()); + observer->unobserve(); + context->notifyContextDestroyed(); + context = nullptr; + Heap::collectAllGarbage(); + EXPECT_EQ(observer->lifecycleContext(), static_cast(0)); + EXPECT_FALSE(observer->contextDestroyedCalled()); +} + +TEST(LifecycleContextTest, observerRemovedDuringNotifyDestroyed) +{ + // FIXME: Oilpan: this test can be removed when the LifecycleNotifier::m_observers + // hash set is on the heap and membership is handled implicitly by the garbage collector. + OwnPtrWillBeRawPtr context = DummyContext::create(); + OwnPtrWillBePersistent observer = TestingObserver::create(context.get()); + OwnPtrWillBeRawPtr innerObserver = TestingObserver::create(context.get()); + // Attach the observer to the other. When 'observer' is notified + // of destruction, it will remove & destroy 'innerObserver'. + observer->setObserverToRemoveAndDestroy(innerObserver.release()); + + EXPECT_EQ(observer->lifecycleContext(), context.get()); + EXPECT_EQ(observer->innerObserver()->lifecycleContext(), context.get()); + EXPECT_FALSE(observer->contextDestroyedCalled()); + EXPECT_FALSE(observer->innerObserver()->contextDestroyedCalled()); + + context->notifyContextDestroyed(); + EXPECT_EQ(observer->innerObserver(), nullptr); + context = nullptr; + Heap::collectAllGarbage(); + EXPECT_EQ(observer->lifecycleContext(), static_cast(0)); + EXPECT_TRUE(observer->contextDestroyedCalled()); +} + +} // namespace blink diff --git a/pool/shard001/C++/0017831_dir_list_ci.cpp b/pool/shard001/C++/0017831_dir_list_ci.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb939dadb88f48eed9297cbfaf4ced743ebdc62b --- /dev/null +++ b/pool/shard001/C++/0017831_dir_list_ci.cpp @@ -0,0 +1,113 @@ +#include "dir_list_ci.h" + +#include "../DirManager/dirman.h" +#include "strings.h" +#include + + +DirListCI::DirListCI(const std::string &curDir) + : m_curDir(curDir) +{ + rescan(); +} + +void DirListCI::setCurDir(const std::string &path) +{ + m_curDir = path; + rescan(); +} + +static void replaceSlashes(std::string &str, const std::string &from) +{ + str.clear(); + if(from.empty()) + return; + + str.reserve(from.size()); + + char prevC = '\0'; + + for(char c : from) + { + if(c == '\\') + c = '/'; // Replace backslashes + if(c == '/' && prevC == '/') + continue; // skip duplicated slashes + prevC = c; + str.push_back(c); + } +} + +std::string DirListCI::resolveFileCase(const std::string &in_name) +{ +#if 0 //def _WIN32 + std::string name; + replaceSlashes(name, in_name); + return name; +#else + if(in_name.empty()) + return in_name; + + std::string name; + replaceSlashes(name, in_name); + + // For sub-directory path, look deeply + auto subDir = name.find('/'); + if(subDir != std::string::npos) + { + auto sdName = resolveDirCase(name.substr(0, subDir)); + DirListCI sd(m_curDir + "/" + sdName); + return sdName + "/" + sd.resolveFileCase(name.substr(subDir + 1)); + } + + // keep MixerX path arguments untouched + auto pathArgs = name.find('|'); + if(pathArgs != std::string::npos) + { + auto n = name.substr(0, pathArgs); + for(std::string &c : m_fileList) + { + if(SDL_strcasecmp(c.c_str(), n.c_str()) == 0) + return c + name.substr(pathArgs); + } + } + else + for(std::string &c : m_fileList) + { + if(SDL_strcasecmp(c.c_str(), name.c_str()) == 0) + return c; + } + + return name; +#endif +} + +std::string DirListCI::resolveDirCase(const std::string &name) +{ +#if 0 //def _WIN32 + return name; // no need on Windows +#else + if(name.empty()) + return name; + + for(std::string &c : m_dirList) + { + if(SDL_strcasecmp(c.c_str(), name.c_str()) == 0) + return c; + } + + return name; +#endif +} + +void DirListCI::rescan() +{ + m_fileList.clear(); + m_dirList.clear(); + if(m_curDir.empty()) + return; + + DirMan d(m_curDir); + d.getListOfFiles(m_fileList); + d.getListOfFolders(m_dirList); +} diff --git a/pool/shard001/C++/0017833_item_vers.cc b/pool/shard001/C++/0017833_item_vers.cc new file mode 100644 index 0000000000000000000000000000000000000000..8aa1321e396265d642597107e1efcf03583f2870 --- /dev/null +++ b/pool/shard001/C++/0017833_item_vers.cc @@ -0,0 +1,182 @@ +/* Copyright (c) 2017, MariaDB Corporation. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ + + +/** + @brief + System Versioning items +*/ + +#include "mariadb.h" +#include "sql_priv.h" + +#include "sql_class.h" +#include "tztime.h" +#include "item.h" + +Item_func_vtq_ts::Item_func_vtq_ts(THD *thd, Item* a, TR_table::field_id_t _vtq_field) : + Item_datetimefunc(thd, a), + vtq_field(_vtq_field) +{ + decimals= 6; + null_value= true; + DBUG_ASSERT(arg_count == 1 && args[0]); +} + + +bool +Item_func_vtq_ts::get_date(MYSQL_TIME *res, ulonglong fuzzy_date) +{ + THD *thd= current_thd; // can it differ from constructor's? + DBUG_ASSERT(thd); + DBUG_ASSERT(args[0]); + if (args[0]->result_type() != INT_RESULT) + { + my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0), + args[0]->type_handler()->name().ptr(), + func_name()); + return true; + } + ulonglong trx_id= args[0]->val_uint(); + if (trx_id == ULONGLONG_MAX) + { + null_value= false; + thd->variables.time_zone->gmt_sec_to_TIME(res, TIMESTAMP_MAX_VALUE); + res->second_part= TIME_MAX_SECOND_PART; + return false; + } + + TR_table trt(thd); + + null_value= !trt.query(trx_id); + if (null_value) + { + my_error(ER_VERS_NO_TRX_ID, MYF(0), trx_id); + return true; + } + + return trt[vtq_field]->get_date(res, fuzzy_date); +} + + +Item_func_vtq_id::Item_func_vtq_id(THD *thd, Item* a, TR_table::field_id_t _vtq_field, + bool _backwards) : + Item_longlong_func(thd, a), + vtq_field(_vtq_field), + backwards(_backwards) +{ + decimals= 0; + unsigned_flag= 1; + null_value= true; + DBUG_ASSERT(arg_count == 1 && args[0]); +} + +Item_func_vtq_id::Item_func_vtq_id(THD *thd, Item* a, Item* b, TR_table::field_id_t _vtq_field) : + Item_longlong_func(thd, a, b), + vtq_field(_vtq_field), + backwards(false) +{ + decimals= 0; + unsigned_flag= 1; + null_value= true; + DBUG_ASSERT(arg_count == 2 && args[0] && args[1]); +} + +longlong +Item_func_vtq_id::get_by_trx_id(ulonglong trx_id) +{ + THD *thd= current_thd; + DBUG_ASSERT(thd); + + if (trx_id == ULONGLONG_MAX) + { + null_value= true; + return 0; + } + + TR_table trt(thd); + null_value= !trt.query(trx_id); + if (null_value) + return 0; + + return trt[vtq_field]->val_int(); +} + +longlong +Item_func_vtq_id::get_by_commit_ts(MYSQL_TIME &commit_ts, bool backwards) +{ + THD *thd= current_thd; + DBUG_ASSERT(thd); + + TR_table trt(thd); + null_value= !trt.query(commit_ts, backwards); + if (null_value) + return 0; + + return trt[vtq_field]->val_int(); +} + +longlong +Item_func_vtq_id::val_int() +{ + if (args[0]->is_null()) + { + if (arg_count < 2 || vtq_field == TR_table::FLD_TRX_ID) + { + null_value= true; + return 0; + } + return get_by_trx_id(args[1]->val_uint()); + } + else + { + MYSQL_TIME commit_ts; + if (args[0]->get_date(&commit_ts, 0)) + { + null_value= true; + return 0; + } + if (arg_count > 1) + { + backwards= args[1]->val_bool(); + DBUG_ASSERT(arg_count == 2); + } + return get_by_commit_ts(commit_ts, backwards); + } +} + +Item_func_vtq_trx_sees::Item_func_vtq_trx_sees(THD *thd, Item* a, Item* b) : + Item_bool_func(thd, a, b), + accept_eq(false) +{ + null_value= true; + DBUG_ASSERT(arg_count == 2 && args[0] && args[1]); +} + +longlong +Item_func_vtq_trx_sees::val_int() +{ + THD *thd= current_thd; + DBUG_ASSERT(thd); + + DBUG_ASSERT(arg_count > 1); + ulonglong trx_id1= args[0]->val_uint(); + ulonglong trx_id0= args[1]->val_uint(); + bool result= accept_eq; + + TR_table trt(thd); + null_value= trt.query_sees(result, trx_id1, trx_id0); + return result; +} diff --git a/pool/shard001/C++/0017837_DeleteAttributesRequest.cpp b/pool/shard001/C++/0017837_DeleteAttributesRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32e3baa8f01c910a29d703fb176c265fb1a51fa3 --- /dev/null +++ b/pool/shard001/C++/0017837_DeleteAttributesRequest.cpp @@ -0,0 +1,65 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file 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 + +using namespace Aws::ECS::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +DeleteAttributesRequest::DeleteAttributesRequest() : + m_clusterHasBeenSet(false), + m_attributesHasBeenSet(false) +{ +} + +Aws::String DeleteAttributesRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_clusterHasBeenSet) + { + payload.WithString("cluster", m_cluster); + + } + + if(m_attributesHasBeenSet) + { + Array attributesJsonList(m_attributes.size()); + for(unsigned attributesIndex = 0; attributesIndex < attributesJsonList.GetLength(); ++attributesIndex) + { + attributesJsonList[attributesIndex].AsObject(m_attributes[attributesIndex].Jsonize()); + } + payload.WithArray("attributes", std::move(attributesJsonList)); + + } + + return payload.WriteReadable(); +} + +Aws::Http::HeaderValueCollection DeleteAttributesRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DeleteAttributes")); + return headers; + +} + + + + diff --git a/pool/shard001/C++/0017850_main.cpp b/pool/shard001/C++/0017850_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c49dc1d4470e23c64e9d3a7e771c88ceb8cce056 --- /dev/null +++ b/pool/shard001/C++/0017850_main.cpp @@ -0,0 +1,100 @@ +/* + * File: begin_adventure.cpp + * Author: Michael Ryan + * + * Created on August 1, 2014, 9:10 PM + */ + +#include +#include +#include +#include +#include +#include +#include +//#include +#include "begin_adventure.h" + +using namespace std; + + +int main() { + + system("pause"); // press any key to continue + string Menu[3] = {"Start Game", "Continue", "Exit"}; + int pointer = 1; + + while (true) { + system("cls"); + + cout << " ***************************************************\n"; + cout << " * *\n"; + cout << " * Forest of the Dark Things That Hurt Good People *\n"; + cout << " * FotDTTHGP *\n"; + cout << " * Main Menu *\n"; + cout << " ***************************************************\n"; + // windows header file function to establish menu that can be + // navigated by arrow keys + SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15); + + for (int i = 0; i < 3; ++i) { + if (i == pointer) { + SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11); + cout << Menu[i] << endl; + } else { + SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15); + cout << Menu[i] << endl; + } + } + + while (true) { // loop until a selection is made + if (GetAsyncKeyState(VK_UP) != 0) { + pointer -= 1; + if (pointer == -1) { + pointer = 2; + } + break; + } else if (GetAsyncKeyState(VK_DOWN) != 0) { + pointer += 1; + if (pointer == 3) { + pointer = 0; + } + break; + } else if (GetAsyncKeyState(VK_RETURN) != 0) { + switch (pointer) { + case 0: { + cout << "Start new game?"; + Sleep(1000); +// pause(); + begin_adventure(); + } break; + case 1: { + cout << "\n\n\nNo file saved..."; + Sleep(1000); + } break; + case 2: { + cout << "\n\n\n Exit the game..."; + return 0; + } break; + } + break; + } + } + Sleep(150); + } + return 0; +} + + +// + +/** + Notes: To compile and run: + * 1. Navigate in your command prompt to the folder that contains the project files. + * 2. type "g++ main.cpp -o "name of executable" + * Ex. + * cd Documents\GitHub\mrd\dailey-bros\Dailey Bros + * g++ main.cpp -o main + * 3. Then type the name of the executable to run. + * + */ \ No newline at end of file diff --git a/pool/shard001/C++/0017853_tsodyks_connection.cpp b/pool/shard001/C++/0017853_tsodyks_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cfc9e57038d9b88ce8ee32fe7220b237acb2eef --- /dev/null +++ b/pool/shard001/C++/0017853_tsodyks_connection.cpp @@ -0,0 +1,148 @@ +/* + * tsodyks_connection.cpp + * + * This file is part of NEST. + * + * Copyright (C) 2004 The NEST Initiative + * + * NEST 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. + * + * NEST 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 NEST. If not, see . + * + */ + +#include "tsodyks_connection.h" +#include "network.h" +#include "connector_model.h" + +namespace nest +{ + + TsodyksConnection::TsodyksConnection() : + ConnectionHetWD(), + tau_psc_(3.0), + tau_fac_(0.0), + tau_rec_(800.0), + U_(0.5), + x_(1.0), + y_(0.0), + u_(0.0) + { } + + void TsodyksConnection::get_status(DictionaryDatum & d) const + { + ConnectionHetWD::get_status(d); + + def(d, "U", U_); + def(d, "tau_psc", tau_psc_); + def(d, "tau_rec", tau_rec_); + def(d, "tau_fac", tau_fac_); + def(d, "x", x_); + def(d, "y", y_); + def(d, "u", u_); + } + + void TsodyksConnection::set_status(const DictionaryDatum & d, ConnectorModel &cm) + { + ConnectionHetWD::set_status(d, cm); + + updateValue(d, "U", U_); + updateValue(d, "tau_psc", tau_psc_); + updateValue(d, "tau_rec", tau_rec_); + updateValue(d, "tau_fac", tau_fac_); + + double_t x = x_; + double_t y = y_; + updateValue(d, "x", x); + updateValue(d, "y", y); + + if (x + y > 1.0) + { + cm.network().message(SLIInterpreter::M_ERROR, + "TsodyksConnection::set_status()", "x + y must be <= 1.0."); + throw BadProperty(); + } + else + { + x_ = x; + y_ = y; + } + + updateValue(d, "u", u_); + } + + /** + * Set properties of this connection from position p in the properties + * array given in dictionary. + */ + void TsodyksConnection::set_status(const DictionaryDatum & d, index p, ConnectorModel &cm) + { + ConnectionHetWD::set_status(d, p, cm); + + set_property(d, "Us", p, U_); + set_property(d, "tau_pscs", p, tau_psc_); + set_property(d, "tau_facs", p, tau_fac_); + set_property(d, "tau_recs", p, tau_rec_); + + + double_t x = x_; + double_t y = y_; + set_property(d, "xs", p, x); + set_property(d, "ys", p, y); + + if (x + y > 1.0) + { + cm.network().message(SLIInterpreter::M_ERROR, + "TsodyksConnection::set_status()", + "x + y must be <= 1.0."); + throw BadProperty(); + } + else + { + x_ = x; + y_ = y; + } + + set_property(d, "us", p, u_); + } + + void TsodyksConnection::initialize_property_arrays(DictionaryDatum & d) const + { + ConnectionHetWD::initialize_property_arrays(d); + + initialize_property_array(d, "Us"); + initialize_property_array(d, "tau_pscs"); + initialize_property_array(d, "tau_facs"); + initialize_property_array(d, "tau_recs"); + initialize_property_array(d, "xs"); + initialize_property_array(d, "ys"); + initialize_property_array(d, "us"); + } + + /** + * Append properties of this connection to the given dictionary. If the + * dictionary is empty, new arrays are created first. + */ + void TsodyksConnection::append_properties(DictionaryDatum & d) const + { + ConnectionHetWD::append_properties(d); + + append_property(d, "Us", U_); + append_property(d, "tau_pscs", tau_psc_); + append_property(d, "tau_facs", tau_fac_); + append_property(d, "tau_recs", tau_rec_); + append_property(d, "xs", x_); + append_property(d, "ys", y_); + append_property(d, "us", u_); + } + +} // of namespace nest diff --git a/pool/shard001/C++/0017856_bspline.cc b/pool/shard001/C++/0017856_bspline.cc new file mode 100644 index 0000000000000000000000000000000000000000..491b64bdaeabac730f0111d104aa01255ff689fc --- /dev/null +++ b/pool/shard001/C++/0017856_bspline.cc @@ -0,0 +1,80 @@ +#include "bspline.h" + + +BSpline::BSpline() + : Curve3D() +{ + setOrder(4); + m_knots.clear(); +} + +void BSpline::build() +{ + float max = float(m_basePoints.size() - m_order + 2); + int size = int(max / m_step); + if (max - m_step * size >= 0.5f * m_step) { + ++size; + } + m_step = max / size; + + m_data.clear(); + m_data.resize(size + 1); + + calculateKnots(); + + for (int i = 0; i < size + 1; ++i) { + QVector3D tmp(0.0f, 0.0f, 0.0f); + float sum = 0.0f; + float u = m_step * i; + if (u > max) { + u = max; + } + for (int j = 0; j < m_basePoints.size(); ++j) { + float n = calculateN(j, m_order, u); + tmp += m_basePoints[j] * n; + sum += n; + } + m_data[i] = tmp / sum; // WARNING if (sum == 0.0f) ??? + } +} + +void BSpline::calculateKnots() +{ + int k = m_order; + int n = m_basePoints.size(); + m_knots.clear(); + m_knots.resize(k + n); + + for (int i = 0; i < k + n; ++i) { + if (i < k) { + m_knots[i] = 0.0f; + } else if (k <= i && i < n) { + m_knots[i] = float(i - k + 1); + } else { + m_knots[i] = float(n - k + 2); + } + } +} + +float BSpline::calculateN(int i, int n, float u) +{ + assert(i >= 0); + assert(i < m_knots.size() - 1); + assert(n >= 0); + assert(i + n < m_knots.size()); + + if (n == 1) { + if (m_knots[i] <= u && u <= m_knots[i + 1]) { + return 1; + } + return 0; + } + + float a = m_knots[i + n] - m_knots[i]; + if (std::fabs(a) > std::numeric_limits::epsilon()) { + float A = calculateN(i, n - 1, u) * (u - m_knots[i]) / a; + float B = calculateN(i + 1, n - 1, u) * (m_knots[i + n] - u) / a; + return A + B; + } + return 0.0f; +} diff --git a/pool/shard001/C++/0017860_translator_test_ref_ptr_library_child_ctocpp.cc b/pool/shard001/C++/0017860_translator_test_ref_ptr_library_child_ctocpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..4917e02784b4805cd1a212a92efefc25d9509420 --- /dev/null +++ b/pool/shard001/C++/0017860_translator_test_ref_ptr_library_child_ctocpp.cc @@ -0,0 +1,119 @@ +// Copyright (c) 2017 The Chromium Embedded Framework 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 was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_ctocpp.h" +#include "libcef_dll/ctocpp/test/translator_test_ref_ptr_library_child_child_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefTranslatorTestRefPtrLibraryChild::Create( + int value, int other_value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_translator_test_ref_ptr_library_child_t* _retval = + cef_translator_test_ref_ptr_library_child_create( + value, + other_value); + + // Return type: refptr_same + return CefTranslatorTestRefPtrLibraryChildCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +int CefTranslatorTestRefPtrLibraryChildCToCpp::GetOtherValue() { + cef_translator_test_ref_ptr_library_child_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, get_other_value)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = _struct->get_other_value(_struct); + + // Return type: simple + return _retval; +} + +void CefTranslatorTestRefPtrLibraryChildCToCpp::SetOtherValue(int value) { + cef_translator_test_ref_ptr_library_child_t* _struct = GetStruct(); + if (CEF_MEMBER_MISSING(_struct, set_other_value)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + _struct->set_other_value(_struct, + value); +} + +int CefTranslatorTestRefPtrLibraryChildCToCpp::GetValue() { + cef_translator_test_ref_ptr_library_t* _struct = + reinterpret_cast(GetStruct()); + if (CEF_MEMBER_MISSING(_struct, get_value)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = _struct->get_value(_struct); + + // Return type: simple + return _retval; +} + +void CefTranslatorTestRefPtrLibraryChildCToCpp::SetValue(int value) { + cef_translator_test_ref_ptr_library_t* _struct = + reinterpret_cast(GetStruct()); + if (CEF_MEMBER_MISSING(_struct, set_value)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + _struct->set_value(_struct, + value); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefTranslatorTestRefPtrLibraryChildCToCpp::CefTranslatorTestRefPtrLibraryChildCToCpp( + ) { +} + +template<> cef_translator_test_ref_ptr_library_child_t* CefCToCppRefCounted::UnwrapDerived( + CefWrapperType type, CefTranslatorTestRefPtrLibraryChild* c) { + if (type == WT_TRANSLATOR_TEST_REF_PTR_LIBRARY_CHILD_CHILD) { + return reinterpret_cast( + CefTranslatorTestRefPtrLibraryChildChildCToCpp::Unwrap( + reinterpret_cast(c))); + } + NOTREACHED() << "Unexpected class type: " << type; + return NULL; +} + +#if DCHECK_IS_ON() +template<> base::AtomicRefCount CefCToCppRefCounted::DebugObjCt = 0; +#endif + +template<> CefWrapperType CefCToCppRefCounted::kWrapperType = + WT_TRANSLATOR_TEST_REF_PTR_LIBRARY_CHILD; diff --git a/pool/shard001/C++/0017861_UdpClient.cpp b/pool/shard001/C++/0017861_UdpClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fad6579df6e518a51eb0d849e66a5a209d0cd4c --- /dev/null +++ b/pool/shard001/C++/0017861_UdpClient.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2005-2012 Team XBMC + * http://www.xbmc.org + * + * 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 XBMC; see the file COPYING. If not, see + * . + * + */ + +#include "threads/SystemClock.h" +#include "UdpClient.h" +#ifdef _LINUX +#include +#endif +#include "Network.h" +#include "guilib/GraphicContext.h" +#include "utils/log.h" +#include "utils/TimeUtils.h" + +#include "threads/SingleLock.h" + +#include + +#define UDPCLIENT_DEBUG_LEVEL LOGDEBUG + +CUdpClient::CUdpClient(void) : CThread("CUdpClient") +{} + +CUdpClient::~CUdpClient(void) +{ +} + +bool CUdpClient::Create(void) +{ + m_bStop = false; + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Creating UDP socket..."); + + // Create a UDP socket + client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (client_socket == SOCKET_ERROR) + { + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Unable to create socket."); + return false; + } + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Setting broadcast socket option..."); + + unsigned int value = 1; + if ( setsockopt( client_socket, SOL_SOCKET, SO_BROADCAST, (char*) &value, sizeof( unsigned int ) ) == SOCKET_ERROR) + { + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Unable to set socket option."); + return false; + } + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Setting non-blocking socket options..."); + + unsigned long nonblocking = 1; + ioctlsocket(client_socket, FIONBIO, &nonblocking); + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Spawning listener thread..."); + CThread::Create(false, THREAD_MINSTACKSIZE); + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Ready."); + + return true; +} + +void CUdpClient::Destroy() +{ + StopThread(); + closesocket(client_socket); +} + +void CUdpClient::OnStartup() +{ + SetPriority( GetMinPriority() ); +} + +bool CUdpClient::Broadcast(int aPort, CStdString& aMessage) +{ + CSingleLock lock(critical_section); + + SOCKADDR_IN addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(aPort); + addr.sin_addr.s_addr = INADDR_BROADCAST; + memset(&addr.sin_zero, 0, sizeof(addr.sin_zero)); + + UdpCommand broadcast = {addr, aMessage, NULL, 0}; + commands.push_back(broadcast); + + return true; +} + + +bool CUdpClient::Send(CStdString aIpAddress, int aPort, CStdString& aMessage) +{ + CSingleLock lock(critical_section); + + SOCKADDR_IN addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(aPort); + addr.sin_addr.s_addr = inet_addr(aIpAddress); + memset(&addr.sin_zero, 0, sizeof(addr.sin_zero)); + + UdpCommand transmit = {addr, aMessage, NULL, 0}; + commands.push_back(transmit); + + return true; +} + +bool CUdpClient::Send(SOCKADDR_IN aAddress, CStdString& aMessage) +{ + CSingleLock lock(critical_section); + + UdpCommand transmit = {aAddress, aMessage, NULL, 0}; + commands.push_back(transmit); + + return true; +} + +bool CUdpClient::Send(SOCKADDR_IN aAddress, LPBYTE pMessage, DWORD dwSize) +{ + CSingleLock lock(critical_section); + + UdpCommand transmit = {aAddress, "", pMessage, dwSize}; + commands.push_back(transmit); + + return true; +} + + +void CUdpClient::Process() +{ + Sleep(2000); + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Listening."); + + SOCKADDR_IN remoteAddress; + char messageBuffer[1024]; + DWORD dataAvailable; + + while ( !m_bStop ) + { + fd_set readset, exceptset; + FD_ZERO(&readset); FD_SET(client_socket, &readset); + FD_ZERO(&exceptset); FD_SET(client_socket, &exceptset); + + int nfds = (int)(client_socket); + timeval tv = { 0, 100000 }; + if (select(nfds, &readset, NULL, &exceptset, &tv) < 0) + { + CLog::Log(LOGERROR, "UDPCLIENT: failed to select on socket"); + break; + } + + // is there any data to read + dataAvailable = 0; + ioctlsocket(client_socket, FIONREAD, &dataAvailable); + + // while there is data to read + while (dataAvailable > 0) + { + // read data + int messageLength = sizeof(messageBuffer) - 1 ; +#ifndef _LINUX + int remoteAddressSize; +#else + socklen_t remoteAddressSize; +#endif + remoteAddressSize = sizeof(remoteAddress); + + int ret = recvfrom(client_socket, messageBuffer, messageLength, 0, (struct sockaddr *) & remoteAddress, &remoteAddressSize); + if (ret != SOCKET_ERROR) + { + // Packet received + messageLength = ret; + messageBuffer[messageLength] = '\0'; + + CStdString message = messageBuffer; + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT RX: %u\t\t<- '%s'", + XbmcThreads::SystemClockMillis(), message.c_str() ); + + // NOTE: You should consider locking access to the screen device + // or at least wait until after vertical refresh before firing off events + // to protect access to graphics resources. + + g_graphicsContext.Lock(); + OnMessage(remoteAddress, message, (LPBYTE)messageBuffer, messageLength); + g_graphicsContext.Unlock(); + } + else + { + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Socket error %u", WSAGetLastError()); + } + + // is there any more data to read? + dataAvailable = 0; + ioctlsocket(client_socket, FIONREAD, &dataAvailable); + } + + // dispatch a single command if any pending + while(DispatchNextCommand()) {} + } + + closesocket(client_socket); + + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT: Stopped listening."); +} + + +bool CUdpClient::DispatchNextCommand() +{ + UdpCommand command; + { + CSingleLock lock(critical_section); + + if (commands.size() <= 0) + return false; + + COMMANDITERATOR it = commands.begin(); + command = *it; + commands.erase(it); + } + + int ret; + if (command.binarySize > 0) + { + // only perform the following if logging level at debug + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT TX: %u\t\t-> " + "", + XbmcThreads::SystemClockMillis(), command.binarySize ); + + do + { + ret = sendto(client_socket, (LPCSTR) command.binary, command.binarySize, 0, (struct sockaddr *) & command.address, sizeof(command.address)); + } + while (ret == -1); + + delete[] command.binary; + } + else + { + // only perform the following if logging level at debug + CLog::Log(UDPCLIENT_DEBUG_LEVEL, "UDPCLIENT TX: %u\t\t-> '%s'", + XbmcThreads::SystemClockMillis(), command.message.c_str() ); + + do + { + ret = sendto(client_socket, command.message, command.message.GetLength(), 0, (struct sockaddr *) & command.address, sizeof(command.address)); + } + while (ret == -1 && !m_bStop); + } + return true; +} diff --git a/pool/shard001/C++/0017864_util.cpp b/pool/shard001/C++/0017864_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9508acb543f7508e48c1228c76c46c45e9700c6d --- /dev/null +++ b/pool/shard001/C++/0017864_util.cpp @@ -0,0 +1,47 @@ +#include "../model/house.h" +#include "../main.h" +#include "util.h" + +namespace multi_feed { + +std::string header_value( + const std::string &hdr, + const feed_value_map_type &vals +) { + // Build up the text as: + // (Header (specifier1/specifier2): text1/text2) + std::string tiv; + // Header specifiers (blabla/blabla2) + std::string tih; + + const model::house::group_desc_type &grp_desc = house_model()->group_desc(); + + model::house::group_desc_type::const_iterator gi = grp_desc.begin(); + for (; gi != grp_desc.end(); gi++) { + ACE_DEBUG((LM_DEBUG, "finding %d\n", gi->first)); + feed_value_map_type::const_iterator vi = vals.find(gi->first); + if (vi != vals.end()) { + ACE_DEBUG((LM_DEBUG, "found: %s\n", vi->second.c_str())); + tih += (tih.empty() ? gi->second : "/" + gi->second); + tiv += (tiv.empty() ? vi->second : "/" + vi->second); + } + } + + return tih.empty() || hdr.empty() + ? header_value(hdr, tiv) + : header_value(hdr + " (" + tih + ")", tiv); + +} + +std::string header_value( + const std::string &hdr, + const std::string &value +) { + if (hdr.empty()) + return value; + std::string tihv; + tihv = hdr + ": " + value; // + "\n"; + return tihv; +} + +} // ns multi_feed diff --git a/pool/shard001/C++/0017867_Bitmap_writePixels.cpp b/pool/shard001/C++/0017867_Bitmap_writePixels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e41af6995272e5943498a8526e870f7209e78d2f --- /dev/null +++ b/pool/shard001/C++/0017867_Bitmap_writePixels.cpp @@ -0,0 +1,26 @@ +// 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 "tools/fiddle/examples.h" +// HASH=9b3133a6673d2514d166398adbe1f9f4 +REG_FIDDLE(Bitmap_writePixels, 256, 256, false, 3) { +void draw(SkCanvas* canvas) { + std::vector srcPixels; + int width = image->width(); + int height = image->height(); + srcPixels.resize(height * width * 4); + SkPixmap pixmap(SkImageInfo::MakeN32Premul(width, height), (const void*) &srcPixels.front(), + width * 4); + image->readPixels(nullptr, pixmap, 0, 0); + canvas->scale(.5f, .5f); + width /= 4; + height /= 4; + for (int y = 0; y < 4; ++y) { + for (int x = 0; x < 4; ++x) { + SkBitmap bitmap; + bitmap.allocPixels(SkImageInfo::MakeN32Premul(width, height)); + bitmap.writePixels(pixmap, -y * width, -x * height); + canvas->drawImage(bitmap.asImage(), x * width, y * height); + } + } +} +} // END FIDDLE diff --git a/pool/shard001/C++/0017875_theme_model_associator.cc b/pool/shard001/C++/0017875_theme_model_associator.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c6dd3c9ad0717a2d71cf8a6568e00a1ac422597 --- /dev/null +++ b/pool/shard001/C++/0017875_theme_model_associator.cc @@ -0,0 +1,118 @@ +// 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/glue/theme_model_associator.h" + +#include "base/basictypes.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/sync/glue/sync_backend_host.h" +#include "chrome/browser/sync/glue/theme_util.h" +#include "chrome/browser/sync/profile_sync_service.h" +#include "sync/api/sync_error.h" +#include "sync/internal_api/public/read_node.h" +#include "sync/internal_api/public/read_transaction.h" +#include "sync/internal_api/public/write_node.h" +#include "sync/internal_api/public/write_transaction.h" +#include "sync/protocol/theme_specifics.pb.h" + +namespace browser_sync { + +namespace { + +static const char kThemesTag[] = "google_chrome_themes"; +static const char kCurrentThemeNodeTitle[] = "Current Theme"; + +static const char kNoThemesFolderError[] = + "Server did not create the top-level themes node. We " + "might be running against an out-of-date server."; + +} // namespace + +ThemeModelAssociator::ThemeModelAssociator( + ProfileSyncService* sync_service, + DataTypeErrorHandler* error_handler) + : sync_service_(sync_service), + error_handler_(error_handler) { + DCHECK(sync_service_); +} + +ThemeModelAssociator::~ThemeModelAssociator() {} + +syncer::SyncError ThemeModelAssociator::AssociateModels() { + syncer::WriteTransaction trans(FROM_HERE, sync_service_->GetUserShare()); + syncer::ReadNode root(&trans); + if (root.InitByTagLookup(kThemesTag) != syncer::BaseNode::INIT_OK) { + return error_handler_->CreateAndUploadError(FROM_HERE, + kNoThemesFolderError, + model_type()); + } + + Profile* profile = sync_service_->profile(); + syncer::WriteNode node(&trans); + // TODO(akalin): When we have timestamps, we may want to do + // something more intelligent than preferring the sync data over our + // local data. + if (node.InitByClientTagLookup(syncer::THEMES, kCurrentThemeClientTag) == + syncer::BaseNode::INIT_OK) { + // Update the current theme from the sync data. + // TODO(akalin): If the sync data does not have + // use_system_theme_by_default and we do, update that flag on the + // sync data. + sync_pb::ThemeSpecifics theme_specifics = node.GetThemeSpecifics(); + if (UpdateThemeSpecificsOrSetCurrentThemeIfNecessary(profile, + &theme_specifics)) + node.SetThemeSpecifics(theme_specifics); + } else { + // Set the sync data from the current theme. + syncer::WriteNode node(&trans); + syncer::WriteNode::InitUniqueByCreationResult result = + node.InitUniqueByCreation(syncer::THEMES, root, + kCurrentThemeClientTag); + if (result != syncer::WriteNode::INIT_SUCCESS) { + return error_handler_->CreateAndUploadError( + FROM_HERE, + "Could not create current theme node.", + model_type()); + } + node.SetIsFolder(false); + node.SetTitle(UTF8ToWide(kCurrentThemeNodeTitle)); + sync_pb::ThemeSpecifics theme_specifics; + GetThemeSpecificsFromCurrentTheme(profile, &theme_specifics); + node.SetThemeSpecifics(theme_specifics); + } + return syncer::SyncError(); +} + +syncer::SyncError ThemeModelAssociator::DisassociateModels() { + // We don't maintain any association state, so nothing to do. + return syncer::SyncError(); +} + +bool ThemeModelAssociator::SyncModelHasUserCreatedNodes(bool* has_nodes) { + DCHECK(has_nodes); + *has_nodes = false; + syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare()); + syncer::ReadNode root(&trans); + if (root.InitByTagLookup(kThemesTag) != syncer::BaseNode::INIT_OK) { + LOG(ERROR) << kNoThemesFolderError; + return false; + } + // The sync model has user created nodes iff the themes folder has + // any children. + *has_nodes = root.HasChildren(); + return true; +} + +bool ThemeModelAssociator::CryptoReadyIfNecessary() { + // We only access the cryptographer while holding a transaction. + syncer::ReadTransaction trans(FROM_HERE, sync_service_->GetUserShare()); + const syncer::ModelTypeSet encrypted_types = + syncer::GetEncryptedTypes(&trans); + return !encrypted_types.Has(syncer::THEMES) || + sync_service_->IsCryptographerReady(&trans); +} + +} // namespace browser_sync diff --git a/pool/shard001/C++/0017877_AuthenticatorTest.cpp b/pool/shard001/C++/0017877_AuthenticatorTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..180f5a9536dffe6c8f93f538e61286f2b7a2be95 --- /dev/null +++ b/pool/shard001/C++/0017877_AuthenticatorTest.cpp @@ -0,0 +1,50 @@ +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ +class AuthenticatorTest : public ::testing::Test +{ + protected: + virtual void SetUp() {} + virtual void TearDown() {} + public: + std::random_device rd; // only used once to initialise (seed) engine + std::mt19937 rng; // random-number engine used (Mersenne-Twister in this case) + std::uniform_int_distribution uni; // guaranteed unbiased + + AuthenticatorTest() : rd(), rng(rd()), uni(0, std::numeric_limits::max()) {} +}; +TEST_F(AuthenticatorTest, GenerateAndVerify) +{ + Authenticator auth; + + std::string nickname(Utils::random_string(20)); + auto random_integer = uni(rng); + Models::User user(nickname, random_integer); + + std::string token(auth.generateToken(user)); + + Models::User decoded(auth.authenticateUser(token)); + + EXPECT_EQ(decoded.getID(), random_integer); + EXPECT_EQ(decoded.getDisplayName(), nickname); +} + +TEST_F(AuthenticatorTest, InvalidToken) +{ + Authenticator auth; + + std::string token("This is an invalid token!"); + + Models::User decoded(auth.authenticateUser(token)); + + EXPECT_FALSE(decoded.isValid()); +} +} \ No newline at end of file diff --git a/pool/shard001/C++/0017890_PropertyItemDelegate.cpp b/pool/shard001/C++/0017890_PropertyItemDelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cbff438b4be20ea5d4b5deae9247c2c640169117 --- /dev/null +++ b/pool/shard001/C++/0017890_PropertyItemDelegate.cpp @@ -0,0 +1,196 @@ +/*************************************************************************** + * Copyright (c) 2004 Werner Mayer * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * 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., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + + +#include "PreCompiled.h" + +#ifndef _PreComp_ +# include +# include +# include +#endif + +#include +#include +#include +#include +#include +#include "PropertyItemDelegate.h" +#include "PropertyItem.h" +#include "PropertyEditor.h" + +FC_LOG_LEVEL_INIT("PropertyView",true,true) + +using namespace Gui::PropertyEditor; + + +PropertyItemDelegate::PropertyItemDelegate(QObject* parent) + : QItemDelegate(parent), expressionEditor(0) + , pressed(false), changed(false) +{ +} + +PropertyItemDelegate::~PropertyItemDelegate() +{ +} + +QSize PropertyItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const +{ + QSize size = QItemDelegate::sizeHint(option, index); + size += QSize(0, 5); + return size; +} + +void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const +{ + QStyleOptionViewItem option = opt; + + PropertyItem *property = static_cast(index.internalPointer()); + + if (property && property->isSeparator()) { + QColor color = option.palette.color(QPalette::BrightText); + QObject* par = parent(); + if (par) { + QVariant value = par->property("groupTextColor"); + if (value.canConvert()) + color = value.value(); + } + option.palette.setColor(QPalette::Text, color); + option.font.setBold(true); + option.state &= ~QStyle::State_Selected; + } + + if (index.column() == 1) { + option.state &= ~QStyle::State_Selected; + } + + option.state &= ~QStyle::State_HasFocus; + + if (property && property->isSeparator()) { + QBrush brush = option.palette.dark(); + QObject* par = parent(); + if (par) { + QVariant value = par->property("groupBackground"); + if (value.canConvert()) + brush = value.value(); + } + painter->fillRect(option.rect, brush); + } + + QPen savedPen = painter->pen(); + + QItemDelegate::paint(painter, option, index); + + QColor color = static_cast(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt, qobject_cast(parent()))); + painter->setPen(QPen(color)); + if (index.column() == 1 || !(property && property->isSeparator())) { + int right = (option.direction == Qt::LeftToRight) ? option.rect.right() : option.rect.left(); + painter->drawLine(right, option.rect.y(), right, option.rect.bottom()); + } + painter->drawLine(option.rect.x(), option.rect.bottom(), + option.rect.right(), option.rect.bottom()); + painter->setPen(savedPen); +} + +bool PropertyItemDelegate::editorEvent (QEvent * event, QAbstractItemModel* model, + const QStyleOptionViewItem& option, const QModelIndex& index) +{ + if (event && event->type() == QEvent::MouseButtonPress) + this->pressed = true; + else + this->pressed = false; + return QItemDelegate::editorEvent(event, model, option, index); +} + +QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex & index ) const +{ + if (!index.isValid()) + return 0; + + PropertyItem *childItem = static_cast(index.internalPointer()); + if (!childItem) + return 0; + + FC_LOG("create editor " << index.row() << "," << index.column()); + + PropertyEditor *parentEditor = qobject_cast(this->parent()); + QWidget* editor; + expressionEditor = 0; + if(parentEditor && parentEditor->isBinding()) + expressionEditor = editor = childItem->createExpressionEditor(parent, this, SLOT(valueChanged())); + else + editor = childItem->createEditor(parent, this, SLOT(valueChanged())); + if (editor) // Make sure the editor background is painted so the cell content doesn't show through + editor->setAutoFillBackground(true); + if (editor && childItem->isReadOnly()) + editor->setDisabled(true); + else if (editor /*&& this->pressed*/) { + // We changed the way editor is activated in PropertyEditor (in response + // of signal activated and clicked), so now we should grab focus + // regardless of "pressed" or not (e.g. when activated by keyboard + // enter) + editor->setFocus(); + } + this->pressed = false; + + return editor; +} + +void PropertyItemDelegate::valueChanged() +{ + QWidget* editor = qobject_cast(sender()); + if (editor) { + Base::FlagToggler<> flag(changed); + commitData(editor); + } +} + +void PropertyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +{ + if (!index.isValid()) + return; + QVariant data = index.data(Qt::EditRole); + PropertyItem *childItem = static_cast(index.internalPointer()); + editor->blockSignals(true); + if(expressionEditor == editor) + childItem->setExpressionEditorData(editor, data); + else + childItem->setEditorData(editor, data); + editor->blockSignals(false); + return; +} + +void PropertyItemDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const +{ + if (!index.isValid() || !changed) + return; + PropertyItem *childItem = static_cast(index.internalPointer()); + QVariant data; + if(expressionEditor == editor) + data = childItem->expressionEditorData(editor); + else + data = childItem->editorData(editor); + model->setData(index, data, Qt::EditRole); +} + +#include "moc_PropertyItemDelegate.cpp" diff --git a/pool/shard001/C++/0017908_resource_fetcher_impl.cc b/pool/shard001/C++/0017908_resource_fetcher_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..b48ad21d89df43dcfd6cf1429e5e6f6aa8ee8d37 --- /dev/null +++ b/pool/shard001/C++/0017908_resource_fetcher_impl.cc @@ -0,0 +1,153 @@ +// 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 "content/renderer/fetchers/resource_fetcher_impl.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/time/time.h" +#include "third_party/WebKit/public/platform/Platform.h" +#include "third_party/WebKit/public/platform/WebHTTPBody.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/platform/WebURLLoader.h" +#include "third_party/WebKit/public/platform/WebURLRequest.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebKit.h" +#include "third_party/WebKit/public/web/WebSecurityPolicy.h" + +namespace content { + +// static +ResourceFetcher* ResourceFetcher::Create(const GURL& url) { + return new ResourceFetcherImpl(url); +} + +ResourceFetcherImpl::ResourceFetcherImpl(const GURL& url) + : request_(url) { +} + +ResourceFetcherImpl::~ResourceFetcherImpl() { + if (!completed() && loader_) + loader_->cancel(); +} + +void ResourceFetcherImpl::SetMethod(const std::string& method) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + request_.setHTTPMethod(blink::WebString::fromUTF8(method)); +} + +void ResourceFetcherImpl::SetBody(const std::string& body) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + blink::WebHTTPBody web_http_body; + web_http_body.initialize(); + web_http_body.appendData(blink::WebData(body)); + request_.setHTTPBody(web_http_body); +} + +void ResourceFetcherImpl::SetHeader(const std::string& header, + const std::string& value) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + if (base::LowerCaseEqualsASCII(header, "referer")) { + blink::WebString referrer = + blink::WebSecurityPolicy::generateReferrerHeader( + blink::WebReferrerPolicyDefault, + request_.url(), + blink::WebString::fromUTF8(value)); + request_.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault); + } else { + request_.setHTTPHeaderField(blink::WebString::fromUTF8(header), + blink::WebString::fromUTF8(value)); + } +} + +void ResourceFetcherImpl::SetSkipServiceWorker(bool skip_service_worker) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + request_.setSkipServiceWorker(skip_service_worker); +} + +void ResourceFetcherImpl::SetCachePolicy( + blink::WebURLRequest::CachePolicy policy) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + request_.setCachePolicy(policy); +} + +void ResourceFetcherImpl::SetLoaderOptions( + const blink::WebURLLoaderOptions& options) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + options_ = options; +} + +void ResourceFetcherImpl::Start( + blink::WebFrame* frame, + blink::WebURLRequest::RequestContext request_context, + blink::WebURLRequest::FrameType frame_type, + LoaderType loader_type, + const Callback& callback) { + DCHECK(!loader_); + DCHECK(!request_.isNull()); + DCHECK(callback_.is_null()); + DCHECK(!completed()); + if (!request_.httpBody().isNull()) + DCHECK_NE("GET", request_.httpMethod().utf8()) << "GETs can't have bodies."; + + callback_ = callback; + + request_.setRequestContext(request_context); + request_.setFrameType(frame_type); + request_.setFirstPartyForCookies(frame->document().firstPartyForCookies()); + frame->dispatchWillSendRequest(request_); + + switch (loader_type) { + case PLATFORM_LOADER: + loader_.reset(blink::Platform::current()->createURLLoader()); + break; + case FRAME_ASSOCIATED_LOADER: + loader_.reset(frame->createAssociatedURLLoader(options_)); + break; + } + loader_->loadAsynchronously(request_, this); + + // No need to hold on to the request. + request_.reset(); +} + +void ResourceFetcherImpl::SetTimeout(const base::TimeDelta& timeout) { + DCHECK(loader_); + DCHECK(!completed()); + + timeout_timer_.Start(FROM_HERE, timeout, this, &ResourceFetcherImpl::Cancel); +} + +void ResourceFetcherImpl::OnLoadComplete() { + timeout_timer_.Stop(); + if (callback_.is_null()) + return; + + // Take a reference to the callback as running the callback may lead to our + // destruction. + Callback callback = callback_; + callback.Run(status() == LOAD_FAILED ? blink::WebURLResponse() : response(), + status() == LOAD_FAILED ? std::string() : data()); +} + +void ResourceFetcherImpl::Cancel() { + loader_->cancel(); + WebURLLoaderClientImpl::Cancel(); +} + +} // namespace content diff --git a/pool/shard001/C++/0017917_op_special.cc b/pool/shard001/C++/0017917_op_special.cc new file mode 100644 index 0000000000000000000000000000000000000000..f53bd4c7b93cf0b4d1d3eff976ab77fb8d3efddd --- /dev/null +++ b/pool/shard001/C++/0017917_op_special.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2016 by Contributors +// implementation of common nn operators +#include +#include +#include +#include "./op_util.h" + +namespace tinyflow { + +using namespace nnvm; + +const FLuaCompute kLuaNOP = "function(x, y, kwarg) return function() end end"; + +NNVM_REGISTER_OP(placeholder) +.describe("placeholder op") +.set_num_inputs(0); + +template +inline bool EmptyAttr(const NodeAttrs& attrs, + std::vector *ishape, + std::vector *oshape) { + oshape->at(0) = Attr{0}; return true; +} + +NNVM_REGISTER_OP(_nop) +.describe("no operation") +.set_num_inputs(0) +.set_num_outputs(1) +.set_attr("FInferShape", EmptyAttr) +.set_attr("FInferType", EmptyAttr); + + +NNVM_REGISTER_OP(assign) +.describe("assign second to the first") +.set_num_inputs(2) +.set_attr("FMutateInputs", [](const NodeAttrs& attrs) { + return std::vector{0}; + }) +.set_attr("FInferShape", SameShape) +.set_attr("FInplaceOption", InplaceIn1Out0); + +// special no gradient op to report error when take +// gradient wrt non-differentiable inputs +NNVM_REGISTER_OP(_no_gradient) +.describe("Special op indicating no gradient") +.set_num_inputs(0); + +} // namespace tinyflow diff --git a/pool/shard001/C++/0017922_console_std.cpp b/pool/shard001/C++/0017922_console_std.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56120ecef5d9eab3c7bdb6a7657d634e18eecddc --- /dev/null +++ b/pool/shard001/C++/0017922_console_std.cpp @@ -0,0 +1,203 @@ +/* + * console_std.cpp + * + * Created on: Apr 25, 2014 + * Author: lion + */ + +#include "console.h" +#include "utf8.h" + +namespace fibjs +{ + +TextColor *logger::get_std_color() +{ + static obj_ptr s_tc; + + if (!s_tc) + s_tc = new TextColor; + + return s_tc; +} + +void std_logger::out(const char *txt) +{ + +#ifdef _WIN32 + class color_out + { + public: + color_out() + { + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + + m_handle = GetStdHandle(STD_OUTPUT_HANDLE); + GetConsoleScreenBufferInfo(m_handle, &csbiInfo); + m_Now = m_wAttr = csbiInfo.wAttributes; + m_wLight = m_wAttr & FOREGROUND_INTENSITY; + } + + void out(const char *s, FILE *stream) + { + wstring ws = utf8to16String(s); + wchar *ptr = &ws[0]; + wchar *ptr2; + + while (ptr2 = (wchar *) qstrchr(ptr, L'\x1b')) + { + if (ptr2[1] == '[') + { + ptr2[0] = 0; + fputws(ptr, stream); + fflush(stream); + + ptr2 += 2; + + while (true) + { + if (ptr2[0] == 'm') + { + m_Now = m_wAttr; + m_wLight = m_wAttr & FOREGROUND_INTENSITY; + SetConsoleTextAttribute(m_handle, m_Now); + ptr2 ++; + break; + } + + if (qisdigit(ptr2[0])) + { + if (ptr2[1] == 'm') + { + if (ptr2[0] == '0') + { + m_Now = m_wAttr; + m_wLight = m_wAttr & FOREGROUND_INTENSITY; + SetConsoleTextAttribute(m_handle, m_Now); + } + ptr2 += 2; + break; + } + + WORD mask, val; + WORD light = m_wLight; + + if (ptr2[1] == ';') + { + if (ptr2[0] == '0') + m_wLight = light = 0; + else if (ptr2[0] == '1') + m_wLight = light = FOREGROUND_INTENSITY; + ptr2 += 2; + } + + if (ptr2[0] == '3') + { + mask = 0xf0; + ptr2 ++; + } + else if (ptr2[0] == '4') + { + mask = 0x0f; + ptr2 ++; + } + else if (ptr2[0] == '9') + { + mask = 0xf0; + light |= FOREGROUND_INTENSITY; + ptr2 ++; + } + else if (ptr2[0] == '1' && ptr2[1] == '0') + { + mask = 0x0f; + light |= FOREGROUND_INTENSITY << 4; + ptr2 += 2; + } + else + break; + + if (!qisdigit(ptr2[0])) + break; + + val = ptr2[0] - '0'; + + if (val != 8) + { + if (val == 9) + { + val = (m_wAttr & 0x0f) | (m_Now & 0xf0); + + m_Now = val | light; + SetConsoleTextAttribute(m_handle, m_Now); + } + else + { + val = (val & 2) | ((val & 1) ? 4 : 0) + | ((val & 4) ? 1 : 0); + + if (mask == 0x0f) + val <<= 4; + + m_Now = (m_Now & mask) | val | light; + SetConsoleTextAttribute(m_handle, m_Now); + } + } + + ptr2 ++; + if (ptr2[0] == 'm') + { + ptr2 ++; + break; + } + } + } + } + ptr = ptr2; + } + + fputws(ptr, stream); + fflush(stream); + } + + private: + HANDLE m_handle; + WORD m_wAttr, m_Now; + WORD m_wLight; + }; + static color_out s_out; + + s_out.out(txt, stdout); +#else + fputs(txt, stdout); +#endif + + fflush(stdout); +} + +result_t std_logger::write(AsyncEvent *ac) +{ + item *p1; + + while ((p1 = m_workinglogs.getHead()) != 0) + { + std::string txt; + if (p1->m_priority == console_base::_NOTICE) + txt = logger::notice() + p1->m_msg + COLOR_RESET + "\n"; + else if (p1->m_priority == console_base::_WARN) + txt = logger::warn() + p1->m_msg + COLOR_RESET + "\n"; + else if (p1->m_priority <= console_base::_ERROR) + txt = logger::error() + p1->m_msg + COLOR_RESET + "\n"; + else if (p1->m_priority == console_base::_PRINT) + txt = p1->m_msg; + else + txt = p1->m_msg + "\n"; + + out(txt.c_str()); + + delete p1; + } + + return 0; +} + +} diff --git a/pool/shard001/C++/0017929_qabstractstate.cpp b/pool/shard001/C++/0017929_qabstractstate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..08c3f45b827bf0c60a528f97f5749b870d7f16e7 --- /dev/null +++ b/pool/shard001/C++/0017929_qabstractstate.cpp @@ -0,0 +1,215 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtCore 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 "qabstractstate.h" + +#ifndef QT_NO_STATEMACHINE + +#include "qabstractstate_p.h" +#include "qstate.h" +#include "qstate_p.h" +#include "qstatemachine.h" +#include "qstatemachine_p.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QAbstractState + + \brief The QAbstractState class is the base class of states of a QStateMachine. + + \since 4.6 + \ingroup statemachine + + The QAbstractState class is the abstract base class of states that are part + of a QStateMachine. It defines the interface that all state objects have in + common. QAbstractState is part of \l{The State Machine Framework}. + + The entered() signal is emitted when the state has been entered. The + exited() signal is emitted when the state has been exited. + + The parentState() function returns the state's parent state. The machine() + function returns the state machine that the state is part of. + + \section1 Subclassing + + The onEntry() function is called when the state is entered; reimplement this + function to perform custom processing when the state is entered. + + The onExit() function is called when the state is exited; reimplement this + function to perform custom processing when the state is exited. +*/ + +QAbstractStatePrivate::QAbstractStatePrivate(StateType type) + : stateType(type), isMachine(false), parentState(0) +{ +} + +QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q) +{ + return q->d_func(); +} + +const QAbstractStatePrivate *QAbstractStatePrivate::get(const QAbstractState *q) +{ + return q->d_func(); +} + +QStateMachine *QAbstractStatePrivate::machine() const +{ + QObject *par = parent; + while (par != 0) { + if (QStateMachine *mach = qobject_cast(par)) + return mach; + par = par->parent(); + } + return 0; +} + +void QAbstractStatePrivate::callOnEntry(QEvent *e) +{ + Q_Q(QAbstractState); + q->onEntry(e); +} + +void QAbstractStatePrivate::callOnExit(QEvent *e) +{ + Q_Q(QAbstractState); + q->onExit(e); +} + +void QAbstractStatePrivate::emitEntered() +{ + Q_Q(QAbstractState); + emit q->entered(); +} + +void QAbstractStatePrivate::emitExited() +{ + Q_Q(QAbstractState); + emit q->exited(); +} + +/*! + Constructs a new state with the given \a parent state. +*/ +QAbstractState::QAbstractState(QState *parent) + : QObject(*new QAbstractStatePrivate(QAbstractStatePrivate::AbstractState), parent) +{ +} + +/*! + \internal +*/ +QAbstractState::QAbstractState(QAbstractStatePrivate &dd, QState *parent) + : QObject(dd, parent) +{ +} + +/*! + Destroys this state. +*/ +QAbstractState::~QAbstractState() +{ +} + +/*! + Returns this state's parent state, or 0 if the state has no parent state. +*/ +QState *QAbstractState::parentState() const +{ + Q_D(const QAbstractState); + if (d->parentState != parent()) + d->parentState = qobject_cast(parent()); + return d->parentState; +} + +/*! + Returns the state machine that this state is part of, or 0 if the state is + not part of a state machine. +*/ +QStateMachine *QAbstractState::machine() const +{ + Q_D(const QAbstractState); + return d->machine(); +} + +/*! + \fn QAbstractState::onExit(QEvent *event) + + This function is called when the state is exited. The given \a event is what + caused the state to be exited. Reimplement this function to perform custom + processing when the state is exited. +*/ + +/*! + \fn QAbstractState::onEntry(QEvent *event) + + This function is called when the state is entered. The given \a event is + what caused the state to be entered. Reimplement this function to perform + custom processing when the state is entered. +*/ + +/*! + \fn QAbstractState::entered() + + This signal is emitted when the state has been entered (after onEntry() has + been called). +*/ + +/*! + \fn QAbstractState::exited() + + This signal is emitted when the state has been exited (after onExit() has + been called). +*/ + +/*! + \reimp +*/ +bool QAbstractState::event(QEvent *e) +{ + return QObject::event(e); +} + +QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/pool/shard001/C++/0017931_ReferenceSelection.cpp b/pool/shard001/C++/0017931_ReferenceSelection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2bfcd42e093a381d329e6880a76ebef5e73193d --- /dev/null +++ b/pool/shard001/C++/0017931_ReferenceSelection.cpp @@ -0,0 +1,78 @@ +/****************************************************************************** + * Copyright (c)2012 Konstantinos Poulios * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * 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., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ******************************************************************************/ + +#include "PreCompiled.h" + +#ifndef _PreComp_ +# include +# include +# include +# include +# include +#endif + +#include +#include +#include "ReferenceSelection.h" + +using namespace PartDesignGui; +using namespace Gui; + +/* TRANSLATOR PartDesignGui::ReferenceSelection.cpp */ + +bool ReferenceSelection::allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) +{ + if (!sSubName || sSubName[0] == '\0') + return false; + if (pObj != support) + return false; + std::string subName(sSubName); + if (edge && subName.size() > 4 && subName.substr(0,4) == "Edge") { + const Part::TopoShape &shape = static_cast(support)->Shape.getValue(); + TopoDS_Shape sh = shape.getSubShape(subName.c_str()); + const TopoDS_Edge& edge = TopoDS::Edge(sh); + if (!edge.IsNull()) { + if (planar) { + BRepAdaptor_Curve adapt(edge); + if (adapt.GetType() == GeomAbs_Line) + return true; + } else { + return true; + } + } + } + if (plane && subName.size() > 4 && subName.substr(0,4) == "Face") { + const Part::TopoShape &shape = static_cast(support)->Shape.getValue(); + TopoDS_Shape sh = shape.getSubShape(subName.c_str()); + const TopoDS_Face& face = TopoDS::Face(sh); + if (!face.IsNull()) { + if (planar) { + BRepAdaptor_Surface adapt(face); + if (adapt.GetType() == GeomAbs_Plane) + return true; + } else { + return true; + } + } + } + return false; +} diff --git a/pool/shard001/C++/0017957_NCPkgFilterMain.cc b/pool/shard001/C++/0017957_NCPkgFilterMain.cc new file mode 100644 index 0000000000000000000000000000000000000000..a276e1cb9e5d1e629f7fc4bbbd82630c455e62ee --- /dev/null +++ b/pool/shard001/C++/0017957_NCPkgFilterMain.cc @@ -0,0 +1,103 @@ +/* + Copyright (c) [2002-2011] Novell, Inc. + Copyright (c) 2021 SUSE LLC + + 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.0 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, write + to the Free Software Foundation, Inc., 51 Franklin Street, Fifth + Floor, Boston, MA 02110-1301 USA + + + File: NCPkgFilterMain.cc + Author: Hedgehog Painter + +*/ + + +#define YUILogComponent "ncurses-pkg" +#include + +#include "NCPkgFilterMain.h" +#include "NCPkgFilterService.h" + + +using std::endl; + +/* + Textdomain "ncurses-pkg" +*/ + +NCPkgFilterMain::NCPkgFilterMain (YWidget *parent, std::string label, NCPackageSelector *pkger ) + :NCComboBox(parent, label, false) + , pkg (pkger) +{ + createLayout(); + setNotify( true ); +} + +NCPkgFilterMain::~NCPkgFilterMain() +{ + +} + +void NCPkgFilterMain::createLayout() +{ + patterns = new YItem( _( "Patterns" ) ); + items.push_back( patterns ); + + languages = new YItem( _( "Languages" ) ); + items.push_back( languages ); + + repositories = new YItem( _( "Repositories" ) ); + items.push_back( repositories ); + + if (NCPkgServiceTable::any_service()) + { + services = new YItem( _( "Services" ) ); + items.push_back( services ); + } + + search = new YItem( _( "Search" ) ); + search->setSelected(); + items.push_back( search ); + + inst_summary = new YItem( _( "Installation Summary" ) ); + items.push_back( inst_summary ); + + pkg_class = new YItem( _( "Package Classification" ) ); + items.push_back( pkg_class ); + + addItems( items ); + +} + +bool NCPkgFilterMain::handleEvent() +{ + + YItem *currentItem = selectedItem(); + + if ( currentItem == patterns ) + pkg->replaceFilter ( NCPackageSelector::Patterns ); + else if ( currentItem == languages ) + pkg->replaceFilter ( NCPackageSelector::Languages ); + else if ( currentItem == repositories ) + pkg->replaceFilter ( NCPackageSelector::Repositories ); + else if ( currentItem == services ) + pkg->replaceFilter ( NCPackageSelector::Services ); + else if ( currentItem == search ) + pkg->replaceFilter ( NCPackageSelector::Search ); + else if ( currentItem == inst_summary ) + pkg->replaceFilter ( NCPackageSelector::Summary ); + else if ( currentItem == pkg_class ) + pkg->replaceFilter ( NCPackageSelector::PkgClassification ); + else + yuiError() << "zatim nic" << endl; + return true; +} diff --git a/pool/shard001/C++/0017959_swkbd.cpp b/pool/shard001/C++/0017959_swkbd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d87bf3d57b5d1af5b9088e4714aa722b5a5a3f9d --- /dev/null +++ b/pool/shard001/C++/0017959_swkbd.cpp @@ -0,0 +1,120 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include + +#include "common/assert.h" +#include "common/logging/log.h" +#include "common/string_util.h" + +#include "core/hle/applets/swkbd.h" +#include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/shared_memory.h" +#include "core/hle/service/hid/hid.h" +#include "core/hle/service/gsp_gpu.h" +#include "core/hle/result.h" +#include "core/memory.h" + +#include "video_core/video_core.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +namespace HLE { +namespace Applets { + +ResultCode SoftwareKeyboard::ReceiveParameter(Service::APT::MessageParameter const& parameter) { + if (parameter.signal != static_cast(Service::APT::SignalType::LibAppJustStarted)) { + LOG_ERROR(Service_APT, "unsupported signal %u", parameter.signal); + UNIMPLEMENTED(); + // TODO(Subv): Find the right error code + return ResultCode(-1); + } + + // The LibAppJustStarted message contains a buffer with the size of the framebuffer shared memory. + // Create the SharedMemory that will hold the framebuffer data + Service::APT::CaptureBufferInfo capture_info; + ASSERT(sizeof(capture_info) == parameter.buffer.size()); + + memcpy(&capture_info, parameter.buffer.data(), sizeof(capture_info)); + + using Kernel::MemoryPermission; + // Allocate a heap block of the required size for this applet. + heap_memory = std::make_shared>(capture_info.size); + // Create a SharedMemory that directly points to this heap block. + framebuffer_memory = Kernel::SharedMemory::CreateForApplet(heap_memory, 0, heap_memory->size(), + MemoryPermission::ReadWrite, MemoryPermission::ReadWrite, + "SoftwareKeyboard Memory"); + + // Send the response message with the newly created SharedMemory + Service::APT::MessageParameter result; + result.signal = static_cast(Service::APT::SignalType::LibAppFinished); + result.buffer.clear(); + result.destination_id = static_cast(Service::APT::AppletId::Application); + result.sender_id = static_cast(id); + result.object = framebuffer_memory; + + Service::APT::SendParameter(result); + return RESULT_SUCCESS; +} + +ResultCode SoftwareKeyboard::StartImpl(Service::APT::AppletStartupParameter const& parameter) { + ASSERT_MSG(parameter.buffer.size() == sizeof(config), "The size of the parameter (SoftwareKeyboardConfig) is wrong"); + + memcpy(&config, parameter.buffer.data(), parameter.buffer.size()); + text_memory = boost::static_pointer_cast(parameter.object); + + // TODO(Subv): Verify if this is the correct behavior + memset(text_memory->GetPointer(), 0, text_memory->size); + + DrawScreenKeyboard(); + + started = true; + return RESULT_SUCCESS; +} + +void SoftwareKeyboard::Update() { + // TODO(Subv): Handle input using the touch events from the HID module + + // TODO(Subv): Remove this hardcoded text + std::u16string text = Common::UTF8ToUTF16("Citra"); + memcpy(text_memory->GetPointer(), text.c_str(), text.length() * sizeof(char16_t)); + + // TODO(Subv): Ask for input and write it to the shared memory + // TODO(Subv): Find out what are the possible values for the return code, + // some games seem to check for a hardcoded 2 + config.return_code = 2; + config.text_length = 6; + config.text_offset = 0; + + // TODO(Subv): We're finalizing the applet immediately after it's started, + // but we should defer this call until after all the input has been collected. + Finalize(); +} + +void SoftwareKeyboard::DrawScreenKeyboard() { + auto bottom_screen = GSP_GPU::GetFrameBufferInfo(0, 1); + auto info = bottom_screen->framebuffer_info[bottom_screen->index]; + + // TODO(Subv): Draw the HLE keyboard, for now just zero-fill the framebuffer + Memory::ZeroBlock(info.address_left, info.stride * 320); + + GSP_GPU::SetBufferSwap(1, info); +} + +void SoftwareKeyboard::Finalize() { + // Let the application know that we're closing + Service::APT::MessageParameter message; + message.buffer.resize(sizeof(SoftwareKeyboardConfig)); + std::memcpy(message.buffer.data(), &config, message.buffer.size()); + message.signal = static_cast(Service::APT::SignalType::LibAppClosed); + message.destination_id = static_cast(Service::APT::AppletId::Application); + message.sender_id = static_cast(id); + Service::APT::SendParameter(message); + + started = false; +} + +} +} // namespace diff --git a/pool/shard001/C++/0017962_2028925.cpp b/pool/shard001/C++/0017962_2028925.cpp new file mode 100644 index 0000000000000000000000000000000000000000..435b0d57e31cbc37ff4e181103217c7590248de4 --- /dev/null +++ b/pool/shard001/C++/0017962_2028925.cpp @@ -0,0 +1,80 @@ +//Language: GNU C++ + + +#include +#include +#include +#include +using namespace std; + +int map[1010][1010]; +int vis[1010][1010]; +int f[4][2]={0,1,1,0,0,-1,-1,0}; +int m,maxx,maxy; +void dfs(int x,int y) +{ + vis[x][y]=1; + m++; + int px,py;; + int flag; + for(int i=0;i<4;i++) + { + px=x;py=y; + flag=0; + while(1){ + px=px+f[i][0]; + py=py+f[i][1]; + if(px>=1&&px<=maxx&&py>=1&&py<=maxy&&vis[px][py]==0&&map[px][py]==1) + { + flag=1; + break; + } + if(px<1||px>maxx||py<1||py>maxy) + break; + } + if(flag==1) + dfs(px,py); + } + +} + +int main() +{ + int n; + int x,y; + while(~scanf("%d",&n)) + { + maxx=-1;maxy=-1; + memset(map,0,sizeof(map)); + for(int i=1;i<=n;i++) + { + scanf("%d %d",&x,&y); + if(x>maxx) + maxx=x; + if(y>maxy) + maxy=y; + map[x][y]=1; + } + int ans=0; + memset(vis,0,sizeof(vis)); + m=0; + for(int i=1;i<=maxx;i++) + { + for(int j=1;j<=maxy;j++) + if(map[i][j]==1&&vis[i][j]==0) + { + dfs(i,j); + ans++; + if(m==n) + break; + } + if(m==n) + break; + } + printf("%d\n",ans-1); + } + return 0; +} + + + diff --git a/pool/shard001/C++/0017976_npc_rentalmount.cpp b/pool/shard001/C++/0017976_npc_rentalmount.cpp new file mode 100644 index 0000000000000000000000000000000000000000..956176d0bce19eeb47de925a5029e95b00aa102f --- /dev/null +++ b/pool/shard001/C++/0017976_npc_rentalmount.cpp @@ -0,0 +1,65 @@ +#include "ScriptPCH.h" +#include "Config/Config.h" + +#define MSG_GOSSIP_TEXT_1 "Ich möchte ein Reittier mieten (Kosten 1s)" +#define MSG_GOSSIP_TEXT_2 "Ich möchte ein sehr schnelles Reittier mieten (Kosten 5s)" +#define MSG_NOT_MONEY "Du hast nicht genügend Gold." +#define MSG_MOUTED "Du hast bereits ein Reittier" +#define MOUNT_SPELL_ID_1 43899 +#define MOUNT_SPELL_ID_2 43900 + +bool GossipHello_npc_rentalmount(Player *player, Creature *_creature) +{ + player->ADD_GOSSIP_ITEM(4, MSG_GOSSIP_TEXT_1, GOSSIP_SENDER_MAIN, 1001); + player->ADD_GOSSIP_ITEM(4, MSG_GOSSIP_TEXT_2, GOSSIP_SENDER_MAIN, 1002); + player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, _creature->GetGUID()); + return true; +} + +bool GossipSelect_npc_rentalmount(Player *player, Creature *_creature, uint32 sender, uint32 action ) +{ + if (sender != GOSSIP_SENDER_MAIN) + return false; + + if (player->IsMounted()){ + _creature->MonsterWhisper(MSG_MOUTED, player->GetGUID()); + return false; + } + + uint32 slowprice = sConfig.GetIntDefault("RentalMountNPC.SlowPrice",100); + uint32 fastprice = sConfig.GetIntDefault("RentalMountNPC.FastPrice",500); + + switch (action) + { + case 1001: + if (player->GetMoney() < slowprice) + { + _creature->MonsterWhisper(MSG_NOT_MONEY, player->GetGUID()); + } else { + player->AddAura(MOUNT_SPELL_ID_1, player); + player->ModifyMoney(-slowprice); + } + break; + case 1002: + if (player->GetMoney() < fastprice) + { + _creature->MonsterWhisper(MSG_NOT_MONEY, player->GetGUID()); + } else { + player->AddAura(MOUNT_SPELL_ID_2, player); + player->ModifyMoney(-fastprice); + } + break; + } + player->CLOSE_GOSSIP_MENU(); + return true; +} + +void AddSC_npc_rentalmount() +{ + Script *newscript; + newscript = new Script; + newscript->Name = "npc_rentalmount"; + newscript->pGossipHello = &GossipHello_npc_rentalmount; + newscript->pGossipSelect = &GossipSelect_npc_rentalmount; + newscript->RegisterSelf(); +} diff --git a/pool/shard001/C++/0017977_Image.cpp b/pool/shard001/C++/0017977_Image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2894710bd497d253265db38ef51dca72c31f5cb --- /dev/null +++ b/pool/shard001/C++/0017977_Image.cpp @@ -0,0 +1,223 @@ +/* + **************************************************************************** + * Copyright (c) 2014 Uriah Liggett * + * This file is part of FreeLSS. * + * * + * FreeLSS 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. * + * * + * FreeLSS 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 FreeLSS. If not, see . * + **************************************************************************** +*/ + +#include "Main.h" +#include "Image.h" +#include "Camera.h" + +static void InitBuffer(jpeg_compress_struct* cinfo) { } +static boolean EmptyBuffer(jpeg_compress_struct* cinfo) { return TRUE; } +static void TermBuffer(jpeg_compress_struct* cinfo) { } + + +namespace freelss +{ + +Image::Image() : + m_pixels(NULL), + m_numComponents(0), + m_width(0), + m_height(0), + m_owner(true) +{ + Camera * camera = Camera::getInstance(); + m_height = camera->getImageHeight(); + m_width = camera->getImageWidth(); + m_numComponents = camera->getImageComponents(); +} + +Image::Image(unsigned width, unsigned height, unsigned numComponents): + m_pixels(NULL), + m_numComponents(numComponents), + m_width(width), + m_height(height), + m_owner(true) +{ + // Do nothing +} + +Image::~Image() +{ + if (m_owner) + { + delete [] m_pixels; + } +} + +void Image::assignPixels(unsigned char * newPixels) +{ + if (m_owner) + { + delete [] m_pixels; + m_owner = false; + } + + m_pixels = newPixels; +} + +bool Image::isOwner() const +{ + return m_owner; +} + +unsigned Image::getHeight() const +{ + return m_height; +} + +unsigned Image::getWidth() const +{ + return m_width; +} + +unsigned char * Image::getPixels() +{ + if (m_pixels == NULL) + { + m_pixels = new unsigned char [m_numComponents * m_height * m_width]; + m_owner = true; + } + + return m_pixels; +} + +unsigned Image::getNumComponents() const +{ + return m_numComponents; +} + +unsigned Image::getPixelBufferSize() const +{ + return m_width * m_height * m_numComponents; +} + +void Image::convertToJpeg(Image& image, byte* buffer, unsigned * size) +{ + size_t bufferSize = * size; + + struct jpeg_destination_mgr dmgr; + dmgr.init_destination = InitBuffer; + dmgr.empty_output_buffer = EmptyBuffer; + dmgr.term_destination = TermBuffer; + dmgr.next_output_byte = buffer; + dmgr.free_in_buffer = bufferSize; + + struct jpeg_compress_struct cinfo; + + struct jpeg_error_mgr jerr; + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_compress(&cinfo); + + cinfo.dest = &dmgr; + cinfo.image_width = image.getWidth(); + cinfo.image_height = image.getHeight(); + cinfo.input_components = image.getNumComponents(); + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality (&cinfo, 90, true); + jpeg_start_compress(&cinfo, true); + + unsigned rowSize = cinfo.image_width * cinfo.input_components; + + JSAMPROW rowPointer; + unsigned char * pixels = image.getPixels(); + + // Write the JPEG data + while (cinfo.next_scanline < cinfo.image_height) + { + rowPointer = (JSAMPROW) &pixels[cinfo.next_scanline * rowSize]; + jpeg_write_scanlines(&cinfo, &rowPointer, 1); + } + + jpeg_finish_compress(&cinfo); + + * size = bufferSize - dmgr.free_in_buffer; +} + + +void Image::writeJpeg(Image& image, const std::string& filename) +{ + std::cout << "Writing " << filename << "..." << std::endl; + + // Get the image from the camera + unsigned imageSize = image.getPixelBufferSize(); + byte * imageData = (byte *) malloc(imageSize); + if (imageData == NULL) + { + throw Exception("Out of memory"); + } + + std::ofstream fout (filename.c_str()); + if (!fout.is_open()) + { + free(imageData); + throw Exception("Error opening file for writing: " + filename); + } + + try + { + // Convert to JPEG + Image::convertToJpeg(image, imageData, &imageSize); + + // Write the JPEG to the disk + fout.write((const char *)imageData, imageSize); + } + catch (...) + { + fout.close(); + free(imageData); + throw; + } + + fout.close(); + free(imageData); +} + +void Image::overlayPixels(Image& image, PixelLocation * locations, int numLocations, unsigned char r, unsigned char g, unsigned b) +{ + int width = image.getWidth(); + int height = image.getHeight(); + int numComp = image.getNumComponents(); + unsigned char * pixels = image.getPixels(); + + int rowStep = (width * numComp); + for (int iLoc = 0; iLoc < numLocations; iLoc++) + { + const PixelLocation & location = locations[iLoc]; + int x = ROUND(location.x); + if (x < 0) x = 0; + if (x >= width) x = width - 1; + + int y = ROUND(location.y); + if (y < 0) y = 0; + if (y >= height) y = height - 1; + + // Find the pixels + unsigned char * px = pixels + (rowStep * y + x * numComp); + + // Set the pixel to red + px[0] = r; + px[1] = g; + px[2] = b; + } +} + +} diff --git a/pool/shard001/C++/0017979_remote_test_server_spawner_request.cc b/pool/shard001/C++/0017979_remote_test_server_spawner_request.cc new file mode 100644 index 0000000000000000000000000000000000000000..2fa5cf6cf4749edb2cada167b88e3078b88570c0 --- /dev/null +++ b/pool/shard001/C++/0017979_remote_test_server_spawner_request.cc @@ -0,0 +1,214 @@ +// 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 "net/test/spawned_test_server/remote_test_server_spawner_request.h" + +#include +#include + +#include "base/bind.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/synchronization/waitable_event.h" +#include "base/task/single_thread_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" +#include "build/build_config.h" +#include "net/base/elements_upload_data_stream.h" +#include "net/base/io_buffer.h" +#include "net/base/port_util.h" +#include "net/base/upload_bytes_element_reader.h" +#include "net/http/http_response_headers.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_test_util.h" +#include "url/gurl.h" + +namespace net { + +static const int kBufferSize = 2048; + +class RemoteTestServerSpawnerRequest::Core : public URLRequest::Delegate { + public: + Core(); + + Core(const Core&) = delete; + Core& operator=(const Core&) = delete; + + ~Core() override; + + void SendRequest(const GURL& url, const std::string& post_data); + + // Blocks until request is finished. If |response| isn't nullptr then server + // response is copied to *response. Returns true if the request was completed + // successfully. + bool WaitForCompletion(std::string* response) WARN_UNUSED_RESULT; + + private: + // URLRequest::Delegate methods. + void OnResponseStarted(URLRequest* request, int net_error) override; + void OnReadCompleted(URLRequest* request, int num_bytes) override; + + void ReadResponse(); + void OnCommandCompleted(int net_error); + + // Request results. + int result_code_ = 0; + std::string data_received_; + + // WaitableEvent to notify when the request is finished. + base::WaitableEvent event_; + + std::unique_ptr context_; + std::unique_ptr request_; + + scoped_refptr read_buffer_; + + THREAD_CHECKER(thread_checker_); +}; + +RemoteTestServerSpawnerRequest::Core::Core() + : event_(base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED), + read_buffer_(base::MakeRefCounted(kBufferSize)) { + DETACH_FROM_THREAD(thread_checker_); +} + +void RemoteTestServerSpawnerRequest::Core::SendRequest( + const GURL& url, + const std::string& post_data) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + // Prepare the URLRequest for sending the command. + DCHECK(!request_.get()); + context_ = std::make_unique(); + request_ = context_->CreateRequest(url, DEFAULT_PRIORITY, this, + TRAFFIC_ANNOTATION_FOR_TESTS); + + if (post_data.empty()) { + request_->set_method("GET"); + } else { + request_->set_method("POST"); + std::unique_ptr reader( + UploadOwnedBytesElementReader::CreateWithString(post_data)); + request_->set_upload( + ElementsUploadDataStream::CreateWithReader(std::move(reader), 0)); + request_->SetExtraRequestHeaderByName(HttpRequestHeaders::kContentType, + "application/json", + /*override=*/true); + } + + request_->Start(); +} + +RemoteTestServerSpawnerRequest::Core::~Core() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); +} + +bool RemoteTestServerSpawnerRequest::Core::WaitForCompletion( + std::string* response) { + // Called by RemoteTestServerSpawnerRequest::WaitForCompletion() on the main + // thread. + + event_.Wait(); + if (response) + *response = data_received_; + return result_code_ == OK; +} + +void RemoteTestServerSpawnerRequest::Core::OnCommandCompleted(int net_error) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK_NE(ERR_IO_PENDING, net_error); + DCHECK(!event_.IsSignaled()); + + // If request has failed, return the error code. + if (net_error != OK) { + LOG(ERROR) << "request failed, error: " << ErrorToString(net_error); + result_code_ = net_error; + } else if (request_->GetResponseCode() != 200) { + LOG(ERROR) << "Spawner server returned bad status: " + << request_->response_headers()->GetStatusLine() << ", " + << data_received_; + result_code_ = ERR_FAILED; + } + + if (result_code_ != OK) + data_received_.clear(); + + request_.reset(); + context_.reset(); + + event_.Signal(); +} + +void RemoteTestServerSpawnerRequest::Core::ReadResponse() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + while (true) { + int result = request_->Read(read_buffer_.get(), kBufferSize); + if (result == ERR_IO_PENDING) + return; + + if (result <= 0) { + OnCommandCompleted(result); + return; + } + + data_received_.append(read_buffer_->data(), result); + } +} + +void RemoteTestServerSpawnerRequest::Core::OnResponseStarted( + URLRequest* request, + int net_error) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK_NE(ERR_IO_PENDING, net_error); + DCHECK_EQ(request, request_.get()); + + if (net_error != OK) { + OnCommandCompleted(net_error); + return; + } + + ReadResponse(); +} + +void RemoteTestServerSpawnerRequest::Core::OnReadCompleted(URLRequest* request, + int read_result) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK_NE(ERR_IO_PENDING, read_result); + DCHECK_EQ(request, request_.get()); + + if (read_result <= 0) { + OnCommandCompleted(read_result); + return; + } + + data_received_.append(read_buffer_->data(), read_result); + + ReadResponse(); +} + +RemoteTestServerSpawnerRequest::RemoteTestServerSpawnerRequest( + scoped_refptr io_task_runner, + const GURL& url, + const std::string& post_data) + : io_task_runner_(io_task_runner), + core_(new Core()), + allowed_port_(new ScopedPortException(url.EffectiveIntPort())) { + io_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Core::SendRequest, + base::Unretained(core_.get()), url, post_data)); +} + +RemoteTestServerSpawnerRequest::~RemoteTestServerSpawnerRequest() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + io_task_runner_->DeleteSoon(FROM_HERE, core_.release()); +} + +bool RemoteTestServerSpawnerRequest::WaitForCompletion(std::string* response) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return core_->WaitForCompletion(response); +} + +} // namespace net diff --git a/pool/shard001/C++/0017981_CWE127_Buffer_Underread__new_wchar_t_loop_83_bad.cpp b/pool/shard001/C++/0017981_CWE127_Buffer_Underread__new_wchar_t_loop_83_bad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3293274cdaaa2c6d210fe12d08fbeb3b6fe70384 --- /dev/null +++ b/pool/shard001/C++/0017981_CWE127_Buffer_Underread__new_wchar_t_loop_83_bad.cpp @@ -0,0 +1,55 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__new_wchar_t_loop_83_bad.cpp +Label Definition File: CWE127_Buffer_Underread__new.label.xml +Template File: sources-sink-83_bad.tmpl.cpp +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack + * + * */ +#ifndef OMITBAD + +#include "std_testcase.h" +#include "CWE127_Buffer_Underread__new_wchar_t_loop_83.h" + +namespace CWE127_Buffer_Underread__new_wchar_t_loop_83 +{ +CWE127_Buffer_Underread__new_wchar_t_loop_83_bad::CWE127_Buffer_Underread__new_wchar_t_loop_83_bad(wchar_t * dataCopy) +{ + data = dataCopy; + { + wchar_t * dataBuffer = new wchar_t[100]; + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } +} + +CWE127_Buffer_Underread__new_wchar_t_loop_83_bad::~CWE127_Buffer_Underread__new_wchar_t_loop_83_bad() +{ + { + size_t i; + wchar_t dest[100]; + wmemset(dest, L'C', 100-1); /* fill with 'C's */ + dest[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + for (i = 0; i < 100; i++) + { + dest[i] = data[i]; + } + /* Ensure null termination */ + dest[100-1] = L'\0'; + printWLine(dest); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by new [] so can't safely call delete [] on it */ + } +} +} +#endif /* OMITBAD */ diff --git a/pool/shard001/C++/0017985_ReputationTests.cpp b/pool/shard001/C++/0017985_ReputationTests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8410be0f22c57aedcc31c95101dfd2a392bf1ee --- /dev/null +++ b/pool/shard001/C++/0017985_ReputationTests.cpp @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#include "pch.h" +#define TEST_CLASS_OWNER L"jasonsa" +#define TEST_CLASS_AREA L"Reputation" +#include "UnitTestIncludes.h" + +#include "Utils_WinRT.h" +#include "WinRT/ReputationFeedbackType_WinRT.h" +#include "xsapi\social.h" +#include "social_internal.h" + +// TODO 718292: HTTP error handling +using namespace Microsoft::Xbox::Services; +using namespace Microsoft::Xbox::Services::System; +using namespace xbox::services::system; +using namespace xbox::services::social; +using namespace Microsoft::Xbox::Services::Social; + +NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN + +struct ReputationTestValues +{ + Platform::String^ xboxUserId; + Windows::Foundation::DateTime dateCreated; + uint32 overallReputation; + uint32 fairplayReputation; + uint32 commsReputation; + uint32 ugcReputation; +}; + +const std::wstring defaultUserReputationData = +LR"( +{ + "items": + [ + { + "xuid" : "98052", + "dateCreated" : "2012-06-13T16:22:21Z", + "overallReputation" : 3, + "fairplayReputation" : 5, + "commsReputation" : 2, + "ugcReputation" : 1 + }, + { + "xuid" : "98052", + "dateCreated" : "2012-06-15T21:15:07Z", + "overallReputation" : 9, + "fairplayReputation" : 8, + "commsReputation" : 0, + "ugcReputation" : 1 + } + ] + +} +)"; + +DEFINE_TEST_CLASS(ReputationTests) +{ +public: + DEFINE_TEST_CLASS_PROPS(ReputationTests) + + void TestSubmitReputationFeedback( + ReputationFeedbackType reputationFeedback, + Platform::String^ sessionName, + Platform::String^ reasonMessage, + Platform::String^ evidenceResourceId + ) + { + auto responseJson = web::json::value::parse(defaultUserReputationData); + auto httpCall = m_mockXboxSystemFactory->GetMockHttpCall(); + httpCall->ResultValue = StockMocks::CreateMockHttpCallResponse(responseJson); + + XboxLiveContext^ xboxLiveContext = GetMockXboxLiveContext_WinRT(); + auto success = create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + "98052", + reputationFeedback, + sessionName, + reasonMessage, + evidenceResourceId + ) + ).wait(); + VERIFY_ARE_EQUAL_STR(L"POST", httpCall->HttpMethod); + VERIFY_ARE_EQUAL_STR(L"https://reputation.mockenv.xboxlive.com", httpCall->ServerName); + VERIFY_ARE_EQUAL_STR(L"/users/xuid(98052)/feedback", httpCall->PathQueryFragment.to_string()); + + auto requestJson = web::json::value::parse(httpCall->request_body().request_message_string()); + auto feedbackRequest = reputation_feedback_request::convert_reputation_feedback_type_to_string(static_cast(reputationFeedback)); + VERIFY_IS_TRUE(!feedbackRequest.err() && !feedbackRequest.payload().empty()); + if (!sessionName->IsEmpty()) + { + VERIFY_ARE_EQUAL_STR(sessionName->Data(), requestJson[L"sessionName"].as_string()); + } + if (!reasonMessage->IsEmpty()) + { + VERIFY_ARE_EQUAL_STR(reasonMessage->Data(), requestJson[L"textReason"].as_string()); + } + if (!evidenceResourceId->IsEmpty()) + { + VERIFY_ARE_EQUAL_STR(evidenceResourceId->Data(), requestJson[L"evidenceId"].as_string()); + } + } + + DEFINE_TEST_CASE(TestSubmitReputationFeedbackAsync) + { + DEFINE_TEST_CASE_PROPERTIES(TestSubmitReputationFeedbackAsync); + Platform::String^ sessionName = L"SecretSession"; + Platform::String^ reasonMessage = L"Yelled Loudly"; + Platform::String^ evidenceResourceId= L"99991999"; + + TestSubmitReputationFeedback(ReputationFeedbackType::CommunicationsAbusiveVoice, sessionName, reasonMessage, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::CommunicationsInappropriateVideo, nullptr, reasonMessage, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::FairPlayCheater, sessionName, nullptr, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::FairPlayKicked, sessionName, reasonMessage, nullptr); + TestSubmitReputationFeedback(ReputationFeedbackType::FairPlayKillsTeammates, nullptr, nullptr, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::FairPlayQuitter, nullptr, reasonMessage, nullptr); + TestSubmitReputationFeedback(ReputationFeedbackType::FairPlayTampering, sessionName, nullptr, nullptr); + TestSubmitReputationFeedback(ReputationFeedbackType::InappropriateUserGeneratedContent, nullptr, nullptr, nullptr); + TestSubmitReputationFeedback(ReputationFeedbackType::PositiveHelpfulPlayer, sessionName, reasonMessage, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::PositiveHighQualityUserGeneratedContent, sessionName, nullptr, evidenceResourceId); + TestSubmitReputationFeedback(ReputationFeedbackType::PositiveSkilledPlayer, sessionName, reasonMessage, evidenceResourceId); + } + + DEFINE_TEST_CASE(TestSubmitReputationFeedbackAsyncInvalidArgs) + { + DEFINE_TEST_CASE_PROPERTIES(TestSubmitReputationFeedbackAsyncInvalidArgs); + auto responseJson = web::json::value::parse(defaultUserReputationData); + m_mockXboxSystemFactory->GetMockHttpCall()->ResultValue = StockMocks::CreateMockHttpCallResponse(responseJson); + + XboxLiveContext^ xboxLiveContext = GetMockXboxLiveContext_WinRT(); + +#pragma warning(suppress: 6387) + VERIFY_THROWS_HR_CX( + create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + nullptr, // invalid arg + ReputationFeedbackType::FairPlayCheater, + nullptr, + nullptr, + nullptr + )).get(), + E_INVALIDARG + ) + + VERIFY_THROWS_HR_CX( + create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + L"", // invalid arg + ReputationFeedbackType::FairPlayCheater, + nullptr, + nullptr, + nullptr + )).get(), + E_INVALIDARG + ) + + Platform::String^ emptyXboxUserId; +#pragma warning(suppress: 6387) + VERIFY_THROWS_HR_CX( + create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + emptyXboxUserId, // invalid arg + ReputationFeedbackType::FairPlayCheater, + nullptr, + nullptr, + nullptr + )).get(), + E_INVALIDARG + ) + + Platform::String^ xuid = L"98052"; + + VERIFY_THROWS_HR_CX( + create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + xuid, + static_cast((int)ReputationFeedbackType::FairPlayKillsTeammates - 1), // invalid arg + nullptr, + nullptr, + nullptr + )).get(), + E_INVALIDARG + ) + + VERIFY_THROWS_HR_CX( + create_task(xboxLiveContext->ReputationService->SubmitReputationFeedbackAsync( + xuid, + static_cast((int)ReputationFeedbackType::FairPlayLeaderboardCheater + 1), // invalid arg + nullptr, + nullptr, + nullptr + )).get(), + E_INVALIDARG + ) + } + +}; + +NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END diff --git a/pool/shard001/C++/0017991_paymentserver.cpp b/pool/shard001/C++/0017991_paymentserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5843d66dbec57232062006f87c679ba5d400daf3 --- /dev/null +++ b/pool/shard001/C++/0017991_paymentserver.cpp @@ -0,0 +1,165 @@ +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include "paymentserver.h" + +#include "guiconstants.h" +#include "ui_interface.h" +#include "util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost; + +const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds +const QString BITCOIN_IPC_PREFIX("perkcoin:"); + +// +// Create a name that is unique for: +// testnet / non-testnet +// data directory +// +static QString ipcServerName() +{ + QString name("PerkcoinQt"); + + // Append a simple hash of the datadir + // Note that GetDataDir(true) returns a different path + // for -testnet versus main net + QString ddir(GetDataDir(true).string().c_str()); + name.append(QString::number(qHash(ddir))); + + return name; +} + +// +// This stores payment requests received before +// the main GUI window is up and ready to ask the user +// to send payment. +// +static QStringList savedPaymentRequests; + +// +// Sending to the server is done synchronously, at startup. +// If the server isn't already running, startup continues, +// and the items in savedPaymentRequest will be handled +// when uiReady() is called. +// +bool PaymentServer::ipcSendCommandLine() +{ + bool fResult = false; + + const QStringList& args = qApp->arguments(); + for (int i = 1; i < args.size(); i++) + { + if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) + continue; + savedPaymentRequests.append(args[i]); + } + + foreach (const QString& arg, savedPaymentRequests) + { + QLocalSocket* socket = new QLocalSocket(); + socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); + if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) + return false; + + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_0); + out << arg; + out.device()->seek(0); + socket->write(block); + socket->flush(); + + socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); + socket->disconnectFromServer(); + delete socket; + fResult = true; + } + return fResult; +} + +PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) +{ + // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) + parent->installEventFilter(this); + + QString name = ipcServerName(); + + // Clean up old socket leftover from a crash: + QLocalServer::removeServer(name); + + uriServer = new QLocalServer(this); + + if (!uriServer->listen(name)) + qDebug() << tr("Cannot start perkcoin: click-to-pay handler"); + else + connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); +} + +bool PaymentServer::eventFilter(QObject *object, QEvent *event) +{ + // clicking on bitcoin: URLs creates FileOpen events on the Mac: + if (event->type() == QEvent::FileOpen) + { + QFileOpenEvent* fileEvent = static_cast(event); + if (!fileEvent->url().isEmpty()) + { + if (saveURIs) // Before main window is ready: + savedPaymentRequests.append(fileEvent->url().toString()); + else + emit receivedURI(fileEvent->url().toString()); + return true; + } + } + return false; +} + +void PaymentServer::uiReady() +{ + saveURIs = false; + foreach (const QString& s, savedPaymentRequests) + emit receivedURI(s); + savedPaymentRequests.clear(); +} + +void PaymentServer::handleURIConnection() +{ + QLocalSocket *clientConnection = uriServer->nextPendingConnection(); + + while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) + clientConnection->waitForReadyRead(); + + connect(clientConnection, SIGNAL(disconnected()), + clientConnection, SLOT(deleteLater())); + + QDataStream in(clientConnection); + in.setVersion(QDataStream::Qt_4_0); + if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { + return; + } + QString message; + in >> message; + + if (saveURIs) + savedPaymentRequests.append(message); + else + emit receivedURI(message); +} + +void PaymentServer::setOptionsModel(OptionsModel *optionsModel) +{ + this->optionsModel = optionsModel; +} diff --git a/pool/shard001/C++/0017996_lw2_4.cpp b/pool/shard001/C++/0017996_lw2_4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..315930343d1187c10406001873a618acec5400c5 --- /dev/null +++ b/pool/shard001/C++/0017996_lw2_4.cpp @@ -0,0 +1,173 @@ +#include "stdafx.h" + +using namespace std; + +const int PARAMS_COUNT = 4; +const char* PACK_ARGUMENT = "pack"; +const char* UNPACK_ARGUMENT = "unpack"; + +enum class ErrorCodeType +{ + OpenFiles, + ParsingModeParameter, + WrongParamsNumber, + PackedFileDamaged +}; + +struct RLEChunk +{ + unsigned char count; + char val; +}; + +typedef bool(*RLEProcessor)(ifstream&, ofstream&, ErrorCodeType&); + +RLEChunk ReadChunk(ifstream &input) +{ + RLEChunk chunk; + input.read(reinterpret_cast(&chunk), sizeof(chunk)); + return chunk; +} + +void ReadCharSequence(ifstream& input, RLEChunk & chunk) +{ + chunk.val = input.get(); + chunk.count = 1; + while (!input.eof() && (chunk.val == input.peek()) && (chunk.count < UCHAR_MAX)) + { + chunk.val = input.get(); + ++chunk.count; + } +} + +void WriteChunk(ofstream &output, RLEChunk const& chunk) +{ + output.write(reinterpret_cast(&chunk), sizeof(chunk)); +} + +void ExpandChunk(ofstream &output, RLEChunk const& chunk) +{ + for (int i = 0; i < chunk.count; ++i) + { + output.put(chunk.val); + } +} + +streamoff GetFileSize(ifstream & input) +{ + auto currPos = input.tellg(); + input.seekg(0, ios::end); + auto size = input.tellg(); + input.seekg(currPos, ios::beg); + return size; +} + +bool CanUnpack(ifstream & input) +{ + return (GetFileSize(input) % 2 == 0); +} + +bool Pack(ifstream& input, ofstream& output, ErrorCodeType &errorCode) +{ + RLEChunk chunk; + while (!input.eof()) + { + ReadCharSequence(input, chunk); + WriteChunk(output, chunk); + } + return true; +} + +bool Unpack(ifstream& input, ofstream& output, ErrorCodeType &errorCode) +{ + if (!CanUnpack(input)) + { + errorCode = ErrorCodeType::PackedFileDamaged; + return false; + } + + RLEChunk chunk; + while (input.peek() != EOF) + { + chunk = ReadChunk(input); + ExpandChunk(output, chunk); + } + return true; +} + +RLEProcessor GetProgramByMode(const char* str) +{ + RLEProcessor funcPtr = nullptr; + if (strcmp(str, PACK_ARGUMENT) == 0) + { + funcPtr = Pack; + } + else if (strcmp(str, UNPACK_ARGUMENT) == 0) + { + funcPtr = Unpack; + } + return funcPtr; +} + +void PrintErrorByCode(const ErrorCodeType errorCode) +{ + switch (errorCode) + { + case ErrorCodeType::OpenFiles: + { + cout << "Can't Open Files!" << endl; + break; + } + case ErrorCodeType::ParsingModeParameter: + { + cout << "Invalid mode parameter\nUsage: [pack | unpack]" << endl; + break; + } + case ErrorCodeType::WrongParamsNumber: + { + cout << "Wrong number of parameters!" << endl; + break; + } + case ErrorCodeType::PackedFileDamaged: + { + cout << "Can't unpack, input file damaged!" << endl; + break; + } + } +} + +int main(int argc, char* argv[]) +{ + if (argc != PARAMS_COUNT) + { + PrintErrorByCode(ErrorCodeType::WrongParamsNumber); + return 1; + } + + RLEProcessor processor = GetProgramByMode(argv[1]); + if (!processor) + { + PrintErrorByCode(ErrorCodeType::ParsingModeParameter); + return 1; + } + + ifstream input(argv[2], ios::in | ios::binary); + ofstream output(argv[3], ios::out | ios::binary); + if (input.bad() || output.bad()) + { + PrintErrorByCode(ErrorCodeType::OpenFiles); + return 1; + } + + ErrorCodeType errorCode; + if (!(*processor)(input, output, errorCode)) + { + PrintErrorByCode(errorCode); + return 1; + } + + input.close(); + output.close(); + + return 0; +} \ No newline at end of file diff --git a/pool/shard001/C++/0018010_timer_test.cpp b/pool/shard001/C++/0018010_timer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54509855fa3ef05f0d9adbca76d585c1ec0a7768 --- /dev/null +++ b/pool/shard001/C++/0018010_timer_test.cpp @@ -0,0 +1,85 @@ +// timer_test.cpp +// +// Test QTimer Accuracy +// +// (C) Copyright 2013 Fred Gleason +// +// $Id: timer_test.cpp,v 1.1.2.1 2013/02/07 18:22:06 cvs Exp $ +// +// 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., 675 Mass Ave, Cambridge, MA 02139, USA. +// + +#include + +#include + +#include + +MainObject::MainObject(QObject *parent,const char *name) + : QObject(parent,name) +{ + // + // Timer + // + test_timer=new QTimer(this); + connect(test_timer,SIGNAL(timeout()),this,SLOT(timeoutData())); + + // + // Start Run + // + test_interval=60000; + if(gettimeofday(&test_start_tv,NULL) !=0) { + perror("gettimeofday"); + } + test_timer->start(test_interval,true); +} + + +void MainObject::timeoutData() +{ + // + // Calculate Result + // + if(gettimeofday(&test_end_tv,NULL) !=0) { + perror("gettimeofday"); + } + double expected=(double)test_interval/1000.0; + double got=Time(&test_end_tv)-Time(&test_start_tv); + + printf("Expected: %12.3lf Got: %12.3lf Diff: %8.3lf%%\n", + expected,got,100.0*got/expected); + + // + // Start Next Run + // + test_interval*=2; + if(gettimeofday(&test_start_tv,NULL) !=0) { + perror("gettimeofday"); + } + test_timer->start(test_interval,true); +} + + +double MainObject::Time(struct timeval *tv) +{ + return (double)tv->tv_sec+(double)tv->tv_usec/1000000.0; +} + + +int main(int argc,char *argv[]) +{ + QApplication a(argc,argv,false); + new MainObject(NULL,"main"); + return a.exec(); +} diff --git a/pool/shard001/C++/0018011_pixSpecularGLSL.cpp b/pool/shard001/C++/0018011_pixSpecularGLSL.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5227cfa57aa96e31a559f602e14ba9cfe9f56471 --- /dev/null +++ b/pool/shard001/C++/0018011_pixSpecularGLSL.cpp @@ -0,0 +1,166 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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 "platform/platform.h" +#include "shaderGen/GLSL/pixSpecularGLSL.h" +#include "materials/processedMaterial.h" +#include "materials/materialFeatureTypes.h" +#include "shaderGen/shaderOp.h" +#include "shaderGen/shaderGenVars.h" +#include "gfx/gfxStructs.h" +#include "shaderGen/shaderGen.h" + +PixelSpecularGLSL::PixelSpecularGLSL() + : mDep(ShaderGen::smCommonShaderPath + String("/gl/lighting.glsl" )) +{ + addDependency( &mDep ); +} + +void PixelSpecularGLSL::processVert( Vector &componentList, + const MaterialFeatureData &fd ) +{ + AssertFatal( fd.features[MFT_RTLighting], + "PixelSpecularHLSL requires RTLighting to be enabled!" ); + + // Nothing to do here... MFT_RTLighting should have + // taken care of passing everything to the pixel shader. +} + +void PixelSpecularGLSL::processPix( Vector &componentList, + const MaterialFeatureData &fd ) +{ + AssertFatal( fd.features[MFT_RTLighting], + "PixelSpecularHLSL requires RTLighting to be enabled!" ); + + // RTLighting should have spit out the 4 specular + // powers for the 4 potential lights on this pass. + // + // This can sometimes be NULL if RTLighting skips out + // on us for lightmaps or missing normals. + Var *specular = (Var*)LangElement::find( "specular" ); + if ( !specular ) + return; + + MultiLine *meta = new MultiLine; + + LangElement *specMul = new GenOp( "@", specular ); + LangElement *final = specMul; + + // mask out with lightmap if present + if ( fd.features[MFT_LightMap] ) + { + LangElement *lmColor = NULL; + + // find lightmap color + lmColor = LangElement::find( "lmColor" ); + + if ( !lmColor ) + { + LangElement * lightMap = LangElement::find( "lightMap" ); + LangElement * lmCoord = LangElement::find( "texCoord2" ); + + lmColor = new GenOp( "texture(@, @)", lightMap, lmCoord ); + } + + final = new GenOp( "@ * vec4(@.rgb,0)", specMul, lmColor ); + } + + // If we have a normal map then mask the specular + if ( fd.features[MFT_SpecularMap] ) + { + Var *specularColor = (Var*)LangElement::find( "specularColor" ); + if (specularColor) + final = new GenOp( "@ * @", final, specularColor ); + } + else if ( fd.features[MFT_NormalMap] && !fd.features[MFT_IsBC3nm] && !fd.features[MFT_IsBC5nm]) + { + Var *bumpColor = (Var*)LangElement::find( "bumpNormal" ); + final = new GenOp( "@ * @.a", final, bumpColor ); + } + + // Add the specular to the final color. + // search for color var + Var *color = (Var*)LangElement::find( "col" ); + meta->addStatement( new GenOp( " @.rgb += ( @ ).rgb;\r\n", color, final ) ); + + output = meta; +} + +ShaderFeature::Resources PixelSpecularGLSL::getResources( const MaterialFeatureData &fd ) +{ + Resources res; + return res; +} + +void SpecularMapGLSL::processVert(Vector &componentList, const MaterialFeatureData &fd) +{ + MultiLine *meta = new MultiLine; + + // Add the texture coords. + getOutTexCoord("texCoord", + "vec2", + fd.features[MFT_TexAnim], + meta, + componentList); + + output = meta; +} + +void SpecularMapGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) +{ + // Get the texture coord. + Var *texCoord = getInTexCoord( "texCoord", "vec2", componentList ); + + // create texture var + Var *specularMap = new Var; + specularMap->setType( "sampler2D" ); + specularMap->setName( "specularMap" ); + specularMap->uniform = true; + specularMap->sampler = true; + specularMap->constNum = Var::getTexUnitNum(); + LangElement *texOp = new GenOp( "texture(@, @)", specularMap, texCoord ); + + Var *specularColor = new Var( "specularColor", "vec4" ); + + output = new GenOp( " @ = @;\r\n", new DecOp( specularColor ), texOp ); +} + +ShaderFeature::Resources SpecularMapGLSL::getResources( const MaterialFeatureData &fd ) +{ + Resources res; + res.numTex = 1; + return res; +} + +void SpecularMapGLSL::setTexData( Material::StageData &stageDat, + const MaterialFeatureData &fd, + RenderPassData &passData, + U32 &texIndex ) +{ + GFXTextureObject *tex = stageDat.getTex( MFT_SpecularMap ); + if ( tex ) + { + passData.mTexType[ texIndex ] = Material::Standard; + passData.mSamplerNames[ texIndex ] = "specularMap"; + passData.mTexSlot[ texIndex++ ].texObject = tex; + } +} diff --git a/pool/shard001/C++/0018013_HsaProgram.cc b/pool/shard001/C++/0018013_HsaProgram.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa8c621aa3f644206ab28c5abee5799812ae1ed4 --- /dev/null +++ b/pool/shard001/C++/0018013_HsaProgram.cc @@ -0,0 +1,60 @@ +/* + * Multi2Sim + * Copyright (C) 2014 Yifan Sun (yifansun@coe.neu.edu) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include + +#include "HsaProgram.h" + + +namespace HSA +{ + +HsaProgram::HsaProgram() : + modules() +{ +} + + +HsaProgram::HsaProgram(const HsaProgram &program): + HsaProgram() +{ + for (auto it = program.modules.begin(); + it != program.modules.end(); + it++) + { + AddModule((*it)->getBuffer()); + } +} + + +HsaProgram::~HsaProgram() +{ +} + + +void HsaProgram::AddModule(const char *module) +{ + auto binary = misc::new_unique(); + binary->LoadFileFromBuffer(module); + modules.push_back(std::move(binary)); +} + +} // namespace HSA + diff --git a/pool/shard001/C++/0018018_main.cpp b/pool/shard001/C++/0018018_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1f75b8cae8dc21adcec8242a068a1742bbabf0f --- /dev/null +++ b/pool/shard001/C++/0018018_main.cpp @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Digia Plc and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QObject *parent = &app; + + QStringList numbers; + numbers << "One" << "Two" << "Three" << "Four" << "Five"; + + QAbstractItemModel *stringListModel = new QStringListModel(numbers, parent); + +//! [0] + QSortFilterProxyModel *filterModel = new QSortFilterProxyModel(parent); + filterModel->setSourceModel(stringListModel); +//! [0] + + QWidget *window = new QWidget; + +//! [1] + QListView *filteredView = new QListView; + filteredView->setModel(filterModel); +//! [1] + filteredView->setWindowTitle("Filtered view onto a string list model"); + + QLineEdit *patternEditor = new QLineEdit; + QObject:: + connect(patternEditor, SIGNAL(textChanged(QString)), + filterModel, SLOT(setFilterRegExp(QString))); + + QVBoxLayout *layout = new QVBoxLayout(window); + layout->addWidget(filteredView); + layout->addWidget(patternEditor); + + window->show(); + return app.exec(); +} diff --git a/pool/shard001/C++/0018019_substructure.cpp b/pool/shard001/C++/0018019_substructure.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dea390d8954a922ddb169cf7b59ec38f9f742a7c --- /dev/null +++ b/pool/shard001/C++/0018019_substructure.cpp @@ -0,0 +1,171 @@ +#include "../src/substructure.h" +#include "../src/smiles.h" + +#include "test.h" + +using namespace Helium; + +void test_substructure1() +{ + HeMol mol = hemol_from_smiles("c1ccccc1c2ccccc2"); + + std::vector atoms1(num_atoms(mol)); + std::vector bonds1(num_bonds(mol)); + std::vector atoms2(num_atoms(mol)); + std::vector bonds2(num_bonds(mol)); + for (int i = 0; i < 6; ++i) { + atoms1[i] = true; + bonds1[i] = true; + atoms2[i + 6] = true; + bonds2[i + 7] = true; + } + + + Substructure substruct1(mol, atoms1, bonds1); + Substructure substruct2(mol, atoms2, bonds2); + + COMPARE(6, substruct2.oldAtomIndex(get_atom(substruct2, 0))); + COMPARE(7, substruct2.oldAtomIndex(get_atom(substruct2, 1))); + COMPARE(8, substruct2.oldAtomIndex(get_atom(substruct2, 2))); + COMPARE(9, substruct2.oldAtomIndex(get_atom(substruct2, 3))); + COMPARE(10, substruct2.oldAtomIndex(get_atom(substruct2, 4))); + COMPARE(11, substruct2.oldAtomIndex(get_atom(substruct2, 5))); + + COMPARE(7, substruct2.oldBondIndex(get_bond(substruct2, 0))); + COMPARE(8, substruct2.oldBondIndex(get_bond(substruct2, 1))); + COMPARE(9, substruct2.oldBondIndex(get_bond(substruct2, 2))); + COMPARE(10, substruct2.oldBondIndex(get_bond(substruct2, 3))); + COMPARE(11, substruct2.oldBondIndex(get_bond(substruct2, 4))); + COMPARE(12, substruct2.oldBondIndex(get_bond(substruct2, 5))); +} + + +int main() +{ + HeMol mol; + SMILES.read("CNOSP", mol); + + std::vector atoms(5), bonds(4); + atoms[1] = true; + atoms[2] = true; + atoms[3] = true; + bonds[1] = true; + bonds[2] = true; + + Substructure substruct(mol, atoms, bonds); + + //////////////////////////////////////////////// + // + // Substructure + // + //////////////////////////////////////////////// + + // test num_atoms + COMPARE(3, num_atoms(substruct)); + + // test get_atoms + unsigned int numAtoms = 0; + for (auto &atom : get_atoms(substruct)) { + HEUNUSED(atom); + ++numAtoms; + } + COMPARE(3, numAtoms); + + // test get_atom + COMPARE(get_atom(mol, 1), get_atom(substruct, 0)); + COMPARE(get_atom(mol, 2), get_atom(substruct, 1)); + COMPARE(get_atom(mol, 3), get_atom(substruct, 2)); + + // test num_bonds + COMPARE(2, num_bonds(substruct)); + + // test get_bonds + unsigned int numBonds = 0; + for (auto &bond : get_bonds(substruct)) { + HEUNUSED(bond); + ++numBonds; + } + COMPARE(2, numBonds); + + // test get_bond + COMPARE(get_bond(mol, 1), get_bond(substruct, 0)); + COMPARE(get_bond(mol, 2), get_bond(substruct, 1)); + + COMPARE(get_bond(mol, 1), get_bond(substruct, get_atom(substruct, 0), get_atom(substruct, 1))); + COMPARE(get_bond(mol, 2), get_bond(substruct, get_atom(substruct, 1), get_atom(substruct, 2))); + + //////////////////////////////////////////////// + // + // Atom + // + //////////////////////////////////////////////// + + // test get_index + COMPARE(0, get_index(substruct, get_atom(substruct, 0))); + COMPARE(1, get_index(substruct, get_atom(substruct, 1))); + COMPARE(2, get_index(substruct, get_atom(substruct, 2))); + + // test get_bonds + numBonds = 0; + for (auto &bond : get_bonds(substruct, get_atom(substruct, 0))) { + HEUNUSED(bond); + ++numBonds; + } + COMPARE(1, numBonds); + + numBonds = 0; + for (auto &bond : get_bonds(substruct, get_atom(substruct, 1))) { + HEUNUSED(bond); + ++numBonds; + } + COMPARE(2, numBonds); + + numBonds = 0; + for (auto &bond : get_bonds(substruct, get_atom(substruct, 2))) { + HEUNUSED(bond); + ++numBonds; + } + COMPARE(1, numBonds); + + // test get_nbrs + unsigned int numNbrs = 0; + for (auto &nbr : get_nbrs(substruct, get_atom(substruct, 0))) { + HEUNUSED(nbr); + ++numNbrs; + } + COMPARE(1, numNbrs); + + numNbrs = 0; + for (auto &nbr : get_nbrs(substruct, get_atom(substruct, 1))) { + HEUNUSED(nbr); + ++numNbrs; + } + COMPARE(2, numNbrs); + + numNbrs = 0; + for (auto &nbr : get_nbrs(substruct, get_atom(substruct, 2))) { + HEUNUSED(nbr); + ++numNbrs; + } + COMPARE(1, numNbrs); + + // test get_degree + COMPARE(1, get_degree(substruct, get_atom(substruct, 0))); + COMPARE(2, get_degree(substruct, get_atom(substruct, 1))); + COMPARE(1, get_degree(substruct, get_atom(substruct, 2))); + + //////////////////////////////////////////////// + // + // Atom + // + //////////////////////////////////////////////// + + // test get_index + COMPARE(0, get_index(substruct, get_bond(substruct, 0))); + COMPARE(1, get_index(substruct, get_bond(substruct, 1))); + + + test_substructure1(); + + //check_molecule_concept(Substructure(HeMol(), std::vector(), std::vector())); +} diff --git a/pool/shard001/C++/0018030_CustomEditControl.cpp b/pool/shard001/C++/0018030_CustomEditControl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d584d53748803d974553930bbbe7b31abd02fba7 --- /dev/null +++ b/pool/shard001/C++/0018030_CustomEditControl.cpp @@ -0,0 +1,31 @@ +#include "CustomEditControl.h" + +bool CCustomEditControl::AttachToDlgItem(HWND parent, UINT dlgID) { + + HWND hWnd = ::GetDlgItem(parent,dlgID); + return SubclassWindow(hWnd)!= FALSE; +} + +void CCustomEditControl::setOnPasteCallback(PasteCallback callback) { + onPasteCallback_ = std::move(callback); +} + +LRESULT CCustomEditControl::OnKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { + WPARAM vk = wParam; + if ( vk == _T('A') && GetKeyState(VK_CONTROL) & 0x80 ) { // Ctrl + A + SendMessage(EM_SETSEL, 0, -1); + } + bHandled = false; + return 0; +} + +LRESULT CCustomEditControl::OnPaste(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { + bHandled = false; + if ( onPasteCallback_ ) { + if (onPasteCallback_(this) ) { + bHandled = true; + } + } + + return 0; +} \ No newline at end of file diff --git a/pool/shard001/C++/0018031_addarraymembervisitor.cpp b/pool/shard001/C++/0018031_addarraymembervisitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3652dfe8860561dea441ef767416b34e83af4ab6 --- /dev/null +++ b/pool/shard001/C++/0018031_addarraymembervisitor.cpp @@ -0,0 +1,119 @@ +/************************************************************************** +** +** 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 "addarraymembervisitor.h" + +#include +#include + +using namespace QmlDesigner; +using namespace QmlDesigner::Internal; +using namespace QmlJS; +using namespace QmlJS::AST; + +AddArrayMemberVisitor::AddArrayMemberVisitor(QmlDesigner::TextModifier &modifier, + quint32 parentLocation, + const QString &propertyName, + const QString &content): + QMLRewriter(modifier), + m_parentLocation(parentLocation), + m_propertyName(propertyName), + m_content(content), + m_convertObjectBindingIntoArrayBinding(false) +{ +} + +void AddArrayMemberVisitor::findArrayBindingAndInsert(const QString &m_propertyName, UiObjectMemberList *ast) +{ + for (UiObjectMemberList *iter = ast; iter; iter = iter->next) { + if (UiArrayBinding *arrayBinding = cast(iter->member)) { + if (flatten(arrayBinding->qualifiedId) == m_propertyName) + insertInto(arrayBinding); + } else if (UiObjectBinding *objectBinding = cast(iter->member)) { + if (flatten(objectBinding->qualifiedId) == m_propertyName && willConvertObjectBindingIntoArrayBinding()) + convertAndAdd(objectBinding); + } + } +} + +bool AddArrayMemberVisitor::visit(QmlJS::AST::UiObjectBinding *ast) +{ + if (didRewriting()) + return false; + + if (ast->firstSourceLocation().offset == m_parentLocation) + findArrayBindingAndInsert(m_propertyName, ast->initializer->members); + + return !didRewriting(); +} + +bool AddArrayMemberVisitor::visit(QmlJS::AST::UiObjectDefinition *ast) +{ + if (didRewriting()) + return false; + + if (ast->firstSourceLocation().offset == m_parentLocation) + findArrayBindingAndInsert(m_propertyName, ast->initializer->members); + + return !didRewriting(); +} + +// FIXME: duplicate code in the QmlJS::Rewriter class, remove this +void AddArrayMemberVisitor::insertInto(QmlJS::AST::UiArrayBinding *arrayBinding) +{ + UiObjectMember *lastMember = 0; + for (UiArrayMemberList *iter = arrayBinding->members; iter; iter = iter->next) + if (iter->member) + lastMember = iter->member; + + if (!lastMember) + return; // an array binding cannot be empty, so there will (or should) always be a last member. + + const int insertionPoint = lastMember->lastSourceLocation().end(); + const int indentDepth = calculateIndentDepth(lastMember->firstSourceLocation()); + + replace(insertionPoint, 0, QLatin1String(",\n") + addIndentation(m_content, indentDepth)); + + setDidRewriting(true); +} + +void AddArrayMemberVisitor::convertAndAdd(QmlJS::AST::UiObjectBinding *objectBinding) +{ + const int indentDepth = calculateIndentDepth(objectBinding->firstSourceLocation()); + const QString arrayPrefix = QLatin1String("[\n") + addIndentation(QString(), indentDepth); + replace(objectBinding->qualifiedTypeNameId->identifierToken.offset, 0, arrayPrefix); + const int insertionPoint = objectBinding->lastSourceLocation().end(); + replace(insertionPoint, 0, + QLatin1String(",\n") + + addIndentation(m_content, indentDepth) + QLatin1Char('\n') + + addIndentation(QLatin1String("]"), indentDepth) + ); + + setDidRewriting(true); +} diff --git a/pool/shard001/C++/0018034_SaveImage.cpp b/pool/shard001/C++/0018034_SaveImage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09b63c46ad74cc77337f01fba64c2c95624f9adf --- /dev/null +++ b/pool/shard001/C++/0018034_SaveImage.cpp @@ -0,0 +1,58 @@ +// SaveImage.cpp +// this file is part of Context Free +// --------------------- +// Copyright (C) 2008 John Horigan - john@glyphic.com +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +// John Horigan can be contacted at john@glyphic.com or at +// John Horigan, 1209 Villa St., Mountain View, CA 94041-1123, USA +// +// + +#include "StdAfx.h" +#include "SaveImage.h" +#include "Form1.h" + +using namespace ContextFreeNet; +using namespace System; +using namespace System::Data; +using namespace System::ComponentModel; +using namespace System::Collections; +using namespace System::Windows::Forms; + +DialogResult SaveImage::ShowTheDialog(IWin32Window^ owner) +{ + checkCropImage->Checked = Form1::prefs->ImageCrop; + JPEGQuality->Text = Form1::prefs->JPEGQuality.ToString(); + DialogResult res = DialogResult::Cancel; + + try { + res = ShowDialog(owner); + if (res == DialogResult::OK) { + Form1::prefs->ImageCrop = checkCropImage->Checked; + Form1::prefs->JPEGQuality = System::Int32::Parse(JPEGQuality->Text); + } + } catch (Exception^) {} + + return res; +} + +void SaveImage::OnPrepareMSDialog() +{ + FileDlgFileName = fileName; + FileDlgInitialDirectory = fileDir; + FileDialogExtenders::FileDialogControlBase::OnPrepareMSDialog(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0018035_main.cpp b/pool/shard001/C++/0018035_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98ba574cd91cd3ffa9a0a8673b4341c916028227 --- /dev/null +++ b/pool/shard001/C++/0018035_main.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include "libABI.hh" +#include "NibblerCore.hh" +#include "NibblerSnake.hh" + +static void print_score_message(int score) +{ + if (score == 0) + std::cout << "You are really, really bad..." << std::endl; + if (score > 0) + std::cout << "Ragequit ? Anyway, your score is " << score << std::endl; + if (score < 0) + std::cout << "Hit that noob !! You only got " << -1 * score << std::endl; +} + +static int check_args(int ac, char **av, int *h, int *w) +{ + std::stringstream streamh; + std::stringstream streamw; + + if (ac != 4) { + std::cerr << "Usage: " << av[0] << " largeur hauteur lib_path" + << std::endl; + return (-42); + } + streamw << av[1]; + streamh << av[2]; + streamw >> *w; + streamh >> *h; + if (*w < WIDTH_MIN || *w > WIDTH_MAX) { + std::cerr << "Error: width must be " << WIDTH_MIN << " < width < " + << WIDTH_MAX << std::endl; + return (-42); + } + if (*h < HEIGHT_MIN || *h > HEIGHT_MAX) { + std::cerr << "Error: height must be " << HEIGHT_MIN << " < height < " + << HEIGHT_MAX << std::endl; + return (-42); + } + return (0); +} + +int main(int ac, char **av) +{ + NibblerCore *core; + IPlayer *snake; + int height; + int width; + int score = 0; + + if (check_args(ac, av, &height, &width)) + return (EXIT_FAILURE); + snake = new Snake(height, width); + core = new NibblerCore(height, width, snake); + srand(time(0)); + try { + if (-1 == core->getGraphicLib(av[3])) { + delete core; + return (EXIT_FAILURE); + } + score = core->run(); + } + catch (myException* excp) { + /* + * Some lib (ncurses ie) may avoid printing on cerr. + */ + delete core; + std::cerr << excp->what() << std::endl; + delete excp; + return (EXIT_FAILURE); + } + /* Cleanup */ + delete core; + print_score_message(score); + return (EXIT_SUCCESS); +} diff --git a/pool/shard001/C++/0018039_pi_generator.cc b/pool/shard001/C++/0018039_pi_generator.cc new file mode 100644 index 0000000000000000000000000000000000000000..2b5766f75c5ce80532a9e44bc0c92ee52f45c075 --- /dev/null +++ b/pool/shard001/C++/0018039_pi_generator.cc @@ -0,0 +1,242 @@ +// 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 +#include +#include +#include +#include +#include +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/var.h" + +#include "pi_generator.h" + +namespace { +const int kPthreadMutexSuccess = 0; +const char* const kPaintMethodId = "paint"; +const double kInvalidPiValue = -1.0; +const int kMaxPointCount = 1000000000; // The total number of points to draw. +const uint32_t kOpaqueColorMask = 0xff000000; // Opaque pixels. +const uint32_t kRedMask = 0xff0000; +const uint32_t kBlueMask = 0xff; +const uint32_t kRedShift = 16; +const uint32_t kBlueShift = 0; + +// This is called by the browser when the 2D context has been flushed to the +// browser window. +void FlushCallback(void* data, int32_t result) { + static_cast(data)->set_flush_pending(false); +} + +} // namespace + +namespace pi_generator { + +// A small helper RAII class that implements a scoped pthread_mutex lock. +class ScopedMutexLock { + public: + explicit ScopedMutexLock(pthread_mutex_t* mutex) : mutex_(mutex) { + if (pthread_mutex_lock(mutex_) != kPthreadMutexSuccess) { + mutex_ = NULL; + } + } + ~ScopedMutexLock() { + if (mutex_) + pthread_mutex_unlock(mutex_); + } + bool is_valid() const { + return mutex_ != NULL; + } + private: + pthread_mutex_t* mutex_; // Weak reference. +}; + +// A small helper RAII class used to acquire and release the pixel lock. +class ScopedPixelLock { + public: + explicit ScopedPixelLock(PiGenerator* image_owner) + : image_owner_(image_owner), pixels_(image_owner->LockPixels()) {} + + ~ScopedPixelLock() { + pixels_ = NULL; + image_owner_->UnlockPixels(); + } + + uint32_t* pixels() const { + return pixels_; + } + private: + PiGenerator* image_owner_; // Weak reference. + uint32_t* pixels_; // Weak reference. + + ScopedPixelLock(); // Not implemented, do not use. +}; + +PiGenerator::PiGenerator(PP_Instance instance) + : pp::Instance(instance), + graphics_2d_context_(NULL), + pixel_buffer_(NULL), + flush_pending_(false), + quit_(false), + thread_create_result_(0), + pi_(0.0) { + pthread_mutex_init(&pixel_buffer_mutex_, NULL); +} + +PiGenerator::~PiGenerator() { + quit_ = true; + if (thread_create_result_ == 0) { + pthread_join(compute_pi_thread_, NULL); + } + DestroyContext(); + // The ComputePi() thread should be gone by now, so there is no need to + // acquire the mutex for |pixel_buffer_|. + delete pixel_buffer_; + pthread_mutex_destroy(&pixel_buffer_mutex_); +} + +void PiGenerator::DidChangeView(const pp::View& view) { + pp::Rect position = view.GetRect(); + if (pixel_buffer_ && position.size() == pixel_buffer_->size()) + return; // Size didn't change, no need to update anything. + + // Create a new device context with the new size. + DestroyContext(); + CreateContext(position.size()); + // Delete the old pixel buffer and create a new one. + ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_); + delete pixel_buffer_; + pixel_buffer_ = NULL; + if (graphics_2d_context_ != NULL) { + pixel_buffer_ = new pp::ImageData(this, + PP_IMAGEDATAFORMAT_BGRA_PREMUL, + graphics_2d_context_->size(), + false); + } +} + +bool PiGenerator::Init(uint32_t argc, const char* argn[], const char* argv[]) { + thread_create_result_ = pthread_create(&compute_pi_thread_, NULL, ComputePi, + this); + return thread_create_result_ == 0; +} + +uint32_t* PiGenerator::LockPixels() { + void* pixels = NULL; + // Do not use a ScopedMutexLock here, since the lock needs to be held until + // the matching UnlockPixels() call. + if (pthread_mutex_lock(&pixel_buffer_mutex_) == kPthreadMutexSuccess) { + if (pixel_buffer_ != NULL && !pixel_buffer_->is_null()) { + pixels = pixel_buffer_->data(); + } + } + return reinterpret_cast(pixels); +} + +void PiGenerator::HandleMessage(const pp::Var& var_message) { + if (!var_message.is_string()) { + PostMessage(pp::Var(kInvalidPiValue)); + } + std::string message = var_message.AsString(); + if (message == kPaintMethodId) { + Paint(); + } else { + PostMessage(pp::Var(kInvalidPiValue)); + } +} + +void PiGenerator::UnlockPixels() const { + pthread_mutex_unlock(&pixel_buffer_mutex_); +} + +void PiGenerator::Paint() { + ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_); + if (!scoped_mutex.is_valid()) { + return; + } + FlushPixelBuffer(); + // Post the current estimate of Pi back to the browser. + pp::Var pi_estimate(pi()); + // Paint() is called on the main thread, so no need for CallOnMainThread() + // here. It's OK to just post the message. + PostMessage(pi_estimate); +} + +void PiGenerator::CreateContext(const pp::Size& size) { + ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_); + if (!scoped_mutex.is_valid()) { + return; + } + if (IsContextValid()) + return; + graphics_2d_context_ = new pp::Graphics2D(this, size, false); + if (!BindGraphics(*graphics_2d_context_)) { + printf("Couldn't bind the device context\n"); + } +} + +void PiGenerator::DestroyContext() { + ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_); + if (!scoped_mutex.is_valid()) { + return; + } + if (!IsContextValid()) + return; + delete graphics_2d_context_; + graphics_2d_context_ = NULL; +} + +void PiGenerator::FlushPixelBuffer() { + if (!IsContextValid()) + return; + // Note that the pixel lock is held while the buffer is copied into the + // device context and then flushed. + graphics_2d_context_->PaintImageData(*pixel_buffer_, pp::Point()); + if (flush_pending()) + return; + set_flush_pending(true); + graphics_2d_context_->Flush(pp::CompletionCallback(&FlushCallback, this)); +} + +void* PiGenerator::ComputePi(void* param) { + int count = 0; // The number of points put inside the inscribed quadrant. + unsigned int seed = 1; + srand(seed); + + PiGenerator* pi_generator = static_cast(param); + for (int i = 1; i <= kMaxPointCount && !pi_generator->quit(); ++i) { + ScopedPixelLock scoped_pixel_lock(pi_generator); + uint32_t* pixel_bits = scoped_pixel_lock.pixels(); + if (pixel_bits == NULL) { + // Note that if the pixel buffer never gets initialized, this won't ever + // paint anything. Which is probably the right thing to do. Also, this + // clause means that the image will not get the very first few Pi dots, + // since it's possible that this thread starts before the pixel buffer is + // initialized. + continue; + } + double x = static_cast(rand()) / RAND_MAX; + double y = static_cast(rand()) / RAND_MAX; + double distance = sqrt(x * x + y * y); + int px = x * pi_generator->width(); + int py = (1.0 - y) * pi_generator->height(); + uint32_t color = pixel_bits[pi_generator->width() * py + px]; + if (distance < 1.0) { + // Set color to blue. + ++count; + pi_generator->pi_ = 4.0 * count / i; + color += 4 << kBlueShift; + color &= kBlueMask; + } else { + // Set color to red. + color += 4 << kRedShift; + color &= kRedMask; + } + pixel_bits[pi_generator->width() * py + px] = color | kOpaqueColorMask; + } + return 0; +} + +} // namespace pi_generator diff --git a/pool/shard001/C++/0018043_LRULocalDestroyAction.cpp b/pool/shard001/C++/0018043_LRULocalDestroyAction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdd3f973a46b6827f2f59a4b3955fa5c51abdfc9 --- /dev/null +++ b/pool/shard001/C++/0018043_LRULocalDestroyAction.cpp @@ -0,0 +1,36 @@ +/* + * 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 "LRULocalDestroyAction.hpp" +#include "LRUEntriesMap.hpp" +#include "CacheImpl.hpp" + +using namespace apache::geode::client; + +bool LRULocalDestroyAction::evict(const std::shared_ptr& mePtr) { + std::shared_ptr keyPtr; + mePtr->getKeyI(keyPtr); + std::shared_ptr versionTag; + // we should invoke the destroyNoThrow with appropriate + // flags to correctly invoke listeners + LOGDEBUG("LRULocalDestroy: evicting entry with key [%s]", + Utils::getCacheableKeyString(keyPtr)->asChar()); + GfErrType err = m_regionPtr->destroyNoThrow( + keyPtr, nullptr, -1, CacheEventFlags::EVICTION | CacheEventFlags::LOCAL, + versionTag); + return (err == GF_NOERR); +} diff --git a/pool/shard001/C++/0018051_editaddressdialog.cpp b/pool/shard001/C++/0018051_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b487b214a8142efee7fd7eb42f1791ec488c9d98 --- /dev/null +++ b/pool/shard001/C++/0018051_editaddressdialog.cpp @@ -0,0 +1,136 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid Aero address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard001/C++/0018053_RunningSchedule.cpp b/pool/shard001/C++/0018053_RunningSchedule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8908192a087763fb1af777465c795cc437dc15a2 --- /dev/null +++ b/pool/shard001/C++/0018053_RunningSchedule.cpp @@ -0,0 +1,72 @@ +/*************************************************************** + * This source files comes from the xLights project + * https://www.xlights.org + * https://github.com/smeighan/xLights + * See the github commit history for a record of contributing + * developers. + * Copyright claimed based on commit dates recorded in Github + * License: https://github.com/smeighan/xLights/blob/master/License.txt + **************************************************************/ + +#include "RunningSchedule.h" +#include "Schedule.h" +#include "PlayList/PlayList.h" +#include + +RunningSchedule::RunningSchedule(PlayList* playlist, Schedule* schedule) +{ + _stop = false; + _playlist = new PlayList(*playlist); + _schedule = new Schedule(*schedule); + + //static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); + //logger_base.info("Running schedule create containing Playlist %s and Schedule %s 0x%lx.", (const char*)GetPlayList()->GetName().c_str(), (const char*)GetSchedule()->GetName().c_str(), this); +} + +RunningSchedule::~RunningSchedule() +{ + //static log4cpp::Category &logger_base = log4cpp::Category::getInstance(std::string("log_base")); + //logger_base.info("Running schedule containing Playlist %s and Schedule %s being destroyed 0x%lx.", (const char*)GetPlayList()->GetName().c_str(), (const char*)GetSchedule()->GetName().c_str(), this); + + _playlist->Stop(); + + delete _playlist; + _playlist = nullptr; + delete _schedule; + _schedule = nullptr; +} + +bool RunningSchedule::operator<(const RunningSchedule& rs) const +{ + // this is intentional ... I want them in reverse order + return _schedule->GetPriority() > rs._schedule->GetPriority(); +} + +void RunningSchedule::Reset() +{ + _stop = false; + if (!_playlist->IsRunning()) + { + _playlist->StartSuspended(_schedule->GetLoop(), _schedule->GetRandom(), _schedule->GetLoops()); + } + else + { + _playlist->Stop(); + _playlist->StartSuspended(_schedule->GetLoop(), _schedule->GetRandom(), _schedule->GetLoops()); + } + if (_playlist->IsPaused()) + { + _playlist->TogglePause(); + } +} + +void RunningSchedule::Stop() +{ + _stop = true; + _playlist->Stop(); +} + +bool RunningSchedule::ShouldBeRunning() const +{ + return !_stop && _schedule->CheckActive(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0018054_build_custom_targets_menu_manager.cpp b/pool/shard001/C++/0018054_build_custom_targets_menu_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bae664cd0f72b0f822b708e5623dff66d298ffe5 --- /dev/null +++ b/pool/shard001/C++/0018054_build_custom_targets_menu_manager.cpp @@ -0,0 +1,61 @@ +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 Eran Ifrah +// file name : build_custom_targets_menu_manager.cpp +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// 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 "build_custom_targets_menu_manager.h" +#include "macros.h" + +CustomTargetsMgr::CustomTargetsMgr() {} + +CustomTargetsMgr::~CustomTargetsMgr() {} + +CustomTargetsMgr& CustomTargetsMgr::Get() +{ + static CustomTargetsMgr theMgr; + return theMgr; +} + +void CustomTargetsMgr::SetTargets(const wxString& projectName, const std::map& targets) +{ + Clear(); + m_projectName = projectName; + + int id = ID_MENU_CUSTOM_TARGET_FIRST; + for(const auto& vt : targets) { + m_targets.insert({ id, { vt.first, vt.second } }); + ++id; + } +} + +CustomTargetsMgr::Pair_t CustomTargetsMgr::GetTarget(int menuId) const +{ + if(m_targets.count(menuId)) { return m_targets.find(menuId)->second; } + return Pair_t(); +} + +void CustomTargetsMgr::Clear() +{ + m_projectName.Clear(); + m_targets.clear(); +} diff --git a/pool/shard001/C++/0018057_phonograph_cylinder.cpp b/pool/shard001/C++/0018057_phonograph_cylinder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45cca3776c56467469bd54233fb731eff23799eb --- /dev/null +++ b/pool/shard001/C++/0018057_phonograph_cylinder.cpp @@ -0,0 +1,205 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "titanic/carry/phonograph_cylinder.h" +#include "titanic/game/phonograph.h" +#include "titanic/sound/music_room.h" + +namespace Titanic { + +BEGIN_MESSAGE_MAP(CPhonographCylinder, CCarry) + ON_MESSAGE(UseWithOtherMsg) + ON_MESSAGE(QueryCylinderMsg) + ON_MESSAGE(RecordOntoCylinderMsg) + ON_MESSAGE(SetMusicControlsMsg) + ON_MESSAGE(ErasePhonographCylinderMsg) +END_MESSAGE_MAP() + +CPhonographCylinder::CPhonographCylinder() : CCarry(), + _bellsMuteControl(false), _bellsPitchControl(0), + _bellsSpeedControl(0), _bellsDirectionControl(false), + _bellsInversionControl(false), _snakeMuteControl(false), + _snakeSpeedControl(0), _snakePitchControl(0), + _snakeInversionControl(false), _snakeDirectionControl(false), + _pianoMuteControl(false), _pianoSpeedControl(0), + _pianoPitchControl(0), _pianoInversionControl(false), + _pianoDirectionControl(false), _bassMuteControl(false), + _bassSpeedControl(0), _bassPitchControl(0), + _bassInversionControl(false) { +} + +void CPhonographCylinder::save(SimpleFile *file, int indent) { + file->writeNumberLine(1, indent); + file->writeQuotedLine(_itemName, indent); + file->writeNumberLine(_bellsMuteControl, indent); + file->writeNumberLine(_bellsPitchControl, indent); + file->writeNumberLine(_bellsSpeedControl, indent); + file->writeNumberLine(_bellsDirectionControl, indent); + file->writeNumberLine(_bellsInversionControl, indent); + file->writeNumberLine(_snakeMuteControl, indent); + file->writeNumberLine(_snakeSpeedControl, indent); + file->writeNumberLine(_snakePitchControl, indent); + file->writeNumberLine(_snakeInversionControl, indent); + file->writeNumberLine(_snakeDirectionControl, indent); + file->writeNumberLine(_pianoMuteControl, indent); + file->writeNumberLine(_pianoSpeedControl, indent); + file->writeNumberLine(_pianoPitchControl, indent); + file->writeNumberLine(_pianoInversionControl, indent); + file->writeNumberLine(_pianoDirectionControl, indent); + file->writeNumberLine(_bassMuteControl, indent); + file->writeNumberLine(_bassSpeedControl, indent); + file->writeNumberLine(_bassPitchControl, indent); + file->writeNumberLine(_bassInversionControl, indent); + file->writeNumberLine(_bassDirectionControl, indent); + + CCarry::save(file, indent); +} + +void CPhonographCylinder::load(SimpleFile *file) { + file->readNumber(); + _itemName = file->readString(); + _bellsMuteControl = file->readNumber(); + _bellsPitchControl = file->readNumber(); + _bellsSpeedControl = file->readNumber(); + _bellsDirectionControl = file->readNumber(); + _bellsInversionControl = file->readNumber(); + _snakeMuteControl = file->readNumber(); + _snakeSpeedControl = file->readNumber(); + _snakePitchControl = file->readNumber(); + _snakeInversionControl = file->readNumber(); + _snakeDirectionControl = file->readNumber(); + _pianoMuteControl = file->readNumber(); + _pianoSpeedControl = file->readNumber(); + _pianoPitchControl = file->readNumber(); + _pianoInversionControl = file->readNumber(); + _pianoDirectionControl = file->readNumber(); + _bassMuteControl = file->readNumber(); + _bassSpeedControl = file->readNumber(); + _bassPitchControl = file->readNumber(); + _bassInversionControl = file->readNumber(); + _bassDirectionControl = file->readNumber(); + + CCarry::load(file); +} + +bool CPhonographCylinder::UseWithOtherMsg(CUseWithOtherMsg *msg) { + CPhonograph *phonograph = dynamic_cast(msg->_other); + if (phonograph) { + // Below is redundant, since original never actually executes message + CSetVarMsg varMsg("m_RecordStatus", 1); + return true; + } else { + return CCarry::UseWithOtherMsg(msg); + } +} + +bool CPhonographCylinder::QueryCylinderMsg(CQueryCylinderMsg *msg) { + msg->_name = _itemName; + return true; +} + +bool CPhonographCylinder::RecordOntoCylinderMsg(CRecordOntoCylinderMsg *msg) { + _itemName = "STMusic"; + + CQueryMusicControlSettingMsg queryMsg; + queryMsg.execute("Bells Mute Control"); + _bellsMuteControl = queryMsg._value; + queryMsg.execute("Bells Pitch Control"); + _bellsPitchControl = queryMsg._value; + queryMsg.execute("Bells Speed Control"); + _bellsSpeedControl = queryMsg._value; + queryMsg.execute("Bells Direction Control"); + _bellsDirectionControl = queryMsg._value; + queryMsg.execute("Bells Inversion Control"); + _bellsInversionControl = queryMsg._value; + queryMsg.execute("Snake Mute Control"); + _snakeMuteControl = queryMsg._value; + queryMsg.execute("Snake Speed Control"); + _snakeSpeedControl = queryMsg._value; + queryMsg.execute("Snake Pitch Control"); + _snakePitchControl = queryMsg._value; + queryMsg.execute("Snake Inversion Control"); + _snakeInversionControl = queryMsg._value; + queryMsg.execute("Snake Direction Control"); + _snakeDirectionControl = queryMsg._value; + queryMsg.execute("Piano Mute Control"); + _pianoMuteControl = queryMsg._value; + queryMsg.execute("Piano Speed Control"); + _pianoSpeedControl = queryMsg._value; + queryMsg.execute("Piano Pitch Control"); + _pianoPitchControl = queryMsg._value; + queryMsg.execute("Piano Inversion Control"); + _pianoInversionControl = queryMsg._value; + queryMsg.execute("Piano Direction Control"); + _pianoDirectionControl = queryMsg._value; + queryMsg.execute("Bass Mute Control"); + _bassMuteControl = queryMsg._value; + queryMsg.execute("Bass Speed Control"); + _bassSpeedControl = queryMsg._value; + queryMsg.execute("Bass Pitch Control"); + _bassPitchControl = queryMsg._value; + queryMsg.execute("Bass Inversion Control"); + _bassInversionControl = queryMsg._value; + queryMsg.execute("Bass Direction Control"); + _bassDirectionControl = queryMsg._value; + + return true; +} + +bool CPhonographCylinder::SetMusicControlsMsg(CSetMusicControlsMsg *msg) { + if (!_itemName.hasPrefix("STMusic")) + return true; + + CMusicRoom *musicRoom = getMusicRoom(); + musicRoom->setMuteControl(BELLS, _bellsMuteControl); + musicRoom->setPitchControl(BELLS, _bellsPitchControl); + musicRoom->setSpeedControl(BELLS, _bellsSpeedControl); + musicRoom->setInversionControl(BELLS, _bellsInversionControl); + musicRoom->setDirectionControl(BELLS, _bellsDirectionControl); + + musicRoom->setMuteControl(SNAKE, _snakeMuteControl); + musicRoom->setPitchControl(SNAKE, _snakePitchControl); + musicRoom->setSpeedControl(SNAKE, _snakeSpeedControl); + musicRoom->setInversionControl(SNAKE, _snakeInversionControl); + musicRoom->setDirectionControl(SNAKE, _snakeDirectionControl); + + musicRoom->setMuteControl(PIANO, _pianoMuteControl); + musicRoom->setPitchControl(PIANO, _pianoPitchControl); + musicRoom->setSpeedControl(PIANO, _pianoSpeedControl); + musicRoom->setInversionControl(PIANO, _pianoInversionControl); + musicRoom->setDirectionControl(PIANO, _pianoDirectionControl); + + musicRoom->setMuteControl(BASS, _bassMuteControl); + musicRoom->setPitchControl(BASS, _bassPitchControl); + musicRoom->setSpeedControl(BASS, _bassSpeedControl); + musicRoom->setInversionControl(BASS, _bassInversionControl); + musicRoom->setDirectionControl(BASS, _bassDirectionControl); + + return true; +} + +bool CPhonographCylinder::ErasePhonographCylinderMsg(CErasePhonographCylinderMsg *msg) { + _itemName.clear(); + return true; +} + +} // End of namespace Titanic diff --git a/pool/shard001/C++/0018064_x_privet_token.cc b/pool/shard001/C++/0018064_x_privet_token.cc new file mode 100644 index 0000000000000000000000000000000000000000..d14d9a697200fc7c25e510d66132afacd9f54caa --- /dev/null +++ b/pool/shard001/C++/0018064_x_privet_token.cc @@ -0,0 +1,78 @@ +// 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 "cloud_print/gcp20/prototype/x_privet_token.h" + +#include +#include + +#include "base/base64.h" +#include "base/format_macros.h" +#include "base/guid.h" +#include "base/logging.h" +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" + +namespace { + +const char kXPrivetTokenDelimeter = ':'; +const uint64_t kTimeExpiration = 24 * 60 * 60; // in seconds +const uint64_t kTimeSecretRefresh = 24 * 60 * 60; // in seconds + +} // namespace + +using base::Time; +using base::TimeDelta; + +XPrivetToken::XPrivetToken() { + UpdateSecret(); +} + +XPrivetToken::XPrivetToken(const std::string& secret, + const base::Time& gen_time) + : secret_(secret), + last_gen_time_(gen_time) { +} + +std::string XPrivetToken::GenerateXToken() { + if (Time::Now() > last_gen_time_ + TimeDelta::FromSeconds(kTimeSecretRefresh)) + UpdateSecret(); + + return GenerateXTokenWithTime(static_cast(Time::Now().ToTimeT())); +} + +bool XPrivetToken::CheckValidXToken(const std::string& token) const { + size_t delimeter_pos = token.find(kXPrivetTokenDelimeter); + if (delimeter_pos == std::string::npos) + return false; + + std::string issue_time_str = token.substr(delimeter_pos + 1); + uint64_t issue_time; + if (!base::StringToUint64(issue_time_str, &issue_time)) + return false; + + if (GenerateXTokenWithTime(issue_time) != token) + return false; + + return Time::FromTimeT(issue_time) - last_gen_time_ < + TimeDelta::FromSeconds(kTimeExpiration); +} + +std::string XPrivetToken::GenerateXTokenWithTime(uint64_t issue_time) const { + std::string result; + std::string issue_time_str = base::StringPrintf("%" PRIu64, issue_time); + std::string hash = base::SHA1HashString(secret_ + + kXPrivetTokenDelimeter + + issue_time_str); + base::Base64Encode(hash, &result); + return result + kXPrivetTokenDelimeter + issue_time_str; +} + +void XPrivetToken::UpdateSecret() { + secret_ = base::GenerateGUID(); + last_gen_time_ = base::Time::Now(); + VLOG(1) << "New Secret is Generated."; +} + diff --git a/pool/shard001/C++/0018067_sat_subnormal_conversion.cpp b/pool/shard001/C++/0018067_sat_subnormal_conversion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1d4288aaa61d16d2bd7e018cac9290482e60f5a --- /dev/null +++ b/pool/shard001/C++/0018067_sat_subnormal_conversion.cpp @@ -0,0 +1,181 @@ +// sat_subnormal_conversion.cpp: test suite runner for subnormal IEEE-754 floating-point to fixed-point +// +// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. +// +// This file is part of the universal numbers project, which is released under an MIT Open Source license. +#include +#include +#include + +// Configure the fixpnt template environment +// first: enable general or specialized fixed-point configurations +#define FIXPNT_FAST_SPECIALIZATION +// second: enable/disable fixpnt arithmetic exceptions +#define FIXPNT_THROW_ARITHMETIC_EXCEPTION 0 +#include +#include + +/* + +IEEE-754 has subnormal numbers that a fixed-point needs to be able to pick up. + +The stored exponents 0x00 and 0xFF are interpreted specially. + +Exponent | fraction = 0 | fraction ≠ 0 | Equation +0x00 | zero | subnormal number | (-1)sign * 0.fraction * 2^-126 +0x01...0xFE | normal value | (-1)sign * 1.fraction * 2^(exponent - 127) +0xFF | ±infinity | NaN(quiet, signalling) + +The minimum positive normal value is 2−126 ≈ 1.18 × 10−38. +The minimum positive(subnormal) value is 2−149 ≈ 1.4 × 10−45. +*/ + +template +void TestDenormalizedNumberConversions() { + using namespace sw::universal; + + // minimum positive normal value of a single precision float == 2^-126 + float minpos_normal = 1.1754943508222875079687365372222e-38; + std::cout << to_binary(minpos_normal) << '\n'; + float minpos_subnormal = 1.4012984643248170709237295832899e-45; + std::cout << to_binary(minpos_subnormal) << '\n'; + + fixpnt a; + float f = minpos_normal; + for (int i = 0; i < 16; ++i) { + f *= 0.5f; + a = 1; + std::cout << to_float(a) << '\n'; +// std::cout << setw(10) << f << ' ' << to_binary(f) << ' ' << to_binary(a) << ' ' << a << '\n'; + } +} + +/* + +IEEE-754 has subnormal numbers that a fixed-point needs to be able to pick up. + +The stored exponents 0x000 and 0x7FF are interpreted specially. + +Exponent | fraction = 0 | fraction ≠ 0 | Equation +0x000 | zero | subnormal number | (-1)^sign * 0.fraction * 2^-1022 +0x001...0x7FE | normal value | (-1)^sign * 1.fraction * 2^(exponent - 1023) +0x7FF | ±infinity | NaN(quiet, signalling) + +The minimum positive normal value is 2−1022 ≈ 2.22e-308. +The minimum positive(subnormal) value is 2−1074 ≈ 1.4 × 10−45. +*/ + +template +void FloatGenerateFixedPointValues(std::ostream& ostr = std::cout) { + constexpr size_t NR_TEST_CASES = (size_t(1) << nbits); + sw::universal::fixpnt a; + ostr << " fixpnt<" << nbits << "," << rbits << ">\n"; + for (size_t i = 0; i < NR_TEST_CASES; ++i) { + a.setbits(i); + float f = float(a); + ostr << to_binary(a) << " | " << to_triple(a) << " | " << std::setw(15) << a << " | " << std::setw(15) << f << std::endl; + } +} + +template +void DoubleGenerateFixedPointValues(std::ostream& ostr = std::cout) { + constexpr size_t NR_TEST_CASES = (size_t(1) << nbits); + sw::universal::fixpnt a; + ostr << " fixpnt<" << nbits << "," << rbits << ">\n"; + for (size_t i = 0; i < NR_TEST_CASES; ++i) { + a.setbits(i); + double f = double(a); + ostr << to_binary(a) << " | " << to_triple(a) << " | " << std::setw(15) << a << " | " << std::setw(15) << f << std::endl; + } +} + +// Regression testing guards: typically set by the cmake configuration, but MANUAL_TESTING is an override +#define MANUAL_TESTING 1 +// REGRESSION_LEVEL_OVERRIDE is set by the cmake file to drive a specific regression intensity +// It is the responsibility of the regression test to organize the tests in a quartile progression. +//#undef REGRESSION_LEVEL_OVERRIDE +#ifndef REGRESSION_LEVEL_OVERRIDE +#define REGRESSION_LEVEL_1 1 +#define REGRESSION_LEVEL_2 1 +#define REGRESSION_LEVEL_3 1 +#define REGRESSION_LEVEL_4 1 +#endif + +int main() +try { + using namespace sw::universal; + + std::string test_suite = "Fixed-point saturating subnormal conversion "; + std::string test_tag = "conversion of IEEE-754 subnormals"; +// bool reportTestCases = false; + int nrOfFailedTestCases = 0; + + std::cout << test_suite << '\n'; + +#if MANUAL_TESTING + // minpos_subnormal value + float multiplier = 1.4012984643248170709237295832899e-45; + for (int i = 0; i < 149 - 127; ++i) { + multiplier *= 2.0f; + } + std::cout << to_binary(multiplier) << std::endl; + float minpos_normal = 1.1754943508222875079687365372222e-38; + std::cout << to_binary(minpos_normal) << std::endl; + + // minimum positive normal value of a single precision float == 2^-1022 + double dbl_minpos_normal = 2.2250738585072013830902327173324e-308; + std::cout << to_binary(dbl_minpos_normal) << std::endl; + double dbl_minpos_subnormal = 4.940656458412465441765687928622e-324; + std::cout << to_binary(dbl_minpos_subnormal) << std::endl; + + FloatGenerateFixedPointValues<8, 4>(); + DoubleGenerateFixedPointValues<8, 4>(); + + // can't use the regular exhaustive test suites for these very large fixed-points + // nrOfFailedTestCases = ReportTestResult(ValidateAssignment<256, 150, Modular, uint32_t, float>(reportTestCases), tag, "fixpnt<4,0, Modular, uint32_t>"); + + ReportTestSuiteResults(test_suite, nrOfFailedTestCases); + return EXIT_SUCCESS; // ignore failures +#else + + +#if REGRESSION_LEVEL_1 + +#endif + +#if REGRESSION_LEVEL_2 + +#endif + +#if REGRESSION_LEVEL_3 + +#endif + +#if REGRESSION_LEVEL_4 + +#endif + + ReportTestSuiteResults(test_suite, nrOfFailedTestCases); + return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); +#endif // MANUAL_TESTING +} +catch (char const* msg) { + std::cerr << msg << std::endl; + return EXIT_FAILURE; +} +catch (const sw::universal::fixpnt_arithmetic_exception& err) { + std::cerr << "Uncaught fixpnt arithmetic exception: " << err.what() << std::endl; + return EXIT_FAILURE; +} +catch (const sw::universal::fixpnt_internal_exception& err) { + std::cerr << "Uncaught fixpnt internal exception: " << err.what() << std::endl; + return EXIT_FAILURE; +} +catch (const std::runtime_error& err) { + std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; + return EXIT_FAILURE; +} +catch (...) { + std::cerr << "Caught unknown exception" << std::endl; + return EXIT_FAILURE; +} diff --git a/pool/shard001/C++/0018068_VoicePacketImpl.cpp b/pool/shard001/C++/0018068_VoicePacketImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13be830cce668d32c91680c65b5b68e79839b6d7 --- /dev/null +++ b/pool/shard001/C++/0018068_VoicePacketImpl.cpp @@ -0,0 +1,93 @@ +// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved +// Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved.. + +#include "VoicePacketImpl.h" +#include "OnlineSubsystemB3atZ.h" +#include "Interfaces/OnlineIdentityInterface.h" + +FVoicePacketImpl::FVoicePacketImpl(const FVoicePacketImpl& Other) : + FVoicePacket(Other) +{ + Sender = Other.Sender; + Length = Other.Length; + + // Copy the contents of the voice packet + Buffer.Empty(Other.Length); + Buffer.AddUninitialized(Other.Length); + FMemory::Memcpy(Buffer.GetData(), Other.Buffer.GetData(), Other.Length); +} + +uint16 FVoicePacketImpl::GetTotalPacketSize() +{ +#if DEBUG_VOICE_PACKET_ENCODING + return Sender->GetSize() + sizeof(Length) + Length + sizeof(uint32); +#else + return Sender->GetSize() + sizeof(Length) + Length; +#endif +} + +uint16 FVoicePacketImpl::GetBufferSize() +{ + return Length; +} + +TSharedPtr FVoicePacketImpl::GetSender() +{ + return Sender; +} + +void FVoicePacketImpl::Serialize(class FArchive& Ar) +{ + // Make sure not to overflow the buffer by reading an invalid amount + if (Ar.IsLoading()) + { + FString SenderStr; + Ar << SenderStr; + + // Don't need to distinguish OSS interfaces here with world because we just want the create function below + IOnlineSubsystemB3atZ* OnlineSub = IOnlineSubsystemB3atZ::Get(); + IOnlineIdentityPtr IdentityInt = OnlineSub->GetIdentityInterface(); + if (IdentityInt.IsValid()) + { + Sender = IdentityInt->CreateUniquePlayerId(SenderStr); + } + + Ar << Length; + // Verify the packet is a valid size + if (Length <= MAX_VOICE_DATA_SIZE) + { + Buffer.Empty(Length); + Buffer.AddUninitialized(Length); + Ar.Serialize(Buffer.GetData(), Length); + +#if DEBUG_VOICE_PACKET_ENCODING + uint32 CRC = 0; + Ar << CRC; + if (CRC != FCrc::MemCrc32(Buffer.GetData(), Length)) + { + UE_LOG(LogVoice, Warning, TEXT("CRC Mismatch in voice packet")); + Length = 0; + } +#endif + } + else + { + Length = 0; + } + } + else + { + check(Sender.IsValid()); + FString SenderStr = Sender->ToString(); + Ar << SenderStr; + Ar << Length; + + // Always safe to save the data as the voice code prevents overwrites + Ar.Serialize(Buffer.GetData(), Length); + +#if DEBUG_VOICE_PACKET_ENCODING + uint32 CRC = FCrc::MemCrc32(Buffer.GetData(), Length); + Ar << CRC; +#endif + } +} diff --git a/pool/shard001/C++/0018070_ImageProvider_debug.cpp b/pool/shard001/C++/0018070_ImageProvider_debug.cpp new file mode 100644 index 0000000000000000000000000000000000000000..add173d71d2208799731b1b0e9a17dd0d8382b60 --- /dev/null +++ b/pool/shard001/C++/0018070_ImageProvider_debug.cpp @@ -0,0 +1,52 @@ +#include "main.hpp" + +#include "ImageProvider.hpp" +#include "Resources.hpp" + +static cv::Mat debug_image; + +bool ImageProvider::create(Resources *resources) { + debug_image = cv::imread("Rayman2_1920x1080.jpg"); + webcam_size = debug_image.size(); + return true; +} + +bool ImageProvider::start() { + for(size_t i=0u; iwebcamThreadFunc(); }); + + return true; +} +void ImageProvider::stop() { + if(webcam_thread.joinable()) { + kill_threads = true; + webcam_thread.join(); + } +} + +void ImageProvider::webcamThreadFunc() { + while(!kill_threads) { + auto assigned = data.startWrite(); + + auto &frame = assigned->webcam_pixels; + auto &faces = assigned->faces; + + frame = debug_image; + + faces.clear(); + faces.emplace_back(1142, 36, 400, 400); + +#if 0 + for(const auto &f : faces) { + cv::rectangle(frame, f, cv::Scalar(0, 0, 255)); + } +#endif + + data.finishWrite(); + + SDL_Delay(10u); + } +} diff --git a/pool/shard001/C++/0018073_FreeLookGeneral.cpp b/pool/shard001/C++/0018073_FreeLookGeneral.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7fcd8bb63be0964d533dda27ac96f436164f24cd --- /dev/null +++ b/pool/shard001/C++/0018073_FreeLookGeneral.cpp @@ -0,0 +1,48 @@ +// Copyright 2020 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#include "DolphinQt/Config/Mapping/FreeLookGeneral.h" + +#include +#include + +#include "Core/FreeLookManager.h" +#include "InputCommon/InputConfig.h" + +FreeLookGeneral::FreeLookGeneral(MappingWindow* window) : MappingWidget(window) +{ + CreateMainLayout(); +} + +void FreeLookGeneral::CreateMainLayout() +{ + auto* layout = new QGridLayout; + + layout->addWidget( + CreateGroupBox(tr("Move"), FreeLook::GetInputGroup(GetPort(), FreeLookGroup::Move)), 0, 0); + layout->addWidget( + CreateGroupBox(tr("Speed"), FreeLook::GetInputGroup(GetPort(), FreeLookGroup::Speed)), 0, 1); + layout->addWidget(CreateGroupBox(tr("Field of View"), + FreeLook::GetInputGroup(GetPort(), FreeLookGroup::FieldOfView)), + 0, 2); + layout->addWidget( + CreateGroupBox(tr("Other"), FreeLook::GetInputGroup(GetPort(), FreeLookGroup::Other)), 0, 3); + + setLayout(layout); +} + +void FreeLookGeneral::LoadSettings() +{ + FreeLook::LoadInputConfig(); +} + +void FreeLookGeneral::SaveSettings() +{ + FreeLook::GetInputConfig()->SaveConfig(); +} + +InputConfig* FreeLookGeneral::GetConfig() +{ + return FreeLook::GetInputConfig(); +} diff --git a/pool/shard001/C++/0018074_etc_services.cpp b/pool/shard001/C++/0018074_etc_services.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e91a8c98844b098b910c630c71e6513b8a8c9664 --- /dev/null +++ b/pool/shard001/C++/0018074_etc_services.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace osquery { +namespace tables { + +QueryData parseEtcServicesContent(const std::string& content) { + QueryData results; + + for (const auto& line : split(content, "\n")) { + // Empty line or comment. + if (line.size() == 0 || boost::starts_with(line, "#")) { + continue; + } + + // [0]: name port/protocol [aliases] + // [1]: [comment part1] + // [2]: [comment part2] + // [n]: [comment partn] + auto service_info_comment = split(line, "#"); + + // [0]: name + // [1]: port/protocol + // [2]: [aliases0] + // [3]: [aliases1] + // [n]: [aliasesn] + auto service_info = split(service_info_comment[0]); + if (service_info.size() < 2) { + continue; + } + + // [0]: port [1]: protocol + auto service_port_protocol = split(service_info[1], "/"); + if (service_port_protocol.size() != 2) { + continue; + } + + Row r; + r["name"] = TEXT(service_info[0]); + r["port"] = INTEGER(service_port_protocol[0]); + r["protocol"] = TEXT(service_port_protocol[1]); + + // Removes the name and the port/protcol elements. + service_info.erase(service_info.begin(), service_info.begin() + 2); + r["aliases"] = TEXT(boost::algorithm::join(service_info, " ")); + + // If there is a comment for the service. + if (service_info_comment.size() > 1) { + // Removes everything except the comment (parts of the comment). + service_info_comment.erase(service_info_comment.begin(), + service_info_comment.begin() + 1); + r["comment"] = TEXT(boost::algorithm::join(service_info_comment, " # ")); + } + results.push_back(r); + } + return results; +} + +QueryData genEtcServices(QueryContext& context) { + std::string content; + auto s = osquery::readFile("/etc/services", content); + if (s.ok()) { + return parseEtcServicesContent(content); + } else { + return {}; + } +} +} +} diff --git a/pool/shard001/C++/0018092_clipboard.cpp b/pool/shard001/C++/0018092_clipboard.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24be035ee000f81a8675e547b4ae5e156e0205b7 --- /dev/null +++ b/pool/shard001/C++/0018092_clipboard.cpp @@ -0,0 +1,101 @@ +/** + * @file + * @brief Platform-independent GTK clipboard support. + * @todo Using GDK_SELECTION_CLIPBOARD fails on win32, so we use the win32 API directly for now. + */ + +/* + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. + + This file is part of GtkRadiant. + + GtkRadiant 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. + + GtkRadiant 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 GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "clipboard.h" + +#include "stream/memstream.h" +#include "stream/textstream.h" +#include "string/string.h" + +#include + +#define RADIANT_CLIPPINGS 23 + +static gchar clipboard_target[] = "RADIANT_CLIPPINGS"; +static const GtkTargetEntry clipboard_targets = { clipboard_target, 0, RADIANT_CLIPPINGS }; +/** + * @sa Map_ExportSelected + * @sa Map_ImportSelected + */ +static ClipboardPasteFunc g_clipboardPasteFunc = 0; + +static void clipboard_get (GtkClipboard *clipboard, GtkSelectionData *selection_data, guint info, gpointer data) +{ + std::size_t len = *reinterpret_cast (data); + const char* buffer = (len != 0) ? reinterpret_cast (data) + sizeof(std::size_t) : 0; + + GdkAtom type = GDK_NONE; + if (info == clipboard_targets.info) { + type = gdk_atom_intern(clipboard_targets.target, FALSE); + } + + gtk_selection_data_set(selection_data, type, 8, reinterpret_cast (buffer), static_cast (len)); +} + +static void clipboard_clear (GtkClipboard *clipboard, gpointer data) +{ + delete[] reinterpret_cast (data); +} + +static void clipboard_received (GtkClipboard *clipboard, GtkSelectionData *data, gpointer user_data) +{ + if (data->length < 0) { + globalErrorStream() << "Error retrieving selection\n"; + } else if (string_equal(gdk_atom_name(data->type), clipboard_targets.target)) { + BufferInputStream istream(reinterpret_cast (data->data), data->length); + (*reinterpret_cast (user_data))(istream); + } +} + +/** + * @sa clipboard_paste + */ +void clipboard_copy (ClipboardCopyFunc copy) +{ + GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); + + BufferOutputStream ostream; + copy(ostream); + std::size_t length = ostream.size(); + char* data = new char[length + sizeof(std::size_t)]; + *reinterpret_cast (data) = length; + memcpy(data + sizeof(std::size_t), ostream.data(), length); + + gtk_clipboard_set_with_data(clipboard, &clipboard_targets, 1, clipboard_get, clipboard_clear, data); +} + +/** + * @sa clipboard_copy + */ +void clipboard_paste (ClipboardPasteFunc paste) +{ + GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); + + g_clipboardPasteFunc = paste; + gtk_clipboard_request_contents(clipboard, gdk_atom_intern(clipboard_targets.target, FALSE), clipboard_received, + &g_clipboardPasteFunc); +} diff --git a/pool/shard001/C++/0018100_MipsModuleISelDAGToDAG.cpp b/pool/shard001/C++/0018100_MipsModuleISelDAGToDAG.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf85eb3f2416044b12024c99dffb9790bfe5b7b1 --- /dev/null +++ b/pool/shard001/C++/0018100_MipsModuleISelDAGToDAG.cpp @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// Instruction Selector Subtarget Control +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// This file defines a pass used to change the subtarget for the +// Mips Instruction selector. +// +//===----------------------------------------------------------------------===// + +#include "Mips.h" +#include "MipsTargetMachine.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" + +using namespace llvm; + +#define DEBUG_TYPE "mips-isel" + +namespace { + class MipsModuleDAGToDAGISel : public MachineFunctionPass { + public: + static char ID; + + explicit MipsModuleDAGToDAGISel(MipsTargetMachine &TM_) + : MachineFunctionPass(ID), TM(TM_) {} + + // Pass Name + StringRef getPassName() const override { + return "MIPS DAG->DAG Pattern Instruction Selection"; + } + + bool runOnMachineFunction(MachineFunction &MF) override; + + protected: + MipsTargetMachine &TM; + }; + + char MipsModuleDAGToDAGISel::ID = 0; +} + +bool MipsModuleDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) { + DEBUG(errs() << "In MipsModuleDAGToDAGISel::runMachineFunction\n"); + TM.resetSubtarget(&MF); + return false; +} + +llvm::FunctionPass *llvm::createMipsModuleISelDagPass(MipsTargetMachine &TM) { + return new MipsModuleDAGToDAGISel(TM); +} diff --git a/pool/shard001/C++/0018104_account.cpp b/pool/shard001/C++/0018104_account.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b2960112336eb08aa3c98fceaa41784ce2f089e --- /dev/null +++ b/pool/shard001/C++/0018104_account.cpp @@ -0,0 +1,52 @@ +#include "account.h" +#include +#include +#include + +Account::Account(int uid){ + id = 0; + if(uid<=0) return; + DB::Result r = DB::query("SELECT name, email, about, notify, license FROM users WHERE id=" + number(uid)); + if(!r.empty()){ + id = uid; + name = r[0][0]; + email = r[0][1]; + about = r[0][2]; + notify = r[0][3] == "t"; + license = r[0][4]; + } + + // Using LEFT JOIN / GROUP BY above would require grouping by all otherwise + // selected attributes, we're probably better off this way. + r = DB::query("SELECT COUNT(*) FROM favorites, tracks WHERE tracks.visible = TRUE and tracks.id = favorites.ref AND favorites.type = 'track' AND favorites.user_id = " + number(uid)); + num_favs = r.empty() ? 0 : number(r[0][0]); + + r = DB::query("SELECT COUNT(*) FROM favorites WHERE favorites.ref = " + number(uid) + " AND favorites.type = 'artist'"); + num_followers = r.empty() ? 0 : number(r[0][0]); + +} + +void Account::fill(Dict* d) const{ + User::fill(d); + d->SetValue("EMAIL", email); + d->SetValueAndShowSection("ABOUT", about, "HAS_ABOUT"); + d->SetValue("LICENSE", license); + if(notify) d->ShowSection("NOTIFY"); + // Avatar + d->SetValue("EMAIL_MD5", md5(email)); + Dict *a = d->AddIncludeDictionary("AVATAR"); + a->SetFilename("html/avatar.tpl"); + a->SetValue("EMAIL_MD5", md5(email)); + if(self()) a->ShowSection("IS_SELF"); + // Number of favorites + if(num_favs > 0) { + d->ShowSection("HAS_FAVS"); + } + d->SetValue("NUM_FAVS", number(num_favs)); + if(num_followers > 0) { + d->ShowSection("HAS_FOLLOWERS"); + if(num_followers > 1) + d->ShowSection("FOLLOWERS_PLURAL"); + } + d->SetValue("NUM_FOLLOWERS", number(num_followers)); +} diff --git a/pool/shard001/C++/0018113_CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62a.cpp b/pool/shard001/C++/0018113_CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd49ccf3c24bf11d034956f26ad3e4ff500e9f57 --- /dev/null +++ b/pool/shard001/C++/0018113_CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62a.cpp @@ -0,0 +1,208 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62a.cpp +Label Definition File: CWE321_Hard_Coded_Cryptographic_Key__w32.label.xml +Template File: sources-sink-62a.tmpl.cpp +*/ +/* + * @description + * CWE: 321 Use of Hard-coded Cryptographic Key + * BadSource: Copy a hardcoded value into cryptoKey + * GoodSource: Read cryptoKey from the console + * Sinks: + * BadSink : Hash cryptoKey and use the value to encrypt a string + * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include +#include + +/* Link with the Advapi32.lib file for Crypt* functions */ +#pragma comment (lib, "Advapi32") + +namespace CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSource(wchar_t * &cryptoKey); + +void bad() +{ + wchar_t * cryptoKey; + wchar_t cryptoKeyBuffer[100] = L""; + cryptoKey = cryptoKeyBuffer; + badSource(cryptoKey); + { + HCRYPTPROV hCryptProv; + HCRYPTKEY hKey; + HCRYPTHASH hHash; + wchar_t toBeEncrypted[] = L"String to be encrypted"; + DWORD encryptedLen = wcslen(toBeEncrypted)*sizeof(wchar_t); + BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ + /* Copy plaintext (without NUL terminator) into byte buffer */ + memcpy(encrypted, toBeEncrypted, encryptedLen); + /* Try to get a context with and without a new key set */ + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) + { + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) + { + printLine("Error in acquiring cryptographic context"); + exit(1); + } + } + /* Create Hash handle */ + if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) + { + printLine("Error in creating hash"); + exit(1); + } + /* Hash the cryptoKey */ + if(!CryptHashData(hHash, (BYTE *) cryptoKey, wcslen(cryptoKey)*sizeof(wchar_t), 0)) + { + printLine("Error in hashing cryptoKey"); + exit(1); + } + /* Derive an AES key from the Hashed cryptoKey */ + if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) + { + printLine("Error in CryptDeriveKey"); + exit(1); + } + /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ + /* Use the derived key to encrypt something */ + if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) + { + printLine("Error in CryptEncrypt"); + exit(1); + } + /* use encrypted block */ + printBytesLine(encrypted, encryptedLen); + if (hKey) + { + CryptDestroyKey(hKey); + } + if (hHash) + { + CryptDestroyHash(hHash); + } + if (hCryptProv) + { + CryptReleaseContext(hCryptProv, 0); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSource(wchar_t * &cryptoKey); + +static void goodG2B() +{ + wchar_t * cryptoKey; + wchar_t cryptoKeyBuffer[100] = L""; + cryptoKey = cryptoKeyBuffer; + goodG2BSource(cryptoKey); + { + HCRYPTPROV hCryptProv; + HCRYPTKEY hKey; + HCRYPTHASH hHash; + wchar_t toBeEncrypted[] = L"String to be encrypted"; + DWORD encryptedLen = wcslen(toBeEncrypted)*sizeof(wchar_t); + BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */ + /* Copy plaintext (without NUL terminator) into byte buffer */ + memcpy(encrypted, toBeEncrypted, encryptedLen); + /* Try to get a context with and without a new key set */ + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0)) + { + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET)) + { + printLine("Error in acquiring cryptographic context"); + exit(1); + } + } + /* Create Hash handle */ + if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) + { + printLine("Error in creating hash"); + exit(1); + } + /* Hash the cryptoKey */ + if(!CryptHashData(hHash, (BYTE *) cryptoKey, wcslen(cryptoKey)*sizeof(wchar_t), 0)) + { + printLine("Error in hashing cryptoKey"); + exit(1); + } + /* Derive an AES key from the Hashed cryptoKey */ + if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) + { + printLine("Error in CryptDeriveKey"); + exit(1); + } + /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */ + /* Use the derived key to encrypt something */ + if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted))) + { + printLine("Error in CryptEncrypt"); + exit(1); + } + /* use encrypted block */ + printBytesLine(encrypted, encryptedLen); + if (hKey) + { + CryptDestroyKey(hKey); + } + if (hHash) + { + CryptDestroyHash(hHash); + } + if (hCryptProv) + { + CryptReleaseContext(hCryptProv, 0); + } + } +} + +void good() +{ + goodG2B(); +} + +#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 CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_62; /* 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/shard001/C++/0018117_iirFilter.cpp b/pool/shard001/C++/0018117_iirFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2b89ed0eb0dee4ad81e94f5c42b18ba5a4c3afe --- /dev/null +++ b/pool/shard001/C++/0018117_iirFilter.cpp @@ -0,0 +1,142 @@ +#include "stdafx.h" +#include "iirFilter.h" + +#include + +/// Create filter shell +ADTF_FILTER_PLUGIN("IIR Filter", OID_ADTF_IIR_FILTER, cIIR); + +cIIR::cIIR(const tChar* __info):cFilter(__info) { + faktor = 50; + SetPropertyFloat("Faktor", faktor); + SetPropertyFloat("Faktor" NSSUBPROP_REQUIRED, tTrue); +} + +cIIR::~cIIR() { + +} + +tResult cIIR::Init(tInitStage eStage, __exception) { + // never miss calling the parent implementation!! + RETURN_IF_FAILED(cFilter::Init(eStage, __exception_ptr)) + + // in StageFirst you can create and register your static pins. + if (eStage == StageFirst) + { + // get a media type for the input pin + cObjectPtr pDescManager; + RETURN_IF_FAILED(_runtime->GetObject(OID_ADTF_MEDIA_DESCRIPTION_MANAGER,IID_ADTF_MEDIA_DESCRIPTION_MANAGER,(tVoid**)&pDescManager,__exception_ptr)); + + //input descriptor + tChar const * strDescSignalValue = pDescManager->GetMediaDescription("tSignalValue"); + RETURN_IF_POINTER_NULL(strDescSignalValue); + cObjectPtr pTypeSignalValue = new cMediaType(0, 0, 0, "tSignalValue", strDescSignalValue,IMediaDescription::MDF_DDL_DEFAULT_VERSION); + RETURN_IF_FAILED(pTypeSignalValue->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**)&m_pCoderDescSignalValue)); + + // create and register the input pin + + RETURN_IF_FAILED(m_pin_input.Create("input_value", pTypeSignalValue, static_cast (this))); + RETURN_IF_FAILED(RegisterPin(&m_pin_input)); + + + // create and register the output pin + RETURN_IF_FAILED(m_pin_output.Create("output_value", pTypeSignalValue, static_cast (this))); + RETURN_IF_FAILED(RegisterPin(&m_pin_output)); + + + // get FILTER_SHIFT value + faktor = float(GetPropertyFloat("Faktor")); + + // Register auf 0 setzen + filter_reg = 0; + + } + else if (eStage == StageNormal) + { + // In this stage you would do further initialisation and/or create your dynamic pins. + // Please take a look at the demo_dynamicpin example for further reference. + } + else if (eStage == StageGraphReady) + { + // All pin connections have been established in this stage so you can query your pins + // about their media types and additional meta data. + // Please take a look at the demo_imageproc example for further reference. + } + + RETURN_NOERROR; +} + +tResult cIIR::Shutdown(tInitStage eStage, __exception) +{ + // In each stage clean up everything that you initiaized in the corresponding stage during Init. + // Pins are an exception: + // - The base class takes care of static pins that are members of this class. + // - Dynamic pins have to be cleaned up in the ReleasePins method, please see the demo_dynamicpin + // example for further reference. + + if (eStage == StageGraphReady) + { + } + else if (eStage == StageNormal) + { + } + else if (eStage == StageFirst) + { + } + + // call the base class implementation + return cFilter::Shutdown(eStage, __exception_ptr); +} + +tResult cIIR::OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample) +{ + // first check what kind of event it is + RETURN_IF_POINTER_NULL(pMediaSample); + RETURN_IF_POINTER_NULL(pSource); + + if (nEventCode == IPinEventSink::PE_MediaSampleReceived) + { + //write values with zero + tFloat32 f32Value = 0; + tUInt32 timeStamp = 0; + if (m_pCoderDescSignalValue != NULL) { + + { // focus for sample read lock + __adtf_sample_read_lock_mediadescription(m_pCoderDescSignalValue,pMediaSample,pCoder); + + pCoder->Get("ui32ArduinoTimestamp", (tVoid*)&timeStamp); + pCoder->Get("f32Value", (tVoid*)&f32Value); + } + + float output = 0; + + output = (((filter_reg * faktor) + ((100 - faktor) * (float)f32Value))) / 100; + filter_reg = output; + + + timeStamp = 0; + //create new media sample + cObjectPtr pMediaSample; + AllocMediaSample((tVoid**)&pMediaSample); + + //allocate memory with the size given by the descriptor + cObjectPtr pSerializer; + m_pCoderDescSignalValue->GetMediaSampleSerializer(&pSerializer); + tInt nSize = pSerializer->GetDeserializedSize(); + pMediaSample->AllocBuffer(nSize); + + //write date to the media sample with the coder of the descriptor + { + __adtf_sample_write_lock_mediadescription(m_pCoderDescSignalValue, pMediaSample, pCoder); + + pCoder->Set("f32Value", (tVoid*)&(output)); + pCoder->Set("ui32ArduinoTimestamp", (tVoid*)&timeStamp); + } + + //transmit media sample over output pin + pMediaSample->SetTime(_clock->GetStreamTime()); + m_pin_output.Transmit(pMediaSample); + } + } + RETURN_NOERROR; +} diff --git a/pool/shard001/C++/0018120_view_update_job.cpp b/pool/shard001/C++/0018120_view_update_job.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21a8045cf7d0e834c6bca9b302045a286a853f4e --- /dev/null +++ b/pool/shard001/C++/0018120_view_update_job.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2008,2009, Yale Laboratory of Networked Systems + * 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 Yale University 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 "view_update_job.h" + +#include +#include +#include +#include "state.h" +#include "plugin_base.h" +#include "view_update.h" + +ViewUpdateJob::ViewUpdateJob(JobQueuePtr queue, const boost::system_time& deadline, const std::string& name) + : Job(queue, deadline), + name_(name), + interval_(0) +{ +} + +void ViewUpdateJob::run() +{ + get_logger()->info("starting update"); + + get_logger()->debug("acquiring locks"); + GlobalStatePtr global_state = GLOBAL_STATE; + UpgradableReadLock global_state_lock(*global_state); + + NetStatePtr net_state = global_state->get_net(global_state_lock); + BlockReadLock net_state_lock(*net_state); + + ViewRegistryPtr views = global_state->get_views(global_state_lock); + UpgradableReadLock views_lock(*views); + + ViewPtr view = views->get(name_, views_lock); + if (!view) + { + get_logger()->warn("Could not find view: %s; cancelling job", name_.c_str()); + return; + } + + ViewUpdateStateUpgrade view_state(view); + + interval_ = ViewUpdateUpgrade(global_state, global_state_lock, + net_state, net_state_lock, + views, views_lock, + view_state).do_update(); + + if (interval_ > 0) + { + get_logger()->info("update succeeded; rescheduling"); + reschedule(); + } + else + get_logger()->info("update failed; NOT rescheduling"); +} + +bool ViewUpdateJob::equals(JobPtr job) +{ + boost::shared_ptr view_job = boost::dynamic_pointer_cast(job); + if (!view_job) + return false; + + return name_ == view_job->name_; +} + +JobPtr ViewUpdateJob::make_next() +{ + if (interval_ == 0) + return JobPtr(); + + boost::posix_time::time_duration interval = boost::posix_time::seconds(interval_); + return JobPtr(new ViewUpdateJob(get_queue(), boost::get_system_time() + interval, name_)); +} diff --git a/pool/shard001/C++/0018126_track.cpp b/pool/shard001/C++/0018126_track.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6086735258a51516b3c3bd5b628909ff7b8d4a0 --- /dev/null +++ b/pool/shard001/C++/0018126_track.cpp @@ -0,0 +1,150 @@ +/*************************************************************************** + * Copyright (C) 2009 by Marek Vavrusa * + * 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, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * + ***************************************************************************/ + + +#include +#include +#include +#include +#include +#include +#include "track.h" + +Track::Track(QGraphicsWidget *parent) : + Plasma::Label(parent), mBarValue(0.0), mBarColor(QColor(215, 0, 25, 96)) +{ + // Set default size + QFontMetrics fnm(font()); + setScaledContents(false); + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); + setMaximumHeight(fnm.height() * 1.25); +} + +void Track::setFlags(Flags flags) +{ + mFlags = flags; + updateLabel(); +} + +void Track::setFormat(const QString &fmt) +{ + mFormat = fmt; + updateLabel(); +} + +float Track::setBarValue(float val) +{ + float oldVal = mBarValue; + mBarValue = val; + update(); + + return oldVal; +} + +QColor Track::setBarColor(const QColor& color) +{ + QColor oldColor = mBarColor; + mBarColor = color; + update(); + return oldColor; +} + +void Track::updateLabel() +{ + // Get text + QString text = toString(); + + // Update toolTip + if(!attrib(PlayCount).isEmpty()) + setToolTip(text + tr(" (%1 plays)").arg(attrib(PlayCount))); + else + setToolTip(text); + + // Elide text + if(flags() & ElideText) { + QFontMetrics fnm(font()); + setText(fnm.elidedText(text, Qt::ElideRight, contentsRect().width())); + } +} + +QString Track::toString() { + QString res(format()); + res.replace("%n", attrib(Name)); + res.replace("%l", attrib(Album)); + res.replace("%a", attrib(Artist)); + res.replace("%d", attrib(Date)); + res.replace("%p", attrib(PlayCount)); + return res; +} + +void Track::resizeEvent(QGraphicsSceneResizeEvent *event) +{ + Plasma::Label::resizeEvent(event); + + // Update label + updateLabel(); +} + +void Track::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + // Unused + Q_UNUSED(option); + Q_UNUSED(widget); + + // Paint background + if(mBarValue > 0.0) { + painter->setRenderHint(QPainter::Antialiasing); + + QRectF barRect = boundingRect(); + barRect.setWidth(barRect.width() * mBarValue); + + // Bar color + QColor barColor(mBarColor); + if(flags() & NowPlaying) + barColor = QColor(255, 252, 202, 96); // Soft yellow + + // Edge decoration for progress + if(flags() & EdgeMark) { + + // Avoid overflow + float edgeLen = barRect.height() * 0.5; + if(barRect.width() > edgeLen) + barRect.setWidth(barRect.width() - edgeLen); + else + barRect.setWidth(0.0); + + QPainterPath path(barRect.topLeft()); + path.lineTo(barRect.topRight()); + path.lineTo(barRect.topRight() + QPointF(edgeLen, barRect.height() * 0.5)); + path.lineTo(barRect.bottomRight()); + path.lineTo(barRect.bottomLeft()); + path.closeSubpath(); + painter->fillPath(path, QBrush(barColor)); + } + else { + painter->fillRect(barRect, QBrush(barColor)); + } + } + + // Paint text + painter->drawText(boundingRect(), text()); +} + +#include "track.moc" diff --git a/pool/shard001/C++/0018127_shortcuts_database_unittest.cc b/pool/shard001/C++/0018127_shortcuts_database_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..19c2be2328c2ae62fdd6b52768fc514e5ecd1983 --- /dev/null +++ b/pool/shard001/C++/0018127_shortcuts_database_unittest.cc @@ -0,0 +1,191 @@ +// 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 "base/files/scoped_temp_dir.h" +#include "base/path_service.h" +#include "base/stringprintf.h" +#include "base/time.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/history/shortcuts_database.h" +#include "chrome/test/base/testing_profile.h" +#include "sql/statement.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace history { + +struct ShortcutsDatabaseTestInfo { + std::string guid; + std::string url; + std::string title; // The text that orginally was searched for. + std::string contents; + std::string contents_class; + std::string description; + std::string description_class; + int typed_count; + int days_from_now; +} shortcut_test_db[] = { + { "BD85DBA2-8C29-49F9-84AE-48E1E90880DF", + "http://www.google.com/", "goog", + "Google", "0,1,4,0", "Google", "0,3,4,1", 100, 1 }, + { "BD85DBA2-8C29-49F9-84AE-48E1E90880E0", + "http://slashdot.org/", "slash", + "slashdot.org", "0,3,5,1", + "Slashdot - News for nerds, stuff that matters", "0,2,5,0", 100, 0}, + { "BD85DBA2-8C29-49F9-84AE-48E1E90880E1", + "http://slashdot.org/", "news", + "slashdot.org", "0,1", + "Slashdot - News for nerds, stuff that matters", "0,0,11,2,15,0", 5, 0}, +}; + +class ShortcutsDatabaseTest : public testing::Test { + public: + virtual void SetUp(); + virtual void TearDown(); + + void ClearDB(); + size_t CountRecords() const; + + ShortcutsBackend::Shortcut ShortcutFromTestInfo( + const ShortcutsDatabaseTestInfo& info); + + void AddAll(); + + scoped_ptr profile_; + scoped_refptr db_; +}; + +void ShortcutsDatabaseTest::SetUp() { + profile_.reset(new TestingProfile()); + db_ = new ShortcutsDatabase(profile_.get()); + ASSERT_TRUE(db_->Init()); + ClearDB(); +} + +void ShortcutsDatabaseTest::TearDown() { + db_ = NULL; +} + +void ShortcutsDatabaseTest::ClearDB() { + sql::Statement + s(db_->db_.GetUniqueStatement("DELETE FROM omni_box_shortcuts")); + EXPECT_TRUE(s.Run()); +} + +size_t ShortcutsDatabaseTest::CountRecords() const { + sql::Statement s(db_->db_.GetUniqueStatement( + "SELECT count(*) FROM omni_box_shortcuts")); + EXPECT_TRUE(s.Step()); + return static_cast(s.ColumnInt(0)); +} + +ShortcutsBackend::Shortcut ShortcutsDatabaseTest::ShortcutFromTestInfo( + const ShortcutsDatabaseTestInfo& info) { + return ShortcutsBackend::Shortcut(info.guid, ASCIIToUTF16(info.title), + GURL(info.url), ASCIIToUTF16(info.contents), + AutocompleteMatch::ClassificationsFromString(info.contents_class), + ASCIIToUTF16(info.description), + AutocompleteMatch::ClassificationsFromString(info.description_class), + base::Time::Now() - base::TimeDelta::FromDays(info.days_from_now), + info.typed_count); +} + +void ShortcutsDatabaseTest::AddAll() { + ClearDB(); + for (size_t i = 0; i < arraysize(shortcut_test_db); ++i) { + db_->AddShortcut(ShortcutFromTestInfo(shortcut_test_db[i])); + } + EXPECT_EQ(arraysize(shortcut_test_db), CountRecords()); +} + +TEST_F(ShortcutsDatabaseTest, AddShortcut) { + ClearDB(); + EXPECT_EQ(0U, CountRecords()); + EXPECT_TRUE(db_->AddShortcut(ShortcutFromTestInfo(shortcut_test_db[0]))); + EXPECT_EQ(1U, CountRecords()); + EXPECT_TRUE(db_->AddShortcut(ShortcutFromTestInfo(shortcut_test_db[1]))); + EXPECT_EQ(2U, CountRecords()); + EXPECT_TRUE(db_->AddShortcut(ShortcutFromTestInfo(shortcut_test_db[2]))); + EXPECT_EQ(3U, CountRecords()); +} + +TEST_F(ShortcutsDatabaseTest, UpdateShortcut) { + AddAll(); + ShortcutsBackend::Shortcut shortcut( + ShortcutFromTestInfo(shortcut_test_db[1])); + shortcut.contents = ASCIIToUTF16("gro.todhsals"); + EXPECT_TRUE(db_->UpdateShortcut(shortcut)); + ShortcutsDatabase::GuidToShortcutMap shortcuts; + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + ShortcutsDatabase::GuidToShortcutMap::iterator it = + shortcuts.find(shortcut.id); + EXPECT_TRUE(it != shortcuts.end()); + EXPECT_TRUE(it->second.contents == shortcut.contents); +} + +TEST_F(ShortcutsDatabaseTest, DeleteShortcutsWithIds) { + AddAll(); + std::vector shortcut_ids; + shortcut_ids.push_back(shortcut_test_db[0].guid); + shortcut_ids.push_back(shortcut_test_db[2].guid); + EXPECT_TRUE(db_->DeleteShortcutsWithIds(shortcut_ids)); + EXPECT_EQ(arraysize(shortcut_test_db) - 2, CountRecords()); + + ShortcutsDatabase::GuidToShortcutMap shortcuts; + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + + ShortcutsDatabase::GuidToShortcutMap::iterator it = + shortcuts.find(shortcut_test_db[0].guid); + EXPECT_TRUE(it == shortcuts.end()); + + it = shortcuts.find(shortcut_test_db[1].guid); + EXPECT_TRUE(it != shortcuts.end()); + + it = shortcuts.find(shortcut_test_db[2].guid); + EXPECT_TRUE(it == shortcuts.end()); +} + +TEST_F(ShortcutsDatabaseTest, DeleteShortcutsWithUrl) { + AddAll(); + + EXPECT_TRUE(db_->DeleteShortcutsWithUrl("http://slashdot.org/")); + EXPECT_EQ(arraysize(shortcut_test_db) - 2, CountRecords()); + + ShortcutsDatabase::GuidToShortcutMap shortcuts; + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + + ShortcutsDatabase::GuidToShortcutMap::iterator it = + shortcuts.find(shortcut_test_db[0].guid); + EXPECT_TRUE(it != shortcuts.end()); + + it = shortcuts.find(shortcut_test_db[1].guid); + EXPECT_TRUE(it == shortcuts.end()); + + it = shortcuts.find(shortcut_test_db[2].guid); + EXPECT_TRUE(it == shortcuts.end()); +} + +TEST_F(ShortcutsDatabaseTest, LoadShortcuts) { + AddAll(); + ShortcutsDatabase::GuidToShortcutMap shortcuts; + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + + for (size_t i = 0; i < arraysize(shortcut_test_db); ++i) { + SCOPED_TRACE(base::StringPrintf("Looking for shortcut #%d", + static_cast(i))); + EXPECT_TRUE(shortcuts.find(shortcut_test_db[i].guid) != shortcuts.end()); + } +} + +TEST_F(ShortcutsDatabaseTest, DeleteAllShortcuts) { + AddAll(); + ShortcutsDatabase::GuidToShortcutMap shortcuts; + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + EXPECT_EQ(arraysize(shortcut_test_db), shortcuts.size()); + EXPECT_TRUE(db_->DeleteAllShortcuts()); + EXPECT_TRUE(db_->LoadShortcuts(&shortcuts)); + EXPECT_EQ(0U, shortcuts.size()); +} + +} // namespace history diff --git a/pool/shard001/C++/0018131_macro.cpp b/pool/shard001/C++/0018131_macro.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b34adacdd71b3cd4f64160697ab94711177ae07 --- /dev/null +++ b/pool/shard001/C++/0018131_macro.cpp @@ -0,0 +1,201 @@ +/************************************************************************** +** +** Copyright (c) 2014 Nicolas Arnaud-Cormos +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "macro.h" +#include "macroevent.h" + +#include +#include + +#include +#include + +using namespace Macros::Internal; + +/*! + \class Macros::Macro + + \brief The Macro class represents a macro, which is more or less a list of + Macros::MacroEvent. + + A macro is a list of events that can be replayed in \QC. A macro has + an header consisting of the \QC version where the macro was created + and a description. + The name of the macro is the filename without the extension. +*/ + +class Macro::MacroPrivate +{ +public: + MacroPrivate(); + + QString description; + QString version; + QString fileName; + QList events; +}; + +Macro::MacroPrivate::MacroPrivate() : + version(QLatin1String(Core::Constants::IDE_VERSION_LONG)) +{ +} + + + +// ---------- Macro ------------ + +Macro::Macro() : + d(new MacroPrivate) +{ +} + +Macro::Macro(const Macro &other): + d(new MacroPrivate) +{ + d->description = other.d->description; + d->version = other.d->version; + d->fileName = other.d->fileName; + d->events = other.d->events; +} + +Macro::~Macro() +{ + delete d; +} + +Macro& Macro::operator=(const Macro &other) +{ + if (this == &other) + return *this; + d->description = other.d->description; + d->version = other.d->version; + d->fileName = other.d->fileName; + d->events = other.d->events; + return *this; +} + +bool Macro::load(QString fileName) +{ + if (d->events.count()) + return true; // the macro is not empty + + // Take the current filename if the parameter is null + if (fileName.isNull()) + fileName = d->fileName; + else + d->fileName = fileName; + + // Load all the macroevents + QFile file(fileName); + if (file.open(QFile::ReadOnly)) { + QDataStream stream(&file); + stream >> d->version; + stream >> d->description; + while (!stream.atEnd()) { + MacroEvent macroEvent; + macroEvent.load(stream); + append(macroEvent); + } + return true; + } + return false; +} + +bool Macro::loadHeader(const QString &fileName) +{ + d->fileName = fileName; + QFile file(fileName); + if (file.open(QFile::ReadOnly)) { + QDataStream stream(&file); + stream >> d->version; + stream >> d->description; + return true; + } + return false; +} + +bool Macro::save(const QString &fileName, QWidget *parent) +{ + Utils::FileSaver saver(fileName); + if (!saver.hasError()) { + QDataStream stream(saver.file()); + stream << d->version; + stream << d->description; + foreach (const MacroEvent &event, d->events) { + event.save(stream); + } + saver.setResult(&stream); + } + if (!saver.finalize(parent)) + return false; + d->fileName = fileName; + return true; +} + +QString Macro::displayName() const +{ + QFileInfo fileInfo(d->fileName); + return fileInfo.baseName(); +} + +void Macro::append(const MacroEvent &event) +{ + d->events.append(event); +} + +const QString &Macro::description() const +{ + return d->description; +} + +void Macro::setDescription(const QString &text) +{ + d->description = text; +} + +const QString &Macro::version() const +{ + return d->version; +} + +const QString &Macro::fileName() const +{ + return d->fileName; +} + +const QList &Macro::events() const +{ + return d->events; +} + +bool Macro::isWritable() const +{ + QFileInfo fileInfo(d->fileName); + return fileInfo.exists() && fileInfo.isWritable(); +} diff --git a/pool/shard001/C++/0018135_waypoint-mobility-model-test.cc b/pool/shard001/C++/0018135_waypoint-mobility-model-test.cc new file mode 100644 index 0000000000000000000000000000000000000000..624fea228c989b80fbf1c89aed7f6303d268a8f2 --- /dev/null +++ b/pool/shard001/C++/0018135_waypoint-mobility-model-test.cc @@ -0,0 +1,157 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 Phillip Sitbon + * + * 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 + * + * Author: Phillip Sitbon + */ + +#include "ns3/simulator.h" +#include "ns3/boolean.h" +#include "ns3/config.h" +#include "ns3/waypoint-mobility-model.h" +#include "ns3/test.h" + +using namespace ns3; + +class WaypointMobilityModelNotifyTest : public TestCase +{ +public: + WaypointMobilityModelNotifyTest (bool lazy) + : TestCase (lazy ? "Check Waypoint Mobility Model LAZY notification accuracy" + : "Check Waypoint Mobility Model NON-LAZY notification accuracy"), + lazyNotify (lazy) + { + } + virtual ~WaypointMobilityModelNotifyTest () + { + } + +private: + std::vector > mobilityStack; + uint32_t mobilityCount; + uint32_t waypointCount; + std::deque waypoints; + bool lazyNotify; +private: + virtual void DoRun (void); + virtual void DoTeardown (void); + void ForceUpdates (void); + void CourseChangeCallback (std::string path, Ptr model); +}; + +void +WaypointMobilityModelNotifyTest::DoTeardown (void) +{ + mobilityStack.clear(); + waypoints.clear(); +} + +void +WaypointMobilityModelNotifyTest::DoRun (void) +{ + mobilityCount = 1; + waypointCount = 100; + + ObjectFactory mobilityFactory; + mobilityFactory.SetTypeId ("ns3::WaypointMobilityModel"); + mobilityFactory.Set ("LazyNotify", BooleanValue (lazyNotify)); + + // Populate the vector of mobility models. + for (uint32_t i = 0; i < mobilityCount; i++) + { + // Create a new mobility model. + Ptr model = mobilityFactory.Create ()->GetObject (); + + // Add this mobility model to the stack. + mobilityStack.push_back (model); + Simulator::Schedule (Seconds (0.0), &Object::Initialize, model); + } + + Waypoint wpt (Seconds (0.0), Vector (0.0, 0.0, 0.0)); + + // Create waypoints + for ( uint32_t iw = 0; iw < waypointCount; ++iw ) + { + wpt.time += Seconds (1.0); + waypoints.push_back (wpt); + } + + // Add the same waypoints to each node + std::vector >::iterator i; + for (i = mobilityStack.begin (); i != mobilityStack.end (); ++i) + { + Ptr mob = (*i)->GetObject (); + + for ( std::deque::iterator w = waypoints.begin (); w != waypoints.end (); ++w ) + { + mob->AddWaypoint (*w); + } + } + + // Schedule updates at non-waypoint times to make sure lazy notifications don't happen + for ( double updateTime = 0.5; updateTime <= ((double)waypointCount + 1.5); updateTime += 1.0 ) + { + Simulator::Schedule (Seconds (updateTime), &WaypointMobilityModelNotifyTest::ForceUpdates, this); + } + + Config::Connect ("/NodeList/*/$ns3::WaypointMobilityModel/CourseChange", + MakeCallback (&WaypointMobilityModelNotifyTest::CourseChangeCallback, this)); + + Simulator::Stop (Seconds ((double)waypointCount + 2.0)); + Simulator::Run (); + Simulator::Destroy (); +} +void +WaypointMobilityModelNotifyTest::ForceUpdates (void) +{ + std::vector >::iterator i; + for (i = mobilityStack.begin (); i != mobilityStack.end (); ++i) + { + Ptr mob = (*i)->GetObject (); + mob->Update (); + } +} +void +WaypointMobilityModelNotifyTest::CourseChangeCallback (std::string path, Ptr model) +{ + const Time now = Simulator::Now (); + const double sec = now.GetSeconds (); + Ptr mob = model->GetObject (); + + NS_TEST_EXPECT_MSG_EQ (now, mob->m_current.time, "Waypoint time not properly updated"); + + if ( !lazyNotify ) + { + // All waypoints are on second boundaries only + NS_TEST_EXPECT_MSG_EQ (sec - ((double)((int)sec)) + sec, sec, + "Course didn't change on one second time boundary with NON-LAZY notifcations"); + } + else + { + // Updates should happen at the times they are forced, in between waypoints. + NS_TEST_EXPECT_MSG_EQ (sec - ((double)((int)sec)), 0.5, + "Course didn't change between waypoints with LAZY notifications"); + } +} + +static struct WaypointMobilityModelTestSuite : public TestSuite +{ + WaypointMobilityModelTestSuite () : TestSuite ("waypoint-mobility-model", UNIT) + { + AddTestCase (new WaypointMobilityModelNotifyTest (true), TestCase::QUICK); + AddTestCase (new WaypointMobilityModelNotifyTest (false), TestCase::QUICK); + } +} g_waypointMobilityModelTestSuite; diff --git a/pool/shard001/C++/0018137_TrayItemWin.cpp b/pool/shard001/C++/0018137_TrayItemWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abcc0676a66c759754907687aa0809402638965a --- /dev/null +++ b/pool/shard001/C++/0018137_TrayItemWin.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2009-2010 Appcelerator, Inc. 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. + */ + +#include "TrayItemWin.h" + +#include "MenuItemWin.h" +#include "MenuWin.h" +#include "UIWin.h" + +using namespace std; + +namespace Titanium { + +vector > TrayItemWin::trayItems; +UINT TrayItemWin::trayClickedMessage = + ::RegisterWindowMessageA(PRODUCT_NAME"TrayClicked"); + +TrayItemWin::TrayItemWin(string& iconURL, KMethodRef cbSingleClick) + : TrayItem(iconURL) + , oldNativeMenu(0) + , trayIconData(0) +{ + this->AddEventListener(Event::CLICKED, cbSingleClick); + + HWND hwnd = Host::GetInstance()->AddMessageHandler( + &TrayItemWin::MessageHandler); + + NOTIFYICONDATA* notifyIconData = new NOTIFYICONDATA; + notifyIconData->cbSize = sizeof(NOTIFYICONDATA); + notifyIconData->hWnd = hwnd; + notifyIconData->uID = ++UIWin::nextItemId; + notifyIconData->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + notifyIconData->uCallbackMessage = trayClickedMessage; + + HICON icon = UIWin::LoadImageAsIcon(iconPath, + GetSystemMetrics(SM_CXSMICON), + GetSystemMetrics(SM_CYSMICON)); + notifyIconData->hIcon = icon; + + lstrcpy(notifyIconData->szTip, L"Titanium Application"); + Shell_NotifyIcon(NIM_ADD, notifyIconData); + this->trayIconData = notifyIconData; + + trayItems.push_back(this); +} + +TrayItemWin::~TrayItemWin() +{ + this->Remove(); +} + +void TrayItemWin::SetIcon(string& iconPath) +{ + if (!this->trayIconData) + return; + + HICON icon = UIWin::LoadImageAsIcon(iconPath, + GetSystemMetrics(SM_CXSMICON), + GetSystemMetrics(SM_CYSMICON)); + this->trayIconData->hIcon = icon; + Shell_NotifyIcon(NIM_MODIFY, this->trayIconData); +} + +void TrayItemWin::SetMenu(AutoPtr menu) +{ + this->menu = menu; +} + +void TrayItemWin::SetHint(string& hint) +{ + if (this->trayIconData) + { + // NotifyIconData.szTip has 128 character limit. + ZeroMemory(this->trayIconData->szTip, 128); + + // make sure we don't overflow the static buffer. + wstring hintW = ::UTF8ToWide(hint); + lstrcpyn(this->trayIconData->szTip, hintW.c_str(), 128); + + Shell_NotifyIcon(NIM_MODIFY, this->trayIconData); + } +} + +void TrayItemWin::Remove() +{ + if (this->trayIconData) + { + Shell_NotifyIcon(NIM_DELETE, this->trayIconData); + this->trayIconData = 0; + } +} + +void TrayItemWin::HandleRightClick() +{ + if (this->oldNativeMenu) + { + DestroyMenu(this->oldNativeMenu); + this->oldNativeMenu = 0; + } + + if (this->menu.isNull()) + return; + + AutoPtr win32menu = this->menu.cast(); + if (win32menu.isNull()) + return; + + this->oldNativeMenu = win32menu->CreateNative(false); + POINT pt; + GetCursorPos(&pt); + + SetForegroundWindow(this->trayIconData->hWnd); + TrackPopupMenu(this->oldNativeMenu, TPM_BOTTOMALIGN, + pt.x, pt.y, 0, this->trayIconData->hWnd, NULL); + PostMessage(this->trayIconData->hWnd, WM_NULL, 0, 0); +} + +void TrayItemWin::HandleLeftClick() +{ + try + { + this->FireEvent(Event::CLICKED); + } + catch (ValueException& e) + { + Logger* logger = Logger::Get("UI.TrayItemWin"); + SharedString ss = e.DisplayString(); + logger->Error("Tray icon single click callback failed: %s", ss->c_str()); + } +} + +void TrayItemWin::HandleDoubleLeftClick() +{ + try + { + this->FireEvent(Event::DOUBLE_CLICKED); + } + catch (ValueException& e) + { + Logger* logger = Logger::Get("UI.TrayItemWin"); + SharedString ss = e.DisplayString(); + logger->Error("Tray icon double left click callback failed: %s", ss->c_str()); + } +} + +UINT TrayItemWin::GetId() +{ + return this->trayIconData->uID; +} + +/*static*/ +bool TrayItemWin::MessageHandler( + HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + if (message == trayClickedMessage) + { + UINT button = (UINT) lParam; + int id = LOWORD(wParam); + bool handled = false; + + for (size_t i = 0; i < trayItems.size(); i++) + { + AutoPtr item = trayItems[i]; + + item->is_double_clicked = false; + if(item->GetId() == id && button == WM_LBUTTONDBLCLK) + { + item->is_double_clicked = true; + KillTimer(hWnd, 100); + item->HandleDoubleLeftClick(); + handled = true; + } + if (item->GetId() == id && button == WM_LBUTTONDOWN) + { + SetTimer(hWnd, 100, GetDoubleClickTime(), (TIMERPROC)DoubleClickTimerProc); + handled = true; + } + else if (item->GetId() == id && button == WM_RBUTTONDOWN) + { + item->HandleRightClick(); + handled = true; + } + } + return handled; + } + else if (message == WM_MENUCOMMAND) + { + HMENU nativeMenu = (HMENU) lParam; + UINT position = (UINT) wParam; + return MenuItemWin::HandleClickEvent(nativeMenu, position); + } + else + { + // Not handled; + return false; + } +} + +/*static*/ +LRESULT CALLBACK TrayItemWin::DoubleClickTimerProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + int id = LOWORD(wParam); + bool handled = false; + + KillTimer(hWnd, 100); + for (size_t i = 0; i < trayItems.size(); i++) + { + AutoPtr item = trayItems[i]; + if (!(item->is_double_clicked)) + { + item->HandleLeftClick(); + } + + item->is_double_clicked = false; + } + return 0; +} + +} // namespace Titanium diff --git a/pool/shard001/C++/0018140_dep.cc b/pool/shard001/C++/0018140_dep.cc new file mode 100644 index 0000000000000000000000000000000000000000..0c42050b75a11e051ea709c81edb63155f6e6d89 --- /dev/null +++ b/pool/shard001/C++/0018140_dep.cc @@ -0,0 +1,89 @@ +// Copyright (c) 2006-2008 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 "sandbox/win/src/dep.h" + +#include + +#include "base/logging.h" + +namespace sandbox { + +namespace { + +// These values are in the Windows 2008 SDK but not in the previous ones. Define +// the values here until we're sure everyone updated their SDK. +#ifndef PROCESS_DEP_ENABLE +#define PROCESS_DEP_ENABLE 0x00000001 +#endif +#ifndef PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION +#define PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION 0x00000002 +#endif + +// SetProcessDEPPolicy is declared in the Windows 2008 SDK. +typedef BOOL (WINAPI *FnSetProcessDEPPolicy)(DWORD dwFlags); + +enum PROCESS_INFORMATION_CLASS { + ProcessExecuteFlags = 0x22, +}; + +// Flags named as per their usage. +const int MEM_EXECUTE_OPTION_ENABLE = 1; +const int MEM_EXECUTE_OPTION_DISABLE = 2; +const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4; +const int MEM_EXECUTE_OPTION_PERMANENT = 8; + +// Not exactly the right signature but that will suffice. +typedef HRESULT (WINAPI *FnNtSetInformationProcess)( + HANDLE ProcessHandle, + PROCESS_INFORMATION_CLASS ProcessInformationClass, + PVOID ProcessInformation, + ULONG ProcessInformationLength); + +} // namespace + +bool SetCurrentProcessDEP(DepEnforcement enforcement) { +#ifdef _WIN64 + // DEP is always on in x64. + return enforcement != DEP_DISABLED; +#endif + // Only available on Windows XP SP2 and Windows Server 2003 SP1. + // For reference: http://www.uninformed.org/?v=2&a=4 + FnNtSetInformationProcess NtSetInformationProc = + reinterpret_cast( + GetProcAddress(GetModuleHandle(L"ntdll.dll"), + "NtSetInformationProcess")); + + if (!NtSetInformationProc) + return false; + + // Flags being used as per SetProcessDEPPolicy on Vista SP1. + ULONG dep_flags; + switch (enforcement) { + case DEP_DISABLED: + // 2 + dep_flags = MEM_EXECUTE_OPTION_DISABLE; + break; + case DEP_ENABLED: + // 9 + dep_flags = MEM_EXECUTE_OPTION_PERMANENT | MEM_EXECUTE_OPTION_ENABLE; + break; + case DEP_ENABLED_ATL7_COMPAT: + // 0xD + dep_flags = MEM_EXECUTE_OPTION_PERMANENT | MEM_EXECUTE_OPTION_ENABLE | + MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION; + break; + default: + NOTREACHED(); + return false; + } + + HRESULT status = NtSetInformationProc(GetCurrentProcess(), + ProcessExecuteFlags, + &dep_flags, + sizeof(dep_flags)); + return SUCCEEDED(status); +} + +} // namespace sandbox diff --git a/pool/shard001/C++/0018148_CodeCoverage_Callback.cpp b/pool/shard001/C++/0018148_CodeCoverage_Callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d92b0b59f50586fd495afada35518caed73e2c13 --- /dev/null +++ b/pool/shard001/C++/0018148_CodeCoverage_Callback.cpp @@ -0,0 +1,67 @@ +// +// OpenCover - S Wilde +// +// This source code is released under the MIT License; see the accompanying license file. +// +// CodeCoverage.cpp : Implementation of CCodeCoverage + +#include "stdafx.h" +#include "CodeCoverage.h" + +UINT_PTR CCodeCoverage::FunctionMapper2(FunctionID functionId, void* clientData, BOOL* pbHookFunction) +{ + CCodeCoverage* profiler = static_cast(clientData); + *pbHookFunction = FALSE; + if(profiler == NULL) + return 0; + + UINT_PTR retVal = 0; + std::wstring modulePath; + mdToken functionToken; + ModuleID moduleId; + AssemblyID assemblyId; + + if (profiler->GetTokenAndModule(functionId, functionToken, moduleId, modulePath, &assemblyId)) + { + ULONG uniqueId; + if (profiler->_host->TrackMethod(functionToken, (LPWSTR)modulePath.c_str(), + (LPWSTR)profiler->m_allowModulesAssemblyMap[modulePath].c_str(), uniqueId)) + { + *pbHookFunction = TRUE; + retVal = uniqueId; + } + } + + return retVal; +} + +UINT_PTR CCodeCoverage::FunctionMapper(FunctionID functionId, BOOL* pbHookFunction) +{ + return FunctionMapper2(functionId, g_pProfiler, pbHookFunction); +} + +void CCodeCoverage::FunctionEnter2( + /*[in]*/FunctionID funcID, + /*[in]*/UINT_PTR clientData, + /*[in]*/COR_PRF_FRAME_INFO func, + /*[in]*/COR_PRF_FUNCTION_ARGUMENT_INFO *argumentInfo) +{ + _host->AddTestEnterPoint((ULONG)clientData); +} + +void CCodeCoverage::FunctionLeave2( + /*[in]*/FunctionID funcID, + /*[in]*/UINT_PTR clientData, + /*[in]*/COR_PRF_FRAME_INFO func, + /*[in]*/COR_PRF_FUNCTION_ARGUMENT_RANGE *retvalRange) +{ + _host->AddTestLeavePoint((ULONG)clientData); +} + +void CCodeCoverage::FunctionTailcall2( + /*[in]*/FunctionID funcID, + /*[in]*/UINT_PTR clientData, + /*[in]*/COR_PRF_FRAME_INFO func) +{ + _host->AddTestTailcallPoint((ULONG)clientData); +} diff --git a/pool/shard001/C++/0018150_reactor.cpp b/pool/shard001/C++/0018150_reactor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c7a07bd31e97efdc2869a98f7933c22cccc228d --- /dev/null +++ b/pool/shard001/C++/0018150_reactor.cpp @@ -0,0 +1,146 @@ +// (C) 2013 Cybozu. + +#include "reactor.hpp" +#include "util.hpp" + +#include +#include +#include + +namespace { + +const int EPOLL_SIZE = 128; +const int POLLING_TIMEOUT = 100; // milli seconds + +} + +namespace cybozu { + +reactor::reactor(): + m_fd( epoll_create1(EPOLL_CLOEXEC) ), m_running(true) +{ + if( m_fd == -1 ) + throw_unix_error(errno, "epoll_create1"); + m_resources.max_load_factor(1.0); + m_resources.reserve(100000); + m_readables.reserve(256); + m_readables_copy.reserve(256); + m_drop_req.reserve(256); + m_drop_req_copy.reserve(256); +} + +reactor::~reactor() { + ::close(m_fd); +} + +void reactor::add_resource(std::unique_ptr res, int events) { + if( res->m_reactor != nullptr ) + throw std::logic_error(" already added!"); + res->m_reactor = this; + const int fd = res->fileno(); + struct epoll_event ev; + ev.events = events | EPOLLET; + ev.data.fd = fd; + if( epoll_ctl(m_fd, EPOLL_CTL_ADD, fd, &ev) == -1 ) + throw_unix_error(errno, "epoll_ctl"); + m_resources.emplace(fd, std::move(res)); +} + +void reactor::modify_events(const resource& res, int events) { + const int fd = res.fileno(); + struct epoll_event ev; + ev.events = events | EPOLLET; + ev.data.fd = fd; + if( epoll_ctl(m_fd, EPOLL_CTL_MOD, fd, &ev) == -1 ) + throw_unix_error(errno, "epoll_ctl"); +} + +void reactor::run(std::function callback, int interval) { + namespace crn = std::chrono; + const int milli_interval = interval * 1000; + auto last = crn::steady_clock::now(); + + m_running = true; + while( m_running ) { + poll(); + auto now = crn::steady_clock::now(); + auto diff = crn::duration_cast(now - last).count(); + if( diff > milli_interval ) { + callback(*this); + last = now; + } + } +} + +void reactor::remove_resource(int fd) { + resource_map::iterator it = m_resources.find(fd); + if( it == m_resources.end() ) { + dump_stack(); + throw std::logic_error("bug in remove_resource"); + } + m_garbage.emplace_back( std::move(it->second) ); + m_resources.erase(it); + if( epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL) == -1 ) + throw_unix_error(errno, "epoll_ctl(EPOLL_CTL_DEL)"); + m_readables.erase(std::remove(m_readables.begin(), m_readables.end(), fd), + m_readables.end()); +} + +void reactor::poll() { + // process readable resources + std::sort(m_readables.begin(), m_readables.end()); + std::unique_copy(m_readables.begin(), m_readables.end(), + std::back_inserter(m_readables_copy)); + m_readables.clear(); + for( int fd: m_readables_copy ) { + if( ! m_resources[fd]->on_readable() ) + remove_resource(fd); + } + m_readables_copy.clear(); + + // process drop requests + { + lock_guard g(m_lock); + m_drop_req_copy.swap(m_drop_req); + } + for( int fd: m_drop_req_copy ) + remove_resource(fd); + m_drop_req_copy.clear(); + + struct epoll_event events[EPOLL_SIZE]; + int timeout = m_readables.empty() ? POLLING_TIMEOUT : 0; + int n = epoll_wait(m_fd, events, EPOLL_SIZE, timeout); + if( n == -1 ) { + if( errno == EINTR ) return; + throw_unix_error(errno, "epoll_wait"); + } + + for( int i = 0; i < n; ++i ) { + const struct epoll_event& ev = events[i]; + const int fd = ev.data.fd; + resource& r = *(m_resources[fd]); + if( ev.events & EPOLLERR ) { + if( ! r.on_error() ) + remove_resource(fd); + continue; + } + if( ev.events & EPOLLHUP ) { + if( ! r.on_hangup() ) { + remove_resource(fd); + continue; + } + } + if( ev.events & EPOLLIN ) { + if( ! r.on_readable() ) { + remove_resource(fd); + continue; + } + } + if( ev.events & EPOLLOUT ) { + if( ! r.on_writable() ) + remove_resource(fd); + } + } +} + +} // namespace cybozu diff --git a/pool/shard001/C++/0018153_xrPhase_MergeLM.cpp b/pool/shard001/C++/0018153_xrPhase_MergeLM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eda4e58ada6e86f93f98e1c07c714d7da056b683 --- /dev/null +++ b/pool/shard001/C++/0018153_xrPhase_MergeLM.cpp @@ -0,0 +1,509 @@ + +#include "stdafx.h" +#include "build.h" + +#include "xrPhase_MergeLM_Rect.h" +#include "../xrlc_light/xrdeflector.h" +#include "../xrlc_light/xrlc_globaldata.h" +#include "../xrlc_light/lightmap.h" +// Surface access +extern void _InitSurface(); +extern BOOL _rect_place(L_rect& r, lm_layer* D); + +IC int compare_defl(CDeflector* D1, CDeflector* D2) { + // First - by material + u16 M1 = D1->GetBaseMaterial(); + u16 M2 = D2->GetBaseMaterial(); + if (M1 < M2) + return 1; // less + if (M1 > M2) + return 0; // more + return 2; // equal +} + +// should define LESS(D1GetBaseMaterial(); + u16 M2 = D2->GetBaseMaterial(); + + // 1. material area + u32 A1 = pBuild->materials()[M1].internal_max_area; + u32 A2 = pBuild->materials()[M2].internal_max_area; + if (A1 < A2) + return 2; // A2 better + if (A1 > A2) + return 1; // A1 better + + // 2. material sector (geom - locality) + u32 s1 = pBuild->materials()[M1].sector; + u32 s2 = pBuild->materials()[M2].sector; + if (s1 < s2) + return 2; // s2 better + if (s1 > s2) + return 1; // s1 better + + // 3. just material index + if (M1 < M2) + return 2; // s2 better + if (M1 > M2) + return 1; // s1 better + + // 4. deflector area + u32 da1 = D1->layer.Area(); + u32 da2 = D2->layer.Area(); + if (da1 < da2) + return 2; // s2 better + if (da1 > da2) + return 1; // s1 better + + // 5. they are EQUAL + return 0; // equal +} + +// should define LESS(D1bMerged) { + D->bMerged = FALSE; + return TRUE; + } else + return FALSE; + }; +}; + +void CBuild::xrPhase_MergeLM() { + vecDefl Layer; + + // **** Select all deflectors, which contain this light-layer + Layer.clear(); + for (u32 it = 0; it < lc_global_data()->g_deflectors().size(); it++) { + CDeflector* D = lc_global_data()->g_deflectors()[it]; + if (D->bMerged) + continue; + Layer.push_back(D); + } + + // Merge this layer (which left unmerged) + while (Layer.size()) { + VERIFY(lc_global_data()); + string512 phase_name; + xr_sprintf(phase_name, "Building lightmap %d...", lc_global_data()->lightmaps().size()); + Phase(phase_name); + + // Sort layer by similarity (state changes) + // + calc material area + Status("Selection..."); + for (u32 it = 0; it < materials().size(); it++) + materials()[it].internal_max_area = 0; + for (u32 it = 0; it < Layer.size(); it++) { + CDeflector* D = Layer[it]; + materials()[D->GetBaseMaterial()].internal_max_area = + std::max(D->layer.Area(), materials()[D->GetBaseMaterial()].internal_max_area); + } + std::stable_sort(Layer.begin(), Layer.end(), sort_defl_complex); + + // Select first deflectors which can fit + Status("Selection..."); + u32 maxarea = c_LMAP_size * c_LMAP_size * 8; // Max up to 8 lm selected + u32 curarea = 0; + u32 merge_count = 0; + for (u32 it = 0; it < (int)Layer.size(); it++) { + int defl_area = Layer[it]->layer.Area(); + if (curarea + defl_area > maxarea) + break; + curarea += defl_area; + merge_count++; + } + + // Startup + Status("Processing..."); + _InitSurface(); + CLightmap* lmap = xr_new(); + VERIFY(lc_global_data()); + lc_global_data()->lightmaps().push_back(lmap); + + // Process + for (u32 it = 0; it < merge_count; it++) { + if (0 == (it % 1024)) + Status("Process [%d/%d]...", it, merge_count); + lm_layer& L = Layer[it]->layer; + L_rect rT, rS; + rS.a.set(0, 0); + rS.b.set(L.width + 2 * BORDER - 1, L.height + 2 * BORDER - 1); + rS.iArea = L.Area(); + rT = rS; + if (_rect_place(rT, &L)) { + BOOL bRotated; + if (rT.SizeX() == rS.SizeX()) { + R_ASSERT(rT.SizeY() == rS.SizeY()); + bRotated = FALSE; + } else { + R_ASSERT(rT.SizeX() == rS.SizeY()); + R_ASSERT(rT.SizeY() == rS.SizeX()); + bRotated = TRUE; + } + lmap->Capture(Layer[it], rT.a.x, rT.a.y, rT.SizeX(), rT.SizeY(), bRotated); + Layer[it]->bMerged = TRUE; + } + Progress(std::sqrt(float(it) / float(merge_count))); + } + Progress(1.f); + + // Remove merged lightmaps + Status("Cleanup..."); + vecDeflIt last = std::remove_if(Layer.begin(), Layer.end(), pred_remove()); + Layer.erase(last, Layer.end()); + + // Save + Status("Saving..."); + VERIFY(pBuild); + lmap->Save(pBuild->path); + } + VERIFY(lc_global_data()); + clMsg("%d lightmaps builded", lc_global_data()->lightmaps().size()); + + // Cleanup deflectors + Progress(1.f); + Status("Destroying deflectors..."); + for (u32 it = 0; it < lc_global_data()->g_deflectors().size(); it++) + xr_delete(lc_global_data()->g_deflectors()[it]); + lc_global_data()->g_deflectors().clear(); +} + +/* + +#include "stdafx.h" +#include "build.h" + +#include "xrPhase_MergeLM_Rect.h" +#include "../xrlc_light/xrdeflector.h" +#include "../xrlc_light/xrlc_globaldata.h" +#include "../xrlc_light/lightmap.h" +// Surface access +extern void _InitSurface (); +extern BOOL _rect_place (L_rect &r, lm_layer* D); + +IC int compare_defl (CDeflector* D1, CDeflector* D2) +{ + // First - by material + u16 M1 = D1->GetBaseMaterial(); + u16 M2 = D2->GetBaseMaterial(); + if (M1M2) return 0; // more + return 2; // equal +} + +// should define LESS(D1GetBaseMaterial(); + u16 M2 = D2->GetBaseMaterial(); + + // 1. material area + u32 A1 = pBuild->materials()[M1].internal_max_area; + u32 A2 = pBuild->materials()[M2].internal_max_area; + if (A1A2) return 1; // A1 better + + // 2. material sector (geom - locality) + u32 s1 = pBuild->materials()[M1].sector; + u32 s2 = pBuild->materials()[M2].sector; + if (s1s2) return 1; // s1 better + + // 3. just material index + if (M1M2) return 1; // s1 better + + // 4. deflector area + u32 da1 = D1->layer.Area(); + u32 da2 = D2->layer.Area(); + if (da1da2)return 1; // s1 better + + // 5. they are EQUAL + return 0; // equal +} + +// should define LESS(D1bMerged) {D->bMerged=FALSE; return TRUE; } else return FALSE; }; }; + +void MergeLM_process( u32 m_from , u32 m_to , vecDefl* pLayer , CLightmap* lmap ); + +typedef struct MERGELM_PARAMS +{ + u32 m_from; + u32 m_to; + vecDefl* Layer; + CLightmap* lmap; + HANDLE hEvents[3]; // 0=start,1=terminate,2=ready +} * LP_MERGELM_PARAMS; + +static CRITICAL_SECTION mergelm_cs; +static BOOL mergelm_threads_initialized = FALSE; +static u32 mergelm_threads_count = 0; +static LPHANDLE mergelm_threads_handles = NULL; +static LPHANDLE mergelm_ready_events = NULL; +static LP_MERGELM_PARAMS mergelm_params = NULL; + +DWORD WINAPI MergeThreadProc( LPVOID lpParameter ) +{ + LP_MERGELM_PARAMS pParams = ( LP_MERGELM_PARAMS ) lpParameter; + + while( TRUE ) { + // Wait for "start" and "terminate" events + switch ( WaitForMultipleObjects( 2 , pParams->hEvents , FALSE , INFINITE ) ) { + case WAIT_OBJECT_0 + 0 : + MergeLM_process( pParams->m_from , pParams->m_to , pParams->Layer , +pParams->lmap ); + // Signal "ready" event + SetEvent( pParams->hEvents[ 2 ] ); + break; + case WAIT_OBJECT_0 + 1 : + ExitThread( 0 ); + break; + default : + // Error ? + ExitThread( 1 ); + break; + } // switch + } // while + + return 0; +} + + +void InitMergeThreads() +{ + if ( mergelm_threads_initialized ) + return; + + + SYSTEM_INFO SystemInfo; + GetSystemInfo( &SystemInfo ); + mergelm_threads_count = SystemInfo.dwNumberOfProcessors; + + mergelm_threads_handles = (LPHANDLE) xr_malloc( mergelm_threads_count * sizeof( HANDLE ) ); + mergelm_ready_events = (LPHANDLE) xr_malloc( mergelm_threads_count * sizeof( HANDLE ) ); + mergelm_params = (LP_MERGELM_PARAMS) xr_malloc( mergelm_threads_count * sizeof( +MERGELM_PARAMS ) ); + + InitializeCriticalSection( &mergelm_cs ); + + for ( u32 i = 0 ; i < mergelm_threads_count ; i++ ) { + + ZeroMemory( &mergelm_params[ i ] , sizeof( MERGELM_PARAMS ) ); + + // Creating start,terminate,ready events for each thread + for( u32 x = 0 ; x < 3 ; x++ ) + mergelm_params[ i ].hEvents[ x ] = CreateEvent( NULL , FALSE , FALSE , NULL +); + + // Duplicate ready event into array + mergelm_ready_events[ i ] = mergelm_params[ i ].hEvents[ 2 ]; + + mergelm_threads_handles[ i ] = CreateThread( NULL , 0 , &MergeThreadProc , +&mergelm_params[ i ] , 0 , NULL ); + } + + mergelm_threads_initialized = TRUE; +} + +void DoneMergeThreads() +{ + if ( ! mergelm_threads_initialized ) + return; + + // Asking helper threads to terminate + for ( u32 i = 0 ; i < mergelm_threads_count ; i++ ) + SetEvent( mergelm_params[ i ].hEvents[ 1 ] ); + + // Waiting threads for completion + WaitForMultipleObjects( mergelm_threads_count , mergelm_threads_handles , TRUE , INFINITE ); + + // Deleting events + for ( u32 i = 0 ; i < mergelm_threads_count ; i++ ) + for( u32 x = 0 ; x < 3 ; x++ ) + CloseHandle( mergelm_params[ i ].hEvents[ x ] ); + + // Freeing resources + DeleteCriticalSection( &mergelm_cs ); + + xr_free( mergelm_threads_handles ); mergelm_threads_handles = NULL; + xr_free( mergelm_ready_events ); mergelm_ready_events = NULL; + xr_free( mergelm_params ); mergelm_params = NULL; + + mergelm_threads_count = 0; + + mergelm_threads_initialized = FALSE; +} + + +void MergeLM_process_threads( u32 m_count , vecDefl* pLayer , CLightmap* lmap ) +{ + u32 m_range = m_count / mergelm_threads_count; + + for ( u32 i = 0 ; i < mergelm_threads_count ; i++ ) { + mergelm_params[ i ].Layer = pLayer; + mergelm_params[ i ].lmap = lmap; + + + mergelm_params[ i ].m_from = i * m_range; + mergelm_params[ i ].m_to = ( i == ( mergelm_threads_count - 1 ) ) ? m_count : +mergelm_params[ i ].m_from + m_range; + + SetEvent( mergelm_params[ i ].hEvents[ 0 ] ); + } // for + + WaitForMultipleObjects( mergelm_threads_count , mergelm_ready_events , TRUE , INFINITE ); +} + + +void MergeLM_process( u32 m_from , u32 m_to , vecDefl* pLayer , CLightmap* lmap ) +{ + for ( u32 it = m_from ; it < m_to ; it++ ) { + lm_layer& L = (*pLayer)[ it ]->layer; + L_rect rT , rS; + rS.a.set( 0 , 0 ); + rS.b.set( L.width + 2*BORDER - 1 , L.height + 2*BORDER - 1 ); + rS.iArea = L.Area(); + rT = rS; + if ( _rect_place( rT , &L ) ) { + BOOL bRotated; + if ( rT.SizeX() == rS.SizeX() ) { + R_ASSERT(rT.SizeY() == rS.SizeY()); + bRotated = FALSE; + } else { + R_ASSERT(rT.SizeX() == rS.SizeY()); + R_ASSERT(rT.SizeY() == rS.SizeX()); + bRotated = TRUE; + } + + EnterCriticalSection( &mergelm_cs ); + lmap->Capture( (*pLayer)[ it ] , rT.a.x , rT.a.y , rT.SizeX() , +rT.SizeY() , bRotated ); LeaveCriticalSection( &mergelm_cs ); + + (*pLayer)[it]->bMerged = TRUE; + } // if + } // for +} + +void CBuild::xrPhase_MergeLM() +{ + vecDefl Layer; + + // Initialize helper threads + InitMergeThreads(); + + // **** Select all deflectors, which contain this light-layer + Layer.clear (); + for (u32 it=0; itg_deflectors().size(); it++) + { + CDeflector* D = lc_global_data()->g_deflectors()[it]; + if (D->bMerged) continue; + Layer.push_back (D); + } + + // Merge this layer (which left unmerged) + while (Layer.size()) + { + VERIFY( lc_global_data() ); + string512 phase_name; + xr_sprintf (phase_name,"Building lightmap %d...", +lc_global_data()->lightmaps().size()); Phase (phase_name); + + // Sort layer by similarity (state changes) + // + calc material area + Status ("Selection..."); + for (u32 it=0; itGetBaseMaterial()].internal_max_area = +_max(D->layer.Area(),materials()[D->GetBaseMaterial()].internal_max_area); + } + std::stable_sort(Layer.begin(),Layer.end(),sort_defl_complex); + + // Select first deflectors which can fit + Status ("Selection..."); + u32 maxarea = c_LMAP_size*c_LMAP_size*8; // Max up to 8 lm selected + u32 curarea = 0; + u32 merge_count = 0; + for (u32 it=0; it<(int)Layer.size(); it++) { + int defl_area = Layer[it]->layer.Area(); + if (curarea + defl_area > maxarea) break; + curarea += defl_area; + merge_count ++; + } + + // Startup + Status ("Processing..."); + _InitSurface (); + CLightmap* lmap = xr_new (); + VERIFY( lc_global_data() ); + lc_global_data()->lightmaps().push_back (lmap); + + // Process + MergeLM_process_threads( merge_count , &Layer , lmap ); + + Progress (1.f); + + // Remove merged lightmaps + Status ("Cleanup..."); + vecDeflIt last = std::remove_if (Layer.begin(),Layer.end(),pred_remove()); + Layer.erase (last,Layer.end()); + + // Save + Status ("Saving..."); + VERIFY ( pBuild ); + lmap->Save (pBuild->path); + } + VERIFY( lc_global_data() ); + clMsg ( "%d lightmaps builded", lc_global_data()->lightmaps().size() ); + + // Cleanup deflectors + Progress (1.f); + Status ("Destroying deflectors..."); + for (u32 it=0; itg_deflectors().size(); it++) + xr_delete(lc_global_data()->g_deflectors()[it]); + lc_global_data()->g_deflectors().clear(); + + // Destroy helper threads + DoneMergeThreads(); +} +*/ diff --git a/pool/shard001/C++/0018155_json-parse.cpp b/pool/shard001/C++/0018155_json-parse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57aab785e351dd9c4619f277d7d7b351a454288a --- /dev/null +++ b/pool/shard001/C++/0018155_json-parse.cpp @@ -0,0 +1,34 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License + ********************************************************************/ + +#include + +NAN_METHOD(Parse) { + Nan::JSON NanJSON; + + Nan::MaybeLocal inp = Nan::To(info[0]); + + if (!inp.IsEmpty()) { + Nan::MaybeLocal result = NanJSON.Parse( + inp.ToLocalChecked() + ); + + if (!result.IsEmpty()) { + info.GetReturnValue().Set(result.ToLocalChecked()); + } + } +} + +NAN_MODULE_INIT(Init) { + Nan::Set(target + , Nan::New("parse").ToLocalChecked() + , Nan::New(Parse)->GetFunction() + ); +} + +NODE_MODULE(parse, Init) diff --git a/pool/shard001/C++/0018157_stats_tree_dialog.cpp b/pool/shard001/C++/0018157_stats_tree_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83fe65245e2f591539faf345e17dffbdf8e5c587 --- /dev/null +++ b/pool/shard001/C++/0018157_stats_tree_dialog.cpp @@ -0,0 +1,233 @@ +/* stats_tree_dialog.cpp + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * 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 "stats_tree_dialog.h" + +#include "file.h" + +#include "epan/stats_tree_priv.h" + +#include "qt_ui_utils.h" + +#include +#include +#include +#include + +const int item_col_ = 0; + +Q_DECLARE_METATYPE(stat_node *) + +const int sn_type_ = 1000; +class StatsTreeWidgetItem : public QTreeWidgetItem +{ +public: + StatsTreeWidgetItem(int type = sn_type_) : QTreeWidgetItem (type) + { + for (int col = 1; col < columnCount(); col++) { + setTextAlignment(col, Qt::AlignRight); + } + } + bool operator< (const QTreeWidgetItem &other) const + { + stat_node *thisnode = data(item_col_, Qt::UserRole).value(); + stat_node *othernode = other.data(item_col_, Qt::UserRole).value(); + Qt::SortOrder order = treeWidget()->header()->sortIndicatorOrder(); + int result; + + result = stats_tree_sort_compare(thisnode, othernode, treeWidget()->sortColumn(), + order==Qt::DescendingOrder); + if (order==Qt::DescendingOrder) { + result = -result; + } + return result < 0; + } +}; + +StatsTreeDialog::StatsTreeDialog(QWidget &parent, CaptureFile &cf, const char *cfg_abbr) : + TapParameterDialog(parent, cf), + st_(NULL), + st_cfg_(NULL) +{ + st_cfg_ = stats_tree_get_cfg_by_abbr(cfg_abbr); + memset(&cfg_pr_, 0, sizeof(struct _tree_cfg_pres)); + + if (!st_cfg_) { + QMessageBox::critical(this, tr("Configuration not found"), + tr("Unable to find configuration for %1.").arg(cfg_abbr)); + QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); + } +} + +StatsTreeDialog::~StatsTreeDialog() +{ + if (st_) { + stats_tree_free(st_); + } +} + +// Adds a node to the QTreeWidget +// Note: We're passing QTreeWidgetItem pointers as st_node_pres pointers +void StatsTreeDialog::setupNode(stat_node* node) +{ + if (!node || !node->st || !node->st->cfg || !node->st->cfg->pr + || !node->st->cfg->pr->st_dlg) return; + StatsTreeDialog *st_dlg = node->st->cfg->pr->st_dlg; + + QTreeWidgetItem *ti = new StatsTreeWidgetItem(), *parent = NULL; + + ti->setText(item_col_, node->name); + ti->setData(item_col_, Qt::UserRole, qVariantFromValue(node)); + node->pr = (st_node_pres *) ti; + if (node->parent && node->parent->pr) { + parent = (QTreeWidgetItem *) node->parent->pr; + parent->setExpanded(true); + } + if (parent) { + parent->addChild(ti); + } else { + st_dlg->statsTreeWidget()->addTopLevelItem(ti); + } + st_dlg->statsTreeWidget()->resizeColumnToContents(item_col_); +} + +void StatsTreeDialog::fillTree() +{ + GString *error_string; + if (!st_cfg_ || file_closed_) return; + + QString display_name = gchar_free_to_qstring(stats_tree_get_displayname(st_cfg_->name)); + + // The GTK+ UI appends "Stats Tree" to the window title. If we do the same + // here we should expand the name completely, e.g. to "Statistics Tree". + setWindowSubtitle(display_name); + + st_cfg_->pr = &cfg_pr_; + cfg_pr_.st_dlg = this; + + if (st_) { + stats_tree_free(st_); + } + QString display_filter = displayFilter(); + st_ = stats_tree_new(st_cfg_, NULL, display_filter.toUtf8().constData()); + + // Add number of columns for this stats_tree + QStringList header_labels; + for (int count = 0; countnum_columns; count++) { + header_labels.push_back(stats_tree_get_column_name(count)); + } + statsTreeWidget()->setColumnCount(header_labels.count()); + statsTreeWidget()->setHeaderLabels(header_labels); + resize(st_->num_columns*80+80, height()); + statsTreeWidget()->setSortingEnabled(false); + + error_string = register_tap_listener(st_cfg_->tapname, + st_, + st_->filter, + st_cfg_->flags, + resetTap, + stats_tree_packet, + drawTreeItems); + if (error_string) { + QMessageBox::critical(this, tr("%1 failed to attach to tap").arg(display_name), + error_string->str); + g_string_free(error_string, TRUE); + reject(); + } + + cf_retap_packets(cap_file_.capFile()); + drawTreeItems(st_); + + statsTreeWidget()->setSortingEnabled(true); + remove_tap_listener(st_); + + st_cfg_->pr = NULL; +} + +void StatsTreeDialog::resetTap(void *st_ptr) +{ + stats_tree *st = (stats_tree *) st_ptr; + if (!st || !st->cfg || !st->cfg->pr || !st->cfg->pr->st_dlg) return; + + st->cfg->pr->st_dlg->statsTreeWidget()->clear(); + st->cfg->init(st); +} + +void StatsTreeDialog::drawTreeItems(void *st_ptr) +{ + stats_tree *st = (stats_tree *) st_ptr; + if (!st || !st->cfg || !st->cfg->pr || !st->cfg->pr->st_dlg) return; + TapParameterDialog *st_dlg = st->cfg->pr->st_dlg; + QTreeWidgetItemIterator iter(st_dlg->statsTreeWidget()); + int node_count = 0; + + while (*iter) { + stat_node *node = (*iter)->data(item_col_, Qt::UserRole).value(); + if (node) { + gchar **valstrs = stats_tree_get_values_from_node(node); + for (int count = 0; countnum_columns; count++) { + (*iter)->setText(count,valstrs[count]); + g_free(valstrs[count]); + } + (*iter)->setExpanded( (node->parent==(&st->root)) && + (!(node->st_flags&ST_FLG_DEF_NOEXPAND)) ); + g_free(valstrs); + } + node_count++; + ++iter; + } + + st_dlg->drawTreeItems(); +} + +QByteArray StatsTreeDialog::getTreeAsString(st_format_type format) +{ + GString *str_tree; + + // produce output in selected format using current sort information + str_tree = stats_tree_format_as_str(st_, format, statsTreeWidget()->sortColumn(), + statsTreeWidget()->header()->sortIndicatorOrder()==Qt::DescendingOrder); + + return gstring_free_to_qbytearray(str_tree); +} + +extern "C" { +void +register_tap_listener_qt_stats_tree_stat(void) +{ + stats_tree_presentation(NULL, + StatsTreeDialog::setupNode, + NULL, NULL); +} +} + +/* + * Editor modelines + * + * Local Variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard001/C++/0018158_airtank.cpp b/pool/shard001/C++/0018158_airtank.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d0dda22226778448c1d12862dc8209298311afe --- /dev/null +++ b/pool/shard001/C++/0018158_airtank.cpp @@ -0,0 +1,85 @@ +#include "precompiled.h" + +/* +* Globals initialization +*/ +#ifndef HOOK_GAMEDLL + +TYPEDESCRIPTION CAirtank::m_SaveData[] = +{ + DEFINE_FIELD(CAirtank, m_state, FIELD_INTEGER) +}; + +#endif + +LINK_ENTITY_TO_CLASS(item_airtank, CAirtank, CCSAirtank) +IMPLEMENT_SAVERESTORE(CAirtank, CGrenade) + +void CAirtank::__MAKE_VHOOK(Spawn)() +{ + Precache(); + + // motor + pev->movetype = MOVETYPE_FLY; + pev->solid = SOLID_BBOX; + + SET_MODEL(ENT(pev), "models/w_oxygen.mdl"); + UTIL_SetSize(pev, Vector(-16, -16, 0), Vector(16, 16, 36)); + UTIL_SetOrigin(pev, pev->origin); + + SetTouch(&CAirtank::TankTouch); + SetThink(&CAirtank::TankThink); + + pev->flags |= FL_MONSTER; + pev->takedamage = DAMAGE_YES; + pev->health = 20; + pev->dmg = 50; + m_state = 1; +} + +void CAirtank::__MAKE_VHOOK(Precache)() +{ + PRECACHE_MODEL("models/w_oxygen.mdl"); + PRECACHE_SOUND("doors/aliendoor3.wav"); +} + +void CAirtank::__MAKE_VHOOK(Killed)(entvars_t *pevAttacker, int iGib) +{ + pev->owner = ENT(pevAttacker); + + // UNDONE: this should make a big bubble cloud, not an explosion + Explode(pev->origin, Vector(0, 0, -1)); +} + +void CAirtank::TankThink() +{ + // Fire trigger + m_state = 1; + SUB_UseTargets(this, USE_TOGGLE, 0); +} + +void CAirtank::TankTouch(CBaseEntity *pOther) +{ + if (!pOther->IsPlayer()) + { + return; + } + + if (!m_state) + { + // "no oxygen" sound + EMIT_SOUND(ENT(pev), CHAN_BODY, "player/pl_swim2.wav", VOL_NORM, ATTN_NORM); + return; + } + + // give player 12 more seconds of air + pOther->pev->air_finished = gpGlobals->time + 12.0f; + + // suit recharge sound + EMIT_SOUND(ENT(pev), CHAN_VOICE, "doors/aliendoor3.wav", VOL_NORM, ATTN_NORM); + + // recharge airtank in 30 seconds + pev->nextthink = gpGlobals->time + 30.0f; + m_state = 0; + SUB_UseTargets(this, USE_TOGGLE, 1); +} diff --git a/pool/shard001/C++/0018159_CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62a.cpp b/pool/shard001/C++/0018159_CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..313a2d3e2943fd1aca9e9e66c50bd70c679237af --- /dev/null +++ b/pool/shard001/C++/0018159_CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62a.cpp @@ -0,0 +1,126 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62a.cpp +Label Definition File: CWE134_Uncontrolled_Format_String.label.xml +Template File: sources-sinks-62a.tmpl.cpp +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Copy a fixed string into data + * Sinks: snprintf + * GoodSink: snwprintf with "%s" as the third argument and data as the fourth + * BadSink : snwprintf with data as the third argument + * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifdef _WIN32 +#define SNPRINTF _snwprintf +#else +#define SNPRINTF snprintf +#endif + +namespace CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSource(wchar_t * &data); + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + badSource(data); + { + wchar_t dest[100] = L""; + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + SNPRINTF(dest, 100-1, data); + printWLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSource(wchar_t * &data); + +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + goodG2BSource(data); + { + wchar_t dest[100] = L""; + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + SNPRINTF(dest, 100-1, data); + printWLine(dest); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSource(wchar_t * &data); + +static void goodB2G() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + goodB2GSource(data); + { + wchar_t dest[100] = L""; + /* FIX: Specify the format disallowing a format string vulnerability */ + SNPRINTF(dest, 100-1, L"%s", data); + printWLine(dest); + } +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#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 CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_snprintf_62; /* 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/shard001/C++/0018161_Sprite.cpp b/pool/shard001/C++/0018161_Sprite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f0b7112c4273624d2aac2863eaf69e1097fa1a8 --- /dev/null +++ b/pool/shard001/C++/0018161_Sprite.cpp @@ -0,0 +1,163 @@ +/*================================================================================================= + Glance Engine - (C) 2010-2013 Daniel L. Watkins + + Filename: Sprite.cpp +=================================================================================================*/ +#include "Render2D.h" + +namespace ge +{ + /*============================================================================= + -- Constructor for Sprite. + =============================================================================*/ + Sprite::Sprite() + { + mIsSheet = false; + mFrame = 0; + mColumns = 1; + mFrameWidth = 0; + mFrameHeight = 0; + mWindow = NULL; + } + + + /*============================================================================= + -- Calculates the clipping region to draw only part of a sprite sheet. If this + is not currently a sprite sheet, then the clipping region is set to the + entire image. + =============================================================================*/ + void Sprite::_RecalculateClipping() + { + if (mIsSheet) + { + mClipping.Left = (mFrame % mColumns) * mFrameWidth; + mClipping.Top = (mFrame / mColumns) * mFrameHeight; + mClipping.Right = mClipping.Left + mFrameWidth; + mClipping.Bottom = mClipping.Top + mFrameHeight; + + mSprite.SetSubRect(mClipping); + } + else + { + sf::IntRect defaultSubRect; + defaultSubRect.Left = 0; + defaultSubRect.Top = 0; + defaultSubRect.Right = mSprite.GetImage()->GetWidth(); + defaultSubRect.Bottom = mSprite.GetImage()->GetHeight(); + + mSprite.SetSubRect(defaultSubRect); + } + } + + + /*============================================================================= + -- Sets the render window pointer and the image the sprite uses. + =============================================================================*/ + bool Sprite::Init(Window *window, sf::Image *image) + { + mWindow = window; + + if (image) + { + mSprite.SetImage(*image); + _RecalculateClipping(); + } + + return (mSprite.GetImage() != NULL); + } + + + /*============================================================================= + -- Loads the image from a specific file. + =============================================================================*/ + bool Sprite::LoadImageFromFile(String filepath) + { + io::Standardize(filepath); + + if (!mImage.LoadFromFile(filepath.GetStd())) + return false; + + mImage.SetSmooth(false); + mSprite.SetImage(mImage); + + //SetFrameWidth(mImage.GetWidth()); + //SetFrameHeight(mImage.GetHeight()); + + return true; + } + + + /*============================================================================= + -- Draws the sprite with offset @x,@y using all of the current states. + =============================================================================*/ + void Sprite::Draw(int x, int y) + { + float nx = mSprite.GetPosition().x + (float)x; + float ny = mSprite.GetPosition().y + (float)y; + + mSprite.SetPosition(nx, ny); + Draw(); + mSprite.SetPosition(nx - (float)x, ny - (float)y); + } + + + /*============================================================================= + -- Slightly faster drawing method. It does not need to calculate offset + positions and then revert. + =============================================================================*/ + void Sprite::Draw() + { + if (mWindow != NULL) + mWindow->GetWindow()->Draw(mSprite); + } + + + /*============================================================================= + -- Sets the horizontal (x) scale factor to make the source image seem like it + is the specified width. + =============================================================================*/ + void Sprite::SetWidth(unsigned width) + { + if (mSprite.GetImage()) + SetScaleX( DivideF((float)width, (float)mSprite.GetImage()->GetWidth()) ); + } + + + /*============================================================================= + -- Returns the width of the image to be displayed. It takes into account + scale factors. If this is a sheet, then just the frame to be displayed is + used instead of the entire image. + =============================================================================*/ + unsigned Sprite::GetWidth() + { + if (mSprite.GetImage()) + return (unsigned)(GetScaleX() *mSprite.GetImage()->GetWidth()); + + return 0; + } + + + /*============================================================================= + -- Sets the vertical (y) scale factor to make the source image seem like it + is the specified width. + =============================================================================*/ + void Sprite::SetHeight(unsigned height) + { + if (mSprite.GetImage()) + SetScaleY( DivideF((float)height, (float)mSprite.GetImage()->GetHeight()) ); + } + + + /*============================================================================= + -- Returns the height of the image to be displayed. It takes into account + scale factors. If this is a sheet, then just the frame to be displayed is + used instead of the entire image. + =============================================================================*/ + unsigned Sprite::GetHeight() + { + if (mSprite.GetImage()) + return (unsigned)(GetScaleY() *mSprite.GetImage()->GetHeight()); + + return 0; + } +}; \ No newline at end of file diff --git a/pool/shard001/C++/0018166_date_provider_impl.cc b/pool/shard001/C++/0018166_date_provider_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..6f08a53258eea7ea967b7c42a921476dd75b1237 --- /dev/null +++ b/pool/shard001/C++/0018166_date_provider_impl.cc @@ -0,0 +1,37 @@ +#include "common/http/date_provider_impl.h" + +#include +#include + +namespace Envoy { +namespace Http { + +DateFormatter DateProviderImplBase::date_formatter_("%a, %d %b %Y %H:%M:%S GMT"); + +TlsCachingDateProviderImpl::TlsCachingDateProviderImpl(Event::Dispatcher& dispatcher, + ThreadLocal::SlotAllocator& tls) + : DateProviderImplBase(dispatcher.timeSource()), tls_(tls.allocateSlot()), + refresh_timer_(dispatcher.createTimer([this]() -> void { onRefreshDate(); })) { + + onRefreshDate(); +} + +void TlsCachingDateProviderImpl::onRefreshDate() { + std::string new_date_string = date_formatter_.now(time_source_); + tls_->set([new_date_string](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return std::make_shared(new_date_string); + }); + + refresh_timer_->enableTimer(std::chrono::milliseconds(500)); +} + +void TlsCachingDateProviderImpl::setDateHeader(ResponseHeaderMap& headers) { + headers.setDate(tls_->getTyped().date_string_); +} + +void SlowDateProviderImpl::setDateHeader(ResponseHeaderMap& headers) { + headers.setDate(date_formatter_.now(time_source_)); +} + +} // namespace Http +} // namespace Envoy diff --git a/pool/shard001/C++/0018169_blur.cpp b/pool/shard001/C++/0018169_blur.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3f272d485316ba7be6d66bdb25c68c7b0e23d59 --- /dev/null +++ b/pool/shard001/C++/0018169_blur.cpp @@ -0,0 +1,48 @@ +/** + * @file blur.cpp + * @brief mex interface for blur + * @author Kota Yamaguchi + * @date 2011 + */ +#include "mexopencv.hpp" +using namespace std; +using namespace cv; + +/** + * Main entry called from Matlab + * @param nlhs number of left-hand-side arguments + * @param plhs pointers to mxArrays in the left-hand-side + * @param nrhs number of right-hand-side arguments + * @param prhs pointers to mxArrays in the right-hand-side + */ +void mexFunction( int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[] ) +{ + // Check the number of arguments + if (nrhs<1 || ((nrhs%2)!=1) || nlhs>1) + mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); + + // Argument vector + vector rhs(prhs,prhs+nrhs); + + // Option processing + Size ksize(5,5); + Point anchor(-1,-1); + int borderType = BORDER_DEFAULT; + for (int i=1; iCheck(); +} + +OwnershipStatusChecker::~OwnershipStatusChecker() { + core_->Cancel(); +} + +OwnershipStatusChecker::Core::Core(Callback* callback) + : callback_(callback), + origin_loop_(base::MessageLoopProxy::CreateForCurrentThread()) {} + +void OwnershipStatusChecker::Core::Check() { + DCHECK(origin_loop_->BelongsToCurrentThread()); + OwnershipService::Status status = + OwnershipService::GetSharedInstance()->GetStatus(false); + if (status != OwnershipService::OWNERSHIP_UNKNOWN) { + // Take a spin on the message loop in order to avoid reentrancy in callers. + origin_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, + &OwnershipStatusChecker::Core::ReportResult, + status)); + } else { + // Switch to the file thread to make the blocking call. + BrowserThread::PostTask( + BrowserThread::FILE, FROM_HERE, + NewRunnableMethod(this, + &OwnershipStatusChecker::Core::CheckOnFileThread)); + } +} + +void OwnershipStatusChecker::Core::Cancel() { + DCHECK(origin_loop_->BelongsToCurrentThread()); + callback_.reset(); +} + +void OwnershipStatusChecker::Core::CheckOnFileThread() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); + OwnershipService::Status status = + OwnershipService::GetSharedInstance()->GetStatus(true); + origin_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, + &OwnershipStatusChecker::Core::ReportResult, + status)); +} + +void OwnershipStatusChecker::Core::ReportResult( + OwnershipService::Status status) { + DCHECK(origin_loop_->BelongsToCurrentThread()); + if (callback_.get()) { + callback_->Run(status); + callback_.reset(); + } +} + +} // namespace chromeos diff --git a/pool/shard001/C++/0018186_out_of_memory_reporter_unittest.cc b/pool/shard001/C++/0018186_out_of_memory_reporter_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..b5a0f0ebc10c44905484bbe21f129f255f78829b --- /dev/null +++ b/pool/shard001/C++/0018186_out_of_memory_reporter_unittest.cc @@ -0,0 +1,277 @@ +// 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 "chrome/browser/metrics/oom/out_of_memory_reporter.h" + +#include +#include +#include + +#include "base/at_exit.h" +#include "base/bind.h" +#include "base/callback.h" +#include "base/files/file_util.h" +#include "base/files/scoped_file.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/optional.h" +#include "base/path_service.h" +#include "base/process/kill.h" +#include "base/run_loop.h" +#include "base/task/post_task.h" +#include "base/test/simple_test_tick_clock.h" +#include "build/build_config.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/ukm/content/source_url_recorder.h" +#include "components/ukm/test_ukm_recorder.h" +#include "content/public/browser/navigation_handle.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/test/mock_render_process_host.h" +#include "content/public/test/navigation_simulator.h" +#include "content/public/test/test_renderer_host.h" +#include "content/public/test/test_utils.h" +#include "net/base/net_errors.h" +#include "services/metrics/public/cpp/ukm_builders.h" +#include "services/metrics/public/cpp/ukm_source.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +#if defined(OS_ANDROID) +#include "chrome/common/chrome_descriptors.h" +#include "components/crash/content/browser/child_exit_observer_android.h" +#include "components/crash/content/browser/child_process_crash_observer_android.h" +#endif + +#if defined(OS_ANDROID) +// This class listens for notifications that crash dumps have been processed. +// Notifications will come from all crashes, even if an associated crash dump +// was not created. +class CrashDumpWaiter : public crash_reporter::CrashMetricsReporter::Observer { + public: + CrashDumpWaiter() { + crash_reporter::CrashMetricsReporter::GetInstance()->AddObserver(this); + } + ~CrashDumpWaiter() { + crash_reporter::CrashMetricsReporter::GetInstance()->RemoveObserver(this); + } + + // Waits for the crash dump notification and returns whether the crash was + // considered a foreground oom. + const crash_reporter::CrashMetricsReporter::ReportedCrashTypeSet& Wait() { + waiter_.Run(); + return reported_counts_; + } + + private: + // CrashDumpManager::Observer: + void OnCrashDumpProcessed( + int rph_id, + const crash_reporter::CrashMetricsReporter::ReportedCrashTypeSet& + reported_counts) override { + reported_counts_ = reported_counts; + waiter_.Quit(); + } + + base::RunLoop waiter_; + crash_reporter::CrashMetricsReporter::ReportedCrashTypeSet reported_counts_; + DISALLOW_COPY_AND_ASSIGN(CrashDumpWaiter); +}; +#endif // defined(OS_ANDROID) + +class OutOfMemoryReporterTest : public ChromeRenderViewHostTestHarness, + public OutOfMemoryReporter::Observer { + public: + OutOfMemoryReporterTest() {} + ~OutOfMemoryReporterTest() override {} + + // ChromeRenderViewHostTestHarness: + void SetUp() override { +#if defined(OS_ANDROID) + crash_reporter::ChildExitObserver::Create(); + crash_reporter::ChildExitObserver::GetInstance()->RegisterClient( + std::make_unique()); +#endif + + ChromeRenderViewHostTestHarness::SetUp(); + EXPECT_NE(content::ChildProcessHost::kInvalidUniqueID, process()->GetID()); + + OutOfMemoryReporter::CreateForWebContents(web_contents()); + OutOfMemoryReporter* reporter = + OutOfMemoryReporter::FromWebContents(web_contents()); + reporter->AddObserver(this); + auto tick_clock = std::make_unique(); + test_tick_clock_ = tick_clock.get(); + reporter->SetTickClockForTest(std::move(tick_clock)); + // Ensure clock is set to something that's not 0 to begin. + test_tick_clock_->Advance(base::TimeDelta::FromSeconds(1)); + + test_ukm_recorder_ = std::make_unique(); + ukm::InitializeSourceUrlRecorderForWebContents(web_contents()); + } + + // OutOfMemoryReporter::Observer: + void OnForegroundOOMDetected(const GURL& url, + ukm::SourceId source_id) override { + last_oom_url_ = url; + } + + void SimulateRendererCreated() { +#if defined(OS_ANDROID) + content::RenderProcessHostCreationObserver* creation_observer = + crash_reporter::ChildExitObserver::GetInstance(); + creation_observer->OnRenderProcessHostCreated(process()); +#endif + content::NotificationService::current()->Notify( + content::NOTIFICATION_RENDERER_PROCESS_CREATED, + content::Source(process()), + content::NotificationService::NoDetails()); + } + + void SimulateOOM() { + test_tick_clock_->Advance(base::TimeDelta::FromSeconds(3)); + SimulateRendererCreated(); +#if defined(OS_ANDROID) + process()->SimulateRenderProcessExit(base::TERMINATION_STATUS_OOM_PROTECTED, + 0); +#elif defined(OS_CHROMEOS) + process()->SimulateRenderProcessExit( + base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM, 0); +#else + process()->SimulateRenderProcessExit(base::TERMINATION_STATUS_OOM, 0); +#endif + } + + // Runs a closure which should simulate some sort of crash, and waits until + // the OutOfMemoryReporter *should* have received a notification for it. + void RunCrashClosureAndWait(base::OnceClosure crash_closure, + bool oom_expected) { +#if defined(OS_ANDROID) + CrashDumpWaiter crash_waiter; + std::move(crash_closure).Run(); + const auto& reported_counts = crash_waiter.Wait(); + EXPECT_EQ(oom_expected ? 1u : 0u, + reported_counts.count( + crash_reporter::CrashMetricsReporter::ProcessedCrashCounts:: + kRendererForegroundVisibleOom)); + + // Since the observer list is not ordered, it isn't guaranteed that the + // OutOfMemoryReporter will be notified at this point. Flush the current + // message loop and task scheduler of tasks. + content::RunAllTasksUntilIdle(); +#else + // No need to wait on non-android platforms. The message will be + // synchronous. + std::move(crash_closure).Run(); +#endif + } + + void SimulateOOMAndWait() { + RunCrashClosureAndWait(base::BindOnce(&OutOfMemoryReporterTest::SimulateOOM, + base::Unretained(this)), + true); + } + + void CheckUkmMetricRecorded(const GURL& url, int64_t time_delta) { + const auto& entries = test_ukm_recorder_->GetEntriesByName( + ukm::builders::Tab_RendererOOM::kEntryName); + EXPECT_EQ(1u, entries.size()); + for (const auto* entry : entries) { + test_ukm_recorder_->ExpectEntrySourceHasUrl(entry, url); + test_ukm_recorder_->ExpectEntryMetric( + entry, ukm::builders::Tab_RendererOOM::kTimeSinceLastNavigationName, + time_delta); + } + } + + protected: + base::ShadowingAtExitManager at_exit_; + + base::Optional last_oom_url_; + std::unique_ptr test_ukm_recorder_; + + private: + base::SimpleTestTickClock* test_tick_clock_; + + DISALLOW_COPY_AND_ASSIGN(OutOfMemoryReporterTest); +}; + +TEST_F(OutOfMemoryReporterTest, SimpleOOM) { + const GURL url("https://example.test/"); + NavigateAndCommit(url); + + SimulateOOMAndWait(); + EXPECT_TRUE(last_oom_url_.has_value()); + EXPECT_EQ(url, last_oom_url_.value()); + CheckUkmMetricRecorded(url, 3000); +} + +TEST_F(OutOfMemoryReporterTest, NormalCrash_NoOOM) { + const GURL url("https://example.test/"); + NavigateAndCommit(url); + SimulateRendererCreated(); +#if defined(OS_ANDROID) + crash_reporter::ChildExitObserver::GetInstance()->ChildReceivedCrashSignal( + process()->GetProcess().Handle(), SIGSEGV); +#endif + RunCrashClosureAndWait( + base::BindOnce(&content::MockRenderProcessHost::SimulateRenderProcessExit, + base::Unretained(process()), + base::TERMINATION_STATUS_PROCESS_WAS_KILLED, 0), + false); + EXPECT_FALSE(last_oom_url_.has_value()); + const auto& entries = test_ukm_recorder_->GetEntriesByName( + ukm::builders::Tab_RendererOOM::kEntryName); + EXPECT_EQ(0u, entries.size()); +} + +TEST_F(OutOfMemoryReporterTest, SubframeNavigation_IsNotLogged) { + const GURL url("https://example.test/"); + NavigateAndCommit(url); + + // Navigate a subframe, make sure it isn't the navigation that is logged. + const GURL subframe_url("https://subframe.test/"); + auto* subframe = + content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); + subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( + subframe_url, subframe); + EXPECT_TRUE(subframe); + + SimulateOOMAndWait(); + EXPECT_TRUE(last_oom_url_.has_value()); + EXPECT_EQ(url, last_oom_url_.value()); + CheckUkmMetricRecorded(url, 3000); +} + +TEST_F(OutOfMemoryReporterTest, OOMOnPreviousPage) { + const GURL url1("https://example.test1/"); + const GURL url2("https://example.test2/"); + const GURL url3("https://example.test2/"); + NavigateAndCommit(url1); + NavigateAndCommit(url2); + + // Should not commit. + content::NavigationSimulator::NavigateAndFailFromBrowser(web_contents(), url3, + net::ERR_ABORTED); + SimulateOOMAndWait(); + EXPECT_TRUE(last_oom_url_.has_value()); + EXPECT_EQ(url2, last_oom_url_.value()); + CheckUkmMetricRecorded(url2, 3000); + + last_oom_url_.reset(); + NavigateAndCommit(url1); + + // Should navigate to an error page. + content::NavigationSimulator::NavigateAndFailFromBrowser( + web_contents(), url3, net::ERR_CONNECTION_RESET); + // Don't report OOMs on error pages. + SimulateOOMAndWait(); + EXPECT_FALSE(last_oom_url_.has_value()); + // Only the first OOM is recorded. + CheckUkmMetricRecorded(url2, 3000); +} diff --git a/pool/shard001/C++/0018191_clumpFinding.cpp b/pool/shard001/C++/0018191_clumpFinding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5a2563b08d3da60290d96aad0c2ad66e2e38b85 --- /dev/null +++ b/pool/shard001/C++/0018191_clumpFinding.cpp @@ -0,0 +1,85 @@ +// +// ClumpFinding.cpp +// +// +// Created by Shenmo Lu on 1/11/17. +// +// + +#include +#include +#include +#include +#include +#include "functions.hpp" + +using namespace std; + +// Frequency Array approach +vector clumpFinding(string genome, int k, int L, int t) { + vector freqArray; + freqArray = computingFrequencies(genome.substr(0, L), k); + + for (int i = 0; i <= genome.size() - L; i++) { + + + + } + +} +/* +vector clumpFinding(string genome, int k, int l, int t) { + string kmer; + int index; + vector pos; + vector frequentPatterns; + + for (int i = 0; i <= genome.size() - k; i++) { + kmer = genome.substr(i, k); + index = patternToNumber(kmer); + pos = patternMatching(genome, kmer); + if (pos.size() >= t) { + for (int j = 0; j <= pos.size() - t; j++) { + if (pos[j+t-1] + k - pos[j] <= l) { + if(find(frequentPatterns.begin(), frequentPatterns.end(), kmer) == frequentPatterns.end()) { + frequentPatterns.push_back(kmer); + } + break; + } + } + } + } + + return frequentPatterns; +}*/ + +/* +//A time-saving but memory-consuming version of the function +vector clumpFinding(string genome, int k, int l, int t) { + string kmer; + int index; + vector pos; + vector frequentPatterns; + int size = (int)pow(4, k); + int clump[size]; + fill(clump, clump+size, 0); + for (int i = 0; i <= genome.size() - k; i++) { + kmer = genome.substr(i, k); + index = patternToNumber(kmer); + if (clump[index] == 0) { + pos = patternMatching(genome, kmer); + if (pos.size() >= t) { + for (int j = 0; j <= pos.size() - t; j++) { + if (pos[j+t-1] - pos[j] <= l - k) { + clump[index] = 1; + frequentPatterns.push_back(kmer); + break; + } + } + } + } + } + + return frequentPatterns; +} +*/ \ No newline at end of file diff --git a/pool/shard001/C++/0018193_importer_test_legacy_reshape.cc b/pool/shard001/C++/0018193_importer_test_legacy_reshape.cc new file mode 100644 index 0000000000000000000000000000000000000000..3d4f440efe602137bd829bb457dca0eb31502174 --- /dev/null +++ b/pool/shard001/C++/0018193_importer_test_legacy_reshape.cc @@ -0,0 +1,143 @@ +/* Copyright 2019 The TensorFlow Authors. 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. +==============================================================================*/ + +#include +#include + +#include "absl/strings/string_view.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/InitLLVM.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/PrettyStackTrace.h" +#include "llvm/Support/raw_ostream.h" +#include "tensorflow/lite/model.h" +#include "tensorflow/lite/schema/schema_generated.h" + +using llvm::Optional; +using llvm::cl::opt; + +// RUN: flatbuffer_translate -mlir-to-tflite-flatbuffer %p/reshape.mlir -o - \ +// RUN: | %p/importer_test_legacy_reshape - \ +// RUN: | flatbuffer_translate --tflite-flatbuffer-to-mlir - -o - \ +// RUN: | FileCheck %s + +// RUN: flatbuffer_translate -mlir-to-tflite-flatbuffer %p/reshape.mlir -o - \ +// RUN: | %p/importer_test_legacy_reshape - \ +// RUN: | flatbuffer_to_string - \ +// RUN: | FileCheck --check-prefix=FB %s + +// Tests for verifying the tflite model with single operand reshape can be +// imported correctly. + +// NOLINTNEXTLINE +static opt inputFileName(llvm::cl::Positional, + llvm::cl::desc(""), + llvm::cl::init("-")); + +namespace mlir { +namespace { +Optional> RemoveConstantOpInReshape( + llvm::StringRef buffer) { + auto model_ptr = tflite::FlatBufferModel::VerifyAndBuildFromBuffer( + buffer.data(), buffer.size()); + if (nullptr == model_ptr) { + return llvm::None; + } + std::unique_ptr model(model_ptr->GetModel()->UnPack()); + + // CHECK: %[[cst:.*]] = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32> + // CHECK: %{{.*}} = "tfl.reshape"(%{{.*}}, %[[cst]]) + + // FB: subgraphs: [ { + // FB-NEXT: tensors: [ { + // FB-NEXT: shape: [ 2 ], + // FB-NEXT: type: INT32, + // FB-NEXT: buffer: 1, + // FB-NEXT: name: "std.constant", + // FB-NEXT: quantization: { + // FB-EMPTY: + // FB-NEXT: } + // FB-NEXT: }, { + // FB-NEXT: shape: [ 4 ], + // FB-NEXT: buffer: 2, + // FB-NEXT: name: "Const", + // FB-NEXT: quantization: { + // FB-EMPTY: + // FB-NEXT: } + // FB-NEXT: }, { + // FB-NEXT: shape: [ 2, 2 ], + // FB-NEXT: buffer: 3, + // FB-NEXT: name: "reshape", + // FB-NEXT: quantization: { + // FB-EMPTY: + // FB-NEXT: } + // FB-NEXT: } ], + // FB-NEXT: outputs: [ 2 ], + // FB-NEXT: operators: [ { + // FB-NEXT: inputs: [ 1 ], + // FB-NEXT: outputs: [ 2 ] + // FB-NEXT: } ], + // FB-NEXT: name: "main" + // FB-NEXT: } ], + + // Find the reshape ops and make it single operand. + for (auto& sub_graph : model->subgraphs) { + for (auto& op : sub_graph->operators) { + if (model->operator_codes[op->opcode_index]->builtin_code == + tflite::BuiltinOperator_RESHAPE) { + auto& output_tensor = sub_graph->tensors[op->outputs[0]]; + auto shape = output_tensor->shape; + bool static_shape = true; + for (auto dim : shape) { + if (dim <= 0) static_shape = false; + } + // Remove the second operand + if (static_shape) { + op->inputs.resize(1); + } + } + } + } + return model; +} + +} // namespace +} // namespace mlir + +int main(int argc, char** argv) { + llvm::InitLLVM y(argc, argv); + llvm::cl::ParseCommandLineOptions(argc, argv); + auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(inputFileName.c_str()); + if (std::error_code error = file_or_err.getError()) { + llvm::errs() << argv[0] << ": could not open input file '" << inputFileName + << "': " << error.message() << "\n"; + return 1; + } + auto buffer = file_or_err->get(); + auto maybe_module = + mlir::RemoveConstantOpInReshape(buffer->getBuffer().str()); + if (!maybe_module.hasValue()) { + return 1; + } + flatbuffers::FlatBufferBuilder builder; + flatbuffers::Offset output_model_location = + tflite::Model::Pack(builder, maybe_module.getValue().get()); + tflite::FinishModelBuffer(builder, output_model_location); + std::string output_model_content( + reinterpret_cast(builder.GetBufferPointer()), + builder.GetSize()); + std::cout << output_model_content << "\n"; + return 0; +} diff --git a/pool/shard001/C++/0018196_qgsalgorithmdensifygeometriesbycount.cpp b/pool/shard001/C++/0018196_qgsalgorithmdensifygeometriesbycount.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d342ec8b4e2af214a63b1644ead7237b691e5151 --- /dev/null +++ b/pool/shard001/C++/0018196_qgsalgorithmdensifygeometriesbycount.cpp @@ -0,0 +1,128 @@ +/*************************************************************************** + qgsalgorithmdensifygeometries.cpp + --------------------- + begin : October 2019 + copyright : (C) 2019 by Clemens Raffler + email : clemens dot raffler at gmail dot 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 "qgsalgorithmdensifygeometriesbycount.h" + +///@cond PRIVATE + +QString QgsDensifyGeometriesByCountAlgorithm::name() const +{ + return QStringLiteral( "densifygeometries" ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::displayName() const +{ + return QObject::tr( "Densify by count" ); +} + +QStringList QgsDensifyGeometriesByCountAlgorithm::tags() const +{ + return QObject::tr( "add,vertex,vertices,points,nodes" ).split( ',' ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::group() const +{ + return QObject::tr( "Vector geometry" ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::groupId() const +{ + return QStringLiteral( "vectorgeometry" ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::shortHelpString() const +{ + return QObject::tr( "This algorithm takes a polygon or line layer " + "and generates a new one in which the geometries " + "have a larger number of vertices than the " + "original one.\n\n If the geometries have z or m values " + "present then these will be linearly interpolated " + "at the added nodes.\n\n The number of new vertices to " + "add to each feature geometry is specified " + "as an input parameter." ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::shortDescription() const +{ + return QObject::tr( "Creates a densified version of geometries." ); +} + +QgsDensifyGeometriesByCountAlgorithm *QgsDensifyGeometriesByCountAlgorithm::createInstance() const +{ + return new QgsDensifyGeometriesByCountAlgorithm; + +} + +QList QgsDensifyGeometriesByCountAlgorithm::inputLayerTypes() const +{ + return QList() << QgsProcessing::TypeVectorLine << QgsProcessing::TypeVectorPolygon; +} + +void QgsDensifyGeometriesByCountAlgorithm::initParameters( const QVariantMap &configuration ) +{ + Q_UNUSED( configuration ) + std::unique_ptr verticesCnt = qgis::make_unique( QStringLiteral( "VERTICES" ), + QObject::tr( "Number of vertices to add" ), + QgsProcessingParameterNumber::Integer, + 1, false, 1, 10000000 ); + verticesCnt->setIsDynamic( true ); + verticesCnt->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "VerticesCount" ), QObject::tr( "Vertices count" ), QgsPropertyDefinition::IntegerPositive ) ); + verticesCnt->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) ); + addParameter( verticesCnt.release() ); +} + +QString QgsDensifyGeometriesByCountAlgorithm::outputName() const +{ + return QObject::tr( "Densified" ); +} + +bool QgsDensifyGeometriesByCountAlgorithm::prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) +{ + Q_UNUSED( feedback ) + mVerticesCnt = parameterAsInt( parameters, QStringLiteral( "VERTICES" ), context ); + + mDynamicVerticesCnt = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "VERTICES" ) ); + if ( mDynamicVerticesCnt ) + mVerticesCntProperty = parameters.value( QStringLiteral( "VERTICES" ) ).value< QgsProperty >(); + + return true; +} + +QgsFeatureList QgsDensifyGeometriesByCountAlgorithm::processFeature( const QgsFeature &feature, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) +{ + Q_UNUSED( context ) + Q_UNUSED( feedback ) + + QgsFeature densifiedFeature = feature; + + if ( feature.hasGeometry() ) + { + int verticesCnt = mVerticesCnt; + if ( mDynamicVerticesCnt ) + verticesCnt = mVerticesCntProperty.valueAsInt( context.expressionContext(), verticesCnt ); + + if ( verticesCnt > 0 ) + densifiedFeature.setGeometry( feature.geometry().densifyByCount( verticesCnt ) ); + } + + return QgsFeatureList() << densifiedFeature; +} + + + +///@endcond PRIVATE diff --git a/pool/shard001/C++/0018197_SimpleLinkCallbacks.cpp b/pool/shard001/C++/0018197_SimpleLinkCallbacks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82af8931a829373ebf61f3f174493387f4ca74b8 --- /dev/null +++ b/pool/shard001/C++/0018197_SimpleLinkCallbacks.cpp @@ -0,0 +1,150 @@ +/* + SimpleLinkCallbacks.c + Author: Noah Luskey | LuskeyNoah@gmail.com + Use: Place code for callbacks in this file if desired. + + 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +extern "C" { + #include "SimpleLink.h" + #include +} + +#include "WiFi.h" +#include + +#if (defined(sl_GeneralEvtHdlr)) +extern void sl_GeneralEvtHdlr(SlDeviceEvent_t *pSlDeviceEvent) +{ +} +#endif + +// +// WLAN Event Handler: Modifies static variable in WiFi +// to indicate if a connection to an AP is made or not +// +#if (defined(sl_WlanEvtHdlr)) +extern void sl_WlanEvtHdlr(SlWlanEvent_t *pSlWlanEvent) +{ + unsigned char tmp[4] = {0,0,0,0}; + + switch (pSlWlanEvent->Event) { + + // + //Wlan has connected to a station + //brackets necessary to avoid crosses initialization error + // + case SL_WLAN_CONNECT_EVENT: { + WiFiClass::WiFi_status = WL_CONNECTED; + // + //copy ssid name to WiFiClass and manually add null terminator + // + char* pSSID = (char*)pSlWlanEvent->EventData.STAandP2PModeWlanConnected.ssid_name; + uint8_t ssidLength = pSlWlanEvent->EventData.STAandP2PModeWlanConnected.ssid_len; + if (ssidLength > MAX_SSID_LEN) { + return; + } + memcpy(WiFiClass::connected_ssid, pSSID, ssidLength); + WiFiClass::connected_ssid[ssidLength] = '\0'; + + // + //copy bssid to WiFiClass (no null terminator. Length always = 6) + // + char* pBSSID = (char*)pSlWlanEvent->EventData.STAandP2PModeWlanConnected.bssid; + WiFiClass::connected_bssid[5] = pBSSID[0]; + WiFiClass::connected_bssid[4] = pBSSID[1]; + WiFiClass::connected_bssid[3] = pBSSID[2]; + WiFiClass::connected_bssid[2] = pBSSID[3]; + WiFiClass::connected_bssid[1] = pBSSID[4]; + WiFiClass::connected_bssid[0] = pBSSID[5]; + break; + } + + // + //Wlan has disconnected, so completely zero out the ssid and bssid + // + case SL_WLAN_DISCONNECT_EVENT: + WiFiClass::WiFi_status = WL_DISCONNECTED; + memset(WiFiClass::connected_ssid, 0, MAX_SSID_LEN); + memset(WiFiClass::connected_bssid, 0, BSSID_LEN); + + break; + + /* Track station connects & disconnects in AP mode */ + case SL_WLAN_STA_CONNECTED_EVENT: + /* Register the MAC w/o an IP; later on, when an IP is leased to this user, the _latestConnect index will update + * to point to this one (inside sl_NetAppEvtHdlr's run of _registerNewDeviceIP() below). + */ + WiFiClass::_registerNewDeviceIP(tmp, pSlWlanEvent->EventData.APModeStaConnected.mac); + break; + + case SL_WLAN_STA_DISCONNECTED_EVENT: + WiFiClass::_unregisterDevice(pSlWlanEvent->EventData.APModestaDisconnected.mac); + WiFiClass::_connectedDeviceCount--; + break; + + + default: + break; + } +} +#endif + +#if (defined(sl_NetAppEvtHdlr)) +extern void sl_NetAppEvtHdlr(SlNetAppEvent_t *pSlSockEvent) +{ + switch (pSlSockEvent->Event) { + // + //IP address acquired. Copy the uint32 to the WiFiClass static variable + //do the following for both IPV4 and IPV6 + // + case SL_NETAPP_IPV4_ACQUIRED: + case SL_NETAPP_IPV6_ACQUIRED: + { + WiFiClass::local_IP = pSlSockEvent->EventData.ipAcquiredV4.ip; + break; + } + + /* Track station IP leases in AP mode */ + case SL_NETAPP_IP_LEASED: + unsigned char ipAddrAry[4]; + + ipAddrAry[0] = (pSlSockEvent->EventData.ipLeased.ip_address >> 24); + ipAddrAry[1] = (pSlSockEvent->EventData.ipLeased.ip_address >> 16) & 0xFF; + ipAddrAry[2] = (pSlSockEvent->EventData.ipLeased.ip_address >> 8) & 0xFF; + ipAddrAry[3] = pSlSockEvent->EventData.ipLeased.ip_address & 0xFF; + WiFiClass::_registerNewDeviceIP(ipAddrAry, pSlSockEvent->EventData.ipLeased.mac); + WiFiClass::_connectedDeviceCount++; + break; + + default: + break; + } +} +#endif + +#if (defined(sl_SockEvtHdlr)) +extern void sl_SockEvtHdlr(SlSockEvent_t *pSlSockEvent) +{ +} +#endif + +#if (defined(sl_HttpServerCallback)) +extern void sl_HttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse) +{ +} +#endif diff --git a/pool/shard001/C++/0018202_exercise2_list.cpp b/pool/shard001/C++/0018202_exercise2_list.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dadea65f0291b5d9856648216a7900c9c26dc7c --- /dev/null +++ b/pool/shard001/C++/0018202_exercise2_list.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "grade.h" +#include "Student_info.h" +#include "extract_failed.h" + +using std::cin; +using std::cout; +using std::domain_error; +using std::endl; +using std::max; +using std::setprecision; +using std::sort; +using std::streamsize; +using std::list; +using std::string; +using std::ifstream; + + +int main(int argc, const char *argv[]) +{ + list students, failed; + Student_info record; + string::size_type maxlen = 0; + ifstream myfile; + + myfile.open("input.txt"); + + /* read and store all the students' data + * Invariant: students contains all the students records read so far + * maxlen contains the lenght of the longest name in students*/ + while (read(myfile, record)) { + // find length of longest name + maxlen = max(maxlen, record.name.size()); + students.push_back(record); + } + + /* remove students that failed from list */ + failed = extract_failed(students); + + // sort students records alphabetically + // lists have their own sort + students.sort(compare); + + + // write the names and grades + for (list::const_iterator iter = students.begin(); iter != students.end(); iter++) { + cout << iter->name << string(maxlen + 1 - iter->name.size(), ' '); + /* try: initiates a block that might throw an exception */ + + try { + double final_grade = grade(*iter); + streamsize prec = cout.precision(); + cout << setprecision(3) << final_grade << setprecision(prec); + } catch (domain_error e) { + /* what is a member function of exception in Std lib, that has copy of + * argument of exception */ + cout << e.what(); + } + cout << endl; + } + myfile.close(); + return 0; +} diff --git a/pool/shard001/C++/0018217_messageaction.cc b/pool/shard001/C++/0018217_messageaction.cc new file mode 100644 index 0000000000000000000000000000000000000000..9856891e3c177e39cbdcb55d2b5c336c5b4a2de2 --- /dev/null +++ b/pool/shard001/C++/0018217_messageaction.cc @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016 Jason Waataja + * + * 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 "messageaction.h" + +#include +#include + +#include "messageeditor.h" + +namespace gdfm { + +MessageAction::MessageAction() +{ +} + +MessageAction::MessageAction(const std::string& message) : message(message) +{ + updateName(); +} + +bool +MessageAction::performAction() +{ + if (!getParent()) + return false; + Gtk::MessageDialog dialog(*getParent(), message, false, Gtk::MESSAGE_INFO, + Gtk::BUTTONS_OK, true); + dialog.run(); + return true; +} + +const std::string& +MessageAction::getMessage() const +{ + return message; +} + +void +MessageAction::setMessage(const std::string& message) +{ + this->message = message; +} + +void +MessageAction::updateName() +{ + setName("Message"); +} + +void +MessageAction::graphicalEdit(Gtk::Window& parent) +{ + MessageEditor editor(parent, this); + editor.run(); +} + +std::vector +MessageAction::createConfigLines() const +{ + std::ostringstream outputStream; + for (std::string::size_type i = 0; i < message.length(); i++) { + if (message[i] == '"') + outputStream << "\\\""; + else + outputStream << message[i]; + } + std::string line = "message \"" + outputStream.str() + "\""; + std::vector lines; + lines.push_back(line); + return lines; +} +} /* namespace gdfm */ diff --git a/pool/shard001/C++/0018222_SceneNode.cpp b/pool/shard001/C++/0018222_SceneNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9611170bb2e1978aee0b125acea3fb331f2b7f3f --- /dev/null +++ b/pool/shard001/C++/0018222_SceneNode.cpp @@ -0,0 +1,133 @@ +/** + * @file SceneNode.cpp + * @author Cristian Bidea + * @copyright 2012 Cristian Bidea + * + * This file is part of QUI2D. + * + * QUI2D 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. + * + * QUI2D 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 QUI2D. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include + +namespace qui +{ +namespace Q2D +{ +SceneNode::SceneNode() + : IObject() + , data(new ObjectData()) +{ +} + +SceneNode::~SceneNode() +{ +} + +void SceneNode::addChild(cpp0x::shared_ptr child) +{ + this->children.push_back(child); +} + +void SceneNode::removeChild(cpp0x::shared_ptr child) +{ + this->children.erase(std::remove(this->children.begin(), this->children.end(), child), this->children.end()); +} + +void SceneNode::clearChildren() +{ + this->children.clear(); +} +bool SceneNode::getHasUpdate() const +{ + return data->hasUpdate; +} + +void SceneNode::setHasUpdate(bool update) +{ + data->hasUpdate = update; +} + +bool SceneNode::isVisible() const +{ + return data->visible; +} + +void SceneNode::setVisible(bool visible) +{ + data->visible = visible; +} + +void SceneNode::setPosition(const glm::vec2& pos) +{ + data->setPosition(pos); +} + +glm::vec2& SceneNode::getPosition() +{ + return data->position; +} + +void SceneNode::setRotationAngle(float angle) +{ + data->setRotationAngle(angle); +} + +float SceneNode::getRotationAngle() const +{ + return data->rotationAngle; +} + +void SceneNode::setAnchorPoint(const glm::vec2& anchor) +{ + data->anchorPoint = anchor; +} + +glm::vec2& SceneNode::getAnchorPoint() +{ + return data->anchorPoint; +} + +void SceneNode::update(uint64_t dt) +{ + for (std::vector >::iterator it = children.begin() + ; it != children.end() + ; it++) + { + if ((*it)->getHasUpdate()) + { + (*it)->update(dt); + } + } +} + +void SceneNode::paint() +{ + for (std::vector >::iterator it = children.begin() + ; it != children.end() + ; it++) + { + if ((*it)->isVisible()) + { + (*it)->paint(); + } + } +} +} // namespace Q2D +} // namespace qui diff --git a/pool/shard001/C++/0018229_credential_android.cc b/pool/shard001/C++/0018229_credential_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..c1be78d139f8d8362a7f8d5173ca789af3be65eb --- /dev/null +++ b/pool/shard001/C++/0018229_credential_android.cc @@ -0,0 +1,40 @@ +// 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 "chrome/browser/password_manager/credential_android.h" + +#include "base/android/jni_string.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/grit/generated_resources.h" +#include "jni/Credential_jni.h" +#include "ui/base/l10n/l10n_util.h" + +base::android::ScopedJavaLocalRef CreateNativeCredential( + JNIEnv* env, + const autofill::PasswordForm& password_form, + int position, + int type) { + using base::android::ConvertUTF16ToJavaString; + using base::android::ConvertUTF8ToJavaString; + std::string federation = + password_form.federation_url.is_empty() + ? std::string() + : l10n_util::GetStringFUTF8( + IDS_PASSWORDS_VIA_FEDERATION, + base::ASCIIToUTF16(password_form.federation_url.host())); + return Java_Credential_createCredential( + env, ConvertUTF16ToJavaString(env, password_form.username_value).obj(), + ConvertUTF16ToJavaString(env, password_form.display_name).obj(), + ConvertUTF8ToJavaString(env, federation).obj(), type, position); +} + +base::android::ScopedJavaLocalRef CreateNativeCredentialArray( + JNIEnv* env, + size_t size) { + return Java_Credential_createCredentialArray(env, static_cast(size)); +} + +bool RegisterCredential(JNIEnv* env) { + return RegisterNativesImpl(env); +} diff --git a/pool/shard001/C++/0018230_main.cpp b/pool/shard001/C++/0018230_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ff16bafda8e9a22fd96df0c87fcb7bfb1c54fc23 --- /dev/null +++ b/pool/shard001/C++/0018230_main.cpp @@ -0,0 +1,90 @@ +/* + * RWMapMaker is © IvimeyCom 2011-2014. + * + * This file is part of RWMapMaker. + * + * RWMapMaker 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. + * + * RWMapMaker 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 RWMapMaker. If not, see http://www.gnu.org/licenses/gpl.html. + */ + +#include "stdafx.h" +#include + +#include "RWMapMaker.h" +#include "splashscreen.h" +#include "qxtbasicfileloggerengine.h" + +void setupLogEngine() +{ + QSettings settings; + + // set up the event logger + bool logToFile = settings.value("logToFile", false).toBool(); + if (logToFile) + { + QString logFilename = settings.value("logFile", QString("C:/Temp/rwmapmaker.log")).toString(); + if (!logFilename.isEmpty()) + { + qxtLog->addLoggerEngine("logFile", new QxtBasicFileLoggerEngine(logFilename)); + } + } + qxtLog->disableLogLevels(QxtLogger::DebugLevel|QxtLogger::TraceLevel); +} + +int main(int argc, char *argv[]) +{ + SplashScreen *ss; + QApplication a(argc, argv); + QString routeFile; + + QCoreApplication::setOrganizationName("IvimeyCom"); + QCoreApplication::setOrganizationDomain("ivimey.com"); + QCoreApplication::setApplicationName(PROGRAM_NAME); + + setupLogEngine(); + + for(int i = 1; i < argc; i++) + { + if (argv[i][0] == '-') + { + if (strcmp(argv[i], "--help") == 0) + { + printf(PROGRAM_NAME " (c) 2013-2014 IvimeyCom, by Ruth Ivimey-Cook\n" + "\nUsage: RWMapMaker [--help] [path..to..RouteProperties.xml]\n"); + exit(0); + } + } + else + { + routeFile = argv[i]; + break; + } + } + + ss = new SplashScreen(); + ss->show(); + try + { + RWMapMaker *w = new RWMapMaker(routeFile); + w->show(); + return a.exec(); + } + catch(std::exception ex) + { + printf(PROGRAM_NAME " Exception caught:\n%s", ex.what()); + exit(1); + } + catch(...) + { + printf(PROGRAM_NAME " Exception caught:\n"); + exit(2); + } +} diff --git a/pool/shard001/C++/0018232_qgswmsgetstyles.cpp b/pool/shard001/C++/0018232_qgswmsgetstyles.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ae53b20c6ab97812a585aae64b5a4eb34132f12 --- /dev/null +++ b/pool/shard001/C++/0018232_qgswmsgetstyles.cpp @@ -0,0 +1,195 @@ +/*************************************************************************** + qgswmsgetstyles.h + ------------------------- + begin : December 20 , 2016 + copyright : (C) 2007 by Marco Hugentobler (original code) + (C) 2014 by Alessandro Pasotti (original code) + (C) 2016 by David Marteau + email : marco dot hugentobler at karto dot baug dot ethz dot ch + a dot pasotti at itopen dot it + david dot marteau at 3liz dot 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 "qgswmsutils.h" +#include "qgswmsgetstyles.h" +#include "qgsserverprojectutils.h" + +#include "qgsrenderer.h" +#include "qgsvectorlayer.h" +#include "qgsmaplayerstylemanager.h" + +namespace QgsWms +{ + + namespace + { + QDomDocument getStyledLayerDescriptorDocument( QgsServerInterface *serverIface, const QgsProject *project, + QStringList &layerList ); + } + + void writeGetStyles( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, + const QgsServerRequest &request, QgsServerResponse &response ) + { + QDomDocument doc = getStyles( serverIface, project, version, request ); + response.setHeader( QStringLiteral( "Content-Type" ), QStringLiteral( "text/xml; charset=utf-8" ) ); + response.write( doc.toByteArray() ); + } + + QDomDocument getStyles( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, + const QgsServerRequest &request ) + { + Q_UNUSED( version ); + + QgsServerRequest::Parameters parameters = request.parameters(); + + QString layersName = parameters.value( "LAYERS" ); + + if ( layersName.isEmpty() ) + { + throw QgsBadRequestException( QStringLiteral( "LayerNotSpecified" ), + QStringLiteral( "Layers is mandatory for GetStyles operation" ) ); + } + + QStringList layerList = layersName.split( ',', QString::SkipEmptyParts ); + if ( layerList.isEmpty() ) + { + throw QgsBadRequestException( QStringLiteral( "LayerNotSpecified" ), + QStringLiteral( "Layers is mandatory for GetStyles operation" ) ); + } + + return getStyledLayerDescriptorDocument( serverIface, project, layerList ); + } + + //GetStyle for compatibility with earlier QGIS versions + void writeGetStyle( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, + const QgsServerRequest &request, QgsServerResponse &response ) + { + QDomDocument doc = getStyle( serverIface, project, version, request ); + response.setHeader( QStringLiteral( "Content-Type" ), QStringLiteral( "text/xml; charset=utf-8" ) ); + response.write( doc.toByteArray() ); + } + + QDomDocument getStyle( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, + const QgsServerRequest &request ) + { + Q_UNUSED( version ); + + QgsServerRequest::Parameters parameters = request.parameters(); + + QDomDocument doc; + + QString styleName = parameters.value( QStringLiteral( "STYLE" ) ); + QString layerName = parameters.value( QStringLiteral( "LAYER" ) ); + + if ( styleName.isEmpty() ) + { + throw QgsServiceException( QStringLiteral( "StyleNotSpecified" ), + QStringLiteral( "Style is mandatory for GetStyle operation" ), 400 ); + } + + if ( layerName.isEmpty() ) + { + throw QgsServiceException( QStringLiteral( "LayerNotSpecified" ), + QStringLiteral( "Layer is mandatory for GetStyle operation" ), 400 ); + } + + QStringList layerList; + layerList.append( layerName ); + return getStyledLayerDescriptorDocument( serverIface, project, layerList ); + } + + namespace + { + QDomDocument getStyledLayerDescriptorDocument( QgsServerInterface *serverIface, const QgsProject *project, + QStringList &layerList ) + { + QDomDocument myDocument = QDomDocument(); + + QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) ); + myDocument.appendChild( header ); + + // Create the root element + QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "StyledLayerDescriptor" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.1.0" ) ); + root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ) ); + root.setAttribute( QStringLiteral( "xmlns:ogc" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); + root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) ); + root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + myDocument.appendChild( root ); + + // access control + QgsAccessControl *accessControl = serverIface->accessControls(); + // Use layer ids + bool useLayerIds = QgsServerProjectUtils::wmsUseLayerIds( *project ); + // WMS restricted layers + QStringList restrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *project ); + + Q_FOREACH ( QgsMapLayer *layer, project->mapLayers() ) + { + QString name = layer->name(); + if ( useLayerIds ) + name = layer->id(); + else if ( !layer->shortName().isEmpty() ) + name = layer->shortName(); + + if ( !layerList.contains( name ) ) + { + continue; + } + + //unpublished layer + if ( restrictedLayers.contains( layer->name() ) ) + { + throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) ); + } + + if ( accessControl && !accessControl->layerReadPermission( layer ) ) + { + throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) ); + } + + // Create the NamedLayer element + QDomElement namedLayerNode = myDocument.createElement( QStringLiteral( "NamedLayer" ) ); + root.appendChild( namedLayerNode ); + + // store the Name element + QDomElement nameNode = myDocument.createElement( QStringLiteral( "se:Name" ) ); + nameNode.appendChild( myDocument.createTextNode( name ) ); + namedLayerNode.appendChild( nameNode ); + + if ( layer->type() == QgsMapLayer::VectorLayer ) + { + QgsVectorLayer *vlayer = qobject_cast( layer ); + if ( vlayer->isSpatial() ) + { + QString currentStyle = vlayer->styleManager()->currentStyle(); + Q_FOREACH ( QString styleName, vlayer->styleManager()->styles() ) + { + vlayer->styleManager()->setCurrentStyle( styleName ); + QDomElement styleElem = vlayer->renderer()->writeSld( myDocument, styleName ); + namedLayerNode.appendChild( styleElem ); + } + vlayer->styleManager()->setCurrentStyle( currentStyle ); + } + } + } + + return myDocument; + } + } + + +} // samespace QgsWms + + + + diff --git a/pool/shard001/C++/0018243_VideoPreprocessor.cpp b/pool/shard001/C++/0018243_VideoPreprocessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcbff4765ae6372002701a8c7424a60ffc822858 --- /dev/null +++ b/pool/shard001/C++/0018243_VideoPreprocessor.cpp @@ -0,0 +1,149 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace MediaConvert +{ +namespace Model +{ + +VideoPreprocessor::VideoPreprocessor() : + m_colorCorrectorHasBeenSet(false), + m_deinterlacerHasBeenSet(false), + m_dolbyVisionHasBeenSet(false), + m_imageInserterHasBeenSet(false), + m_noiseReducerHasBeenSet(false), + m_partnerWatermarkingHasBeenSet(false), + m_timecodeBurninHasBeenSet(false) +{ +} + +VideoPreprocessor::VideoPreprocessor(JsonView jsonValue) : + m_colorCorrectorHasBeenSet(false), + m_deinterlacerHasBeenSet(false), + m_dolbyVisionHasBeenSet(false), + m_imageInserterHasBeenSet(false), + m_noiseReducerHasBeenSet(false), + m_partnerWatermarkingHasBeenSet(false), + m_timecodeBurninHasBeenSet(false) +{ + *this = jsonValue; +} + +VideoPreprocessor& VideoPreprocessor::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("colorCorrector")) + { + m_colorCorrector = jsonValue.GetObject("colorCorrector"); + + m_colorCorrectorHasBeenSet = true; + } + + if(jsonValue.ValueExists("deinterlacer")) + { + m_deinterlacer = jsonValue.GetObject("deinterlacer"); + + m_deinterlacerHasBeenSet = true; + } + + if(jsonValue.ValueExists("dolbyVision")) + { + m_dolbyVision = jsonValue.GetObject("dolbyVision"); + + m_dolbyVisionHasBeenSet = true; + } + + if(jsonValue.ValueExists("imageInserter")) + { + m_imageInserter = jsonValue.GetObject("imageInserter"); + + m_imageInserterHasBeenSet = true; + } + + if(jsonValue.ValueExists("noiseReducer")) + { + m_noiseReducer = jsonValue.GetObject("noiseReducer"); + + m_noiseReducerHasBeenSet = true; + } + + if(jsonValue.ValueExists("partnerWatermarking")) + { + m_partnerWatermarking = jsonValue.GetObject("partnerWatermarking"); + + m_partnerWatermarkingHasBeenSet = true; + } + + if(jsonValue.ValueExists("timecodeBurnin")) + { + m_timecodeBurnin = jsonValue.GetObject("timecodeBurnin"); + + m_timecodeBurninHasBeenSet = true; + } + + return *this; +} + +JsonValue VideoPreprocessor::Jsonize() const +{ + JsonValue payload; + + if(m_colorCorrectorHasBeenSet) + { + payload.WithObject("colorCorrector", m_colorCorrector.Jsonize()); + + } + + if(m_deinterlacerHasBeenSet) + { + payload.WithObject("deinterlacer", m_deinterlacer.Jsonize()); + + } + + if(m_dolbyVisionHasBeenSet) + { + payload.WithObject("dolbyVision", m_dolbyVision.Jsonize()); + + } + + if(m_imageInserterHasBeenSet) + { + payload.WithObject("imageInserter", m_imageInserter.Jsonize()); + + } + + if(m_noiseReducerHasBeenSet) + { + payload.WithObject("noiseReducer", m_noiseReducer.Jsonize()); + + } + + if(m_partnerWatermarkingHasBeenSet) + { + payload.WithObject("partnerWatermarking", m_partnerWatermarking.Jsonize()); + + } + + if(m_timecodeBurninHasBeenSet) + { + payload.WithObject("timecodeBurnin", m_timecodeBurnin.Jsonize()); + + } + + return payload; +} + +} // namespace Model +} // namespace MediaConvert +} // namespace Aws diff --git a/pool/shard001/C++/0018248_Attitude.cpp b/pool/shard001/C++/0018248_Attitude.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43d15f6dda19f9432d931bca001516d5ea844465 --- /dev/null +++ b/pool/shard001/C++/0018248_Attitude.cpp @@ -0,0 +1,158 @@ +#include "Copter.h" + +// transform pilot's yaw input into a desired yaw rate +// returns desired yaw rate in centi-degrees per second +float Copter::get_pilot_desired_yaw_rate(int16_t stick_angle) +{ + // throttle failsafe check + if (failsafe.radio || !ap.rc_receiver_present) { + return 0.0f; + } + float yaw_request; + + // range check expo + g2.acro_y_expo = constrain_float(g2.acro_y_expo, 0.0f, 1.0f); + + // calculate yaw rate request + if (is_zero(g2.acro_y_expo)) { + yaw_request = stick_angle * g.acro_yaw_p; + } else { + // expo variables + float y_in, y_in3, y_out; + + // yaw expo + y_in = float(stick_angle)/ROLL_PITCH_YAW_INPUT_MAX; + y_in3 = y_in*y_in*y_in; + y_out = (g2.acro_y_expo * y_in3) + ((1.0f - g2.acro_y_expo) * y_in); + yaw_request = ROLL_PITCH_YAW_INPUT_MAX * y_out * g.acro_yaw_p; + } + // convert pilot input to the desired yaw rate + return yaw_request; +} + +/************************************************************* + * throttle control + ****************************************************************/ + +// update estimated throttle required to hover (if necessary) +// called at 100hz +void Copter::update_throttle_hover() +{ +#if FRAME_CONFIG != HELI_FRAME + // if not armed or landed exit + if (!motors->armed() || ap.land_complete) { + return; + } + + // do not update in manual throttle modes or Drift + if (flightmode->has_manual_throttle() || (control_mode == Mode::Number::DRIFT)) { + return; + } + + // do not update while climbing or descending + if (!is_zero(pos_control->get_desired_velocity().z)) { + return; + } + + // get throttle output + float throttle = motors->get_throttle(); + + // calc average throttle if we are in a level hover + if (throttle > 0.0f && fabsf(inertial_nav.get_velocity_z()) < 60 && + labs(ahrs.roll_sensor) < 500 && labs(ahrs.pitch_sensor) < 500) { + // Can we set the time constant automatically + motors->update_throttle_hover(0.01f); +#if HAL_GYROFFT_ENABLED + gyro_fft.update_freq_hover(0.01f, motors->get_throttle_out()); +#endif + } +#endif +} + +// get_pilot_desired_climb_rate - transform pilot's throttle input to climb rate in cm/s +// without any deadzone at the bottom +float Copter::get_pilot_desired_climb_rate(float throttle_control) +{ + // throttle failsafe check + if (failsafe.radio || !ap.rc_receiver_present) { + return 0.0f; + } + +#if TOY_MODE_ENABLED == ENABLED + if (g2.toy_mode.enabled()) { + // allow throttle to be reduced after throttle arming and for + // slower descent close to the ground + g2.toy_mode.throttle_adjust(throttle_control); + } +#endif + + float desired_rate = 0.0f; + float mid_stick = get_throttle_mid(); + float deadband_top = mid_stick + g.throttle_deadzone; + float deadband_bottom = mid_stick - g.throttle_deadzone; + + // ensure a reasonable throttle value + throttle_control = constrain_float(throttle_control,0.0f,1000.0f); + + // ensure a reasonable deadzone + g.throttle_deadzone = constrain_int16(g.throttle_deadzone, 0, 400); + + // check throttle is above, below or in the deadband + if (throttle_control < deadband_bottom) { + // below the deadband + desired_rate = get_pilot_speed_dn() * (throttle_control-deadband_bottom) / deadband_bottom; + } else if (throttle_control > deadband_top) { + // above the deadband + desired_rate = g.pilot_speed_up * (throttle_control-deadband_top) / (1000.0f-deadband_top); + } else { + // must be in the deadband + desired_rate = 0.0f; + } + + return desired_rate; +} + +// get_non_takeoff_throttle - a throttle somewhere between min and mid throttle which should not lead to a takeoff +float Copter::get_non_takeoff_throttle() +{ + return MAX(0,motors->get_throttle_hover()/2.0f); +} + +// get target climb rate reduced to avoid obstacles and altitude fence +float Copter::get_avoidance_adjusted_climbrate(float target_rate) +{ +#if AC_AVOID_ENABLED == ENABLED + avoid.adjust_velocity_z(pos_control->get_pos_z_p().kP(), pos_control->get_max_accel_z(), target_rate, G_Dt); + return target_rate; +#else + return target_rate; +#endif +} + +// set_accel_throttle_I_from_pilot_throttle - smoothes transition from pilot controlled throttle to autopilot throttle +void Copter::set_accel_throttle_I_from_pilot_throttle() +{ + // get last throttle input sent to attitude controller + float pilot_throttle = constrain_float(attitude_control->get_throttle_in(), 0.0f, 1.0f); + // shift difference between pilot's throttle and hover throttle into accelerometer I + pos_control->get_accel_z_pid().set_integrator((pilot_throttle-motors->get_throttle_hover()) * 1000.0f); +} + +// rotate vector from vehicle's perspective to North-East frame +void Copter::rotate_body_frame_to_NE(float &x, float &y) +{ + float ne_x = x*ahrs.cos_yaw() - y*ahrs.sin_yaw(); + float ne_y = x*ahrs.sin_yaw() + y*ahrs.cos_yaw(); + x = ne_x; + y = ne_y; +} + +// It will return the PILOT_SPEED_DN value if non zero, otherwise if zero it returns the PILOT_SPEED_UP value. +uint16_t Copter::get_pilot_speed_dn() +{ + if (g2.pilot_speed_dn == 0) { + return abs(g.pilot_speed_up); + } else { + return abs(g2.pilot_speed_dn); + } +} diff --git a/pool/shard001/C++/0018253_clear_allocator.cc b/pool/shard001/C++/0018253_clear_allocator.cc new file mode 100644 index 0000000000000000000000000000000000000000..934f1be33563791e37ed8835498af6eb4c7fc679 --- /dev/null +++ b/pool/shard001/C++/0018253_clear_allocator.cc @@ -0,0 +1,87 @@ +// Copyright (C) 2004, 2009 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 +// . + +#include +#include + +using namespace std; +using __gnu_cxx::new_allocator; + +template + class clear_alloc : public new_allocator + { + public: + + template + struct rebind + { typedef clear_alloc other; }; + + virtual void clear() throw() + { } + + clear_alloc() throw() + { } + + clear_alloc(clear_alloc const&) throw() : new_allocator() + { } + + template + clear_alloc(clear_alloc const&) throw() + { } + + virtual ~clear_alloc() throw() + { this->clear(); } + + T* allocate(typename new_allocator::size_type n, const void *hint = 0) + { + this->clear(); + return new_allocator::allocate(n, hint); + } + + void deallocate(T *ptr, typename new_allocator::size_type n) + { + this->clear(); + new_allocator::deallocate(ptr, n); + } + }; + +template + void Check_Container() + { + Container* pic = new Container; + int x = 230; + + while (x--) + { + pic->push_back(x); + } + + pic->get_allocator(); + + // The following has led to infinite recursions or cores. + pic->clear(); + + delete pic; + } + + +int main() +{ + Check_Container > >(); + return 0; +} + diff --git a/pool/shard001/C++/0018262_main.cpp b/pool/shard001/C++/0018262_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..922e4dd2000b31008474cd16026e0d975a659256 --- /dev/null +++ b/pool/shard001/C++/0018262_main.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include "opencv2/highgui/highgui.hpp" +#include "opencv2/imgproc/imgproc.hpp" +#include +#include +#include +using boost::asio::ip::tcp; +using namespace std; +using namespace cv; + +int main() +{ + VideoCapture cap(0); /* open webcam */ + if(!cap.isOpened()) + { + return -1; + } + Mat frame; + cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); /* set width */ + cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240); /* set height */ + while (true) + { + cap>>frame; + imshow("client",frame); + waitKey(100); + frame = (frame.reshape(0,1)); // to make it continuous + try + { + boost::asio::io_service io_service; + tcp::endpoint end_point(boost::asio::ip::address::from_string("10.104.3.196"), 3200); // 10.104.3.196 is my android server ip + // tcp::endpoint end_point(boost::asio::ip::address::from_string("127.0.0.1"), 3200); // 127.0.0.1 is my pc server ip + + tcp::socket socket(io_service); + socket.connect(end_point); + boost::system::error_code ignored_error; + std::string message((char *)frame.data,230400); /* the size of mat data is 320*240*3 */ + cout<<"sending...."<. + + +//---------------------------------------------------------------------------- +//-- This example loads the simplest 3-module snake robot and makes it perform +//-- some test movements: walking, turning, rolling, etc +//---------------------------------------------------------------------------- + + +#include "TestBase.h" + +class Example : public TestBase +{ + public: + Example(string envfile,string controller,bool showgui=true) : + TestBase(envfile,controller,showgui) {}; + void run(dReal step, bool realtime=true); +}; + +void Example::run(dReal step, bool realtime) +{ + stringstream os,is; + + is << "oscillation on "; + pcontroller->SendCommand(os,is); + penv->StartSimulation(step,realtime); + + while(1) { + + //-- Sideways movement + is << "setperiod 1.5 "; + pcontroller->SendCommand(os,is); + is << "setoffset 0 0 0 "; + pcontroller->SendCommand(os,is); + is << "setinitialphase 0 90 0 "; + pcontroller->SendCommand(os,is); + is << "setamplitude 30 30 30 "; + pcontroller->SendCommand(os,is); + sleep(10); + + //-- sideways movement (oposite direction) + is << "setinitialphase 0 -90 0 "; + pcontroller->SendCommand(os,is); + sleep(10); + + //-- Debug! Show the viewer transformation + //RaveTransform t = viewer->GetCameraTransform(); + //cout << "Transform: " << t << endl; + + //-- Rotating + is << "setinitialphase 0 90 180 "; + pcontroller->SendCommand(os,is); + is << "setamplitude 30 60 30 "; + pcontroller->SendCommand(os,is); + sleep(20); + + //-- Preparation to rolling + is << "setamplitude 0 0 0 "; + pcontroller->SendCommand(os,is); + is << "setoffset 0 70 0 "; + pcontroller->SendCommand(os,is); + sleep(2); + + //-- Rolling + is << "setperiod 2 "; + pcontroller->SendCommand(os,is); + is << "setinitialphase 0 90 0 "; + pcontroller->SendCommand(os,is); + is << "setoffset 0 0 0 "; + pcontroller->SendCommand(os,is); + is << "setamplitude 70 70 70 "; + pcontroller->SendCommand(os,is); + sleep(10); + } + +} + +int main(int argc, char ** argv) +{ + string envfile; + + if (argc==1) + //-- Default file + envfile="../models/Minicube-II.env.xml"; + else + envfile = argv[1]; + + Example example(envfile,"sinoscontroller"); + usleep(100000); + example.SetCamera(0.493, 0.286, 0.378, 0.729,0.557, 0.097, 0.352); + example.run(0.001,true); + + return 0; +} + + + diff --git a/pool/shard001/C++/0018293_timetick.cpp b/pool/shard001/C++/0018293_timetick.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0fa09e241b1c252471aae531b420e5b418fe37b --- /dev/null +++ b/pool/shard001/C++/0018293_timetick.cpp @@ -0,0 +1,142 @@ + +//============================================================================= +/** + * @file timetick.cpp + * + * $Id: timetick.cpp 93651 2011-03-28 08:49:11Z johnnyw $ + * + * Class implentation for SMI Timeticks class. + * + * + * @author Peter E MellquistMichael R MacFaden mrm@cisco.com - rework & ACE port + */ +//============================================================================= + +/*=================================================================== + Copyright (c) 1996 + Hewlett-Packard Company + + ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS. + Permission to use, copy, modify, distribute and/or sell this software + and/or its documentation is hereby granted without fee. User agrees + to display the above copyright notice and this license notice in all + copies of the software and any documentation of the software. User + agrees to assume all liability for the use of the software; Hewlett-Packard + makes no representations about the suitability of this software for any + purpose. It is provided "AS-IS without warranty of any kind,either express + or implied. User hereby grants a royalty-free license to any and all + derivatives based upon this software code base. +=====================================================================*/ + +#include "asnmp/timetick.h" // include header file for timetick class +#include "ace/OS_NS_stdio.h" + +// constructor with a value +TimeTicks::TimeTicks( const unsigned long i):SnmpUInt32(i) +{ + smival.syntax = sNMP_SYNTAX_TIMETICKS; +} + +// copy constructor +TimeTicks::TimeTicks( const TimeTicks &t) + : SnmpUInt32 (t) +{ + smival.value.uNumber = t.smival.value.uNumber; + smival.syntax = sNMP_SYNTAX_TIMETICKS; +} + +// destructor +TimeTicks::~TimeTicks() +{ +} + +// syntax type +SmiUINT32 TimeTicks::get_syntax() +{ + return sNMP_SYNTAX_TIMETICKS; +} + +// create a new instance of this Value +SnmpSyntax *TimeTicks::clone() const +{ + return (SnmpSyntax *) new TimeTicks(*this); +} + +// overloaded assignement from ulong +TimeTicks& TimeTicks::operator=( const unsigned long int i) +{ + smival.value.uNumber =i; return *this; +} + +// overloaded assignment from TimeTicks +TimeTicks& TimeTicks::operator=( const TimeTicks &uli) +{ + this->smival.value.uNumber = uli.smival.value.uNumber; return *this; +} + +// general assignment from any Value +SnmpSyntax& TimeTicks::operator=( SnmpSyntax &in_val) +{ + if ( this == &in_val ) // handle assignement from itself + return *this; + + valid_flag = 0; // will get set true if really valid + if (in_val.valid()) { + switch (in_val.get_syntax()) { + case sNMP_SYNTAX_UINT32: + // case sNMP_SYNTAX_GAUGE32: .. indistinquishable from UINT32 + case sNMP_SYNTAX_CNTR32: + case sNMP_SYNTAX_TIMETICKS: + case sNMP_SYNTAX_INT32: // implied cast int -> uint + this->smival.value.uNumber = + ((TimeTicks &)in_val).smival.value.uNumber; + valid_flag = 1; + break; + } + } + return *this; +} + +// otherwise, behave like an unsigned long +TimeTicks::operator unsigned long() +{ + return smival.value.uNumber; +} + + +// ASCII format return +const char * TimeTicks::to_string() + /* Should do something nicer like days:hours:minutes... */ +{ + unsigned long tt, hseconds, seconds, minutes, hours, days; + tt = this->smival.value.uNumber; + + // days + days = tt / 8640000; + tt %= 8640000; + + // hours + hours = tt / 360000; + tt %= 360000; + + // minutes + minutes = tt / 6000; + tt %= 6000; + + seconds = tt / 100; + tt %= 100; + + hseconds = tt; + + if ( days ==0) + ACE_OS::sprintf( output_buffer,"%ld:%02ld:%02ld.%02ld", hours, + minutes,seconds,hseconds); + else if ( days==1) + ACE_OS::sprintf( output_buffer,"1 day %ld:%02ld:%02ld.%02ld", hours, + minutes,seconds,hseconds); + else + ACE_OS::sprintf( output_buffer,"%ld days, %ld:%02ld:%02ld.%02ld", + days,hours, minutes,seconds, hseconds); + + return output_buffer; +} diff --git a/pool/shard001/C++/0018295_11865180.cpp b/pool/shard001/C++/0018295_11865180.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60ec601430f488c0e3a9f51611bc9359791c8ae0 --- /dev/null +++ b/pool/shard001/C++/0018295_11865180.cpp @@ -0,0 +1,84 @@ +//Language: GNU C++11 + + +#include +using namespace std; + +#define mp make_pair +#define pb push_back + +typedef unsigned long long ll; +typedef pair pii; + +const int MAXN = 100100; + +int n, m; +int was[MAXN]; +vector g[MAXN]; +bool was2[3][MAXN]; + +bool dfs(int v, int col = 1) { + was[v] = col; + for (int i = 0; i < (int)g[v].size(); ++i) { + if (!was[g[v][i]]) { + if (dfs(g[v][i], 3 - col)) { + return true; + } + } else if (was[v] == was[g[v][i]]) + return true; + } + return false; +} + +int dfs2(int v, int col) { + was2[col][v] = true; + int res = was[v] == col; + for (int i = 0; i < (int)g[v].size(); ++i) { + if (!was2[col][g[v][i]]) { + res += dfs2(g[v][i], col); + } + } + return res; +} + +ll C(int n, int k) { + if (k > n) return 0; + ll res = 1; + for (int i = 0; i < k; ++i) + res *= n - i; + for (int i = 2; i <= k; ++i) + res /= i; + return res; +} + +int main() { + scanf("%d%d", &n, &m); + for (int i = 0, a, b; i < m; ++i) { + scanf("%d%d", &a, &b); + g[a].pb(b); + g[b].pb(a); + } + for (int i = 1; i <= n; ++i) { + if (!was[i] && dfs(i)) { + puts("0 1"); + return 0; + } + } + ll one = 0; + for (int i = 1; i <= n; ++i) { + if (!was2[1][i]) { + one += C(dfs2(i, 1), 2); + one += C(dfs2(i, 2), 2); + } + } + if (one) { + cout << 1 << ' ' << one << endl; + return 0; + } + if (m) { + cout << 2 << ' ' << m * 1ll * (n - 2) << '\n'; + return 0; + } + cout << 3 << ' ' << C(n, 3) << '\n'; + return 0; +} diff --git a/pool/shard001/C++/0018299_Type.cc b/pool/shard001/C++/0018299_Type.cc new file mode 100644 index 0000000000000000000000000000000000000000..3765711aa23342fee6b9298dfdd839acd736670c --- /dev/null +++ b/pool/shard001/C++/0018299_Type.cc @@ -0,0 +1,76 @@ +#include "IR/Type.h" + +// Type +Type* Type::voidtype_ = new Type(VoidTy); +Type* Type::labeltype_ = new Type(LabelTy); + +Type::Type(TypeID tid) : typeid_(tid) { +} + +Type::~Type() { +} + +Type::TypeID Type::getTypeID() const { + return typeid_; +} + +bool Type::isIntegerTy() const { + return getTypeID() == IntegerTy; +} + +bool Type::isLabelTy() const { + return getTypeID() == LabelTy; +} + +bool Type::isPointerTy() const { + return getTypeID() == PointerTy; +} + +Type* Type::getVoidTy() { + return voidtype_; +} + +IntegerType* Type::getInt64Ty() { + return IntegerType::get(64); +} + +Type* Type::getLabelTy() { + return labeltype_; +} + +PointerType* Type::getInt64PtrTy() { + return PointerType::getInt64PtrTy(); +} + +// IntegerType +IntegerType* IntegerType::i64type_ = new IntegerType(); + +IntegerType::IntegerType() : + Type(Type::IntegerTy) { +} + +IntegerType::~IntegerType() { +} + +IntegerType* IntegerType::get(unsigned bits) { + return bits == 64 ? i64type_ : nullptr; +} + +unsigned IntegerType::getBitWidth() const { + return this == i64type_ ? 64 : 0; +} + +// PointerType +PointerType* PointerType::i64ptype_ = new PointerType(); + +PointerType::PointerType() : + Type(Type::PointerTy) +{ +} + +PointerType::~PointerType() { +} + +PointerType* PointerType::getInt64PtrTy() { + return i64ptype_; +} diff --git a/pool/shard001/C++/0018307_BattlegroundRV.cpp b/pool/shard001/C++/0018307_BattlegroundRV.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d16f3ac511599a613638cf9339c54492bca17c77 --- /dev/null +++ b/pool/shard001/C++/0018307_BattlegroundRV.cpp @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2005-2011 MaNGOS + * + * Copyright (C) 2008-2011 Trinity + * + * Copyright (C) 2010-2011 Project SkyFire + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "gamePCH.h" +#include "Battleground.h" +#include "BattlegroundRV.h" +#include "ObjectAccessor.h" +#include "Language.h" +#include "Player.h" +#include "WorldPacket.h" +#include "GameObject.h" + +BattlegroundRV::BattlegroundRV() +{ + m_BgObjects.resize(BG_RV_OBJECT_MAX); + + m_StartDelayTimes[BG_STARTING_EVENT_FIRST] = BG_START_DELAY_1M; + m_StartDelayTimes[BG_STARTING_EVENT_SECOND] = BG_START_DELAY_30S; + m_StartDelayTimes[BG_STARTING_EVENT_THIRD] = BG_START_DELAY_15S; + m_StartDelayTimes[BG_STARTING_EVENT_FOURTH] = BG_START_DELAY_NONE; + //we must set messageIds + m_StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_ARENA_ONE_MINUTE; + m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_ARENA_THIRTY_SECONDS; + m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_ARENA_FIFTEEN_SECONDS; + m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_ARENA_HAS_BEGUN; +} + +BattlegroundRV::~BattlegroundRV() +{ + +} + +void BattlegroundRV::Update(uint32 diff) +{ + Battleground::Update(diff); + + if (GetStatus() == STATUS_IN_PROGRESS) + { + if (GetStartTime() >= 47*MINUTE*IN_MILLISECONDS) // after 47 minutes without one team losing, the arena closes with no winner and no rating change + { + UpdateArenaWorldState(); + CheckArenaAfterTimerConditions(); + } + } + + if (getTimer() < diff) + { + uint32 i; + switch(getState()) + { + case BG_RV_STATE_OPEN_FENCES: + { + setTimer(BG_RV_PILAR_TO_FIRE_TIMER); + setState(BG_RV_STATE_CLOSE_FIRE); + break; + } + case BG_RV_STATE_CLOSE_FIRE: + for (i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i) + DoorClose(i); + setTimer(BG_RV_FIRE_TO_PILAR_TIMER); + setState(BG_RV_STATE_OPEN_PILARS); + break; + case BG_RV_STATE_OPEN_PILARS: + for (i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_PULLEY_2; ++i) + DoorOpen(i); + setTimer(BG_RV_PILAR_TO_FIRE_TIMER); + setState(BG_RV_STATE_OPEN_FIRE); + break; + case BG_RV_STATE_OPEN_FIRE: + for (i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i) + DoorOpen(i); + setTimer(BG_RV_FIRE_TO_PILAR_TIMER); + setState(BG_RV_STATE_CLOSE_PILARS); + break; + case BG_RV_STATE_CLOSE_PILARS: + uint32 i; + for (i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_PULLEY_2; ++i) + DoorOpen(i); + setTimer(BG_RV_PILAR_TO_FIRE_TIMER); + setState(BG_RV_STATE_CLOSE_FIRE); + break; + } + } + else + setTimer(getTimer() - diff); +} + +void BattlegroundRV::StartingEventCloseDoors() +{ +} + +void BattlegroundRV::StartingEventOpenDoors() +{ + // Buff respawn + SpawnBGObject(BG_RV_OBJECT_BUFF_1, 90); + SpawnBGObject(BG_RV_OBJECT_BUFF_2, 90); + // Open fences + DoorOpen(BG_RV_OBJECT_FENCE_1); + DoorOpen(BG_RV_OBJECT_FENCE_2); + // Elevators + DoorOpen(BG_RV_OBJECT_ELEVATOR_1); + DoorOpen(BG_RV_OBJECT_ELEVATOR_2); + + setState(BG_RV_STATE_OPEN_FENCES); + setTimer(BG_RV_FIRST_TIMER); +} + +void BattlegroundRV::AddPlayer(Player *plr) +{ + Battleground::AddPlayer(plr); + //create score and add it to map, default values are set in constructor + BattlegroundRVScore* sc = new BattlegroundRVScore; + + m_PlayerScores[plr->GetGUID()] = sc; + + UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE)); + UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE)); +} + +void BattlegroundRV::RemovePlayer(Player * /*plr*/, uint64 /*guid*/) +{ + if (GetStatus() == STATUS_WAIT_LEAVE) + return; + + UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE)); + UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE)); + + CheckArenaWinConditions(); +} + +void BattlegroundRV::HandleKillPlayer(Player *player, Player *killer) +{ + if (GetStatus() != STATUS_IN_PROGRESS) + return; + + if (!killer) + { + sLog->outError("BattlegroundRV: Killer player not found"); + return; + } + + Battleground::HandleKillPlayer(player, killer); + + UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE)); + UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE)); + + CheckArenaWinConditions(); +} + +bool BattlegroundRV::HandlePlayerUnderMap(Player *player) +{ + player->TeleportTo(GetMapId(), 763.5f, -284, 28.276f, 2.422f, false); + return true; +} + + +void BattlegroundRV::HandleAreaTrigger(Player *Source, uint32 Trigger) +{ + if (GetStatus() != STATUS_IN_PROGRESS) + return; + + switch(Trigger) + { + case 5224: + case 5226: + break; + default: + sLog->outError("WARNING: Unhandled AreaTrigger in Battleground: %u", Trigger); + Source->GetSession()->SendAreaTriggerMessage("Warning: Unhandled AreaTrigger in Battleground: %u", Trigger); + break; + } +} + +void BattlegroundRV::FillInitialWorldStates(WorldPacket &data) +{ + data << uint32(BG_RV_WORLD_STATE_A) << uint32(GetAlivePlayersCountByTeam(ALLIANCE)); + data << uint32(BG_RV_WORLD_STATE_H) << uint32(GetAlivePlayersCountByTeam(HORDE)); + data << uint32(BG_RV_WORLD_STATE) << uint32(1); +} + +void BattlegroundRV::Reset() +{ + //call parent's class reset + Battleground::Reset(); +} + +bool BattlegroundRV::SetupBattleground() +{ + // Fence + if (!AddObject(BG_RV_OBJECT_FENCE_1, BG_RV_OBJECT_TYPE_FENCE_1, 763.432373f, -274.058197f, 28.276695f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FENCE_2, BG_RV_OBJECT_TYPE_FENCE_2, 763.432373f, -294.419464f, 28.276684f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // elevators + || !AddObject(BG_RV_OBJECT_ELEVATOR_1, BG_RV_OBJECT_TYPE_ELEVATOR_1, 763.536377f, -294.535767f, 0.505383f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_ELEVATOR_2, BG_RV_OBJECT_TYPE_ELEVATOR_2, 763.506348f, -273.873352f, 0.505383f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // buffs + || !AddObject(BG_RV_OBJECT_BUFF_1, BG_RV_OBJECT_TYPE_BUFF_1, 735.551819f, -284.794678f, 28.276682f, 0.034906f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_BUFF_2, BG_RV_OBJECT_TYPE_BUFF_2, 791.224487f, -284.794464f, 28.276682f, 2.600535f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // fire + || !AddObject(BG_RV_OBJECT_FIRE_1, BG_RV_OBJECT_TYPE_FIRE_1, 743.543457f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIRE_2, BG_RV_OBJECT_TYPE_FIRE_2, 782.971802f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIREDOOR_1, BG_RV_OBJECT_TYPE_FIREDOOR_1, 743.711060f, -284.099609f, 27.542587f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_FIREDOOR_2, BG_RV_OBJECT_TYPE_FIREDOOR_2, 783.221252f, -284.133362f, 27.535686f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Gear + || !AddObject(BG_RV_OBJECT_GEAR_1, BG_RV_OBJECT_TYPE_GEAR_1, 763.664551f, -261.872986f, 26.686588f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_GEAR_2, BG_RV_OBJECT_TYPE_GEAR_2, 763.578979f, -306.146149f, 26.665222f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Pulley + || !AddObject(BG_RV_OBJECT_PULLEY_1, BG_RV_OBJECT_TYPE_PULLEY_1, 700.722290f, -283.990662f, 39.517582f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PULLEY_2, BG_RV_OBJECT_TYPE_PULLEY_2, 826.303833f, -283.996429f, 39.517582f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + // Pilars + || !AddObject(BG_RV_OBJECT_PILAR_1, BG_RV_OBJECT_TYPE_PILAR_1, 763.632385f, -306.162384f, 25.909504f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_2, BG_RV_OBJECT_TYPE_PILAR_2, 723.644287f, -284.493256f, 24.648525f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_3, BG_RV_OBJECT_TYPE_PILAR_3, 763.611145f, -261.856750f, 25.909504f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_4, BG_RV_OBJECT_TYPE_PILAR_4, 802.211609f, -284.493256f, 24.648525f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) +/* + // Pilars Collision - Fixme: Use the collision pilars - should make u break LoS + || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_1, BG_RV_OBJECT_TYPE_PILAR_COLLISION_1, 763.632385f, -306.162384f, 30.639660f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_2, BG_RV_OBJECT_TYPE_PILAR_COLLISION_2, 723.644287f, -284.493256f, 32.382710f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_3, BG_RV_OBJECT_TYPE_PILAR_COLLISION_3, 763.611145f, -261.856750f, 30.639660f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY) + || !AddObject(BG_RV_OBJECT_PILAR_COLLISION_4, BG_RV_OBJECT_TYPE_PILAR_COLLISION_4, 802.211609f, -284.493256f, 32.382710f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY) +*/ +) + { + sLog->outErrorDb("BatteGroundRV: Failed to spawn some object!"); + return false; + } + return true; +} diff --git a/pool/shard001/C++/0018313_MY_Scene_Menu.cpp b/pool/shard001/C++/0018313_MY_Scene_Menu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4ed8bf2669f00e9ada09fa773ebe5b8a20164b5 --- /dev/null +++ b/pool/shard001/C++/0018313_MY_Scene_Menu.cpp @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include + +#include +#include + +MY_Scene_Menu::MY_Scene_Menu(Game * _game) : + MY_Scene_Base(_game) +{ + // Create a linear layout to contain all of our menu items + // remember that these elements are all going to exist in the uiLayer, so we pass in its physics world in the constructors + VerticalLinearLayout * layout = new VerticalLinearLayout(uiLayer->world); + layout->horizontalAlignment = kCENTER; + layout->verticalAlignment = kMIDDLE; + // set the layout's size to 100% of its parent + layout->setRationalHeight(1.f, uiLayer); + layout->setRationalWidth(1.f, uiLayer); + + // Create some text labels + TextLabel * label6 = new TextLabel(uiLayer->world, font, textShader); + TextLabel * label7 = new TextLabel(uiLayer->world, font, textShader); + TextLabel * label8 = new TextLabel(uiLayer->world, font, textShader); + + // set the text on the labels + label6->setText("Quit Game"); + label7->setText("Play Game"); + label8->setText("Path Thing"); + + // make the labels' background visible (by default both the scene's clear colour and the text colour will be black) + label6->setBackgroundColour(1,1,1,1); + label7->setBackgroundColour(1,1,1,1); + label8->setBackgroundColour(1,1,1,1); + + // make the labels clickable + label6->setMouseEnabled(true); + label7->setMouseEnabled(true); + label8->setMouseEnabled(true); + + // add listeners to each label, making them buttons that take the player to different scenes + label6->eventManager->addEventListener("click", [&](sweet::Event * _event){ + game->exit(); + }); + label7->eventManager->addEventListener("click", [&](sweet::Event * _event){ + if(game->scenes.count("main") == 0){ + game->scenes["main"] = new MY_Scene_Main(game); + } + game->switchScene("main", false); + }); + label8->eventManager->addEventListener("click", [&](sweet::Event * _event){ + if(game->scenes.count("path") == 0){ + game->scenes["path"] = new MY_Scene_Path(game); + } + game->switchScene("path", false); + }); + + + // add the labels to the layout + layout->addChild(label6); + layout->addChild(label7); + layout->addChild(label8); + + // add the layout to the uiLayer + uiLayer->addChild(layout); + + uiLayer->invalidateLayout(); + + // add a mouse indicator (AKA a cursor) to the uiLayer so that the user can see what they're doing + uiLayer->addMouseIndicator(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0018325_MDaUCa.cpp b/pool/shard001/C++/0018325_MDaUCa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb4bcd16c53e19909f460e9e4dcab5327aeff9fa --- /dev/null +++ b/pool/shard001/C++/0018325_MDaUCa.cpp @@ -0,0 +1,92 @@ +//================================================================================================= +/*! +// \file src/mathtest/dmatsmatadd/MDaUCa.cpp +// \brief Source file for the MDaUCa dense matrix/sparse matrix addition math test +// +// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved +// +// This file is part of the Blaze library. You can redistribute it and/or modify it under +// the terms of the New (Revised) BSD License. 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. +// 3. Neither the names of the Blaze development group 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 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. +*/ +//================================================================================================= + + +//************************************************************************************************* +// Includes +//************************************************************************************************* + +#include +#include +#include +#include +#include +#include +#include +#include + + +//================================================================================================= +// +// MAIN FUNCTION +// +//================================================================================================= + +//************************************************************************************************* +int main() +{ + std::cout << " Running 'MDaUCa'..." << std::endl; + + using blazetest::mathtest::TypeA; + + try + { + // Matrix type definitions + typedef blaze::DynamicMatrix MDa; + typedef blaze::UpperMatrix< blaze::CompressedMatrix > UCa; + + // Creator type definitions + typedef blazetest::Creator CMDa; + typedef blazetest::Creator CUCa; + + // Running tests with small matrices + for( size_t i=0UL; i<=6UL; ++i ) { + for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) { + RUN_DMATSMATADD_OPERATION_TEST( CMDa( i, i ), CUCa( i, j ) ); + } + } + + // Running tests with large matrices + RUN_DMATSMATADD_OPERATION_TEST( CMDa( 67UL, 67UL ), CUCa( 67UL, 7UL ) ); + RUN_DMATSMATADD_OPERATION_TEST( CMDa( 128UL, 128UL ), CUCa( 128UL, 16UL ) ); + } + catch( std::exception& ex ) { + std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix addition:\n" + << ex.what() << "\n"; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} +//************************************************************************************************* diff --git a/pool/shard001/C++/0018334_ServerTransport.cpp b/pool/shard001/C++/0018334_ServerTransport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c28d975fac88243e682f9d2162f57bf5e44951ad --- /dev/null +++ b/pool/shard001/C++/0018334_ServerTransport.cpp @@ -0,0 +1,185 @@ + +//****************************************************************************** +// RCF - Remote Call Framework +// +// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved. +// http://www.deltavsoft.com +// +// RCF is distributed under dual licenses - closed source or GPL. +// Consult your particular license for conditions of use. +// +// If you have not purchased a commercial license, you are using RCF +// under GPL terms. +// +// Version: 2.0 +// Contact: support deltavsoft.com +// +//****************************************************************************** + +#include + +#include + +namespace RCF { + + ServerTransport::ServerTransport() : + mRpcProtocol(Rp_Rcf), + mCustomFraming(false), + mReadWriteMutex(WriterPriority), + mMaxMessageLength(getDefaultMaxMessageLength()), + mConnectionLimit(0), + mInitialNumberOfConnections(1) + {} + + ServerTransport & ServerTransport::setMaxMessageLength(std::size_t maxMessageLength) + { + return setMaxIncomingMessageLength(maxMessageLength); + } + + std::size_t ServerTransport::getMaxMessageLength() const + { + return getMaxIncomingMessageLength(); + } + + ServerTransport & ServerTransport::setMaxIncomingMessageLength(std::size_t maxMessageLength) + { + WriteLock writeLock(mReadWriteMutex); + mMaxMessageLength = maxMessageLength; + return *this; + } + + std::size_t ServerTransport::getMaxIncomingMessageLength() const + { + ReadLock readLock(mReadWriteMutex); + return mMaxMessageLength; + } + + std::size_t ServerTransport::getConnectionLimit() const + { + ReadLock readLock(mReadWriteMutex); + return mConnectionLimit; + } + + ServerTransport & ServerTransport::setConnectionLimit( + std::size_t connectionLimit) + { + WriteLock writeLock(mReadWriteMutex); + mConnectionLimit = connectionLimit; + + return *this; + } + + std::size_t ServerTransport::getInitialNumberOfConnections() const + { + ReadLock readLock(mReadWriteMutex); + return mInitialNumberOfConnections; + } + + ServerTransport & ServerTransport::setInitialNumberOfConnections( + std::size_t initialNumberOfConnections) + { + WriteLock writeLock(mReadWriteMutex); + mInitialNumberOfConnections = initialNumberOfConnections; + + return *this; + } + + void ServerTransport::setRpcProtocol(RpcProtocol rpcProtocol) + { + mRpcProtocol = rpcProtocol; + + // For JSON-RPC over HTTP/S, enable HTTP framing. + if (rpcProtocol == Rp_JsonRpc) + { + TransportType tt = getTransportType(); + if (tt == Tt_Http || tt == Tt_Https) + { + mCustomFraming = true; + } + } + } + + RpcProtocol ServerTransport::getRpcProtocol() const + { + return mRpcProtocol; + } + + ServerTransport & ServerTransport::setThreadPool( + ThreadPoolPtr threadPoolPtr) + { + I_Service & svc = dynamic_cast(*this); + svc.setThreadPool(threadPoolPtr); + return *this; + } + + ServerTransport & ServerTransport::setSupportedProtocols(const std::vector & protocols) + { + mSupportedProtocols = protocols; + return *this; + } + + const std::vector & ServerTransport::getSupportedProtocols() const + { + return mSupportedProtocols; + } + + std::size_t gDefaultMaxMessageLength = 1024*1024; // 1 Mb + + std::size_t getDefaultMaxMessageLength() + { + return gDefaultMaxMessageLength; + } + + void setDefaultMaxMessageLength(std::size_t maxMessageLength) + { + gDefaultMaxMessageLength = maxMessageLength; + } + + NetworkSession::NetworkSession() : + mEnableReconnect(true), + mBytesReceivedCounter(0), + mBytesSentCounter(0), + mLastActivityTimestampMs(0) + { + } + + NetworkSession::~NetworkSession() + { + } + + void NetworkSession::setEnableReconnect(bool enableReconnect) + { + mEnableReconnect = enableReconnect; + } + + bool NetworkSession::getEnableReconnect() + { + return mEnableReconnect; + } + + boost::uint64_t NetworkSession::getTotalBytesReceived() const + { + return mBytesReceivedCounter; + } + + boost::uint64_t NetworkSession::getTotalBytesSent() const + { + return mBytesSentCounter; + } + + SessionPtr NetworkSession::getSessionPtr() const + { + return mRcfSessionPtr; + } + + boost::uint32_t NetworkSession::getLastActivityTimestamp() const + { + return mLastActivityTimestampMs; + } + + void NetworkSession::setLastActivityTimestamp() + { + mLastActivityTimestampMs = RCF::getCurrentTimeMs(); + } + +} // namespace RCF diff --git a/pool/shard001/C++/0018337_ChannelStream.cpp b/pool/shard001/C++/0018337_ChannelStream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75afc7b5d33d2a2e9155d910b9db728fb7cd18e6 --- /dev/null +++ b/pool/shard001/C++/0018337_ChannelStream.cpp @@ -0,0 +1,208 @@ +// +// ChannelStream.cpp +// +// $Id: //poco/1.6/RemotingNG/TCP/src/ChannelStream.cpp#1 $ +// +// Library: RemotingNG/TCP +// Package: TCP +// Module: ChannelStream +// +// Copyright (c) 2006-2012, Applied Informatics Software Engineering GmbH. +// All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + + +#include "Poco/RemotingNG/TCP/ChannelStream.h" + + +namespace Poco { +namespace RemotingNG { +namespace TCP { + + +// +// ChannelStreamBuf +// + + +ChannelStreamBuf::ChannelStreamBuf(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::Timespan timeout): + Poco::BufferedStreamBuf(Frame::FRAME_MAX_PAYLOAD_SIZE + 4, std::ios::in), + _pConnection(pConnection), + _pQueue(new FrameQueue(pConnection, frameType, channel)), + _timeout(timeout) +{ + _pConnection->pushFrameHandler(_pQueue); +} + + +ChannelStreamBuf::ChannelStreamBuf(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::UInt16 flags): + Poco::BufferedStreamBuf(Frame::FRAME_MAX_PAYLOAD_SIZE, std::ios::out), + _pConnection(pConnection), + _pFrame(new Frame(frameType, channel, flags, Frame::FRAME_MAX_SIZE)) +{ +} + + +ChannelStreamBuf::~ChannelStreamBuf() +{ + try + { + if (_pQueue) + { + _pConnection->popFrameHandler(_pQueue); + } + } + catch (...) + { + poco_unexpected(); + } +} + + +void ChannelStreamBuf::close() +{ + if (!_pFrame) return; + + _pFrame->updateFlags(_pFrame->flags() | Frame::FRAME_FLAG_EOM); + if (pptr() && pptr() > pbase()) + { + sync(); + } + else + { + _pFrame->setPayloadSize(0); + _pConnection->sendFrame(_pFrame); + } + _pFrame = 0; +} + + +FrameQueue::Ptr ChannelStreamBuf::queue() +{ + return _pQueue; +} + + +Connection::Ptr ChannelStreamBuf::connection() +{ + return _pConnection; +} + + +int ChannelStreamBuf::readFromDevice(char* buffer, std::streamsize length) +{ + if (_pQueue) + { + Frame::Ptr pFrame = _pQueue->dequeueFrame(_timeout); + if (pFrame) + { + poco_assert (length >= pFrame->getPayloadSize()); + std::memcpy(buffer, pFrame->payloadBegin(), pFrame->getPayloadSize()); + int n = static_cast(pFrame->getPayloadSize()); + bool eof = (pFrame->flags() & Frame::FRAME_FLAG_EOM) != 0; + _pConnection->returnFrame(pFrame); + if (eof) + { + _pConnection->popFrameHandler(_pQueue); + _pQueue = 0; + } + return n; + } + else return -1; + } + else return 0; +} + + +int ChannelStreamBuf::writeToDevice(const char* buffer, std::streamsize length) +{ + poco_assert (length <= _pFrame->maxPayloadSize()); + + std::memcpy(_pFrame->payloadBegin(), buffer, static_cast(length)); + _pFrame->setPayloadSize(static_cast(length)); + _pConnection->sendFrame(_pFrame); + _pFrame->updateFlags(_pFrame->flags() | Frame::FRAME_FLAG_CONT); + return static_cast(length); +} + + +// +// ChannelIOS +// + + +ChannelIOS::ChannelIOS(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::Timespan timeout): + _buf(pConnection, frameType, channel, timeout) +{ + poco_ios_init(&_buf); +} + + +ChannelIOS::ChannelIOS(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::UInt16 flags): + _buf(pConnection, channel, frameType, flags) +{ + poco_ios_init(&_buf); +} + + +ChannelIOS::~ChannelIOS() +{ + try + { + _buf.close(); + } + catch (...) + { + } +} + + +ChannelStreamBuf* ChannelIOS::rdbuf() +{ + return &_buf; +} + + +void ChannelIOS::close() +{ + _buf.close(); +} + + +// +// ChannelInputStream +// + + +ChannelInputStream::ChannelInputStream(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::Timespan timeout): + ChannelIOS(pConnection, frameType, channel, timeout), + std::istream(&_buf) +{ +} + + +ChannelInputStream::~ChannelInputStream() +{ +} + + +// +// ChannelOutputStream +// + + +ChannelOutputStream::ChannelOutputStream(Connection::Ptr pConnection, Poco::UInt32 frameType, Poco::UInt32 channel, Poco::UInt16 flags): + ChannelIOS(pConnection, channel, frameType, flags), + std::ostream(&_buf) +{ +} + + +ChannelOutputStream::~ChannelOutputStream() +{ +} + + +} } } // namespace Poco::RemotingNG::TCP diff --git a/pool/shard001/C++/0018343_thread.cpp b/pool/shard001/C++/0018343_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..744d1729906bf2d6279e50ebfcac080ff87a85ce --- /dev/null +++ b/pool/shard001/C++/0018343_thread.cpp @@ -0,0 +1,69 @@ +/* +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. + +Author: Leonardo de Moura +*/ +#include +#include +#include "api/lean.h" + +void check_core(int v, unsigned l) { + if (!v) { + printf("Test failed at line %d\n", l); + exit(1); + } +} + +#define check(v) check_core(v, __LINE__) + +lean_name mk_name(char const * n) { + lean_exception ex; + lean_name a, r; + check(lean_name_mk_anonymous(&a, &ex)); + check(lean_name_mk_str(a, n, &r, &ex)); + lean_name_del(a); + return r; +} + +lean_list_name mk_unary_name_list(lean_name u) { + lean_exception ex; + lean_list_name n, r; + check(lean_list_name_mk_nil(&n, &ex)); + check(lean_list_name_mk_cons(u, n, &r, &ex)); + lean_list_name_del(n); + return r; +} + +lean_env mk_env() { + lean_exception ex; + lean_env r; + check(lean_env_mk_std(LEAN_TRUST_HIGH, &r, &ex)); + return r; +} + +void test_import() { + lean_exception ex; + lean_env env = mk_env(); + lean_name std = mk_name("standard"); + lean_list_name ms = mk_unary_name_list(std); + lean_options o; + lean_ios ios; + lean_env new_env; + check(lean_options_mk_empty(&o, &ex)); + check(lean_ios_mk_std(o, &ios, &ex)); + check(lean_env_import(env, ios, ms, &new_env, &ex)); + std::cout << "standard library has been imported\n"; + lean_env_del(env); + lean_env_del(new_env); + lean_name_del(std); + lean_list_name_del(ms); + lean_options_del(o); + lean_ios_del(ios); +} + +int main() { + std::thread t1(test_import); + t1.join(); + return 0; +} diff --git a/pool/shard001/C++/0018345_image_viewer.cpp b/pool/shard001/C++/0018345_image_viewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db4f48d2c57372b6ec30953e56cd8e9211c1803b --- /dev/null +++ b/pool/shard001/C++/0018345_image_viewer.cpp @@ -0,0 +1,81 @@ +/* + * 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 +#ifndef Q_MOC_RUN +#include +#endif +#include +#include +#include //fps calculations +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +int +main (int, char ** argv) +{ + pcl::PCDReader reader; + pcl::PCLPointCloud2 cloud; + reader.read (argv[1], cloud); + + pcl::PointCloud xyz; + pcl::fromPCLPointCloud2 (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/shard001/C++/0018346_drive_integration_service_unittest.cc b/pool/shard001/C++/0018346_drive_integration_service_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd32d69d65f09b62738a4761649ffb6e9cf9ca18 --- /dev/null +++ b/pool/shard001/C++/0018346_drive_integration_service_unittest.cc @@ -0,0 +1,52 @@ +// 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/ash/drive/drive_integration_service.h" + +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile.h" +#include "chrome/test/base/testing_profile_manager.h" +#include "content/public/test/browser_task_environment.h" +#include "content/public/test/test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace drive { + +class DriveIntegrationServiceTest : public testing::Test { + public: + DriveIntegrationServiceTest() + : profile_manager_(TestingBrowserProcess::GetGlobal()) {} + + void SetUp() override { ASSERT_TRUE(profile_manager_.SetUp()); } + + protected: + content::BrowserTaskEnvironment task_environment_; + // DriveIntegrationService depends on DriveNotificationManager which depends + // on InvalidationService. On Chrome OS, the InvalidationServiceFactory + // uses chromeos::ProfileHelper, which needs the ProfileManager or a + // TestProfileManager to be running. + TestingProfileManager profile_manager_; +}; + +// This test is flaky on chromeos. +// https://crbug.com/943376 +TEST_F(DriveIntegrationServiceTest, DISABLED_ServiceInstanceIdentity) { + TestingProfile* user1 = profile_manager_.CreateTestingProfile("user1"); + + // Integration Service is created as a profile keyed service. + EXPECT_TRUE(DriveIntegrationServiceFactory::GetForProfile(user1)); + + // Shares the same instance with the incognito mode profile. + Profile* user1_incognito = + user1->GetPrimaryOTRProfile(/*create_if_needed=*/true); + EXPECT_EQ(DriveIntegrationServiceFactory::GetForProfile(user1), + DriveIntegrationServiceFactory::GetForProfile(user1_incognito)); + + // For different profiles, different services are running. + TestingProfile* user2 = profile_manager_.CreateTestingProfile("user2"); + EXPECT_NE(DriveIntegrationServiceFactory::GetForProfile(user1), + DriveIntegrationServiceFactory::GetForProfile(user2)); +} + +} // namespace drive diff --git a/pool/shard001/C++/0018363_MyGUI_OpenGLRTTexture.cpp b/pool/shard001/C++/0018363_MyGUI_OpenGLRTTexture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a4ed15dc407cf12ada0a89d29a7283e83c0f52b --- /dev/null +++ b/pool/shard001/C++/0018363_MyGUI_OpenGLRTTexture.cpp @@ -0,0 +1,101 @@ +/*! + @file + @author Albert Semenov + @date 12/2009 +*/ + +#include "MyGUI_OpenGLRTTexture.h" +#include "MyGUI_OpenGLRenderManager.h" +#include "MyGUI_OpenGLDiagnostic.h" + +#include "GL/glew.h" + +namespace MyGUI +{ + + OpenGLRTTexture::OpenGLRTTexture(unsigned int _texture) : + mTextureID(_texture), + mWidth(0), + mHeight(0), + mFBOID(0), + mRBOID(0) + { + int miplevel = 0; + glBindTexture(GL_TEXTURE_2D, mTextureID); + glGetTexLevelParameteriv(GL_TEXTURE_2D, miplevel, GL_TEXTURE_WIDTH, &mWidth); + glGetTexLevelParameteriv(GL_TEXTURE_2D, miplevel, GL_TEXTURE_HEIGHT, &mHeight); + glBindTexture(GL_TEXTURE_2D, 0); + + mRenderTargetInfo.maximumDepth = 1.0f; + mRenderTargetInfo.hOffset = 0; + mRenderTargetInfo.vOffset = 0; + mRenderTargetInfo.aspectCoef = float(mHeight) / float(mWidth); + mRenderTargetInfo.pixScaleX = 1.0f / float(mWidth); + mRenderTargetInfo.pixScaleY = 1.0f / float(mHeight); + + // create a framebuffer object, you need to delete them when program exits. + glGenFramebuffersEXT(1, &mFBOID); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFBOID); + + // create a renderbuffer object to store depth info + // NOTE: A depth renderable image should be attached the FBO for depth test. + // If we don't attach a depth renderable image to the FBO, then + // the rendering output will be corrupted because of missing depth test. + // If you also need stencil test for your rendering, then you must + // attach additional image to the stencil attachement point, too. + glGenRenderbuffersEXT(1, &mRBOID); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRBOID); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, mWidth, mHeight); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); + + // attach a texture to FBO color attachement point + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, mTextureID, 0); + + // attach a renderbuffer to depth attachment point + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mRBOID); + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + } + + OpenGLRTTexture::~OpenGLRTTexture() + { + if (mFBOID != 0) + { + glDeleteFramebuffersEXT(1, &mFBOID); + mFBOID = 0; + } + if (mRBOID != 0) + { + glDeleteRenderbuffersEXT(1, &mRBOID); + mRBOID = 0; + } + } + + void OpenGLRTTexture::begin() + { + glPushAttrib(GL_VIEWPORT_BIT); + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFBOID); + + glViewport(0, 0, mWidth, mHeight); + + OpenGLRenderManager::getInstance().begin(); + glOrtho(-1, 1, 1, -1, -1, 1); + glClear(GL_COLOR_BUFFER_BIT/* | GL_DEPTH_BUFFER_BIT*/); + } + + void OpenGLRTTexture::end() + { + OpenGLRenderManager::getInstance().end(); + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // unbind + + glPopAttrib(); + } + + void OpenGLRTTexture::doRender(IVertexBuffer* _buffer, ITexture* _texture, size_t _count) + { + OpenGLRenderManager::getInstance().doRender(_buffer, _texture, _count); + } + +} // namespace MyGUI diff --git a/pool/shard001/C++/0018366_9507.cc b/pool/shard001/C++/0018366_9507.cc new file mode 100644 index 0000000000000000000000000000000000000000..db96e4cbc693536aa18e877e8550775d870f6a8c --- /dev/null +++ b/pool/shard001/C++/0018366_9507.cc @@ -0,0 +1,70 @@ +// { dg-require-mkfifo "" } + +// Copyright (C) 2001-2021 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 +// . + +// 27.8.1.3 filebuf member functions +// @require@ %-*.tst %-*.txt +// @diff@ %-*.tst %-*.txt + +// various tests for filebuf::open() and filebuf::close() including +// the non-portable functionality in the libstdc++-v3 IO library + +#include +#include +#include +#include +#include +#include +#include + +// libstdc++/9507 +void test_06() +{ + using namespace __gnu_test; + const char* name = "tmp_fifo2"; + + signal(SIGPIPE, SIG_IGN); + + unlink(name); + mkfifo(name, S_IRWXU); + + std::filebuf fbuf; + // The use of ios_base::ate implies an attempt to seek on the file + // descriptor. The seek will fail. Thus, at the OS level, this + // call to "fbuf.open" will result in a call to "open" (which will + // succeed), a call to "lseek" (which will fail), and, finally, a + // call to "close" (which will succeed). Thus, after this call, the + // file should be closed. + std::filebuf* r = fbuf.open(name, + std::ios_base::in + | std::ios_base::out + | std::ios_base::ate); + if (!r) + VERIFY( !fbuf.is_open() ); + else + VERIFY( fbuf.is_open() ); +} + +int +main() +{ + test_06(); + return 0; +} + + diff --git a/pool/shard001/C++/0018374_systemsolver.cpp b/pool/shard001/C++/0018374_systemsolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce3056d196b432ca05c7a49fc3b3d52833e13a8f --- /dev/null +++ b/pool/shard001/C++/0018374_systemsolver.cpp @@ -0,0 +1,90 @@ +#include "systemsolver.h" + +#include +#include <%EIGEN_USER_NAME%/eigen/Dense> +extern "C" +{ +#include "%CSPARSE_USER_NAME%/csparse/cs.h" +} +using namespace Eigen; + +vector SystemSolver::SolveSparse(vector valuesB) +{ +//THe matrix A + vector values; + vector rows; + vector nums; + int num=0; + + for(sparseMatrix::const_iterator it=matrix.begin();it!=matrix.end();it++) + { + const sparseCol& col=it->second; + for(sparseCol::const_iterator it2=col.begin();it2!=col.end();it2++) + { + values.push_back(it2->second); + rows.push_back(it2->first); + } + nums.push_back(num); + num+=col.size(); + } + nums.push_back(num); + + cs_sparse A; + int nnz=values.size(); + A.nzmax=nnz; + A.m=num_row; + A.n=num_col; + A.x=new double[nnz]; + A.nz=-1;//column-compressed (not triplet) + + A.p =new ptrdiff_t[num_col+1]; /// column pointers (size n+1) or col indices (size nzmax) + A.i=new ptrdiff_t[nnz] ; /* row indices, size nzmax */ + + unsigned int i; + for(i=0;i ret(valuesB.size()); + + memcpy(&ret[0],b,sizeof(double)*valuesB.size()); + + //log<<"Time: "< SystemSolver::SolveDense(vector valuesB) +{ + int size=max(num_col,num_row); + MatrixXd A=MatrixXd::Zero(size,size); + + for(sparseMatrix::const_iterator it=matrix.begin();it!=matrix.end();it++) + { + const sparseCol& col=it->second; + for(sparseCol::const_iterator it2=col.begin();it2!=col.end();it2++) + { + A(it->first,it2->first)=it2->second; + } + } + VectorXd b(valuesB.size()); + for(int i=0;i ret(valuesB.size()); + for(int i=0;i cr, const int width, const int height) const{ + // now draw a circle + cr->save(); + cr->arc(x_*width, y_*height, radius_*width, 0.0, 2.0 * M_PI); // full circle + cr->set_source_rgba(0.0, 0.0, 0.8, 0.6); // partially translucent + cr->fill_preserve(); + cr->restore(); // back to opaque black + cr->stroke(); +} + + void Circle::handleEvent(const double& x, const double& y) + { + x_ = x; + y_ = y; + } diff --git a/pool/shard001/C++/0018381_DVecSVecCross.cpp b/pool/shard001/C++/0018381_DVecSVecCross.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6bfe353cccc944ae5af7fc3565ef183b8eda629 --- /dev/null +++ b/pool/shard001/C++/0018381_DVecSVecCross.cpp @@ -0,0 +1,126 @@ +//================================================================================================= +/*! +// \file src/blaze/DVecSVecCross.cpp +// \brief Source file for the Blaze dense vector/sparse vector cross product kernel +// +// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved +// +// This file is part of the Blaze library. You can redistribute it and/or modify it under +// the terms of the New (Revised) BSD License. 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. +// 3. Neither the names of the Blaze development group 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 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. +*/ +//================================================================================================= + + +//************************************************************************************************* +// Includes +//************************************************************************************************* + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace blazemark { + +namespace blaze { + +//================================================================================================= +// +// KERNEL FUNCTIONS +// +//================================================================================================= + +//************************************************************************************************* +/*!\brief Blaze dense vector/sparse vector cross product kernel. +// +// \param N The number of cross products to be computed. +// \param F The number of non-zero elements for the sparse vector. +// \param steps The number of iteration steps to perform. +// \return Minimum runtime of the kernel function. +// +// This kernel function implements the dense vector/sparse vector cross product by means of +// the Blaze functionality. +*/ +double dvecsveccross( size_t N, size_t F, size_t steps ) +{ + using ::blazemark::element_t; + using ::blaze::columnVector; + + typedef ::blaze::StaticVector VectorType; + typedef ::blaze::AlignedAllocator AllocatorType; + + ::blaze::setSeed( seed ); + + ::std::vector< VectorType, AllocatorType > a( N ), c( N ); + ::std::vector< ::blaze::CompressedVector > b( N ); + ::blaze::timing::WcTimer timer; + + for( size_t i=0UL; i maxtime ) + break; + } + + const double minTime( timer.min() ); + const double avgTime( timer.average() ); + + if( minTime * ( 1.0 + deviation*0.01 ) < avgTime ) + std::cerr << " Blaze kernel 'dvecsveccross': Time deviation too large!!!\n"; + + return minTime; +} +//************************************************************************************************* + +} // namespace blaze + +} // namespace blazemark diff --git a/pool/shard001/C++/0018383_juce_ChildProcess.cpp b/pool/shard001/C++/0018383_juce_ChildProcess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98dc84af09f50019d215263648f03acd4ff692cf --- /dev/null +++ b/pool/shard001/C++/0018383_juce_ChildProcess.cpp @@ -0,0 +1,118 @@ +/* + ============================================================================== + + This file is part of the JUCE library. + Copyright (c) 2017 - ROLI Ltd. + + JUCE is an open source library subject to commercial or open-source + licensing. + + The code included in this file is provided under the terms of the ISC license + http://www.isc.org/downloads/software-support-policy/isc-license. Permission + To use, copy, modify, and/or distribute this software for any purpose with or + without fee is hereby granted provided that the above copyright notice and + this permission notice appear in all copies. + + JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER + EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE + DISCLAIMED. + + ============================================================================== +*/ + +namespace juce +{ + +ChildProcess::ChildProcess() {} +ChildProcess::~ChildProcess() {} + +bool ChildProcess::isRunning() const +{ + return activeProcess != nullptr && activeProcess->isRunning(); +} + +int ChildProcess::readProcessOutput (void* dest, int numBytes) +{ + return activeProcess != nullptr ? activeProcess->read (dest, numBytes) : 0; +} + +bool ChildProcess::kill() +{ + return activeProcess == nullptr || activeProcess->killProcess(); +} + +uint32 ChildProcess::getExitCode() const +{ + return activeProcess != nullptr ? activeProcess->getExitCode() : 0; +} + +bool ChildProcess::waitForProcessToFinish (const int timeoutMs) const +{ + auto timeoutTime = Time::getMillisecondCounter() + (uint32) timeoutMs; + + do + { + if (! isRunning()) + return true; + + Thread::sleep (2); + } + while (timeoutMs < 0 || Time::getMillisecondCounter() < timeoutTime); + + return false; +} + +String ChildProcess::readAllProcessOutput() +{ + MemoryOutputStream result; + + for (;;) + { + char buffer[512]; + auto num = readProcessOutput (buffer, sizeof (buffer)); + + if (num <= 0) + break; + + result.write (buffer, (size_t) num); + } + + return result.toString(); +} + + +//============================================================================== +//============================================================================== +#if JUCE_UNIT_TESTS + +class ChildProcessTests : public UnitTest +{ +public: + ChildProcessTests() + : UnitTest ("ChildProcess", UnitTestCategories::threads) + {} + + void runTest() override + { + beginTest ("Child Processes"); + + #if JUCE_WINDOWS || JUCE_MAC || JUCE_LINUX + ChildProcess p; + + #if JUCE_WINDOWS + expect (p.start ("tasklist")); + #else + expect (p.start ("ls /")); + #endif + + auto output = p.readAllProcessOutput(); + expect (output.isNotEmpty()); + #endif + } +}; + +static ChildProcessTests childProcessUnitTests; + +#endif + +} // namespace juce diff --git a/pool/shard001/C++/0018391_boss_amnennar_the_coldbringer.cpp b/pool/shard001/C++/0018391_boss_amnennar_the_coldbringer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6aaa0b7d2a0ec73ba4d41c40c33aafad29ac616 --- /dev/null +++ b/pool/shard001/C++/0018391_boss_amnennar_the_coldbringer.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2011-2012 DarkCore + * Copyright (C) 2011-2012 Project SkyFire + * Copyright (C) 2008-2012 TrinityCore + * Copyright (C) 2005-2012 MaNGOS + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 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 . + */ + + +/* ScriptData +SDName: Boss_Amnennar_the_coldbringer +SD%Complete: 100 +SDComment: +SDCategory: Razorfen Downs +EndScriptData */ + +#include "ScriptPCH.h" + +#define SAY_AGGRO -1129000 +#define SAY_SUMMON60 -1129001 +#define SAY_SUMMON30 -1129002 +#define SAY_HP -1129003 +#define SAY_KILL -1129004 + +#define SPELL_AMNENNARSWRATH 13009 +#define SPELL_FROSTBOLT 15530 +#define SPELL_FROST_NOVA 15531 +#define SPELL_FROST_SPECTRES 12642 + +class boss_amnennar_the_coldbringer : public CreatureScript +{ +public: + boss_amnennar_the_coldbringer() : CreatureScript("boss_amnennar_the_coldbringer") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_amnennar_the_coldbringerAI (creature); + } + + struct boss_amnennar_the_coldbringerAI : public ScriptedAI + { + boss_amnennar_the_coldbringerAI(Creature* c) : ScriptedAI(c) {} + + uint32 AmnenarsWrath_Timer; + uint32 FrostBolt_Timer; + uint32 FrostNova_Timer; + bool Spectrals60; + bool Spectrals30; + bool Hp; + + void Reset() + { + AmnenarsWrath_Timer = 8000; + FrostBolt_Timer = 1000; + FrostNova_Timer = urand(10000, 15000); + Spectrals30 = false; + Spectrals60 = false; + Hp = false; + } + + void EnterCombat(Unit* /*who*/) + { + DoScriptText(SAY_AGGRO, me); + } + + void KilledUnit(Unit* /*victim*/) + { + DoScriptText(SAY_KILL, me); + } + + void UpdateAI(const uint32 diff) + { + if (!UpdateVictim()) + return; + + //AmnenarsWrath_Timer + if (AmnenarsWrath_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_AMNENNARSWRATH); + AmnenarsWrath_Timer = 12000; + } else AmnenarsWrath_Timer -= diff; + + //FrostBolt_Timer + if (FrostBolt_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_FROSTBOLT); + FrostBolt_Timer = 8000; + } else FrostBolt_Timer -= diff; + + if (FrostNova_Timer <= diff) + { + DoCast(me, SPELL_FROST_NOVA); + FrostNova_Timer = 15000; + } else FrostNova_Timer -= diff; + + if (!Spectrals60 && HealthBelowPct(60)) + { + DoScriptText(SAY_SUMMON60, me); + DoCast(me->getVictim(), SPELL_FROST_SPECTRES); + Spectrals60 = true; + } + + if (!Hp && HealthBelowPct(50)) + { + DoScriptText(SAY_HP, me); + Hp = true; + } + + if (!Spectrals30 && HealthBelowPct(30)) + { + DoScriptText(SAY_SUMMON30, me); + DoCast(me->getVictim(), SPELL_FROST_SPECTRES); + Spectrals30 = true; + } + + DoMeleeAttackIfReady(); + } + }; +}; + +void AddSC_boss_amnennar_the_coldbringer() +{ + new boss_amnennar_the_coldbringer(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0018394_SubmitStaging.cpp b/pool/shard001/C++/0018394_SubmitStaging.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4c0654c396a8a56d630eed752208bfb05572fd8 --- /dev/null +++ b/pool/shard001/C++/0018394_SubmitStaging.cpp @@ -0,0 +1,66 @@ +#include + +#include +#include +#include + +#include + +namespace GHULBUS_VULKAN_NAMESPACE +{ +void SubmitStaging::addWaitingSemaphore(Semaphore& semaphore, VkPipelineStageFlags stage_to_wait) +{ + m_waitingSemaphores.push_back(semaphore.getVkSemaphore()); + m_waitingSemaphoreStageFlags.push_back(stage_to_wait); +} + +void SubmitStaging::addSignalingSemaphore(Semaphore& semaphore) +{ + m_signallingSemaphores.push_back(semaphore.getVkSemaphore()); +} + +void SubmitStaging::addCommandBuffer(CommandBuffer& command_buffer) +{ + m_commandBuffers.push_back(command_buffer.getVkCommandBuffer()); +} + +void SubmitStaging::addCommandBuffers(CommandBuffers& command_buffers) +{ + VkCommandBuffer* p = command_buffers.getVkCommandBuffers(); + m_commandBuffers.insert(m_commandBuffers.end(), p, p + command_buffers.size()); +} + +void SubmitStaging::addCleanupCallback(Callback cb) +{ + m_callbacks.emplace_back(std::move(cb)); +} + +void SubmitStaging::performCleanup() +{ + for (auto& cb : m_callbacks) { + Callback c = std::move(cb); + c(); + } + m_callbacks.clear(); +} + +VkSubmitInfo SubmitStaging::getVkSubmitInfo() const +{ + VkSubmitInfo submit_info; + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.pNext = nullptr; + std::vector const& ws = m_waitingSemaphores; + submit_info.waitSemaphoreCount = static_cast(ws.size()); + submit_info.pWaitSemaphores = (ws.empty()) ? nullptr : ws.data(); + std::vector const& wsf = m_waitingSemaphoreStageFlags; + GHULBUS_ASSERT(wsf.size() == ws.size()); + submit_info.pWaitDstStageMask = (ws.empty()) ? nullptr : wsf.data(); + std::vector const& cb = m_commandBuffers; + submit_info.commandBufferCount = static_cast(cb.size()); + submit_info.pCommandBuffers = (cb.empty()) ? nullptr : cb.data(); + std::vector const& ss = m_signallingSemaphores; + submit_info.signalSemaphoreCount = static_cast(ss.size()); + submit_info.pSignalSemaphores = (ss.empty()) ? nullptr : ss.data(); + return submit_info; +} +} diff --git a/pool/shard001/C++/0018401_launchd_interception_server.cc b/pool/shard001/C++/0018401_launchd_interception_server.cc new file mode 100644 index 0000000000000000000000000000000000000000..06f10812e4f358384095ef92dbbd8c9052bc5fcd --- /dev/null +++ b/pool/shard001/C++/0018401_launchd_interception_server.cc @@ -0,0 +1,153 @@ +// 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 "sandbox/mac/launchd_interception_server.h" + +#include + +#include "base/logging.h" +#include "base/mac/mach_logging.h" +#include "sandbox/mac/bootstrap_sandbox.h" +#include "sandbox/mac/mach_message_server.h" + +namespace sandbox { + +// The buffer size for all launchd messages. This comes from +// sizeof(union __RequestUnion__vproc_mig_job_subsystem) in launchd, and it +// is larger than the __ReplyUnion. +const mach_msg_size_t kBufferSize = 2096; + +LaunchdInterceptionServer::LaunchdInterceptionServer( + const BootstrapSandbox* sandbox) + : sandbox_(sandbox), + sandbox_port_(MACH_PORT_NULL), + compat_shim_(GetLaunchdCompatibilityShim()) { +} + +LaunchdInterceptionServer::~LaunchdInterceptionServer() { +} + +bool LaunchdInterceptionServer::Initialize(mach_port_t server_receive_right) { + mach_port_t task = mach_task_self(); + kern_return_t kr; + + // Allocate the dummy sandbox port. + mach_port_t port; + if ((kr = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &port)) != + KERN_SUCCESS) { + MACH_LOG(ERROR, kr) << "Failed to allocate dummy sandbox port."; + return false; + } + sandbox_port_.reset(port); + if ((kr = mach_port_insert_right(task, sandbox_port_, sandbox_port_, + MACH_MSG_TYPE_MAKE_SEND) != KERN_SUCCESS)) { + MACH_LOG(ERROR, kr) << "Failed to allocate dummy sandbox port send right."; + return false; + } + sandbox_send_port_.reset(sandbox_port_); + + message_server_.reset( + new MachMessageServer(this, server_receive_right, kBufferSize)); + return message_server_->Initialize(); +} + +void LaunchdInterceptionServer::DemuxMessage(IPCMessage request) { + const uint64_t message_id = compat_shim_.ipc_message_get_id(request); + VLOG(3) << "Incoming message #" << message_id; + + pid_t sender_pid = message_server_->GetMessageSenderPID(request); + const BootstrapSandboxPolicy* policy = + sandbox_->PolicyForProcess(sender_pid); + if (policy == NULL) { + // No sandbox policy is in place for the sender of this message, which + // means it came from the unknown. Reject it. + VLOG(3) << "Message from unknown pid " << sender_pid << " rejected."; + message_server_->RejectMessage(request, MIG_REMOTE_ERROR); + return; + } + + if (message_id == compat_shim_.msg_id_look_up2) { + // Filter messages sent via bootstrap_look_up to enforce the sandbox policy + // over the bootstrap namespace. + HandleLookUp(request, policy); + } else if (message_id == compat_shim_.msg_id_swap_integer) { + // Ensure that any vproc_swap_integer requests are safe. + HandleSwapInteger(request); + } else { + // All other messages are not permitted. + VLOG(1) << "Rejecting unhandled message #" << message_id; + message_server_->RejectMessage(request, MIG_REMOTE_ERROR); + } +} + +void LaunchdInterceptionServer::HandleLookUp( + IPCMessage request, + const BootstrapSandboxPolicy* policy) { + const std::string request_service_name( + compat_shim_.look_up2_get_request_name(request)); + VLOG(2) << "Incoming look_up2 request for " << request_service_name; + + // Find the Rule for this service. If a named rule is not found, use the + // default specified by the policy. + const BootstrapSandboxPolicy::NamedRules::const_iterator it = + policy->rules.find(request_service_name); + Rule rule(policy->default_rule); + if (it != policy->rules.end()) + rule = it->second; + + if (rule.result == POLICY_ALLOW) { + // This service is explicitly allowed, so this message will not be + // intercepted by the sandbox. + VLOG(1) << "Permitting and forwarding look_up2: " << request_service_name; + ForwardMessage(request); + } else if (rule.result == POLICY_DENY_ERROR) { + // The child is not permitted to look up this service. Send a MIG error + // reply to the client. Returning a NULL or unserviced port for a look up + // can cause clients to crash or hang. + VLOG(1) << "Denying look_up2 with MIG error: " << request_service_name; + message_server_->RejectMessage(request, BOOTSTRAP_UNKNOWN_SERVICE); + } else if (rule.result == POLICY_DENY_DUMMY_PORT || + rule.result == POLICY_SUBSTITUTE_PORT) { + // The policy result is to deny access to the real service port, replying + // with a sandboxed port in its stead. Use either the dummy sandbox_port_ + // or the one specified in the policy. + VLOG(1) << "Intercepting look_up2 with a sandboxed service port: " + << request_service_name; + + mach_port_t result_port; + if (rule.result == POLICY_DENY_DUMMY_PORT) + result_port = sandbox_port_.get(); + else + result_port = rule.substitute_port; + + IPCMessage reply = message_server_->CreateReply(request); + compat_shim_.look_up2_fill_reply(reply, result_port); + // If the message was sent successfully, clear the result_port out of the + // message so that it is not destroyed at the end of ReceiveMessage. The + // above-inserted right has been moved out of the process, and destroying + // the message will unref yet another right. + if (message_server_->SendReply(reply)) + compat_shim_.look_up2_fill_reply(reply, MACH_PORT_NULL); + } else { + NOTREACHED(); + } +} + +void LaunchdInterceptionServer::HandleSwapInteger(IPCMessage request) { + // Only allow getting information out of launchd. Do not allow setting + // values. Two commonly observed values that are retrieved are + // VPROC_GSK_MGR_PID and VPROC_GSK_TRANSACTIONS_ENABLED. + if (compat_shim_.swap_integer_is_get_only(request)) { + VLOG(2) << "Forwarding vproc swap_integer message."; + ForwardMessage(request); + } else { + VLOG(2) << "Rejecting non-read-only swap_integer message."; + message_server_->RejectMessage(request, BOOTSTRAP_NOT_PRIVILEGED); + } +} +void LaunchdInterceptionServer::ForwardMessage(IPCMessage request) { + message_server_->ForwardMessage(request, sandbox_->real_bootstrap_port()); +} + +} // namespace sandbox diff --git a/pool/shard001/C++/0018403_Notifier.cpp b/pool/shard001/C++/0018403_Notifier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7df800dffd395432cffe23a6168bcb9f878e1111 --- /dev/null +++ b/pool/shard001/C++/0018403_Notifier.cpp @@ -0,0 +1,57 @@ +#include "firtex/common/Notifier.h" + +using namespace std; +FX_NS_USE(thread); + +FX_NS_DEF(common); + +SETUP_STREAM_LOGGER(common, Notifier); + +Notifier::Notifier() +{ +} + +Notifier::~Notifier() +{ +} + +void Notifier::registerClient(const tstring& sIdentifier, Notifiable* pNotifiable) +{ + FastMutex::Guard lock(m_tableLock); + NotifyTable::iterator it = m_notifyTable.find(sIdentifier); + if (it == m_notifyTable.end()) + { + NotifyList noList; + noList.push_back(pNotifiable); + m_notifyTable.insert(make_pair(sIdentifier, noList)); + } + else + { + NotifyList& noList = it->second; + noList.push_back(pNotifiable); + } +} + +void Notifier::unregisterAll() +{ + FastMutex::Guard lock(m_tableLock); + m_notifyTable.clear(); +} + +void Notifier::update(const Notification& notif) +{ + FastMutex::Guard lock(m_tableLock); + + NotifyTable::iterator it = m_notifyTable.find(notif.getIdentifier()); + if (it != m_notifyTable.end()) + { + NotifyList& noList = it->second; + for (NotifyList::iterator noIt = noList.begin(); + noIt != noList.end(); ++noIt) + { + (*noIt)->update(notif); + } + } +} + +FX_NS_END diff --git a/pool/shard001/C++/0018411_SessionMessageRouter.cpp b/pool/shard001/C++/0018411_SessionMessageRouter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..468436acd88b19d835cc11d3c4b9ea7281ce88d8 --- /dev/null +++ b/pool/shard001/C++/0018411_SessionMessageRouter.cpp @@ -0,0 +1,47 @@ +////////////////////////////////////////////////////////////////////////// +// SessionMessageRouter.cpp +// +// Allows user code to register functions to call back to when different +// types of JSON messages +// +// Copyright (C) 2014 Microsoft Corp. All Rights Reserved +////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "SessionMessageRouter.h" + +XTOOLS_NAMESPACE_BEGIN + +void SessionMessageRouter::RegisterHandler(const MessageHandlerProxyPtr& handler) +{ + m_handlerMap[handler->GetMessageType()] = handler; +} + + +bool SessionMessageRouter::CallHandler(const JSONMessagePtr& message, const NetworkConnectionPtr& connection) const +{ + try + { + std::string messageType = message->GetStringValue(kSessionMessageTypeKey); + + auto handler = m_handlerMap.find(messageType); + if (handler != m_handlerMap.end()) + { + handler->second->HandleMessage(message, connection); + } + else + { + LogWarning("Received a session message for which there is no handler registered"); + return false; + } + } + catch (web::json::json_exception e) + { + LogError("Bad JSON message received: %s", e.what()); + return false; + } + + return true; +} + +XTOOLS_NAMESPACE_END diff --git a/pool/shard001/C++/0018421_GLWindow.cpp b/pool/shard001/C++/0018421_GLWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e4158b2ebddae3146d37a51fedca30df25136ea --- /dev/null +++ b/pool/shard001/C++/0018421_GLWindow.cpp @@ -0,0 +1,240 @@ +#include "GLWindow.h" + +// Window dimensions +const GLuint WIDTH = 1920; +const GLuint HEIGHT = 1080; + +GLfloat uniMixValue = 0.2f; +static bool isKeyPress[1024] = { false }; +static bool isMouseButtonPress[16] = { false }; +static double dMousePosX = 0.0; +static double dMousePosY = 0.0; +static int iScrollPlusCnt = 0; +static int iScrollMinusCnt = 0; +static std::mutex scrollCntMutex; + +glm::vec3 objectPositions[] = { + //glm::vec3(0.0f, -10.0f, 0.0f) + glm::vec3(0.0f, -2.0f, 0.0f) +}; + +static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) +{ + // LOG_DBG("key:%d\n", key); + if (GLFW_KEY_ESCAPE == key && GLFW_RELEASE == action) { + glfwSetWindowShouldClose(window, GL_TRUE); + } + else if (GLFW_KEY_UP == key && GLFW_RELEASE == action) { + uniMixValue = (uniMixValue + 0.1f > 1.0f) ? 1.0f : (uniMixValue + 0.1f); + // LOG_DBG("uniMixValue:%f\n", uniMixValue); + } + else if (GLFW_KEY_DOWN == key && GLFW_RELEASE == action) { + uniMixValue = (uniMixValue - 0.1f < 0.0f) ? 0.0f : (uniMixValue - 0.1f); + // LOG_DBG("uniMixValue:%f\n", uniMixValue); + } + else { + if ((GLFW_PRESS == action) || GLFW_REPEAT == action) { + isKeyPress[key] = true; + } + else { + isKeyPress[key] = false; + } + } +} + +static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos) +{ + dMousePosX = xpos; + dMousePosY = ypos; +} + +static void mouse_button_callback(GLFWwindow* window, int button, int action, int mode) +{ + if (GLFW_PRESS == action) { + isMouseButtonPress[button] = true; + } + else { + isMouseButtonPress[button] = false; + } +} + +static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) +{ + scrollCntMutex.lock(); + if (yoffset > 0) + iScrollPlusCnt++; + else + iScrollMinusCnt++; + scrollCntMutex.unlock(); +} + +GLWindow::GLWindow(std::string title, bool isFullScreen) + : m_sWindow(nullptr) + , m_iWidth(WIDTH) + , m_iHeight(HEIGHT) +{ + m_strTtile = title; + m_bIsFullScreen = isFullScreen; +} + +GLWindow::~GLWindow() +{ + if (m_cCamera) + delete m_cCamera; +} + +void GLWindow::CreateWindow() +{ + LOG_DBG("[%s:%d]\n", __FUNCTION__, __LINE__); + + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); + // glfwDefaultWindowHints(); + + GLFWmonitor *pcMonitor = nullptr; + if (m_bIsFullScreen) + pcMonitor = glfwGetPrimaryMonitor(); + m_sWindow = glfwCreateWindow(WIDTH, HEIGHT, m_strTtile.c_str(), pcMonitor, nullptr); +} + +bool GLWindow::Init() +{ + LOG_DBG("[%s:%d]\n", __FUNCTION__, __LINE__); + + // set callback + glfwSetKeyCallback(m_sWindow, key_callback); + glfwSetMouseButtonCallback(m_sWindow, mouse_button_callback); + glfwSetCursorPosCallback(m_sWindow, cursor_pos_callback); + glfwSetScrollCallback(m_sWindow, scroll_callback); + + // cursor options + // glfwSetInputMode(m_sWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + + glfwGetFramebufferSize(m_sWindow, &m_iWidth, &m_iHeight); + LOG_INFO("[%s:%d] Width=%d, Height=%d\n", __FUNCTION__, __LINE__, m_iWidth, m_iHeight); + glViewport(0, 0, m_iWidth, m_iHeight); + + // setup OpenGL options + glEnable(GL_DEPTH_TEST); + + // init GLCamera + m_cCamera = new GLCamera(this); + if (nullptr == m_cCamera) { + LOG_ERR("[%s:%d] m_cCamera is nullptr\n", __FUNCTION__, __LINE__); + return false; + } + m_cCamera->Init(); + + // init GLShaderProgram + m_cLightingShaderProgram = new GLShaderProgram(this, "vertex_lighting.shader", "fragment_lighting.shader"); + if (nullptr == m_cLightingShaderProgram) { + LOG_ERR("[%s:%d] m_cLightingShaderProgram is nullptr\n", __FUNCTION__, __LINE__); + return false; + } + bool bRes = m_cLightingShaderProgram->Init(); + if (!bRes) { + LOG_ERR("[%s:%d] Init GLShaderProgram failed\n", __FUNCTION__, __LINE__); + return false; + } + + // append objects + for (int i = 0; i < sizeof(objectPositions) / sizeof(objectPositions[0]); i++) { + std::list listModelTransforms; + listModelTransforms.push_back(GLTransform(TRANSFORM_TRANSLATE, objectPositions[i])); + listModelTransforms.push_back(GLTransform(TRANSFORM_ROTATE, glm::vec3(1.0f, 0.3f, 0.5f), glm::radians(20.0f * i))); + m_cLightingShaderProgram->AppendObject(GLObject(listModelTransforms)); + } + + return true; +} + +void GLWindow::Run() +{ + LOG_DBG("[%s:%d]\n", __FUNCTION__, __LINE__); + + // Game loop + while (!glfwWindowShouldClose(m_sWindow)) + { + m_cCamera->SetDeltaTime(); + + glfwPollEvents(); + m_cCamera->ProcessEvents(); + + // Render + Render(); + + glfwSwapBuffers(m_sWindow); + } +} + +GLFWwindow* GLWindow::GetWindow() +{ + return m_sWindow; +} + +int GLWindow::GetWidth() +{ + return m_iWidth; +} + +int GLWindow::GetHeight() +{ + return m_iHeight; +} + +void GLWindow::DecreaseScrollPlusCnt() +{ + scrollCntMutex.lock(); + + if (iScrollPlusCnt > 0) + iScrollPlusCnt--; + + scrollCntMutex.unlock(); +} + +void GLWindow::DecreaseScrollMinusCnt() +{ + scrollCntMutex.lock(); + + if (iScrollMinusCnt > 0) + iScrollMinusCnt--; + + scrollCntMutex.unlock(); +} + +GLInputData GLWindow::GetInput() +{ + scrollCntMutex.lock(); + + GLInputData sInputData; + memset(&sInputData, 0, sizeof(sInputData)); + memcpy(sInputData.bIsKeyPress, isKeyPress, sizeof(sInputData.bIsKeyPress)); + memcpy(sInputData.bIsMouseButtonPress, isMouseButtonPress, sizeof(sInputData.bIsMouseButtonPress)); + sInputData.dMousePosX = dMousePosX; + sInputData.dMousePosY = dMousePosY; + sInputData.iScrollPlusCnt = iScrollPlusCnt; + sInputData.iScrollMinusCnt = iScrollMinusCnt; + + scrollCntMutex.unlock(); + + return sInputData; +} + +GLCamera* GLWindow::GetCamera() +{ + return m_cCamera; +} + +void GLWindow::Render() +{ + // Clear the colorbuffer + // glClearColor(0.78f, 0.93f, 0.8f, 1.0f); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + // Draw our first triangle + m_cLightingShaderProgram->UseProgram(); + m_cLightingShaderProgram->RenderObjects(); +} diff --git a/pool/shard001/C++/0018423_eeprom_flash.cpp b/pool/shard001/C++/0018423_eeprom_flash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..252b057362c99dbba307793d87c24ee67238c01a --- /dev/null +++ b/pool/shard001/C++/0018423_eeprom_flash.cpp @@ -0,0 +1,277 @@ +/** + * Marlin 3D Printer Firmware + * + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com + * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com + * Copyright (c) 2016 Victor Perez victor_pv@hotmail.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 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 "../platforms.h" + +#ifdef HAL_STM32 + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(FLASH_EEPROM_EMULATION) + +#include "../shared/eeprom_api.h" + +// Better: "utility/stm32_eeprom.h", but only after updating stm32duino to 2.0.0 +// Use EEPROM.h for compatibility, for now. +#include + +/** + * The STM32 HAL supports chips that deal with "pages" and some with "sectors" and some that + * even have multiple "banks" of flash. + * + * This code is a bit of a mashup of + * framework-arduinoststm32/cores/arduino/stm32/stm32_eeprom.c + * hal/hal_lpc1768/persistent_store_flash.cpp + * + * This has only be written against those that use a single "sector" design. + * + * Those that deal with "pages" could be made to work. Looking at the STM32F07 for example, there are + * 128 "pages", each 2kB in size. If we continued with our EEPROM being 4Kb, we'd always need to operate + * on 2 of these pages. Each write, we'd use 2 different pages from a pool of pages until we are done. + */ + +#if ENABLED(FLASH_EEPROM_LEVELING) + + #include "stm32_def.h" + + #define DEBUG_OUT ENABLED(EEPROM_CHITCHAT) + #include "../../core/debug_out.h" + + #ifndef MARLIN_EEPROM_SIZE + #define MARLIN_EEPROM_SIZE 0x1000 // 4KB + #endif + + #ifndef FLASH_SECTOR + #define FLASH_SECTOR (FLASH_SECTOR_TOTAL - 1) + #endif + #ifndef FLASH_UNIT_SIZE + #define FLASH_UNIT_SIZE 0x20000 // 128kB + #endif + + #ifndef FLASH_ADDRESS_START + #define FLASH_ADDRESS_START (FLASH_END - ((FLASH_SECTOR_TOTAL - (FLASH_SECTOR)) * (FLASH_UNIT_SIZE)) + 1) + #endif + #define FLASH_ADDRESS_END (FLASH_ADDRESS_START + FLASH_UNIT_SIZE - 1) + + #define EEPROM_SLOTS ((FLASH_UNIT_SIZE) / (MARLIN_EEPROM_SIZE)) + #define SLOT_ADDRESS(slot) (FLASH_ADDRESS_START + (slot * (MARLIN_EEPROM_SIZE))) + + #define UNLOCK_FLASH() if (!flash_unlocked) { \ + HAL_FLASH_Unlock(); \ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | \ + FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); \ + flash_unlocked = true; \ + } + #define LOCK_FLASH() if (flash_unlocked) { HAL_FLASH_Lock(); flash_unlocked = false; } + + #define EMPTY_UINT32 ((uint32_t)-1) + #define EMPTY_UINT8 ((uint8_t)-1) + + static uint8_t ram_eeprom[MARLIN_EEPROM_SIZE] __attribute__((aligned(4))) = {0}; + static int current_slot = -1; + + static_assert(0 == MARLIN_EEPROM_SIZE % 4, "MARLIN_EEPROM_SIZE must be a multiple of 4"); // Ensure copying as uint32_t is safe + static_assert(0 == FLASH_UNIT_SIZE % MARLIN_EEPROM_SIZE, "MARLIN_EEPROM_SIZE must divide evenly into your FLASH_UNIT_SIZE"); + static_assert(FLASH_UNIT_SIZE >= MARLIN_EEPROM_SIZE, "FLASH_UNIT_SIZE must be greater than or equal to your MARLIN_EEPROM_SIZE"); + static_assert(IS_FLASH_SECTOR(FLASH_SECTOR), "FLASH_SECTOR is invalid"); + static_assert(IS_POWER_OF_2(FLASH_UNIT_SIZE), "FLASH_UNIT_SIZE should be a power of 2, please check your chip's spec sheet"); + +#endif + +static bool eeprom_data_written = false; + +#ifndef MARLIN_EEPROM_SIZE + #define MARLIN_EEPROM_SIZE size_t(E2END + 1) +#endif +size_t PersistentStore::capacity() { return MARLIN_EEPROM_SIZE; } + +bool PersistentStore::access_start() { + + EEPROM.begin(); // Avoid STM32 EEPROM.h warning (do nothing) + + #if ENABLED(FLASH_EEPROM_LEVELING) + + if (current_slot == -1 || eeprom_data_written) { + // This must be the first time since power on that we have accessed the storage, or someone + // loaded and called write_data and never called access_finish. + // Lets go looking for the slot that holds our configuration. + if (eeprom_data_written) DEBUG_ECHOLNPGM("Dangling EEPROM write_data"); + uint32_t address = FLASH_ADDRESS_START; + while (address <= FLASH_ADDRESS_END) { + uint32_t address_value = (*(__IO uint32_t*)address); + if (address_value != EMPTY_UINT32) { + current_slot = (address - (FLASH_ADDRESS_START)) / (MARLIN_EEPROM_SIZE); + break; + } + address += sizeof(uint32_t); + } + if (current_slot == -1) { + // We didn't find anything, so we'll just initialize to empty + for (int i = 0; i < MARLIN_EEPROM_SIZE; i++) ram_eeprom[i] = EMPTY_UINT8; + current_slot = EEPROM_SLOTS; + } + else { + // load current settings + uint8_t *eeprom_data = (uint8_t *)SLOT_ADDRESS(current_slot); + for (int i = 0; i < MARLIN_EEPROM_SIZE; i++) ram_eeprom[i] = eeprom_data[i]; + DEBUG_ECHOLNPGM("EEPROM loaded from slot ", current_slot, "."); + } + eeprom_data_written = false; + } + + #else + eeprom_buffer_fill(); + #endif + + return true; +} + +bool PersistentStore::access_finish() { + + if (eeprom_data_written) { + #ifdef STM32F4xx + // MCU may come up with flash error bits which prevent some flash operations. + // Clear flags prior to flash operations to prevent errors. + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); + #endif + + #if ENABLED(FLASH_EEPROM_LEVELING) + + HAL_StatusTypeDef status = HAL_ERROR; + bool flash_unlocked = false; + + if (--current_slot < 0) { + // all slots have been used, erase everything and start again + + FLASH_EraseInitTypeDef EraseInitStruct; + uint32_t SectorError = 0; + + EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; + EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; + EraseInitStruct.Sector = FLASH_SECTOR; + EraseInitStruct.NbSectors = 1; + + current_slot = EEPROM_SLOTS - 1; + UNLOCK_FLASH(); + + TERN_(HAS_PAUSE_SERVO_OUTPUT, PAUSE_SERVO_OUTPUT()); + DISABLE_ISRS(); + status = HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError); + ENABLE_ISRS(); + TERN_(HAS_PAUSE_SERVO_OUTPUT, RESUME_SERVO_OUTPUT()); + if (status != HAL_OK) { + DEBUG_ECHOLNPGM("HAL_FLASHEx_Erase=", status); + DEBUG_ECHOLNPGM("GetError=", HAL_FLASH_GetError()); + DEBUG_ECHOLNPGM("SectorError=", SectorError); + LOCK_FLASH(); + return false; + } + } + + UNLOCK_FLASH(); + + uint32_t offset = 0; + uint32_t address = SLOT_ADDRESS(current_slot); + uint32_t address_end = address + MARLIN_EEPROM_SIZE; + uint32_t data = 0; + + bool success = true; + + while (address < address_end) { + memcpy(&data, ram_eeprom + offset, sizeof(uint32_t)); + status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, data); + if (status == HAL_OK) { + address += sizeof(uint32_t); + offset += sizeof(uint32_t); + } + else { + DEBUG_ECHOLNPGM("HAL_FLASH_Program=", status); + DEBUG_ECHOLNPGM("GetError=", HAL_FLASH_GetError()); + DEBUG_ECHOLNPGM("address=", address); + success = false; + break; + } + } + + LOCK_FLASH(); + + if (success) { + eeprom_data_written = false; + DEBUG_ECHOLNPGM("EEPROM saved to slot ", current_slot, "."); + } + + return success; + + #else + // The following was written for the STM32F4 but may work with other MCUs as well. + // Most STM32F4 flash does not allow reading from flash during erase operations. + // This takes about a second on a STM32F407 with a 128kB sector used as EEPROM. + // Interrupts during this time can have unpredictable results, such as killing Servo + // output. Servo output still glitches with interrupts disabled, but recovers after the + // erase. + TERN_(HAS_PAUSE_SERVO_OUTPUT, PAUSE_SERVO_OUTPUT()); + DISABLE_ISRS(); + eeprom_buffer_flush(); + ENABLE_ISRS(); + TERN_(HAS_PAUSE_SERVO_OUTPUT, RESUME_SERVO_OUTPUT()); + + eeprom_data_written = false; + #endif + } + + return true; +} + +bool PersistentStore::write_data(int &pos, const uint8_t *value, size_t size, uint16_t *crc) { + while (size--) { + uint8_t v = *value; + #if ENABLED(FLASH_EEPROM_LEVELING) + if (v != ram_eeprom[pos]) { + ram_eeprom[pos] = v; + eeprom_data_written = true; + } + #else + if (v != eeprom_buffered_read_byte(pos)) { + eeprom_buffered_write_byte(pos, v); + eeprom_data_written = true; + } + #endif + crc16(crc, &v, 1); + pos++; + value++; + } + return false; +} + +bool PersistentStore::read_data(int &pos, uint8_t *value, size_t size, uint16_t *crc, const bool writing/*=true*/) { + do { + const uint8_t c = TERN(FLASH_EEPROM_LEVELING, ram_eeprom[pos], eeprom_buffered_read_byte(pos)); + if (writing) *value = c; + crc16(crc, &c, 1); + pos++; + value++; + } while (--size); + return false; +} + +#endif // FLASH_EEPROM_EMULATION +#endif // HAL_STM32 diff --git a/pool/shard001/C++/0018429_BoundaryPressure.cpp b/pool/shard001/C++/0018429_BoundaryPressure.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96af1001490287ae2ab143c4dd06a506dce28899 --- /dev/null +++ b/pool/shard001/C++/0018429_BoundaryPressure.cpp @@ -0,0 +1,80 @@ +// +// BoundaryPressure.cpp +// aletler +// +// Created by Phaedon Sinis on 1/2/14. +// Copyright (c) 2014 Phaedon Sinis. All rights reserved. +// + +#include "BoundaryPressure.h" +#include +#include + + +template +T StringToNumber (const std::string &Text ) { + //character array as argument + std::stringstream ss(Text); + T result; + return ss >> result ? result : 0; +} + +void BoundaryPressure::read(const std::string &filename) { + std::ifstream ifile(filename.c_str()); + std::string line; + + const std::string& whitespace = " \t"; + if (ifile.is_open()) { + while (std::getline (ifile,line)) { + + size_t strBegin = line.find_first_not_of(whitespace); + if (strBegin == std::string::npos) // empty line + continue; + + if (line[strBegin] == '~' || line[strBegin] == 'F' || line[strBegin] == 'E') + continue; + + std::stringstream stream(line); + std::string realStr, imStr; + std::string junk; + stream >> junk; // index + stream >> junk; // open paren + stream >> realStr; + stream >> imStr; + + double realD = StringToNumber(realStr); + double imD = StringToNumber(imStr); + + std::cout << realD << " " << imD << std::endl; + + _cpressures.push_back(std::complex(realD, imD)); + + } + ifile.close(); + } + + computeModuli(); +} + + + +void BoundaryPressure::visualize(const TriangleMesh &combined) const { + + vdb_frame(); + + float span = _moduli.maxCoeff() - _moduli.minCoeff(); + + for (size_t i = 0; i < combined.size(); i++) { + Triangle t = combined.triangle(i); + Vector3d c = t.centroid(); + + float r = (_moduli(i) - _moduli.minCoeff()) / span; + float g = 0.0; + float b = 1.0 - r; + + vdb_color(r,g,b); + vdb_point(c.x(), c.y(), c.z()); + } + + +} \ No newline at end of file diff --git a/pool/shard001/C++/0018443_WebCoreBundleWin.cpp b/pool/shard001/C++/0018443_WebCoreBundleWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b7c8e1a20a451ad7cb3848eb61622e97fd024c7 --- /dev/null +++ b/pool/shard001/C++/0018443_WebCoreBundleWin.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2011, 2013 Apple 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 APPLE INC. AND ITS 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 APPLE INC. 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. + */ + +#include "config.h" +#include "WebCoreBundleWin.h" + +#if USE(CF) + +#include "WebCoreInstanceHandle.h" +#include +#include +#include + +namespace WebCore { + +static CFBundleRef createWebKitBundle() +{ + if (CFBundleRef existingBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.WebKit"))) { + CFRetain(existingBundle); + return existingBundle; + } + + wchar_t dllPathBuffer[MAX_PATH]; + DWORD length = ::GetModuleFileNameW(WebCore::instanceHandle(), dllPathBuffer, WTF_ARRAY_LENGTH(dllPathBuffer)); + ASSERT(length); + ASSERT(length < WTF_ARRAY_LENGTH(dllPathBuffer)); + + RetainPtr dllPath = adoptCF(CFStringCreateWithCharactersNoCopy(0, reinterpret_cast(dllPathBuffer), length, kCFAllocatorNull)); + RetainPtr dllURL = adoptCF(CFURLCreateWithFileSystemPath(0, dllPath.get(), kCFURLWindowsPathStyle, false)); + RetainPtr dllDirectoryURL = adoptCF(CFURLCreateCopyDeletingLastPathComponent(0, dllURL.get())); + RetainPtr resourcesDirectoryURL = adoptCF(CFURLCreateCopyAppendingPathComponent(0, dllDirectoryURL.get(), CFSTR("WebKit.resources"), true)); + + return CFBundleCreate(0, resourcesDirectoryURL.get()); +} + +CFBundleRef webKitBundle() +{ + static CFBundleRef bundle = createWebKitBundle(); + ASSERT(bundle); + return bundle; +} + +} // namespace WebCore + +#endif diff --git a/pool/shard001/C++/0018445_Program.cpp b/pool/shard001/C++/0018445_Program.cpp new file mode 100644 index 0000000000000000000000000000000000000000..167a49c91ffd10766b980a453e2c7867cf0c4d60 --- /dev/null +++ b/pool/shard001/C++/0018445_Program.cpp @@ -0,0 +1,89 @@ +/**************************************************** +* Author: Kacper Domañski +* Contact: kacper.domanski@kacpidev.pl +* Web: blog.kacpidev.pl +* +* Warsaw University of Technology +* Faculty of Electronics and Information Technology +****************************************************/ +#include "Program.h" + + +Program::Program(int argc, char *argv[]) : _interface(argc, argv) +{ +} + +void Program::run() +{ + if (_interface.getBoolParameter("--usage")) + { + _interface.printUsage(); + return; + } + if (_interface.getBoolParameter("--help")) + { + _interface.printHelp(); + return; + } + + if (_interface.getStringParameter("--file") != "") + { + if (_interface.getStringParameter("--getnerate-tests") != "") + { + MessageHandler::printMessage("Random generation & input file given, ignoring generation", MessageHandler::WARNING); + } + + MessageHandler::printMessage("Loading form file", MessageHandler::INFO); + Utilities::timeStart(); + //acquire + MessageHandler::printMessage(std::to_string(Utilities::timeStop()), MessageHandler::TIME); + } + else if (_interface.getStringParameter("--generate-tests") != "") + { + unsigned int tests = Utilities::convertFromString(_interface.getStringParameter("--generate-tests")); + + if (tests > 0) + { + MessageHandler::printMessage("Generating records", MessageHandler::INFO); + Utilities::timeStart(); + this->_collection.generateRandomData(tests, Utilities::windowSize); + MessageHandler::printMessage(std::to_string(Utilities::timeStop()), MessageHandler::TIME); + } + else + { + MessageHandler::printMessage("Number of tests is equal or less than 0.", MessageHandler::ERR); + return; + } + + CollisionDetector::AlgorithmType algorithmType = CollisionDetector::WS; + CollisionDetector::ArrangmentType arrangmentType = CollisionDetector::NO; + + std::string algorithmParameter, arrangmentParameter; + algorithmParameter = _interface.getStringParameter("--algorithm"); + arrangmentParameter = _interface.getStringParameter("--arrangment"); + + + if (algorithmParameter != "") + { + algorithmParameter == "WS" ? algorithmType = CollisionDetector::WS : algorithmType = CollisionDetector::DS; + } + + if (arrangmentParameter != "") + { + algorithmParameter == "NO" ? arrangmentType = CollisionDetector::NO : arrangmentType = CollisionDetector::SH; + } + + _collection.setCollisionDetector(new CollisionDetector(_collection.getSegments(), algorithmType, arrangmentType)); + + _collection.getCollisionDetector()->arrange(); + + + } +} + +void Program::draw(void) +{ + Program::program->_collection.getCollisionDetector()->drawAll(); +} + +Program * Program::program = nullptr; diff --git a/pool/shard001/C++/0018447_ProcessMapperPushtestclass.cpp b/pool/shard001/C++/0018447_ProcessMapperPushtestclass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b75f56b4f9461caeea278ade9c66398dceee9ce --- /dev/null +++ b/pool/shard001/C++/0018447_ProcessMapperPushtestclass.cpp @@ -0,0 +1,69 @@ +/* + * File: ProcessMapperPushtestclass.cpp + * Author: ntanaka + * + * Created on 2014/12/17, 22:32:52 + */ + +#include +#include +#include + +#include "ProcessMapperPushtestclass.h" +#include "../jsonMapper/ProcessMapper.h" +#include "../ComponentIF.h" +#include "../ComponentSample1.h" +//#include "../Message.h" +//#include "../InPort.h" +#include "../MessageWithInPort.h" + +CPPUNIT_TEST_SUITE_REGISTRATION(ProcessMapperPushtestclass); + +ProcessMapperPushtestclass::ProcessMapperPushtestclass() { +} + +ProcessMapperPushtestclass::~ProcessMapperPushtestclass() { +} + +void ProcessMapperPushtestclass::setUp() { +} + +void ProcessMapperPushtestclass::tearDown() { +} + +void ProcessMapperPushtestclass::testCreate() { + std::string fileName_ = "Process.txt"; + //jsonMapper::ProcessMapper processMapper; + utah::Process* processP = jsonMapper::ProcessMapper::create("data", fileName_, "PortMap.txt"); + utah::ComponentIF* component = new utah::ComponentSample1(); + std::string thread = "threadA"; + std::string stateMachine = "StateMachine1"; + processP->setComponent(thread, stateMachine, component); + + utah::ComponentIF* component2 = new utah::ComponentSample1(); + std::string thread2 = "threadB"; + std::string stateMachine2 = "StateMachine2"; + processP->setComponent(thread2, stateMachine2, component2); + + utah::InPort inPort("z", "StateMachine1", "threadA"); //{"port" : "z" , "stateMachine" : "StateMachine1" , "thread" : "threadA"} + utah::Message message("x", "NULL"); + utah::MessageWithInPort messageWithInPort(message, inPort); + + processP->push(messageWithInPort); + //void push(MessageWithInPort messageWithInPort_); + + utah::Message message2("v", "NULL"); + utah::MessageWithInPort messageWithInPort2(message2, inPort); + processP->push(messageWithInPort2); + + sleep(10); // ugly + + processP->done(); + processP->join(); + + //sleep(10); + if (true /*check result*/) { + CPPUNIT_ASSERT(true); + } +} + diff --git a/pool/shard001/C++/0018451_lua.cpp b/pool/shard001/C++/0018451_lua.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbbbdf61cc25e085954951075af9c554cf8ab46e --- /dev/null +++ b/pool/shard001/C++/0018451_lua.cpp @@ -0,0 +1,62 @@ +#include + +int main() +{ + int total_medicoes; + int intervalo; + + int soma_medicao; + int count_teste = 0; + while(true) + { + scanf("%d", &total_medicoes); + scanf("%d", &intervalo); + + if(total_medicoes == 0 && intervalo == 0) + break; + + soma_medicao = 0; + int medicoes[total_medicoes]; + int maior_medicao = -200; + int menor_medicao = 200; + int lido = 0; + bool deve_somar; + bool deve_ler; + int med = 0; + for(int i = 0; i < total_medicoes; i++){ + scanf("%d",&medicoes[i]); + } + for(int j = 0; j < intervalo;j++) + { + deve_somar = j < total_medicoes; + + if(deve_somar){ + soma_medicao += medicoes[j]; + } + if(j == intervalo - 1 && deve_somar){ + med = soma_medicao/intervalo; + if(med > maior_medicao) + maior_medicao = med; + if(med < menor_medicao) + menor_medicao = med; + } + } + for(int i = 1;i < total_medicoes; i++) + { + med = 0; + if(i+intervalo-1 < total_medicoes){ + soma_medicao = (soma_medicao - medicoes[i-1]) + medicoes[i+intervalo-1]; + med = soma_medicao/intervalo; + if(med > maior_medicao) + maior_medicao = med; + if(med < menor_medicao) + menor_medicao = med; + } + + } + printf("Teste %d\n%d %d\n\n",++count_teste,menor_medicao, maior_medicao); + } + return 0; + +} + diff --git a/pool/shard001/C++/0018452_CdHandler.cpp b/pool/shard001/C++/0018452_CdHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e06e9a3c3e5d33b1f70919c9fe95b85ea86662ee --- /dev/null +++ b/pool/shard001/C++/0018452_CdHandler.cpp @@ -0,0 +1,180 @@ +/** + * VisualNetkit is an advanced graphical tool for NetKit + * Copyright (C) 2008 Alessio Di Fazio, Paolo Minasi + * + * 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 "CdHandler.h" +#include "../../core/CollisionDomain.h" +#include "../CollisionDomainItem.h" +#include "../undoCommands/UndoCommands.h" +#include "../../plugin_framework/PluginRegistry.h" + +/* Init che instance field to NULL */ +CdHandler* CdHandler::instance = NULL; + +/** + * Constructor + */ +CdHandler::CdHandler() +{ + /* Get the controller (Domain side) */ + labFacadeController = LabFacadeController::getInstance(); + + /* view side */ + labHandler = LabHandler::getInstance(); + propertyController = new CdPropertyController(); + + pluginPropDialog = new InitPluginsPropertiesDialog( + PluginRegistry::getInstance()->getAllPluginFactories()); +} + +/** + * Deconstructor + */ +CdHandler::~CdHandler() +{ +} + +/** + * Singletone get instance + */ +CdHandler* CdHandler::getInstance() +{ + if (instance == NULL) + { + instance = new CdHandler(); + } + + return instance; +} + +/** + * Check if the name passed is owned by a collision domain + */ +bool CdHandler::cdNameExist(QString cdNameToCheck) +{ + return labFacadeController->getCurrentLab()->cdExist(cdNameToCheck); +} + +/** + * [PUBLIC-SLOT] + * Handle the signal for inserte a new collision domain + */ +void CdHandler::handleAddNewCd(QString cdName, QStringList selectedPlugins, + bool manuallyInit, QPointF pos) +{ + /* Create the view and domain objects */ + CollisionDomain *cd = new CollisionDomain(cdName); + + CollisionDomainItem *cdItem = new CollisionDomainItem(cdName); + + cdItem->setPos(pos); //place the item wher user clicked + + /* Create plugins and attach these to the vm */ + QList cdPlugins; + QStringListIterator iter(selectedPlugins); + PluginRegistry* registry = PluginRegistry::getInstance(); + + /* Save proxies for undo command */ + while(iter.hasNext()) + { + PluginProxy* proxy; + if((proxy = registry->registerPlugin(iter.next(), cd)) != NULL) + cdPlugins.append(proxy); + } + + labFacadeController->getCurrentLab()->addCollisionDomain(cd); + + /* the undo command (redo) can accomplish the action */ + labHandler->getUndoStack()->push(new AddCdCommand(cdItem, cd, cdPlugins)); + + /* reset the default action (manage graph) */ + labHandler->getMainWindow()->forceManageGraphAction(); + + /* now check if the user want init manually the plugins properties */ + if(manuallyInit && selectedPlugins.size() > 0) + { + propertyController->setCd(cd); + pluginPropDialog->buildGui(cdPlugins, propertyController); + pluginPropDialog->setVisible(true); + } +} + +/** + * Handle the cditem selection and render the properties + */ +void CdHandler::renderCdProperties(CollisionDomainItem *cdItem) +{ + CollisionDomain *cd; + if(!(cd = CdMapper::getInstance()->getCD(cdItem))) + return; + + propertyController->setCd(cd); + + /* Clear the property editor and render properties */ + labHandler->getMainWindow()->clearPropertyDock(propertyController->getComposedModel()); +} + +/** + * Delete a collision domain and all links connected + */ +void CdHandler::deleteCd(CollisionDomainItem *cdItem) +{ + /* Get the low level object */ + CollisionDomain *cd = CdMapper::getInstance()->getCD(cdItem); + + /* Get all links connected */ + QMap links = LinkMapper::getInstance()->getMappingsByCd(cd); + + /* Destroy the mapper */ + CdMapper::getInstance()->destroyMapper(cdItem); + + /* Remove item from scene */ + labHandler->removeItemFromScene(cdItem); + + /* Remove connected links from the scene and from the three scene view */ + foreach(LinkItem* link, links.keys()) + { + labHandler->removeItemFromScene(link); + SceneTreeMapper::getInstance()->removeLink(link, link->getVirtualMachineItem()); + } + + /* Remove all link from own vm (lov level) and get all proxies */ + QMap hiProxies; //used with insert-multi + foreach(HardwareInterface* hi, links.values()) + { + hi->getMyVirtualMachine()->deleteHi(hi->getName()); + foreach(PluginProxy *p, PluginRegistry::getInstance()->takeHiProxies(hi)) + hiProxies.insertMulti(hi, p); + } + + QList cdProxies; + /* Take proxies for this collision domain */ + cdProxies = PluginRegistry::getInstance()->takeCdProxies(cd); + + /* Remove cd from low-level */ + LabFacadeController::getInstance()->removeCd(cd); + + /* Create the undo command */ + labHandler->getUndoStack()->push(new DeleteCdCommand(cd, cdItem, cdProxies, links, hiProxies)); + + /* Remove the Collision domain from tree scene view */ + SceneTreeMapper::getInstance()->removeCd(cdItem); + + /* Clear property dock content */ + LabHandler::getInstance()->getMainWindow()->clearPropertyDock(); + +} diff --git a/pool/shard001/C++/0018455_testoutputreader.cpp b/pool/shard001/C++/0018455_testoutputreader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2ad3bff0543f2424b5853e588d4e38c5424489b --- /dev/null +++ b/pool/shard001/C++/0018455_testoutputreader.cpp @@ -0,0 +1,208 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "testoutputreader.h" + +#include "testresult.h" +#include "testresultspane.h" +#include "testtreeitem.h" + +#include + +#include +#include +#include +#include + +namespace Autotest { + +Utils::FilePath TestOutputReader::constructSourceFilePath(const Utils::FilePath &path, + const QString &file) +{ + const Utils::FilePath filePath = path.resolvePath(file); + return filePath.isReadableFile() ? filePath : Utils::FilePath(); +} + +TestOutputReader::TestOutputReader(const QFutureInterface &futureInterface, + QProcess *testApplication, const Utils::FilePath &buildDirectory) + : m_futureInterface(futureInterface) + , m_testApplication(testApplication) + , m_buildDir(buildDirectory) + , m_id(testApplication ? testApplication->program() : QString()) +{ + auto chopLineBreak = [](QByteArray line) { + if (line.endsWith('\n')) + line.chop(1); + if (line.endsWith('\r')) + line.chop(1); + return line; + }; + + if (m_testApplication) { + connect(m_testApplication, &QProcess::readyReadStandardOutput, + this, [chopLineBreak, this] () { + m_testApplication->setReadChannel(QProcess::StandardOutput); + while (m_testApplication->canReadLine()) + processStdOutput(chopLineBreak(m_testApplication->readLine())); + }); + connect(m_testApplication, &QProcess::readyReadStandardError, + this, [chopLineBreak, this] () { + m_testApplication->setReadChannel(QProcess::StandardError); + while (m_testApplication->canReadLine()) + processStdError(chopLineBreak(m_testApplication->readLine())); + }); + } +} + +TestOutputReader::~TestOutputReader() +{ + if (m_sanitizerResult) + sendAndResetSanitizerResult(); +} + +void TestOutputReader::processStdOutput(const QByteArray &outputLine) +{ + processOutputLine(outputLine); + emit newOutputLineAvailable(outputLine, OutputChannel::StdOut); +} + +void TestOutputReader::processStdError(const QByteArray &outputLine) +{ + checkForSanitizerOutput(outputLine); + emit newOutputLineAvailable(outputLine, OutputChannel::StdErr); +} + +void TestOutputReader::reportCrash() +{ + TestResultPtr result = createDefaultResult(); + result->setDescription(tr("Test executable crashed.")); + result->setResult(ResultType::MessageFatal); + m_futureInterface.reportResult(result); +} + +void TestOutputReader::createAndReportResult(const QString &message, ResultType type) +{ + TestResultPtr result = createDefaultResult(); + result->setDescription(message); + result->setResult(type); + reportResult(result); +} + +void TestOutputReader::resetCommandlineColor() +{ + emit newOutputLineAvailable("\u001B[m", OutputChannel::StdOut); + emit newOutputLineAvailable("\u001B[m", OutputChannel::StdErr); +} + +QString TestOutputReader::removeCommandlineColors(const QString &original) +{ + static const QRegularExpression pattern("\u001B\\[.*?m"); + QString result = original; + while (!result.isEmpty()) { + QRegularExpressionMatch match = pattern.match(result); + if (match.hasMatch()) + result.remove(match.capturedStart(), match.captured().length()); + else + break; + } + return result; +} + +void TestOutputReader::reportResult(const TestResultPtr &result) +{ + if (m_sanitizerResult) + sendAndResetSanitizerResult(); + m_futureInterface.reportResult(result); + m_hadValidOutput = true; +} + +void TestOutputReader::checkForSanitizerOutput(const QByteArray &line) +{ + const QString lineStr = removeCommandlineColors(QString::fromUtf8(line)); + if (m_sanitizerOutputMode == SanitizerOutputMode::Asan) { + // append the new line and check for end + m_sanitizerLines.append(lineStr); + static const QRegularExpression regex("^==\\d+==\\s*ABORTING.*"); + if (regex.match(lineStr).hasMatch()) + sendAndResetSanitizerResult(); + return; + } + + static const QRegularExpression regex("^==\\d+==\\s*(ERROR|WARNING|Sanitizer CHECK failed):.*"); + static const QRegularExpression ubsanRegex("^(.*):(\\d+):(\\d+): runtime error:.*"); + QRegularExpressionMatch match = regex.match(lineStr); + SanitizerOutputMode mode = SanitizerOutputMode::None; + if (match.hasMatch()) { + mode = SanitizerOutputMode::Asan; + } else { + match = ubsanRegex.match(lineStr); + if (m_sanitizerOutputMode == SanitizerOutputMode::Ubsan && !match.hasMatch()) { + m_sanitizerLines.append(lineStr); + return; + } + if (match.hasMatch()) + mode = SanitizerOutputMode::Ubsan; + } + if (mode != SanitizerOutputMode::None) { + if (m_sanitizerResult) // we have a result that has not been reported yet + sendAndResetSanitizerResult(); + + m_sanitizerOutputMode = mode; + m_sanitizerResult = createDefaultResult(); + m_sanitizerLines.append("Sanitizer Issue"); + m_sanitizerLines.append(lineStr); + if (m_sanitizerOutputMode == SanitizerOutputMode::Ubsan) { + const Utils::FilePath path = constructSourceFilePath(m_buildDir, match.captured(1)); + // path may be empty if not existing - so, provide at least what we have + m_sanitizerResult->setFileName( + path.exists() ? path : Utils::FilePath::fromString(match.captured(1))); + m_sanitizerResult->setLine(match.captured(2).toInt()); + } + } +} + +void TestOutputReader::sendAndResetSanitizerResult() +{ + QTC_ASSERT(m_sanitizerResult, return); + m_sanitizerResult->setDescription(m_sanitizerLines.join('\n')); + m_sanitizerResult->setResult(m_sanitizerOutputMode == SanitizerOutputMode::Ubsan + ? ResultType::Fail : ResultType::MessageFatal); + + if (m_sanitizerResult->fileName().isEmpty()) { + const ITestTreeItem *testItem = m_sanitizerResult->findTestTreeItem(); + if (testItem && testItem->line()) { + m_sanitizerResult->setFileName(testItem->filePath()); + m_sanitizerResult->setLine(testItem->line()); + } + } + + m_futureInterface.reportResult(m_sanitizerResult); + m_hadValidOutput = true; + m_sanitizerLines.clear(); + m_sanitizerResult.reset(); + m_sanitizerOutputMode = SanitizerOutputMode::None; +} + +} // namespace Autotest diff --git a/pool/shard001/C++/0018458_focus_tab_after_navigation_helper.cc b/pool/shard001/C++/0018458_focus_tab_after_navigation_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..9fc474936d8d663e2b39f9b299850336bc851415 --- /dev/null +++ b/pool/shard001/C++/0018458_focus_tab_after_navigation_helper.cc @@ -0,0 +1,93 @@ +// 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 "chrome/browser/ui/focus_tab_after_navigation_helper.h" + +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search/search.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/webui_url_constants.h" +#include "content/public/browser/browser_url_handler.h" +#include "content/public/browser/navigation_handle.h" +#include "content/public/browser/web_contents.h" + +FocusTabAfterNavigationHelper::FocusTabAfterNavigationHelper( + content::WebContents* contents) + : content::WebContentsObserver(contents) {} + +FocusTabAfterNavigationHelper::~FocusTabAfterNavigationHelper() = default; + +void FocusTabAfterNavigationHelper::ReadyToCommitNavigation( + content::NavigationHandle* navigation) { + // Focus the tab contents if needed. This is done at the ReadyToCommit time + // to: + // 1) ignore same-document navigations (ReadyToCommitNavigation method is not + // invoked for same-document navigations) + // 2) postpone moving the focus until we are ready to commit the page + // 3) move the focus before the page starts rendering + // (only 1 is a hard-requirement; 2 and 3 seem desirable but there are no + // known scenarios where violating these requirements would lead to bugs). + if (ShouldFocusTabContents(navigation)) + web_contents()->SetInitialFocus(); +} + +bool FocusTabAfterNavigationHelper::ShouldFocusTabContents( + content::NavigationHandle* navigation) { + // Don't focus content in an inactive window or tab. + Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); + if (!browser) + return false; + if (!browser->window()->IsActive()) + return false; + if (browser->tab_strip_model()->GetActiveWebContents() != web_contents()) + return false; + + // Don't focus content after subframe navigations. + if (!navigation->IsInMainFrame()) + return false; + + // Browser-initiated navigations (e.g. typing in an omnibox) are taken care of + // in Browser::UpdateUIForNavigationInTab. See also https://crbug.com/1048591 + // for possible regression risks related to returning |true| here. + if (!navigation->IsRendererInitiated()) + return false; + + // Renderer-initiated navigations shouldn't focus the tab contents, unless the + // navigation is leaving the NTP. See also https://crbug.com/1027719. + bool started_at_ntp = IsNtpURL(web_contents()->GetLastCommittedURL()); + if (!started_at_ntp) + return false; + + // Navigations initiated via chrome.tabs.update and similar APIs should not + // steal focus from the omnibox. See also https://crbug.com/1085779. + if (navigation->GetPageTransition() & ui::PAGE_TRANSITION_FROM_API) + return false; + + // Rewrite chrome://newtab to compare with the navigation URL. + GURL rewritten_ntp_url = web_contents()->GetLastCommittedURL(); + Profile* profile = + Profile::FromBrowserContext(web_contents()->GetBrowserContext()); + content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary( + &rewritten_ntp_url, profile); + + // Focus if the destination is not the NTP. + return !IsNtpURL(navigation->GetURL()) && + (navigation->GetURL() != rewritten_ntp_url); +} + +bool FocusTabAfterNavigationHelper::IsNtpURL(const GURL& url) { + // TODO(lukasza): https://crbug.com/1034999: Try to avoid special-casing + // kChromeUINewTabURL below and covering it via IsNTPOrRelatedURL instead. + if (url == GURL(chrome::kChromeUINewTabURL)) + return true; + + Profile* profile = + Profile::FromBrowserContext(web_contents()->GetBrowserContext()); + return search::IsNTPOrRelatedURL(url, profile); +} + +WEB_CONTENTS_USER_DATA_KEY_IMPL(FocusTabAfterNavigationHelper) diff --git a/pool/shard001/C++/0018463_app_installer_util_unittest.cc b/pool/shard001/C++/0018463_app_installer_util_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1c1ab00e2a0baa88585bcc75d3ca21435e1e52b7 --- /dev/null +++ b/pool/shard001/C++/0018463_app_installer_util_unittest.cc @@ -0,0 +1,74 @@ +// 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 "chrome/app_installer/win/app_installer_util.h" + +#include +#include + +#include "base/files/file_util.h" +#include "base/path_service.h" +#include "base/strings/sys_string_conversions.h" +#include "net/test/spawned_test_server/spawned_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace app_installer { + +TEST(AppInstallerUtilTest, ParseTag) { + std::map parsed_pairs; + + parsed_pairs.clear(); + EXPECT_TRUE(ParseTag("key1=value1&key2=value2", &parsed_pairs)); + EXPECT_EQ(2, parsed_pairs.size()); + EXPECT_EQ("value1", parsed_pairs["key1"]); + EXPECT_EQ("value2", parsed_pairs["key2"]); + + parsed_pairs.clear(); + EXPECT_FALSE(ParseTag("a&b", &parsed_pairs)); + + parsed_pairs.clear(); + EXPECT_FALSE(ParseTag("#=a", &parsed_pairs)); + + parsed_pairs.clear(); + EXPECT_FALSE(ParseTag("a=\01", &parsed_pairs)); +} + +void TestFetchUrlWithScheme(net::SpawnedTestServer::Type type, bool success) { + net::SpawnedTestServer http_server( + type, net::SpawnedTestServer::kLocalhost, + base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); + ASSERT_TRUE(http_server.Start()); + + std::vector response_data; + net::HostPortPair host_port = http_server.host_port_pair(); + EXPECT_EQ(success, + FetchUrl(L"user agent", base::SysUTF8ToWide(host_port.host()), + host_port.port(), L"files/extensions/app/manifest.json", + &response_data)); + if (success) { + EXPECT_TRUE(response_data.size()); + base::FilePath source_root; + ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &source_root)); + base::FilePath file_path = source_root.Append( + FILE_PATH_LITERAL("chrome/test/data/extensions/app/manifest.json")); + std::string file_contents; + EXPECT_TRUE(base::ReadFileToString(file_path, &file_contents)); + EXPECT_EQ(file_contents, + std::string(response_data.begin(), response_data.end())); + } else { + EXPECT_FALSE(response_data.size()); + } + + ASSERT_TRUE(http_server.Stop()); +} + +TEST(AppInstallerUtilTest, FetchUrlHttps) { + TestFetchUrlWithScheme(net::SpawnedTestServer::TYPE_HTTPS, true); +} + +TEST(AppInstallerUtilTest, FetchUrlNoHttps) { + TestFetchUrlWithScheme(net::SpawnedTestServer::TYPE_HTTP, false); +} + +} // namespace app_installer diff --git a/pool/shard001/C++/0018470_FEDisplacementMap.cpp b/pool/shard001/C++/0018470_FEDisplacementMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8eb5640e28bc6eab2e5bb1aa8d9b2e65afa5161a --- /dev/null +++ b/pool/shard001/C++/0018470_FEDisplacementMap.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann + * Copyright (C) 2004, 2005 Rob Buis + * Copyright (C) 2005 Eric Seidel + * Copyright (C) 2009 Dirk Schulze + * Copyright (C) Research In Motion Limited 2010. All rights reserved. + * + * 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 "config.h" + +#if ENABLE(FILTERS) +#include "FEDisplacementMap.h" + +#include "Filter.h" +#include "GraphicsContext.h" +#include "RenderTreeAsText.h" +#include "TextStream.h" + +#include + +namespace WebCore { + +FEDisplacementMap::FEDisplacementMap(Filter* filter, ChannelSelectorType xChannelSelector, ChannelSelectorType yChannelSelector, float scale) + : FilterEffect(filter) + , m_xChannelSelector(xChannelSelector) + , m_yChannelSelector(yChannelSelector) + , m_scale(scale) +{ +} + +PassRefPtr FEDisplacementMap::create(Filter* filter, ChannelSelectorType xChannelSelector, + ChannelSelectorType yChannelSelector, float scale) +{ + return adoptRef(new FEDisplacementMap(filter, xChannelSelector, yChannelSelector, scale)); +} + +ChannelSelectorType FEDisplacementMap::xChannelSelector() const +{ + return m_xChannelSelector; +} + +bool FEDisplacementMap::setXChannelSelector(const ChannelSelectorType xChannelSelector) +{ + if (m_xChannelSelector == xChannelSelector) + return false; + m_xChannelSelector = xChannelSelector; + return true; +} + +ChannelSelectorType FEDisplacementMap::yChannelSelector() const +{ + return m_yChannelSelector; +} + +bool FEDisplacementMap::setYChannelSelector(const ChannelSelectorType yChannelSelector) +{ + if (m_yChannelSelector == yChannelSelector) + return false; + m_yChannelSelector = yChannelSelector; + return true; +} + +float FEDisplacementMap::scale() const +{ + return m_scale; +} + +bool FEDisplacementMap::setScale(float scale) +{ + if (m_scale == scale) + return false; + m_scale = scale; + return true; +} + +void FEDisplacementMap::setResultColorSpace(ColorSpace) +{ + // Spec: The 'color-interpolation-filters' property only applies to the 'in2' source image + // and does not apply to the 'in' source image. The 'in' source image must remain in its + // current color space. + // The result is in that smae color space because it is a displacement of the 'in' image. + FilterEffect::setResultColorSpace(inputEffect(0)->resultColorSpace()); +} + +void FEDisplacementMap::transformResultColorSpace(FilterEffect* in, const int index) +{ + // Do not transform the first primitive input, as per the spec. + if (index) + in->transformResultColorSpace(operatingColorSpace()); +} + +void FEDisplacementMap::platformApplySoftware() +{ + FilterEffect* in = inputEffect(0); + FilterEffect* in2 = inputEffect(1); + + ASSERT(m_xChannelSelector != CHANNEL_UNKNOWN); + ASSERT(m_yChannelSelector != CHANNEL_UNKNOWN); + + Uint8ClampedArray* dstPixelArray = createPremultipliedImageResult(); + if (!dstPixelArray) + return; + + IntRect effectADrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect()); + RefPtr srcPixelArrayA = in->asPremultipliedImage(effectADrawingRect); + + IntRect effectBDrawingRect = requestedRegionOfInputImageData(in2->absolutePaintRect()); + RefPtr srcPixelArrayB = in2->asUnmultipliedImage(effectBDrawingRect); + + ASSERT(srcPixelArrayA->length() == srcPixelArrayB->length()); + + Filter* filter = this->filter(); + IntSize paintSize = absolutePaintRect().size(); + float scaleX = filter->applyHorizontalScale(m_scale); + float scaleY = filter->applyVerticalScale(m_scale); + float scaleForColorX = scaleX / 255.0; + float scaleForColorY = scaleY / 255.0; + float scaledOffsetX = 0.5 - scaleX * 0.5; + float scaledOffsetY = 0.5 - scaleY * 0.5; + int stride = paintSize.width() * 4; + for (int y = 0; y < paintSize.height(); ++y) { + int line = y * stride; + for (int x = 0; x < paintSize.width(); ++x) { + int dstIndex = line + x * 4; + int srcX = x + static_cast(scaleForColorX * srcPixelArrayB->item(dstIndex + m_xChannelSelector - 1) + scaledOffsetX); + int srcY = y + static_cast(scaleForColorY * srcPixelArrayB->item(dstIndex + m_yChannelSelector - 1) + scaledOffsetY); + for (unsigned channel = 0; channel < 4; ++channel) { + if (srcX < 0 || srcX >= paintSize.width() || srcY < 0 || srcY >= paintSize.height()) + dstPixelArray->set(dstIndex + channel, static_cast(0)); + else { + unsigned char pixelValue = srcPixelArrayA->item(srcY * stride + srcX * 4 + channel); + dstPixelArray->set(dstIndex + channel, pixelValue); + } + } + } + } +} + +void FEDisplacementMap::dump() +{ +} + +static TextStream& operator<<(TextStream& ts, const ChannelSelectorType& type) +{ + switch (type) { + case CHANNEL_UNKNOWN: + ts << "UNKNOWN"; + break; + case CHANNEL_R: + ts << "RED"; + break; + case CHANNEL_G: + ts << "GREEN"; + break; + case CHANNEL_B: + ts << "BLUE"; + break; + case CHANNEL_A: + ts << "ALPHA"; + break; + } + return ts; +} + +TextStream& FEDisplacementMap::externalRepresentation(TextStream& ts, int indent) const +{ + writeIndent(ts, indent); + ts << "[feDisplacementMap"; + FilterEffect::externalRepresentation(ts); + ts << " scale=\"" << m_scale << "\" " + << "xChannelSelector=\"" << m_xChannelSelector << "\" " + << "yChannelSelector=\"" << m_yChannelSelector << "\"]\n"; + inputEffect(0)->externalRepresentation(ts, indent + 1); + inputEffect(1)->externalRepresentation(ts, indent + 1); + return ts; +} + +} // namespace WebCore + +#endif // ENABLE(FILTERS) diff --git a/pool/shard001/C++/0018471_327_Count_of_Range_Sum.cpp b/pool/shard001/C++/0018471_327_Count_of_Range_Sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..997b25e6a5430a2f0c0ba0a782b8984b0bb792db --- /dev/null +++ b/pool/shard001/C++/0018471_327_Count_of_Range_Sum.cpp @@ -0,0 +1,86 @@ +// +// 327_Count_of_Range_Sum.cpp +// leetcode +// +// Created by Suhwan Hwang on 2017. 1. 19.. +// Copyright © 2017년 Suhwan Hwang. All rights reserved. +// + +#include +#include +#include + +using namespace std; + +class Solution { +private: + int lower; + int upper; + vector sums; + + int countRangeSumCross(int left, int right) { + int mid = (left + right) / 2; + int count = 0; + int l = mid + 1; + int u = mid + 1; + for (int i = left; i <= mid; ++i) { + while(l <= right && sums[l] - sums[i] < lower) l++; + while(u <= right && sums[u] - sums[i] <= upper) u++; + count += (u - l); + } + + vector tmp; + + int i = left; + int j = mid + 1; + while (tmp.size() < right - left + 1) { + if (i <= mid && (j > right || sums[i] < sums[j])) { + tmp.push_back(sums[i++]); + } else { + tmp.push_back(sums[j++]); + } + } + copy(tmp.begin(), tmp.end(), sums.begin() + left); + + return count; + } + + int countRangeSumDnQ(int left, int right) { + if (left == right) { + return 0; + } + + int mid = (left + right) / 2; + int left_count = countRangeSumDnQ(left, mid); + int right_count = countRangeSumDnQ(mid + 1, right); + int cross_count = countRangeSumCross(left, right); + + return left_count + right_count + cross_count; + } + +public: + int countRangeSum(vector& nums, int lower, int upper) { + if (nums.empty()) { + return 0; + } + + this->lower = lower; + this->upper = upper; + sums.clear(); + sums.push_back(0); + for (int i = 0;i < nums.size(); ++i) { + sums.push_back(sums.back() + nums[i]); + } + + return countRangeSumDnQ(0, (int)sums.size() - 1); + } +}; + +int main(void) +{ + Solution s; + vector nums{-2, 5, -1}; + + cout << s.countRangeSum(nums, -2, 2) << endl; + return 0; +} diff --git a/pool/shard001/C++/0018474_DOMTokenList.cpp b/pool/shard001/C++/0018474_DOMTokenList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b434de742135c97e057c103ca3a1c70f0ba875c1 --- /dev/null +++ b/pool/shard001/C++/0018474_DOMTokenList.cpp @@ -0,0 +1,249 @@ +/* + * 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: + * 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 APPLE INC. AND ITS 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 APPLE INC. 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. + */ + +#include "config.h" +#include "core/dom/DOMTokenList.h" + +#include "bindings/core/v8/ExceptionState.h" +#include "core/dom/ExceptionCode.h" +#include "core/html/parser/HTMLParserIdioms.h" +#include "wtf/text/StringBuilder.h" + +namespace blink { + +bool DOMTokenList::validateToken(const String& token, ExceptionState& exceptionState) +{ + if (token.isEmpty()) { + exceptionState.throwDOMException(SyntaxError, "The token provided must not be empty."); + return false; + } + + if (token.find(isHTMLSpace) != kNotFound) { + exceptionState.throwDOMException(InvalidCharacterError, "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens."); + return false; + } + + return true; +} + +bool DOMTokenList::validateTokens(const Vector& tokens, ExceptionState& exceptionState) +{ + for (size_t i = 0; i < tokens.size(); ++i) { + if (!validateToken(tokens[i], exceptionState)) + return false; + } + + return true; +} + +bool DOMTokenList::contains(const AtomicString& token, ExceptionState& exceptionState) const +{ + if (!validateToken(token, exceptionState)) + return false; + return containsInternal(token); +} + +void DOMTokenList::add(const AtomicString& token, ExceptionState& exceptionState) +{ + Vector tokens; + tokens.append(token.string()); + add(tokens, exceptionState); +} + +// Optimally, this should take a Vector const ref in argument but the +// bindings generator does not handle that. +void DOMTokenList::add(const Vector& tokens, ExceptionState& exceptionState) +{ + Vector filteredTokens; + filteredTokens.reserveCapacity(tokens.size()); + for (size_t i = 0; i < tokens.size(); ++i) { + if (!validateToken(tokens[i], exceptionState)) + return; + if (containsInternal(AtomicString(tokens[i]))) + continue; + if (filteredTokens.contains(tokens[i])) + continue; + filteredTokens.append(tokens[i]); + } + + if (filteredTokens.isEmpty()) + return; + + setValue(addTokens(value(), filteredTokens)); +} + +void DOMTokenList::remove(const AtomicString& token, ExceptionState& exceptionState) +{ + Vector tokens; + tokens.append(token.string()); + remove(tokens, exceptionState); +} + +// Optimally, this should take a Vector const ref in argument but the +// bindings generator does not handle that. +void DOMTokenList::remove(const Vector& tokens, ExceptionState& exceptionState) +{ + if (!validateTokens(tokens, exceptionState)) + return; + + // Check using containsInternal first since it is a lot faster than going + // through the string character by character. + bool found = false; + for (size_t i = 0; i < tokens.size(); ++i) { + if (containsInternal(AtomicString(tokens[i]))) { + found = true; + break; + } + } + + if (found) + setValue(removeTokens(value(), tokens)); +} + +bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& exceptionState) +{ + if (!validateToken(token, exceptionState)) + return false; + + if (containsInternal(token)) { + removeInternal(token); + return false; + } + addInternal(token); + return true; +} + +bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& exceptionState) +{ + if (!validateToken(token, exceptionState)) + return false; + + if (force) + addInternal(token); + else + removeInternal(token); + + return force; +} + +void DOMTokenList::addInternal(const AtomicString& token) +{ + if (!containsInternal(token)) + setValue(addToken(value(), token)); +} + +void DOMTokenList::removeInternal(const AtomicString& token) +{ + // Check using contains first since it uses AtomicString comparisons instead + // of character by character testing. + if (!containsInternal(token)) + return; + setValue(removeToken(value(), token)); +} + +AtomicString DOMTokenList::addToken(const AtomicString& input, const AtomicString& token) +{ + Vector tokens; + tokens.append(token.string()); + return addTokens(input, tokens); +} + +// This returns an AtomicString because it is always passed as argument to setValue() and setValue() +// takes an AtomicString in argument. +AtomicString DOMTokenList::addTokens(const AtomicString& input, const Vector& tokens) +{ + bool needsSpace = false; + + StringBuilder builder; + if (!input.isEmpty()) { + builder.append(input); + needsSpace = !isHTMLSpace(input[input.length() - 1]); + } + + for (size_t i = 0; i < tokens.size(); ++i) { + if (needsSpace) + builder.append(' '); + builder.append(tokens[i]); + needsSpace = true; + } + + return builder.toAtomicString(); +} + +AtomicString DOMTokenList::removeToken(const AtomicString& input, const AtomicString& token) +{ + Vector tokens; + tokens.append(token.string()); + return removeTokens(input, tokens); +} + +// This returns an AtomicString because it is always passed as argument to setValue() and setValue() +// takes an AtomicString in argument. +AtomicString DOMTokenList::removeTokens(const AtomicString& input, const Vector& tokens) +{ + // Algorithm defined at http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#remove-a-token-from-a-string + // New spec is at http://dom.spec.whatwg.org/#remove-a-token-from-a-string + + unsigned inputLength = input.length(); + StringBuilder output; // 3 + output.reserveCapacity(inputLength); + unsigned position = 0; // 4 + + // Step 5 + while (position < inputLength) { + if (isHTMLSpace(input[position])) { // 6 + output.append(input[position++]); // 6.1, 6.2 + continue; // 6.3 + } + + // Step 7 + StringBuilder tokenBuilder; + while (position < inputLength && isNotHTMLSpace(input[position])) + tokenBuilder.append(input[position++]); + + // Step 8 + String token = tokenBuilder.toString(); + if (tokens.contains(token)) { + // Step 8.1 + while (position < inputLength && isHTMLSpace(input[position])) + ++position; + + // Step 8.2 + size_t j = output.length(); + while (j > 0 && isHTMLSpace(output[j - 1])) + --j; + output.resize(j); + + // Step 8.3 + if (position < inputLength && !output.isEmpty()) + output.append(' '); + } else { + output.append(token); // Step 9 + } + } + + return output.toAtomicString(); +} + +} // namespace blink diff --git a/pool/shard001/C++/0018476_VideoSystem.cpp b/pool/shard001/C++/0018476_VideoSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..640284d20373ed77bf587007c7fbed9f88919a21 --- /dev/null +++ b/pool/shard001/C++/0018476_VideoSystem.cpp @@ -0,0 +1,198 @@ +/* + * halfmapper, a renderer for GoldSrc maps and chapters. + * + * Copyright(C) 2014 Gonzalo Ávila "gzalo" Alterach + * Copyright(C) 2015 Anthony "birkett" Birkett + * + * This file is part of halfmapper. + * + * 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 http://www.gnu.org/licenses/ + */ +#include +#include +#include +#include "VideoSystem.h" + +/** + * Set the basic configuration of the window and renderer. + * \param iWidth Window width. + * \param iHeight Window height. + * \param fFox Field of View angle. + * \param bFullscreen Fullscreen or Windowed mode. + * \param bMultisampling Enable or disable multisampling. + * \param bVsync Enable or disable Vsync. + */ +VideoSystem::VideoSystem(int iWidth, int iHeight, float fFov, bool bFullscreen, bool bMultisampling, bool bVsync) +{ + m_iWidth = iWidth; + m_iHeight = iHeight; + m_fFov = fFov; + m_bFullscreen = bFullscreen; + m_bMultisampling = bMultisampling; + m_bVsync = bVsync; + +}//end VideoSystem::VideoSystem() + + +/** + * Cleanup the renderer. + */ +VideoSystem::~VideoSystem() +{ + SDL_GL_DeleteContext(this->sdlGLContext); + SDL_DestroyWindow(this->sdlWindow); + +}//end VideoSystem::~VideoSystem() + + +/** + * Create the window and GL context. + */ +int VideoSystem::Init() +{ + if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { + std::cerr << "Can't initialize SDL." << std::endl; + return -1; + } + + unsigned int windowflags = SDL_WINDOW_OPENGL; + + if (this->m_bFullscreen) { + windowflags |= SDL_WINDOW_FULLSCREEN; + } + + this->SetMultisampling(this->m_bMultisampling); // Setup multisampling before creating the window. + + this->sdlWindow = SDL_CreateWindow("HalfMapper (loading maps, please wait)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->m_iWidth, this->m_iHeight, windowflags); + + if (this->sdlWindow == NULL) { + std::cerr << "Can't create SDL window." << std::endl; + return -1; + } + + this->sdlGLContext = SDL_GL_CreateContext(this->sdlWindow); + + if (this->sdlGLContext == NULL) { + std::cerr << "Can't create OpenGL Context." << std::endl; + return -1; + } + + SDL_GL_MakeCurrent(this->sdlWindow, this->sdlGLContext); + + if (glewInit() != GLEW_OK) { + std::cerr << "Can't initialize Glew." << std::endl; + return -1; + } + + SDL_SetRelativeMouseMode(SDL_TRUE); + + this->SetVsync(this->m_bVsync); // Set Vsync after creating the GL context. + + this->SetupViewport(); + + return 0; + +}//end VideoSystem::Init() + + +/** + * Clear the buffer. + */ +void VideoSystem::ClearBuffer() +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + +}//end VideoSystem::ClearBuffer() + + +/** + * Swap the buffers (double buffering). + */ +void VideoSystem::SwapBuffers() +{ + SDL_GL_SwapWindow(this->sdlWindow); + +}//end VideoSystem::SwapBuffers() + + +/** + * Set the title of the program window. + * \param szTitle New window title. + */ +void VideoSystem::SetWindowTitle(const char* szTitle) +{ + SDL_SetWindowTitle(this->sdlWindow, szTitle); + +}//end VideoSystem::SetWindowTitle() + + +/** + * Set the perspective of the viewport, and set some GL hints. + */ +void VideoSystem::SetupViewport() +{ + glViewport(0, 0, this->m_iWidth, this->m_iHeight); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(this->m_fFov, (float)this->m_iWidth / (float)this->m_iHeight, 20.0f, 50000.0f); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glShadeModel(GL_SMOOTH); + glEnable(GL_DEPTH_TEST); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.8f); + glDepthFunc(GL_LEQUAL); + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); + glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + glEnable(GL_TEXTURE_2D); + +}//end VideoSystem::SetupViewport() + + +/** + * Enable or disable multisampling for the GL context. + * \param bEnable Enable or Disable. + */ +void VideoSystem::SetMultisampling(bool bEnable) +{ + if (bEnable) { + glEnable(GL_MULTISAMPLE); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); + } + else { + glDisable(GL_MULTISAMPLE); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); + } + + this->m_bMultisampling = bEnable; + +}//end VideoSystem::SetMultiSampling() + + +/** + * Enable or disable Vsync for the GL context. + * \param bEnable Enable or Disable. + */ +void VideoSystem::SetVsync(bool bEnable) +{ + bEnable ? SDL_GL_SetSwapInterval(1) : SDL_GL_SetSwapInterval(0); + this->m_bVsync = bEnable; + +}//end VideoSystem::SetVsync() diff --git a/pool/shard001/C++/0018480_QTMovieTask.cpp b/pool/shard001/C++/0018480_QTMovieTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87135881f561061b935613f88a0287cc190ad667 --- /dev/null +++ b/pool/shard001/C++/0018480_QTMovieTask.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2007, 2008, 2009, 2010 Apple, 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "QTMovieTask.h" + +// Put Movies.h first so build failures here point clearly to QuickTime +#include + +#include +#include +#include + +QTMovieTask::QTMovieTask() + : m_setTaskTimerDelay(0) + , m_stopTaskTimer(0) +{ +} + +QTMovieTask::~QTMovieTask() +{ +} + +QTMovieTask* QTMovieTask::sharedTask() +{ + static QTMovieTask* s_sharedTask = new QTMovieTask; + return s_sharedTask; +} + +void QTMovieTask::updateTaskTimer(double maxInterval, double minInterval) +{ + ASSERT(m_setTaskTimerDelay); + if (!m_setTaskTimerDelay) + return; + + ASSERT(m_stopTaskTimer); + if (!m_taskList.size() && m_stopTaskTimer) { + m_stopTaskTimer(); + return; + } + + long intervalInMS; + OSStatus status = QTGetTimeUntilNextTask(&intervalInMS, 1000); + double interval = intervalInMS / 1000.0; + if (interval < minInterval) + interval = minInterval; + if (interval > maxInterval) + interval = maxInterval; + m_setTaskTimerDelay(interval); +} + +void QTMovieTask::fireTaskClients() +{ + Vector clients; + copyToVector(m_taskList, clients); + for (Vector::iterator i = clients.begin(); i != clients.end(); ++i) + (*i)->task(); +} + +void QTMovieTask::addTaskClient(QTMovieTaskClient* client) +{ + ASSERT(client); + if (!client) + return; + + m_taskList.add(client); +} + +void QTMovieTask::removeTaskClient(QTMovieTaskClient* client) +{ + ASSERT(client); + if (!client) + return; + + m_taskList.remove(client); +} + +void QTMovieTask::setTaskTimerFuncs(SetTaskTimerDelayFunc setTaskTimerDelay, StopTaskTimerFunc stopTaskTimer) +{ + m_setTaskTimerDelay = setTaskTimerDelay; + m_stopTaskTimer = stopTaskTimer; +} + diff --git a/pool/shard001/C++/0018482_hsQuat.cpp b/pool/shard001/C++/0018482_hsQuat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ca5354765f60971240b28fb86d77c1e99b8c6de --- /dev/null +++ b/pool/shard001/C++/0018482_hsQuat.cpp @@ -0,0 +1,66 @@ +/* This file is part of HSPlasma. + * + * HSPlasma 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. + * + * HSPlasma 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 HSPlasma. If not, see . + */ + +#include "hsQuat.h" +#include + +hsQuat::hsQuat(float rad, const hsVector3& axis) { + W = cos(rad * 0.5f); + X = sin(rad * 0.5f) * axis.X; + Y = sin(rad * 0.5f) * axis.Y; + Z = sin(rad * 0.5f) * axis.Z; +} + +hsQuat& hsQuat::operator=(const hsQuat& cpy) { + X = cpy.X; + Y = cpy.Y; + Z = cpy.Z; + W = cpy.W; + return *this; +} + +void hsQuat::read(hsStream* S) { + X = S->readFloat(); + Y = S->readFloat(); + Z = S->readFloat(); + W = S->readFloat(); +} + +void hsQuat::write(hsStream* S) { + S->writeFloat(X); + S->writeFloat(Y); + S->writeFloat(Z); + S->writeFloat(W); +} + +void hsQuat::prcWrite(pfPrcHelper* prc) { + prc->startTag("hsQuat"); + prc->writeParam("X", X); + prc->writeParam("Y", Y); + prc->writeParam("Z", Z); + prc->writeParam("W", W); + prc->endTag(true); +} + +void hsQuat::prcParse(const pfPrcTag* tag) { + if (tag->getName() != "hsQuat") + throw pfPrcTagException(__FILE__, __LINE__, tag->getName()); + + X = tag->getParam("X", "0").toFloat(); + Y = tag->getParam("Y", "0").toFloat(); + Z = tag->getParam("Z", "0").toFloat(); + W = tag->getParam("W", "1").toFloat(); +} diff --git a/pool/shard001/C++/0018485_scheduler.cpp b/pool/shard001/C++/0018485_scheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c16fcc2f56fe964810fe2211390d8e73a9be13f --- /dev/null +++ b/pool/shard001/C++/0018485_scheduler.cpp @@ -0,0 +1,149 @@ +#include +#include "tls.hpp" +#include "scheduler.hpp" +#include "messagestrategy.hpp" + +namespace pasl { +namespace sched { +namespace scheduler { + + +/***********************************************************************/ + +util::worker::controller_factory_t* the_factory; + +bool _private::stay() { + return ! periodic_set.empty() || ! util::worker::the_group.exit_controller(); +} + +/*---------------------------------------------------------------------*/ +/* Methods required by worker::controller_t */ + +void _private::init() { + controller_t::init(); + //add_periodic(messagestrategy::the_messagestrategy); + current_thread = nullptr; + should_communicate = false; +} + +void _private::destroy() { + controller_t::destroy(); + //rem_periodic(messagestrategy::the_messagestrategy); +} + +void _private::new_launch() { + //STAT_ONLY(date_enter_wait = ticks::now()); + STAT_IDLE_ONLY(date_enter_wait = util::microtime::now()); +} + +void _private::enter_wait() { + LOG_BASIC(ENTER_WAIT); + STAT_COUNT(ENTER_WAIT); + // STAT_IDLE_ONLY(date_enter_wait = ticks::now()); + STAT_IDLE_ONLY(date_enter_wait = util::microtime::now()); + util::worker::controller_t::enter_wait(); +} + +void _private::exit_wait() { + util::worker::controller_t::exit_wait(); + //STAT_IDLE(add_to_idle_time(ticks::seconds_since(date_enter_wait))); + //debug: atomic::aprintf("%f\n", microtime::seconds_since(date_enter_wait)); + STAT_IDLE(add_to_idle_time(util::microtime::seconds_since(date_enter_wait))); + LOG_BASIC(EXIT_WAIT); +} + +/*---------------------------------------------------------------------*/ +/* Thread management */ + +// later: move somewhere else +template +void pasl_delete(Pointer p) { + delete p; + // util::atomic::aprintf("%lld deleting p=%p\n",util::worker::get_my_id(),p); +} + +void _private::exec(thread_p t) { + assert(t != nullptr); + LOG_THREAD(THREAD_EXEC, t); + STAT_COUNT(THREAD_EXEC); +#ifdef TRACK_LOCALITY + LOG_EVENT(LOCALITY, new util::logging::locality_event_t(logging::LOCALITY_START, t->locality.low)); +#endif + bool should_not_deallocate = t->should_not_deallocate; + reuse_thread_requested = false; + current_thread = t; + current_outstrategy = t->out; + t->out = nullptr; // optional + interrupt_was_blocked = false; + if (interrupt_was_blocked) + check_on_interrupt(); + allow_interrupt = true; + t->exec(); + allow_interrupt = false; +#ifdef TRACK_LOCALITY + LOG_EVENT(LOCALITY, new util::logging::locality_event_t(logging::LOCALITY_STOP, t->locality.hi)); +#endif + //! \todo could handle interrupt_was_blocked + if (should_not_deallocate || reuse_thread_requested) + t->reset_caches(); + else + pasl_delete(t); + LOG_THREAD(THREAD_FINISH, t); + outstrategy::finished(t, current_outstrategy); + current_outstrategy = nullptr; // optional + current_thread = nullptr; // would probably be optional when assertions are disabled +} + +void _private::add_thread(thread_p t) { + instrategy::init(t->in, t); + LOG_THREAD(THREAD_CREATE, t); + STAT_COUNT(THREAD_CREATE); +} + +void _private::add_dependency(thread_p t1, thread_p t2) { + assert (t1->out != nullptr); + assert (t2->in != nullptr); + outstrategy::add(t1->out, t2); + instrategy::delta(t2->in, t2, +1l); +} + +outstrategy_p _private::capture_outstrategy() { + assert (current_outstrategy != nullptr); + outstrategy_p out = current_outstrategy; + current_outstrategy = outstrategy::noop_new(); + return out; +} + +void _private::decr_dependencies(thread_p t) { + instrategy::delta(t->in, t, -1l); +} + +void _private::reuse_calling_thread() { + reuse_thread_requested = true; +} + +thread_p _private::get_current_thread() const { + return current_thread; +} + +void _private::schedule(thread_p t) { + t->in = nullptr; + assert (t->out != nullptr); + LOG_THREAD(THREAD_SCHEDULE, t); + if (! allow_interrupt) + add_to_pool_of_ready_threads(t); + else { + interrupt_was_blocked = false; + allow_interrupt = false; + add_to_pool_of_ready_threads(t); + if (interrupt_was_blocked) + check_on_interrupt(); + allow_interrupt = true; + } +} + +/***********************************************************************/ + +} // end namespace +} // end namespace +} // end namespace diff --git a/pool/shard001/C++/0018490_E_24_fattoriale_con_sottoprogrammi.cpp b/pool/shard001/C++/0018490_E_24_fattoriale_con_sottoprogrammi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c27153a27a6b6137556b7bd8ca1ef12a749d56de --- /dev/null +++ b/pool/shard001/C++/0018490_E_24_fattoriale_con_sottoprogrammi.cpp @@ -0,0 +1,33 @@ +#include +#include +/* +program:fattoriale con sottoprogramma +Diego Gattari +3INA +13/09/2017 +versione 1.0 +*/ +int main () { + int r; + int n; + + do{//ciclo per rendere l'inserimento del numero corretto + printf("Inserisci un numero: "); + scanf("%d", & n); + }while(n<0); + r=fat_n(int n);//operazione che richiama il sottoprogramma + printf("Il fattoriale è: %d", r); + system("PAUSE"); +} + +int fat_n (int n){//sottoprogramma + int a; + a=1; + if(n>=0){ + while(n!=0){ + a=a*n; + n--; + } + } + return a; +} diff --git a/pool/shard001/C++/0018496_loadxml.cpp b/pool/shard001/C++/0018496_loadxml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99a2f9ed0e445b64a62fecae66eed988d8ebfc31 --- /dev/null +++ b/pool/shard001/C++/0018496_loadxml.cpp @@ -0,0 +1,297 @@ +//%2005//////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development +// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. +// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; +// IBM Corp.; EMC Corporation, The Open Group. +// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; +// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. +// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; +// EMC Corporation; VERITAS Software Corporation; The Open Group. +// +// 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. +// +//============================================================================== +// +// Author: Karl Schopmeyer (k.schopmeyer@opengroup.org) +// +// Modified By: +// +//%///////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include + +PEGASUS_USING_PEGASUS; +PEGASUS_USING_STD; + +static const String CIMV2_NAMESPACE = "root/cimv2"; +static const String ROOT_NAMESPACE = "root"; + +//------------------------------------------------------------------------------ +// ProcessValueObjectElement() +// +// +// +// ATTN: Nothing handled but CLASS. +// +//------------------------------------------------------------------------------ + +Boolean ProcessValueObjectElement(CIMRepository& repository, XmlParser& parser) +{ + XmlEntry entry; + + if (!XmlReader::testStartTag(parser, entry, "VALUE.OBJECT")) + return false; + + CIMClass cimClass; + CIMQualifierDecl qualifierDecl; + + if (XmlReader::getClassElement(parser, cimClass)) + { + cout << "Creating: class "; + cout << cimClass.getClassName() << endl; + + repository.createClass(CIMV2_NAMESPACE, cimClass); + repository.createClass(ROOT_NAMESPACE, cimClass); + } + else if (XmlReader::getQualifierDeclElement(parser, qualifierDecl)) + { + cout << "Creating: qualifier "; + cout << qualifierDecl.getName() << endl; + + repository.setQualifier(CIMV2_NAMESPACE, qualifierDecl); + repository.setQualifier(ROOT_NAMESPACE, qualifierDecl); + } + + XmlReader::expectEndTag(parser, "VALUE.OBJECT"); + + return true; +} + +//------------------------------------------------------------------------------ +// ProcessDeclGroupElement() +// +// +// +// ATTN: Nothing handled but VALUE.OBJECT: +// +//------------------------------------------------------------------------------ + +Boolean ProcessDeclGroupElement(CIMRepository& repository, XmlParser& parser) +{ + XmlEntry entry; + + if (!XmlReader::testStartTag(parser, entry, "DECLGROUP")) + return false; + + while (ProcessValueObjectElement(repository, parser)) + ; + + XmlReader::expectEndTag(parser, "DECLGROUP"); + + return true; +} + +//------------------------------------------------------------------------------ +// ProcessDeclarationElement() +// +// +// +// ATTN: DECLGROUP.WITHNAME ande DECLGROUP.WITHPATH not handled: +// +//------------------------------------------------------------------------------ + +Boolean ProcessDeclarationElement(CIMRepository& repository, XmlParser& parser) +{ + XmlEntry entry; + + if (!XmlReader::testStartTag(parser, entry, "DECLARATION")) + return false; + + while(ProcessDeclGroupElement(repository, parser)) + ; + + XmlReader::expectEndTag(parser, "DECLARATION"); + + return true; +} + +//------------------------------------------------------------------------------ +// ProcessCimElement() +// +// +// +// +// ATTN: only declarations are handled here! +// +//------------------------------------------------------------------------------ + +Boolean ProcessCimElement(CIMRepository& repository, XmlParser& parser) +{ + XmlEntry entry; + + if (!parser.next(entry) || entry.type != XmlEntry::XML_DECLARATION) + { + throw(parser.getLine(), "expected XML declaration"); + } + + if (!XmlReader::testStartTag(parser, entry, "CIM")) + return false; + + String cimVersion; + + if (!entry.getAttributeValue("CIMVERSION", cimVersion)) + { + throw XmlValidationError(parser.getLine(), + "missing CIM.CIMVERSION attribute"); + } + + String dtdVersion; + + if (!entry.getAttributeValue("DTDVERSION", dtdVersion)) + { + throw XmlValidationError(parser.getLine(), + "missing CIM.DTDVERSION attribute"); + } + + if (!ProcessDeclarationElement(repository, parser)) + { + throw XmlValidationError(parser.getLine(), + "Expected DECLARATION element"); + } + + XmlReader::expectEndTag(parser, "CIM"); + + return true; +} + +//------------------------------------------------------------------------------ +// +// _processFile() +// +//------------------------------------------------------------------------------ + +static void _processFile(const char* xmlFileName, + const char* nameSpace, + const char* repositoryRoot) +{ + // Create the parser: + + Array text; + text.reserve(1024 * 1024); + FileSystem::loadFileToMemory(text, xmlFileName); + text.append('\0'); + XmlParser parser((char*)text.getData()); + + CIMRepository repository(repositoryRoot); + // Need to test if namespace exists before adding it + repository.createNameSpace(nameSpace); + + // Put the file in the repository: + + if (!ProcessCimElement(repository, parser)) + { + cerr << "CIM root element missing" << endl; + exit(1); + } +} + +static void Usage(const char* name, const char* message) +{ + cerr << "Usage: " << name << " xmlfile namespace repository-root" << endl; + cerr << name << "Installs an XML file containing CIM classes and instances "; + cerr << "into the repository." << endl; + cerr << "ex. " << name << " x.xml /root/cimv2/ " << endl; + cerr << message; +} + +//------------------------------------------------------------------------------ +// +// main() +// +//------------------------------------------------------------------------------ + +int main(int argc, char** argv) +{ + String name = argv[0]; + String message = ""; + if ((argc > 4) || (argc < 2)) + { + Usage(argv[0], ""); + exit(1); + } + + + try + { + char* repositoryRoot; + char* nameSpace = "CIMv2"; + if (argc == 4) + { + repositoryRoot = argv[3]; + cout << "repository Root " << repositoryRoot << endl; + } + else + { + static char* tmp; + + tmp = getenv("PEGASUS_HOME"); + + if (tmp) + { + repositoryRoot = tmp; + } + else + { + Usage(argv[0], "The Environment variable PEGASUS_HOME could not be found"); + exit(1); + } + + } + cout << "test argc" << argc << endl; + if (argc == 2) + { + nameSpace = argv[2]; + } + cout << "test xmlfile" << endl; + + char* xmlFile = argv[1]; + + cout << argv[0] << " loading " << xmlFile << " to namespace " + << nameSpace << " in repository " << repositoryRoot << endl; + _processFile(argv[1], nameSpace, repositoryRoot); + } + catch (Exception& e) + { + cerr << e.getMessage() << endl; + exit(1); + } + + cout << argv[0] << "loaded" << endl; + + return 0; +} diff --git a/pool/shard001/C++/0018501_DeleteSnapshotResult.cpp b/pool/shard001/C++/0018501_DeleteSnapshotResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7eede327ec29ba4a49bc5867f2069b52c8a583a3 --- /dev/null +++ b/pool/shard001/C++/0018501_DeleteSnapshotResult.cpp @@ -0,0 +1,48 @@ +/** + * 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::FSx::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +DeleteSnapshotResult::DeleteSnapshotResult() : + m_lifecycle(SnapshotLifecycle::NOT_SET) +{ +} + +DeleteSnapshotResult::DeleteSnapshotResult(const Aws::AmazonWebServiceResult& result) : + m_lifecycle(SnapshotLifecycle::NOT_SET) +{ + *this = result; +} + +DeleteSnapshotResult& DeleteSnapshotResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("SnapshotId")) + { + m_snapshotId = jsonValue.GetString("SnapshotId"); + + } + + if(jsonValue.ValueExists("Lifecycle")) + { + m_lifecycle = SnapshotLifecycleMapper::GetSnapshotLifecycleForName(jsonValue.GetString("Lifecycle")); + + } + + + + return *this; +} diff --git a/pool/shard001/C++/0018502_constanthemisphereenvironmentedf.cpp b/pool/shard001/C++/0018502_constanthemisphereenvironmentedf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55cc8c5d34b06c455888466305f9a3290018d9eb --- /dev/null +++ b/pool/shard001/C++/0018502_constanthemisphereenvironmentedf.cpp @@ -0,0 +1,238 @@ + +// +// This source file is part of appleseed. +// Visit http://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited +// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization +// +// 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. +// + +// Interface header. +#include "constanthemisphereenvironmentedf.h" + +// appleseed.renderer headers. +#include "renderer/global/globaltypes.h" +#include "renderer/modeling/environmentedf/environmentedf.h" +#include "renderer/modeling/input/inputarray.h" +#include "renderer/modeling/input/source.h" + +// appleseed.foundation headers. +#include "foundation/math/sampling/mappings.h" +#include "foundation/math/vector.h" +#include "foundation/platform/compiler.h" +#include "foundation/utility/containers/dictionary.h" +#include "foundation/utility/containers/specializedarrays.h" + +// Standard headers. +#include + +// Forward declarations. +namespace foundation { class IAbortSwitch; } +namespace renderer { class InputEvaluator; } +namespace renderer { class Project; } + +using namespace foundation; +using namespace std; + +namespace renderer +{ + +namespace +{ + // + // Per-hemisphere constant-emittance environment EDF. + // + + const char* Model = "constant_hemisphere_environment_edf"; + + class ConstantHemisphereEnvironmentEDF + : public EnvironmentEDF + { + public: + ConstantHemisphereEnvironmentEDF( + const char* name, + const ParamArray& params) + : EnvironmentEDF(name, params) + { + m_inputs.declare("upper_hemi_radiance", InputFormatSpectralIlluminance); + m_inputs.declare("lower_hemi_radiance", InputFormatSpectralIlluminance); + } + + virtual void release() APPLESEED_OVERRIDE + { + delete this; + } + + virtual const char* get_model() const APPLESEED_OVERRIDE + { + return Model; + } + + virtual bool on_frame_begin( + const Project& project, + IAbortSwitch* abort_switch) APPLESEED_OVERRIDE + { + if (!EnvironmentEDF::on_frame_begin(project, abort_switch)) + return false; + + if (!check_uniform("upper_hemi_radiance") || !check_uniform("lower_hemi_radiance")) + return false; + + if (is_uniform_zero_spectrum("upper_hemi_radiance") && is_uniform_zero_spectrum("lower_hemi_radiance")) + warn_zero_emission(); + + m_inputs.evaluate_uniforms(&m_values); + + return true; + } + + virtual void sample( + const ShadingContext& shading_context, + InputEvaluator& input_evaluator, + const Vector2d& s, + Vector3d& outgoing, + Spectrum& value, + double& probability) const APPLESEED_OVERRIDE + { + outgoing = sample_sphere_uniform(s); + value = + outgoing.y >= 0.0 + ? m_values.m_upper_hemi_radiance + : m_values.m_lower_hemi_radiance; + probability = RcpFourPi; + } + + virtual void evaluate( + const ShadingContext& shading_context, + InputEvaluator& input_evaluator, + const Vector3d& outgoing, + Spectrum& value) const APPLESEED_OVERRIDE + { + assert(is_normalized(outgoing)); + value = + outgoing.y >= 0.0 + ? m_values.m_upper_hemi_radiance + : m_values.m_lower_hemi_radiance; + } + + virtual void evaluate( + const ShadingContext& shading_context, + InputEvaluator& input_evaluator, + const Vector3d& outgoing, + Spectrum& value, + double& probability) const APPLESEED_OVERRIDE + { + assert(is_normalized(outgoing)); + value = + outgoing.y >= 0.0 + ? m_values.m_upper_hemi_radiance + : m_values.m_lower_hemi_radiance; + probability = RcpFourPi; + } + + virtual double evaluate_pdf( + InputEvaluator& input_evaluator, + const Vector3d& outgoing) const APPLESEED_OVERRIDE + { + assert(is_normalized(outgoing)); + return RcpFourPi; + } + + private: + APPLESEED_DECLARE_INPUT_VALUES(InputValues) + { + Spectrum m_upper_hemi_radiance; // radiance emitted by the upper hemisphere, in W.m^-2.sr^-1 + Spectrum m_lower_hemi_radiance; // radiance emitted by the lower hemisphere, in W.m^-2.sr^-1 + }; + + InputValues m_values; + }; +} + + +// +// ConstantHemisphereEnvironmentEDFFactory class implementation. +// + +const char* ConstantHemisphereEnvironmentEDFFactory::get_model() const +{ + return Model; +} + +Dictionary ConstantHemisphereEnvironmentEDFFactory::get_model_metadata() const +{ + return + Dictionary() + .insert("name", Model) + .insert("label", "Per-Hemisphere Constant Environment EDF") + .insert("help", "An environment made of two hemispheres of constant radiance"); +} + +DictionaryArray ConstantHemisphereEnvironmentEDFFactory::get_input_metadata() const +{ + DictionaryArray metadata; + + metadata.push_back( + Dictionary() + .insert("name", "upper_hemi_radiance") + .insert("label", "Upper Hemisphere Radiance") + .insert("type", "colormap") + .insert("entity_types", + Dictionary().insert("color", "Colors")) + .insert("use", "required") + .insert("default", "0.7") + .insert("help", "Upper hemisphere radiance")); + + metadata.push_back( + Dictionary() + .insert("name", "lower_hemi_radiance") + .insert("label", "Lower Hemisphere Radiance") + .insert("type", "colormap") + .insert("entity_types", + Dictionary().insert("color", "Colors")) + .insert("use", "required") + .insert("default", "0.3") + .insert("help", "Lower hemisphere radiance")); + + return metadata; +} + +auto_release_ptr ConstantHemisphereEnvironmentEDFFactory::create( + const char* name, + const ParamArray& params) const +{ + return + auto_release_ptr( + new ConstantHemisphereEnvironmentEDF(name, params)); +} + +auto_release_ptr ConstantHemisphereEnvironmentEDFFactory::static_create( + const char* name, + const ParamArray& params) +{ + return + auto_release_ptr( + new ConstantHemisphereEnvironmentEDF(name, params)); +} + +} // namespace renderer diff --git a/pool/shard001/C++/0018507_KoApplication.cpp b/pool/shard001/C++/0018507_KoApplication.cpp new file mode 100644 index 0000000000000000000000000000000000000000..399d312a2e896611aab35a19e3ab34798f3b1b56 --- /dev/null +++ b/pool/shard001/C++/0018507_KoApplication.cpp @@ -0,0 +1,260 @@ +/* This file is part of the KDE project + Copyright (C) 1998, 1999 Torben Weis + Copyright (C) 2009 Thomas Zander + + 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 "KoApplication.h" + +#include "KoGlobal.h" +#include "KoApplicationAdaptor.h" +#include "KoPrintJob.h" +#include "KoQueryTrader.h" +#include "KoDocument.h" +#include "KoMainWindow.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void qt_generate_epsf(bool b); + +bool KoApplication::m_starting = true; + +class KoApplicationPrivate +{ +public: + KoApplicationPrivate() { +// m_appIface = 0L; + } +// KoApplicationIface *m_appIface; // to avoid a leak +}; + +KoApplication::KoApplication() + : KApplication(initHack()) + , d(new KoApplicationPrivate) +{ + // Tell the iconloader about share/apps/koffice/icons + KIconLoader::global()->addAppDir("koffice"); + + // Initialize all KOffice directories etc. + KoGlobal::initialize(); + + new KoApplicationAdaptor(this); + QDBusConnection::sessionBus().registerObject("/application", this); + + m_starting = true; +} + +// This gets called before entering KApplication::KApplication +bool KoApplication::initHack() +{ + KCmdLineOptions options; + options.add("print", ki18n("Only print and exit")); + options.add("template", ki18n("Open a new document with a template")); + options.add("dpi ", ki18n("Override display DPI")); + options.add("export-pdf", ki18n("Only export to PDF and exit")); + options.add("export-filename ", ki18n("Filename for export-pdf")); + KCmdLineArgs::addCmdLineOptions(options, ki18n("KOffice"), "koffice", "kde"); + return true; +} + +// Small helper for start() so that we don't forget to reset m_starting before a return +class KoApplication::ResetStarting +{ +public: + ~ResetStarting() { + KoApplication::m_starting = false; + } +}; + +bool KoApplication::start() +{ + ResetStarting resetStarting; // reset m_starting to false when we're done + Q_UNUSED(resetStarting); + + // Find the *.desktop file corresponding to the kapp instance name + KoDocumentEntry entry = KoDocumentEntry(KoDocument::readNativeService()); + if (entry.isEmpty()) { + kError(30003) << KGlobal::mainComponent().componentName() << "part.desktop not found." << endl; + kError(30003) << "Run 'kde4-config --path services' to see which directories were searched, assuming kde startup had the same environment as your current shell." << endl; + kError(30003) << "Check your installation (did you install KOffice in a different prefix than KDE, without adding the prefix to /etc/kderc ?)" << endl; + return false; + } + + // Get the command line arguments which we have to parse + KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); + int argsCount = args->count(); + + KCmdLineArgs *koargs = KCmdLineArgs::parsedArgs("koffice"); + QString dpiValues = koargs->getOption("dpi"); + if (!dpiValues.isEmpty()) { + int sep = dpiValues.indexOf(QRegExp("[x, ]")); + int dpiX; + int dpiY = 0; + bool ok = true; + if (sep != -1) { + dpiY = dpiValues.mid(sep + 1).toInt(&ok); + dpiValues.truncate(sep); + } + if (ok) { + dpiX = dpiValues.toInt(&ok); + if (ok) { + if (!dpiY) dpiY = dpiX; + KoGlobal::setDPI(dpiX, dpiY); + } + } + } + + // No argument -> create an empty document + if (!argsCount) { + QString errorMsg; + KoDocument* doc = entry.createDoc(&errorMsg); + if (!doc) { + if (!errorMsg.isEmpty()) + KMessageBox::error(0, errorMsg); + return false; + } + KoMainWindow *shell = new KoMainWindow(doc->componentData()); + shell->show(); + QObject::connect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int))); + // for initDoc to fill in the recent docs list + // and for KoDocument::slotStarted + doc->addShell(shell); + + if (doc->checkAutoSaveFile()) { + shell->setRootDocument(doc); + } else { + doc->showStartUpWidget(shell); + } + + // FIXME This needs to be moved someplace else + QObject::disconnect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int))); + } else { + const bool print = koargs->isSet("print"); + const bool exportAsPdf = koargs->isSet("export-pdf"); + QString pdfFileName = koargs->getOption("export-filename"); + const bool doTemplate = koargs->isSet("template"); + koargs->clear(); + + // Loop through arguments + + short int n = 0; // number of documents open + short int nPrinted = 0; + for (int i = 0; i < argsCount; i++) { + // For now create an empty document + QString errorMsg; + KoDocument* doc = entry.createDoc(&errorMsg, 0); + if (doc) { + // show a shell asap + KoMainWindow *shell = new KoMainWindow(doc->componentData()); + shell->show(); + // are we just trying to open a template? + if (doTemplate) { + QStringList paths; + if (args->url(i).isLocalFile() && QFile::exists(args->url(i).toLocalFile())) { + paths << QString(args->url(i).toLocalFile()); + kDebug(30003) << "using full path..."; + } else { + QString desktopName(args->arg(i)); + QString appName = KGlobal::mainComponent().componentName(); + + paths = KGlobal::dirs()->findAllResources("data", appName + "/templates/*/" + desktopName); + if (paths.isEmpty()) { + paths = KGlobal::dirs()->findAllResources("data", appName + "/templates/" + desktopName); + } + if (paths.isEmpty()) { + KMessageBox::error(0L, i18n("No template found for: %1 ", desktopName)); + delete shell; + } else if (paths.count() > 1) { + KMessageBox::error(0L, i18n("Too many templates found for: %1", desktopName)); + delete shell; + } + } + + if (!paths.isEmpty()) { + KUrl templateBase; + templateBase.setPath(paths[0]); + KDesktopFile templateInfo(paths[0]); + + QString templateName = templateInfo.readUrl(); + KUrl templateURL; + templateURL.setPath(templateBase.directory() + '/' + templateName); + if (shell->openDocument(doc, templateURL)) { + doc->resetURL(); + doc->setEmpty(); + doc->setTitleModified(); + kDebug(30003) << "Template loaded..."; + n++; + } else { + KMessageBox::error(0L, i18n("Template %1 failed to load.", templateURL.prettyUrl())); + delete shell; + } + } + // now try to load + } + else if (shell->openDocument(doc, args->url(i))) { + if (print) { + shell->slotFilePrint(); + // delete shell; done by ~KoDocument + nPrinted++; + } else if (exportAsPdf) { + KoPrintJob *job = shell->exportToPdf(pdfFileName); + if (job) + connect (job, SIGNAL(destroyed(QObject*)), shell, + SLOT(slotFileQuit()), Qt::QueuedConnection); + nPrinted++; + } else { + // Normal case, success + n++; + } + } else { + // .... if failed + // delete doc; done by openDocument + // delete shell; done by ~KoDocument + } + } + } + if (print || exportAsPdf) + return nPrinted > 0; + if (n == 0) // no doc, e.g. all URLs were malformed + return false; + } + + args->clear(); + // not calling this before since the program will quit there. + return true; +} + +KoApplication::~KoApplication() +{ +// delete d->m_appIface; + delete d; +} + +bool KoApplication::isStarting() +{ + return KoApplication::m_starting; +} + +#include diff --git a/pool/shard001/C++/0018515_AddNoise.cpp b/pool/shard001/C++/0018515_AddNoise.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d39767656227ab35887e7bf7ade3abd00989e92 --- /dev/null +++ b/pool/shard001/C++/0018515_AddNoise.cpp @@ -0,0 +1,61 @@ + +#include "AddNoise.h" +#include +#include +#include + +using std::vector; +using std::random_device; +using std::mt19937; +using std::uniform_real_distribution; + +/** + * データごとに0.0以上1.0未満の乱数を生成し,rate未満であればそのデータを0.0にする + * @param input ノイズをのせるデータ + * @param rate ノイズをのせる確率 + * @return ノイズをのせたデータ + */ +vector> add_noise(const vector> &input, const float rate) { + random_device rnd; + mt19937 mt; + mt.seed(rnd()); + uniform_real_distribution real_rnd(0.0, 1.0); + + vector> result(input); + + for (unsigned long i = 0, i_s = result.size(); i < i_s; ++i) { + for (unsigned long j = 0, j_s = result[i].size(); j < j_s; ++j) { + if (real_rnd(mt) < rate) result[i][j] = 0.0; + } + } + + return result; +} + +/** + * データごとに0.0以上1.0未満の乱数を生成し,rate未満であればそのデータをデータセットの最小値以上最大値未満の乱数にする + * @param input ノイズをのせるデータ + * @param rate ノイズをのせる確率 + * @return ノイズをのせたデータ + */ +vector> add_random_noise(const vector> &input, const float rate) { + random_device rnd; + mt19937 mt; + mt.seed(rnd()); + uniform_real_distribution rnd_zero_one(0.0, 1.0); + + vector> result(input); + + for (unsigned long i = 0, i_s = result.size(); i < i_s; ++i) { + double min = *std::min_element(result[i].begin(), result[i].end()); + double max = *std::max_element(result[i].begin(), result[i].end()); + uniform_real_distribution rnd_val(min, max); + for (unsigned long j = 0, j_s = result[i].size(); j < j_s; ++j) { + if (rnd_zero_one(mt) < rate) { + result[i][j] = rnd_val(mt); + } + } + } + + return result; +} \ No newline at end of file diff --git a/pool/shard001/C++/0018518_css_selector_list.cc b/pool/shard001/C++/0018518_css_selector_list.cc new file mode 100644 index 0000000000000000000000000000000000000000..b421a3b9303526a8dadc577c47caae17eaf57ef4 --- /dev/null +++ b/pool/shard001/C++/0018518_css_selector_list.cc @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2008, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2009 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: + * 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 APPLE INC. ``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 APPLE INC. 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 "third_party/blink/renderer/core/css/css_selector_list.h" + +#include +#include "third_party/blink/renderer/core/css/parser/css_parser_selector.h" +#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" + +namespace blink { + +CSSSelectorList CSSSelectorList::Copy() const { + CSSSelectorList list; + + unsigned length = ComputeLength(); + list.selector_array_ = std::make_unique(length); + for (unsigned i = 0; i < length; ++i) + new (&list.selector_array_[i]) CSSSelector(selector_array_[i]); + + return list; +} + +CSSSelectorList CSSSelectorList::AdoptSelectorVector( + Vector>& selector_vector) { + size_t flattened_size = 0; + for (wtf_size_t i = 0; i < selector_vector.size(); ++i) { + for (CSSParserSelector* selector = selector_vector[i].get(); selector; + selector = selector->TagHistory()) + ++flattened_size; + } + DCHECK(flattened_size); + + CSSSelectorList list; + list.selector_array_ = std::make_unique(flattened_size); + wtf_size_t array_index = 0; + for (wtf_size_t i = 0; i < selector_vector.size(); ++i) { + CSSParserSelector* current = selector_vector[i].get(); + while (current) { + // Move item from the parser selector vector into selector_array_ without + // invoking destructor (Ugh.) + CSSSelector* current_selector = current->ReleaseSelector().release(); + memcpy(&list.selector_array_[array_index], current_selector, + sizeof(CSSSelector)); + WTF::Partitions::FastFree(current_selector); + + current = current->TagHistory(); + DCHECK(!list.selector_array_[array_index].IsLastInSelectorList()); + if (current) + list.selector_array_[array_index].SetLastInTagHistory(false); + ++array_index; + } + DCHECK(list.selector_array_[array_index - 1].IsLastInTagHistory()); + } + DCHECK_EQ(flattened_size, array_index); + list.selector_array_[array_index - 1].SetLastInSelectorList(true); + list.selector_array_[array_index - 1].SetLastInOriginalList(true); + selector_vector.clear(); + + return list; +} + +const CSSSelector* CSSSelectorList::FirstForCSSOM() const { + const CSSSelector* s = First(); + if (!s) + return nullptr; + while (Next(*s)) + s = Next(*s); + if (NextInFullList(*s)) + return NextInFullList(*s); + return First(); +} + +unsigned CSSSelectorList::ComputeLength() const { + if (!selector_array_) + return 0; + const CSSSelector* current = First(); + while (!current->IsLastInSelectorList()) + ++current; + return SelectorIndex(*current) + 1; +} + +String CSSSelectorList::SelectorsText() const { + StringBuilder result; + + for (const CSSSelector* s = FirstForCSSOM(); s; s = Next(*s)) { + if (s != FirstForCSSOM()) + result.Append(", "); + result.Append(s->SelectorText()); + } + + return result.ReleaseString(); +} + +} // namespace blink diff --git a/pool/shard001/C++/0018520_SparseMatrix.cpp b/pool/shard001/C++/0018520_SparseMatrix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15e19bd33c93b533f77b5e5161d2bee0f8bd7fd6 --- /dev/null +++ b/pool/shard001/C++/0018520_SparseMatrix.cpp @@ -0,0 +1,203 @@ +#include +#include +#include + +class TestSparseMatrix : public ::testing::Test { }; +class TestVector : public ::testing::Test { }; + +TEST_F(TestSparseMatrix, DokSetFromPattern) { + + cask::DokMatrix dkMatrix{ + 1, 1, 1, 1, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }; + + ASSERT_EQ(dkMatrix.nnzs, 10); + ASSERT_EQ(dkMatrix.n, 4); + // test some entries + ASSERT_EQ(dkMatrix.at(0, 0), 1); + ASSERT_EQ(dkMatrix.at(1, 1), 1); + ASSERT_EQ(dkMatrix.at(0, 1), 1); + ASSERT_EQ(dkMatrix.at(0, 2), 1); + ASSERT_EQ(dkMatrix.at(0, 3), 1); + ASSERT_EQ(dkMatrix.at(3, 3), 1); +} + +TEST(TestDokMatrix, SetFromPatternWithGivenRows) { + cask::DokMatrix dkMatrix{ + 1, {4, 5, 3, 2}}; + EXPECT_EQ(dkMatrix.nnzs, 4); + EXPECT_EQ(dkMatrix.n, 1); + EXPECT_EQ(dkMatrix.at(0, 0), 4); + EXPECT_EQ(dkMatrix.at(0, 1), 5); + EXPECT_EQ(dkMatrix.at(0, 2), 3); + EXPECT_EQ(dkMatrix.at(0, 3), 2); +} + +TEST_F(TestSparseMatrix, DokExplicitSymmetry) { + cask::DokMatrix dkMatrix{ + 1, 0, 0, 0, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }; + + ASSERT_EQ(dkMatrix.nnzs, 7); + ASSERT_EQ(dkMatrix.n, 4); + + cask::DokMatrix sym = dkMatrix.explicitSymmetric(); + ASSERT_EQ(sym.nnzs, 10); + ASSERT_EQ(sym.n, 4); + + cask::DokMatrix expSym{ + 1, 1, 1, 1, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }; + ASSERT_EQ(sym, expSym); +} + +TEST_F(TestSparseMatrix, DokDotProduct) { + cask::DokMatrix dkMatrix{ + 1, 0, 0, 0, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }; + std::vector b{1, 2, 3, 4}; + std::vector exp{1, 3, 4, 5}; + ASSERT_EQ(dkMatrix.dot(b), exp); +} + +TEST_F(TestSparseMatrix, CsrToFromDok) { + cask::DokMatrix dokA{ + 2, 1, 1, 1, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }; + + cask::CsrMatrix a{dokA}; + ASSERT_EQ(a.toDok().dok, dokA.dok); + ASSERT_EQ(a.toDok(), dokA); +} + + +TEST_F(TestSparseMatrix, CsrLowerTriangular) { + cask::CsrMatrix m{cask::DokMatrix{ + 1, 1, 1, 1, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }}; + + std::cout << "Matrix" << std::endl; + m.pretty_print(); + + cask::CsrMatrix expL{cask::DokMatrix{ + 1, 0, 0, 0, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }}; + + std::cout << "Lower triangular" << std::endl; + auto l = m.getLowerTriangular(); + l.pretty_print(); + + ASSERT_EQ(l, expL); +} + +TEST_F(TestSparseMatrix, CsrUpperTriangular) { + cask::CsrMatrix m{cask::DokMatrix{ + 1, 1, 1, 1, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 0, 1 + }}; + + std::cout << "Matrix" << std::endl; + m.pretty_print(); + + cask::CsrMatrix expU{cask::DokMatrix{ + 1, 1, 1, 1, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + }}; + + std::cout << "Upper triangular" << std::endl; + auto u = m.getUpperTriangular(); + u.pretty_print(); + + ASSERT_EQ(u, expU); +} + +TEST(CsrMatrix, RowSlice) { + cask::CsrMatrix a{cask::DokMatrix{ + 1, 2, 5, 4, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + }}; + cask::CsrMatrix expU(1, {1, 2, 5, 4}); + auto u = a.sliceRows(0, 1); + EXPECT_EQ(u.values, expU.values); + EXPECT_EQ(u.row_ptr, expU.row_ptr); + EXPECT_EQ(u.col_ind, expU.col_ind); + + cask::CsrMatrix expU2{2, {0, 1, 0, 0, + 0, 0, 1, 0}}; + auto u2 = a.sliceRows(1, 2); + EXPECT_EQ(u2.values, expU2.values); + EXPECT_EQ(u2.row_ptr, expU2.row_ptr); + EXPECT_EQ(u2.col_ind, expU2.col_ind); + + auto u3 = a.sliceRows(0, 4); + EXPECT_EQ(a, u3); +} + + +TEST_F(TestSparseMatrix, SymCsrDotProduct) { + cask::SymCsrMatrix m{cask::DokMatrix{ + 1, 0, 0, 0, + 1, 1, 0, 0, + 1, 0, 1, 0, + 1, 0, 1, 1 + }}; + // -- actual matrix: + // 1, 1, 1, 1, + // 1, 1, 0, 0, + // 1, 0, 1, 1, + // 1, 0, 1, 1 + std::vector b{1, 2, 3, 4}; + std::vector e{10, 3, 8, 8}; + ASSERT_EQ(m.dot(b), e); +} + +TEST_F(TestSparseMatrix, CsrDotProduct) { + cask::CsrMatrix m{cask::DokMatrix{ + 1, 0, 0, 0, + 1, 0, 1, 0, + 0, 1, 1, 0, + 0, 0, 1, 1 + }}; + cask::Vector b{1, 2, 3, 4}; + cask::Vector e{1, 4, 5, 7}; + ASSERT_EQ(m.dot(b), e); +} + +TEST_F(TestVector, VectorSubtract) { + cask::Vector a{1, 6, 9, 4}; + cask::Vector b{3, 4, 5, 7}; + cask::Vector exp{-2, 2, 4, -3}; + ASSERT_EQ(a - b, exp); +} + +TEST_F(TestVector, VectorNorm) { + cask::Vector a{1, 2, 3, 1, 1}; + ASSERT_EQ(a.norm(), 4); +} diff --git a/pool/shard001/C++/0018538_filter_config.cc b/pool/shard001/C++/0018538_filter_config.cc new file mode 100644 index 0000000000000000000000000000000000000000..550218e6661b011df97348f5e036227ab0352b45 --- /dev/null +++ b/pool/shard001/C++/0018538_filter_config.cc @@ -0,0 +1,84 @@ +#include "source/extensions/filters/http/jwt_authn/filter_config.h" + +#include // std::sort + +#include "source/common/common/empty_string.h" + +using envoy::extensions::filters::http::jwt_authn::v3::RequirementRule; + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace JwtAuthn { + +FilterConfigImpl::FilterConfigImpl( + envoy::extensions::filters::http::jwt_authn::v3::JwtAuthentication proto_config, + const std::string& stats_prefix, Server::Configuration::FactoryContext& context) + : proto_config_(std::move(proto_config)), stats_(generateStats(stats_prefix, context.scope())), + cm_(context.clusterManager()), time_source_(context.mainThreadDispatcher().timeSource()) { + + ENVOY_LOG(debug, "Loaded JwtAuthConfig: {}", proto_config_.DebugString()); + + jwks_cache_ = JwksCache::create(proto_config_, context, Common::JwksFetcher::create, stats_); + + std::vector names; + for (const auto& it : proto_config_.requirement_map()) { + names.push_back(it.first); + name_verifiers_.emplace(it.first, + Verifier::create(it.second, proto_config_.providers(), *this)); + } + // sort is just for unit-test since protobuf map order is not deterministic. + std::sort(names.begin(), names.end()); + all_requirement_names_ = absl::StrJoin(names, ","); + + for (const auto& rule : proto_config_.rules()) { + switch (rule.requirement_type_case()) { + case RequirementRule::RequirementTypeCase::kRequires: + rule_pairs_.emplace_back(Matcher::create(rule), + Verifier::create(rule.requires(), proto_config_.providers(), *this)); + break; + case RequirementRule::RequirementTypeCase::kRequirementName: { + // Use requirement_name to lookup requirement_map. + auto map_it = proto_config_.requirement_map().find(rule.requirement_name()); + if (map_it == proto_config_.requirement_map().end()) { + throw EnvoyException(fmt::format("Wrong requirement_name: {}. It should be one of [{}]", + rule.requirement_name(), all_requirement_names_)); + } + rule_pairs_.emplace_back(Matcher::create(rule), + Verifier::create(map_it->second, proto_config_.providers(), *this)); + } break; + case RequirementRule::RequirementTypeCase::REQUIREMENT_TYPE_NOT_SET: + rule_pairs_.emplace_back(Matcher::create(rule), nullptr); + break; + } + } + + if (proto_config_.has_filter_state_rules()) { + filter_state_name_ = proto_config_.filter_state_rules().name(); + for (const auto& it : proto_config_.filter_state_rules().requires()) { + filter_state_verifiers_.emplace( + it.first, Verifier::create(it.second, proto_config_.providers(), *this)); + } + } +} + +std::pair +FilterConfigImpl::findPerRouteVerifier(const PerRouteFilterConfig& per_route) const { + if (per_route.config().disabled()) { + return std::make_pair(nullptr, EMPTY_STRING); + } + + const auto& it = name_verifiers_.find(per_route.config().requirement_name()); + if (it != name_verifiers_.end()) { + return std::make_pair(it->second.get(), EMPTY_STRING); + } + + return std::make_pair( + nullptr, absl::StrCat("Wrong requirement_name: ", per_route.config().requirement_name(), + ". It should be one of [", all_requirement_names_, "]")); +} + +} // namespace JwtAuthn +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/pool/shard001/C++/0018555_custom_video_settings.cpp b/pool/shard001/C++/0018555_custom_video_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1966ac8afb560d2a55fe63178a0acf0cf0647e27 --- /dev/null +++ b/pool/shard001/C++/0018555_custom_video_settings.cpp @@ -0,0 +1,149 @@ +// SuperTuxKart - a fun racing game with go-kart +// Copyright (C) 2009-2013 Marianne Gagnon +// +// 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, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +#include "states_screens/dialogs/custom_video_settings.hpp" + +#include "config/user_config.hpp" +#include "guiengine/widgets/check_box_widget.hpp" +#include "guiengine/widgets/spinner_widget.hpp" +#include "states_screens/options_screen_video.hpp" +#include "utils/translation.hpp" + +#include + + +using namespace GUIEngine; +using namespace irr; +using namespace irr::core; +using namespace irr::gui; + +// ----------------------------------------------------------------------------- + +CustomVideoSettingsialog::CustomVideoSettingsialog(const float w, const float h) : + ModalDialog(w, h) +{ + loadFromFile("custom_video_settings.stkgui"); +} + +// ----------------------------------------------------------------------------- + +CustomVideoSettingsialog::~CustomVideoSettingsialog() +{ +} + +// ----------------------------------------------------------------------------- + +void CustomVideoSettingsialog::beforeAddingWidgets() +{ + getWidget("anim_gfx")->setState( UserConfigParams::m_graphical_effects ); + getWidget("weather_gfx")->setState( UserConfigParams::m_weather_effects ); + + SpinnerWidget* kart_anim = getWidget("steering_animations"); + kart_anim->addLabel( _("Disabled") ); // 0 + //I18N: animations setting (only karts with human players are animated) + kart_anim->addLabel( _("Human players only") ); // 1 + //I18N: animations setting (all karts are animated) + kart_anim->addLabel( _("Enabled for all") ); // 2 + kart_anim->setValue( UserConfigParams::m_show_steering_animations ); + + SpinnerWidget* filtering = getWidget("filtering"); + int value = 0; + if (UserConfigParams::m_anisotropic == 2) value = 2; + else if (UserConfigParams::m_anisotropic == 4) value = 3; + else if (UserConfigParams::m_anisotropic == 8) value = 4; + else if (UserConfigParams::m_anisotropic == 16) value = 5; + else if (UserConfigParams::m_trilinear) value = 1; + filtering->addLabel( _("Bilinear") ); // 0 + filtering->addLabel( _("Trilinear") ); // 1 + filtering->addLabel( _("Anisotropic x2") ); // 2 + filtering->addLabel( _("Anisotropic x4") ); // 3 + filtering->addLabel( _("Anisotropic x8") ); // 4 + filtering->addLabel( _("Anisotropic x16") ); // 5 + + filtering->setValue( value ); + + SpinnerWidget* antialias = getWidget("antialiasing"); + antialias->addLabel( _("Disabled") ); // 0 + antialias->addLabel( L"x2" ); // 1 + antialias->addLabel( L"x4" ); // 2 + antialias->addLabel( L"x8" ); // 3 + antialias->setValue( UserConfigParams::m_antialiasing ); + + getWidget("postprocessing")->setState( UserConfigParams::m_postprocess_enabled ); + getWidget("pixelshaders")->setState( UserConfigParams::m_pixel_shaders ); +} + +// ----------------------------------------------------------------------------- + +GUIEngine::EventPropagation CustomVideoSettingsialog::processEvent(const std::string& eventSource) +{ + if (eventSource == "close") + { + UserConfigParams::m_graphical_effects = + getWidget("anim_gfx")->getState(); + UserConfigParams::m_weather_effects = + getWidget("weather_gfx")->getState(); + UserConfigParams::m_antialiasing = + getWidget("antialiasing")->getValue(); + UserConfigParams::m_postprocess_enabled = + getWidget("postprocessing")->getState(); + UserConfigParams::m_show_steering_animations = + getWidget("steering_animations")->getValue(); + UserConfigParams::m_pixel_shaders = + getWidget("pixelshaders")->getState(); + + switch (getWidget("filtering")->getValue()) + { + case 0: + UserConfigParams::m_anisotropic = 0; + UserConfigParams::m_trilinear = false; + break; + case 1: + UserConfigParams::m_anisotropic = 0; + UserConfigParams::m_trilinear = true; + break; + case 2: + UserConfigParams::m_anisotropic = 2; + UserConfigParams::m_trilinear = true; + break; + case 3: + UserConfigParams::m_anisotropic = 4; + UserConfigParams::m_trilinear = true; + break; + case 4: + UserConfigParams::m_anisotropic = 8; + UserConfigParams::m_trilinear = true; + break; + case 5: + UserConfigParams::m_anisotropic = 16; + UserConfigParams::m_trilinear = true; + break; + } + + user_config->saveConfig(); + + ModalDialog::dismiss(); + OptionsScreenVideo::getInstance()->updateGfxSlider(); + return GUIEngine::EVENT_BLOCK; + } + + return GUIEngine::EVENT_LET; +} + +// ----------------------------------------------------------------------------- + + diff --git a/pool/shard001/C++/0018566_ccd_iterations.cc b/pool/shard001/C++/0018566_ccd_iterations.cc new file mode 100644 index 0000000000000000000000000000000000000000..68e950a1ad0e22e4f95c059b77ca304de920d1c0 --- /dev/null +++ b/pool/shard001/C++/0018566_ccd_iterations.cc @@ -0,0 +1,147 @@ +/* + * @BEGIN LICENSE + * + * Psi4: an open-source quantum chemistry software package + * + * Copyright (c) 2007-2017 The Psi4 Developers. + * + * The copyrights for code used from other parties are included in + * the corresponding files. + * + * 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. + * + * @END LICENSE + */ + +#include "psi4/libqt/qt.h" +#include "defines.h" +#include "psi4/libdiis/diismanager.h" +#include "dfocc.h" +#include "psi4/libmints/matrix.h" +using namespace std; + + +namespace psi{ namespace dfoccwave{ + +void DFOCC::ccd_iterations() +{ + +outfile->Printf("\n"); +outfile->Printf(" ============================================================================== \n"); +outfile->Printf(" ================ Performing DF-CCD iterations... ============================= \n"); +outfile->Printf(" ============================================================================== \n"); +outfile->Printf("\n"); +outfile->Printf(" Iter E_corr DE T2 RMS \n"); +outfile->Printf(" ---- ---------------- ---------------- ---------- \n"); + +//========================================================================================== +//========================= CCD iterations ================================================= +//========================================================================================== + itr_occ = 0; + conver = 1; // Assuming that the iterations will converge + Eccd_old = Eccd; + + // DIIS + if (do_diis_ == 1) { + std::shared_ptr T2(new Matrix("T2", naoccA*navirA, naoccA*navirA)); + if (reference_ == "RESTRICTED") { + ccsdDiisManager = std::shared_ptr(new DIISManager(cc_maxdiis_, "CCSD DIIS T Amps", DIISManager::LargestError, DIISManager::OnDisk)); + ccsdDiisManager->set_error_vector_size(1, DIISEntry::Matrix, T2.get()); + ccsdDiisManager->set_vector_size(1, DIISEntry::Matrix, T2.get()); + } + T2.reset(); + }// if diis true + +// head of loop +do +{ + // iterate + itr_occ++; + + // 3-index intermediates + timer_on("CCSD 3-index intr"); + ccd_3index_intr(); + timer_off("CCSD 3-index intr"); + + // F intermediates + timer_on("CCSD F intr"); + ccd_F_intr(); + timer_off("CCSD F intr"); + + // T2 amplitudes + timer_on("T2 AMPS"); + ccd_t2_amps(); + timer_off("T2 AMPS"); + + DE = Eccd - Eccd_old; + Eccd_old = Eccd; + + // RMS + if (reference_ == "UNRESTRICTED") { + rms_t2=MAX0(rms_t2AA,rms_t2BB); + rms_t2=MAX0(rms_t2,rms_t2AB); + } + + // print + outfile->Printf(" %3d %12.10f %12.10f %12.2e \n", itr_occ, Ecorr, DE, rms_t2); + + if (itr_occ >= cc_maxiter) { + conver = 0; // means iterations were NOT converged + break; + } + + if (rms_t2 >= DIVERGE) { + throw PSIEXCEPTION("CCD iterations are diverging"); + } + +} +while(fabs(DE) >= tol_Eod || rms_t2 >= tol_t2); + + //delete + if (do_diis_ == 1) ccsdDiisManager->delete_diis_file(); + + // Mem alloc for DF ints + if (df_ints_incore) { + if (cc_lambda_ == "FALSE") { + bQijA.reset(); + bQiaA.reset(); + bQabA.reset(); + } + } + + // free t2 amps + if (t2_incore) { + if (cc_lambda_ == "TRUE") { + t2->write_symm(psio_, PSIF_DFOCC_AMPS); + } + else t2.reset(); + } + + + +if (conver == 1) { +outfile->Printf("\n"); +outfile->Printf(" ============================================================================== \n"); +outfile->Printf(" ===================== DF-CCD ITERATIONS ARE CONVERGED ======================== \n"); +outfile->Printf(" ============================================================================== \n"); +} + +else if (conver == 0) { + outfile->Printf("\n ====================== DF-CCD IS NOT CONVERGED IN %2d ITERATIONS ============= \n", cc_maxiter); + throw PSIEXCEPTION("DF-CCD iterations did not converge"); +} + +}// end ccd_iterations +}} // End Namespaces diff --git a/pool/shard001/C++/0018567_extract_economy.cpp b/pool/shard001/C++/0018567_extract_economy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eeea39896a922c05ebb0b85ab43d8979d3a902e9 --- /dev/null +++ b/pool/shard001/C++/0018567_extract_economy.cpp @@ -0,0 +1,132 @@ +#include "framework/data.h" +#include "framework/framework.h" +#include "game/state/city/economyinfo.h" +#include "game/state/gamestate.h" +#include "library/strings_format.h" +#include "tools/extractors/common/ufo2p.h" +#include "tools/extractors/extractors.h" + +namespace OpenApoc +{ + +namespace +{ +static std::vector vehicleAmmoNames = { + + {"VEQUIPMENTAMMOTYPE_FUSION_POWERFUEL"}, + {"VEQUIPMENTAMMOTYPE_ELERIUM_115"}, + {"VEQUIPMENTAMMOTYPE_ZORIUM"}, + {"VEQUIPMENTAMMOTYPE_MULTI_CANNON_ROUND"}, + {"VEQUIPMENTAMMOTYPE_JANITOR_MISSILE"}, + {"VEQUIPMENTAMMOTYPE_JUSTICE_MISSILE"}, + {"VEQUIPMENTAMMOTYPE_PROPHET_MISSILE"}, + {"VEQUIPMENTAMMOTYPE_RETRIBUTION_MISSILE"}, + {"VEQUIPMENTAMMOTYPE_DISRUPTOR_BOMB"}, + {"VEQUIPMENTAMMOTYPE_STASIS_BOMB"}, + {"VEQUIPMENTAMMOTYPE_DISRUPTOR_MULTI-BOMB"}, + {"VEQUIPMENTAMMOTYPE_REPEATER_40MM_CANNON_ROUND"}, + {"VEQUIPMENTAMMOTYPE_AIRGUARD_52MM_CANNON_ROUND"}, + {"VEQUIPMENTAMMOTYPE_GROUND_LAUNCHED_MISSILE"}, + {"VEQUIPMENTAMMOTYPE_AIR_DEFENSE_MISSILE"}, +}; +} + +void InitialGameStateExtractor::extractEconomy(GameState &state) const +{ + auto &data = this->ufo2p; + LogInfo("Number of economy 1 data chunks: %u", (unsigned)data.economy_data1->count()); + LogInfo("Number of economy 2 data chunks: %u", (unsigned)data.economy_data2->count()); + LogInfo("Number of economy 3 data chunks: %u", (unsigned)data.economy_data3->count()); + + for (unsigned idx = 0; idx < data.economy_data1->count(); idx++) + { + int i = idx; + auto e = data.economy_data1->get(i); + + auto economyInfo = EconomyInfo(); + economyInfo.weekAvailable = e.week; + economyInfo.basePrice = e.basePrice; + economyInfo.currentPrice = e.curPrice; + economyInfo.currentStock = e.curStock; + economyInfo.lastStock = e.lastStock; + economyInfo.maxStock = e.maxStock; + economyInfo.minStock = e.minStock; + + UString id = ""; + if (i < 34) + { + // Skip overspawn + if (i == 33) + { + continue; + } + id = data.getVehicleId(i); + } + else + { + i -= 34; + if (i < 49) + { + id = data.getVequipmentId(i); + } + else + { + LogError("Unexpected data in economy data pack 1!"); + } + } + state.economy[id] = economyInfo; + } + for (unsigned idx = 0; idx < data.economy_data2->count(); idx++) + { + int i = idx; + auto e = data.economy_data2->get(i); + + auto economyInfo = EconomyInfo(); + economyInfo.weekAvailable = e.week; + economyInfo.basePrice = e.basePrice; + economyInfo.currentPrice = e.curPrice; + economyInfo.currentStock = e.curStock; + economyInfo.lastStock = e.lastStock; + economyInfo.maxStock = e.maxStock; + economyInfo.minStock = e.minStock; + + UString id = ""; + if (i < 15) + { + id = vehicleAmmoNames[i]; + } + else + { + LogError("Unexpected data in economy data pack 2!"); + } + state.economy[id] = economyInfo; + } + for (unsigned idx = 0; idx < data.economy_data3->count(); idx++) + { + int i = idx; + auto e = data.economy_data3->get(i); + + auto economyInfo = EconomyInfo(); + economyInfo.weekAvailable = e.week; + economyInfo.basePrice = e.basePrice; + economyInfo.currentPrice = e.curPrice; + economyInfo.currentStock = e.curStock; + economyInfo.lastStock = e.lastStock; + economyInfo.maxStock = e.maxStock; + economyInfo.minStock = e.minStock; + + UString id = ""; + if (i < 87) + { + id = data.agent_equipment_names->get(i); + id = format("%s%s", AEquipmentType::getPrefix(), canon_string(id)); + } + else + { + LogError("Unexpected data in economy data pack 3!"); + } + state.economy[id] = economyInfo; + } +} + +} // namespace OpenApoc diff --git a/pool/shard001/C++/0018571_runtime-proxy.cc b/pool/shard001/C++/0018571_runtime-proxy.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a521c6b7c49831e8cbcc6f0be1fd2c7b589f191 --- /dev/null +++ b/pool/shard001/C++/0018571_runtime-proxy.cc @@ -0,0 +1,177 @@ +// Copyright 2014 the V8 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. + +#include "src/runtime/runtime-utils.h" + +#include "src/arguments.h" +#include "src/elements.h" +#include "src/factory.h" +#include "src/isolate-inl.h" +#include "src/objects-inl.h" + +namespace v8 { +namespace internal { + + +// ES6 9.5.13 [[Call]] (thisArgument, argumentsList) +RUNTIME_FUNCTION(Runtime_JSProxyCall) { + HandleScope scope(isolate); + DCHECK_LE(2, args.length()); + // thisArgument == receiver + CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0); + CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, args.length() - 1); + Handle trap_name = isolate->factory()->apply_string(); + // 1. Let handler be the value of the [[ProxyHandler]] internal slot of O. + Handle handler(proxy->handler(), isolate); + // 2. If handler is null, throw a TypeError exception. + if (proxy->IsRevoked()) { + THROW_NEW_ERROR_RETURN_FAILURE( + isolate, NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); + } + // 3. Assert: Type(handler) is Object. + DCHECK(handler->IsJSReceiver()); + // 4. Let target be the value of the [[ProxyTarget]] internal slot of O. + Handle target(proxy->target(), isolate); + // 5. Let trap be ? GetMethod(handler, "apply"). + Handle trap; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, trap, + Object::GetMethod(Handle::cast(handler), trap_name)); + // 6. If trap is undefined, then + int const arguments_length = args.length() - 2; + if (trap->IsUndefined()) { + // 6.a. Return Call(target, thisArgument, argumentsList). + ScopedVector> argv(arguments_length); + for (int i = 0; i < arguments_length; ++i) { + argv[i] = args.at(i + 1); + } + Handle result; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, result, Execution::Call(isolate, target, receiver, + arguments_length, argv.start())); + return *result; + } + // 7. Let argArray be CreateArrayFromList(argumentsList). + Handle arg_array = isolate->factory()->NewJSArray( + FAST_ELEMENTS, arguments_length, arguments_length); + ElementsAccessor* accessor = arg_array->GetElementsAccessor(); + { + DisallowHeapAllocation no_gc; + FixedArrayBase* elements = arg_array->elements(); + for (int i = 0; i < arguments_length; i++) { + accessor->Set(elements, i, args[i + 1]); + } + } + // 8. Return Call(trap, handler, «target, thisArgument, argArray»). + Handle trap_result; + Handle trap_args[] = {target, receiver, arg_array}; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, trap_result, + Execution::Call(isolate, trap, handler, arraysize(trap_args), trap_args)); + return *trap_result; +} + + +// 9.5.14 [[Construct]] (argumentsList, newTarget) +RUNTIME_FUNCTION(Runtime_JSProxyConstruct) { + HandleScope scope(isolate); + DCHECK_LE(3, args.length()); + CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, args.length() - 2); + CONVERT_ARG_HANDLE_CHECKED(Object, new_target, args.length() - 1); + Handle trap_name = isolate->factory()->construct_string(); + + // 1. Let handler be the value of the [[ProxyHandler]] internal slot of O. + Handle handler(proxy->handler(), isolate); + // 2. If handler is null, throw a TypeError exception. + if (proxy->IsRevoked()) { + THROW_NEW_ERROR_RETURN_FAILURE( + isolate, NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); + } + // 3. Assert: Type(handler) is Object. + DCHECK(handler->IsJSReceiver()); + // 4. Let target be the value of the [[ProxyTarget]] internal slot of O. + Handle target(JSReceiver::cast(proxy->target()), isolate); + // 5. Let trap be ? GetMethod(handler, "construct"). + Handle trap; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, trap, + Object::GetMethod(Handle::cast(handler), trap_name)); + // 6. If trap is undefined, then + int const arguments_length = args.length() - 3; + if (trap->IsUndefined()) { + // 6.a. Assert: target has a [[Construct]] internal method. + DCHECK(target->IsConstructor()); + // 6.b. Return Construct(target, argumentsList, newTarget). + ScopedVector> argv(arguments_length); + for (int i = 0; i < arguments_length; ++i) { + argv[i] = args.at(i + 1); + } + Handle result; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, result, Execution::New(isolate, target, new_target, + arguments_length, argv.start())); + return *result; + } + // 7. Let argArray be CreateArrayFromList(argumentsList). + Handle arg_array = isolate->factory()->NewJSArray( + FAST_ELEMENTS, arguments_length, arguments_length); + ElementsAccessor* accessor = arg_array->GetElementsAccessor(); + { + DisallowHeapAllocation no_gc; + FixedArrayBase* elements = arg_array->elements(); + for (int i = 0; i < arguments_length; i++) { + accessor->Set(elements, i, args[i + 1]); + } + } + // 8. Let newObj be ? Call(trap, handler, «target, argArray, newTarget »). + Handle new_object; + Handle trap_args[] = {target, arg_array, new_target}; + ASSIGN_RETURN_FAILURE_ON_EXCEPTION( + isolate, new_object, + Execution::Call(isolate, trap, handler, arraysize(trap_args), trap_args)); + // 9. If Type(newObj) is not Object, throw a TypeError exception. + if (!new_object->IsJSReceiver()) { + THROW_NEW_ERROR_RETURN_FAILURE( + isolate, + NewTypeError(MessageTemplate::kProxyConstructNonObject, new_object)); + } + // 10. Return newObj. + return *new_object; +} + + +RUNTIME_FUNCTION(Runtime_IsJSProxy) { + SealHandleScope shs(isolate); + DCHECK(args.length() == 1); + CONVERT_ARG_CHECKED(Object, obj, 0); + return isolate->heap()->ToBoolean(obj->IsJSProxy()); +} + + +RUNTIME_FUNCTION(Runtime_JSProxyGetHandler) { + SealHandleScope shs(isolate); + DCHECK(args.length() == 1); + CONVERT_ARG_CHECKED(JSProxy, proxy, 0); + return proxy->handler(); +} + + +RUNTIME_FUNCTION(Runtime_JSProxyGetTarget) { + SealHandleScope shs(isolate); + DCHECK(args.length() == 1); + CONVERT_ARG_CHECKED(JSProxy, proxy, 0); + return proxy->target(); +} + + +RUNTIME_FUNCTION(Runtime_JSProxyRevoke) { + HandleScope scope(isolate); + DCHECK(args.length() == 1); + CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, 0); + JSProxy::Revoke(proxy); + return isolate->heap()->undefined_value(); +} + +} // namespace internal +} // namespace v8 diff --git a/pool/shard001/C++/0018573_test.cpp b/pool/shard001/C++/0018573_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b49b7ecac6532d7c0c0c095a3c77a02819c3c19f --- /dev/null +++ b/pool/shard001/C++/0018573_test.cpp @@ -0,0 +1,59 @@ +/* + * test.cpp + * + * Created on: 2014年11月4日 + * Author: nemo + */ + +#include + +#include "src/libTriangularMatrix.h" + +using namespace std; + +int main() +{ + TriangularMatrix::showVersion(); + + cout << "Test UpperTriangularMatrix." << endl; + UpperTriangularMatrix UTM; + int sizeOfMatrix = 5; + UTM.setSizeOfMatrix(sizeOfMatrix); + UTM.initial(); + + int count = 1; + for(int j = 0; j < sizeOfMatrix; j++) + { + for(int k = j; k < sizeOfMatrix; k++) + { + UTM.setElement(j,k,count++); + } + } + UTM.showOneDimensionData(); + + UTM.showMatrix(); + UTM.showSymmetricalMatrix(); + cout << endl; + + + cout << "Test LowerTriangularMatrix." << endl; + LowerTriangularMatrix LTM; + + LTM.setSizeOfMatrix(sizeOfMatrix); + LTM.initial(); + + count = 1; + for(int j = 0; j < sizeOfMatrix; j++) + { + for(int k = 0; k <= j; k++) + { + LTM.setElement(j,k,count++); + } + } + UTM.showOneDimensionData(); + + LTM.showMatrix(); + LTM.showSymmetricalMatrix(); + return 0; +} + diff --git a/pool/shard001/C++/0018578_browser_ui_browsertest.cc b/pool/shard001/C++/0018578_browser_ui_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e7d3c1eaa43fdc0150a0ac729e83df8bd2b89e6 --- /dev/null +++ b/pool/shard001/C++/0018578_browser_ui_browsertest.cc @@ -0,0 +1,79 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/command_line.h" +#include "base/process/launch.h" +#include "base/stl_util.h" +#include "base/test/launcher/test_launcher.h" +#include "base/test/test_switches.h" +#include "base/test/test_timeouts.h" +#include "build/build_config.h" +#include "content/public/common/content_switches.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +// Switch for BrowserUiTest.Invoke to spawn a subprocess testing the provided +// argument under a consistent setup. +constexpr const char kUiSwitch[] = "ui"; + +// Pattern to search in test names that indicate support for UI testing. +constexpr const char kUiPattern[] = "InvokeUi_"; + +} // namespace + +// Adds a browser_test entry point into the UI testing framework. Without a +// --ui specified, just lists the available UIs and exits. +TEST(BrowserUiTest, Invoke) { + const base::CommandLine& invoker = *base::CommandLine::ForCurrentProcess(); + const std::string ui_name = invoker.GetSwitchValueASCII(kUiSwitch); + + std::set ui_cases; + const testing::UnitTest* unit_test = testing::UnitTest::GetInstance(); + for (int i = 0; i < unit_test->total_test_case_count(); ++i) { + const testing::TestCase* test_case = unit_test->GetTestCase(i); + for (int j = 0; j < test_case->total_test_count(); ++j) { + const char* name = test_case->GetTestInfo(j)->name(); + if (strstr(name, kUiPattern)) + ui_cases.insert(test_case->name() + std::string(".") + name); + } + } + + if (ui_name.empty()) { + std::string case_list; + for (const std::string& name : ui_cases) + case_list += "\t" + name + "\n"; + VLOG(0) << "\nPass one of the following after --" << kUiSwitch << "=\n" + << case_list; + return; + } + + auto it = ui_cases.find(ui_name); + ASSERT_NE(it, ui_cases.end()) << "UI '" << ui_name << "' not found."; + + // Don't create test output for the subprocess (the paths will conflict). + base::CommandLine::StringVector argv = invoker.argv(); + std::string ascii(switches::kTestLauncherOutput); + base::CommandLine::StringType native_switch(ascii.begin(), ascii.end()); + base::EraseIf( + argv, [native_switch](const base::CommandLine::StringType& arg) -> bool { + return arg.find(native_switch) != arg.npos; // Substring search. + }); + base::CommandLine command(argv); + + // Replace TestBrowserUi.Invoke with |ui_name|. + command.AppendSwitchASCII(base::kGTestFilterFlag, ui_name); + + base::LaunchOptions options; + +#if defined(OS_WIN) + // Under Windows, the child process won't launch without the wait option. + // See http://crbug.com/688534. + options.wait = true; +#else + options.wait = !command.HasSwitch(switches::kTestLauncherInteractive); +#endif + + base::LaunchProcess(command, options); +} diff --git a/pool/shard001/C++/0018582_acm_pcmu.cc b/pool/shard001/C++/0018582_acm_pcmu.cc new file mode 100644 index 0000000000000000000000000000000000000000..92f7f5c275194f2d2f2b5fc4bc64e569b79d7c7a --- /dev/null +++ b/pool/shard001/C++/0018582_acm_pcmu.cc @@ -0,0 +1,132 @@ +/* + * 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 "acm_pcmu.h" + +#include "acm_common_defs.h" +#include "acm_neteq.h" +#include "trace.h" +#include "webrtc_neteq.h" +#include "webrtc_neteq_help_macros.h" + +// Codec interface +#include "g711_interface.h" + +namespace webrtc { + +ACMPCMU::ACMPCMU(WebRtc_Word16 codecID) { + _codecID = codecID; +} + +ACMPCMU::~ACMPCMU() { + return; +} + +WebRtc_Word16 ACMPCMU::InternalEncode(WebRtc_UWord8* bitStream, + WebRtc_Word16* bitStreamLenByte) { + *bitStreamLenByte = WebRtcG711_EncodeU(NULL, &_inAudio[_inAudioIxRead], + _frameLenSmpl * _noChannels, + (WebRtc_Word16*) bitStream); + // Increment the read index this tell the caller that how far + // we have gone forward in reading the audio buffer. + _inAudioIxRead += _frameLenSmpl * _noChannels; + return *bitStreamLenByte; +} + +WebRtc_Word16 ACMPCMU::DecodeSafe(WebRtc_UWord8* /* bitStream */, + WebRtc_Word16 /* bitStreamLenByte */, + WebRtc_Word16* /* audio */, + WebRtc_Word16* /* audioSamples */, + WebRtc_Word8* /* speechType */) { + return 0; +} + +WebRtc_Word16 ACMPCMU::InternalInitEncoder( + WebRtcACMCodecParams* /* codecParams */) { + // This codec does not need initialization, PCM has no instance. + return 0; +} + +WebRtc_Word16 ACMPCMU::InternalInitDecoder( + WebRtcACMCodecParams* /* codecParams */) { + // This codec does not need initialization, PCM has no instance. + return 0; +} + +WebRtc_Word32 ACMPCMU::CodecDef(WebRtcNetEQ_CodecDef& codecDef, + const CodecInst& codecInst) { + // Fill up the structure by calling + // "SET_CODEC_PAR" & "SET_PCMU_FUNCTION." + // Then call NetEQ to add the codec to it's database. + if (codecInst.channels == 1) { + // Mono mode. + SET_CODEC_PAR(codecDef, kDecoderPCMu, codecInst.pltype, NULL, 8000); + } else { + // Stereo mode. + SET_CODEC_PAR(codecDef, kDecoderPCMu_2ch, codecInst.pltype, NULL, 8000); + } + SET_PCMU_FUNCTIONS(codecDef); + return 0; +} + +ACMGenericCodec* ACMPCMU::CreateInstance(void) { + return NULL; +} + +WebRtc_Word16 ACMPCMU::InternalCreateEncoder() { + // PCM has no instance. + return 0; +} + +WebRtc_Word16 ACMPCMU::InternalCreateDecoder() { + // PCM has no instance. + return 0; +} + +void ACMPCMU::InternalDestructEncoderInst(void* /* ptrInst */) { + // PCM has no instance. + return; +} + +void ACMPCMU::DestructEncoderSafe() { + // PCM has no instance. + _encoderExist = false; + _encoderInitialized = false; + return; +} + +void ACMPCMU::DestructDecoderSafe() { + // PCM has no instance. + _decoderInitialized = false; + _decoderExist = false; + return; +} + +// Split the stereo packet and place left and right channel after each other +// in the payload vector. +void ACMPCMU::SplitStereoPacket(uint8_t* payload, int32_t* payload_length) { + uint8_t right_byte; + + // Check for valid inputs. + assert(payload != NULL); + assert(*payload_length > 0); + + // Move one bytes representing right channel each loop, and place it at the + // end of the bytestream vector. After looping the data is reordered to: + // l1 l2 l3 l4 ... l(N-1) lN r1 r2 r3 r4 ... r(N-1) r(N), + // where N is the total number of samples. + for (int i = 0; i < *payload_length / 2; i++) { + right_byte = payload[i + 1]; + memmove(&payload[i + 1], &payload[i + 2], *payload_length - i - 2); + payload[*payload_length - 1] = right_byte; + } +} + +} // namespace webrtc diff --git a/pool/shard001/C++/0018583_naive-server.cpp b/pool/shard001/C++/0018583_naive-server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..017037faf699d80751539f84473fa46388f9d8b8 --- /dev/null +++ b/pool/shard001/C++/0018583_naive-server.cpp @@ -0,0 +1,40 @@ +// Copyright(c) Andre Caron, 2009-2010 +// +// This document is covered by the Artistic License 2.0 (Open Source Initiative +// approved license). A copy of the license should have been provided alongside +// this software package (see "license.rtf"). If not, the license is available +// online at "http://www.opensource.org/licenses/artistic-license-2.0.php". + + // Include this to get a linking error if compiled by itself. +#include + +#include + +namespace { + + int run ( int argc, wchar_t ** argv ) + { + // Must load Windows Sockets environment. + w32::net::Context context; + + // Setup connection parameters. + w32::net::Host host(w32::computername()); + w32::net::ipv4::Address address + (host.address(0)); + w32::net::uint16 port(4321); + w32::net::ipv4::EndPoint endpoint(address,port); + + // Wait for a client connection. + w32::net::tcp::Listener listener(endpoint); + w32::net::tcp::Stream stream(listener); + + // Use some convenient way to communicate. + w32::net::sockstream channel(stream); + + // Let the client code work things from here! + return (transaction(channel)); + } + +} + +#include diff --git a/pool/shard001/C++/0018588_mainwindow.cpp b/pool/shard001/C++/0018588_mainwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e1ac58f481f926f482b85f2608d208747f9ee2e --- /dev/null +++ b/pool/shard001/C++/0018588_mainwindow.cpp @@ -0,0 +1,115 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "board.h" +#include +#include +#include +#include +#include +#include + +#include "parser/sgfparser.h" +#include "parser/gamerecord.h" +#include "gametreemodel.h" +#include "resourceholder.h" + +MainWindow::MainWindow(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::MainWindow) +{ + ui->setupUi(this); + + ResourceHolder::initResource(); + + createActions(); + createMenus(); + + createStatusBar(); + + rightSpliter = new QSplitter(Qt::Vertical); + commentView = new QTextEdit(); + stepTreeView = new QTreeView(); + rightSpliter->addWidget(commentView); + rightSpliter->addWidget(stepTreeView); + + mainSpliter = new QSplitter(Qt::Horizontal); + boardView = new Board(this); + mainSpliter->addWidget(boardView); + mainSpliter->addWidget(rightSpliter); + QList tmp; + tmp.append(400); + tmp.append(100); + mainSpliter->setSizes(tmp); + + + setCentralWidget(mainSpliter); + + setWindowTitle(tr("Go")); +} + +MainWindow::~MainWindow() +{ + delete boardView; + delete commentView; + delete stepTreeView; + delete rightSpliter; + delete mainSpliter; + + delete openAction; + delete statusLabel; + delete ui; +} + +void MainWindow::createMenus() +{ + fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(openAction); +} + +void MainWindow::createActions() +{ + openAction = new QAction(tr("&Open"), this); + openAction->setShortcut(QKeySequence::Open); + connect(openAction, SIGNAL(triggered(bool)), this, SLOT(open())); +} + +void MainWindow::open() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Open File"), "", tr("SGF Files (*.sgf)")); + RecordNode *root = NULL; + if (!fileName.isEmpty()) { + qInfo("Open:%s", fileName.toStdString().c_str()); + QFile file(fileName); + if (file.open(QIODevice::ReadWrite)) { + QTextStream in(&file); + SgfParser parser; + root = new RecordNode; + if (parser.doParse(in, root)) { + setGameRecordTree(root); + } else { + delete root; + } + file.close(); + } + } +} + +void MainWindow::createStatusBar() +{ + statusLabel = new QLabel; + statusLabel->setIndent(5); + statusBar()->addWidget(statusLabel); +} + +void MainWindow::updateStatusBar(QString &str) +{ + statusLabel->setText(str); +} + +void MainWindow::setGameRecordTree(RecordNode *node) +{ + GameTreeModel *model = new GameTreeModel; + model->setModelData(node); + stepTreeView->setModel(model); +} diff --git a/pool/shard001/C++/0018591_fundatapage.cpp b/pool/shard001/C++/0018591_fundatapage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69b60aa06411a91c03408f91f4cf51a1e27412ba --- /dev/null +++ b/pool/shard001/C++/0018591_fundatapage.cpp @@ -0,0 +1,118 @@ +/* Copyright (C) 2016 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br) + * + * This file is part of GameCap. + * + * GameCap 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. + * + * GameCap 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 "fundatapage.h" + +// +----------------------------------------------------------- +gc::FunDataPage::FunDataPage(QWidget *pParent) : BasePage(pParent) +{ + m_pQuestionnaire = new Questionnaire(this); + layout()->addWidget(m_pQuestionnaire); + + for(uint i = 0; i < GEQ_SIZE; i++) + m_pQuestionnaire->addQuestion(Questionnaire::Likert, 5); + + connect(m_pQuestionnaire, &Questionnaire::completed, this, &FunDataPage::onCompleted); + connect(m_pQuestionnaire, &Questionnaire::questionChanged, this, &FunDataPage::onQuestionChanged); + + m_pData = static_cast(qApp)->getGameplayData(); +} + +// +----------------------------------------------------------- +void gc::FunDataPage::initializePage() +{ + Game *pGame = static_cast(qApp)->gamePlayer()->currentGame(); + + m_pQuestionnaire->setTitle(tr("Experience with the Game")); + m_pQuestionnaire->setDescription(tr("Please answer the questions bellow considering how you felt about your whole experience playing %1.").arg(pGame->name())); + + QStringList lQuestions = QStringList({ + tr("1. I felt content"), + tr("2. I felt skilful"), + tr("3. I was interested in the game's story"), + tr("4. I thought it was fun"), + tr("5. I was fully occupied with the game"), + tr("6. I felt happy"), + tr("7. It gave me a bad mood"), + tr("8. I thought about other things"), + tr("9. I found it tiresome"), + tr("10. I felt competent"), + tr("11. I thought it was hard"), + tr("12. It was aesthetically pleasing"), + tr("13. I forgot everything around me"), + tr("14. I felt good"), + tr("15. I was good at it"), + tr("16. I felt bored"), + tr("17. I felt successful"), + tr("18. I felt imaginative"), + tr("19. I felt that I could explore things"), + tr("20. I enjoyed it"), + tr("21. I was fast at reaching the game's targets"), + tr("22. I felt annoyed"), + tr("23. I felt pressured"), + tr("24. I felt irritable"), + tr("25. I lost track of time"), + tr("26. I felt challenged"), + tr("27. I found it impressive"), + tr("28. I was deeply concentrated in the game"), + tr("29. I felt frustrated"), + tr("30. It felt like a rich experience"), + tr("31. I lost connection with the outside world"), + tr("32. I felt time pressure"), + tr("33. I had to put a lot of effort into it") + }); + + QStringList lOptions = { + tr("not at all"), + tr("slightly"), + tr("moderately"), + tr("fairly"), + tr("extremely") + }; + + for(int i = 0; i < GEQ_SIZE; i++) + { + m_pQuestionnaire->setQuestionTitle(i, lQuestions[i]); + m_pQuestionnaire->setLikertOptionTitles(i, lOptions); + m_pQuestionnaire->setQuestionValue(i, -1); + } + + m_bCompleted = false; + emit completeChanged(); + + m_pQuestionnaire->setFocus(); +} + +// +----------------------------------------------------------- +bool gc::FunDataPage::isComplete() const +{ + return m_bCompleted; +} + +// +----------------------------------------------------------- +void gc::FunDataPage::onCompleted() +{ + m_bCompleted = true; + emit completeChanged(); +} + +// +----------------------------------------------------------- +void gc::FunDataPage::onQuestionChanged(const uint iIndex, const Questionnaire::QuestionType eType, const QVariant oValue) +{ + m_pData->setGEQAnswer(iIndex, static_cast(oValue.toInt() - 2)); +} \ No newline at end of file diff --git a/pool/shard001/C++/0018594_05.cc b/pool/shard001/C++/0018594_05.cc new file mode 100644 index 0000000000000000000000000000000000000000..8036744a3843ee119727d73ac495ccc298a1625d --- /dev/null +++ b/pool/shard001/C++/0018594_05.cc @@ -0,0 +1,92 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2004 - 2015 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, 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. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +// check querying the number of nonzero elements in +// TrilinosWrappers::SparseMatrix + +#include "../tests.h" +#include +#include +#include +#include + + +void test (TrilinosWrappers::SparseMatrix &m) +{ + // first set a few entries. count how many + // entries we have + unsigned int counter = 0; + for (unsigned int i=0; ikeyIdentifier(); + if (key == "U+0020") { + element().setActive(true); + // No setDefaultHandled(), because IE dispatches a keypress in this case + // and the caller will only dispatch a keypress if we don't call setDefaultHandled(). + } +} + +void BaseCheckableInputType::handleKeypressEvent(KeyboardEvent* event) +{ + if (event->charCode() == ' ') { + // Prevent scrolling down the page. + event->setDefaultHandled(); + } +} + +bool BaseCheckableInputType::canSetStringValue() const +{ + return false; +} + +// FIXME: Could share this with BaseClickableWithKeyInputType and RangeInputType if we had a common base class. +void BaseCheckableInputType::accessKeyAction(bool sendMouseEvents) +{ + InputType::accessKeyAction(sendMouseEvents); + + element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents); +} + +bool BaseCheckableInputType::matchesDefaultPseudoClass() +{ + return element().fastHasAttribute(checkedAttr); +} + +String BaseCheckableInputType::fallbackValue() const +{ + return "on"; +} + +bool BaseCheckableInputType::storesValueSeparateFromAttribute() +{ + return false; +} + +void BaseCheckableInputType::setValue(const String& sanitizedValue, bool, TextFieldEventBehavior) +{ + element().setAttribute(valueAttr, AtomicString(sanitizedValue)); +} + +void BaseCheckableInputType::readingChecked() const +{ + if (m_isInClickHandler) + UseCounter::count(element().document(), UseCounter::ReadingCheckedInClickHandler); +} + +bool BaseCheckableInputType::isCheckable() +{ + return true; +} + +bool BaseCheckableInputType::shouldDispatchFormControlChangeEvent(String& oldValue, String& newValue) +{ + return oldValue != newValue; +} + +} // namespace blink diff --git a/pool/shard001/C++/0018625_bitstream_buffer.cc b/pool/shard001/C++/0018625_bitstream_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..49caf5b8215cf03622a04e9a673bce76081d8355 --- /dev/null +++ b/pool/shard001/C++/0018625_bitstream_buffer.cc @@ -0,0 +1,34 @@ +// 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 "media/base/bitstream_buffer.h" + +namespace media { + +BitstreamBuffer::BitstreamBuffer(int32_t id, + base::SharedMemoryHandle handle, + size_t size) + : id_(id), + handle_(handle), + size_(size), + presentation_timestamp_(kNoTimestamp()) {} + +BitstreamBuffer::BitstreamBuffer(int32_t id, + base::SharedMemoryHandle handle, + size_t size, + base::TimeDelta presentation_timestamp) + : id_(id), + handle_(handle), + size_(size), + presentation_timestamp_(presentation_timestamp) {} + +BitstreamBuffer::~BitstreamBuffer() {} + +void BitstreamBuffer::SetDecryptConfig(const DecryptConfig& decrypt_config) { + key_id_ = decrypt_config.key_id(); + iv_ = decrypt_config.iv(); + subsamples_ = decrypt_config.subsamples(); +} + +} // namespace media diff --git a/pool/shard001/C++/0018626_CWE191_Integer_Underflow__char_rand_sub_43.cpp b/pool/shard001/C++/0018626_CWE191_Integer_Underflow__char_rand_sub_43.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abc4c114867ddf05dbb3dc7876f5d3760139fa85 --- /dev/null +++ b/pool/shard001/C++/0018626_CWE191_Integer_Underflow__char_rand_sub_43.cpp @@ -0,0 +1,126 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE191_Integer_Underflow__char_rand_sub_43.cpp +Label Definition File: CWE191_Integer_Underflow.label.xml +Template File: sources-sinks-43.tmpl.cpp +*/ +/* + * @description + * CWE: 191 Integer Underflow + * BadSource: rand Set data to result of rand() + * GoodSource: Set data to a small, non-zero number (negative two) + * Sinks: sub + * GoodSink: Ensure there will not be an underflow before subtracting 1 from data + * BadSink : Subtract 1 from data, which can cause an Underflow + * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +namespace CWE191_Integer_Underflow__char_rand_sub_43 +{ + +#ifndef OMITBAD + +static void badSource(char &data) +{ + /* POTENTIAL FLAW: Use a random value */ + data = (char)RAND32(); +} + +void bad() +{ + char data; + data = ' '; + badSource(data); + { + /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ + char result = data - 1; + printHexCharLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSource(char &data) +{ + /* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */ + data = -2; +} + +static void goodG2B() +{ + char data; + data = ' '; + goodG2BSource(data); + { + /* POTENTIAL FLAW: Subtracting 1 from data could cause an underflow */ + char result = data - 1; + printHexCharLine(result); + } +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2GSource(char &data) +{ + /* POTENTIAL FLAW: Use a random value */ + data = (char)RAND32(); +} + +static void goodB2G() +{ + char data; + data = ' '; + goodB2GSource(data); + /* FIX: Add a check to prevent an underflow from occurring */ + if (data > CHAR_MIN) + { + char result = data - 1; + printHexCharLine(result); + } + else + { + printLine("data value is too large to perform subtraction."); + } +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#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 CWE191_Integer_Underflow__char_rand_sub_43; /* 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/shard001/C++/0018630_Ray.cpp b/pool/shard001/C++/0018630_Ray.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cad87fdc58168f197dbbfdef6050e0a239cf58cd --- /dev/null +++ b/pool/shard001/C++/0018630_Ray.cpp @@ -0,0 +1,48 @@ +// +// Author: Shervin Aflatooni +// + +#include "Ray.h" + +#include + +Ray::Ray(glm::vec3 position, glm::vec3 direction) +{ + m_position = position; + m_direction = direction; +} + +Ray::~Ray(void) +{ +} + +Ray Ray::getPickRay(glm::vec2 mousePosition, const glm::vec4 &viewport, const glm::mat4 &viewMatrix, const glm::mat4 &projectionMatrix) +{ + float xRel = mousePosition.x; + float yRel = viewport.w - mousePosition.y; + + glm::vec3 v1 = glm::unProject(glm::vec3(xRel, yRel, 0.0f), viewMatrix, projectionMatrix, viewport); + glm::vec3 v2 = glm::unProject(glm::vec3(xRel, yRel, 1.0f), viewMatrix, projectionMatrix, viewport); + + return Ray(v1, glm::normalize(v2 - v1)); +} + +glm::vec3 Ray::getPosition(void) const +{ + return m_position; +} + +glm::vec3 Ray::getDirection(void) const +{ + return m_direction; +} + +glm::vec3 Ray::getEndPosition(float length) const +{ + return m_position + (length * m_direction); +} + +Line Ray::getLine(float length) const +{ + return Line(m_position, m_position + m_direction * length); +} diff --git a/pool/shard001/C++/0018631_InboundConnectionStatusCode.cpp b/pool/shard001/C++/0018631_InboundConnectionStatusCode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81e321636c1bd805e9a3ad196feb696081858b43 --- /dev/null +++ b/pool/shard001/C++/0018631_InboundConnectionStatusCode.cpp @@ -0,0 +1,112 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace OpenSearchService + { + namespace Model + { + namespace InboundConnectionStatusCodeMapper + { + + static const int PENDING_ACCEPTANCE_HASH = HashingUtils::HashString("PENDING_ACCEPTANCE"); + static const int APPROVED_HASH = HashingUtils::HashString("APPROVED"); + static const int PROVISIONING_HASH = HashingUtils::HashString("PROVISIONING"); + static const int ACTIVE_HASH = HashingUtils::HashString("ACTIVE"); + static const int REJECTING_HASH = HashingUtils::HashString("REJECTING"); + static const int REJECTED_HASH = HashingUtils::HashString("REJECTED"); + static const int DELETING_HASH = HashingUtils::HashString("DELETING"); + static const int DELETED_HASH = HashingUtils::HashString("DELETED"); + + + InboundConnectionStatusCode GetInboundConnectionStatusCodeForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == PENDING_ACCEPTANCE_HASH) + { + return InboundConnectionStatusCode::PENDING_ACCEPTANCE; + } + else if (hashCode == APPROVED_HASH) + { + return InboundConnectionStatusCode::APPROVED; + } + else if (hashCode == PROVISIONING_HASH) + { + return InboundConnectionStatusCode::PROVISIONING; + } + else if (hashCode == ACTIVE_HASH) + { + return InboundConnectionStatusCode::ACTIVE; + } + else if (hashCode == REJECTING_HASH) + { + return InboundConnectionStatusCode::REJECTING; + } + else if (hashCode == REJECTED_HASH) + { + return InboundConnectionStatusCode::REJECTED; + } + else if (hashCode == DELETING_HASH) + { + return InboundConnectionStatusCode::DELETING; + } + else if (hashCode == DELETED_HASH) + { + return InboundConnectionStatusCode::DELETED; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast(hashCode); + } + + return InboundConnectionStatusCode::NOT_SET; + } + + Aws::String GetNameForInboundConnectionStatusCode(InboundConnectionStatusCode enumValue) + { + switch(enumValue) + { + case InboundConnectionStatusCode::PENDING_ACCEPTANCE: + return "PENDING_ACCEPTANCE"; + case InboundConnectionStatusCode::APPROVED: + return "APPROVED"; + case InboundConnectionStatusCode::PROVISIONING: + return "PROVISIONING"; + case InboundConnectionStatusCode::ACTIVE: + return "ACTIVE"; + case InboundConnectionStatusCode::REJECTING: + return "REJECTING"; + case InboundConnectionStatusCode::REJECTED: + return "REJECTED"; + case InboundConnectionStatusCode::DELETING: + return "DELETING"; + case InboundConnectionStatusCode::DELETED: + return "DELETED"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast(enumValue)); + } + + return {}; + } + } + + } // namespace InboundConnectionStatusCodeMapper + } // namespace Model + } // namespace OpenSearchService +} // namespace Aws diff --git a/pool/shard001/C++/0018635_ppb_trace_event_impl.cc b/pool/shard001/C++/0018635_ppb_trace_event_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..ce1afb94b51bb18d824a536088e3ea54a47883bc --- /dev/null +++ b/pool/shard001/C++/0018635_ppb_trace_event_impl.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 "ppapi/shared_impl/ppb_trace_event_impl.h" + +#include "base/basictypes.h" +#include "base/debug/trace_event.h" +#include "base/threading/platform_thread.h" +#include "ppapi/thunk/thunk.h" + +namespace ppapi { + +// PPB_Trace_Event_Dev is a shared implementation because Trace Events can be +// sent from either the plugin process or renderer process depending on whether +// the plugin is in- or out-of-process. Also, for NaCl plugins these functions +// will be executed from untrusted code and handled appropriately by tracing +// functionality in the IRT. + +// static +void* TraceEventImpl::GetCategoryEnabled(const char* category_name) { + // This casting is here because all mem_t return types in Pepper are void* and + // non-const. All mem_t parameters are const void* so there is no way to + // return a pointer type to the caller without some const_cast. The pointer + // type the tracing system works with is normally unsigned char*. + return const_cast(static_cast( + base::debug::TraceLog::GetInstance()->GetCategoryGroupEnabled( + category_name))); +} + +// static +void TraceEventImpl::AddTraceEvent(int8_t phase, + const void* category_enabled, + const char* name, + uint64_t id, + uint32_t num_args, + const char* arg_names[], + const uint8_t arg_types[], + const uint64_t arg_values[], + uint8_t flags) { + + COMPILE_ASSERT(sizeof(unsigned long long) == sizeof(uint64_t), msg); + + base::debug::TraceLog::GetInstance()->AddTraceEvent( + phase, + static_cast(category_enabled), + name, + id, + num_args, + arg_names, + arg_types, + // This cast is necessary for LP64 systems, where uint64_t is defined as + // an unsigned long int, but trace_event internals are hermetic and + // accepts an |unsigned long long*|. The pointer types are compatible but + // the compiler throws an error without an explicit cast. + reinterpret_cast(arg_values), + NULL, + flags); +} + +// static +void TraceEventImpl::AddTraceEventWithThreadIdAndTimestamp( + int8_t phase, + const void* category_enabled, + const char* name, + uint64_t id, + int32_t thread_id, + int64_t timestamp, + uint32_t num_args, + const char* arg_names[], + const uint8_t arg_types[], + const uint64_t arg_values[], + uint8_t flags) { + base::debug::TraceLog::GetInstance()->AddTraceEventWithThreadIdAndTimestamp( + phase, + static_cast(category_enabled), + name, + id, + thread_id, + base::TimeTicks::FromInternalValue(timestamp), + num_args, + arg_names, + arg_types, + // This cast is necessary for LP64 systems, where uint64_t is defined as + // an unsigned long int, but trace_event internals are hermetic and + // accepts an |unsigned long long*|. The pointer types are compatible but + // the compiler throws an error without an explicit cast. + reinterpret_cast(arg_values), + NULL, + flags); +} + +// static +int64_t TraceEventImpl::Now() { + return base::TimeTicks::NowFromSystemTraceTime().ToInternalValue(); +} + +// static +void TraceEventImpl::SetThreadName(const char* thread_name) { + base::PlatformThread::SetName(thread_name); +} + +namespace { + +const PPB_Trace_Event_Dev_0_1 g_ppb_trace_event_thunk_0_1 = { + &TraceEventImpl::GetCategoryEnabled, &TraceEventImpl::AddTraceEvent, + &TraceEventImpl::SetThreadName, }; + +const PPB_Trace_Event_Dev_0_2 g_ppb_trace_event_thunk_0_2 = { + &TraceEventImpl::GetCategoryEnabled, + &TraceEventImpl::AddTraceEvent, + &TraceEventImpl::AddTraceEventWithThreadIdAndTimestamp, + &TraceEventImpl::Now, + &TraceEventImpl::SetThreadName, }; + +} // namespace ppapi + +} // namespace + +namespace ppapi { +namespace thunk { + +const PPB_Trace_Event_Dev_0_1* GetPPB_Trace_Event_Dev_0_1_Thunk() { + return &g_ppb_trace_event_thunk_0_1; +} + +const PPB_Trace_Event_Dev_0_2* GetPPB_Trace_Event_Dev_0_2_Thunk() { + return &g_ppb_trace_event_thunk_0_2; +} + +} // namespace thunk +} // namespace ppapi diff --git a/pool/shard001/C++/0018641_AArch64CallingConvention.cpp b/pool/shard001/C++/0018641_AArch64CallingConvention.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0695cef615f39252674bdd4bbefd1e4711e5d84 --- /dev/null +++ b/pool/shard001/C++/0018641_AArch64CallingConvention.cpp @@ -0,0 +1,156 @@ +//=== AArch64CallingConvention.cpp - AArch64 CC impl ------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file contains the table-generated and custom routines for the AArch64 +// Calling Convention. +// +//===----------------------------------------------------------------------===// + +#include "AArch64CallingConvention.h" +#include "AArch64.h" +#include "AArch64InstrInfo.h" +#include "AArch64Subtarget.h" +#include "llvm/CodeGen/CallingConvLower.h" +#include "llvm/CodeGen/TargetInstrInfo.h" +#include "llvm/IR/CallingConv.h" +using namespace llvm; + +static const MCPhysReg XRegList[] = {AArch64::X0, AArch64::X1, AArch64::X2, + AArch64::X3, AArch64::X4, AArch64::X5, + AArch64::X6, AArch64::X7}; +static const MCPhysReg HRegList[] = {AArch64::H0, AArch64::H1, AArch64::H2, + AArch64::H3, AArch64::H4, AArch64::H5, + AArch64::H6, AArch64::H7}; +static const MCPhysReg SRegList[] = {AArch64::S0, AArch64::S1, AArch64::S2, + AArch64::S3, AArch64::S4, AArch64::S5, + AArch64::S6, AArch64::S7}; +static const MCPhysReg DRegList[] = {AArch64::D0, AArch64::D1, AArch64::D2, + AArch64::D3, AArch64::D4, AArch64::D5, + AArch64::D6, AArch64::D7}; +static const MCPhysReg QRegList[] = {AArch64::Q0, AArch64::Q1, AArch64::Q2, + AArch64::Q3, AArch64::Q4, AArch64::Q5, + AArch64::Q6, AArch64::Q7}; + +static bool finishStackBlock(SmallVectorImpl &PendingMembers, + MVT LocVT, ISD::ArgFlagsTy &ArgFlags, + CCState &State, unsigned SlotAlign) { + unsigned Size = LocVT.getSizeInBits() / 8; + const Align StackAlign = + State.getMachineFunction().getDataLayout().getStackAlignment(); + const Align OrigAlign(ArgFlags.getOrigAlign()); + const Align Align = std::min(OrigAlign, StackAlign); + + for (auto &It : PendingMembers) { + It.convertToMem(State.AllocateStack( + Size, std::max((unsigned)Align.value(), SlotAlign))); + State.addLoc(It); + SlotAlign = 1; + } + + // All pending members have now been allocated + PendingMembers.clear(); + return true; +} + +/// The Darwin variadic PCS places anonymous arguments in 8-byte stack slots. An +/// [N x Ty] type must still be contiguous in memory though. +static bool CC_AArch64_Custom_Stack_Block( + unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, + ISD::ArgFlagsTy &ArgFlags, CCState &State) { + SmallVectorImpl &PendingMembers = State.getPendingLocs(); + + // Add the argument to the list to be allocated once we know the size of the + // block. + PendingMembers.push_back( + CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); + + if (!ArgFlags.isInConsecutiveRegsLast()) + return true; + + return finishStackBlock(PendingMembers, LocVT, ArgFlags, State, 8); +} + +/// Given an [N x Ty] block, it should be passed in a consecutive sequence of +/// registers. If no such sequence is available, mark the rest of the registers +/// of that type as used and place the argument on the stack. +static bool CC_AArch64_Custom_Block(unsigned &ValNo, MVT &ValVT, MVT &LocVT, + CCValAssign::LocInfo &LocInfo, + ISD::ArgFlagsTy &ArgFlags, CCState &State) { + const AArch64Subtarget &Subtarget = static_cast( + State.getMachineFunction().getSubtarget()); + bool IsDarwinILP32 = Subtarget.isTargetILP32() && Subtarget.isTargetMachO(); + + // Try to allocate a contiguous block of registers, each of the correct + // size to hold one member. + ArrayRef RegList; + if (LocVT.SimpleTy == MVT::i64 || (IsDarwinILP32 && LocVT.SimpleTy == MVT::i32)) + RegList = XRegList; + else if (LocVT.SimpleTy == MVT::f16) + RegList = HRegList; + else if (LocVT.SimpleTy == MVT::f32 || LocVT.is32BitVector()) + RegList = SRegList; + else if (LocVT.SimpleTy == MVT::f64 || LocVT.is64BitVector()) + RegList = DRegList; + else if (LocVT.SimpleTy == MVT::f128 || LocVT.is128BitVector()) + RegList = QRegList; + else { + // Not an array we want to split up after all. + return false; + } + + SmallVectorImpl &PendingMembers = State.getPendingLocs(); + + // Add the argument to the list to be allocated once we know the size of the + // block. + PendingMembers.push_back( + CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); + + if (!ArgFlags.isInConsecutiveRegsLast()) + return true; + + // [N x i32] arguments get packed into x-registers on Darwin's arm64_32 + // because that's how the armv7k Clang front-end emits small structs. + unsigned EltsPerReg = (IsDarwinILP32 && LocVT.SimpleTy == MVT::i32) ? 2 : 1; + unsigned RegResult = State.AllocateRegBlock( + RegList, alignTo(PendingMembers.size(), EltsPerReg) / EltsPerReg); + if (RegResult && EltsPerReg == 1) { + for (auto &It : PendingMembers) { + It.convertToReg(RegResult); + State.addLoc(It); + ++RegResult; + } + PendingMembers.clear(); + return true; + } else if (RegResult) { + assert(EltsPerReg == 2 && "unexpected ABI"); + bool UseHigh = false; + CCValAssign::LocInfo Info; + for (auto &It : PendingMembers) { + Info = UseHigh ? CCValAssign::AExtUpper : CCValAssign::ZExt; + State.addLoc(CCValAssign::getReg(It.getValNo(), MVT::i32, RegResult, + MVT::i64, Info)); + UseHigh = !UseHigh; + if (!UseHigh) + ++RegResult; + } + PendingMembers.clear(); + return true; + } + + // Mark all regs in the class as unavailable + for (auto Reg : RegList) + State.AllocateReg(Reg); + + unsigned SlotAlign = Subtarget.isTargetDarwin() ? 1 : 8; + + return finishStackBlock(PendingMembers, LocVT, ArgFlags, State, SlotAlign); +} + +// TableGen provides definitions of the calling convention analysis entry +// points. +#include "AArch64GenCallingConv.inc" diff --git a/pool/shard001/C++/0018643_ts_serversinfo.cpp b/pool/shard001/C++/0018643_ts_serversinfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0beaeb086b43b7c724577ecd7633a9c019a159df --- /dev/null +++ b/pool/shard001/C++/0018643_ts_serversinfo.cpp @@ -0,0 +1,107 @@ +#include "core/ts_serversinfo.h" + +#include "core/ts_logging_qt.h" +#include "teamspeak/public_errors.h" +#include "teamspeak/clientlib_publicdefinitions.h" +#include "ts3_functions.h" +#include "plugin.h" + +TSServersInfo::TSServersInfo(QObject* parent) + : QObject(parent) +{} + +TSServerInfo* TSServersInfo::get_server_info(uint64 server_connection_id, bool create_on_not_exist) +{ + if (m_server_infos.contains(server_connection_id)) + { + const auto kServerInfo = m_server_infos.value(server_connection_id); + if (!kServerInfo) + { + TSLogging::Error("(TSServersInfo::get_server_info): Invalid pointer."); + return nullptr; + } + return kServerInfo.data(); + } + else + { + if (create_on_not_exist) + { + auto server_info = new TSServerInfo(this, server_connection_id); + m_server_infos.insert(server_connection_id, server_info); + connect(server_info, &TSServerInfo::serverGroupListUpdated, this, &TSServersInfo::serverGroupListUpdated, Qt::UniqueConnection); + return server_info; + } + else + { + TSLogging::Error("(TSServersInfo::get_server_info): server_connection_id not found."); + return nullptr; + } + } +} + +uint64 TSServersInfo::find_server_by_unique_id(QString server_id) +{ + uint64 server_connection_id = 0; + { + uint64* servers; + if (ts3Functions.getServerConnectionHandlerList(&servers) == ERROR_ok) + { + for (auto server = servers; *server; ++server) + { + auto ts_server_info = get_server_info(*server, true); + if (ts_server_info && (server_id == ts_server_info->getUniqueId())) + { + server_connection_id = ts_server_info->getServerConnectionHandlerID(); + break; + } + } + ts3Functions.freeMemory(servers); + } + } + return server_connection_id; +} + +void TSServersInfo::onConnectStatusChangeEvent(uint64 server_connection_id, int new_status, unsigned int error_number) +{ + if (new_status == STATUS_DISCONNECTED) + { + if (m_server_infos.contains(server_connection_id)) + { + auto p_ServerInfo = m_server_infos.value(server_connection_id); + if (p_ServerInfo) + p_ServerInfo.data()->deleteLater(); + + m_server_infos.remove(server_connection_id); + } + } + + emit connectStatusChanged(server_connection_id, new_status, error_number); +} + +void TSServersInfo::onServerGroupListEvent(uint64 server_connection_id, uint64 server_group_id, const char *name, int type, int icon_id, int save_db) +{ + auto ts_server_info = get_server_info(server_connection_id, true); + if (ts_server_info) + ts_server_info->onServerGroupListEvent(server_group_id, name, type, icon_id, save_db); +} + +void TSServersInfo::onServerGroupListFinishedEvent(uint64 server_connection_id) +{ + auto ts_server_info = get_server_info(server_connection_id, false); + if (ts_server_info) + ts_server_info->onServerGroupListFinishedEvent(); +} + +void TSServersInfo::onChannelGroupListEvent(uint64 server_connection_id, uint64 channel_group_id, const char *name, int type, int icon_id, int save_db) +{ + auto ts_server_info = get_server_info(server_connection_id, true); + if (ts_server_info) + ts_server_info->onChannelGroupListEvent(channel_group_id, name, type, icon_id, save_db); +} + +void TSServersInfo::onChannelGroupListFinishedEvent(uint64 server_connection_id) +{ + auto ts_server_info = get_server_info(server_connection_id, false); + if (ts_server_info) + ts_server_info->onChannelGroupListFinishedEvent(); +} diff --git a/pool/shard001/C++/0018646_linear-bool.cpp b/pool/shard001/C++/0018646_linear-bool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35f96c7c533c130bdc7e8589f4d0c7780cd3083c --- /dev/null +++ b/pool/shard001/C++/0018646_linear-bool.cpp @@ -0,0 +1,196 @@ +/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ +/* + * Main authors: + * Christian Schulte + * + * Copyright: + * Christian Schulte, 2006 + * + * Last modified: + * $Date: 2012-09-07 17:31:22 +0200 (fr, 07 sep 2012) $ by $Author: schulte $ + * $Revision: 13068 $ + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.org + * + * 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 + +namespace Gecode { + + using namespace Int; + + void + linear(Home home, const BoolVarArgs& x, IntRelType irt, int c, + IntConLevel icl) { + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=1; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,c,icl); + } + + void + linear(Home home, const BoolVarArgs& x, IntRelType irt, IntVar y, + IntConLevel icl) { + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=1; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,y,0,icl); + } + + void + linear(Home home, + const IntArgs& a, const BoolVarArgs& x, IntRelType irt, int c, + IntConLevel icl) { + if (a.size() != x.size()) + throw ArgumentSizeMismatch("Int::linear"); + if (home.failed()) + return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=a[i]; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,c,icl); + } + + void + linear(Home home, + const IntArgs& a, const BoolVarArgs& x, IntRelType irt, IntVar y, + IntConLevel icl) { + if (a.size() != x.size()) + throw ArgumentSizeMismatch("Int::linear"); + if (home.failed()) + return; + + int n=x.size(); + Region re(home); + Linear::Term* t = + re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=a[i]; t[i].x=x[i]; + } + int min, max; + estimate(t,n,0,min,max); + IntView v(y); + switch (irt) { + case IRT_EQ: + GECODE_ME_FAIL(v.gq(home,min)); GECODE_ME_FAIL(v.lq(home,max)); + break; + case IRT_GQ: + GECODE_ME_FAIL(v.lq(home,max)); + break; + case IRT_LQ: + GECODE_ME_FAIL(v.gq(home,min)); + break; + default: ; + } + if (home.failed()) return; + Linear::post(home,t,n,irt,y,0,icl); + } + + void + linear(Home home, const BoolVarArgs& x, IntRelType irt, int c, + Reify r, IntConLevel icl) { + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=1; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,c,r,icl); + } + + void + linear(Home home, const BoolVarArgs& x, IntRelType irt, IntVar y, + Reify r, IntConLevel icl) { + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=1; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,y,r,icl); + } + + void + linear(Home home, + const IntArgs& a, const BoolVarArgs& x, IntRelType irt, int c, + Reify r, IntConLevel icl) { + if (a.size() != x.size()) + throw ArgumentSizeMismatch("Int::linear"); + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=a[i]; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,c,r,icl); + } + + void + linear(Home home, + const IntArgs& a, const BoolVarArgs& x, IntRelType irt, IntVar y, + Reify r, IntConLevel icl) { + if (a.size() != x.size()) + throw ArgumentSizeMismatch("Int::linear"); + if (home.failed()) return; + + int n=x.size(); + Region re(home); + Linear::Term* t = re.alloc >(n); + for (int i=n; i--; ) { + t[i].a=a[i]; t[i].x=x[i]; + } + + Linear::post(home,t,n,irt,y,r,icl); + } + +} + +// STATISTICS: int-post diff --git a/pool/shard001/C++/0018648_compile_compile_MatrixBase_template_int_int_topLeftCorner.cpp b/pool/shard001/C++/0018648_compile_compile_MatrixBase_template_int_int_topLeftCorner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b475c7cad14a94044843120dd92ed541420a2cf --- /dev/null +++ b/pool/shard001/C++/0018648_compile_compile_MatrixBase_template_int_int_topLeftCorner.cpp @@ -0,0 +1,40 @@ +#include +#include + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + + +using namespace Eigen; +using namespace std; + +int main(int, char**) +{ + cout.precision(3); + #include +#include + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + + +using namespace Eigen; +using namespace std; + +int main(int, char**) +{ + cout.precision(3); + Matrix4i m = Matrix4i::Random(); +cout << "Here is the matrix m:" << endl << m << endl; +cout << "Here is m.topLeftCorner<2,2>():" << endl; +cout << m.topLeftCorner<2,2>() << endl; +m.topLeftCorner<2,2>().setZero(); +cout << "Now the matrix m is:" << endl << m << endl; + + return 0; +} + + return 0; +} diff --git a/pool/shard001/C++/0018650_CAAUConnections.cpp b/pool/shard001/C++/0018650_CAAUConnections.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3a150130210d392385fb60717409d455ebd8c35 --- /dev/null +++ b/pool/shard001/C++/0018650_CAAUConnections.cpp @@ -0,0 +1,110 @@ +/* Copyright © 2007 Apple Inc. All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by + Apple Inc. ("Apple") in consideration of your agreement to the + following terms, and your use, installation, modification or + redistribution of this Apple software constitutes acceptance of these + terms. If you do not agree with these terms, please do not use, + install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and + subject to these terms, Apple grants you a personal, non-exclusive + license, under Apple's copyrights in this original Apple software (the + "Apple Software"), to use, reproduce, modify and redistribute the Apple + Software, with or without modifications, in source and/or binary forms; + provided that if you redistribute the Apple Software in its entirety and + without modifications, you must retain this notice and the following + text and disclaimers in all such redistributions of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. + may be used to endorse or promote products derived from the Apple + Software without specific prior written permission from Apple. Except + as expressly stated in this notice, no other rights or licenses, express + or implied, are granted by Apple herein, including but not limited to + any patent rights that may be infringed by your derivative works or by + other works in which the Apple Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE + MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND + OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, + MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED + AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), + STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ +#include "CAAUConnections.h" + +OSStatus CAAUConnections::Find (const AUGraph &inGraph, const CAAudioUnit &inUnit, AudioUnitScope inScope) +{ + if (!mConns.empty()) mConns.clear(); + + AudioUnit theUnit; + OSStatus result = AUGraphGetNodeInfo (inGraph, inUnit.GetAUNode(), NULL, NULL, NULL, &theUnit); + if ((theUnit != inUnit.AU()) || result) return (result ? result : -1); + + UInt32 numConns = 0; + if ((result = AUGraphCountNodeConnections (inGraph, inUnit.GetAUNode(), &numConns))) return result; + + if (numConns) { + AudioUnitNodeConnection s_conns[4]; + AudioUnitNodeConnection *conns = (numConns > 4 ? new AudioUnitNodeConnection[numConns] : s_conns); + + require_noerr (result = AUGraphGetNodeConnections (inGraph, inUnit.GetAUNode(), conns, &numConns), home); + + for (unsigned int i = 0; i < numConns; ++i) { + if (inScope == kAudioUnitScope_Output && conns[i].sourceNode == inUnit.GetAUNode()) { + AudioUnit otherAU; + require_noerr (result = AUGraphGetNodeInfo (inGraph, conns[i].destNode, NULL, NULL, NULL, &otherAU), home); + mConns.push_back (AUConn (conns[i].sourceOutputNumber, otherAU, conns[i].destNode, conns[i].destInputNumber)); + } + if (inScope == kAudioUnitScope_Input && conns[i].destNode == inUnit.GetAUNode()) { + AudioUnit otherAU; + require_noerr (result = AUGraphGetNodeInfo (inGraph, conns[i].sourceNode, NULL, NULL, NULL, &otherAU), home); + mConns.push_back (AUConn (conns[i].destInputNumber, otherAU, conns[i].sourceNode, conns[i].sourceOutputNumber)); + } + } + home: + if (numConns > 4) delete [] conns; + } + return result; +} + +bool CAAUConnections::Connection (UInt32 inIndex, + AudioUnitElement &outMyEl, + CAAudioUnit &outOtherAU, + AudioUnitElement &outOtherAUEl) +{ + if (inIndex < Size()) { + outMyEl = mConns[inIndex].mMyEl; + outOtherAU = mConns[inIndex].mOtherAU; + outOtherAUEl = mConns[inIndex].mOtherEl; + return true; + } + return false; +} + +bool CAAUConnections::IsMember (AudioUnitElement inMyEl) const +{ + for (AUConns::const_iterator iter = mConns.begin(); iter < mConns.end(); ++iter) { + const AUConn &conn = (*iter); + if (inMyEl == conn.mMyEl); + return true; + } + return false; +} + +void CAAUConnections::Print (FILE* file) const +{ + for (AUConns::const_iterator iter = mConns.begin(); iter < mConns.end(); ++iter) { + const AUConn &conn = (*iter); + fprintf (file, "El: %d, To:", (int)conn.mMyEl); + conn.mOtherAU.Print (file); + fprintf (file, ", Other El: %d\n", (int)conn.mOtherEl); + } +} diff --git a/pool/shard001/C++/0018651_baciTestUtils.cpp b/pool/shard001/C++/0018651_baciTestUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c02400b8ad696fb2d825394bde700310191a5868 --- /dev/null +++ b/pool/shard001/C++/0018651_baciTestUtils.cpp @@ -0,0 +1,149 @@ +/******************************************************************************* +* ALMA - Atacama Large Millimiter Array +* (c) European Southern Observatory, 2002 +* Copyright by ESO (in the framework of the ALMA collaboration), +* All rights reserved +* +* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* "@(#) $Id: baciTestUtils.cpp,v 1.93 2005/04/20 13:31:46 gchiozzi Exp $" +* +* who when what +* -------- -------- ---------------------------------------------- +* gchiozzi 2001-10-19 created +*/ + +static char *rcsId="@(#) $Id: baciTestUtils.cpp,v 1.93 2005/04/20 13:31:46 gchiozzi Exp $"; +static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); + +#include +#include +#include +#include + +int write_iors_to_file (const int count, + CORBA::String_var name[], + CORBA::String_var type[], + CORBA::String_var ior[]) +{ + const char* ior_output_file = "iors.dat"; + + FILE *output_file = ACE_OS::fopen (ior_output_file, "w"); + + if (output_file == 0) + { + ACS_SHORT_LOG((LM_ERROR, "Cannot open output files for writing IORs: %s", + ior_output_file)); + return -1; + } + + u_int result; + for (int i=0; i < count; i++) + { + result = ACE_OS::fprintf (output_file, "%s %s %s\n", + name[i].in(), + type[i].in(), + ior[i].in()); + + if (result != ( + ACE_OS::strlen (name[i].in()) + 1 + + ACE_OS::strlen (type[i].in()) + 1 + + ACE_OS::strlen (ior[i].in()) + + ACE_OS::strlen ("\n"))) + { + ACS_SHORT_LOG ((LM_ERROR, + "ACE_OS::fprintf failed while writing IORs to file %s", + ior_output_file)); + return -1; + } + + } + ACE_OS::fclose (output_file); + return 0; +} + +int read_IOR_from_file (std::string device, std::string &readIOR) +{ + const char* ior_input_file = "iors.dat"; + + // Open the file for reading. + FILE *input_file = ACE_OS::fopen (ior_input_file, "r"); + + if (input_file == 0) + { + ACS_SHORT_LOG((LM_ERROR, + "Unable to open %s for reading", + ior_input_file)); + return -1; + } + + char name[256]; + char type[256]; + char ior[2048]; + + ACS_SHORT_LOG((LM_INFO,"baciTestClient: Reading file")); + + while( fscanf (input_file, "%s %s %s\n", name, type, ior) != 0) + { + ACS_SHORT_LOG((LM_INFO,"baciTestClient: Looking at %s", name)); + if (ior == 0) + { + ACS_SHORT_LOG((LM_ERROR, + "Unable to read ior")); + return -1; + } + if(device.compare(name)==0) + { + ACS_SHORT_LOG((LM_INFO,"baciTestClient: Found")); + readIOR = ior; + break; + } + } + + ACE_OS::fclose(input_file); + ACS_SHORT_LOG((LM_INFO,"baciTestClient: Input file closed")); + return 0; + +} /* end read_IOR_from_file */ + + +static void worker(void* proc) +{ + (*((CORBAShutdown::ShutdownFunction)proc))(); +} + + +CORBAShutdown::ShutdownFunction CORBAShutdown::m_func = 0; + +void +CORBAShutdown::setShutdownFunction(ShutdownFunction function) +{ + m_func = function; +} + +void +CORBAShutdown::shutdown() +{ + if (!m_func) + return; + + ACE_OS::sleep(1); + + ACE_Thread_Manager *thr_mgr = ACE_Thread_Manager::instance (); + thr_mgr->spawn (ACE_THR_FUNC (worker), (void*)m_func); + +} + + diff --git a/pool/shard001/C++/0018657_main.cc b/pool/shard001/C++/0018657_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..d339e9c06254110897d167051805e7b0e20d0ad6 --- /dev/null +++ b/pool/shard001/C++/0018657_main.cc @@ -0,0 +1,139 @@ + +/* + * MIT License + * + * Copyright (c) 2017 Susanow + * Copyright (c) 2017 Hiroki SHIROKURA + * + * 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 + +class l2fwd_arg { + ssize_t qid; + ssize_t pid; + public: + l2fwd_arg() : pid(-1), qid(-1) {} + void set(size_t p, size_t q) { pid=p; qid=q; } + ssize_t get_pid() const { return pid; } + ssize_t get_qid() const { return qid; } +}; +l2fwd_arg l2fwd_args[RTE_MAX_LCORE]; + +size_t n_ports = 0; +size_t n_queues = 0; +size_t n_pkts[2][10]; + +int l2fwd(void*) +{ + const size_t lcore_id = rte_lcore_id(); + const size_t pid = l2fwd_args[lcore_id].get_pid(); + const size_t qid = l2fwd_args[lcore_id].get_qid(); + printf("start %s on lcore%zd pid=%zd qid=%zd \n", + __func__, lcore_id, pid, qid); + while (true) { + constexpr size_t BURSTSZ = 32; + rte_mbuf* mbufs[BURSTSZ]; + size_t nb_recv = rte_eth_rx_burst(pid, qid, mbufs, BURSTSZ); + if (nb_recv == 0) continue; + + n_pkts[pid][qid] += nb_recv; + for (size_t i=0; i; + +//------------------------------------------------- +// atari_vg_earom_device - constructor +//------------------------------------------------- + +atari_vg_earom_device::atari_vg_earom_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) + : device_t(mconfig, ATARIVGEAROM, "Atari VG EAROM", tag, owner, clock, "atari_vg_earom", __FILE__), + device_nvram_interface(mconfig, *this) +{ +} + +// Activate the output buffer (LS244)'s /G1 and /G2 lines to read whatever is on the EAROM's output bus +READ8_MEMBER( atari_vg_earom_device::read ) +{ + logerror("read from earom output: %02x(%02x):%02x\n", m_in_offset, offset, m_out_data); + return (m_out_data); +} + +// Write to the address input (LS174) and data input (LS374) latches respectively +WRITE8_MEMBER( atari_vg_earom_device::write ) +{ + logerror("write to earom buffers: offset:data of %02x:%02x\n", offset, data); + m_in_offset = offset; + m_in_data = data; +} + +/* CTRL controls the CTRL latch (LS175): +See top of file: there are two possible wirings! + */ +WRITE8_MEMBER( atari_vg_earom_device::ctrl_w ) +{ + static const char *const er2055_State[5] = { "IDLE", "RD_WAIT", "RD_OUTPUT", "WRITE", "ERASE" }; + logerror("EAROM_CTRL written with %02x: ", data); + switch(data&0xe) + { + case 0x0: case 0x2: case 0x4: case 0x6: // CS was low, chip is idle + m_state = ER2055_IDLE; + break; + case 0x8: // C1 = 1, C2 = 0: Read, (wait for clock, if clock has arrived, idle). + if ((m_state==ER2055_READ_WAITING_FOR_CLOCK)&&(((m_old_ctrl&1)==0)&&((data&1)==1))) // rising clock edge? + m_state = ER2055_READ_DRIVING_BUS; + else if (m_state!=ER2055_READ_DRIVING_BUS) // if we're already driving the bus, stay driving it. otherwise we're still waiting. + m_state = ER2055_READ_WAITING_FOR_CLOCK; + break; + case 0xA: // C1 = 0, C2 = 0: Write (set gate 0 if the bit is a 0, set gate 1 if the bit is a 1) HACK: we treat this as WRITE always to handle both wiring variants + m_state = ER2055_WRITING_BITS; + break; + case 0xC: // C1 = 1, C2 = 1: Invalid // HACK: we treat this as WRITE always to handle both wiring variants + logerror("INVALID CTRL STATE!"); + m_state = ER2055_WRITING_BITS; + break; + case 0xE: // C1 = 0, C2 = 1: Erase (zero both gates for all bits of the current byte; byte will read as random garbage after this, different each time!) + m_state = ER2055_ERASING_BITS; + break; + } + logerror("state is now %s\n", er2055_State[m_state]); + + switch(m_state) + { + case ER2055_IDLE: // idle, do nothing. + case ER2055_READ_WAITING_FOR_CLOCK: // waiting for a clock rising edge which we haven't yet seen, do nothing + m_out_data = 0xFF; + break; + case ER2055_READ_DRIVING_BUS: // bus is being driven with data + m_out_data = m_rom[m_in_offset]; + break; + case ER2055_WRITING_BITS: // write contents of bus to rom + m_rom[m_in_offset] = m_in_data; + m_out_data = m_in_data; + break; + case ER2055_ERASING_BITS: // erase contents of rom + m_rom[m_in_offset] = 0; //TODO: this should actually set the rom contents to an invalid state which reads inconsistently until it is written to by a WRITE command + m_out_data = m_in_data; + break; + } + m_old_ctrl = data; +} + +//------------------------------------------------- +// nvram_default - called to initialize NVRAM to +// its default state +//------------------------------------------------- + +void atari_vg_earom_device::nvram_default() +{ + memset(m_rom,0,EAROM_SIZE); +} + +//------------------------------------------------- +// nvram_read - called to read NVRAM from the +// .nv file +//------------------------------------------------- + +void atari_vg_earom_device::nvram_read(emu_file &file) +{ + file.read(m_rom,EAROM_SIZE); +} + +//------------------------------------------------- +// nvram_write - called to write NVRAM to the +// .nv file +//------------------------------------------------- + +void atari_vg_earom_device::nvram_write(emu_file &file) +{ + file.write(m_rom,EAROM_SIZE); +} + +//------------------------------------------------- +// device_start - device-specific startup +//------------------------------------------------- +void atari_vg_earom_device::device_start() +{ + /* register for save states */ + save_item(NAME(m_state)); + save_item(NAME(m_old_ctrl)); + save_item(NAME(m_in_offset)); + save_item(NAME(m_in_data)); + save_item(NAME(m_out_data)); + save_item(NAME(m_rom)); +} + +//------------------------------------------------- +// device_reset - device-specific reset +//------------------------------------------------- + +void atari_vg_earom_device::device_reset() +{ + m_state = ER2055_READ_WAITING_FOR_CLOCK; // start in read mode + m_old_ctrl = 0; + m_in_offset = 0; + m_in_data = 0; + m_out_data = 0xFF; // the value driven to the bus by the resistors if EAROM is open bus +} diff --git a/pool/shard001/C++/0018663_gnuplotfile.cpp b/pool/shard001/C++/0018663_gnuplotfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..498404597d5450b77be062c33df424f446f0a726 --- /dev/null +++ b/pool/shard001/C++/0018663_gnuplotfile.cpp @@ -0,0 +1,238 @@ + +// +// This source file is part of appleseed. +// Visit https://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization +// +// 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. +// + +// Interface header. +#include "gnuplotfile.h" + +// appleseed.foundation headers. +#include "foundation/utility/foreach.h" + +// Standard headers. +#include +#include + +using namespace std; + +namespace foundation +{ + +// +// GnuplotFile class implementation. +// + +GnuplotFile::GnuplotFile() + : m_has_xrange(false) + , m_has_yrange(false) + , m_xrange(0.0, 0.0) + , m_yrange(0.0, 0.0) + , m_logscale_x(false) + , m_logscale_y(false) +{ +} + +GnuplotFile& GnuplotFile::set_title(const string& title) +{ + m_title = title; + return *this; +} + +GnuplotFile& GnuplotFile::set_xlabel(const string& label) +{ + m_xlabel = label; + return *this; +} + +GnuplotFile& GnuplotFile::set_ylabel(const string& label) +{ + m_ylabel = label; + return *this; +} + +GnuplotFile& GnuplotFile::set_xrange(const double low, const double high) +{ + m_has_xrange = true; + m_xrange = Vector2d(low, high); + return *this; +} + +GnuplotFile& GnuplotFile::set_yrange(const double low, const double high) +{ + m_has_yrange = true; + m_yrange = Vector2d(low, high); + return *this; +} + +GnuplotFile& GnuplotFile::set_logscale_x() +{ + m_logscale_x = true; + return *this; +} + +GnuplotFile& GnuplotFile::set_logscale_y() +{ + m_logscale_y = true; + return *this; +} + +GnuplotFile::Plot& GnuplotFile::new_plot() +{ + m_plots.emplace_back(); + return m_plots.back(); +} + +bool GnuplotFile::write(const string& filepath) const +{ + ofstream file(filepath.c_str()); + + if (!file.is_open()) + return false; + + if (!m_title.empty()) + file << "set title \"" << m_title << "\" noenhanced" << endl; + else file << "unset title" << endl; + + if (!m_xlabel.empty()) + file << "set xlabel \"" << m_xlabel << "\" noenhanced" << endl; + else file << "unset xlabel" << endl; + + if (!m_ylabel.empty()) + file << "set ylabel \"" << m_ylabel << "\" noenhanced" << endl; + else file << "unset ylabel" << endl; + + if (m_has_xrange) + file << "set xrange [" << m_xrange[0] << ":" << m_xrange[1] << "]" << endl; + else file << "set autoscale x" << endl; + + if (m_has_yrange) + file << "set yrange [" << m_yrange[0] << ":" << m_yrange[1] << "]" << endl; + else file << "set autoscale y" << endl; + + if (m_logscale_x) + file << "set logscale x" << endl; + else file << "unset logscale x" << endl; + + if (m_logscale_y) + file << "set logscale y" << endl; + else file << "unset logscale y" << endl; + + if (!m_plots.empty()) + { + file << "plot "; + + for (size_t i = 0; i < m_plots.size(); ++i) + { + if (i > 0) + file << ", "; + m_plots[i].write_decl(file); + } + + file << endl; + + for (size_t i = 0; i < m_plots.size(); ++i) + m_plots[i].write_points(file); + } + + return file.good(); +} + + +// +// GnuplotFile::Plot class implementation. +// + +GnuplotFile::Plot& GnuplotFile::Plot::set_points(const vector& points) +{ + m_points = points; + return *this; +} + +GnuplotFile::Plot& GnuplotFile::Plot::set_points(const vector& points) +{ + const size_t n = points.size(); + + m_points.resize(n); + + for (size_t i = 0; i < n; ++i) + m_points[i] = Vector2d(points[i]); + + return *this; +} + +GnuplotFile::Plot& GnuplotFile::Plot::set_title(const string& title) +{ + m_title = title; + return *this; +} + +GnuplotFile::Plot& GnuplotFile::Plot::set_color(const string& color) +{ + m_color = color; + return *this; +} + +GnuplotFile::Plot& GnuplotFile::Plot::set_style(const string& style) +{ + m_style = style; + return *this; +} + +GnuplotFile::Plot& GnuplotFile::Plot::set_smoothing(const string& smoothing) +{ + m_smoothing = smoothing; + return *this; +} + +void GnuplotFile::Plot::write_decl(ofstream& file) const +{ + file << "\"-\" with "; + + file << (m_style.empty() ? "lines" : m_style); + + if (!m_color.empty()) + file << " linecolor rgbcolor \"" << m_color << "\""; + + if (!m_smoothing.empty()) + file << " smooth " << m_smoothing; + + if (!m_title.empty()) + file << " title \"" << m_title << "\" noenhanced"; + else file << " notitle"; +} + +void GnuplotFile::Plot::write_points(ofstream& file) const +{ + for (const_each> i = m_points; i; ++i) + { + const Vector2d& p = *i; + file << " " << p[0] << " " << p[1] << endl; + } + + file << " e" << endl; +} + +} // namespace foundation diff --git a/pool/shard001/C++/0018666_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B.cpp b/pool/shard001/C++/0018666_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d932f4845c478513846d3692a22ca9577fa80deb --- /dev/null +++ b/pool/shard001/C++/0018666_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B.cpp @@ -0,0 +1,42 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B.cpp +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml +Template File: sources-sink-83_goodG2B.tmpl.cpp +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sinks: memmove + * BadSink : Copy data to string using memmove + * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack + * + * */ +#ifndef OMITGOOD + +#include "std_testcase.h" +#include "CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83.h" + +namespace CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83 +{ +CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B::CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B(char * dataCopy) +{ + data = dataCopy; + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + memset(data, 'A', 50-1); /* fill with 'A's */ + data[50-1] = '\0'; /* null terminate */ +} + +CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B::~CWE121_Stack_Based_Buffer_Overflow__CWE806_char_alloca_memmove_83_goodG2B() +{ + { + char dest[50] = ""; + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + memmove(dest, data, strlen(data)*sizeof(char)); + dest[50-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + } +} +} +#endif /* OMITGOOD */ diff --git a/pool/shard001/C++/0018667_UNIX_PeerGatewayForTunnelFixture.cpp b/pool/shard001/C++/0018667_UNIX_PeerGatewayForTunnelFixture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f84b76fb462092429be66d167087ae9a85bc0217 --- /dev/null +++ b/pool/shard001/C++/0018667_UNIX_PeerGatewayForTunnelFixture.cpp @@ -0,0 +1,75 @@ +//%LICENSE//////////////////////////////////////////////////////////////// +// +// Licensed to The Open Group (TOG) under one or more contributor license +// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with +// this work for additional information regarding copyright ownership. +// Each contributor licenses this file to you under the OpenPegasus Open +// Source License; you may not use this file except in compliance with the +// License. +// +// 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 "UNIX_PeerGatewayForTunnelFixture.h" +#include + +UNIX_PeerGatewayForTunnelFixture::UNIX_PeerGatewayForTunnelFixture() +{ +} + +UNIX_PeerGatewayForTunnelFixture::~UNIX_PeerGatewayForTunnelFixture() +{ +} + +void UNIX_PeerGatewayForTunnelFixture::Run() +{ + CIMName className("UNIX_PeerGatewayForTunnel"); + CIMNamespaceName nameSpace("root/cimv2"); + UNIX_PeerGatewayForTunnel _p; + UNIX_PeerGatewayForTunnelProvider _provider; + Uint32 propertyCount; + CIMOMHandle omHandle; + _provider.initialize(omHandle); + _p.initialize(); + + for(int pIndex = 0; _p.load(pIndex); pIndex++) + { + CIMInstance instance = _provider.constructInstance(className, + nameSpace, + _p); + CIMObjectPath path = instance.getPath(); + cout << path.toString() << endl; + propertyCount = instance.getPropertyCount(); + for(Uint32 i = 0; i < propertyCount; i++) + { + + CIMProperty propertyItem = instance.getProperty(i); + cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl; + + } + cout << "------------------------------------" << endl; + cout << endl; + } + + _p.finalize(); +} + diff --git a/pool/shard001/C++/0018671_stattext.cpp b/pool/shard001/C++/0018671_stattext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e0a5fb14d591e6dd488308a2f153fa9cc9ddcb8 --- /dev/null +++ b/pool/shard001/C++/0018671_stattext.cpp @@ -0,0 +1,182 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: src/gtk1/stattext.cpp +// Purpose: +// Author: Robert Roebling +// Copyright: (c) 1998 Robert Roebling +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +// For compilers that support precompilation, includes "wx.h". +#include "wx/wxprec.h" + +#if wxUSE_STATTEXT + +#include "wx/stattext.h" +#include "wx/gtk1/private.h" + +#include "gdk/gdk.h" +#include "gtk/gtk.h" + +extern "C" +void wxgtk_window_size_request_callback(GtkWidget *widget, + GtkRequisition *requisition, + wxWindow *win); + +//----------------------------------------------------------------------------- +// wxStaticText +//----------------------------------------------------------------------------- + +wxStaticText::wxStaticText() +{ +} + +wxStaticText::wxStaticText(wxWindow *parent, + wxWindowID id, + const wxString &label, + const wxPoint &pos, + const wxSize &size, + long style, + const wxString &name) +{ + Create( parent, id, label, pos, size, style, name ); +} + +bool wxStaticText::Create(wxWindow *parent, + wxWindowID id, + const wxString &label, + const wxPoint &pos, + const wxSize &size, + long style, + const wxString &name ) +{ + m_needParent = TRUE; + + if (!PreCreation( parent, pos, size ) || + !CreateBase( parent, id, pos, size, style, wxDefaultValidator, name )) + { + wxFAIL_MSG( wxT("wxStaticText creation failed") ); + return FALSE; + } + + m_label = label; + m_widget = gtk_label_new( wxGTK_CONV( GTKRemoveMnemonics(label)) ); + + GtkJustification justify; + if ( style & wxALIGN_CENTER ) + justify = GTK_JUSTIFY_CENTER; + else if ( style & wxALIGN_RIGHT ) + justify = GTK_JUSTIFY_RIGHT; + else // wxALIGN_LEFT is 0 + justify = GTK_JUSTIFY_LEFT; + gtk_label_set_justify(GTK_LABEL(m_widget), justify); + + // GTK_JUSTIFY_LEFT is 0, RIGHT 1 and CENTER 2 + static const float labelAlignments[] = { 0.0, 1.0, 0.5 }; + gtk_misc_set_alignment(GTK_MISC(m_widget), labelAlignments[justify], 0.0); + + gtk_label_set_line_wrap( GTK_LABEL(m_widget), TRUE ); + + m_parent->DoAddChild( this ); + + PostCreation(size); + + return TRUE; +} + +wxString wxStaticText::GetLabel() const +{ + GtkLabel *label = GTK_LABEL(m_widget); + wxString str = wxString( label->label ); + return wxString(str); +} + +void wxStaticText::SetLabel( const wxString &label ) +{ + wxCHECK_RET( m_widget != NULL, wxT("invalid static text") ); + + GTKSetLabelForLabel(GTK_LABEL(m_widget), label); + + // adjust the label size to the new label unless disabled + if (!HasFlag(wxST_NO_AUTORESIZE)) + SetSize( GetBestSize() ); +} + +bool wxStaticText::SetFont( const wxFont &font ) +{ + bool ret = wxControl::SetFont(font); + + // adjust the label size to the new label unless disabled + if (!HasFlag(wxST_NO_AUTORESIZE)) + { + InvalidateBestSize(); + SetSize( GetBestSize() ); + } + return ret; +} + +void wxStaticText::DoSetSize(int x, int y, + int width, int height, + int sizeFlags ) +{ + wxControl::DoSetSize( x, y, width, height, sizeFlags ); +} + +wxSize wxStaticText::DoGetBestSize() const +{ + // Do not return any arbitrary default value... + wxASSERT_MSG( m_widget, wxT("wxStaticText::DoGetBestSize called before creation") ); + + // This resets the internal GTK1 size calculation, which + // otherwise would be cashed (incorrectly) + gtk_label_set_pattern( GTK_LABEL(m_widget), NULL ); + + // GetBestSize is supposed to return unwrapped size + gtk_label_set_line_wrap( GTK_LABEL(m_widget), FALSE ); + + GtkRequisition req; + req.width = -1; + req.height = -1; + (* GTK_WIDGET_CLASS( GTK_OBJECT_GET_CLASS(m_widget) )->size_request ) + (m_widget, &req ); + + gtk_label_set_line_wrap( GTK_LABEL(m_widget), TRUE ); + + return wxSize (req.width, req.height); +} + +bool wxStaticText::SetForegroundColour(const wxColour& colour) +{ + // First, we call the base class member + wxControl::SetForegroundColour(colour); + // Then, to force the color change, we set the label with the current label + SetLabel(GetLabel()); + return true; +} + +// These functions are not used as GTK supports ellipsization natively and we +// never call the base class UpdateText() which uses them. +// +// Note that, unfortunately, we still need to define them because they still +// exist, as pure virtuals, in the base class even in wxGTK to allow +// wxGenericStaticText to override them. + +wxString wxStaticText::WXGetVisibleLabel() const +{ + wxFAIL_MSG(wxS("Unreachable")); + + return wxString(); +} + +void wxStaticText::WXSetVisibleLabel(const wxString& WXUNUSED(str)) +{ + wxFAIL_MSG(wxS("Unreachable")); +} + +// static +wxVisualAttributes +wxStaticText::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant)) +{ + return GetDefaultAttributesFromGTKWidget(gtk_label_new); +} + +#endif // wxUSE_STATTEXT diff --git a/pool/shard001/C++/0018681_resource_variable_ops.cc b/pool/shard001/C++/0018681_resource_variable_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e28291070c138c39d270444f33a3d16d5b16aa5 --- /dev/null +++ b/pool/shard001/C++/0018681_resource_variable_ops.cc @@ -0,0 +1,166 @@ +// Copyright 2016 The TensorFlow Authors. 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. +// ============================================================================ + +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/shape_inference.h" + +namespace tensorflow { + +REGISTER_OP("VarHandleOp") + .Attr("container: string = ''") + .Attr("shared_name: string = ''") + .Attr("dtype: type") + .Attr("shape: shape") + .Output("resource: resource") + .SetIsStateful() + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->Scalar()); + DataType t; + c->GetAttr("dtype", &t); + c->set_output_handle_dtype(0, t); + TensorShapeProto p; + c->GetAttr("shape", &p); + shape_inference::ShapeHandle s; + TF_RETURN_IF_ERROR(c->MakeShapeFromShapeProto(p, &s)); + c->set_output_handle_shape(0, s); + return Status::OK(); + }) + .Doc(R"( +Creates a handle to a Variable resource. + +container: the container this variable is placed in. +shared_name: the name by which this variable is referred to. +dtype: the type of this variable. Must agree with the dtypes + of all ops using this variable. +shape: The (possibly partially specified) shape of this variable. +)"); + +Status CreateAssignShapeFn(shape_inference::InferenceContext* c) { + DataType handle_dtype = c->input_handle_dtype(0); + DataType value_dtype; + c->GetAttr("dtype", &value_dtype); + if (handle_dtype != value_dtype) { + return errors::InvalidArgument( + "Trying to initialize handle for variable with wrong dtype. " + "Expected ", + handle_dtype, " got ", value_dtype); + } + shape_inference::ShapeHandle s = c->input_handle_shape(0); + shape_inference::ShapeHandle value_shape = c->input(1); + shape_inference::ShapeHandle unused; + TF_RETURN_IF_ERROR(c->Merge(s, value_shape, &unused)); + return Status::OK(); +} + +REGISTER_OP("CreateVariableOp") + .Input("resource: resource") + .Input("value: dtype") + .Attr("dtype: type") + .SetShapeFn(CreateAssignShapeFn) + .Doc(R"( +Creates a variable resource. + +resource: handle to the resource in which to store the variable. +value: the value to set the new tensor to use. +dtype: the dtype of the value. +)"); + +REGISTER_OP("ReadVariableOp") + .Input("resource: resource") + .Output("value: dtype") + .Attr("dtype: type") + .SetShapeFn([](shape_inference::InferenceContext* c) { + DataType handle_dtype = c->input_handle_dtype(0); + DataType value_dtype; + c->GetAttr("dtype", &value_dtype); + if (handle_dtype != value_dtype) { + return errors::InvalidArgument( + "Trying to read variable with wrong dtype. " + "Expected ", + handle_dtype, " got ", value_dtype); + } + c->set_output(0, c->input_handle_shape(0)); + return Status::OK(); + }) + .Doc(R"( +Reads the value of a variable. + +The tensor returned by this operation is immutable. + +The value returned by this operation is guaranteed to be influenced by all the +writes on which this operation depends directly or indirectly, and to not be +influenced by any of the writes which depend directly or indirectly on this +operation. + +resource: handle to the resource in which to store the variable. +dtype: the dtype of the value. +)"); + +REGISTER_OP("AssignVariableOp") + .Input("resource: resource") + .Input("value: dtype") + .Attr("dtype: type") + .SetShapeFn(CreateAssignShapeFn) + .Doc(R"( +Assigns a new value to a variable. + +Any ReadVariableOp with a control dependency on this op is guaranteed to return +this value or a subsequent newer value of the variable. + +resource: handle to the resource in which to store the variable. +value: the value to set the new tensor to use. +dtype: the dtype of the value. +)"); + +REGISTER_OP("AssignAddVariableOp") + .Input("resource: resource") + .Input("value: dtype") + .Output("new_value: dtype") + .Attr("dtype: type") + .SetShapeFn([](shape_inference::InferenceContext* c) { + DataType handle_dtype = c->input_handle_dtype(0); + DataType value_dtype; + c->GetAttr("dtype", &value_dtype); + if (handle_dtype != value_dtype) { + return errors::InvalidArgument( + "Trying to initialize handle for variable with wrong dtype. " + "Expected ", + handle_dtype, " got ", value_dtype); + } + shape_inference::ShapeHandle s = c->input_handle_shape(0); + shape_inference::ShapeHandle value_shape = c->input(1); + shape_inference::ShapeHandle unused; + TF_RETURN_IF_ERROR(c->Merge(s, value_shape, &unused)); + c->set_output(0, value_shape); + return Status::OK(); + }) + .Doc(R"( +Adds a value to the current value of a variable. + +Any ReadVariableOp which depends directly or indirectly on this assign is +guaranteed to see the incremented value or a subsequent newer one. + +Outputs the incremented value, which can be used to totally order the +increments to this variable. + +resource: handle to the resource in which to store the variable. +value: the value by which the variable will be incremented. +new_value: the new value of the variable. +dtype: the dtype of the value. +)"); + +} // namespace tensorflow diff --git a/pool/shard001/C++/0018690_CTSSAProblem.cpp b/pool/shard001/C++/0018690_CTSSAProblem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe58a798f314efa2f65bb5a88bdef0448951aca5 --- /dev/null +++ b/pool/shard001/C++/0018690_CTSSAProblem.cpp @@ -0,0 +1,268 @@ +// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the +// University of Virginia, University of Heidelberg, and University +// of Connecticut School of Medicine. +// All rights reserved. + +// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual +// Properties, Inc., University of Heidelberg, and University of +// of Connecticut School of Medicine. +// All rights reserved. + +// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual +// Properties, Inc., University of Heidelberg, and The University +// of Manchester. +// All rights reserved. + +// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual +// Properties, Inc., EML Research, gGmbH, University of Heidelberg, +// and The University of Manchester. +// All rights reserved. + +// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual +// Properties, Inc. and EML Research, gGmbH. +// All rights reserved. + +/** + * CTSSAProblem class. + * This class describes the time scale separation analysis problem, i.e., it allows to specify + * for example initial conditions and number of steps. + * + */ + +#include +#include +#include + +#include "copasi/copasi.h" +#include "CTSSAProblem.h" +#include "CTSSATask.h" +#include "copasi/model/CModel.h" +//#include "copasi/model/CState.h" +#include "copasi/CopasiDataModel/CDataModel.h" +#include "copasi/core/CRootContainer.h" + +/** + * Default constructor. + */ +CTSSAProblem::CTSSAProblem(const CDataContainer * pParent): + CCopasiProblem(CTaskEnum::Task::timeCourse, pParent), + mpDuration(NULL), + mpStepSize(NULL), + mpStepNumber(NULL), + mpTimeSeriesRequested(NULL), + mpOutputStartTime(NULL), + mStepNumberSetLast(true) +{ + initializeParameter(); + initObjects(); + CONSTRUCTOR_TRACE; +} + +/** + * Copy constructor. + * @param "const CTSSAProblem &" src + */ +CTSSAProblem::CTSSAProblem(const CTSSAProblem & src, + const CDataContainer * pParent): + CCopasiProblem(src, pParent), + mpDuration(NULL), + mpStepSize(NULL), + mpStepNumber(NULL), + mpTimeSeriesRequested(NULL), + mpOutputStartTime(NULL), + mStepNumberSetLast(src.mStepNumberSetLast) +{ + initializeParameter(); + initObjects(); + CONSTRUCTOR_TRACE; +} + +/** + * Destructor. + */ +CTSSAProblem::~CTSSAProblem() +{DESTRUCTOR_TRACE;} + +void CTSSAProblem::initializeParameter() +{ + mpStepNumber = assertParameter("StepNumber", CCopasiParameter::Type::UINT, (unsigned C_INT32) 100); + mpStepSize = assertParameter("StepSize", CCopasiParameter::Type::DOUBLE, (C_FLOAT64) 0.01); + mpDuration = assertParameter("Duration", CCopasiParameter::Type::DOUBLE, (C_FLOAT64) 1.0); + mpTimeSeriesRequested = assertParameter("TimeSeriesRequested", CCopasiParameter::Type::BOOL, (bool) true); + mpOutputStartTime = assertParameter("OutputStartTime", CCopasiParameter::Type::DOUBLE, (C_FLOAT64) 0.0); +} + +bool CTSSAProblem::elevateChildren() +{ + // If we have an old COPASI file "Duration" is not set + // but we can fix that. + if (*mpDuration == 1.0) // the default + setDuration(*mpStepSize * (C_FLOAT64) *mpStepNumber); + + removeParameter("Deuflhard Tolerance"); + + return true; +} + +void CTSSAProblem::initObjects() +{} + +/** + * Set the number of time steps the trajectory method should integrate. + * @param "const unsigned C_INT32 &" stepNumber + */ +void CTSSAProblem::setStepNumber(const unsigned C_INT32 & stepNumber) +{ + *mpStepNumber = stepNumber; + mStepNumberSetLast = true; + sync(); + + return; +} + +/** + * Retrieve the number of time steps the trajectory method should integrate. + * @return "const unsigned C_INT32 &" stepNumber + */ +const unsigned C_INT32 & CTSSAProblem::getStepNumber() const +{return *mpStepNumber;} + +/** + * Set the size a integration step the trajectory method should do. + * @param "const C_FLOAT64 &" stepSize + */ +void CTSSAProblem::setStepSize(const C_FLOAT64 & stepSize) +{ + *mpStepSize = stepSize; + mStepNumberSetLast = false; + sync(); + + return; +} + +/** + * Retrieve the size a integration step the trajectory method should do. + * @return "const C_FLOAT64 &" stepSize + */ +const C_FLOAT64 & CTSSAProblem::getStepSize() const +{return *mpStepSize;} + +/** + * Set the end time. + * @param "const C_FLOAT64 &" duration + * @parem bool success + */ +void CTSSAProblem::setDuration(const C_FLOAT64 & duration) +{ + *mpDuration = duration; + sync(); + + return; +} + +/** + * Retrieve the end time. + * @return "const C_FLOAT64 &" duration + */ +const C_FLOAT64 & CTSSAProblem::getDuration() const +{return *mpDuration;} + +void CTSSAProblem::setOutputStartTime(const C_FLOAT64 & startTime) +{ + *mpOutputStartTime = startTime; +} + +const C_FLOAT64 & CTSSAProblem::getOutputStartTime() const +{return *mpOutputStartTime;} + +void CTSSAProblem::setTimeSeriesRequested(bool flag) +{ + *mpTimeSeriesRequested = flag; +} + +bool CTSSAProblem::timeSeriesRequested() const +{return *mpTimeSeriesRequested;} + +/** + * This function synchronizes step size and number + */ +bool CTSSAProblem::sync() +{ + bool success = true; + + C_FLOAT64 Tmp = *mpDuration; + C_FLOAT64 StepSize = *mpStepSize; + C_FLOAT64 StepNumber = (C_FLOAT64) * mpStepNumber; + + if (mStepNumberSetLast) + { + StepSize = Tmp / (C_FLOAT64) * mpStepNumber; + + /* Assure that the step size is not to small for machine accuracy */ + if (fabs(StepSize) < 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration)) + { + CCopasiMessage(CCopasiMessage::WARNING, + MCTSSAProblem + 3, StepSize); + + StepSize = 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration); + /* Assure that the step size has the appropriate sign. */ + StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize); + StepNumber = fabs(ceil(Tmp / StepSize)); + } + } + else + { + if (fabs(StepSize) < 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration)) + { + CCopasiMessage(CCopasiMessage::WARNING, + MCTSSAProblem + 3, StepSize); + + StepSize = 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration); + + /* Assure that the step size has the appropriate sign. */ + StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize); + } + + StepNumber = fabs(ceil(Tmp / StepSize)); + + /* Protect against overflow */ + if ((C_FLOAT64) ULONG_MAX < StepNumber) + { + CCopasiMessage(CCopasiMessage::WARNING, + MCTSSAProblem + 2, StepNumber); + + StepNumber = (C_FLOAT64) ULONG_MAX; + StepSize = Tmp / StepNumber; + + success = false; + } + + /* Assure that the step size has the appropriate sign. */ + StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize); + } + + *mpStepSize = StepSize; + *mpStepNumber = (unsigned C_INT32) StepNumber; + + if (!success) throw 1; + + return success; +} + +void CTSSAProblem::printResult(std::ostream * ostream) const +{ + std::ostream & os = *ostream; + + const CDataModel* pDataModel = getObjectDataModel(); + assert(pDataModel != NULL); + const CCopasiTask* mpTask = + dynamic_cast(&const_cast(pDataModel)->getTaskList()->operator[]("Time Scale Separation Analysis")); + + if (!mpTask) return; + + const CCopasiMethod* mpMethod = mpTask->getMethod(); + + this->print(&os); + + mpMethod->printResult(&os); +} diff --git a/pool/shard001/C++/0018692_ComputerProfile.cpp b/pool/shard001/C++/0018692_ComputerProfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd4fd801dcdfb29f0ff0ba534d4c304126f31e99 --- /dev/null +++ b/pool/shard001/C++/0018692_ComputerProfile.cpp @@ -0,0 +1,198 @@ +/* +Copyright_License { + + Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/ + Copyright (C) 2000-2016 The Top Hat Soaring Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "ComputerProfile.hpp" +#include "AirspaceConfig.hpp" +#include "TaskProfile.hpp" +#include "TrackingProfile.hpp" +#include "ProfileKeys.hpp" +#include "ContestProfile.hpp" +#include "Map.hpp" +#include "Computer/Settings.hpp" + +namespace Profile { + static void Load(const ProfileMap &map, WindSettings &settings); + static void Load(const ProfileMap &map, PolarSettings &settings); + static void Load(const ProfileMap &map, LoggerSettings &settings); + static void Load(const ProfileMap &map, TeamCodeSettings &settings); + static void Load(const ProfileMap &map, FilePickAndDownloadSettings &settings); + static void Load(const ProfileMap &map, VoiceSettings &settings); + static void Load(const ProfileMap &map, PlacesOfInterestSettings &settings); + static void Load(const ProfileMap &map, FeaturesSettings &settings); + static void Load(const ProfileMap &map, CirclingSettings &settings); + static void Load(const ProfileMap &map, WaveSettings &settings); +}; + +void +Profile::Load(const ProfileMap &map, WindSettings &settings) +{ + unsigned user_wind_source = (unsigned)settings.GetUserWindSource(); + if (map.Get(ProfileKeys::UserWindSource, user_wind_source)) + settings.SetUserWindSource((UserWindSource)user_wind_source); +} + +void +Profile::Load(const ProfileMap &map, PolarSettings &settings) +{ + fixed degradation; + if (map.Get(ProfileKeys::PolarDegradation, degradation) && + degradation >= fixed(0.5) && degradation <= fixed(1)) + settings.SetDegradationFactor(degradation); + + map.Get(ProfileKeys::AutoBugs, settings.auto_bugs); +} + +void +Profile::Load(const ProfileMap &map, LoggerSettings &settings) +{ + map.Get(ProfileKeys::LoggerTimeStepCruise, settings.time_step_cruise); + map.Get(ProfileKeys::LoggerTimeStepCircling, settings.time_step_circling); + + // auto_logger is hard coded to default (ON) + map.Get(ProfileKeys::LoggerID, settings.logger_id); + map.Get(ProfileKeys::PilotName, settings.pilot_name); + map.Get(ProfileKeys::EnableFlightLogger, settings.enable_flight_logger); + map.Get(ProfileKeys::EnableNMEALogger, settings.enable_nmea_logger); +} + +void +Profile::Load(const ProfileMap &map, TeamCodeSettings &settings) +{ + map.Get(ProfileKeys::TeamcodeRefWaypoint, settings.team_code_reference_waypoint); +} + +void +Profile::Load(const ProfileMap &map, FilePickAndDownloadSettings &settings) +{ + map.Get(ProfileKeys::FilePickAndDownloadAreaFilter, settings.area_filter); + map.Get(ProfileKeys::FilePickAndDownloadSubAreaFilter, settings.subarea_filter); +} + +void +Profile::Load(const ProfileMap &map, VoiceSettings &settings) +{ + map.Get(ProfileKeys::VoiceClimbRate, settings.voice_climb_rate_enabled); + map.Get(ProfileKeys::VoiceTerrain, settings.voice_terrain_enabled); + map.Get(ProfileKeys::VoiceWaypointDistance, + settings.voice_waypoint_distance_enabled); + map.Get(ProfileKeys::VoiceTaskAltitudeDifference, + settings.voice_task_altitude_difference_enabled); + map.Get(ProfileKeys::VoiceMacCready, settings.voice_mac_cready_enabled); + map.Get(ProfileKeys::VoiceNewWaypoint, settings.voice_new_waypoint_enabled); + map.Get(ProfileKeys::VoiceInSector, settings.voice_in_sector_enabled); + map.Get(ProfileKeys::VoiceAirspace, settings.voice_airspace_enabled); +} + +void +Profile::Load(const ProfileMap &map, PlacesOfInterestSettings &settings) +{ + map.Get(ProfileKeys::HomeWaypoint, settings.home_waypoint); + settings.home_location_available = + map.GetGeoPoint(ProfileKeys::HomeLocation, settings.home_location); + map.Get(ProfileKeys::HomeElevationAvailable, settings.home_elevation_available); + if (settings.home_elevation_available) + map.Get(ProfileKeys::HomeElevation, settings.home_elevation); + + map.GetGeoPoint(ProfileKeys::ATCReference, settings.atc_reference); +} + +void +Profile::Load(const ProfileMap &map, FeaturesSettings &settings) +{ + // hard code to line for Top Hat + settings.final_glide_terrain = FeaturesSettings::FinalGlideTerrain::LINE; + //map.GetEnum(ProfileKeys::FinalGlideTerrain, settings.final_glide_terrain); + map.Get(ProfileKeys::BlockSTF, settings.block_stf_enabled); + map.Get(ProfileKeys::EnableNavBaroAltitude, settings.nav_baro_altitude_enabled); +} + +void +Profile::Load(const ProfileMap &map, CirclingSettings &settings) +{ + map.Get(ProfileKeys::EnableExternalTriggerCruise, + settings.external_trigger_cruise_enabled); + fixed min_turn_rate; + if (map.Get(ProfileKeys::CirclingMinTurnRate, min_turn_rate)) + settings.min_turn_rate = settings.min_turn_rate.Degrees(min_turn_rate); + map.Get(ProfileKeys::CirclingCruiseClimbSwitch, settings.cruise_climb_switch); + map. Get(ProfileKeys::CirclingClimbCruiseSwitch, settings.climb_cruise_switch); +} + +void +Profile::Load(const ProfileMap &map, WaveSettings &settings) +{ + map.Get(ProfileKeys::WaveAssistant, settings.enabled); +} + +static bool +LoadUTCOffset(const ProfileMap &map, RoughTimeDelta &value_r) +{ + /* NOTE: Until 6.2.4 utc_offset was stored as a positive int in the + settings file (with negative offsets stored as "utc_offset + 24 * + 3600"). Later versions will create a new signed settings key. */ + + int value; + if (map.Get(ProfileKeys::UTCOffsetSigned, value)) { + } else if (map.Get(ProfileKeys::UTCOffset, value)) { + if (value > 12 * 3600) + value = (value % (24 * 3600)) - 24 * 3600; + } else + /* no profile value present */ + return false; + + if (value > 13 * 3600 || value < -13 * 3600) + /* illegal value */ + return false; + + value_r = RoughTimeDelta::FromSeconds(value); + return true; +} + +void +Profile::Load(const ProfileMap &map, ComputerSettings &settings) +{ + Load(map, settings.wind); + Load(map, settings.polar); + Load(map, settings.team_code); + Load(map, settings.file_pick_and_download); + Load(map, settings.voice); + Load(map, settings.poi); + Load(map, settings.features); + Load(map, settings.airspace); + Load(map, settings.circling); + Load(map, settings.wave); + + map.GetEnum(ProfileKeys::AverEffTime, settings.average_eff_time); + + map.Get(ProfileKeys::SetSystemTimeFromGPS, settings.set_system_time_from_gps); + + LoadUTCOffset(map, settings.utc_offset); + + Load(map, settings.task); + Load(map, settings.contest); + Load(map, settings.logger); + +#ifdef HAVE_TRACKING + Load(map, settings.tracking); +#endif +} diff --git a/pool/shard001/C++/0018701_silvermoon_city.cpp b/pool/shard001/C++/0018701_silvermoon_city.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8e9a9ae49a9d15205d93318da04f355d5d56011 --- /dev/null +++ b/pool/shard001/C++/0018701_silvermoon_city.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2008-2012 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: Silvermoon_City +SD%Complete: 100 +SDComment: Quest support: 9685 +SDCategory: Silvermoon City +EndScriptData */ + +/* ContentData +npc_blood_knight_stillblade +EndContentData */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "Player.h" +#include "SpellInfo.h" + +/*####### +# npc_blood_knight_stillblade +#######*/ +enum eStillbladeData +{ + SAY_HEAL = 0, + + QUEST_REDEEMING_THE_DEAD = 9685, + SPELL_SHIMMERING_VESSEL = 31225, + SPELL_REVIVE_SELF = 32343, +}; + +class npc_blood_knight_stillblade : public CreatureScript +{ +public: + npc_blood_knight_stillblade() : CreatureScript("npc_blood_knight_stillblade") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new npc_blood_knight_stillbladeAI (creature); + } + + struct npc_blood_knight_stillbladeAI : public ScriptedAI + { + npc_blood_knight_stillbladeAI(Creature* creature) : ScriptedAI(creature) {} + + uint32 lifeTimer; + bool spellHit; + + void Reset() + { + lifeTimer = 120000; + me->SetStandState(UNIT_STAND_STATE_DEAD); + me->SetUInt32Value(UNIT_FIELD_BYTES_1, 7); // lay down + spellHit = false; + } + + void EnterCombat(Unit* /*who*/) + { + } + + void MoveInLineOfSight(Unit* /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + if (me->IsStandState()) + { + if (lifeTimer <= diff) + me->AI()->EnterEvadeMode(); + else + lifeTimer -= diff; + } + } + + void SpellHit(Unit* Hitter, const SpellInfo* Spellkind) + { + if ((Spellkind->Id == SPELL_SHIMMERING_VESSEL) && !spellHit && + (Hitter->GetTypeId() == TYPEID_PLAYER) && (CAST_PLR(Hitter)->IsActiveQuest(QUEST_REDEEMING_THE_DEAD))) + { + CAST_PLR(Hitter)->AreaExploredOrEventHappens(QUEST_REDEEMING_THE_DEAD); + DoCast(me, SPELL_REVIVE_SELF); + me->SetStandState(UNIT_STAND_STATE_STAND); + me->SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0); + //me->RemoveAllAuras(); + Talk(SAY_HEAL); + spellHit = true; + } + } + }; +}; + +void AddSC_silvermoon_city() +{ + new npc_blood_knight_stillblade(); +} diff --git a/pool/shard001/C++/0018702_seq_packet_protocol.cpp b/pool/shard001/C++/0018702_seq_packet_protocol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d1fc388d7db481a3738cba8276c7deb1f639e17 --- /dev/null +++ b/pool/shard001/C++/0018702_seq_packet_protocol.cpp @@ -0,0 +1,198 @@ +// +// generic/seq_packet_protocol.cpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// 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) +// + +// Disable autolinking for unit tests. +#if !defined(BOOST_ALL_NO_LIB) +#define BOOST_ALL_NO_LIB 1 +#endif // !defined(BOOST_ALL_NO_LIB) + +// Test that header file is self-contained. +#include "asio/generic/seq_packet_protocol.hpp" + +#include +#include "asio/io_service.hpp" +#include "../unit_test.hpp" + +#if defined(__cplusplus_cli) || defined(__cplusplus_winrt) +# define generic cpp_generic +#endif + +//------------------------------------------------------------------------------ + +// generic_seq_packet_protocol_socket_compile test +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// The following test checks that all public member functions on the class +// generic::seq_packet_socket::socket compile and link correctly. Runtime +// failures are ignored. + +namespace generic_seq_packet_protocol_socket_compile { + +void connect_handler(const asio::error_code&) +{ +} + +void send_handler(const asio::error_code&, std::size_t) +{ +} + +void receive_handler(const asio::error_code&, std::size_t) +{ +} + +void test() +{ + using namespace asio; + namespace generic = asio::generic; + typedef generic::seq_packet_protocol spp; + + const int af_inet = ASIO_OS_DEF(AF_INET); + const int sock_seqpacket = ASIO_OS_DEF(SOCK_SEQPACKET); + + try + { + io_service ios; + char mutable_char_buffer[128] = ""; + const char const_char_buffer[128] = ""; + const socket_base::message_flags in_flags = 0; + socket_base::message_flags out_flags = 0; + socket_base::send_buffer_size socket_option; + socket_base::bytes_readable io_control_command; + asio::error_code ec; + + // basic_seq_packet_socket constructors. + + spp::socket socket1(ios); + spp::socket socket2(ios, spp(af_inet, 0)); + spp::socket socket3(ios, spp::endpoint()); +#if !defined(ASIO_WINDOWS_RUNTIME) + int native_socket1 = ::socket(af_inet, sock_seqpacket, 0); + spp::socket socket4(ios, spp(af_inet, 0), native_socket1); +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#if defined(ASIO_HAS_MOVE) + spp::socket socket5(std::move(socket4)); +#endif // defined(ASIO_HAS_MOVE) + + // basic_seq_packet_socket operators. + +#if defined(ASIO_HAS_MOVE) + socket1 = spp::socket(ios); + socket1 = std::move(socket2); +#endif // defined(ASIO_HAS_MOVE) + + // basic_io_object functions. + + io_service& ios_ref = socket1.get_io_service(); + (void)ios_ref; + + // basic_socket functions. + + spp::socket::lowest_layer_type& lowest_layer = socket1.lowest_layer(); + (void)lowest_layer; + + socket1.open(spp(af_inet, 0)); + socket1.open(spp(af_inet, 0), ec); + +#if !defined(ASIO_WINDOWS_RUNTIME) + int native_socket2 = ::socket(af_inet, sock_seqpacket, 0); + socket1.assign(spp(af_inet, 0), native_socket2); + int native_socket3 = ::socket(af_inet, sock_seqpacket, 0); + socket1.assign(spp(af_inet, 0), native_socket3, ec); +#endif // !defined(ASIO_WINDOWS_RUNTIME) + + bool is_open = socket1.is_open(); + (void)is_open; + + socket1.close(); + socket1.close(ec); + + spp::socket::native_handle_type native_socket4 = socket1.native_handle(); + (void)native_socket4; + + socket1.cancel(); + socket1.cancel(ec); + + bool at_mark1 = socket1.at_mark(); + (void)at_mark1; + bool at_mark2 = socket1.at_mark(ec); + (void)at_mark2; + + std::size_t available1 = socket1.available(); + (void)available1; + std::size_t available2 = socket1.available(ec); + (void)available2; + + socket1.bind(spp::endpoint()); + socket1.bind(spp::endpoint(), ec); + + socket1.connect(spp::endpoint()); + socket1.connect(spp::endpoint(), ec); + + socket1.async_connect(spp::endpoint(), connect_handler); + + socket1.set_option(socket_option); + socket1.set_option(socket_option, ec); + + socket1.get_option(socket_option); + socket1.get_option(socket_option, ec); + + socket1.io_control(io_control_command); + socket1.io_control(io_control_command, ec); + + spp::endpoint endpoint1 = socket1.local_endpoint(); + spp::endpoint endpoint2 = socket1.local_endpoint(ec); + + spp::endpoint endpoint3 = socket1.remote_endpoint(); + spp::endpoint endpoint4 = socket1.remote_endpoint(ec); + + socket1.shutdown(socket_base::shutdown_both); + socket1.shutdown(socket_base::shutdown_both, ec); + + // basic_seq_packet_socket functions. + + socket1.send(buffer(mutable_char_buffer), in_flags); + socket1.send(buffer(const_char_buffer), in_flags); + socket1.send(null_buffers(), in_flags); + socket1.send(buffer(mutable_char_buffer), in_flags, ec); + socket1.send(buffer(const_char_buffer), in_flags, ec); + socket1.send(null_buffers(), in_flags, ec); + + socket1.async_send(buffer(mutable_char_buffer), in_flags, send_handler); + socket1.async_send(buffer(const_char_buffer), in_flags, send_handler); + socket1.async_send(null_buffers(), in_flags, send_handler); + + socket1.receive(buffer(mutable_char_buffer), out_flags); + socket1.receive(null_buffers(), out_flags); + socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags); + socket1.receive(null_buffers(), in_flags, out_flags); + socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags, ec); + socket1.receive(null_buffers(), in_flags, out_flags, ec); + + socket1.async_receive(buffer(mutable_char_buffer), out_flags, + receive_handler); + socket1.async_receive(null_buffers(), out_flags, receive_handler); + socket1.async_receive(buffer(mutable_char_buffer), in_flags, + out_flags, receive_handler); + socket1.async_receive(null_buffers(), in_flags, out_flags, receive_handler); + } + catch (std::exception&) + { + } +} + +} // namespace generic_seq_packet_protocol_socket_compile + +//------------------------------------------------------------------------------ + +ASIO_TEST_SUITE +( + "generic/seq_packet_protocol", + ASIO_TEST_CASE(generic_seq_packet_protocol_socket_compile::test) +) diff --git a/pool/shard001/C++/0018706_Nv3DVUtils.cpp b/pool/shard001/C++/0018706_Nv3DVUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecf33cd20ddcecff60ba267a74141b7f9887de1a --- /dev/null +++ b/pool/shard001/C++/0018706_Nv3DVUtils.cpp @@ -0,0 +1,136 @@ +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsIServiceManager.h" +#include "nsIConsoleService.h" +#include +#include "Nv3DVUtils.h" +#include "mozilla/Util.h" + +DEFINE_GUID(CLSID_NV3DVStreaming, +0xf7747266, 0x777d, 0x4f61, 0xa1, 0x75, 0xdd, 0x5a, 0xdf, 0x1e, 0x37, 0xdf); + +DEFINE_GUID(IID_INV3DVStreaming, +0xf98f9bb2, 0xb914, 0x4d44, 0x98, 0xfa, 0x6e, 0x37, 0x85, 0x16, 0x98, 0x55); + +namespace mozilla { +namespace layers { + +/** + * Constructor and Destructor + */ +Nv3DVUtils::Nv3DVUtils() + : m3DVStreaming (NULL) +{ +} + +Nv3DVUtils::~Nv3DVUtils() +{ + UnInitialize(); +} + +/** + * Initializes the Nv3DVUtils object. + */ +void +Nv3DVUtils::Initialize() +{ + /* + * Detect if 3D Streaming object is already loaded. Do nothing in that case. + */ + if (m3DVStreaming) { + NS_WARNING("Nv3DVStreaming COM object already instantiated.\n"); + return; + } + + /* + * Create the COM object. If we fail at any stage, just return + */ + HRESULT hr = CoCreateInstance(CLSID_NV3DVStreaming, NULL, CLSCTX_INPROC_SERVER, IID_INV3DVStreaming, (void**)(getter_AddRefs(m3DVStreaming))); + if (FAILED(hr) || !m3DVStreaming) { + NS_WARNING("Nv3DVStreaming CoCreateInstance failed (disabled)."); + return; + } + + /* + * Initialize the object. Note that m3DVStreaming cannot be NULL at this point. + */ + bool bRetVal = m3DVStreaming->Nv3DVInitialize(); + + if (!bRetVal) { + NS_WARNING("Nv3DVStreaming Nv3DVInitialize failed!"); + return; + } +} + +/** + * Release resources used by the COM Object, and then release + * the COM Object (nsRefPtr gets released by setting to NULL) + * + */ +void +Nv3DVUtils::UnInitialize() +{ + if (m3DVStreaming) { + m3DVStreaming->Nv3DVRelease(); + } +} + +/** + * Sets the device info, along with any other initialization that is needed after device creation + * Pass the D3D9 device pointer is an IUnknown input argument. + */ +void +Nv3DVUtils::SetDeviceInfo(IUnknown *devUnknown) +{ + if (!devUnknown) { + NS_WARNING("D3D Device Pointer (IUnknown) is NULL.\n"); + return; + } + + if (!m3DVStreaming) { + return; + } + + bool rv = m3DVStreaming->Nv3DVSetDevice(devUnknown); + if (!rv) { + NS_WARNING("Nv3DVStreaming Nv3DVControl failed!"); + return; + } + + rv = m3DVStreaming->Nv3DVControl(NV_STEREO_MODE_RIGHT_LEFT, true, FIREFOX_3DV_APP_HANDLE); + NS_WARN_IF_FALSE(rv, "Nv3DVStreaming Nv3DVControl failed!"); +} + +/* + * Send Stereo Control Information. Used mainly to re-route + * calls from ImageLayerD3D9 to the 3DV COM object + */ +void +Nv3DVUtils::SendNv3DVControl(Nv_Stereo_Mode eStereoMode, bool bEnableStereo, DWORD dw3DVAppHandle) +{ + if (!m3DVStreaming) + return; + + DebugOnly rv = m3DVStreaming->Nv3DVControl(eStereoMode, bEnableStereo, dw3DVAppHandle); + NS_WARN_IF_FALSE(rv, "Nv3DVStreaming Nv3DVControl failed!"); +} + +/* + * Send Stereo Metadata. Used mainly to re-route calls + * from ImageLayerD3D9 to the 3DV COM object + */ +void +Nv3DVUtils::SendNv3DVMetaData(unsigned int dwWidth, unsigned int dwHeight, HANDLE hSrcLuma, HANDLE hDst) +{ + if (!m3DVStreaming) + return; + + DebugOnly rv = m3DVStreaming->Nv3DVMetaData((DWORD)dwWidth, (DWORD)dwHeight, hSrcLuma, hDst); + NS_WARN_IF_FALSE(rv, "Nv3DVStreaming Nv3DVMetaData failed!"); +} + +} /* namespace layers */ +} /* namespace mozilla */ diff --git a/pool/shard001/C++/0018707_PriceInfoTest.cpp b/pool/shard001/C++/0018707_PriceInfoTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7975fcda03eea6ffe810b226f09337467fa179bb --- /dev/null +++ b/pool/shard001/C++/0018707_PriceInfoTest.cpp @@ -0,0 +1,156 @@ +#include "gtest/gtest.h" +#include "PriceInfo.h" +#include "Logger/Logger.h" + +TEST (PriceInfoTest, DefaultConstructor) +{ + spark::PriceInfo info; + + EXPECT_FLOAT_EQ(0.0, info.pricePerHour()); + EXPECT_EQ(0, info.timeLimit()); + EXPECT_EQ(0, info.timeResolution()); + EXPECT_FALSE(info.isValid()); +} + + +TEST (PriceInfoTest, Constructor) +{ + spark::PriceInfo info(1.2, 120, 10); + + EXPECT_FLOAT_EQ(1.2, info.pricePerHour()); + EXPECT_EQ(120, info.timeLimit()); + EXPECT_EQ(10, info.timeResolution()); + EXPECT_TRUE(info.isValid()); +} + + +TEST (PriceInfoTest, NegativePriceIsInvalid) +{ + spark::PriceInfo info(-1.0, 120, 10); + EXPECT_FALSE(info.isValid()); +} + + +TEST (PriceInfoTest, NegativeLimitIsInvalid) +{ + spark::PriceInfo info(1.2, -120, 10); + EXPECT_FALSE(info.isValid()); +} + + +TEST (PriceInfoTest, NonPositiveResolutionIsInvalid) +{ + spark::PriceInfo info(1.2, 120, 0); + EXPECT_FALSE(info.isValid()); +} + + +TEST (PriceInfoTest, ToStringTest) +{ + spark::PriceInfo info(2.5, 300, 10); + std::string repr = info.toString(); + + EXPECT_EQ("2.5;300;10", repr); +} + + +TEST (PriceInfoTest, FromStringWithDefaultSeparator) +{ + const std::string str = "1.2;120;10"; + spark::PriceInfo price1 = spark::PriceInfo::fromString(str); + spark::PriceInfo price2 = spark::PriceInfo::fromString(str, ';'); + + EXPECT_TRUE(price1.isValid()); + EXPECT_TRUE(price2.isValid()); + EXPECT_FLOAT_EQ(1.2, price1.pricePerHour()); + EXPECT_FLOAT_EQ(1.2, price2.pricePerHour()); + EXPECT_EQ(120, price1.timeLimit()); + EXPECT_EQ(120, price2.timeLimit()); + EXPECT_EQ(10, price1.timeResolution()); + EXPECT_EQ(10, price2.timeResolution()); +} + + +TEST (PriceInfoTest, FromStringWithCustomSeparator) +{ + const std::string str = "1.2:0:10"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_TRUE(price.isValid()); + EXPECT_FLOAT_EQ(1.2, price.pricePerHour()); + EXPECT_EQ(0, price.timeLimit()); + EXPECT_EQ(10, price.timeResolution()); +} + + +TEST (PriceInfoTest, FromStringTooFewFields) +{ + const std::string str = "1.2:120"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + LOG_DEBUG(price.toString()); + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringTooManyFields) +{ + const std::string str = "1.2:120:10:20"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringPriceNotANumber) +{ + const std::string str = "asd:120:10"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringNegativePrice) +{ + const std::string str = "-1.0:120:10"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringLimitNotANumber) +{ + const std::string str = "1.2:asd:10"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringNegativeLimit) +{ + const std::string str = "1.2:-120:10"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringResolutionNotANumber) +{ + const std::string str = "1.2:120:10asd"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} + + +TEST (PriceInfoTest, FromStringResolutionNotPositive) +{ + const std::string str = "1.2:120:0"; + spark::PriceInfo price = spark::PriceInfo::fromString(str, ':'); + + EXPECT_FALSE(price.isValid()); +} diff --git a/pool/shard001/C++/0018708_polygonmesh_zonohedra.cpp b/pool/shard001/C++/0018708_polygonmesh_zonohedra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9524668073f736cceb8b37b59179a02457759eb0 --- /dev/null +++ b/pool/shard001/C++/0018708_polygonmesh_zonohedra.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** + * VCGLib o o * + * Visual and Computer Graphics Library o o * + * _ O _ * + * Copyright(C) 2004 \/)\/ * + * Visual Computing Lab /\/| * + * ISTI - Italian National Research Council | * + * \ * + * 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 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 (http://www.gnu.org/licenses/gpl.txt) * + * for more details. * + * * + ****************************************************************************/ + +#include +#include +#include +#include +#include + + + +class MyVertex; +class MyEdge; +class MyFace; + +struct MyUsedTypes: public vcg::UsedTypes::AsVertexType,vcg::Use::AsEdgeType,vcg::Use::AsFaceType>{}; + +class MyVertex : public vcg::Vertex< MyUsedTypes,vcg::vertex::Coord3f,vcg::vertex::BitFlags >{}; + +class MyEdge : public vcg::Edge< MyUsedTypes > {}; + +class MyFace : public vcg::Face< MyUsedTypes, + vcg::face::FFAdj, + vcg::face::VertexRef, + vcg::face::Normal3f, + vcg::face::BitFlags > {}; + +// the main mesh class +class MyMesh : public vcg::tri::TriMesh, std::vector > {}; + + + +// example 1: build a cube as a Zonohedron +void example1(){ + + vcg::tri::Zonohedron z; + z.addVector( 0,0,1 ); + z.addVector( 0,1,0 ); + z.addVector( 1,0,0 ); + + MyMesh m; + z.createMesh(m); // this will be a cube + + vcg::tri::UpdateTopology::FaceFace(m); // needed by exporter + + int savemask = vcg::tri::io::Mask::IOM_BITPOLYGONAL; + vcg::tri::io::ExporterOFF::Save(m,"cube.off",savemask); +} + + +// example2: reads input file, builds zonohedra as described there +void example2(){ + + FILE* f = fopen("input.txt","rt"); + if (!f) return; + + while (1) { + + // read mesh name + char meshFilename[1024], fullMeshFilename[1024]; + if (fscanf(f,"%s",meshFilename)!=1) break; + sprintf(fullMeshFilename,"%s.off",meshFilename); + + // build input vector + vcg::tri::Zonohedron z; + while (1) { + float a,b,c; + if (fscanf(f,"%f %f %f",&a, &b, &c)!=3) break; + z.addVector(a,b,c); + } + + printf("Building %s from %d vectors...\n",fullMeshFilename, z.vectors().size() ); + + MyMesh m; + z.createMesh(m); + + vcg::tri::UpdateTopology::FaceFace(m); // needed by exporter + + // normally, faces with more than 4sides are split into parallelograms + // this merges them (optional, try removing it!) + vcg::tri::PolygonSupport::MergeFlatFaces(m); + + int savemask = vcg::tri::io::Mask::IOM_BITPOLYGONAL; + vcg::tri::io::ExporterOFF::Save(m,fullMeshFilename,savemask); + } + +} + +int main(int argc, char *argv[]){ + example1(); + example2(); + return 0; +} diff --git a/pool/shard001/C++/0018719_plEAXEffects.cpp b/pool/shard001/C++/0018719_plEAXEffects.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51b470efe6306a997441fdc9553bb69de2cf83a3 --- /dev/null +++ b/pool/shard001/C++/0018719_plEAXEffects.cpp @@ -0,0 +1,201 @@ +/* This file is part of HSPlasma. + * + * HSPlasma 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. + * + * HSPlasma 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 HSPlasma. If not, see . + */ + +#include "plEAXEffects.h" + +/* plEAXSourceSoftSettings */ +void plEAXSourceSoftSettings::reset() +{ + fOcclusion = 0; + fOcclusionLFRatio = 0.25f; + fOcclusionRoomRatio = 1.5f; + fOcclusionDirectRatio = 1.0f; +} + +void plEAXSourceSoftSettings::read(hsStream* S) +{ + fOcclusion = S->readShort(); + fOcclusionLFRatio = S->readFloat(); + fOcclusionRoomRatio = S->readFloat(); + fOcclusionDirectRatio = S->readFloat(); +} + +void plEAXSourceSoftSettings::write(hsStream* S) +{ + S->writeShort(fOcclusion); + S->writeFloat(fOcclusionLFRatio); + S->writeFloat(fOcclusionRoomRatio); + S->writeFloat(fOcclusionDirectRatio); +} + +void plEAXSourceSoftSettings::prcWrite(pfPrcHelper* prc) +{ + prc->startTag("plEAXSourceSoftSettings"); + prc->writeParam("Occlusion", fOcclusion); + prc->writeParam("LFRatio", fOcclusionLFRatio); + prc->writeParam("RoomRatio", fOcclusionRoomRatio); + prc->writeParam("DirectRatio", fOcclusionDirectRatio); + prc->endTag(true); +} + +void plEAXSourceSoftSettings::prcParse(const pfPrcTag* tag) +{ + if (tag->getName() != "plEAXSourceSoftSettings") + throw pfPrcTagException(__FILE__, __LINE__, tag->getName()); + + fOcclusion = tag->getParam("Occlusion", "0").to_int(); + fOcclusionLFRatio = tag->getParam("LFRatio", "0").to_float(); + fOcclusionRoomRatio = tag->getParam("RoomRatio", "0").to_float(); + fOcclusionDirectRatio = tag->getParam("DirectRatio", "0").to_float(); +} + + +/* plEAXSourceSettings */ +void plEAXSourceSettings::enable(bool en) +{ + fEnabled = en; + if (!fEnabled) { + fRoom = -1; + fRoomHF = -1; + fRoomAuto = true; + fRoomHFAuto = true; + fOutsideVolHF = 0; + fAirAbsorptionFactor = 1.0f; + fRoomRolloffFactor = 0.0f; + fDopplerFactor = 0.0f; + fRolloffFactor = 0.0f; + fOcclusionSoftValue = 0.0f; + fSoftStarts.reset(); + fSoftEnds.reset(); + } +} + +void plEAXSourceSettings::read(hsStream* S) +{ + enable(S->readBool()); + if (fEnabled) { + fRoom = S->readShort(); + fRoomHF = S->readShort(); + fRoomAuto = S->readBool(); + fRoomHFAuto = S->readBool(); + fOutsideVolHF = S->readShort(); + fAirAbsorptionFactor = S->readFloat(); + fRoomRolloffFactor = S->readFloat(); + fDopplerFactor = S->readFloat(); + fRolloffFactor = S->readFloat(); + if (!S->getVer().isNewPlasma() || S->getVer().isUniversal()) { + fSoftStarts.read(S); + fSoftEnds.read(S); + fOcclusionSoftValue = S->readFloat(); + } else { + fOcclusionSoftValue = S->readFloat(); + fSoftStarts.read(S); + fSoftEnds.reset(); + } + } +} + +void plEAXSourceSettings::write(hsStream* S) +{ + S->writeBool(fEnabled); + if (fEnabled) { + S->writeShort(fRoom); + S->writeShort(fRoomHF); + S->writeBool(fRoomAuto); + S->writeBool(fRoomHFAuto); + S->writeShort(fOutsideVolHF); + S->writeFloat(fAirAbsorptionFactor); + S->writeFloat(fRoomRolloffFactor); + S->writeFloat(fDopplerFactor); + S->writeFloat(fRolloffFactor); + if (!S->getVer().isNewPlasma() || S->getVer().isUniversal()) { + fSoftStarts.write(S); + fSoftEnds.write(S); + S->writeFloat(fOcclusionSoftValue); + } else { + S->writeFloat(fOcclusionSoftValue); + fSoftStarts.write(S); + } + } +} + +void plEAXSourceSettings::prcWrite(pfPrcHelper* prc) +{ + prc->startTag("plEAXSourceSettings"); + if (fEnabled) { + prc->writeParam("Room", fRoom); + prc->writeParam("RoomHF", fRoomHF); + prc->writeParam("RoomAuto", fRoomAuto); + prc->writeParam("RoomHFAuto", fRoomHFAuto); + prc->writeParam("OutsideHF", fOutsideVolHF); + prc->endTag(); + prc->startTag("Effects"); + prc->writeParam("AirAbsorption", fAirAbsorptionFactor); + prc->writeParam("RoomRolloff", fRoomRolloffFactor); + prc->writeParam("Doppler", fDopplerFactor); + prc->writeParam("Rolloff", fRolloffFactor); + prc->writeParam("SoftOcclusion", fOcclusionSoftValue); + prc->endTag(true); + prc->writeSimpleTag("Starts"); + fSoftStarts.prcWrite(prc); + prc->closeTag(); + prc->writeSimpleTag("Ends"); + fSoftEnds.prcWrite(prc); + prc->closeTag(); + + prc->closeTag(); // plEAXSourceSettings + } else { + prc->writeParam("enabled", false); + prc->endTag(true); + } +} + +void plEAXSourceSettings::prcParse(const pfPrcTag* tag) +{ + if (tag->getName() != "plEAXSourceSettings") + throw pfPrcTagException(__FILE__, __LINE__, tag->getName()); + + fEnabled = tag->getParam("enabled", "true").to_bool(); + if (fEnabled) { + fRoom = tag->getParam("Room", "0").to_int(); + fRoomHF = tag->getParam("RoomHF", "0").to_int(); + fRoomAuto = tag->getParam("RoomAuto", "false").to_bool(); + fRoomHFAuto = tag->getParam("RoomHFAuto", "false").to_bool(); + fOutsideVolHF = tag->getParam("OutsideHF", "0").to_int(); + + const pfPrcTag* child = tag->getFirstChild(); + while (child) { + if (child->getName() == "Effects") { + fAirAbsorptionFactor = child->getParam("AirAbsorption", "0").to_float(); + fRoomRolloffFactor = child->getParam("RoomRolloff", "0").to_float(); + fDopplerFactor = child->getParam("Doppler", "0").to_float(); + fRolloffFactor = child->getParam("Rolloff", "0").to_float(); + fOcclusionSoftValue = tag->getParam("SoftOcclusion", "0").to_float(); + } else if (child->getName() == "Starts") { + if (tag->hasChildren()) + fSoftStarts.prcParse(child->getFirstChild()); + } else if (child->getName() == "Ends") { + if (tag->hasChildren()) + fSoftEnds.prcParse(child->getFirstChild()); + } else { + throw pfPrcTagException(__FILE__, __LINE__, child->getName()); + } + child = child->getNextSibling(); + } + } else { + enable(false); + } +} diff --git a/pool/shard001/C++/0018720_fake_auto_enrollment_client.cc b/pool/shard001/C++/0018720_fake_auto_enrollment_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba8aa2f99458bbec01eb68a0f39f18fb62d7e7fe --- /dev/null +++ b/pool/shard001/C++/0018720_fake_auto_enrollment_client.cc @@ -0,0 +1,81 @@ +// 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/ash/policy/enrollment/fake_auto_enrollment_client.h" + +#include "services/network/public/cpp/shared_url_loader_factory.h" + +namespace policy { + +FakeAutoEnrollmentClient::FactoryImpl::FactoryImpl( + const base::RepeatingCallback& + fake_client_created_callback) + : fake_client_created_callback_(fake_client_created_callback) {} + +FakeAutoEnrollmentClient::FactoryImpl::~FactoryImpl() {} + +std::unique_ptr +FakeAutoEnrollmentClient::FactoryImpl::CreateForFRE( + const AutoEnrollmentClient::ProgressCallback& progress_callback, + DeviceManagementService* device_management_service, + PrefService* local_state, + scoped_refptr url_loader_factory, + const std::string& server_backed_state_key, + int power_initial, + int power_limit) { + std::unique_ptr fake_client = + std::make_unique(progress_callback); + fake_client_created_callback_.Run(fake_client.get()); + return fake_client; +} + +std::unique_ptr +FakeAutoEnrollmentClient::FactoryImpl::CreateForInitialEnrollment( + const AutoEnrollmentClient::ProgressCallback& progress_callback, + DeviceManagementService* device_management_service, + PrefService* local_state, + scoped_refptr url_loader_factory, + const std::string& device_serial_number, + const std::string& device_brand_code, + int power_initial, + int power_limit, + PrivateMembershipRlweClient::Factory* psm_rlwe_client_factory, + PsmRlweIdProvider* psm_rlwe_id_provider) { + std::unique_ptr fake_client = + std::make_unique(progress_callback); + fake_client_created_callback_.Run(fake_client.get()); + return fake_client; +} + +FakeAutoEnrollmentClient::FakeAutoEnrollmentClient( + const ProgressCallback& progress_callback) + : progress_callback_(progress_callback), + state_(AUTO_ENROLLMENT_STATE_IDLE) {} + +FakeAutoEnrollmentClient::~FakeAutoEnrollmentClient() {} + +void FakeAutoEnrollmentClient::Start() { + SetState(AUTO_ENROLLMENT_STATE_PENDING); +} + +void FakeAutoEnrollmentClient::Retry() {} + +void FakeAutoEnrollmentClient::CancelAndDeleteSoon() { + delete this; +} + +std::string FakeAutoEnrollmentClient::device_id() const { + return std::string(); +} + +AutoEnrollmentState FakeAutoEnrollmentClient::state() const { + return state_; +} + +void FakeAutoEnrollmentClient::SetState(AutoEnrollmentState target_state) { + state_ = target_state; + progress_callback_.Run(state_); +} + +} // namespace policy diff --git a/pool/shard001/C++/0018721_NamespaceStack.cpp b/pool/shard001/C++/0018721_NamespaceStack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a8b7732a384a22e24b0069dc585f688f1218017 --- /dev/null +++ b/pool/shard001/C++/0018721_NamespaceStack.cpp @@ -0,0 +1,71 @@ +/* ========================================================================= + * This file is part of xml.lite-c++ + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * xml.lite-c++ 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. + * + * 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, + * see . + * + */ + +#include "xml/lite/NamespaceStack.h" + +void xml::lite::NamespaceStack::push() +{ + mRefStack.push(0); +} + +void xml::lite::NamespaceStack::pop() +{ + int numToRemove = mRefStack.top(); + + for (int i = 0; i < numToRemove; i++) + { + // Remove this namespace mapping + mMappingStack.pop_back(); + } + + mRefStack.pop(); +} + + +void xml::lite::NamespaceStack::newMapping(const std::string& prefix, + const std::string& uri) +{ + ++mRefStack.top(); + mMappingStack.push_back(xml::lite::NamespaceEntity(prefix, uri)); +} + +std::string +xml::lite::NamespaceStack::getMapping(const std::string& prefix) const +{ + for (int i = (int)mMappingStack.size() - 1; i >= 0; --i) + { + if (mMappingStack[i].first == prefix) + { + return mMappingStack[i].second; + } + } + return std::string(""); +} + +void xml::lite::NamespaceStack:: +getAllPrefixes(std::vector& allPrefixes) const +{ + for (unsigned int i = 0; i < mMappingStack.size(); i++) + { + allPrefixes.push_back(mMappingStack[i].first); + } +} diff --git a/pool/shard001/C++/0018723_base_paths_posix.cc b/pool/shard001/C++/0018723_base_paths_posix.cc new file mode 100644 index 0000000000000000000000000000000000000000..a60e1121c95986c1e5e4569efdf17d4e9734dce8 --- /dev/null +++ b/pool/shard001/C++/0018723_base_paths_posix.cc @@ -0,0 +1,120 @@ +// 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. + +// Defines base::PathProviderPosix, default path provider on POSIX OSes that +// don't have their own base_paths_OS.cc implementation (i.e. all but Mac and +// Android). + +#include "base/base_paths.h" + +#include +#include + +#include +#include +#include + +#include "base/environment.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/nix/xdg_util.h" +#include "base/path_service.h" +#include "base/process/process_metrics.h" +#include "build/build_config.h" + +#if defined(OS_FREEBSD) +#include +#include +#elif defined(OS_SOLARIS) +#include +#endif + +namespace base { + +bool PathProviderPosix(int key, FilePath* result) { + FilePath path; + switch (key) { + case base::FILE_EXE: + case base::FILE_MODULE: { // TODO(evanm): is this correct? +#if defined(OS_LINUX) + FilePath bin_dir; + if (!ReadSymbolicLink(FilePath(kProcSelfExe), &bin_dir)) { + NOTREACHED() << "Unable to resolve " << kProcSelfExe << "."; + return false; + } + *result = bin_dir; + return true; +#elif defined(OS_FREEBSD) + int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; + char bin_dir[PATH_MAX + 1]; + size_t length = sizeof(bin_dir); + // Upon return, |length| is the number of bytes written to |bin_dir| + // including the string terminator. + int error = sysctl(name, 4, bin_dir, &length, NULL, 0); + if (error < 0 || length <= 1) { + NOTREACHED() << "Unable to resolve path."; + return false; + } + *result = FilePath(FilePath::StringType(bin_dir, length - 1)); + return true; +#elif defined(OS_SOLARIS) + char bin_dir[PATH_MAX + 1]; + if (realpath(getexecname(), bin_dir) == NULL) { + NOTREACHED() << "Unable to resolve " << getexecname() << "."; + return false; + } + *result = FilePath(bin_dir); + return true; +#elif defined(OS_OPENBSD) + // There is currently no way to get the executable path on OpenBSD + char* cpath; + if ((cpath = getenv("CHROME_EXE_PATH")) != NULL) + *result = FilePath(cpath); + else + *result = FilePath("/usr/local/chrome/chrome"); + return true; +#endif + } + case base::DIR_SOURCE_ROOT: { + // Allow passing this in the environment, for more flexibility in build + // tree configurations (sub-project builds, gyp --output_dir, etc.) + std::unique_ptr env(base::Environment::Create()); + std::string cr_source_root; + if (env->GetVar("CR_SOURCE_ROOT", &cr_source_root)) { + path = FilePath(cr_source_root); + if (base::PathExists(path)) { + *result = path; + return true; + } else { + DLOG(WARNING) << "CR_SOURCE_ROOT is set, but it appears to not " + << "point to a directory."; + } + } + // On POSIX, unit tests execute two levels deep from the source root. + // For example: out/{Debug|Release}/net_unittest + if (PathService::Get(base::DIR_EXE, &path)) { + *result = path.DirName().DirName(); + return true; + } + + DLOG(ERROR) << "Couldn't find your source root. " + << "Try running from your chromium/src directory."; + return false; + } + case base::DIR_USER_DESKTOP: + *result = base::nix::GetXDGUserDirectory("DESKTOP", "Desktop"); + return true; + case base::DIR_CACHE: { + std::unique_ptr env(base::Environment::Create()); + FilePath cache_dir(base::nix::GetXDGDirectory(env.get(), "XDG_CACHE_HOME", + ".cache")); + *result = cache_dir; + return true; + } + } + return false; +} + +} // namespace base diff --git a/pool/shard001/C++/0018728_sendcoinsentry.cpp b/pool/shard001/C++/0018728_sendcoinsentry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a71d34fd2f9cb2bbc79f36222a8e006f986c2e16 --- /dev/null +++ b/pool/shard001/C++/0018728_sendcoinsentry.cpp @@ -0,0 +1,182 @@ +#include "sendcoinsentry.h" +#include "ui_sendcoinsentry.h" + +#include "guiutil.h" +#include "bitcoinunits.h" +#include "addressbookpage.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "addresstablemodel.h" +#include "stealth.h" + +#include +#include + +SendCoinsEntry::SendCoinsEntry(QWidget *parent) : + QFrame(parent), + ui(new Ui::SendCoinsEntry), + model(0) +{ + ui->setupUi(this); + +#ifdef Q_OS_MAC + ui->payToLayout->setSpacing(4); +#endif +#if QT_VERSION >= 0x040700 + /* Do not move this to the XML file, Qt before 4.7 will choke on it */ + ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); + ui->payTo->setPlaceholderText(tr("Enter a Nodes address (e.g. TVzkf3ahXFWhukoqs6wnZHqVFM3UvSDSP2)")); +#endif + setFocusPolicy(Qt::TabFocus); + setFocusProxy(ui->payTo); + + GUIUtil::setupAddressWidget(ui->payTo, this); +} + +SendCoinsEntry::~SendCoinsEntry() +{ + delete ui; +} + +void SendCoinsEntry::on_pasteButton_clicked() +{ + // Paste text from clipboard into recipient field + ui->payTo->setText(QApplication::clipboard()->text()); +} + +void SendCoinsEntry::on_addressBookButton_clicked() +{ + if(!model) + return; + AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); + dlg.setModel(model->getAddressTableModel()); + if(dlg.exec()) + { + ui->payTo->setText(dlg.getReturnValue()); + ui->payAmount->setFocus(); + } +} + +void SendCoinsEntry::on_payTo_textChanged(const QString &address) +{ + if(!model) + return; + // Fill in label from address book, if address has an associated label + QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); + if(!associatedLabel.isEmpty()) + ui->addAsLabel->setText(associatedLabel); +} + +void SendCoinsEntry::setModel(WalletModel *model) +{ + this->model = model; + + if(model && model->getOptionsModel()) + connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); + + clear(); +} + +void SendCoinsEntry::setRemoveEnabled(bool enabled) +{ + ui->deleteButton->setEnabled(enabled); +} + +void SendCoinsEntry::clear() +{ + ui->payTo->clear(); + ui->addAsLabel->clear(); + ui->payAmount->clear(); + ui->payTo->setFocus(); + // update the display unit, to not use the default ("BTC") + updateDisplayUnit(); +} + +void SendCoinsEntry::on_deleteButton_clicked() +{ + emit removeEntry(this); +} + +bool SendCoinsEntry::validate() +{ + // Check input validity + bool retval = true; + + if(!ui->payAmount->validate()) + { + retval = false; + } + else + { + if(ui->payAmount->value() <= 0) + { + // Cannot send 0 coins or less + ui->payAmount->setValid(false); + retval = false; + } + } + + if(!ui->payTo->hasAcceptableInput() || + (model && !model->validateAddress(ui->payTo->text()))) + { + ui->payTo->setValid(false); + retval = false; + } + + return retval; +} + +SendCoinsRecipient SendCoinsEntry::getValue() +{ + SendCoinsRecipient rv; + + rv.address = ui->payTo->text(); + rv.label = ui->addAsLabel->text(); + rv.amount = ui->payAmount->value(); + + if (rv.address.length() > 75 + && IsStealthAddress(rv.address.toStdString())) + rv.typeInd = AddressTableModel::AT_Stealth; + else + rv.typeInd = AddressTableModel::AT_Normal; + + return rv; +} + +QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) +{ + QWidget::setTabOrder(prev, ui->payTo); + QWidget::setTabOrder(ui->payTo, ui->addressBookButton); + QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); + QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); + QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); + return ui->payAmount->setupTabChain(ui->addAsLabel); +} + +void SendCoinsEntry::setValue(const SendCoinsRecipient &value) +{ + ui->payTo->setText(value.address); + ui->addAsLabel->setText(value.label); + ui->payAmount->setValue(value.amount); +} + +bool SendCoinsEntry::isClear() +{ + return ui->payTo->text().isEmpty(); +} + +void SendCoinsEntry::setFocus() +{ + ui->payTo->setFocus(); +} + +void SendCoinsEntry::updateDisplayUnit() +{ + if(model && model->getOptionsModel()) + { + // Update payAmount with the current unit + ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); + } +} diff --git a/pool/shard001/C++/0018730_distributed-node.cpp b/pool/shard001/C++/0018730_distributed-node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecb2b46679bd507fc535303b7f6b1652793142fd --- /dev/null +++ b/pool/shard001/C++/0018730_distributed-node.cpp @@ -0,0 +1,89 @@ +#include "util.hpp" +#include "distributed-node.hpp" + +DistributedNode::DistributedNode(std::string new_keyfile) +:status(OBJECT), +ddata(OBJECT), +keyfile(new_keyfile){ + uint16_t port = 30000; + while(true){ + try{ + this->server = new SymmetricEpollServer(this->keyfile, port, 10); + }catch(std::runtime_error& e){ + if(errno != 98 && errno != 22){ + PRINT("ERROR: " << errno << ':' << port) + throw e; + } + port++; + sleep(1); + continue; + } + break; + } + + this->server->on_read = [&](int fd, const char* data, ssize_t data_length)->ssize_t{ + PRINT(data) + JsonObject request; + request.parse(data); + PRINT(request.stringify(true)) + JsonObject response(OBJECT); + + if(request.HasObj("hash", STRING)){ + PRINT("GIVEN HASH: " << request.GetStr("hash")) + PRINT("MY HASH: " << this->status.GetStr("hash")) + if(request.GetStr("hash") == this->status.GetStr("hash")){ + response.objectValues["status"] = new JsonObject("Up to date."); + }else{ + response.objectValues["status"] = new JsonObject("Out of date."); + } + }else{ + response.objectValues["hash"] = new JsonObject(this->status.GetStr("hash")); + } + + if(this->server->send(fd, response.stringify(false))){ + ERROR("DistributedNode send") + return -1; + } + + return data_length; + }; + + // Returns and runs on a single thread. + this->server->run(true, 1); + + start_thread = std::thread(&DistributedNode::start, this); + + PRINT("DISTRIBUTED NODE INITIALIZED.") +} + +void DistributedNode::add_client(const char* ip_address, uint16_t port){ + std::string client = std::string(ip_address) + ':' + std::to_string(port); + this->clients_mutex.lock(); + this->clients[client] = new SymmetricTcpClient(ip_address, port, this->keyfile); + this->clients_mutex.unlock(); +} + +bool DistributedNode::set_ddata(std::string data){ + this->ddata.objectValues.clear(); + this->ddata.parse(data.c_str()); + this->status.objectValues["hash"] = new JsonObject(Util::sha256_hash(this->ddata.stringify(false))); + return true; +} + +void DistributedNode::start(){ + std::string response; + while(true){ + this->clients_mutex.lock(); + for(auto iter = this->clients.begin(); iter != this->clients.end(); ++iter){ + response = iter->second->communicate(status.stringify(false)); + if(response.empty()){ + PRINT(iter->first << " DISCONNECTED") + }else{ + PRINT(iter->first << " -> " << response) + } + } + this->clients_mutex.unlock(); + + sleep(5); + } +} diff --git a/pool/shard001/C++/0018732_optioninteger.cpp b/pool/shard001/C++/0018732_optioninteger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b85c8b59b76db6a98837659ce63e30a3d565ca5a --- /dev/null +++ b/pool/shard001/C++/0018732_optioninteger.cpp @@ -0,0 +1,57 @@ +// +// Copyright (C) 2013-2018 University of Amsterdam +// +// 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 "optioninteger.h" + +void OptionInteger::init(const Json::Value &data) +{ + _value = data.get("default", 0).asInt(); + _min = data.get("min", -999999).asInt(); + _max = data.get("max", 999999).asInt(); + _format = data.get("format", "").asString(); +} + +Json::Value OptionInteger::asJSON() const +{ + return Json::Value(_value); +} + +void OptionInteger::set(const Json::Value &value) +{ + _value = value.asInt(); +} + +Option *OptionInteger::clone() const +{ + return new OptionInteger(value()); +} + +int OptionInteger::minimum() const +{ + return _min; +} + +int OptionInteger::maximum() const +{ + return _max; +} + +std::string OptionInteger::format() const +{ + return _format; +} + diff --git a/pool/shard001/C++/0018733_IAudioRecord.cpp b/pool/shard001/C++/0018733_IAudioRecord.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a7de65ac0c0734f96a7080c1ed570192cafe6cb --- /dev/null +++ b/pool/shard001/C++/0018733_IAudioRecord.cpp @@ -0,0 +1,111 @@ +/* +** +** Copyright 2007, The Android Open Source Project +** +** 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. +*/ + +#define LOG_TAG "IAudioRecord" +//#define LOG_NDEBUG 0 +#include + +#include +#include + +#include + +#include + +namespace android { + +enum { + GET_CBLK = IBinder::FIRST_CALL_TRANSACTION, + START, + STOP +}; + +class BpAudioRecord : public BpInterface +{ +public: + BpAudioRecord(const sp& impl) + : BpInterface(impl) + { + } + + virtual sp getCblk() const + { + Parcel data, reply; + sp cblk; + data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor()); + status_t status = remote()->transact(GET_CBLK, data, &reply); + if (status == NO_ERROR) { + cblk = interface_cast(reply.readStrongBinder()); + } + return cblk; + } + + virtual status_t start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) + { + Parcel data, reply; + data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor()); + data.writeInt32(event); + data.writeInt32(triggerSession); + status_t status = remote()->transact(START, data, &reply); + if (status == NO_ERROR) { + status = reply.readInt32(); + } else { + ALOGW("start() error: %s", strerror(-status)); + } + return status; + } + + virtual void stop() + { + Parcel data, reply; + data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor()); + remote()->transact(STOP, data, &reply); + } + +}; + +IMPLEMENT_META_INTERFACE(AudioRecord, "android.media.IAudioRecord"); + +// ---------------------------------------------------------------------- + +status_t BnAudioRecord::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch (code) { + case GET_CBLK: { + CHECK_INTERFACE(IAudioRecord, data, reply); + reply->writeStrongBinder(getCblk()->asBinder()); + return NO_ERROR; + } break; + case START: { + CHECK_INTERFACE(IAudioRecord, data, reply); + int /*AudioSystem::sync_event_t*/ event = data.readInt32(); + int triggerSession = data.readInt32(); + reply->writeInt32(start(event, triggerSession)); + return NO_ERROR; + } break; + case STOP: { + CHECK_INTERFACE(IAudioRecord, data, reply); + stop(); + return NO_ERROR; + } break; + default: + return BBinder::onTransact(code, data, reply, flags); + } +} + +}; // namespace android diff --git a/pool/shard001/C++/0018736_gpu_mojo_media_client.cc b/pool/shard001/C++/0018736_gpu_mojo_media_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..c91d935679faef6515c93dcc34269f5b0009e59d --- /dev/null +++ b/pool/shard001/C++/0018736_gpu_mojo_media_client.cc @@ -0,0 +1,174 @@ +// 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 "media/mojo/services/gpu_mojo_media_client.h" + +#include + +#include "base/bind.h" +#include "base/feature_list.h" +#include "base/memory/ptr_util.h" +#include "build/chromeos_buildflags.h" +#include "gpu/ipc/service/gpu_channel.h" +#include "media/base/audio_decoder.h" +#include "media/base/cdm_factory.h" +#include "media/base/media_switches.h" +#include "media/base/media_util.h" +#include "media/base/video_decoder.h" +#include "media/gpu/gpu_video_accelerator_util.h" +#include "media/gpu/gpu_video_decode_accelerator_factory.h" +#include "media/gpu/gpu_video_decode_accelerator_helpers.h" +#include "media/gpu/ipc/service/media_gpu_channel_manager.h" +#include "media/gpu/ipc/service/vda_video_decoder.h" +#include "media/mojo/mojom/video_decoder.mojom.h" +#include "media/video/video_decode_accelerator.h" + +namespace media { + +namespace { + +gpu::CommandBufferStub* GetCommandBufferStub( + scoped_refptr gpu_task_runner, + base::WeakPtr media_gpu_channel_manager, + base::UnguessableToken channel_token, + int32_t route_id) { + DCHECK(gpu_task_runner->BelongsToCurrentThread()); + if (!media_gpu_channel_manager) + return nullptr; + + gpu::GpuChannel* channel = + media_gpu_channel_manager->LookupChannel(channel_token); + if (!channel) + return nullptr; + + gpu::CommandBufferStub* stub = channel->LookupCommandBuffer(route_id); + if (!stub) + return nullptr; + + // Only allow stubs that have a ContextGroup, that is, the GLES2 ones. Later + // code assumes the ContextGroup is valid. + if (!stub->decoder_context()->GetContextGroup()) + return nullptr; + + return stub; +} + +} // namespace + +VideoDecoderTraits::~VideoDecoderTraits() = default; +VideoDecoderTraits::VideoDecoderTraits( + scoped_refptr task_runner, + scoped_refptr gpu_task_runner, + std::unique_ptr media_log, + RequestOverlayInfoCB request_overlay_info_cb, + const gfx::ColorSpace* target_color_space, + gpu::GpuPreferences gpu_preferences, + gpu::GpuFeatureInfo gpu_feature_info, + const gpu::GpuDriverBugWorkarounds* gpu_workarounds, + gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, + GetConfigCacheCB get_cached_configs_cb, + GetCommandBufferStubCB get_command_buffer_stub_cb, + AndroidOverlayMojoFactoryCB android_overlay_factory_cb) + : task_runner(std::move(task_runner)), + gpu_task_runner(std::move(gpu_task_runner)), + media_log(std::move(media_log)), + request_overlay_info_cb(request_overlay_info_cb), + target_color_space(target_color_space), + gpu_preferences(gpu_preferences), + gpu_feature_info(gpu_feature_info), + gpu_workarounds(gpu_workarounds), + gpu_memory_buffer_factory(gpu_memory_buffer_factory), + get_cached_configs_cb(std::move(get_cached_configs_cb)), + get_command_buffer_stub_cb(std::move(get_command_buffer_stub_cb)), + android_overlay_factory_cb(std::move(android_overlay_factory_cb)) {} + +GpuMojoMediaClient::GpuMojoMediaClient( + const gpu::GpuPreferences& gpu_preferences, + const gpu::GpuDriverBugWorkarounds& gpu_workarounds, + const gpu::GpuFeatureInfo& gpu_feature_info, + scoped_refptr gpu_task_runner, + base::WeakPtr media_gpu_channel_manager, + gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, + AndroidOverlayMojoFactoryCB android_overlay_factory_cb) + : gpu_preferences_(gpu_preferences), + gpu_workarounds_(gpu_workarounds), + gpu_feature_info_(gpu_feature_info), + gpu_task_runner_(std::move(gpu_task_runner)), + media_gpu_channel_manager_(std::move(media_gpu_channel_manager)), + android_overlay_factory_cb_(std::move(android_overlay_factory_cb)), + gpu_memory_buffer_factory_(gpu_memory_buffer_factory) {} + +GpuMojoMediaClient::~GpuMojoMediaClient() = default; + +std::unique_ptr GpuMojoMediaClient::CreateAudioDecoder( + scoped_refptr task_runner) { + return CreatePlatformAudioDecoder(task_runner); +} + +VideoDecoderType GpuMojoMediaClient::GetDecoderImplementationType() { + return GetPlatformDecoderImplementationType(gpu_workarounds_, + gpu_preferences_); +} + +SupportedVideoDecoderConfigs +GpuMojoMediaClient::GetSupportedVideoDecoderConfigs() { + if (!supported_config_cache_) + supported_config_cache_ = GetPlatformSupportedVideoDecoderConfigs( + gpu_workarounds_, gpu_preferences_, + // GetPlatformSupportedVideoDecoderConfigs runs this callback either + // never or immediately, and will not store it, so |this| will outlive + // the bound function. + base::BindOnce(&GpuMojoMediaClient::GetVDAVideoDecoderConfigs, + base::Unretained(this))); + + if (!supported_config_cache_) + return {}; + + return *supported_config_cache_; +} + +SupportedVideoDecoderConfigs GpuMojoMediaClient::GetVDAVideoDecoderConfigs() { + VideoDecodeAccelerator::Capabilities capabilities = + GpuVideoAcceleratorUtil::ConvertGpuToMediaDecodeCapabilities( + GpuVideoDecodeAcceleratorFactory::GetDecoderCapabilities( + gpu_preferences_, gpu_workarounds_)); + return ConvertFromSupportedProfiles( + capabilities.supported_profiles, + capabilities.flags & + VideoDecodeAccelerator::Capabilities::SUPPORTS_ENCRYPTED_STREAMS); +} + +std::unique_ptr GpuMojoMediaClient::CreateVideoDecoder( + scoped_refptr task_runner, + MediaLog* media_log, + mojom::CommandBufferIdPtr command_buffer_id, + RequestOverlayInfoCB request_overlay_info_cb, + const gfx::ColorSpace& target_color_space) { + // All implementations require a command buffer. + if (!command_buffer_id) + return nullptr; + std::unique_ptr log = + media_log ? media_log->Clone() : std::make_unique(); + VideoDecoderTraits traits( + task_runner, gpu_task_runner_, std::move(log), + std::move(request_overlay_info_cb), &target_color_space, gpu_preferences_, + gpu_feature_info_, &gpu_workarounds_, gpu_memory_buffer_factory_, + // CreatePlatformVideoDecoder does not keep a reference to |traits| + // so this bound method will not outlive |this| + base::BindRepeating(&GpuMojoMediaClient::GetSupportedVideoDecoderConfigs, + base::Unretained(this)), + base::BindRepeating( + &GetCommandBufferStub, gpu_task_runner_, media_gpu_channel_manager_, + command_buffer_id->channel_token, command_buffer_id->route_id), + android_overlay_factory_cb_); + + return CreatePlatformVideoDecoder(traits); +} + +std::unique_ptr GpuMojoMediaClient::CreateCdmFactory( + mojom::FrameInterfaceFactory* frame_interfaces) { + return CreatePlatformCdmFactory(frame_interfaces); +} + +} // namespace media diff --git a/pool/shard001/C++/0018744_sqliterfile.cpp b/pool/shard001/C++/0018744_sqliterfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6371945e248daf3123a70bde7ee467a4cc580cfb --- /dev/null +++ b/pool/shard001/C++/0018744_sqliterfile.cpp @@ -0,0 +1,52 @@ +/************************************************************************** +** This file is part of LiteIDE +** +** Copyright (c) 2011-2013 LiteIDE Team. All rights reserved. +** +** 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. +** +** In addition, as a special exception, that plugins developed for LiteIDE, +** are allowed to remain closed sourced and can be distributed under any license . +** These rights are included in the file LGPL_EXCEPTION.txt in this package. +** +**************************************************************************/ +// Module: sqliterfile.cpp +// Creator: visualfc + +#include "sqlitefile.h" +#include +#include +//lite_memory_check_begin +#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) + #define _CRTDBG_MAP_ALLOC + #include + #include + #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) + #define new DEBUG_NEW +#endif +//lite_memory_check_end + +SQLiteFile::SQLiteFile(LiteApi::IApplication *app, QObject *parent) : + QSqlDbFile(app,parent) +{ +} + +bool SQLiteFile::open(const QString &fileName, const QString &/*mimeType*/) +{ + m_db = QSqlDatabase::addDatabase("QSQLITE",fileName); + m_db.setDatabaseName(fileName); + return m_db.open(); +} + +QString SQLiteFile::mimeType() const +{ + return "database/sqlite"; +} diff --git a/pool/shard001/C++/0018749_main.cpp b/pool/shard001/C++/0018749_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2eb98b96db5834361fa070052b4795a60e8c1806 --- /dev/null +++ b/pool/shard001/C++/0018749_main.cpp @@ -0,0 +1,102 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "define.h" +#include "fx/algorithm/RateStrategy.h" +#include "fx/data/FXInfo.h" +#include "fx/client/EvaluateStrategyClient.h" + +#if defined(UNICODE) || defined(_UNICODE) + #define _tmain wmain + #define err std::wcerr +#else + #define _tmain main + #define err std::cerr +#endif + +namespace { + const auto SIMULATION_HIGH_RATE = 1.00; + const auto SIMULATION_LOW_RATE = 3.00; + const auto RATE_OPEN = 1; + const auto RATE_LOW = 2; + const auto RATE_HIGH = 3; + const auto RATE_CLOSE = 4; +}; + +/** + * split + */ +std::vector split(const std::string& s, std::string::value_type ch) { + std::vector r; + std::string tmp; + + for (auto&& each : s) { + if (ch != each) { + tmp += each; + } else { + r.emplace_back(tmp); + tmp.erase(); + } + } + + if (!tmp.empty()) { + r.emplace_back(tmp); + } + + return r; +} + +/** + * FXInfoへConvert + */ +flowTumn::FXInfo convert(const std::string& s) { + auto r = split(s, ','); + return flowTumn::factoryFXInfo( + std::atof(r.at(RATE_OPEN).data()), + std::atof(r.at(RATE_CLOSE).data()), + std::atof(r.at(RATE_HIGH).data()), + std::atof(r.at(RATE_LOW).data()) + ); +} + +/** + * 過去のデータを用いてsimulationを実施する。 + */ +void simulation(const flowTumn::tstr& csv) { + flowTumn::EvaluateStrategyClient evaluate(SIMULATION_HIGH_RATE, SIMULATION_LOW_RATE); + std::ifstream iif(csv); + + if (iif.good()) { + while (!iif.eof()) { + std::string lineBuffer; + if (std::getline(iif, lineBuffer)) { + auto r = convert(lineBuffer); + evaluate.simulation( + flowTumn::factoryFXBidAsk(r.rateOpen, r.rateOpen) + ); + } + } + + std::cout << " totalBuy: " << evaluate.operationBuy() << std::endl; + std::cout << " sellHigh: " << evaluate.operationSellHigh() << std::endl; + std::cout << " sellLow: " << evaluate.operationSellLow() << std::endl; + std::cout << " profit: " << evaluate.profit() << std::endl; + std::cout << "highPercent: " << evaluate.highPercent() << std::endl; + std::cout << "lowPercent: " << evaluate.lowPercent() << std::endl; + } +} + +int _tmain(int argc, flowTumn::tstr::value_type** argv) { + + if (2 == argc) { + simulation(argv[1]); + } + + return 0; + +} diff --git a/pool/shard001/C++/0018750_server_config.cpp b/pool/shard001/C++/0018750_server_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb901c1b918c3b54936410ed261e893563b406dd --- /dev/null +++ b/pool/shard001/C++/0018750_server_config.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2003 Robert Sandilands (Pty) Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +USA. + */ +#include "../../config.h" +#include "server_config.h" +#include "../../os/os.h" +#include + +server_config::server_config( int argc, char **argv ) +{ + int rn, Ln, sn; + std::deque param_pos; + char err_msg[1024]; + + installed=0; + is_version=0; + reply_library_path=NULL; + server_library_path=NULL; + num_proto=0; + protocol_name=NULL; + protocol_port=NULL; + error_string=NULL; + rn=Ln=sn=-1; + + if (argc<6) + { + if (argv[1] && strcmp( argv[1], "-v" )) + { + set_error( "Not enough parameters passed" ); + return; + } + } + for (int cnt=1;cnt=num_proto) return( NULL ); + return( protocol_name[index] ); +} + +unsigned server_config::getProtocolLocalPort( unsigned index ) +{ + if (!isOk()) return( 0 ); + if (index>=num_proto) return( 0 ); + return( protocol_port[index] ); +} diff --git a/pool/shard001/C++/0018771_PPToken.cpp b/pool/shard001/C++/0018771_PPToken.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80577ab6cfa9adbbff153b30b8cbeb5135971bea --- /dev/null +++ b/pool/shard001/C++/0018771_PPToken.cpp @@ -0,0 +1,45 @@ +#include "PPToken.h" + +#include + +using namespace CPlusPlus::Internal; + +ByteArrayRef::ByteArrayRef() + : m_ref(0) + , m_offset(0) + , m_length(0) +{} + +bool ByteArrayRef::startsWith(const char *s) const +{ + int l = std::strlen(s); + if (l > m_length) + return false; + return !qstrncmp(start(), s, l); +} + +int ByteArrayRef::count(char ch) const +{ + if (!m_ref) + return 0; + + int num = 0; + const char *b = start(); + const char *i = b + m_length; + while (i != b) + if (*--i == ch) + ++num; + return num; +} + +PPToken::PPToken() +{} + +void PPToken::squeeze() +{ + if (isValid()) { + m_src = m_src.mid(offset, length()); + m_src.squeeze(); + offset = 0; + } +} diff --git a/pool/shard001/C++/0018772_SyncEvoStorageModelItem.cpp b/pool/shard001/C++/0018772_SyncEvoStorageModelItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2741a403c23adbbddb5d0d1084350c8b53e29907 --- /dev/null +++ b/pool/shard001/C++/0018772_SyncEvoStorageModelItem.cpp @@ -0,0 +1,70 @@ +#include "SyncEvoStatic.h" +#include "SyncEvoStorageModelItem.h" + +MeeGo::Sync::SyncEvoStorageModelItem::SyncEvoStorageModelItem(const QString &name, const QString &storage, const QStringMap &header, const QStringMap &storageInfo, bool isTemplate) + : m_name(name) + , m_storage(storage) + , m_header(header) + , m_storageInfo(storageInfo) + , m_isTemplate(isTemplate) +{ +} + +QString +MeeGo::Sync::SyncEvoStorageModelItem::displayName() const +{ + QString ret = + (m_header.contains("PeerName") + ? m_header["PeerName"] + : m_name); + /* + * FIXME: Ugly hack for Google + */ + return (ret.toLower().startsWith("google")) + ? "Google" + : ret; +} + +QString +MeeGo::Sync::SyncEvoStorageModelItem::iconURI() const +{ + return (m_header.contains("IconURI")) + ? m_header["IconURI"] + : ""; +} + +QString +MeeGo::Sync::SyncEvoStorageModelItem::name() const +{ + return m_name + QString(QChar('\0')) + m_storage; +} + +QString +MeeGo::Sync::SyncEvoStorageModelItem::storage() const +{ + return SyncEvoStatic::instance()->storageTypes()[m_storage]; +} + +QStringMap +MeeGo::Sync::SyncEvoStorageModelItem::header() const +{ + return m_header; +} + +QStringMap +MeeGo::Sync::SyncEvoStorageModelItem::storageInfo() const +{ + return m_storageInfo; +} + +QString +MeeGo::Sync::SyncEvoStorageModelItem::toString() const +{ + return QString() + "name: \"" + m_name + "\" storage: \"" + m_storage + "\" template: " + (m_isTemplate ? "true" : "false"); +} + +bool +MeeGo::Sync::SyncEvoStorageModelItem::isTemplate() const +{ + return m_isTemplate; +} diff --git a/pool/shard001/C++/0018773_fake_dual_net.cc b/pool/shard001/C++/0018773_fake_dual_net.cc new file mode 100644 index 0000000000000000000000000000000000000000..9bd0341899b4a0a6437429b986c4c84951f5ffd9 --- /dev/null +++ b/pool/shard001/C++/0018773_fake_dual_net.cc @@ -0,0 +1,50 @@ +// Copyright 2018 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 +// +// 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 "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/dual_net/fake_dual_net.h" + +#include "REDACTEDmemory/memory.h" +#include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/logging.h" + +namespace minigo { + +FakeDualNet::FakeDualNet(absl::Span priors, float value) + : Model("fake", FeatureDescriptor::Create( + FeatureDescriptor::Layout::kNhwc)), + value_(value) { + if (!priors.empty()) { + MG_CHECK(priors.size() == kNumMoves); + for (int i = 0; i < kNumMoves; ++i) { + priors_[i] = priors[i]; + } + } else { + for (auto& prior : priors_) { + prior = 1.0 / kNumMoves; + } + } +} + +void FakeDualNet::RunMany(const std::vector& inputs, + std::vector* outputs, + std::string* model) { + for (auto* output : *outputs) { + output->policy = priors_; + output->value = value_; + } + if (model != nullptr) { + *model = "FakeDualNet"; + } +} + +} // namespace minigo diff --git a/pool/shard001/C++/0018788_moc_transactiondesc.cpp b/pool/shard001/C++/0018788_moc_transactiondesc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48812ee6a56e7ab3603969b1dd478a598de8bfdc --- /dev/null +++ b/pool/shard001/C++/0018788_moc_transactiondesc.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'transactiondesc.h' +** +** Created: Sat Mar 1 13:00:45 2014 +** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../src/qt/transactiondesc.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'transactiondesc.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.1. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_TransactionDesc[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 0, 0, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + 0 // eod +}; + +static const char qt_meta_stringdata_TransactionDesc[] = { + "TransactionDesc\0" +}; + +void TransactionDesc::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + Q_UNUSED(_o); + Q_UNUSED(_id); + Q_UNUSED(_c); + Q_UNUSED(_a); +} + +const QMetaObjectExtraData TransactionDesc::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject TransactionDesc::staticMetaObject = { + { &QObject::staticMetaObject, qt_meta_stringdata_TransactionDesc, + qt_meta_data_TransactionDesc, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &TransactionDesc::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *TransactionDesc::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *TransactionDesc::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_TransactionDesc)) + return static_cast(const_cast< TransactionDesc*>(this)); + return QObject::qt_metacast(_clname); +} + +int TransactionDesc::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QObject::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard001/C++/0018809_InstanceState.cpp b/pool/shard001/C++/0018809_InstanceState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35c5e69c432b7d5c7e18791306112d02c084b719 --- /dev/null +++ b/pool/shard001/C++/0018809_InstanceState.cpp @@ -0,0 +1,86 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file 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 + +using namespace Aws::EC2::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +InstanceState::InstanceState() : + m_code(0), + m_codeHasBeenSet(false), + m_nameHasBeenSet(false) +{ +} + +InstanceState::InstanceState(const XmlNode& xmlNode) : + m_code(0), + m_codeHasBeenSet(false), + m_nameHasBeenSet(false) +{ + *this = xmlNode; +} + +InstanceState& InstanceState::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode codeNode = resultNode.FirstChild("code"); + if(!codeNode.IsNull()) + { + m_code = StringUtils::ConvertToInt32(StringUtils::Trim(codeNode.GetText().c_str()).c_str()); + m_codeHasBeenSet = true; + } + XmlNode nameNode = resultNode.FirstChild("name"); + if(!nameNode.IsNull()) + { + m_name = InstanceStateNameMapper::GetInstanceStateNameForName(StringUtils::Trim(nameNode.GetText().c_str()).c_str()); + m_nameHasBeenSet = true; + } + } + + return *this; +} + +void InstanceState::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_codeHasBeenSet) + { + oStream << location << index << locationValue << ".Code=" << m_code << "&"; + } + if(m_nameHasBeenSet) + { + oStream << location << index << locationValue << ".Name=" << InstanceStateNameMapper::GetNameForInstanceStateName(m_name) << "&"; + } +} + +void InstanceState::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_codeHasBeenSet) + { + oStream << location << ".Code=" << m_code << "&"; + } + if(m_nameHasBeenSet) + { + oStream << location << ".Name=" << InstanceStateNameMapper::GetNameForInstanceStateName(m_name) << "&"; + } +} diff --git a/pool/shard001/C++/0018811_typingmonitor_unittest.cc b/pool/shard001/C++/0018811_typingmonitor_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..66e2401ea707b19ece2ee834f453239a34144141 --- /dev/null +++ b/pool/shard001/C++/0018811_typingmonitor_unittest.cc @@ -0,0 +1,92 @@ +/* + * libjingle + * Copyright 2004 Google Inc. + * + * 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. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/media/base/fakemediaengine.h" +#include "webrtc/p2p/base/fakesession.h" +#include "talk/session/media/channel.h" +#include "talk/session/media/currentspeakermonitor.h" +#include "talk/session/media/typingmonitor.h" +#include "webrtc/base/gunit.h" + +namespace cricket { + +class TypingMonitorTest : public testing::Test { + protected: + TypingMonitorTest() : session_(true) { + vc_.reset(new VoiceChannel(rtc::Thread::Current(), &engine_, + engine_.CreateChannel(), &session_, "", false)); + engine_.GetVoiceChannel(0)->set_time_since_last_typing(1000); + + TypingMonitorOptions settings = {10, 20, 30, 40, 50}; + monitor_.reset(new TypingMonitor(vc_.get(), + rtc::Thread::Current(), + settings)); + } + + void TearDown() { + vc_.reset(); + } + + rtc::scoped_ptr monitor_; + rtc::scoped_ptr vc_; + FakeMediaEngine engine_; + FakeSession session_; +}; + +TEST_F(TypingMonitorTest, TestTriggerMute) { + EXPECT_FALSE(vc_->IsStreamMuted(0)); + EXPECT_FALSE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); + + engine_.GetVoiceChannel(0)->TriggerError(0, VoiceMediaChannel::ERROR_OTHER); + EXPECT_FALSE(vc_->IsStreamMuted(0)); + EXPECT_FALSE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); + + engine_.GetVoiceChannel(0)->TriggerError( + 0, VoiceMediaChannel::ERROR_REC_TYPING_NOISE_DETECTED); + EXPECT_TRUE(vc_->IsStreamMuted(0)); + EXPECT_TRUE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); + + EXPECT_TRUE_WAIT(!vc_->IsStreamMuted(0) && + !engine_.GetVoiceChannel(0)->IsStreamMuted(0), 100); +} + +TEST_F(TypingMonitorTest, TestResetMonitor) { + engine_.GetVoiceChannel(0)->set_time_since_last_typing(1000); + EXPECT_FALSE(vc_->IsStreamMuted(0)); + EXPECT_FALSE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); + + engine_.GetVoiceChannel(0)->TriggerError( + 0, VoiceMediaChannel::ERROR_REC_TYPING_NOISE_DETECTED); + EXPECT_TRUE(vc_->IsStreamMuted(0)); + EXPECT_TRUE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); + + monitor_.reset(); + EXPECT_FALSE(vc_->IsStreamMuted(0)); + EXPECT_FALSE(engine_.GetVoiceChannel(0)->IsStreamMuted(0)); +} + +} // namespace cricket diff --git a/pool/shard001/C++/0018812_chomp_planner.cpp b/pool/shard001/C++/0018812_chomp_planner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6385091fe2022a69a09678e31762d3e168cea938 --- /dev/null +++ b/pool/shard001/C++/0018812_chomp_planner.cpp @@ -0,0 +1,274 @@ +/********************************************************************* + * Software License Agreement (BSD License) + * + * Copyright (c) 2012, Willow Garage, 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 Willow Garage 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. + *********************************************************************/ + +/* Author: E. Gil Jones */ + +#include +#include +#include +#include +#include +#include + +namespace chomp +{ +bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, + const planning_interface::MotionPlanRequest& req, const ChompParameters& params, + planning_interface::MotionPlanDetailedResponse& res) const +{ + ros::WallTime start_time = ros::WallTime::now(); + if (!planning_scene) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "No planning scene initialized."); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::FAILURE; + return false; + } + + // get the specified start state + moveit::core::RobotState start_state = planning_scene->getCurrentState(); + moveit::core::robotStateMsgToRobotState(planning_scene->getTransforms(), req.start_state, start_state); + + if (!start_state.satisfiesBounds()) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Start state violates joint limits"); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; + return false; + } + + ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name); + robotStateToArray(start_state, req.group_name, trajectory.getTrajectoryPoint(0)); + + if (req.goal_constraints.size() != 1) + { + ROS_ERROR_NAMED("chomp_planner", "Expecting exactly one goal constraint, got: %zd", req.goal_constraints.size()); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; + return false; + } + + if (req.goal_constraints[0].joint_constraints.empty() || !req.goal_constraints[0].position_constraints.empty() || + !req.goal_constraints[0].orientation_constraints.empty()) + { + ROS_ERROR_STREAM("Only joint-space goals are supported"); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; + return false; + } + + const size_t goal_index = trajectory.getNumPoints() - 1; + moveit::core::RobotState goal_state(start_state); + for (const moveit_msgs::JointConstraint& joint_constraint : req.goal_constraints[0].joint_constraints) + goal_state.setVariablePosition(joint_constraint.joint_name, joint_constraint.position); + if (!goal_state.satisfiesBounds()) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Goal state violates joint limits"); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_ROBOT_STATE; + return false; + } + robotStateToArray(goal_state, req.group_name, trajectory.getTrajectoryPoint(goal_index)); + + const moveit::core::JointModelGroup* model_group = + planning_scene->getRobotModel()->getJointModelGroup(req.group_name); + // fix the goal to move the shortest angular distance for wrap-around joints: + for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) + { + const moveit::core::JointModel* model = model_group->getActiveJointModels()[i]; + const moveit::core::RevoluteJointModel* revolute_joint = + dynamic_cast(model); + + if (revolute_joint != nullptr) + { + if (revolute_joint->isContinuous()) + { + double start = (trajectory)(0, i); + double end = (trajectory)(goal_index, i); + ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end)); + (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end); + } + } + } + + // fill in an initial trajectory based on user choice from the chomp_config.yaml file + if (params.trajectory_initialization_method_.compare("quintic-spline") == 0) + trajectory.fillInMinJerk(); + else if (params.trajectory_initialization_method_.compare("linear") == 0) + trajectory.fillInLinearInterpolation(); + else if (params.trajectory_initialization_method_.compare("cubic") == 0) + trajectory.fillInCubicInterpolation(); + else if (params.trajectory_initialization_method_.compare("fillTrajectory") == 0) + { + if (!(trajectory.fillInFromTrajectory(*res.trajectory_[0]))) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Input trajectory has less than 2 points, " + "trajectory must contain at least start and goal state"); + return false; + } + } + else + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "invalid interpolation method specified in the chomp_planner file"); + return false; + } + + ROS_INFO_NAMED("chomp_planner", "CHOMP trajectory initialized using method: %s ", + (params.trajectory_initialization_method_).c_str()); + + // optimize! + ros::WallTime create_time = ros::WallTime::now(); + + int replan_count = 0; + bool replan_flag = false; + double org_learning_rate = 0.04, org_ridge_factor = 0.0, org_planning_time_limit = 10; + int org_max_iterations = 200; + + // storing the initial chomp parameters values + org_learning_rate = params.learning_rate_; + org_ridge_factor = params.ridge_factor_; + org_planning_time_limit = params.planning_time_limit_; + org_max_iterations = params.max_iterations_; + + std::unique_ptr optimizer; + + // create a non_const_params variable which stores the non constant version of the const params variable + ChompParameters params_nonconst = params; + + // while loop for replanning (recovery behaviour) if collision free optimized solution not found + while (true) + { + if (replan_flag) + { + // increase learning rate in hope to find a successful path; increase ridge factor to avoid obstacles; add 5 + // additional secs in hope to find a solution; increase maximum iterations + params_nonconst.setRecoveryParams(params_nonconst.learning_rate_ + 0.02, params_nonconst.ridge_factor_ + 0.002, + params_nonconst.planning_time_limit_ + 5, params_nonconst.max_iterations_ + 50); + } + + // initialize a ChompOptimizer object to load up the optimizer with default parameters or with updated parameters in + // case of a recovery behaviour + optimizer = + std::make_unique(&trajectory, planning_scene, req.group_name, ¶ms_nonconst, start_state); + if (!optimizer->isInitialized()) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Could not initialize optimizer"); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; + return false; + } + + ROS_DEBUG_NAMED("chomp_planner", "Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec()); + + bool optimization_result = optimizer->optimize(); + + // replan with updated parameters if no solution is found + if (params_nonconst.enable_failure_recovery_) + { + ROS_INFO_NAMED("chomp_planner", + "Planned with Chomp Parameters (learning_rate, ridge_factor, " + "planning_time_limit, max_iterations), attempt: # %d ", + (replan_count + 1)); + ROS_INFO_NAMED("chomp_planner", "Learning rate: %f ridge factor: %f planning time limit: %f max_iterations %d ", + params_nonconst.learning_rate_, params_nonconst.ridge_factor_, + params_nonconst.planning_time_limit_, params_nonconst.max_iterations_); + + if (!optimization_result && replan_count < params_nonconst.max_recovery_attempts_) + { + replan_count++; + replan_flag = true; + } + else + { + break; + } + } + else + break; + } // end of while loop + + // resetting the CHOMP Parameters to the original values after a successful plan + params_nonconst.setRecoveryParams(org_learning_rate, org_ridge_factor, org_planning_time_limit, org_max_iterations); + + ROS_DEBUG_NAMED("chomp_planner", "Optimization actually took %f sec to run", + (ros::WallTime::now() - create_time).toSec()); + create_time = ros::WallTime::now(); + // assume that the trajectory is now optimized, fill in the output structure: + + ROS_DEBUG_NAMED("chomp_planner", "Output trajectory has %zd joints", trajectory.getNumJoints()); + + auto result = std::make_shared(planning_scene->getRobotModel(), req.group_name); + // fill in the entire trajectory + for (size_t i = 0; i < trajectory.getNumPoints(); i++) + { + const Eigen::MatrixXd::RowXpr source = trajectory.getTrajectoryPoint(i); + auto state = std::make_shared(start_state); + size_t joint_index = 0; + for (const moveit::core::JointModel* jm : result->getGroup()->getActiveJointModels()) + { + assert(jm->getVariableCount() == 1); + state->setVariablePosition(jm->getFirstVariableIndex(), source[joint_index++]); + } + result->addSuffixWayPoint(state, 0.0); + } + + res.trajectory_.resize(1); + res.trajectory_[0] = result; + + ROS_DEBUG_NAMED("chomp_planner", "Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec()); + ROS_DEBUG_NAMED("chomp_planner", "Serviced planning request in %f wall-seconds", + (ros::WallTime::now() - start_time).toSec()); + + res.error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS; + res.processing_time_.resize(1); + res.processing_time_[0] = (ros::WallTime::now() - start_time).toSec(); + + // report planning failure if path has collisions + if (not optimizer->isCollisionFree()) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Motion plan is invalid."); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN; + return false; + } + + // check that final state is within goal tolerances + kinematic_constraints::JointConstraint jc(planning_scene->getRobotModel()); + const moveit::core::RobotState& last_state = result->getLastWayPoint(); + for (const moveit_msgs::JointConstraint& constraint : req.goal_constraints[0].joint_constraints) + { + if (!jc.configure(constraint) || !jc.decide(last_state).satisfied) + { + ROS_ERROR_STREAM_NAMED("chomp_planner", "Goal constraints are violated: " << constraint.joint_name); + res.error_code_.val = moveit_msgs::MoveItErrorCodes::GOAL_CONSTRAINTS_VIOLATED; + return false; + } + } + + return true; +} +} // namespace chomp diff --git a/pool/shard001/C++/0018835_PrintTask.cpp b/pool/shard001/C++/0018835_PrintTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba80bd9139e8df93e5c24fcfe9bd3c13ad02f87b --- /dev/null +++ b/pool/shard001/C++/0018835_PrintTask.cpp @@ -0,0 +1,32 @@ +// +// PrintTask.cpp +// DataDecomposition +// +// Created by Dom on 30/3/17. +// Copyright (c) 2017 reworks. All rights reserved. +// + +#include + +#include "PrintTask.hpp" + +PrintTask::PrintTask(const std::string& msg) +{ + str = msg; +} + +PrintTask::~PrintTask() +{ + m_isDone = true; +} + +void PrintTask::toExecute() +{ + for (int i = 0; i < 10; i++) + { + std::string msg = std::to_string(i) + ") " + str + "\n"; + printf("%s", msg.c_str()); + } + + m_isDone = true; +} diff --git a/pool/shard001/C++/0018837_StbiHdrImageSaver.cpp b/pool/shard001/C++/0018837_StbiHdrImageSaver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..552acdf79e1d399b4c176d46f2d537c1de1e859c --- /dev/null +++ b/pool/shard001/C++/0018837_StbiHdrImageSaver.cpp @@ -0,0 +1,24 @@ +// This file was developed by Thomas Müller . +// It is published under the BSD 3-Clause License within the LICENSE file. + +#include + +#include + +#include +#include + +using namespace nanogui; +using namespace std; + +TEV_NAMESPACE_BEGIN + +void StbiHdrImageSaver::save(ostream& oStream, const fs::path&, const vector& data, const Vector2i& imageSize, int nChannels) const { + static const auto stbiOStreamWrite = [](void* context, void* data, int size) { + reinterpret_cast(context)->write(reinterpret_cast(data), size); + }; + + stbi_write_hdr_to_func(stbiOStreamWrite, &oStream, imageSize.x(), imageSize.y(), nChannels, data.data()); +} + +TEV_NAMESPACE_END diff --git a/pool/shard001/C++/0018838_mock-io.cpp b/pool/shard001/C++/0018838_mock-io.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f4b57141ce1d3f12add262b23abd6a29a712b4a --- /dev/null +++ b/pool/shard001/C++/0018838_mock-io.cpp @@ -0,0 +1,164 @@ +#include +#include + +#include "mock-io.hpp" +#include "syscalls/cio.h" + +void CIOImplement::set_impl(util::sptr p) +{ + _p = std::move(p); +} + +util::sref CIOImplement::get_impl() +{ + return *_p; +} + +util::sptr CIOImplement::_p(new CIOImplement); + +ssize_t CIOImplement::read(int fd, void* buf, size_t count) +{ + return ::read(fd, buf, count); +} + +ssize_t CIOImplement::write(int fd, void const* buf, size_t count) +{ + return ::write(fd, buf, count); +} + +/* This is also an example for systems that does not support writev */ + +ssize_t CIOImplement::writev(int fd, cio::iovec const* iov, int iovcnt) +{ + ssize_t n = 0; + for (int i = 0; i < iovcnt; ++i) { + EXPECT_LE(iov[i].iov_len, 0xFFFFFF); + ssize_t s = this->write(fd, iov[i].iov_base, iov[i].iov_len); + if (-1 == s) { + return n ? n : -1; + } + if (s < ssize_t(iov[i].iov_len)) { + return n + s; + } + n += s; + } + return n; +} + +int CIOImplement::close(int fd) +{ + return ::close(fd); +} + +ssize_t cio::read(int fd, void* buf, size_t count) +{ + return CIOImplement::get_impl()->read(fd, buf, count); +} + +ssize_t cio::write(int fd, void const* buf, size_t count) +{ + return CIOImplement::get_impl()->write(fd, buf, count); +} + +ssize_t cio::writev(int fd, cio::iovec const* iov, int iovcnt) +{ + return CIOImplement::get_impl()->writev(fd, iov, iovcnt); +} + +int cio::close(int fd) +{ + return CIOImplement::get_impl()->close(fd); +} + +int fctl::new_stream_socket() +{ + return CIOImplement::get_impl()->new_stream_socket(); +} + +int fctl::set_tcpnodelay(int fd) +{ + return CIOImplement::get_impl()->set_tcpnodelay(fd); +} + +void fctl::set_nonblocking(int sockfd) +{ + return CIOImplement::get_impl()->set_nonblocking(sockfd); +} + +void fctl::connect_fd(std::string const& host, int port, int fd) +{ + return CIOImplement::get_impl()->connect_fd(host, port, fd); +} + +void fctl::bind_to(int fd, int port) +{ + return CIOImplement::get_impl()->bind_to(fd, port); +} + +void BufferIO::clear() +{ + this->read_buffer.clear(); + this->write_buffer.clear(); + this->writing_sizes.clear(); +} + +ssize_t BufferIO::read(int, void* b, size_t count) +{ + if (this->read_buffer.empty()) { + errno = EAGAIN; + return -1; + } + char* buf = static_cast(b); + if (count < this->read_buffer[0].size()) { + std::copy(this->read_buffer[0].begin(), this->read_buffer[0].begin() + count, buf); + this->read_buffer[0].erase(this->read_buffer[0].begin(), this->read_buffer[0].begin() + count); + return count; + } + size_t sz = this->read_buffer[0].size(); + std::copy(this->read_buffer[0].begin(), this->read_buffer[0].end(), buf); + this->read_buffer.pop_front(); + return sz; +} + +ssize_t BufferIO::write(int, void const* buf, size_t count) +{ + if (this->writing_sizes.empty()) { + this->write_buffer.push_back(std::string(static_cast(buf), count)); + return count; + } + int sz = this->writing_sizes[0]; + if (-1 == sz) { + this->writing_sizes.pop_front(); + errno = EAGAIN; + return -1; + } + if (sz <= int(count)) { + this->write_buffer.push_back(std::string(static_cast(buf), sz)); + this->writing_sizes[0] = -1; + return sz; + } + this->write_buffer.push_back(std::string(static_cast(buf), count)); + this->writing_sizes[0] -= count; + return count; +} + +int BufferIO::close(int) +{ + EXPECT_TRUE(false); + return 0; +} + +util::sref BufferTestBase::io_obj(nullptr); + +void BufferTestBase::SetUp() +{ + util::sptr buffer_io(new BufferIO); + BufferTestBase::io_obj = *buffer_io; + CIOImplement::set_impl(std::move(buffer_io)); +} + +void BufferTestBase::TearDown() +{ + BufferTestBase::io_obj.reset(); + CIOImplement::set_impl(util::mkptr(new CIOImplement)); +} diff --git a/pool/shard001/C++/0018843_typed_url_data_type_controller.cc b/pool/shard001/C++/0018843_typed_url_data_type_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..835022602b55ecf4c4f93aa36f99fdcc50d8ecf5 --- /dev/null +++ b/pool/shard001/C++/0018843_typed_url_data_type_controller.cc @@ -0,0 +1,173 @@ +// 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/glue/typed_url_data_type_controller.h" + +#include "base/metrics/histogram.h" +#include "chrome/browser/history/history.h" +#include "chrome/browser/prefs/pref_service.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/sync/profile_sync_components_factory.h" +#include "chrome/browser/sync/profile_sync_service.h" +#include "chrome/common/chrome_notification_types.h" +#include "chrome/common/pref_names.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/notification_details.h" + +using content::BrowserThread; + +namespace browser_sync { + +class ControlTask : public HistoryDBTask { + public: + ControlTask(TypedUrlDataTypeController* controller, bool start) + : controller_(controller), start_(start) {} + + virtual bool RunOnDBThread(history::HistoryBackend* backend, + history::HistoryDatabase* db) { + controller_->RunOnHistoryThread(start_, backend); + + // Release the reference to the controller. This ensures that + // the controller isn't held past its lifetime in unit tests. + controller_ = NULL; + return true; + } + + virtual void DoneRunOnMainThread() {} + + protected: + scoped_refptr controller_; + bool start_; +}; + +TypedUrlDataTypeController::TypedUrlDataTypeController( + ProfileSyncComponentsFactory* profile_sync_factory, + Profile* profile, + ProfileSyncService* sync_service) + : NonFrontendDataTypeController(profile_sync_factory, + profile, + sync_service), + backend_(NULL) { + pref_registrar_.Init(profile->GetPrefs()); + pref_registrar_.Add(prefs::kSavingBrowserHistoryDisabled, this); +} + +TypedUrlDataTypeController::~TypedUrlDataTypeController() { +} + +void TypedUrlDataTypeController::RunOnHistoryThread(bool start, + history::HistoryBackend* backend) { + DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); + // The only variable we can access here is backend_, since it is always + // read from the DB thread. Touching anything else could lead to memory + // corruption. + backend_ = backend; + if (start) { + StartAssociation(); + } else { + StopAssociation(); + } + backend_ = NULL; +} + +bool TypedUrlDataTypeController::StartAssociationAsync() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK_EQ(state(), ASSOCIATING); + HistoryService* history = profile()->GetHistoryService( + Profile::IMPLICIT_ACCESS); + if (history) { + history_service_ = history; + history_service_->ScheduleDBTask(new ControlTask(this, true), + &cancelable_consumer_); + return true; + } else { + // History must be disabled - don't start. + LOG(WARNING) << "Cannot access history service - disabling typed url sync"; + return false; + } +} + +void TypedUrlDataTypeController::CreateSyncComponents() { + DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK_EQ(state(), ASSOCIATING); + DCHECK(backend_); + ProfileSyncComponentsFactory::SyncComponents sync_components = + profile_sync_factory()->CreateTypedUrlSyncComponents( + profile_sync_service(), + backend_, + this); + set_model_associator(sync_components.model_associator); + set_change_processor(sync_components.change_processor); +} + +void TypedUrlDataTypeController::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + switch (type) { + case chrome::NOTIFICATION_PREF_CHANGED: + DCHECK(*content::Details(details).ptr() == + prefs::kSavingBrowserHistoryDisabled); + if (profile()->GetPrefs()->GetBoolean( + prefs::kSavingBrowserHistoryDisabled)) { + // We've turned off history persistence, so if we are running, + // generate an unrecoverable error. This can be fixed by restarting + // Chrome (on restart, typed urls will not be a registered type). + if (state() != NOT_RUNNING && state() != STOPPING) { + profile_sync_service()->OnUnrecoverableError( + FROM_HERE, "History saving is now disabled by policy."); + } + } + break; + default: + NOTREACHED(); + break; + } +} + +void TypedUrlDataTypeController::StopModels() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK(state() == STOPPING || state() == NOT_RUNNING || state() == DISABLED); + DVLOG(1) << "TypedUrlDataTypeController::StopModels(): State = " << state(); + notification_registrar_.RemoveAll(); +} + +bool TypedUrlDataTypeController::StopAssociationAsync() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK_EQ(state(), STOPPING); + DCHECK(history_service_.get()); + history_service_->ScheduleDBTask(new ControlTask(this, false), + &cancelable_consumer_); + return true; +} + +syncable::ModelType TypedUrlDataTypeController::type() const { + return syncable::TYPED_URLS; +} + +browser_sync::ModelSafeGroup TypedUrlDataTypeController::model_safe_group() + const { + return browser_sync::GROUP_HISTORY; +} + +void TypedUrlDataTypeController::RecordUnrecoverableError( + const tracked_objects::Location& from_here, + const std::string& message) { + DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); + UMA_HISTOGRAM_COUNTS("Sync.TypedUrlRunFailures", 1); +} + +void TypedUrlDataTypeController::RecordAssociationTime(base::TimeDelta time) { + DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); + UMA_HISTOGRAM_TIMES("Sync.TypedUrlAssociationTime", time); +} + +void TypedUrlDataTypeController::RecordStartFailure(StartResult result) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + UMA_HISTOGRAM_ENUMERATION("Sync.TypedUrlStartFailures", + result, + MAX_START_RESULT); +} +} // namespace browser_sync diff --git a/pool/shard001/C++/0018845_Viewer2.cpp b/pool/shard001/C++/0018845_Viewer2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e81a05a4d3ca9531e467c06cd6c0fd2d5edfd7ff --- /dev/null +++ b/pool/shard001/C++/0018845_Viewer2.cpp @@ -0,0 +1,76 @@ + +// Viewer2.cpp : ÀÀ¿ë ÇÁ·Î±×·¥¿¡ ´ëÇÑ Å¬·¡½º µ¿ÀÛÀ» Á¤ÀÇÇÕ´Ï´Ù. +// + +#include "stdafx.h" +#include "Viewer2.h" +#include "Viewer2Dlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#endif + + +// CViewer2App +BEGIN_MESSAGE_MAP(CViewer2App, CWinApp) + ON_COMMAND(ID_HELP, &CWinApp::OnHelp) +END_MESSAGE_MAP() + + +// CViewer2App »ý¼º +CViewer2App::CViewer2App() +{ + // ´Ù½Ã ½ÃÀÛ °ü¸®ÀÚ Áö¿ø + m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; +} + + +// À¯ÀÏÇÑ CViewer2App °³Ã¼ÀÔ´Ï´Ù. +CViewer2App theApp; + + +// CViewer2App ÃʱâÈ­ +BOOL CViewer2App::InitInstance() +{ + INITCOMMONCONTROLSEX InitCtrls; + InitCtrls.dwSize = sizeof(InitCtrls); + + InitCtrls.dwICC = ICC_WIN95_CLASSES; + InitCommonControlsEx(&InitCtrls); + + CWinApp::InitInstance(); + + AfxEnableControlContainer(); + + CShellManager *pShellManager = new CShellManager; + + + SetRegistryKey(_T("·ÎÄà ÀÀ¿ë ÇÁ·Î±×·¥ ¸¶¹ý»ç¿¡¼­ »ý¼ºµÈ ÀÀ¿ë ÇÁ·Î±×·¥")); + + CViewer2Dlg *pdlg = new CViewer2Dlg(); + pdlg->Create(CViewer2Dlg::IDD); + m_pMainWnd = pdlg; + pdlg->ShowWindow(SW_SHOW); + + pdlg->MainLoop(); + + //INT_PTR nResponse = dlg.DoModal(); + //if (nResponse == IDOK) + //{ + //} + //else if (nResponse == IDCANCEL) + //{ + //} + + if (pShellManager != NULL) + { + delete pShellManager; + } + + delete pdlg; + graphic::ReleaseRenderer(); + memmonitor::Cleanup(); + + return FALSE; +} + diff --git a/pool/shard001/C++/0018853_Swarm.cpp b/pool/shard001/C++/0018853_Swarm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c775281c80adaca92143527810f09889ab2d8c40 --- /dev/null +++ b/pool/shard001/C++/0018853_Swarm.cpp @@ -0,0 +1,112 @@ +/* + This file is part of cpp-ethereum. + + cpp-ethereum 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. + + cpp-ethereum 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 cpp-ethereum. If not, see . +*/ +/** @file Swarm.cpp + * @author Gav Wood + * @date 2015 + */ + +#include "Swarm.h" + +#include +#include +#include +#include +#include +#include "WebThree.h" +#include "Support.h" +#include "IPFS.h" +using namespace std; +using namespace dev; +using namespace bzz; +using namespace eth; + +struct SwarmChannel: public LogChannel { static const char* name(); static const int verbosity = 3; }; +const char* SwarmChannel::name() { return EthYellow "bzz"; } +#define cbzz clog(SwarmChannel) + +bzz::Interface::~Interface() +{ +} + +bzz::Client::Client(WebThreeDirect* _web3): + m_ipfs(new IPFS) +{ + m_owner = _web3; +} + +Pinneds bzz::Client::insertBundle(bytesConstRef _bundle) +{ + cbzz << "Bundle insert" << sha3(_bundle); + + Pinneds ret; + RLP rlp(_bundle); + bool first = true; + for (auto const& r: rlp) + if (first) + first = false; + else + { + cbzz << " inserting slice" << sha3(r.toBytesConstRef()); + ret.push_back(Pinned(m_cache[sha3(r.toBytesConstRef())] = make_shared(r.toBytes()))); + } + return ret; +} + +Pinned bzz::Client::put(bytes const& _data) +{ + h256 ret = sha3(_data); + cbzz << "Inserting" << ret; + + if (!m_cache.count(ret)) + m_cache[ret] = make_shared(_data); + + if (m_putAccount) + { + // send to IPFS... + h256 sha256hash = sha256(&_data); + cbzz << "IPFS-inserting" << sha256hash; + + // set in blockchain + try + { + m_owner->support()->hintSHA256(ret, sha256hash, m_putAccount); + m_ipfs->putBlockForSHA256(&_data); + } + catch (InterfaceNotSupported&) {} + } + + return Pinned(m_cache[ret]); +} + +Pinned bzz::Client::get(h256 const& _hash) +{ + cbzz << "Looking up" << _hash; + auto it = m_cache.find(_hash); + if (it != m_cache.end()) + return it->second; + + if (u256 sha256hash = m_owner->support()->sha256Hint(_hash)) + { + cbzz << "IPFS Searching" << sha256hash; + auto b = m_ipfs->getBlockForSHA256(sha256hash); + if (!b.empty()) + return (m_cache[_hash] = make_shared(b)); + } + + cbzz << "Not found" << _hash; + throw ResourceNotAvailable(); +} diff --git a/pool/shard001/C++/0018856_scatter_op_gpu.cu.cc b/pool/shard001/C++/0018856_scatter_op_gpu.cu.cc new file mode 100644 index 0000000000000000000000000000000000000000..213c62402a1c689b2265cf42d220a51f0b0bd84f --- /dev/null +++ b/pool/shard001/C++/0018856_scatter_op_gpu.cu.cc @@ -0,0 +1,109 @@ +/* Copyright 2015 The TensorFlow Authors. 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. +==============================================================================*/ + +#if GOOGLE_CUDA + +#define EIGEN_USE_GPU + +#include "tensorflow/core/kernels/scatter_op.h" + +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/cuda_kernel_helper.h" + +namespace tensorflow { + +typedef Eigen::GpuDevice GPUDevice; + +template +__global__ void ScatterOpCustomKernel( + T* params, const T* updates, const Index* indices, + Index first_dim_size, Index updates_size, Index indices_size) { + Index update_block = updates_size / indices_size; + CUDA_1D_KERNEL_LOOP(i, updates_size) { + int indices_i = i / update_block; + int updates_i = i; + int param_first_index = indices[indices_i]; + if (!(param_first_index >= 0 && param_first_index < first_dim_size)) { + // Ignore indices that are out of range. + continue; + } + int params_i = param_first_index * update_block + (i % update_block); + switch (op) { + case scatter_op::UpdateOp::ASSIGN: { + params[params_i] = ldg(updates + updates_i); + break; + } + case scatter_op::UpdateOp::ADD: { + CudaAtomicAdd(params + params_i, ldg(updates + updates_i)); + break; + } + case scatter_op::UpdateOp::SUB: { + CudaAtomicSub(params + params_i, ldg(updates + updates_i)); + break; + } + } + } +} + +namespace functor { +// Specialization for a GPU device. +template +struct ScatterFunctor { + Index operator()(OpKernelContext* c, const GPUDevice& d, + typename TTypes::Matrix params, + typename TTypes::ConstMatrix updates, + typename TTypes::ConstFlat indices) { + // TODO: Implement indices range check. The hardest part is with returning + // a value after the range check, as we do not want to do device to host + // memcpy during a stream. + const Index first_dim_size = params.dimension(0); + const Index indices_size = indices.size(); + const Index updates_size = updates.size(); + CudaLaunchConfig config = GetCudaLaunchConfig(updates_size, d); + ScatterOpCustomKernel + <<>>( + params.data(), updates.data(), indices.data(), + first_dim_size, updates_size, indices_size); + return -1; + } +}; + +} // namespace functor + +#define DEFINE_GPU_SPECS_OP(T, Index, op) \ + template struct functor::ScatterFunctor; + +#define DEFINE_GPU_SPECS_INDEX(T, Index) \ + DEFINE_GPU_SPECS_OP(T, Index, scatter_op::UpdateOp::ASSIGN); \ + DEFINE_GPU_SPECS_OP(T, Index, scatter_op::UpdateOp::ADD); \ + DEFINE_GPU_SPECS_OP(T, Index, scatter_op::UpdateOp::SUB); + +#define DEFINE_GPU_SPECS(T) \ + DEFINE_GPU_SPECS_INDEX(T, int32); \ + DEFINE_GPU_SPECS_INDEX(T, int64); + +DEFINE_GPU_SPECS(float); +DEFINE_GPU_SPECS(double); +// TODO: The following fails to compile. +// TF_CALL_GPU_NUMBER_TYPES(DEFINE_GPU_SPECS); + +#undef DEFINE_GPU_SPECS +#undef DEFINE_GPU_SPECS_INDEX +#undef DEFINE_GPU_SPECS_OP + +} // namespace tensorflow + +#endif // GOOGLE_CUDA diff --git a/pool/shard001/C++/0018857_c.cpp b/pool/shard001/C++/0018857_c.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc146a7e493a87f5e3dc677c5b52b0ea2e043c0b --- /dev/null +++ b/pool/shard001/C++/0018857_c.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define REP(i,x) for(int i=0 ; i<(int)(x) ; i++) +#define ALL(x) (x).begin(),(x).end() +#define LL long long + +using namespace std; + +int N, K; +vector > graph; +vector > edges; + +// return num of delete nodes +int dfs(int v,int prev, int sum){ + int res = 0; + REP(i, graph[v].size()){ + int u = graph[v][i]; + if(u==prev)continue; + res += dfs(u, v, sum+1); + } + if(sum>K/2)res++; + return res; +} + + +int main(){ + cin >> N >> K; + graph.assign(N, vector()); + edges.clear(); + REP(i, N-1){ + int A, B; + cin >> A >> B; + A--; + B--; + edges.push_back(make_pair(A, B)); + graph[A].push_back(B); + graph[B].push_back(A); + } + int res = N; + if(K%2==0){ + REP(i,N){ + res = min(res, dfs(i, -1, 0)); + } + }else{ + K--; + REP(i,N-1){ + int a = edges[i].first; + int b = edges[i].second; + res = min(res, dfs(a, b, 0) + dfs(b, a, 0)); + } + } + + cout << res << endl; + + return 0; +} diff --git a/pool/shard001/C++/0018862_5.cpp b/pool/shard001/C++/0018862_5.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74e822920634d3b2f0ebb27e9256ff4b6845fefa --- /dev/null +++ b/pool/shard001/C++/0018862_5.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +using namespace std; +void f(string str,set &s){ + set :: iterator it; + it=s.find(str); + if(it!=s.end()) return ; + s.insert(str); + //cout<'0' && str[i+1]>'0'){ + str[i]=((str[i]-'0')-1)+'0'; + str[i+1]=((str[i+1]-'0')-1)+'0'; + if(i+2!=str.length()){ + str[i+2]=((str[i+2]-'0')+1)+'0'; + f(str,s); + str[i]=((str[i]-'0')+1)+'0'; + str[i+1]=((str[i+1]-'0')+1)+'0'; + str[i+2]=((str[i+2]-'0')-1)+'0'; + }else{ + str.push_back('1'); + f(str,s); + } + } + } +} +int main(int argc, char const *argv[]) { + int t; + cin>>t; + while(t--){ + int n; + cin>>n; + int x; + string str=""; + for(int i=0;i>x; + str.push_back(x+'0'); + } + set s; + f(str,s); + cout< +#include +#include +#include +#include + +#include + +using namespace Aws::CloudWatch::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +DescribeAlarmHistoryResult::DescribeAlarmHistoryResult() +{ +} + +DescribeAlarmHistoryResult::DescribeAlarmHistoryResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +DescribeAlarmHistoryResult& DescribeAlarmHistoryResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (!rootNode.IsNull() && (rootNode.GetName() != "DescribeAlarmHistoryResult")) + { + resultNode = rootNode.FirstChild("DescribeAlarmHistoryResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode alarmHistoryItemsNode = resultNode.FirstChild("AlarmHistoryItems"); + if(!alarmHistoryItemsNode.IsNull()) + { + XmlNode alarmHistoryItemsMember = alarmHistoryItemsNode.FirstChild("member"); + while(!alarmHistoryItemsMember.IsNull()) + { + m_alarmHistoryItems.push_back(alarmHistoryItemsMember); + alarmHistoryItemsMember = alarmHistoryItemsMember.NextNode("member"); + } + + } + XmlNode nextTokenNode = resultNode.FirstChild("NextToken"); + if(!nextTokenNode.IsNull()) + { + m_nextToken = StringUtils::Trim(nextTokenNode.GetText().c_str()); + } + } + + if (!rootNode.IsNull()) { + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::CloudWatch::Model::DescribeAlarmHistoryResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + } + return *this; +} diff --git a/pool/shard001/C++/0018871_boss_patchwerk.cpp b/pool/shard001/C++/0018871_boss_patchwerk.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6d70f56034598cbca0d6e17708ba94796b07beb --- /dev/null +++ b/pool/shard001/C++/0018871_boss_patchwerk.cpp @@ -0,0 +1,208 @@ +/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information + * 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 + */ + +/* ScriptData +SDName: Boss_Patchwerk +SD%Complete: 100 +SDComment: +SDCategory: Naxxramas +EndScriptData */ + +#include "precompiled.h" +#include "naxxramas.h" + +enum +{ + SAY_AGGRO1 = -1533017, + SAY_AGGRO2 = -1533018, + SAY_SLAY = -1533019, + SAY_DEATH = -1533020, + + EMOTE_GENERIC_BERSERK = -1000004, + EMOTE_GENERIC_ENRAGED = -1000003, + + SPELL_HATEFULSTRIKE = 28308, + SPELL_ENRAGE = 28131, + SPELL_BERSERK = 26662, + SPELL_SLIMEBOLT = 32309 +}; + +struct boss_patchwerkAI : public ScriptedAI +{ + boss_patchwerkAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); + Reset(); + } + + instance_naxxramas* m_pInstance; + + uint32 m_uiHatefulStrikeTimer; + uint32 m_uiBerserkTimer; + uint32 m_uiBerserkSlimeBoltTimer; + uint32 m_uiSlimeboltTimer; + bool m_bEnraged; + bool m_bBerserk; + + void Reset() override + { + m_uiHatefulStrikeTimer = 1000; // 1 second + m_uiBerserkTimer = MINUTE * 7 * IN_MILLISECONDS; // 7 minutes + m_uiBerserkSlimeBoltTimer = m_uiBerserkTimer + 30 * IN_MILLISECONDS; // Slime Bolt Enrage + m_uiSlimeboltTimer = 10000; + m_bEnraged = false; + m_bBerserk = false; + } + + void KilledUnit(Unit* /*pVictim*/) override + { + if (urand(0, 4)) + return; + + DoScriptText(SAY_SLAY, m_creature); + } + + void JustDied(Unit* /*pKiller*/) override + { + DoScriptText(SAY_DEATH, m_creature); + + if (m_pInstance) + m_pInstance->SetData(TYPE_PATCHWERK, DONE); + } + + void Aggro(Unit* /*pWho*/) override + { + DoScriptText(urand(0, 1) ? SAY_AGGRO1 : SAY_AGGRO2, m_creature); + + if (m_pInstance) + m_pInstance->SetData(TYPE_PATCHWERK, IN_PROGRESS); + } + + void JustReachedHome() override + { + if (m_pInstance) + m_pInstance->SetData(TYPE_PATCHWERK, FAIL); + } + + void DoHatefulStrike() + { + // The ability is used on highest HP target choosen of the top 2 (3 heroic) targets on threat list being in melee range + Unit* pTarget = nullptr; + uint32 uiHighestHP = 0; + uint32 uiTargets = 2; + + ThreatList const& tList = m_creature->getThreatManager().getThreatList(); + if (tList.size() > 1) // Check if more than two targets, and start loop with second-most aggro + { + ThreatList::const_iterator iter = tList.begin(); + std::advance(iter, 1); + for (; iter != tList.end(); ++iter) + { + if (!uiTargets) + break; + + if (Unit* pTempTarget = m_creature->GetMap()->GetUnit((*iter)->getUnitGuid())) + { + if (m_creature->CanReachWithMeleeAttack(pTempTarget)) + { + if (pTempTarget->GetHealth() > uiHighestHP) + { + uiHighestHP = pTempTarget->GetHealth(); + pTarget = pTempTarget; + } + --uiTargets; + } + } + } + } + + if (!pTarget) + pTarget = m_creature->getVictim(); + + DoCastSpellIfCan(pTarget, SPELL_HATEFULSTRIKE); + } + + void UpdateAI(const uint32 uiDiff) override + { + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + + // Hateful Strike + if (m_uiHatefulStrikeTimer < uiDiff) + { + DoHatefulStrike(); + m_uiHatefulStrikeTimer = 1000; + } + else + m_uiHatefulStrikeTimer -= uiDiff; + + // Soft Enrage at 5% + if (!m_bEnraged) + { + if (m_creature->GetHealthPercent() < 5.0f) + { + if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) + { + DoScriptText(EMOTE_GENERIC_ENRAGED, m_creature); + m_bEnraged = true; + } + } + } + + // Berserk after 7 minutes + if (!m_bBerserk) + { + if (m_uiBerserkTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK) + { + DoScriptText(EMOTE_GENERIC_BERSERK, m_creature); + m_bBerserk = true; + } + } + else + m_uiBerserkTimer -= uiDiff; + } + else if (m_uiBerserkSlimeBoltTimer < uiDiff) + { + // Slimebolt - casted only 30 seconds after Berserking to prevent kiting + if (m_uiSlimeboltTimer < uiDiff) + { + DoCastSpellIfCan(m_creature->getVictim(), SPELL_SLIMEBOLT); + m_uiSlimeboltTimer = 1000; + } + else + m_uiSlimeboltTimer -= uiDiff; + } + + DoMeleeAttackIfReady(); + } +}; + +CreatureAI* GetAI_boss_patchwerk(Creature* pCreature) +{ + return new boss_patchwerkAI(pCreature); +} + +void AddSC_boss_patchwerk() +{ + Script* pNewScript; + + pNewScript = new Script; + pNewScript->Name = "boss_patchwerk"; + pNewScript->GetAI = &GetAI_boss_patchwerk; + pNewScript->RegisterSelf(); +} diff --git a/pool/shard001/C++/0018876_table.cpp b/pool/shard001/C++/0018876_table.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0552d3458a3e91536c99de8623448b9180266ee --- /dev/null +++ b/pool/shard001/C++/0018876_table.cpp @@ -0,0 +1,54 @@ +/* + Copyright 2016 Massachusetts Institute of Technology + + 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 "global.h" +#include "helper.h" +#include "table.h" +#include "catalog.h" +#include "row.h" +#include "mem_alloc.h" + +void table_t::init(Catalog * schema) { + this->table_name = schema->table_name; + this->table_id = schema->table_id; + this->schema = schema; + cur_tab_size = new uint64_t; + // isolate cur_tab_size with other parameters. + // Because cur_tab_size is frequently updated, causing false + // sharing problems + char * ptr = new char[CL_SIZE*2 + sizeof(uint64_t)]; + cur_tab_size = (uint64_t *) &ptr[CL_SIZE]; +} + +RC table_t::get_new_row(row_t *& row) { + // this function is obsolete. + assert(false); + return RCOK; +} + +// the row is not stored locally. the pointer must be maintained by index structure. +RC table_t::get_new_row(row_t *& row, uint64_t part_id, uint64_t &row_id) { + RC rc = RCOK; + DEBUG_M("table_t::get_new_row alloc\n"); + void * ptr = mem_allocator.alloc(sizeof(row_t)); + assert (ptr != NULL); + + row = (row_t *) ptr; + rc = row->init(this, part_id, row_id); + row->init_manager(row); + + return rc; +} diff --git a/pool/shard001/C++/0018878_CWE23_Relative_Path_Traversal__char_file_ifstream_68a.cpp b/pool/shard001/C++/0018878_CWE23_Relative_Path_Traversal__char_file_ifstream_68a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2527acd9c8d23a459592ae26f4dbb92c7f19a766 --- /dev/null +++ b/pool/shard001/C++/0018878_CWE23_Relative_Path_Traversal__char_file_ifstream_68a.cpp @@ -0,0 +1,130 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE23_Relative_Path_Traversal__char_file_ifstream_68a.cpp +Label Definition File: CWE23_Relative_Path_Traversal.label.xml +Template File: sources-sink-68a.tmpl.cpp +*/ +/* + * @description + * CWE: 23 Relative Path Traversal + * BadSource: file Read input from a file + * GoodSource: Use a fixed file name + * Sink: ifstream + * BadSink : Open the file named in data using ifstream::open() + * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#define BASEPATH "c:\\temp\\" +#else +#include +#define BASEPATH "/tmp/" +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#include +using namespace std; + +char * CWE23_Relative_Path_Traversal__char_file_ifstream_68_badData; +char * CWE23_Relative_Path_Traversal__char_file_ifstream_68_goodG2BData; + +namespace CWE23_Relative_Path_Traversal__char_file_ifstream_68 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(); + +void bad() +{ + char * data; + char dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + { + /* Read input from a file */ + size_t dataLen = strlen(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 (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + fclose(pFile); + } + } + } + CWE23_Relative_Path_Traversal__char_file_ifstream_68_badData = data; + badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ +void goodG2BSink(); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + char dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + /* FIX: Use a fixed file name */ + strcat(data, "file.txt"); + CWE23_Relative_Path_Traversal__char_file_ifstream_68_goodG2BData = data; + goodG2BSink(); +} + +void good() +{ + goodG2B(); +} + +#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__char_file_ifstream_68; /* 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/shard001/C++/0018888_ref-params.cc b/pool/shard001/C++/0018888_ref-params.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b26549c660d5e48906675a8716d6e47da2527af --- /dev/null +++ b/pool/shard001/C++/0018888_ref-params.cc @@ -0,0 +1,78 @@ +/* This test script is part of GDB, the GNU debugger. + + Copyright 2006, 2007 Free Software Foundation, Inc. + + 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 . + */ + +/* Author: Paul N. Hilfinger, AdaCore Inc. */ + +struct Parent { + Parent (int id0) : id(id0) { } + int id; +}; + +struct Child : public Parent { + Child (int id0) : Parent(id0) { } +}; + +int f1(Parent& R) +{ + return R.id; /* Set breakpoint marker3 here. */ +} + +int f2(Child& C) +{ + return f1(C); /* Set breakpoint marker2 here. */ +} + +struct OtherParent { + OtherParent (int other_id0) : other_id(other_id0) { } + int other_id; +}; + +struct MultiChild : public Parent, OtherParent { + MultiChild (int id0) : Parent(id0), OtherParent(id0 * 2) { } +}; + +int mf1(OtherParent& R) +{ + return R.other_id; +} + +int mf2(MultiChild& C) +{ + return mf1(C); +} + +int main(void) +{ + Child Q(42); + Child& QR = Q; + + #ifdef usestubs + set_debug_traps(); + breakpoint(); + #endif + + /* Set breakpoint marker1 here. */ + + f2(Q); + f2(QR); + + MultiChild MQ(53); + MultiChild& MQR = MQ; + + mf2(MQ); /* Set breakpoint MQ here. */ +} diff --git a/pool/shard001/C++/0018896_worker_permission_client_proxy.cc b/pool/shard001/C++/0018896_worker_permission_client_proxy.cc new file mode 100644 index 0000000000000000000000000000000000000000..e024935fe940b0ff531af676380c1204912aa918 --- /dev/null +++ b/pool/shard001/C++/0018896_worker_permission_client_proxy.cc @@ -0,0 +1,63 @@ +// 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/common/render_messages.h" +#include "chrome/renderer/worker_permission_client_proxy.h" +#include "content/public/renderer/render_thread.h" +#include "content/public/renderer/render_view.h" +#include "ipc/ipc_sync_message_filter.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebSecurityOrigin.h" + +WorkerPermissionClientProxy::WorkerPermissionClientProxy( + content::RenderView* render_view, + blink::WebFrame* frame) + : routing_id_(render_view->GetRoutingID()), + is_unique_origin_(false) { + if (frame->document().securityOrigin().isUnique() || + frame->top()->document().securityOrigin().isUnique()) + is_unique_origin_ = true; + sync_message_filter_ = content::RenderThread::Get()->GetSyncMessageFilter(); + document_origin_url_ = GURL(frame->document().securityOrigin().toString()); + top_frame_origin_url_ = GURL( + frame->top()->document().securityOrigin().toString()); +} + +WorkerPermissionClientProxy::~WorkerPermissionClientProxy() {} + +bool WorkerPermissionClientProxy::allowDatabase( + const blink::WebString& name, + const blink::WebString& display_name, + unsigned long estimated_size) { + if (is_unique_origin_) + return false; + + bool result = false; + sync_message_filter_->Send(new ChromeViewHostMsg_AllowDatabase( + routing_id_, document_origin_url_, top_frame_origin_url_, + name, display_name, &result)); + return result; +} + +bool WorkerPermissionClientProxy::allowFileSystem() { + if (is_unique_origin_) + return false; + + bool result = false; + sync_message_filter_->Send(new ChromeViewHostMsg_AllowFileSystem( + routing_id_, document_origin_url_, top_frame_origin_url_, &result)); + return result; +} + +bool WorkerPermissionClientProxy::allowIndexedDB( + const blink::WebString& name) { + if (is_unique_origin_) + return false; + + bool result = false; + sync_message_filter_->Send(new ChromeViewHostMsg_AllowIndexedDB( + routing_id_, document_origin_url_, top_frame_origin_url_, name, &result)); + return result; +} diff --git a/pool/shard001/C++/0018921_4.cc b/pool/shard001/C++/0018921_4.cc new file mode 100644 index 0000000000000000000000000000000000000000..f73e8bffadccecbc5c028de7ca679e5238e31273 --- /dev/null +++ b/pool/shard001/C++/0018921_4.cc @@ -0,0 +1,39 @@ +// Copyright (C) 2005-2016 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 +// . + +// sequence_buffer (SGI extension) + +#include +#include +#include + +void test01() +{ + bool test __attribute__((unused)) = true; + + __gnu_cxx::crope r1("wibble"); + __gnu_cxx::crope r2; + std::copy( r1.begin(), r1.end(), + __gnu_cxx::sequence_buffer<__gnu_cxx::crope>(r2) ); + VERIFY( r1 == r2 ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard001/C++/0018933_CParseHandlerPhysicalCTAS.cpp b/pool/shard001/C++/0018933_CParseHandlerPhysicalCTAS.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb47bb235d479b943f2fc1ebde3cdff2a3defad0 --- /dev/null +++ b/pool/shard001/C++/0018933_CParseHandlerPhysicalCTAS.cpp @@ -0,0 +1,219 @@ +//--------------------------------------------------------------------------- +// Greenplum Database +// Copyright (C) 2014 Pivotal Inc +// +// @filename: +// CParseHandlerPhysicalCTAS.cpp +// +// @doc: +// Implementation of the SAX parse handler class for parsing physical +// CTAS operators. +//--------------------------------------------------------------------------- + +#include "naucrates/dxl/parser/CParseHandlerPhysicalCTAS.h" + +#include "naucrates/dxl/parser/CParseHandlerColDescr.h" +#include "naucrates/dxl/parser/CParseHandlerCtasStorageOptions.h" +#include "naucrates/dxl/parser/CParseHandlerProjList.h" +#include "naucrates/dxl/parser/CParseHandlerProperties.h" +#include "naucrates/dxl/parser/CParseHandlerUtils.h" + +#include "naucrates/dxl/parser/CParseHandlerFactory.h" + +#include "naucrates/dxl/operators/CDXLOperatorFactory.h" + +using namespace gpdxl; + + +XERCES_CPP_NAMESPACE_USE + +//--------------------------------------------------------------------------- +// @function: +// CParseHandlerPhysicalCTAS::CParseHandlerPhysicalCTAS +// +// @doc: +// Ctor +// +//--------------------------------------------------------------------------- +CParseHandlerPhysicalCTAS::CParseHandlerPhysicalCTAS + ( + IMemoryPool *pmp, + CParseHandlerManager *pphm, + CParseHandlerBase *pphRoot + ) + : + CParseHandlerPhysicalOp(pmp, pphm, pphRoot), + m_pmdnameSchema(NULL), + m_pmdname(NULL), + m_pdrgpulDistr(NULL), + m_pdrgpulSource(NULL), + m_fTemporary(false), + m_fHasOids(false) +{ +} + +//--------------------------------------------------------------------------- +// @function: +// CParseHandlerPhysicalCTAS::StartElement +// +// @doc: +// Invoked by Xerces to process an opening tag +// +//--------------------------------------------------------------------------- +void +CParseHandlerPhysicalCTAS::StartElement + ( + const XMLCh* const, // xmlszUri, + const XMLCh* const xmlszLocalname, + const XMLCh* const, // xmlszQname + const Attributes &attrs + ) +{ + if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenPhysicalCTAS), xmlszLocalname)) + { + CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); + GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); + } + + // parse table name + const XMLCh *xmlszTableName = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenName, EdxltokenPhysicalCTAS); + m_pmdname = CDXLUtils::PmdnameFromXmlsz(m_pphm->Pmm(), xmlszTableName); + + const XMLCh *xmlszSchema = attrs.getValue(CDXLTokens::XmlstrToken(EdxltokenSchema)); + if (NULL != xmlszSchema) + { + m_pmdnameSchema = CDXLUtils::PmdnameFromXmlsz(m_pphm->Pmm(), xmlszSchema); + } + + // parse distribution policy + const XMLCh *xmlszDistrPolicy = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenRelDistrPolicy, EdxltokenPhysicalCTAS); + m_ereldistrpolicy = CDXLOperatorFactory::EreldistrpolicyFromXmlstr(xmlszDistrPolicy); + + if (IMDRelation::EreldistrHash == m_ereldistrpolicy) + { + // parse distribution columns + const XMLCh *xmlszDistrColumns = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenDistrColumns, EdxltokenPhysicalCTAS); + m_pdrgpulDistr = CDXLOperatorFactory::PdrgpulFromXMLCh(m_pphm->Pmm(), xmlszDistrColumns, EdxltokenDistrColumns, EdxltokenPhysicalCTAS); + } + + // parse storage type + const XMLCh *xmlszStorage = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenRelStorageType, EdxltokenPhysicalCTAS); + m_erelstorage = CDXLOperatorFactory::ErelstoragetypeFromXmlstr(xmlszStorage); + + const XMLCh *xmlszSourceColIds = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenInsertCols, EdxltokenPhysicalCTAS); + m_pdrgpulSource = CDXLOperatorFactory::PdrgpulFromXMLCh(m_pphm->Pmm(), xmlszSourceColIds, EdxltokenInsertCols, EdxltokenPhysicalCTAS); + + const XMLCh *xmlszVarTypeMod = CDXLOperatorFactory::XmlstrFromAttrs(attrs, EdxltokenVarTypeModList, EdxltokenPhysicalCTAS); + m_pdrgpiVarTypeMod = + CDXLOperatorFactory::PdrgpiFromXMLCh(m_pphm->Pmm(), xmlszVarTypeMod, EdxltokenVarTypeModList, EdxltokenPhysicalCTAS); + + m_fTemporary = CDXLOperatorFactory::FValueFromAttrs(m_pphm->Pmm(), attrs, EdxltokenRelTemporary, EdxltokenPhysicalCTAS); + m_fHasOids = CDXLOperatorFactory::FValueFromAttrs(m_pphm->Pmm(), attrs, EdxltokenRelHasOids, EdxltokenPhysicalCTAS); + + // create child node parsers + + // parse handler for logical operator + CParseHandlerBase *pphChild = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenLogical), m_pphm, this); + m_pphm->ActivateParseHandler(pphChild); + + // parse handler for the proj list + CParseHandlerBase *pphPrL = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenScalarProjList), m_pphm, this); + m_pphm->ActivateParseHandler(pphPrL); + + //parse handler for the storage options + CParseHandlerBase *pphCTASOptions = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenCTASOptions), m_pphm, this); + m_pphm->ActivateParseHandler(pphCTASOptions); + + //parse handler for the column descriptors + CParseHandlerBase *pphColDescr = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenColumns), m_pphm, this); + m_pphm->ActivateParseHandler(pphColDescr); + + //parse handler for the properties of the operator + CParseHandlerBase *pphProp = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenProperties), m_pphm, this); + m_pphm->ActivateParseHandler(pphProp); + + // store child parse handler in array + this->Append(pphProp); + this->Append(pphColDescr); + this->Append(pphCTASOptions); + this->Append(pphPrL); + this->Append(pphChild); +} + +//--------------------------------------------------------------------------- +// @function: +// CParseHandlerPhysicalCTAS::EndElement +// +// @doc: +// Invoked by Xerces to process a closing tag +// +//--------------------------------------------------------------------------- +void +CParseHandlerPhysicalCTAS::EndElement + ( + const XMLCh* const, // xmlszUri, + const XMLCh* const xmlszLocalname, + const XMLCh* const // xmlszQname + ) +{ + if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenPhysicalCTAS), xmlszLocalname)) + { + CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname); + GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz()); + } + + GPOS_ASSERT(5 == this->UlLength()); + + CParseHandlerProperties *pphProp = dynamic_cast((*this)[0]); + CParseHandlerColDescr *pphColDescr = dynamic_cast((*this)[1]); + CParseHandlerCtasStorageOptions *pphCTASOptions = dynamic_cast((*this)[2]); + CParseHandlerProjList *pphPrL = dynamic_cast((*this)[3]); + GPOS_ASSERT(NULL != pphPrL->Pdxln()); + CParseHandlerPhysicalOp *pphChild = dynamic_cast((*this)[4]); + + GPOS_ASSERT(NULL != pphProp->Pdxlprop()); + GPOS_ASSERT(NULL != pphColDescr->Pdrgpdxlcd()); + GPOS_ASSERT(NULL != pphCTASOptions->Pdxlctasopt()); + GPOS_ASSERT(NULL != pphPrL->Pdxln()); + GPOS_ASSERT(NULL != pphChild->Pdxln()); + + DrgPdxlcd *pdrgpdxlcd = pphColDescr->Pdrgpdxlcd(); + pdrgpdxlcd->AddRef(); + + CDXLCtasStorageOptions *pdxlctasopt = pphCTASOptions->Pdxlctasopt(); + pdxlctasopt->AddRef(); + + m_pdxln = GPOS_NEW(m_pmp) CDXLNode + ( + m_pmp, + GPOS_NEW(m_pmp) CDXLPhysicalCTAS + ( + m_pmp, + m_pmdnameSchema, + m_pmdname, + pdrgpdxlcd, + pdxlctasopt, + m_ereldistrpolicy, + m_pdrgpulDistr, + m_fTemporary, + m_fHasOids, + m_erelstorage, + m_pdrgpulSource, + m_pdrgpiVarTypeMod + ) + ); + // set statistics and physical properties + CParseHandlerUtils::SetProperties(m_pdxln, pphProp); + + AddChildFromParseHandler(pphPrL); + AddChildFromParseHandler(pphChild); + +#ifdef GPOS_DEBUG + m_pdxln->Pdxlop()->AssertValid(m_pdxln, false /* fValidateChildren */); +#endif // GPOS_DEBUG + + // deactivate handler + m_pphm->DeactivateHandler(); +} + +// EOF diff --git a/pool/shard001/C++/0018945_mp_alerts_options.cpp b/pool/shard001/C++/0018945_mp_alerts_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..654a6bacf8b6c841f649b8cbdca511ef0e92ac70 --- /dev/null +++ b/pool/shard001/C++/0018945_mp_alerts_options.cpp @@ -0,0 +1,161 @@ +/* + Copyright (C) 2014 - 2016 by Chris Beck + Part of the Battle for Wesnoth Project http://www.wesnoth.org/ + + 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. + + See the COPYING file for more details. +*/ + +#define GETTEXT_DOMAIN "wesnoth-lib" + +#include "gui/dialogs/multiplayer/mp_alerts_options.hpp" + +#include "desktop/notifications.hpp" +#include "gui/auxiliary/find_widget.hpp" +#include "gui/dialogs/message.hpp" +#include "gui/widgets/button.hpp" +#include "gui/widgets/label.hpp" +#include "gui/widgets/settings.hpp" +#include "gui/widgets/toggle_button.hpp" +#include "gui/widgets/window.hpp" + +#include "mp_ui_alerts.hpp" +#include "preferences.hpp" +#include "formula/string_utils.hpp" + +#include "utils/functional.hpp" + +#include "gettext.hpp" + +namespace gui2 +{ +namespace dialogs +{ +/*WIKI + * @page = GUIWindowDefinitionWML + * @order = 2_mp_alerts_options + * + * == Lobby sounds options == + * + * A Preferences subdialog permitting to configure the sounds and notifications + * generated in response to various mp lobby / game events. + * + * @begin{table}{dialog_widgets} + * + * _label & & label & m & + * Item name. $ + * + * _sound & & toggle_button & m & + * Toggles whether to play the item sound. $ + * + * _notif & & toggle_button & m & + * Toggles whether to give a notification. $ + * + * _lobby & & toggle_button & m & + * Toggles whether to take actions for this item when in the lobby. $ + * + * @end{table} + */ + +static toggle_button * setup_pref_toggle_button(const std::string & id, bool def, window & window) +{ + toggle_button * b = &find_widget(&window, id, false); + b->set_value(preferences::get(id, def)); + + //ensure we have yes / no for the toggle button, so that the preference matches the toggle button for sure. + if (preferences::get(id).size() == 0) { + preferences::set(id, def); + } + + //Needed to disambiguate overloaded function + void (*set) (const std::string &, bool) = &preferences::set; + + connect_signal_mouse_left_click(*b, std::bind(set, id, std::bind(&toggle_button::get_value_bool, b))); + + return b; +} + +static void setup_item(const std::string & item, window & window) +{ + // Set up the sound checkbox + setup_pref_toggle_button(item+"_sound", mp_ui_alerts::get_def_pref_sound(item), window); + + // Set up the notification checkbox + toggle_button * notif = setup_pref_toggle_button(item+"_notif", mp_ui_alerts::get_def_pref_notif(item), window); + + // Check if desktop notifications are available + if (!desktop::notifications::available()) { + notif->set_value(false); + notif->set_active(false); + preferences::set(item+"_notif", false); + } else { + notif->set_active(true); + } + + // Set up the in_lobby checkbox + setup_pref_toggle_button(item+"_lobby", mp_ui_alerts::get_def_pref_lobby(item), window); +} + +static void set_pref_and_button(const std::string & id, bool value, window & window) +{ + preferences::set(id,value); + toggle_button * button = &find_widget(&window, id, false); + button->set_value(value); +} + +static void revert_to_default_pref_values(window & window) +{ + for (const std::string & i : mp_ui_alerts::items) { + set_pref_and_button(i+"_sound", mp_ui_alerts::get_def_pref_sound(i), window); + set_pref_and_button(i+"_notif", mp_ui_alerts::get_def_pref_notif(i), window); + set_pref_and_button(i+"_lobby", mp_ui_alerts::get_def_pref_lobby(i), window); + } +} + +REGISTER_DIALOG(mp_alerts_options) + +mp_alerts_options::mp_alerts_options() +{ +} + +void mp_alerts_options::pre_show(window& window) +{ + for (const std::string & i : mp_ui_alerts::items) { + setup_item(i, window); + } + + if (!desktop::notifications::available()) { + label * nlabel = &find_widget