diff --git a/pool/shard006/C++/0078449_pagelocker.cpp b/pool/shard006/C++/0078449_pagelocker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..246571eee07e189f14de86d243c2dd3d1601a697 --- /dev/null +++ b/pool/shard006/C++/0078449_pagelocker.cpp @@ -0,0 +1,70 @@ +// Copyright (c) 2009-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. + +#include "support/pagelocker.h" + +#if defined(HAVE_CONFIG_H) +#include "config/mxn-config.h" +#endif + +#ifdef WIN32 +#ifdef _WIN32_WINNT +#undef _WIN32_WINNT +#endif +#define _WIN32_WINNT 0x0501 +#define WIN32_LEAN_AND_MEAN 1 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +// This is used to attempt to keep keying material out of swap +// Note that VirtualLock does not provide this as a guarantee on Windows, +// but, in practice, memory that has been VirtualLock'd almost never gets written to +// the pagefile except in rare circumstances where memory is extremely low. +#else +#include +#include // for PAGESIZE +#include // for sysconf +#endif + +LockedPageManager* LockedPageManager::_instance = NULL; +boost::once_flag LockedPageManager::init_flag = BOOST_ONCE_INIT; + +/** Determine system page size in bytes */ +static inline size_t GetSystemPageSize() +{ + size_t page_size; +#if defined(WIN32) + SYSTEM_INFO sSysInfo; + GetSystemInfo(&sSysInfo); + page_size = sSysInfo.dwPageSize; +#elif defined(PAGESIZE) // defined in limits.h + page_size = PAGESIZE; +#else // assume some POSIX OS + page_size = sysconf(_SC_PAGESIZE); +#endif + return page_size; +} + +bool MemoryPageLocker::Lock(const void* addr, size_t len) +{ +#ifdef WIN32 + return VirtualLock(const_cast(addr), len) != 0; +#else + return mlock(addr, len) == 0; +#endif +} + +bool MemoryPageLocker::Unlock(const void* addr, size_t len) +{ +#ifdef WIN32 + return VirtualUnlock(const_cast(addr), len) != 0; +#else + return munlock(addr, len) == 0; +#endif +} + +LockedPageManager::LockedPageManager() : LockedPageManagerBase(GetSystemPageSize()) +{ +} diff --git a/pool/shard006/C++/0078462_memory_details_android.cc b/pool/shard006/C++/0078462_memory_details_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..056e718ea9d02f6d34ea8f310119feb69a3b936e --- /dev/null +++ b/pool/shard006/C++/0078462_memory_details_android.cc @@ -0,0 +1,142 @@ +// 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/memory_details.h" + +#include +#include +#include + +#include "base/bind.h" +#include "base/memory/scoped_ptr.h" +#include "base/process/process_iterator.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/common/chrome_constants.h" +#include "chrome/grit/chromium_strings.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/common/process_type.h" +#include "ui/base/l10n/l10n_util.h" + +using base::ProcessEntry; +using base::ProcessId; +using content::BrowserThread; + +namespace { + +// A helper for |CollectProcessData()| to include the chrome sandboxed +// processes in android which are not running as a child of the browser +// process. +void AddNonChildChromeProcesses( + std::vector* processes) { + base::ProcessIterator process_iter(NULL); + while (const ProcessEntry* process_entry = process_iter.NextProcessEntry()) { + const std::vector& cmd_args = process_entry->cmd_line_args(); + if (cmd_args.empty() || + cmd_args[0].find(chrome::kHelperProcessExecutableName) == + std::string::npos) { + continue; + } + ProcessMemoryInformation info; + info.pid = process_entry->pid(); + processes->push_back(info); + } +} + +// For each of the pids, collect memory information about that process +// and append a record to |out|. +void GetProcessDataMemoryInformation( + const std::set& pids, ProcessData* out) { + for (std::set::const_iterator i = pids.begin(); i != pids.end(); + ++i) { + ProcessMemoryInformation pmi; + + pmi.pid = *i; + pmi.num_processes = 1; + + if (pmi.pid == base::GetCurrentProcId()) + pmi.process_type = content::PROCESS_TYPE_BROWSER; + else + pmi.process_type = content::PROCESS_TYPE_UNKNOWN; + + scoped_ptr metrics( + base::ProcessMetrics::CreateProcessMetrics(*i)); + metrics->GetWorkingSetKBytes(&pmi.working_set); + + out->processes.push_back(pmi); + } +} + +// Find all children of the given process. +void GetAllChildren(const std::vector& processes, + const std::set& roots, + std::set* out) { + *out = roots; + + std::set wavefront; + for (std::set::const_iterator i = roots.begin(); i != roots.end(); + ++i) { + wavefront.insert(*i); + } + + while (wavefront.size()) { + std::set next_wavefront; + for (std::vector::const_iterator i = processes.begin(); + i != processes.end(); ++i) { + if (wavefront.count(i->parent_pid())) { + out->insert(i->pid()); + next_wavefront.insert(i->pid()); + } + } + + wavefront.clear(); + wavefront.swap(next_wavefront); + } +} + +} // namespace + +MemoryDetails::MemoryDetails() + : user_metrics_mode_(UPDATE_USER_METRICS), + memory_growth_tracker_(NULL) { +} + +ProcessData* MemoryDetails::ChromeBrowser() { + return &process_data_[0]; +} + +void MemoryDetails::CollectProcessData( + const std::vector& chrome_processes) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); + + std::vector all_processes(chrome_processes); + AddNonChildChromeProcesses(&all_processes); + + std::vector processes; + base::ProcessIterator process_iter(NULL); + while (const ProcessEntry* process_entry = process_iter.NextProcessEntry()) { + processes.push_back(*process_entry); + } + + std::set roots; + roots.insert(base::GetCurrentProcId()); + for (std::vector::const_iterator + i = all_processes.begin(); i != all_processes.end(); ++i) { + roots.insert(i->pid); + } + + std::set current_browser_processes; + GetAllChildren(processes, roots, ¤t_browser_processes); + + ProcessData current_browser; + GetProcessDataMemoryInformation(current_browser_processes, ¤t_browser); + current_browser.name = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); + current_browser.process_name = + base::ASCIIToUTF16(chrome::kBrowserProcessExecutableName); + process_data_.push_back(current_browser); + + // Finally return to the browser thread. + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&MemoryDetails::CollectChildInfoOnUIThread, this)); +} diff --git a/pool/shard006/C++/0078464_native_test_launcher.cc b/pool/shard006/C++/0078464_native_test_launcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f880a741a66933441dccc7ff548ce7bbccf66e3 --- /dev/null +++ b/pool/shard006/C++/0078464_native_test_launcher.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. + +// This class sets up the environment for running the native tests inside an +// android application. It outputs (to a fifo) markers identifying the +// START/PASSED/CRASH of the test suite, FAILURE/SUCCESS of individual tests, +// etc. +// These markers are read by the test runner script to generate test results. +// It installs signal handlers to detect crashes. + +#include +#include + +#include "base/android/base_jni_registrar.h" +#include "base/android/context_utils.h" +#include "base/android/fifo_utils.h" +#include "base/android/jni_string.h" +#include "base/android/scoped_java_ref.h" +#include "base/at_exit.h" +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/strings/stringprintf.h" +#include "gtest/gtest.h" +#include "jni/NativeTestActivity_jni.h" +#include "testing/android/native_test/native_test_util.h" + +// The main function of the program to be wrapped as a test apk. +extern int main(int argc, char** argv); + +namespace testing { +namespace android { + +namespace { + +const char kLogTag[] = "chromium"; +const char kCrashedMarker[] = "[ CRASHED ]\n"; + +// The list of signals which are considered to be crashes. +const int kExceptionSignals[] = { + SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1 +}; + +struct sigaction g_old_sa[NSIG]; + +// This function runs in a compromised context. It should not allocate memory. +void SignalHandler(int sig, siginfo_t* info, void* reserved) { + // Output the crash marker. + write(STDOUT_FILENO, kCrashedMarker, sizeof(kCrashedMarker)); + g_old_sa[sig].sa_sigaction(sig, info, reserved); +} + +// Writes printf() style string to Android's logger where |priority| is one of +// the levels defined in . +void AndroidLog(int priority, const char* format, ...) { + va_list args; + va_start(args, format); + __android_log_vprint(priority, kLogTag, format, args); + va_end(args); +} + +} // namespace + +static void RunTests(JNIEnv* env, + const JavaParamRef& obj, + const JavaParamRef& jcommand_line_flags, + const JavaParamRef& jcommand_line_file_path, + const JavaParamRef& jstdout_file_path, + jboolean jstdout_fifo, + const JavaParamRef& app_context) { + // Command line initialized basically, will be fully initialized later. + static const char* const kInitialArgv[] = { "ChromeTestActivity" }; + base::CommandLine::Init(arraysize(kInitialArgv), kInitialArgv); + + std::vector args; + + const std::string command_line_file_path( + base::android::ConvertJavaStringToUTF8(env, jcommand_line_file_path)); + if (command_line_file_path.empty()) + args.push_back("_"); + else + ParseArgsFromCommandLineFile(command_line_file_path.c_str(), &args); + + const std::string command_line_flags( + base::android::ConvertJavaStringToUTF8(env, jcommand_line_flags)); + ParseArgsFromString(command_line_flags, &args); + + std::vector argv; + int argc = ArgsToArgv(args, &argv); + + // Fully initialize command line with arguments. + base::CommandLine::ForCurrentProcess()->AppendArguments( + base::CommandLine(argc, &argv[0]), false); + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + + base::FilePath stdout_file_path( + base::android::ConvertJavaStringToUTF8(env, jstdout_file_path)); + + // A few options, such "--gtest_list_tests", will just use printf directly + // Always redirect stdout to a known file. + unlink(stdout_file_path.value().c_str()); + if (jstdout_fifo) { + if (!base::android::CreateFIFO(stdout_file_path, 0666)) { + AndroidLog(ANDROID_LOG_ERROR, "Failed to create fifo %s: %s\n", + stdout_file_path.value().c_str(), strerror(errno)); + exit(EXIT_FAILURE); + } + } + if (!base::android::RedirectStream(stdout, stdout_file_path, "w+")) { + AndroidLog(ANDROID_LOG_ERROR, "Failed to redirect stream to file: %s: %s\n", + stdout_file_path.value().c_str(), strerror(errno)); + exit(EXIT_FAILURE); + } + dup2(STDOUT_FILENO, STDERR_FILENO); + + if (command_line.HasSwitch(switches::kWaitForDebugger)) { + AndroidLog(ANDROID_LOG_VERBOSE, + "Native test waiting for GDB because flag %s was supplied", + switches::kWaitForDebugger); + base::debug::WaitForDebugger(24 * 60 * 60, false); + } + + ScopedMainEntryLogger scoped_main_entry_logger; + main(argc, &argv[0]); +} + +bool RegisterNativeTestJNI(JNIEnv* env) { + if (!base::android::RegisterJni(env)) { + return false; + } + return RegisterNativesImpl(env); +} + +// TODO(nileshagrawal): now that we're using FIFO, test scripts can detect EOF. +// Remove the signal handlers. +void InstallHandlers() { + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + + sa.sa_sigaction = SignalHandler; + sa.sa_flags = SA_SIGINFO; + + for (unsigned int i = 0; kExceptionSignals[i] != -1; ++i) { + sigaction(kExceptionSignals[i], &sa, &g_old_sa[kExceptionSignals[i]]); + } +} + +} // namespace android +} // namespace testing diff --git a/pool/shard006/C++/0078473_instantiation_test.cpp b/pool/shard006/C++/0078473_instantiation_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67fe89bfca7bfebebc2d5e2ade22649e0f38c788 --- /dev/null +++ b/pool/shard006/C++/0078473_instantiation_test.cpp @@ -0,0 +1,81 @@ +#include"all_defines.hpp" +#include"objects.hpp" +#include"heaps.hpp" +#include"types.hpp" + +#include +#include + +class MyHeap : public Heap { +protected: + virtual void scan_root_object(GenericTraverser* gt) { + gt->traverse(r0); + gt->traverse(r1); + } +public: + Object::ref r0; + Object::ref r1; + explicit MyHeap(size_t sz) : Heap(sz) { } +}; + +class HlError { +public: + char const* val; + explicit HlError(char const* nval) : val(nval) { } +}; + +void throw_HlError(char const* t) { + throw HlError(t); +} + +class OverBrokenHeart { +public: + Generic* cause; + explicit OverBrokenHeart(Generic* ncause) : cause(ncause) { } +}; + +void throw_OverBrokenHeart(Generic* cause) { + throw OverBrokenHeart(cause); +} + +struct RangeError { +}; +struct TypeError { +}; + +void throw_RangeError(const char*) { + throw RangeError(); +} +void throw_TypeError(Object::ref, const char*) { + throw TypeError(); +} + +struct DeallocError { +}; + +void throw_DeallocError(void*) { + throw DeallocError(); +} + +int main(void) { + MyHeap tmp(sizeof(Cons)); + + std::cout << "allocating 1st" << std::endl; + tmp.r0 = Object::to_ref(tmp.create()); + std::cout << "r0 = @" << as_a(tmp.r0) << std::endl; + + std::cout << "allocating 2nd" << std::endl; + tmp.r1 = Object::to_ref(tmp.create()); + scar(tmp.r1, tmp.r0); + std::cout << "r0 = @" << as_a(tmp.r0) << std::endl; + std::cout << "r1 = @" << as_a(tmp.r1) << std::endl; + assert(car(tmp.r1) == tmp.r0); + + std::cout << "allocating 3rd" << std::endl; + tmp.r1 = Object::to_ref(tmp.create()); + scdr(tmp.r0, tmp.r1); + std::cout << "r0 = @" << as_a(tmp.r0) << std::endl; + std::cout << "r1 = @" << as_a(tmp.r1) << std::endl; + assert(cdr(tmp.r0) == tmp.r1); +} + diff --git a/pool/shard006/C++/0078478_moc_vscvideowall.cpp b/pool/shard006/C++/0078478_moc_vscvideowall.cpp new file mode 100644 index 0000000000000000000000000000000000000000..201e9d434829639e21410eb31fe5fa6d3a7fec87 --- /dev/null +++ b/pool/shard006/C++/0078478_moc_vscvideowall.cpp @@ -0,0 +1,216 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'vscvideowall.h' +** +** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.2) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../../../vwidget/vscvideowall.h" +#include +#include +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'vscvideowall.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 67 +#error "This file was generated using the moc from 5.0.2. 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 +struct qt_meta_stringdata_VSCVideoWall_t { + QByteArrayData data[15]; + char stringdata[224]; +}; +#define QT_MOC_LITERAL(idx, ofs, len) \ + Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ + offsetof(qt_meta_stringdata_VSCVideoWall_t, stringdata) + ofs \ + - idx * sizeof(QByteArrayData) \ + ) +static const qt_meta_stringdata_VSCVideoWall_t qt_meta_stringdata_VSCVideoWall = { + { +QT_MOC_LITERAL(0, 0, 12), +QT_MOC_LITERAL(1, 13, 18), +QT_MOC_LITERAL(2, 32, 0), +QT_MOC_LITERAL(3, 33, 3), +QT_MOC_LITERAL(4, 37, 19), +QT_MOC_LITERAL(5, 57, 17), +QT_MOC_LITERAL(6, 75, 16), +QT_MOC_LITERAL(7, 92, 14), +QT_MOC_LITERAL(8, 107, 16), +QT_MOC_LITERAL(9, 124, 16), +QT_MOC_LITERAL(10, 141, 16), +QT_MOC_LITERAL(11, 158, 16), +QT_MOC_LITERAL(12, 175, 14), +QT_MOC_LITERAL(13, 190, 17), +QT_MOC_LITERAL(14, 208, 14) + }, + "VSCVideoWall\0ShowDisplayClicked\0\0nId\0" + "ShowFloatingClicked\0ShowTabbedClicked\0" + "ShowFocusClicked\0floatingAction\0" + "unFloatingAction\0SetLayoutMode4x4\0" + "SetLayoutMode3x3\0SetLayoutMode2x2\0" + "SetLayoutMode6\0SetLayoutMode12p1\0" + "SetLayoutMode1\0" +}; +#undef QT_MOC_LITERAL + +static const uint qt_meta_data_VSCVideoWall[] = { + + // content: + 7, // revision + 0, // classname + 0, 0, // classinfo + 12, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 4, // signalCount + + // signals: name, argc, parameters, tag, flags + 1, 1, 74, 2, 0x05, + 4, 0, 77, 2, 0x05, + 5, 0, 78, 2, 0x05, + 6, 1, 79, 2, 0x05, + + // slots: name, argc, parameters, tag, flags + 7, 0, 82, 2, 0x0a, + 8, 0, 83, 2, 0x0a, + 9, 0, 84, 2, 0x0a, + 10, 0, 85, 2, 0x0a, + 11, 0, 86, 2, 0x0a, + 12, 0, 87, 2, 0x0a, + 13, 0, 88, 2, 0x0a, + 14, 0, 89, 2, 0x0a, + + // signals: parameters + QMetaType::Void, QMetaType::Int, 3, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, QMetaType::Int, 3, + + // slots: parameters + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + + 0 // eod +}; + +void VSCVideoWall::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + VSCVideoWall *_t = static_cast(_o); + switch (_id) { + case 0: _t->ShowDisplayClicked((*reinterpret_cast< int(*)>(_a[1]))); break; + case 1: _t->ShowFloatingClicked(); break; + case 2: _t->ShowTabbedClicked(); break; + case 3: _t->ShowFocusClicked((*reinterpret_cast< int(*)>(_a[1]))); break; + case 4: _t->floatingAction(); break; + case 5: _t->unFloatingAction(); break; + case 6: _t->SetLayoutMode4x4(); break; + case 7: _t->SetLayoutMode3x3(); break; + case 8: _t->SetLayoutMode2x2(); break; + case 9: _t->SetLayoutMode6(); break; + case 10: _t->SetLayoutMode12p1(); break; + case 11: _t->SetLayoutMode1(); break; + default: ; + } + } else if (_c == QMetaObject::IndexOfMethod) { + int *result = reinterpret_cast(_a[0]); + void **func = reinterpret_cast(_a[1]); + { + typedef void (VSCVideoWall::*_t)(int ); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowDisplayClicked)) { + *result = 0; + } + } + { + typedef void (VSCVideoWall::*_t)(); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowFloatingClicked)) { + *result = 1; + } + } + { + typedef void (VSCVideoWall::*_t)(); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowTabbedClicked)) { + *result = 2; + } + } + { + typedef void (VSCVideoWall::*_t)(int ); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowFocusClicked)) { + *result = 3; + } + } + } +} + +const QMetaObject VSCVideoWall::staticMetaObject = { + { &QWidget::staticMetaObject, qt_meta_stringdata_VSCVideoWall.data, + qt_meta_data_VSCVideoWall, qt_static_metacall, 0, 0} +}; + + +const QMetaObject *VSCVideoWall::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; +} + +void *VSCVideoWall::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_VSCVideoWall.stringdata)) + return static_cast(const_cast< VSCVideoWall*>(this)); + return QWidget::qt_metacast(_clname); +} + +int VSCVideoWall::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QWidget::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 12) + qt_static_metacall(this, _c, _id, _a); + _id -= 12; + } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { + if (_id < 12) + *reinterpret_cast(_a[0]) = -1; + _id -= 12; + } + return _id; +} + +// SIGNAL 0 +void VSCVideoWall::ShowDisplayClicked(int _t1) +{ + void *_a[] = { 0, const_cast(reinterpret_cast(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 0, _a); +} + +// SIGNAL 1 +void VSCVideoWall::ShowFloatingClicked() +{ + QMetaObject::activate(this, &staticMetaObject, 1, 0); +} + +// SIGNAL 2 +void VSCVideoWall::ShowTabbedClicked() +{ + QMetaObject::activate(this, &staticMetaObject, 2, 0); +} + +// SIGNAL 3 +void VSCVideoWall::ShowFocusClicked(int _t1) +{ + void *_a[] = { 0, const_cast(reinterpret_cast(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 3, _a); +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard006/C++/0078481_PurchaseHostReservationRequest.cpp b/pool/shard006/C++/0078481_PurchaseHostReservationRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59f9e3e722d5aaeeb2677dc7752c3a44ba3a15fe --- /dev/null +++ b/pool/shard006/C++/0078481_PurchaseHostReservationRequest.cpp @@ -0,0 +1,76 @@ +/* +* 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::EC2::Model; +using namespace Aws::Utils; + +PurchaseHostReservationRequest::PurchaseHostReservationRequest() : + m_offeringIdHasBeenSet(false), + m_hostIdSetHasBeenSet(false), + m_limitPriceHasBeenSet(false), + m_currencyCode(CurrencyCodeValues::NOT_SET), + m_currencyCodeHasBeenSet(false), + m_clientTokenHasBeenSet(false) +{ +} + +Aws::String PurchaseHostReservationRequest::SerializePayload() const +{ + Aws::StringStream ss; + ss << "Action=PurchaseHostReservation&"; + if(m_offeringIdHasBeenSet) + { + ss << "OfferingId=" << StringUtils::URLEncode(m_offeringId.c_str()) << "&"; + } + + if(m_hostIdSetHasBeenSet) + { + unsigned hostIdSetCount = 1; + for(auto& item : m_hostIdSet) + { + ss << "HostIdSet." << hostIdSetCount << "=" + << StringUtils::URLEncode(item.c_str()) << "&"; + hostIdSetCount++; + } + } + + if(m_limitPriceHasBeenSet) + { + ss << "LimitPrice=" << StringUtils::URLEncode(m_limitPrice.c_str()) << "&"; + } + + if(m_currencyCodeHasBeenSet) + { + ss << "CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&"; + } + + if(m_clientTokenHasBeenSet) + { + ss << "ClientToken=" << StringUtils::URLEncode(m_clientToken.c_str()) << "&"; + } + + ss << "Version=2016-11-15"; + return ss.str(); +} + + +void PurchaseHostReservationRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const +{ + uri.SetQueryString(SerializePayload()); +} diff --git a/pool/shard006/C++/0078487_systemmodel.cpp b/pool/shard006/C++/0078487_systemmodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8139598d57ce5104fa768612918524d9c861a11b --- /dev/null +++ b/pool/shard006/C++/0078487_systemmodel.cpp @@ -0,0 +1,186 @@ +/*************************************************************************** + * Copyright (C) 2014 by Eike Hein * + * * + * 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 "systemmodel.h" +#include "actionlist.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "ksmserver_interface.h" + +SystemEntry::SystemEntry(SystemEntry::Action action, const QString &name, const QString &icon) +{ + m_action = action; + m_name = name; + m_icon = QIcon::fromTheme(icon, QIcon::fromTheme("unknown")); +} + +SystemModel::SystemModel(QObject *parent) : AbstractModel(parent) +{ + m_favoriteIds[SystemEntry::LockSession] = "lock-screen"; + m_favoriteIds[SystemEntry::LogoutSession] = "logout"; + m_favoriteIds[SystemEntry::SaveSession] = "save-session"; + m_favoriteIds[SystemEntry::NewSession] = "switch-user"; + m_favoriteIds[SystemEntry::SuspendToRam] = "suspend"; + m_favoriteIds[SystemEntry::SuspendToDisk] = "hibernate"; + m_favoriteIds[SystemEntry::Reboot] = "reboot"; + m_favoriteIds[SystemEntry::Shutdown] = "shutdown"; + + if (KAuthorized::authorizeKAction("lock_screen")) { + m_entryList << new SystemEntry(SystemEntry::LockSession, i18n("Lock"), "system-lock-screen"); + } + + if (KAuthorized::authorizeKAction("logout") && KAuthorized::authorize("logout")) { + m_entryList << new SystemEntry(SystemEntry::LogoutSession, i18n("Logout"), "system-log-out"); + + const KConfigGroup c(KSharedConfig::openConfig("ksmserverrc", KConfig::NoGlobals), "General"); + + if (c.readEntry("loginMode") == "restoreSavedSession") { + m_entryList << new SystemEntry(SystemEntry::SaveSession, i18n("Save Session"), "system-save-session"); + } + } + + if (KAuthorized::authorizeKAction("start_new_session") + && m_displayManager.isSwitchable() + && m_displayManager.numReserve() >= 0) { + m_entryList << new SystemEntry(SystemEntry::NewSession, i18n("New Session"), "system-switch-user"); + } + + QSet sleepStates = Solid::PowerManagement::supportedSleepStates(); + + if (KAuthorized::authorizeKAction("logout") && KAuthorized::authorize("logout")) { + if (sleepStates.contains(Solid::PowerManagement::SuspendState)) { + m_entryList << new SystemEntry(SystemEntry::SuspendToRam, i18n("Suspend"), "system-suspend"); + } + + if (sleepStates.contains(Solid::PowerManagement::HibernateState)) { + m_entryList << new SystemEntry(SystemEntry::SuspendToDisk, i18n("Hibernate"), "system-suspend-hibernate"); + } + } + + m_entryList << new SystemEntry(SystemEntry::Reboot, i18n("Restart"), "system-reboot"); + m_entryList << new SystemEntry(SystemEntry::Shutdown, i18n("Shutdown"), "system-shutdown"); +} + +SystemModel::~SystemModel() +{ + qDeleteAll(m_entryList); +} + +QVariant SystemModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() >= m_entryList.count()) { + return QVariant(); + } + + if (role == Qt::DisplayRole) { + return m_entryList.at(index.row())->name(); + } else if (role == Qt::DecorationRole) { + return m_entryList.at(index.row())->iconName(); + } else if (role == Kicker::FavoriteIdRole) { + return QVariant("sys:" + m_favoriteIds[m_entryList.at(index.row())->action()]); + } + + return QVariant(); +} + +int SystemModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : m_entryList.count(); +} + +bool SystemModel::trigger(int row, const QString &actionId, const QVariant &argument) +{ + Q_UNUSED(actionId) + Q_UNUSED(argument) + + if (row >= 0 && row < m_entryList.count()) { + SystemEntry::Action action = m_entryList.at(row)->action(); + + switch (action) { + case SystemEntry::LockSession: + { + QDBusConnection bus = QDBusConnection::sessionBus(); + QDBusInterface interface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver", bus); + interface.asyncCall("Lock"); + break; + } + case SystemEntry::LogoutSession: + KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeNone); + break; + case SystemEntry::SaveSession: + { + org::kde::KSMServerInterface ksmserver(QStringLiteral("org.kde.ksmserver"), + QStringLiteral("/KSMServer"), QDBusConnection::sessionBus()); + + if (ksmserver.isValid()) { + ksmserver.saveCurrentSession(); + } + + break; + } + case SystemEntry::NewSession: + { + QDBusConnection bus = QDBusConnection::sessionBus(); + QDBusInterface interface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver", bus); + interface.asyncCall("Lock"); + m_displayManager.startReserve(); + break; + }; + case SystemEntry::SuspendToRam: + Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState, 0, 0); + break; + case SystemEntry::SuspendToDisk: + Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState, 0, 0); + break; + case SystemEntry::Shutdown: + KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeHalt); + break; + case SystemEntry::Reboot: + KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeReboot); + break; + } + + return true; + } + + return false; +} + +int SystemModel::rowForFavoriteId(const QString& favoriteId) +{ + const SystemEntry::Action action = m_favoriteIds.key(favoriteId); + + for (int i = 0; i < m_entryList.count(); ++i) { + if (action == m_entryList.at(i)->action()) { + return i; + } + } + + return -1; +} + diff --git a/pool/shard006/C++/0078490_mrlock.cpp b/pool/shard006/C++/0078490_mrlock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98f9da91b1680200097a6c357d83768ebd05fe00 --- /dev/null +++ b/pool/shard006/C++/0078490_mrlock.cpp @@ -0,0 +1,124 @@ +// mrlock.cpp +// author: Mr-Small +#include +#include "mrlock.h" + +namespace mrio { + +// Constructor. +MrLock::MrLock() + : lock_(false) + , lockHandle_(INVALID_HANDLE) { + createHandle(); +} + +// Destructor. +MrLock::~MrLock() { + deleteHandle(); +} + +// Create handle for lock. +void MrLock::createHandle() { + +#if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) + // Create mutex handle. + lockHandle_ = CreateMutex(0, TRUE, NULL); +#elif defined(ANDROID) + // Create semaphore. + lockHandle_ = new sem_t; + sem_init(lockHandle_, 0, 1); +#else + // Create semaphore. + lockHandle_ = semget((key_t)1111, 1, 0666 | IPC_CREAT); + if (lockHandle_ != INVALID_HANDLE) { + union semuni semunion; + semunion.val = 1; + if (semctl(lockHandle_, 0, SETVAL, semunion) == -1) { + perror("create handle failed."); + } + } +#endif // WIIN +} + +// Delete handle for lock. +void MrLock::deleteHandle() { + + unlock(); + if (lockHandle_ != INVALID_HANDLE) { +#if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) + // Check mutex. + CloseHandle(lockHandle_); +#elif defined(ANDROID) + sem_destroy(lockHandle_); +#else + union semuni semunion; + if (semctl(lockHandle_, 0, IPC_RMID, semunion) == -1) { + perror("delete handle failed."); + } +#endif // WIN + lockHandle_ = INVALID_HANDLE; + } + lock_ = false; +} + +// Lock with handle. +bool MrLock::lock() { + + if (lock_) { + return true; + } + + if (lockHandle_ == INVALID_HANDLE) { + perror("lock handle invalid."); + return false; + } + +#if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) + + // Wait for single object. + if (WaitForSingleObject(lockHandle_, INFINITE) == WAIT_FAILED) { + perror("waitforsingleobject wait failed."); + return false; + } +#elif defined(ANDROID) + sem_wait(lockHandle_); +#else + // semaphore lock. + sembuf_.sem_num = 0; + sembuf_.sem_op = -1; + sembuf_.sem_flg = SEM_UNDO; + + if (semop(lockHandle_, &sembuf_, 1) == -1) { + perror("semop failed."); + } +#endif // WIN + + lock_ = true; + return true; +} + +// Unlock. +void MrLock::unlock() { + + if (!lock_) { + return; + } +#if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64) + ReleaseMutex(lockHandle_); +#elif defined(ANDROID) + sem_post(lockHandle_); +#else + sembuf_.sem_op = 1; + if (semop(lockHandle_, &sembuf_, 1) == -1) { + perror("semop failed."); + } +#endif // WIN + lock_ = false; +} + +// Check locked. +bool MrLock::isLocked() { + return lock_; +} + +} // namespace mrio diff --git a/pool/shard006/C++/0078491_main.cpp b/pool/shard006/C++/0078491_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ca6a011585e8a14169cc2d988aa17a63be15e76 --- /dev/null +++ b/pool/shard006/C++/0078491_main.cpp @@ -0,0 +1,107 @@ +/* This file is part of Music Shelf + * Copyright (C) 2011 Martin Grimme + * + * 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 +#include +#include +#include +#include + +#include "context.h" +#include "foldermodel.h" +#include "mobilitybackend.h" + +#include "mediabox-core/abstractbackend.h" +#include "mediabox-core/contentmodel.h" +#include "mediabox-core/contentprovider.h" +#include "mediabox-core/datadirectory.h" +#include "mediabox-core/player.h" +#include "mediabox-core/playqueue.h" + +#ifdef HAS_BOOSTER +#include +#endif + +#ifdef HAS_BOOSTER +Q_DECL_EXPORT +#endif +int main(int argc, char *argv[]) +{ + QGuiApplication* application; + QQuickView* view; + + DataDirectory::initialize(); +#ifdef HAS_BOOSTER + application = MDeclarativeCache::qApplication(argc, argv); + view = MDeclarativeCache::qQuickView(); +#else + qWarning() << Q_FUNC_INFO << "Warning! Running without booster. This may be a bit slower."; + QGuiApplication stackApp(argc, argv); + QQuickView stackView; + application = &stackApp; + view = &stackView; +#endif + QGuiApplication::setOrganizationDomain("org.nemomobile"); + QGuiApplication::setOrganizationName("nemomobile"); + application->setApplicationName("Music Player"); + Context context; + + media::Player player; + MobilityBackend backend; + player.registerBackend("mobility", &backend); + player.selectBackend("mobility"); + + qDebug() << "setting up playing queue"; + media::PlayQueue *playQueue = new media::PlayQueue; + QGuiApplication::connect(playQueue, SIGNAL(itemChanged(content::File::Ptr)), + &player, SLOT(load(content::File::Ptr))); + QGuiApplication::connect(&player, SIGNAL(eofReached()), + playQueue, SLOT(next())); + + FolderModel folderModel; + + // export into QML world + view->rootContext()->setContextProperty("context", &context); + view->rootContext()->setContextProperty("folderModel", &folderModel); + view->rootContext()->setContextProperty("albumModel", + context.contentProvider()->createModel()); + view->rootContext()->setContextProperty("tracksModel", + context.contentProvider()->createModel()); + view->rootContext()->setContextProperty("player", &player); + view->rootContext()->setContextProperty("playQueue", playQueue); + + view->setSource(QUrl("qrc:/qml/main.qml")); + view->setResizeMode(QQuickView::SizeRootObjectToView); + +#if defined(QML_MEDIA_PLAYER_DESKTOP_BUILD) + QScreen *desktop = QGuiApplication::primaryScreen(); + if (desktop->physicalSize().height() < 1000) { + win.scale(.8, .8); + win.resize(win.size() * .8); + } + view->show(); +#else + view->showFullScreen(); +#endif + + return application->exec(); +} diff --git a/pool/shard006/C++/0078497_multisiginputentry.cpp b/pool/shard006/C++/0078497_multisiginputentry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea11c16fe653adcf98ccf113a07d88905ac0f9f7 --- /dev/null +++ b/pool/shard006/C++/0078497_multisiginputentry.cpp @@ -0,0 +1,174 @@ +#include +#include +#include +#include + +#include "base58.h" +#include "multisiginputentry.h" +#include "ui_multisiginputentry.h" +#include "main.h" +#include "script.h" +#include "util.h" +#include "wallet.h" +#include "walletmodel.h" + + +MultisigInputEntry::MultisigInputEntry(QWidget *parent) : QFrame(parent), ui(new Ui::MultisigInputEntry), model(0) +{ + ui->setupUi(this); +} + +MultisigInputEntry::~MultisigInputEntry() +{ + delete ui; +} + +void MultisigInputEntry::setModel(WalletModel *model) +{ + this->model = model; + clear(); +} + +void MultisigInputEntry::clear() +{ + ui->transactionId->clear(); + ui->transactionOutput->clear(); + ui->redeemScript->clear(); +} + +bool MultisigInputEntry::validate() +{ + return (ui->transactionOutput->count() > 0); +} + +CTxIn MultisigInputEntry::getInput() +{ + unsigned int nOutput = ui->transactionOutput->currentIndex(); + CTxIn input(COutPoint(txHash, nOutput)); + + return input; +} + +int64_t MultisigInputEntry::getAmount() +{ + int64_t amount = 0; + unsigned int nOutput = ui->transactionOutput->currentIndex(); + CTransaction tx; + uint256 blockHash = 0; + + if(GetTransaction(txHash, tx, blockHash)) + { + if(nOutput < tx.vout.size()) + { + const CTxOut& txOut = tx.vout[nOutput]; + amount = txOut.nValue; + } + } + + return amount; +} + +QString MultisigInputEntry::getRedeemScript() +{ + return ui->redeemScript->text(); +} + +void MultisigInputEntry::setTransactionId(QString transactionId) +{ + ui->transactionId->setText(transactionId); +} + +void MultisigInputEntry::setTransactionOutputIndex(int index) +{ + ui->transactionOutput->setCurrentIndex(index); +} + +void MultisigInputEntry::setRemoveEnabled(bool enabled) +{ + ui->deleteButton->setEnabled(enabled); +} + +void MultisigInputEntry::on_pasteTransactionIdButton_clicked() +{ + ui->transactionId->setText(QApplication::clipboard()->text()); +} + +void MultisigInputEntry::on_deleteButton_clicked() +{ + emit removeEntry(this); +} + +void MultisigInputEntry::on_pasteRedeemScriptButton_clicked() +{ + ui->redeemScript->setText(QApplication::clipboard()->text()); +} + +void MultisigInputEntry::on_transactionId_textChanged(const QString &transactionId) +{ + ui->transactionOutput->clear(); + if(transactionId.isEmpty()) + return; + + // Make list of transaction outputs + txHash.SetHex(transactionId.toStdString().c_str()); + CTransaction tx; + uint256 blockHash = 0; + if(!GetTransaction(txHash, tx, blockHash)) + return; + for(unsigned int i = 0; i < tx.vout.size(); i++) + { + QString idStr; + idStr.setNum(i); + const CTxOut& txOut = tx.vout[i]; + int64_t amount = txOut.nValue; + QString amountStr; + amountStr.sprintf("%.6f", (double) amount / COIN); + CScript script = txOut.scriptPubKey; + CTxDestination addr; + if(ExtractDestination(script, addr)) + { + CBitcoinAddress address(addr); + QString addressStr(address.ToString().c_str()); + ui->transactionOutput->addItem(idStr + QString(" - ") + addressStr + QString(" - ") + amountStr + QString(" MSCN")); + } + else + ui->transactionOutput->addItem(idStr + QString(" - ") + amountStr + QString(" MSCN")); + } +} + +void MultisigInputEntry::on_transactionOutput_currentIndexChanged(int index) +{ + if(ui->transactionOutput->itemText(index).isEmpty()) + return; + + CTransaction tx; + uint256 blockHash = 0; + if(!GetTransaction(txHash, tx, blockHash)) + return; + const CTxOut& txOut = tx.vout[index]; + CScript script = txOut.scriptPubKey; + + if(script.IsPayToScriptHash()) + { + ui->redeemScript->setEnabled(true); + + if(model) + { + // Try to find the redeem script + CTxDestination dest; + if(ExtractDestination(script, dest)) + { + CScriptID scriptID = boost::get(dest); + CScript redeemScript; + if(model->getWallet()->GetCScript(scriptID, redeemScript)) + ui->redeemScript->setText(HexStr(redeemScript.begin(), redeemScript.end()).c_str()); + } + } + } + else + { + ui->redeemScript->setEnabled(false); + } + + emit updateAmount(); +} \ No newline at end of file diff --git a/pool/shard006/C++/0078507_JSCSSValueCustom.cpp b/pool/shard006/C++/0078507_JSCSSValueCustom.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83c1d3a914085748ccc0f8b4a4d924ec29a51a7a --- /dev/null +++ b/pool/shard006/C++/0078507_JSCSSValueCustom.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2007, 2008 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 "JSCSSValue.h" + +#include "CSSPrimitiveValue.h" +#include "CSSValueList.h" +#include "JSCSSPrimitiveValue.h" +#include "JSCSSValueList.h" +#include "JSWebKitCSSTransformValue.h" +#include "WebKitCSSTransformValue.h" + +#if ENABLE(SVG) +#include "JSSVGColor.h" +#include "JSSVGPaint.h" +#include "SVGColor.h" +#include "SVGPaint.h" +#endif + +using namespace JSC; + +namespace WebCore { + +JSValue toJS(ExecState* exec, JSDOMGlobalObject* globalObject, CSSValue* value) +{ + if (!value) + return jsNull(); + + DOMObject* wrapper = getCachedDOMObjectWrapper(exec, value); + + if (wrapper) + return wrapper; + + if (value->isWebKitCSSTransformValue()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, WebKitCSSTransformValue, value); + else if (value->isValueList()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSValueList, value); +#if ENABLE(SVG) + else if (value->isSVGPaint()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, SVGPaint, value); + else if (value->isSVGColor()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, SVGColor, value); +#endif + else if (value->isPrimitiveValue()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSPrimitiveValue, value); + else + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSValue, value); + + return wrapper; +} + +} // namespace WebCore diff --git a/pool/shard006/C++/0078514_jdtrans.cpp b/pool/shard006/C++/0078514_jdtrans.cpp new file mode 100644 index 0000000000000000000000000000000000000000..199e4ca2b772fb32db1b6fb8f202cbdbc49635d9 --- /dev/null +++ b/pool/shard006/C++/0078514_jdtrans.cpp @@ -0,0 +1,125 @@ +/* + * jdtrans.c + * + * Copyright (C) 1995, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains library routines for transcoding decompression, + * that is, reading raw DCT coefficient arrays from an input JPEG file. + * The routines in jdapimin.c will also be needed by a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + +/* Forward declarations */ +LOCAL void transdecode_master_selection JPP( (j_decompress_ptr cinfo) ); + + +/* + * Read the coefficient arrays from a JPEG file. + * jpeg_read_header must be completed before calling this. + * + * The entire image is read into a set of virtual coefficient-block arrays, + * one per component. The return value is a pointer to the array of + * virtual-array descriptors. These can be manipulated directly via the + * JPEG memory manager, or handed off to jpeg_write_coefficients(). + * To release the memory occupied by the virtual arrays, call + * jpeg_finish_decompress() when done with the data. + * + * Returns NULL if suspended. This case need be checked only if + * a suspending data source is used. + */ + +GLOBAL jvirt_barray_ptr * +jpeg_read_coefficients( j_decompress_ptr cinfo ) { + if ( cinfo->global_state == DSTATE_READY ) { + /* First call: initialize active modules */ + transdecode_master_selection( cinfo ); + cinfo->global_state = DSTATE_RDCOEFS; + } else if ( cinfo->global_state != DSTATE_RDCOEFS ) { + ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); + } + /* Absorb whole file into the coef buffer */ + for (;; ) { + int retcode; + /* Call progress monitor hook if present */ + if ( cinfo->progress != NULL ) { + ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); + } + /* Absorb some more input */ + retcode = ( *cinfo->inputctl->consume_input )( cinfo ); + if ( retcode == JPEG_SUSPENDED ) { + return NULL; + } + if ( retcode == JPEG_REACHED_EOI ) { + break; + } + /* Advance progress counter if appropriate */ + if ( ( cinfo->progress != NULL ) && + ( ( retcode == JPEG_ROW_COMPLETED ) || ( retcode == JPEG_REACHED_SOS ) ) ) { + if ( ++cinfo->progress->pass_counter >= cinfo->progress->pass_limit ) { + /* startup underestimated number of scans; ratchet up one scan */ + cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; + } + } + } + /* Set state so that jpeg_finish_decompress does the right thing */ + cinfo->global_state = DSTATE_STOPPING; + return cinfo->coef->coef_arrays; +} + + +/* + * Master selection of decompression modules for transcoding. + * This substitutes for jdmaster.c's initialization of the full decompressor. + */ + +LOCAL void +transdecode_master_selection( j_decompress_ptr cinfo ) { + /* Entropy decoding: either Huffman or arithmetic coding. */ + if ( cinfo->arith_code ) { + ERREXIT( cinfo, JERR_ARITH_NOTIMPL ); + } else { + if ( cinfo->progressive_mode ) { +#ifdef D_PROGRESSIVE_SUPPORTED + jinit_phuff_decoder( cinfo ); +#else + ERREXIT( cinfo, JERR_NOT_COMPILED ); +#endif + } else { + jinit_huff_decoder( cinfo ); + } + } + + /* Always get a full-image coefficient buffer. */ + jinit_d_coef_controller( cinfo, TRUE ); + + /* We can now tell the memory manager to allocate virtual arrays. */ + ( *cinfo->mem->realize_virt_arrays )( (j_common_ptr) cinfo ); + + /* Initialize input side of decompressor to consume first scan. */ + ( *cinfo->inputctl->start_input_pass )( cinfo ); + + /* Initialize progress monitoring. */ + if ( cinfo->progress != NULL ) { + int nscans; + /* Estimate number of scans to set pass_limit. */ + if ( cinfo->progressive_mode ) { + /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ + nscans = 2 + 3 * cinfo->num_components; + } else if ( cinfo->inputctl->has_multiple_scans ) { + /* For a nonprogressive multiscan file, estimate 1 scan per component. */ + nscans = cinfo->num_components; + } else { + nscans = 1; + } + cinfo->progress->pass_counter = 0L; + cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; + cinfo->progress->completed_passes = 0; + cinfo->progress->total_passes = 1; + } +} diff --git a/pool/shard006/C++/0078515_boss_SpoilsOfPandaria.cpp b/pool/shard006/C++/0078515_boss_SpoilsOfPandaria.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f14b45509c4ab1a22278c6f4e0b86848b23e7801 --- /dev/null +++ b/pool/shard006/C++/0078515_boss_SpoilsOfPandaria.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2013-2015 DeathCore + * 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 . + */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "SiegeOfOrgrimmar.h" + +enum Texts +{ + SAY_AGGRO = 0, + SAY_EARTHQUAKE = 1, + SAY_OVERRUN = 2, + SAY_SLAY = 3, + SAY_DEATH = 4 +}; + +enum Spells +{ + SPELL_EARTHQUAKE = 153616, + SPELL_SUNDER_ARMOR = 153726, + SPELL_CHAIN_LIGHTNING = 153764, + SPELL_OVERRUN = 154221, + SPELL_ENRAGE = 157173, + SPELL_MARK_DEATH = 153234, + SPELL_AURA_DEATH = 153616 +}; + +enum Events +{ + EVENT_ENRAGE = 1, + EVENT_ARMOR = 2, + EVENT_CHAIN = 3, + EVENT_QUAKE = 4, + EVENT_OVERRUN = 5 +}; + +class boss_SpoilsOfPandaria : public CreatureScript +{ + public: + boss_SpoilsOfPandaria() : CreatureScript("boss_SpoilsOfPandaria") { } + + struct boss_SpoilsOfPandariaAI : public ScriptedAI + { + boss_SpoilsOfPandariaAI(Creature* creature) : ScriptedAI(creature) + { + Initialize(); + } + + void Initialize() + { + _inEnrage = false; + } + + void Reset() override + { + _events.Reset(); + _events.ScheduleEvent(EVENT_ENRAGE, 0); + _events.ScheduleEvent(EVENT_ARMOR, urand(5000, 13000)); + _events.ScheduleEvent(EVENT_CHAIN, urand(10000, 30000)); + _events.ScheduleEvent(EVENT_QUAKE, urand(25000, 35000)); + _events.ScheduleEvent(EVENT_OVERRUN, urand(30000, 45000)); + Initialize(); + } + + void KilledUnit(Unit* victim) override + { + victim->CastSpell(victim, SPELL_MARK_DEATH, 0); + + if (urand(0, 4)) + return; + + Talk(SAY_SLAY); + } + + void JustDied(Unit* /*killer*/) override + { + Talk(SAY_DEATH); + } + + void EnterCombat(Unit* /*who*/) override + { + Talk(SAY_AGGRO); + } + + void MoveInLineOfSight(Unit* who) override + + { + if (who && who->GetTypeId() == TYPEID_PLAYER && me->IsValidAttackTarget(who)) + if (who->HasAura(SPELL_MARK_DEATH)) + who->CastSpell(who, SPELL_AURA_DEATH, 1); + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + _events.Update(diff); + + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_ENRAGE: + if (!HealthAbovePct(20)) + { + DoCast(me, SPELL_ENRAGE); + _events.ScheduleEvent(EVENT_ENRAGE, 6000); + _inEnrage = true; + } + break; + case EVENT_OVERRUN: + Talk(SAY_OVERRUN); + DoCastVictim(SPELL_OVERRUN); + _events.ScheduleEvent(EVENT_OVERRUN, urand(25000, 40000)); + break; + case EVENT_QUAKE: + if (urand(0, 1)) + return; + + Talk(SAY_EARTHQUAKE); + + //remove enrage before casting earthquake because enrage + earthquake = 16000dmg over 8sec and all dead + if (_inEnrage) + me->RemoveAurasDueToSpell(SPELL_ENRAGE); + + DoCast(me, SPELL_EARTHQUAKE); + _events.ScheduleEvent(EVENT_QUAKE, urand(30000, 55000)); + break; + case EVENT_CHAIN: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true)) + DoCast(target, SPELL_CHAIN_LIGHTNING); + _events.ScheduleEvent(EVENT_CHAIN, urand(7000, 27000)); + break; + case EVENT_ARMOR: + DoCastVictim(SPELL_SUNDER_ARMOR); + _events.ScheduleEvent(EVENT_ARMOR, urand(10000, 25000)); + break; + default: + break; + } + } + DoMeleeAttackIfReady(); + } + + private: + EventMap _events; + bool _inEnrage; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new boss_SpoilsOfPandariaAI(creature); + } +}; + +void AddSC_boss_SpoilsOfPandaria() +{ + new boss_SpoilsOfPandaria(); +} diff --git a/pool/shard006/C++/0078516_RGBLed.cpp b/pool/shard006/C++/0078516_RGBLed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a63bdd94d8adf1b4da071a0dca29c006b9318c52 --- /dev/null +++ b/pool/shard006/C++/0078516_RGBLed.cpp @@ -0,0 +1,55 @@ +#include "RGBLed.h" +/** + * RGBLed + * Default constructor, init class value and set com PIN to 8,9,10 + */ + +RGBLed :: RGBLed() +{ + redPin = 6; + greenPin = 9; + bluePin = 8; + +} + +/** + * RGBLed + * Overrided constructor, init set com PIN with param + * @param _redPin + * @param _greenPin + * @param _bluePin + */ + +RGBLed :: RGBLed(int _redPin,int _greenPin,int _bluePin) +{ + redPin = _redPin; + greenPin = _greenPin; + bluePin = _bluePin; +} + +/** + * lightOn + * set color value green, blue, red + * @param red + * @param green + * @param blue + */ +void RGBLed :: lightOn(int red,int green,int blue) +{ + analogWrite(redPin, red); + analogWrite(greenPin, green); + analogWrite(bluePin, blue); +} + +/** + * lightOff + * switchOff RGB Led + */ +void RGBLed :: lightOff() +{ + analogWrite(redPin, 0); + analogWrite(greenPin, 0); + analogWrite(bluePin, 0); +} + + diff --git a/pool/shard006/C++/0078519_iniparser.cpp b/pool/shard006/C++/0078519_iniparser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b66b6bf5726b00629fd3de91abbe2dc673e55e14 --- /dev/null +++ b/pool/shard006/C++/0078519_iniparser.cpp @@ -0,0 +1,165 @@ +/** + * This file is a part of ncxmms2, an XMMS2 Client. + * + * Copyright (C) 2011-2015 Pavel Kunavin + * + * 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. + */ + +#include +#include "iniparser.h" + +namespace ncxmms2 { + +class IniParserPrivate +{ +public: + IniParserPrivate() : + keyFile(nullptr) {} + + std::string errorString; + std::string filePath; + GKeyFile *keyFile; + + void closeFile(); +}; +} // ncxmms2 + +using namespace ncxmms2; + +void IniParserPrivate::closeFile() +{ + errorString.clear(); + if (keyFile) { + g_key_file_free(keyFile); + keyFile = nullptr; + } +} + +IniParser::IniParser() : + d(new IniParserPrivate()) +{ + +} + +IniParser::~IniParser() +{ + sync(); + d->closeFile(); +} + +void IniParser::setFile(const std::string& file) +{ + sync(); + d->closeFile(); + + d->filePath = file; + d->keyFile = g_key_file_new(); + GError *error = nullptr; + if (!g_key_file_load_from_file(d->keyFile, d->filePath.c_str(), + G_KEY_FILE_KEEP_COMMENTS, &error)) { + d->errorString = error->message; + g_error_free(error); + } +} + +void IniParser::sync() +{ + if (!d->keyFile) + return; + + gsize size; + gchar *data = g_key_file_to_data(d->keyFile, &size, nullptr); + + GError *error = nullptr; + g_file_set_contents(d->filePath.c_str(), data, size, &error); + if (error) { + d->errorString = error->message; + g_error_free(error); + } + g_free(data); +} + +bool IniParser::isOk() const +{ + return d->errorString.empty(); +} + +std::string IniParser::errorString() const +{ + return d->errorString; +} + +void IniParser::setValue(const std::string& group, const std::string& key, int value) +{ + if (!d->keyFile) + return; + + g_key_file_set_integer(d->keyFile, group.c_str(), key.c_str(), value); +} + +void IniParser::setValue(const std::string& group, const std::string& key, const std::string& value) +{ + if (!d->keyFile) + return; + + g_key_file_set_string(d->keyFile, group.c_str(), key.c_str(), value.c_str()); +} + +void IniParser::setValue(const std::string& group, const std::string& key, bool value) +{ + if (!d->keyFile) + return; + + g_key_file_set_boolean(d->keyFile, group.c_str(), key.c_str(), value); +} + +void IniParser::getValue(const std::string& group, const std::string& key, int *value) const +{ + if (!d->keyFile) + return; + + GError *error = nullptr; + int val = g_key_file_get_integer(d->keyFile, group.c_str(), key.c_str(), &error); + if (error) { + g_error_free(error);; + } else { + *value = val; + } +} + +void IniParser::getValue(const std::string& group, const std::string& key, std::string *value) const +{ + if (!d->keyFile) + return; + + gchar *string = g_key_file_get_string(d->keyFile, group.c_str(), key.c_str(), nullptr); + if (string) { + value->assign(string); + g_free(string); + } +} + +void IniParser::getValue(const std::string& group, const std::string& key, bool *value) const +{ + if (!d->keyFile) + return; + + GError *error = nullptr; + gboolean val = g_key_file_get_boolean(d->keyFile, group.c_str(), key.c_str(), &error); + if (error) { + g_error_free(error);; + } else { + *value = val; + } +} + + diff --git a/pool/shard006/C++/0078520_06.cpp b/pool/shard006/C++/0078520_06.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73ce9aaae7c9a732794b29b3ab5354fc89554793 --- /dev/null +++ b/pool/shard006/C++/0078520_06.cpp @@ -0,0 +1,31 @@ +#include "bm_oopsla.h" + +int main(int argc, char * argv[]) { + RECORD(4, w, x, y, z); + + w = 1; + z = 0; + x = 0; + y = 0; + + while (unknown1()) { + PRINT_VARS(); + PRINT_BAR(1); + + while (unknown2()) { + PRINT_VARS(); + + if (w % 2 == 1) x++; + if (z % 2 == 0) y++; + } + PRINT_VARS(); + PRINT_BAR(2); + + z = x + y; + w = z + 1; + } + PRINT_VARS(); + PRINT_BAR(1); + + assert(x == y); +} diff --git a/pool/shard006/C++/0078524_FlightMapSettings.cc b/pool/shard006/C++/0078524_FlightMapSettings.cc new file mode 100644 index 0000000000000000000000000000000000000000..63c34e59c160b697ee8549ecd1e16a2fe8197b27 --- /dev/null +++ b/pool/shard006/C++/0078524_FlightMapSettings.cc @@ -0,0 +1,159 @@ +/*===================================================================== + + QGroundControl Open Source Ground Control Station + + (c) 2009 - 2015 QGROUNDCONTROL PROJECT + + This file is part of the QGROUNDCONTROL project + + QGROUNDCONTROL 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. + + QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see . + + ======================================================================*/ + +#include "FlightMapSettings.h" + +#include +#include + +const char* FlightMapSettings::_defaultMapProvider = "Bing"; // Bing is default since it support full street/satellite/hybrid set +const char* FlightMapSettings::_settingsGroup = "FlightMapSettings"; +const char* FlightMapSettings::_mapProviderKey = "MapProvider"; +const char* FlightMapSettings::_mapTypeKey = "MapType"; + +FlightMapSettings::FlightMapSettings(QGCApplication* app) + : QGCTool(app) + , _mapProvider(_defaultMapProvider) +{ +} + +void FlightMapSettings::setToolbox(QGCToolbox *toolbox) +{ + QGCTool::setToolbox(toolbox); + + qmlRegisterUncreatableType ("QGroundControl", 1, 0, "FlightMapSetting", "Reference only"); + + _supportedMapProviders << "Bing" << "Google"; // << "OpenStreetMap"; + + _loadSettings(); +} + +void FlightMapSettings::_storeSettings(void) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.setValue(_mapProviderKey, _supportedMapProviders.contains(_mapProvider) ? _mapProvider : _defaultMapProvider); +} + +void FlightMapSettings::_loadSettings(void) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + _mapProvider = settings.value(_mapProviderKey, _defaultMapProvider).toString(); + + if (!_supportedMapProviders.contains(_mapProvider)) { + _mapProvider = _defaultMapProvider; + } + + _setMapTypesForCurrentProvider(); +} + +QString FlightMapSettings::mapProvider(void) +{ + return _mapProvider; +} + +void FlightMapSettings::setMapProvider(const QString& mapProvider) +{ + if (_supportedMapProviders.contains(mapProvider)) { + _mapProvider = mapProvider; + _storeSettings(); + _setMapTypesForCurrentProvider(); + emit mapProviderChanged(mapProvider); + } +} + +void FlightMapSettings::_setMapTypesForCurrentProvider(void) +{ + _mapTypes.clear(); + + if (_mapProvider == "Bing") { + _mapTypes << "Street Map" << "Satellite Map" << "Hybrid Map"; + } else if (_mapProvider == "Google") { + _mapTypes << "Street Map" << "Satellite Map" << "Terrain Map"; + /* + } else if (_mapProvider == "OpenStreetMap") { + _mapTypes << "Street Map"; + */ + } + + emit mapTypesChanged(_mapTypes); +} + +QString FlightMapSettings::mapTypeForMapName(const QString& mapName) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + settings.beginGroup(_mapProvider); + return settings.value(_mapTypeKey, "Satellite Map").toString(); +} + +void FlightMapSettings::setMapTypeForMapName(const QString& mapName, const QString& mapType) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + settings.beginGroup(_mapProvider); + settings.setValue(_mapTypeKey, mapType); +} + +void FlightMapSettings::saveMapSetting (const QString &mapName, const QString& key, const QString& value) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + settings.setValue(key, value); +} + +QString FlightMapSettings::loadMapSetting (const QString &mapName, const QString& key, const QString& defaultValue) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + return settings.value(key, defaultValue).toString(); +} + +void FlightMapSettings::saveBoolMapSetting (const QString &mapName, const QString& key, bool value) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + settings.setValue(key, value); +} + +bool FlightMapSettings::loadBoolMapSetting (const QString &mapName, const QString& key, bool defaultValue) +{ + QSettings settings; + + settings.beginGroup(_settingsGroup); + settings.beginGroup(mapName); + return settings.value(key, defaultValue).toBool(); +} diff --git a/pool/shard006/C++/0078526_12665_jokingfermat.cpp b/pool/shard006/C++/0078526_12665_jokingfermat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71c38cb097a6b89460b2389d601ec6395c9ff654 --- /dev/null +++ b/pool/shard006/C++/0078526_12665_jokingfermat.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +//#define DEBUG //comment this line to pull out print statements +#ifdef DEBUG +#define TAB '\t' +#define debug(a, end) cout << #a << ": " << a << end +#define dbg(end) end +#else +#define debug(a, end) +#define dbg(end) +#endif + +typedef pair point; +typedef vector vi; +typedef vector vp; + +#define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) +#define SORT(c) sort((c).begin(),(c).end()) +#define FOR(i,a,b) for (int i=(a); i < (b); i++) +#define REP(i,n) FOR(i,0,(int)n) +#define CL(a,b) memset(a,b,sizeof(a)) +#define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) + +/*global variables*/ +int cubes[1001]; +int x, y; +/*global variables*/ + +void dump() +{ + //dump data +} + +bool getInput() +{ + //get input + if (feof(stdin)) return false; + scanf("%d %d ", &x, &y); + return true; +} + +void process() +{ + //process input + int n = 0; + long long c; + int b, e; + for (int a = x; a <= y; a++) + { + for (b = a+1; b <= 1001; b++) + { + c = cubes[a] + cubes[b]; + e = c%10; + c /= 10; + if (c > y) + break; + if (e == 3) + n++; + } + if (b == (a+1)) break; + } + printf("%d\n", n*2); +} + +int main() +{ + FOR(i, 1, 1001) + { + cubes[i] = pow(i, 3); + } + debug(sizeof(cubes[1000]), endl); + int pn = 1; + while (getInput()) + { + printf("Case %d: ", pn++); + process(); + + /*CLEAR GLOBAL VARIABLES!*/ + + /*CLEAR GLOBAL VARIABLES!*/ + } + + return 0; +} diff --git a/pool/shard006/C++/0078527_InputManager.cpp b/pool/shard006/C++/0078527_InputManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c81bd6efb46b373dae2c91ca5d3b45b020c7c905 --- /dev/null +++ b/pool/shard006/C++/0078527_InputManager.cpp @@ -0,0 +1,63 @@ +#include "../include/InputManager.h" + +namespace FGF +{ + InputManager::InputManager() + { + } + + InputManager::~InputManager() + { + key_press.clear(); + } + + bool InputManager::getKeyState(SDLKey key) + { + return SDL_GetKeyState(NULL)[key]; + } + + int InputManager::getMouseX() + { + int x; + SDL_GetMouseState(&x,NULL); + return x; + } + int InputManager::getMouseY() + { + int y; + SDL_GetMouseState(NULL,&y); + return y; + } + + int InputManager::getMouseXRel() + { + int x; + SDL_GetRelativeMouseState(&x,NULL); + return x; + } + int InputManager::getMouseYRel() + { + int y; + SDL_GetRelativeMouseState(NULL,&y); + return y; + } + + bool InputManager::getMouseButtonState(int button) + { + return (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(button)); + } + + void InputManager::setCommand_OnKeyPress(SDLKey key,ICommand* cmd) + { + key_press[key] = cmd; + } + + void InputManager::Update(float dt) + { + for(std::map::iterator it = key_press.begin(); + it != key_press.end(); it++) + { + if(getKeyState(it->first)) it->second->Execute(dt); + } + } +} diff --git a/pool/shard006/C++/0078541_BroadcastDiscovery.cpp b/pool/shard006/C++/0078541_BroadcastDiscovery.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cbc97788ca2f5c934c6b36c80f96d1bc789d887 --- /dev/null +++ b/pool/shard006/C++/0078541_BroadcastDiscovery.cpp @@ -0,0 +1,151 @@ +#include "umundo/discovery/BroadcastDiscovery.h" + +namespace umundo { + +/** + * Have a look at https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L81 to + * see how to setup UDP sockets for broadcast. + * + * Receiving Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L700 + * Sending Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L751 + */ + +#if 0 +SOCKET BroadcastDiscovery::udpSocket = 0; +RMutex BroadcastDiscovery::globalMutex; + +sockaddr_in BroadcastDiscovery::bCastAddress; +char BroadcastDiscovery::hostName[NI_MAXHOST]; +#endif + +BroadcastDiscovery::BroadcastDiscovery() { + /** + * This is called twice overall, once for the prototype in the factory and + * once for the instance that is actually used. + */ +} + +BroadcastDiscovery::~BroadcastDiscovery() { +} + +#if 0 +void BroadcastDiscovery::setupUDPSocket() { + RScopeLock(globalMutex); + if (udpSocket == 0) { + int enable = 1; + + udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (udpSocket == INVALID_SOCKET) + return; + + if (setsockopt (udpSocket, SOL_SOCKET, SO_BROADCAST, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { + //error + } + if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { + //error + } + +#if defined (SO_REUSEPORT) + if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEPORT, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { + //error + } +#endif + in_addr_t bindTo = INADDR_ANY; + in_addr_t sendTo = INADDR_BROADCAST; + + bCastAddress.sin_family = AF_INET; + bCastAddress.sin_port = htons(43005); + bCastAddress.sin_addr.s_addr = sendTo; + + sockaddr_in address = bCastAddress; + address.sin_addr.s_addr = bindTo; + +#if (defined (__WINDOWS__)) + sockaddr_in sockaddr = address; +#elif (defined (__APPLE__)) + sockaddr_in sockaddr = bCastAddress; + sockaddr.sin_addr.s_addr = htons (INADDR_ANY); +#else + sockaddr_in sockaddr = bCastAddress; +#endif + + if (bind (udpSocket, (struct sockaddr *) &sockaddr, sizeof (sockaddr_in))) { + // error + } + + getnameinfo ((struct sockaddr *) &address, sizeof (sockaddr_in), hostName, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); + + } +} +#endif + +SharedPtr BroadcastDiscovery::getInstance() { + if (_instance.get() == NULL) { + // setup UDP socket when th first instance is required + //setupUDPSocket(); + + _instance = SharedPtr(new BroadcastDiscovery()); + _instance->start(); + } + return _instance; +} +SharedPtr BroadcastDiscovery::_instance; + +SharedPtr BroadcastDiscovery::create() { + return getInstance(); +} + +void BroadcastDiscovery::init(const Options*) { + /* + * This is where you can setup the non-prototype instance, i.e. not the one + * in the factory, but the one created from the prototype. + * + * The options object is not used and empty. + */ +} + +void BroadcastDiscovery::suspend() { +} + +void BroadcastDiscovery::resume() { +} + +void BroadcastDiscovery::advertise(const EndPoint& node) { + /** + * umundo.core asks you to make the given node discoverable + */ +} + +void BroadcastDiscovery::add(Node& node) { +} + +void BroadcastDiscovery::unadvertise(const EndPoint& node) { + /** + * umundo.core asks you to announce the removal of the given node + */ +} + +void BroadcastDiscovery::remove(Node& node) { +} + +void BroadcastDiscovery::browse(ResultSet* query) { + /** + * Another node wants to browse for nodes + */ +} + +void BroadcastDiscovery::unbrowse(ResultSet* query) { + /** + * Another node no longer wants to browse for nodes + */ +} + +std::vector BroadcastDiscovery::list() { + return std::vector(); +} + +void BroadcastDiscovery::run() { + // your very own thread! +} + +} diff --git a/pool/shard006/C++/0078543_string.cpp b/pool/shard006/C++/0078543_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2a48cf290b599403d3993e4c155dd6df9c18e4b --- /dev/null +++ b/pool/shard006/C++/0078543_string.cpp @@ -0,0 +1,71 @@ +/* + * This file is a part of Luminance HDR package. + * ---------------------------------------------------------------------- + * Copyright (C) 2013 Davide Anastasia + * + * 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 + +using namespace std; + +namespace pfs { +namespace utils { + +// Utility functions for case insensitive string compare +static +int charDiff(char c1, char c2) +{ + if ( tolower(c1) < tolower(c2) ) return -1; + if ( tolower(c1) == tolower(c2) ) return 0; + return 1; +} + +static +int stringCompare(const string& str1, const string& str2) +{ + int diff = 0; + size_t size = std::min(str1.size(), str2.size()); + for (size_t idx = 0; idx < size && diff == 0; ++idx) + { + diff = charDiff(str1[idx], str2[idx]); + } + if ( diff != 0 ) return diff; + + if ( str2.length() == str1.length() ) return 0; + if ( str2.length() > str1.length() ) return 1; + return -1; +} + +bool StringUnsensitiveComp::operator()(const std::string& str1, const std::string& str2) const { + return ( stringCompare(str1, str2) == -1 ); +} + +string getFormat(const string &filename) +{ + size_t i = filename.rfind('.', filename.length()); + if ( i != string::npos ) { + return filename.substr(i+1, filename.length()-i); + } + return string(); +} + +} // utils +} // pfs diff --git a/pool/shard006/C++/0078550_remove_element.cpp b/pool/shard006/C++/0078550_remove_element.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a4d29b64d22a5e46a0357defc62305aa741edae --- /dev/null +++ b/pool/shard006/C++/0078550_remove_element.cpp @@ -0,0 +1,76 @@ +/* + Remove Element + + Given an array and a value, remove all instances of that value + in place and return the new length. + + The order of elements can be changed. + It doesn't matter what you leave beyond the new length. + + */ + +#include +#include + +using namespace std; + +class Solution +{ +public: + int removeElement(int A[], int n, int elem) + { + if (n <= 0) + return n; // + + if (n == 1) + return A[0] == elem ? 0 : 1; + + int start = 0, end = n - 1; + while (start < end) { + if (A[start] != elem) { + start++; + } else if (A[end] == elem) { + end--; + } else { + swap(A[start], A[end]); + start++; + end--; + } + } + return start + (A[start] == elem ? 0 : 1); // + } + + int removeElement2(int A[], int n, int elem) + { + int i = 0, j = 0; + while (j < n) { + if (A[j] != elem) A[i++] = A[j]; + j++; + } + return i; + } + + int removeElement3(int A[], int n, int elem) + { + int idx = 0; + + for (int i = 0; i < n; i++) { + if (A[i] != elem) A[idx++] = A[i]; + } + + return idx; + } +}; + +int main(int argc, char *argv[]) +{ + int a[] = { 3, 3, 5, 4, 5 }; + Solution sol; + + cout << sol.removeElement(a, sizeof(a) / sizeof(int), 5) << endl; + + for (auto t : a) + cout << t << ends; + + return 0; +} diff --git a/pool/shard006/C++/0078551_5.cpp b/pool/shard006/C++/0078551_5.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd6db32fd713baa39f2d31e587a2b18f499348eb --- /dev/null +++ b/pool/shard006/C++/0078551_5.cpp @@ -0,0 +1,108 @@ + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + sort(nums.begin(), nums.end()); + return nums[nums.size() - k ]; + } +}; + + +// n logn +// + + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + priority_queue pq(nums.begin(), nums.end()); + for (int i = 0; i < k - 1; i++) + pq.pop(); + return pq.top(); + } +}; + +// +// +class Solution { +public: + inline int left(int idx) { + return (idx << 1) + 1; + } + inline int right(int idx) { + return (idx << 1) + 2; + } + void max_heapify(vector& nums, int idx) { + int largest = idx; + int l = left(idx), r = right(idx); + if (l < heap_size && nums[l] > nums[largest]) largest = l; + if (r < heap_size && nums[r] > nums[largest]) largest = r; + if (largest != idx) { + swap(nums[idx], nums[largest]); + max_heapify(nums, largest); + } + } + void build_max_heap(vector& nums) { + heap_size = nums.size(); + for (int i = (heap_size >> 1) - 1; i >= 0; i--) + max_heapify(nums, i); + } + int findKthLargest(vector& nums, int k) { + build_max_heap(nums); + for (int i = 0; i < k; i++) { + swap(nums[0], nums[heap_size - 1]); + heap_size--; + max_heapify(nums, 0); + } + return nums[heap_size]; + } +private: + int heap_size; +}; + +// + + +class Solution { +public: + inline int swap(vector& nums, int left, int right){ + if (left <0 or right>= nums.size()) return -1; + int temp = nums[left]; + nums[left] = nums[right]; + nums[right] = temp; + + return 1; + } + + int partition(vector& nums, int left, int right) { + int pivot = nums[left]; + int l = left + 1, r = right; + while (l <= r) { + if (nums[l] < pivot && nums[r] > pivot) + swap(nums,l++, r--); + + if (nums[l] >= pivot) l++; + if (nums[r] <= pivot) r--; + } + swap(nums,left, r); + return r; + } + + /* + * param k : description of k + * param nums : description of array and index 0 ~ n-1 + * return: description of return + */ + + int findKthLargest(vector& nums, int k) { + int left = 0, right = nums.size() - 1; + while (true) { + int pos = partition(nums, left, right); + if (pos == k - 1) return nums[pos]; + if (pos > k - 1) right = pos - 1; + else left = pos + 1; + } + + + } +}; \ No newline at end of file diff --git a/pool/shard006/C++/0078556_uri.cpp b/pool/shard006/C++/0078556_uri.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8b7adf7fe8de3b8dce15c243dba24cd3ff4a898 --- /dev/null +++ b/pool/shard006/C++/0078556_uri.cpp @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: MIT +// Copyright contributors to the gecko project. + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +void check( + base::unit_test & ut, + const std::string &test, + bool should = true, + bool except = false ) +{ + try + { + base::uri u( test ); + std::string match = base::to_string( u ); + + if ( test == match ) + ut.success( test ); + else if ( !should ) + ut.negative_success( test + " != " + match ); + else + ut.failure( test + " != " + match ); + } + catch ( const std::exception &e ) + { + std::stringstream msg; + base::print_exception( msg, e ); + if ( except ) + ut.negative_success( test + " -> exception " + msg.str() ); + else + ut.failure( test + " -> exception " + msg.str() ); + } +} + +int safemain( int argc, char *argv[] ) +{ + base::unit_test test( "uri" ); + + base::cmd_line options( argv[0] ); + test.setup( options ); + + try + { + options.parse( argc, argv ); + } + catch ( ... ) + { + throw_add( "parsing command line arguments" ); + } + + test["basic_parsing"] = [&]( void ) { + check( test, "http", false, true ); + check( test, "http:", false, true ); + check( test, "file:/tmp" ); + check( test, "file:///tmp", false ); + check( test, "http://host.com" ); + check( test, "http://user@host.com" ); + check( test, "http://host.com:1234" ); + check( test, "http://user@host.com:1234" ); + check( test, "http://host.com/path1" ); + check( test, "http://host.com/path1/path2" ); + }; + + test["parse_query_frag"] = [&]( void ) { + check( test, "http://host.com?query" ); + check( test, "http://host.com#frag" ); + check( test, "http://host.com?query#frag" ); + check( test, "http://host.com/path1?query#frag" ); + }; + + test["parse_encoded"] = [&]( void ) { + check( test, "http://host.com/path1#frag%3Fmorefrag" ); + check( test, "http://host%2ecom", false ); + check( test, "http://host%2Ecom", false ); + check( test, "http://host.com/%2fmore", false ); + check( test, "http://host.com/%2Fmore" ); + check( test, "http://host.com/with%20space", false ); + check( test, "http://host.com/with space", true ); + }; + + test["path_construction"] = [&]( void ) { + base::uri tf( "file", "" ); + tf /= "file.txt"; + if ( tf.pretty() == "file:///file.txt" ) + test.success( "operator/=" ); + else + test.failure( "operator/= -> {0}", tf ); + + tf = base::uri( "file", "" ) / "hello" / "world"; + if ( tf.pretty() == "file:///hello/world" ) + test.success( "operator/" ); + else + test.failure( "operator/ -> {0}", tf ); + }; + + // test.cleanup() = [&]( void ) {}; + test.run( options ); + test.clean(); + + return -static_cast( test.failure_count() ); +} + +} // namespace + +int main( int argc, char *argv[] ) +{ + try + { + return safemain( argc, argv ); + } + catch ( const std::exception &e ) + { + base::print_exception( std::cerr, e ); + } + return -1; +} diff --git a/pool/shard006/C++/0078558_partialdate.cpp b/pool/shard006/C++/0078558_partialdate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50c105efe15a66d847f6b83635f5caad40a16eb0 --- /dev/null +++ b/pool/shard006/C++/0078558_partialdate.cpp @@ -0,0 +1,217 @@ +/*************************************************************************** + * (C) 2005-2009 Michal Rudolf * + * * + * 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 "partialdate.h" +#include + +PartialDate::PartialDate(int y, int m, int d) : + m_year(y), + m_month(m), + m_day(d) +{ + m_bIsValid = !m_year || asDate().isValid(); +} + +PartialDate::PartialDate(const QString& s) +{ + m_year = 0; + m_month = 0; + m_day = 0; + fromString(s); +} + +PartialDate::PartialDate(const QDate& d) +{ + m_bIsValid = true; + m_year = d.year(); + m_month = d.month(); + m_day = d.day(); +} + +PartialDate PartialDate::today() +{ + return PartialDate(QDate::currentDate()); +} + +int PartialDate::year() const +{ + return m_year; +} + +int PartialDate::month() const +{ + return m_month; +} + +int PartialDate::day() const +{ + return m_day; +} + +PartialDate& PartialDate::fromString(const QString& s) +{ + QString test = s.trimmed(); + QRegExp regExp("^[\\?0-9]{4}([\\./]([\\?0-9]){1,2}){,2}$"); + if(regExp.exactMatch(test) || test.isEmpty()) + { + QRegExp sep("[\\./]"); + m_year = test.section(sep, 0, 0).toInt(); + m_month = test.section(sep, 1, 1).toInt(); + m_day = test.section(sep, 2, 2).toInt(); + m_bIsValid = !year() || asDate().isValid(); + } + else + { + QRegExp regExpContinental("^(([\\?0-9]){1,2}\\.){,2}[\\?0-9]{4}$"); + if(regExpContinental.exactMatch(test)) + { + m_day = test.section('.', 0, 0).toInt(); + m_month = test.section('.', 1, 1).toInt(); + m_year = test.section('.', 2, 2).toInt(); + m_bIsValid = !year() || asDate().isValid(); + } + else + { + QRegExp regExpAmerican("^(([\\?0-9]){1,2}/){,2}[\\?0-9]{4}$"); + if(regExpAmerican.exactMatch(test)) + { + m_month = test.section('/', 0, 0).toInt(); + m_day = test.section('/', 1, 1).toInt(); + m_year = test.section('/', 2, 2).toInt(); + m_bIsValid = !year() || asDate().isValid(); + } + } + } + return *this; +} + + +QDate PartialDate::asDate() const +{ + return QDate(m_year, m_month ? m_month : 1, m_day ? m_day : 1); +} + +bool PartialDate::isValid() const +{ + return m_bIsValid; +} + +QString PartialDate::asString() const +{ + if(!m_year) + { + return "????.??.??"; + } + QString s = QString("%1.%2.%3") + .arg(m_year, 4) + .arg(numberToString(m_month)) + .arg(numberToString(m_day)); + return s; +} + +QString PartialDate::asShortString(int part) const +{ + if(!m_year) + { + return QString(); + } + QString s; + if(part & Year) + { + s = numberToString(m_year); + } + if(!m_month) + { + return s; + } + if(part & Month) + { + if(!s.isEmpty()) + { + s += '.'; + } + s += numberToString(m_month); + } + if(!m_day) + { + return s; + } + if(part & Day) + { + if(!s.isEmpty()) + { + s += '.'; + } + s += numberToString(m_day); + } + return s; +} + +QString PartialDate::numberToString(int d, QChar fill) const +{ + if(!d) + { + return "??"; + } + return d < 10 ? QString(fill) + QString::number(d) : QString::number(d); +} + +bool operator==(const PartialDate& d1, const PartialDate& d2) +{ + return d1.year() == d2.year() && d1.month() == d2.month() && d1.day() == d2.day(); +} + +bool operator<(const PartialDate& d1, const PartialDate& d2) +{ + return d2.year() > d1.year() || + ((d2.year() == d1.year()) && + (d2.month() > d1.month() || (d2.month() == d1.month() && d2.day() > d1.day()))); +} + +bool operator>(const PartialDate& d1, const PartialDate& d2) +{ + return d1.year() > d2.year() || + ((d1.year() == d2.year()) && + (d1.month() > d2.month() || (d1.month() == d2.month() && d1.day() > d2.day()))); +} + +bool operator>=(const PartialDate& d1, const PartialDate& d2) +{ + return d2 < d1 || d2 == d1; +} + +bool operator<=(const PartialDate& d1, const PartialDate& d2) +{ + return d2 > d1 || d2 == d1; +} + +bool operator!=(const PartialDate& d1, const PartialDate& d2) +{ + return d1.year() != d2.year() || d1.month() != d2.month() || d1.day() != d2.day(); +} + +QString PartialDate::range(const PartialDate& d) const +{ + if(year() != d.year()) + { + return asShortString() + "-" + d.asShortString(); + } + QString result = numberToString(year()); + if(month() != d.month()) + return QString("%1.%2-%3").arg(year()).arg(asShortString(Month | Day)) + .arg(d.asShortString(Month | Day)); + else if(day() != d.day()) + return QString("%1.%2.%3-%4").arg(year()).arg(month()) + .arg(asShortString(Day)).arg(d.asShortString(Day)); + else + { + return asShortString(); + } +} + diff --git a/pool/shard006/C++/0078561_ChShaftsTorqueConverter.cpp b/pool/shard006/C++/0078561_ChShaftsTorqueConverter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e79c44f872648c5df3b01406e8064a1a50a5295d --- /dev/null +++ b/pool/shard006/C++/0078561_ChShaftsTorqueConverter.cpp @@ -0,0 +1,221 @@ +// +// PROJECT CHRONO - http://projectchrono.org +// +// Copyright (c) 2010, 2012 Alessandro Tasora +// Copyright (c) 2013 Project Chrono +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file at the top level of the distribution +// and at http://projectchrono.org/license-chrono.txt. +// + + +#include "physics/ChShaftsTorqueConverter.h" +#include "physics/ChSystem.h" +#include "physics/ChShaft.h" + +#include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only. + +namespace chrono +{ + + +// Register into the object factory, to enable run-time +// dynamic creation and persistence +ChClassRegister a_registration_ChShaftsTorqueConverter; + + + +////////////////////////////////////// +////////////////////////////////////// + + +ChShaftsTorqueConverter::ChShaftsTorqueConverter () +{ + this->shaft1 = 0; + this->shaft2 = 0; + this->shaft_stator = 0; + this->torque_in= 0; + this->torque_out= 0; + this->K = ChSharedPtr (new ChFunction_Const(0.9)); + this->T = ChSharedPtr (new ChFunction_Const(0.9)); + this->state_warning_reverseflow = false; + this->state_warning_wrongimpellerdirection = false; + + SetIdentifier(GetUniqueIntID()); // mark with unique ID +} + + +ChShaftsTorqueConverter::~ChShaftsTorqueConverter () +{ + +} + +void ChShaftsTorqueConverter::Copy(ChShaftsTorqueConverter* source) +{ + // copy the parent class data... + ChPhysicsItem::Copy(source); + + // copy class data + shaft1 = 0; + shaft2 = 0; + shaft_stator = 0; + + torque_in = source->torque_in; + torque_out = source->torque_out; + + state_warning_reverseflow = source->state_warning_reverseflow; + state_warning_wrongimpellerdirection = source->state_warning_wrongimpellerdirection; + + this->K = ChSharedPtr(K->new_Duplicate()); // deep copy + this->T = ChSharedPtr(T->new_Duplicate()); // deep copy +} + + +int ChShaftsTorqueConverter::Initialize(ChSharedPtr mshaft1, ChSharedPtr mshaft2, ChSharedPtr mshaft_stator) +{ + ChShaft* mm1 = mshaft1.get_ptr(); + ChShaft* mm2 = mshaft2.get_ptr(); + ChShaft* mm_stator = mshaft_stator.get_ptr(); + assert(mm1 && mm2 && mm_stator); + assert((mm1 != mm2) && (mm1 != mm_stator)); + assert((mm1->GetSystem() == mm2->GetSystem()) && (mm1->GetSystem() == mm_stator->GetSystem())); + + this->shaft1 = mm1; + this->shaft2 = mm2; + this->shaft_stator = mm_stator; + + this->SetSystem(this->shaft1->GetSystem()); + + return true; +} + + +double ChShaftsTorqueConverter::GetSpeedRatio() const +{ + double wrel1 = this->shaft1->GetPos_dt() - this->shaft_stator->GetPos_dt(); + double wrel2 = this->shaft2->GetPos_dt() - this->shaft_stator->GetPos_dt(); + + if ((fabs(wrel1) < 10e-9) || (fabs(wrel2) < 10e-9)) + return 0; + + return wrel2/wrel1; +} + + +void ChShaftsTorqueConverter::Update (double mytime) +{ + // Inherit time changes of parent class + ChPhysicsItem::Update(mytime); + + // update class data + + state_warning_wrongimpellerdirection= false; + state_warning_reverseflow = false; + + // Compute actual speed ratio + double mR = this->GetSpeedRatio(); + + // The speed ratio must always be in the [0...1] range, + // anyway let's correct singular cases: + + // - it should be inusual that speed ratio >1, say if the impeller + // outruns turbine (if there's a clutch lock-in, this should happen). + // If so, assume a reflection of T curve and a polar reflection of K curve, after 1. + if (mR > 1) + { + mR = 1-(mR-1); + state_warning_reverseflow = true; + } + + // - if the output shaft is spinning a bit backward, when + // close to stall, maybe win/wout < 0. If so, set as stall anyway: + if (mR < 0) + mR = 0; + + // - if input impeller shaft is spinning in negative direction, + // this is assumed as an error: set all torques to zero and bail out: + if (this->shaft1->GetPos_dt() - this->shaft_stator->GetPos_dt() < 0) + { + state_warning_wrongimpellerdirection = true; + this->torque_in = 0; + this->torque_out = 0; + return; + } + + // Compute actual capacity factor + double mK = K->Get_y(mR); + + // Compute actual torque factor + double mT = T->Get_y(mR); + + // compute input torque (with minus sign because applied TO input thaft) + this->torque_in = - pow(( this->shaft1->GetPos_dt() / mK ),2); + + if (state_warning_reverseflow) + this->torque_in = -this->torque_in; + + // compute output torque (with opposite sign because + // applied to output shaft, with same direction of input shaft) + this->torque_out = - mT * this->torque_in; +} + + + + +////////// LCP INTERFACES //// + + + +void ChShaftsTorqueConverter::VariablesFbLoadForces(double factor) +{ + // Apply torques to the three connected 1D variables: + shaft1->Variables().Get_fb().ElementN(0) += torque_in*factor; + shaft2->Variables().Get_fb().ElementN(0) += torque_out*factor; + shaft_stator->Variables().Get_fb().ElementN(0) += GetTorqueReactionOnStator()*factor; +} + + + +//////// FILE I/O + +void ChShaftsTorqueConverter::StreamOUT(ChStreamOutBinary& mstream) +{ + // class version number + mstream.VersionWrite(1); + + // serialize parent class too + ChPhysicsItem::StreamOUT(mstream); + + // stream out all member data + mstream.AbstractWrite(this->K.get_ptr()); //***TODO*** proper serialize for ChSharedPtr + mstream.AbstractWrite(this->T.get_ptr()); //***TODO*** proper serialize for ChSharedPtr +} + +void ChShaftsTorqueConverter::StreamIN(ChStreamInBinary& mstream) +{ + // class version number + int version = mstream.VersionRead(); + + // deserialize parent class too + ChPhysicsItem::StreamIN(mstream); + + // deserialize class + ChFunction* newfun; + mstream.AbstractReadCreate(&newfun); //***TODO*** proper deserialize for ChSharedPtr + this->K = ChSharedPtr(newfun); + mstream.AbstractReadCreate(&newfun); //***TODO*** proper deserialize for ChSharedPtr + this->T = ChSharedPtr(newfun);; + +} + + + + + + +} // END_OF_NAMESPACE____ + + +///////////////////// diff --git a/pool/shard006/C++/0078564_command_interface.cpp b/pool/shard006/C++/0078564_command_interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030ef0f649f2e80248c52e788e131d56d60bee1f --- /dev/null +++ b/pool/shard006/C++/0078564_command_interface.cpp @@ -0,0 +1,47 @@ +#include "command_interface.h" + +#include + +#include "abort/abort.h" +#include "util/str_util.h" + +namespace Chess +{ + CommandInterface::CommandInterface() + : _cmd_map() + { + } + + bool CommandInterface::install(const std::string& name, + handler_t handler) + { + const std::string cmdName = Util::trim(Util::to_lower(name)); + AbortIf(cmdName.empty(), false); + + _cmd_map[cmdName] = handler; + return true; + } + + bool CommandInterface::process(const std::string& data) + { + const std::string input = Util::trim(data); + AbortIf(input.empty(), false); + + std::vector tokens; Util::split(input, tokens); + AbortIf(tokens.empty(), false); + + const std::string cmd = Util::to_lower( tokens[0] ); + auto iter = _cmd_map.find(cmd); + + AbortIf(iter == _cmd_map.end(), false); + + tokens.erase(tokens.begin()); + + const std::string args = Util::build_string(tokens, " "); + + // Invoke the handler for this command + + iter->second(args); + return true; + } +} diff --git a/pool/shard006/C++/0078577_Led.cpp b/pool/shard006/C++/0078577_Led.cpp new file mode 100644 index 0000000000000000000000000000000000000000..512c635da30870fe11e57be8eeaa3e463921b0e4 --- /dev/null +++ b/pool/shard006/C++/0078577_Led.cpp @@ -0,0 +1,109 @@ +/* + To change this license header, choose License Headers in Project Properties. + To change this template file, choose Tools | Templates + and open the template in the editor. +*/ + +/* + File: Led.cpp + Author: Mathilde + + Created on 25 octobre 2016, 16:29 +*/ + +#include "Led.h" + + +Led::Led(int newPin, int newNumber) { + this->pin = newPin; + this->number = newNumber; + this->state = false; + this->blink = false; + this->color = {0, 0, 0}; +} + +bool Led::init() { + + this->strip = Adafruit_NeoPixel(this->number, this->pin, NEO_GRB + NEO_KHZ800); + this->strip.begin();// Initialise toute les led à 'off' + setColorAll(255, 255, 255); +} + +std::vector Led::getColor() { + return this->color; +} + +void Led::show(int ledNbr, int newR, int newV, int newB) { + this->color = { newR, newV, newB }; + this->strip.setPixelColor(ledNbr, newR, newV, newB); + this->strip.show(); +} + +void Led::setColorAll(int newR, int newV, int newB) { + this->color = {newR, newV, newB}; + + int cpt; + for (cpt = 0; cpt < this->number; cpt++) { + this->strip.setPixelColor(cpt, newR, newV, newB); + if (this->pin == 44) { + this->strip.setPixelColor(0, 0, 0, 0); + } + } + this->strip.show(); + delay(100); +} + +void Led::setColorUnit(int ledNbr, int newR, int newV, int newB) { + ledNbr = abs(ledNbr); + if (ledNbr > this->number) show(this->number, 0, 0, 0); + else show(ledNbr - 1, newR, newV, newB); +} + +/* Code de Quentin */ +void Led::setColor(int couleur) { + /*this->r = this->tabColor[couleur][0]; + this->v = this->tabColor[couleur][1]; + this->b = this->tabColor[couleur][2];*/ + switch (couleur) { + case 0: setColorAll(10, 10, 10); //blanc + break; + case 1: setColorAll(100, 0, 0); //rouge + break; + case 2: setColorAll(0, 100, 0); //bleu + break; + case 3: setColorAll(0, 0, 100); //vert + break; + case 4: setColorAll(100, 255, 255); //turquoise + break; + case 5: setColorAll(255, 0, 50); //orange + break; + case 6: setColorAll(160, 160, 160); //gris + break; + case 7: setColorAll(153, 0, 153); //jaune + break; + case 8: setColorAll(255, 255, 51); //magenta + break; + case 9: setColorAll(120, 120, 0); //violet + break; + default: + break; + } +} + + +void Led::ledOnOff(bool state) { + if (state == 1) { + int cpt; + for (cpt = 0; cpt < this->number; cpt++) { + this->strip.setPixelColor(cpt, 255, 255, 255); + } + this->strip.show(); + } + else if (state == 0) { + int cpt; + for (cpt = 0; cpt < this->number; cpt++) { + this->strip.setPixelColor(cpt, 0, 0, 0); + } + this->strip.show(); + } +} diff --git a/pool/shard006/C++/0078596_init_process_reaper.cc b/pool/shard006/C++/0078596_init_process_reaper.cc new file mode 100644 index 0000000000000000000000000000000000000000..2e0b90b7b5dd04fa26878d1691a0cce799658760 --- /dev/null +++ b/pool/shard006/C++/0078596_init_process_reaper.cc @@ -0,0 +1,101 @@ +// 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 "sandbox/linux/services/init_process_reaper.h" + +#include +#include +#include +#include +#include +#include + +#include "base/callback.h" +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" + +namespace sandbox { + +namespace { + +void DoNothingSignalHandler(int signal) {} + +} // namespace + +bool CreateInitProcessReaper(base::Closure* post_fork_parent_callback) { + int sync_fds[2]; + // We want to use send, so we can't use a pipe + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)) { + PLOG(ERROR) << "Failed to create socketpair"; + return false; + } + pid_t child_pid = fork(); + if (child_pid == -1) { + int close_ret; + close_ret = IGNORE_EINTR(close(sync_fds[0])); + DPCHECK(!close_ret); + close_ret = IGNORE_EINTR(close(sync_fds[1])); + DPCHECK(!close_ret); + return false; + } + if (child_pid) { + // In the parent, assuming the role of an init process. + // The disposition for SIGCHLD cannot be SIG_IGN or wait() will only return + // once all of our childs are dead. Since we're init we need to reap childs + // as they come. + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_handler = &DoNothingSignalHandler; + CHECK(sigaction(SIGCHLD, &action, NULL) == 0); + + int close_ret; + close_ret = IGNORE_EINTR(close(sync_fds[0])); + DPCHECK(!close_ret); + close_ret = shutdown(sync_fds[1], SHUT_RD); + DPCHECK(!close_ret); + if (post_fork_parent_callback) + post_fork_parent_callback->Run(); + // Tell the child to continue + CHECK(HANDLE_EINTR(send(sync_fds[1], "C", 1, MSG_NOSIGNAL)) == 1); + close_ret = IGNORE_EINTR(close(sync_fds[1])); + DPCHECK(!close_ret); + + for (;;) { + // Loop until we have reaped our one natural child + siginfo_t reaped_child_info; + int wait_ret = + HANDLE_EINTR(waitid(P_ALL, 0, &reaped_child_info, WEXITED)); + if (wait_ret) + _exit(1); + if (reaped_child_info.si_pid == child_pid) { + int exit_code = 0; + // We're done waiting + if (reaped_child_info.si_code == CLD_EXITED) { + exit_code = reaped_child_info.si_status; + } + // Exit with the same exit code as our parent. Exit with 0 if we got + // signaled. + _exit(exit_code); + } + } + } else { + // The child needs to wait for the parent to run the callback to avoid a + // race condition. + int close_ret; + close_ret = IGNORE_EINTR(close(sync_fds[1])); + DPCHECK(!close_ret); + close_ret = shutdown(sync_fds[0], SHUT_WR); + DPCHECK(!close_ret); + char should_continue; + int read_ret = HANDLE_EINTR(read(sync_fds[0], &should_continue, 1)); + close_ret = IGNORE_EINTR(close(sync_fds[0])); + DPCHECK(!close_ret); + if (read_ret == 1) + return true; + else + return false; + } +} + +} // namespace sandbox. diff --git a/pool/shard006/C++/0078598_boss_ambassador_hellmaw.cpp b/pool/shard006/C++/0078598_boss_ambassador_hellmaw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f385768043b3ef9ac69b33d7e127a366cb26e13 --- /dev/null +++ b/pool/shard006/C++/0078598_boss_ambassador_hellmaw.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (C) 2008-2012 TrinityCore + * Copyright (C) 2006-2012 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +/* ScriptData +SDName: Boss_Ambassador_Hellmaw +SD%Complete: 80 +SDComment: Enrage spell missing/not known +SDCategory: Auchindoun, Shadow Labyrinth +EndScriptData */ + +#include "ScriptPCH.h" +#include "ScriptedEscortAI.h" +#include "shadow_labyrinth.h" + +enum eEnums +{ + SAY_INTRO = -1555000, + SAY_AGGRO1 = -1555001, + SAY_AGGRO2 = -1555002, + SAY_AGGRO3 = -1555003, + SAY_HELP = -1555004, + SAY_SLAY1 = -1555005, + SAY_SLAY2 = -1555006, + SAY_DEATH = -1555007, + + SPELL_BANISH = 30231, + SPELL_CORROSIVE_ACID = 33551, + SPELL_FEAR = 33547, + SPELL_ENRAGE = 34970 +}; + +class boss_ambassador_hellmaw : public CreatureScript +{ +public: + boss_ambassador_hellmaw() : CreatureScript("boss_ambassador_hellmaw") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_ambassador_hellmawAI(creature); + } + + struct boss_ambassador_hellmawAI : public npc_escortAI + { + boss_ambassador_hellmawAI(Creature* creature) : npc_escortAI(creature) + { + m_pInstance = creature->GetInstanceScript(); + } + + InstanceScript* m_pInstance; + + uint32 EventCheck_Timer; + uint32 CorrosiveAcid_Timer; + uint32 Fear_Timer; + uint32 Enrage_Timer; + bool Intro; + bool IsBanished; + bool Enraged; + + void Reset() + { + EventCheck_Timer = 5000; + CorrosiveAcid_Timer = urand(5000, 10000); + Fear_Timer = urand(25000, 30000); + Enrage_Timer = 180000; + Intro = false; + IsBanished = true; + Enraged = false; + + if (m_pInstance && me->isAlive()) + { + if (m_pInstance->GetData(TYPE_OVERSEER) != DONE) + DoCast(me, SPELL_BANISH, true); + } + } + + void JustReachedHome() + { + if (m_pInstance) + m_pInstance->SetData(TYPE_HELLMAW, FAIL); + } + + void MoveInLineOfSight(Unit* who) + { + if (me->HasAura(SPELL_BANISH)) + return; + + npc_escortAI::MoveInLineOfSight(who); + } + + void WaypointReached(uint32 /*i*/) + { + } + + void DoIntro() + { + if (me->HasAura(SPELL_BANISH)) + me->RemoveAurasDueToSpell(SPELL_BANISH); + + IsBanished = false; + Intro = true; + + if (m_pInstance) + { + if (m_pInstance->GetData(TYPE_HELLMAW) != FAIL) + { + DoScriptText(SAY_INTRO, me); + Start(true, false, 0, NULL, false, true); + } + + m_pInstance->SetData(TYPE_HELLMAW, IN_PROGRESS); + } + } + + void EnterCombat(Unit* /*who*/) + { + DoScriptText(RAND(SAY_AGGRO1, SAY_AGGRO2, SAY_AGGRO3), me); + } + + void KilledUnit(Unit* /*victim*/) + { + DoScriptText(RAND(SAY_SLAY1, SAY_SLAY2), me); + } + + void JustDied(Unit* /*victim*/) + { + DoScriptText(SAY_DEATH, me); + + if (m_pInstance) + m_pInstance->SetData(TYPE_HELLMAW, DONE); + } + + void UpdateAI(const uint32 diff) + { + if (!Intro && !HasEscortState(STATE_ESCORT_ESCORTING)) + { + if (EventCheck_Timer <= diff) + { + if (m_pInstance) + { + if (m_pInstance->GetData(TYPE_OVERSEER) == DONE) + { + DoIntro(); + return; + } + } + EventCheck_Timer = 5000; + return; + } + else + { + EventCheck_Timer -= diff; + return; + } + } + + npc_escortAI::UpdateAI(diff); + + if (!UpdateVictim()) + return; + + if (me->HasAura(SPELL_BANISH, 0)) + { + EnterEvadeMode(); + return; + } + + if (CorrosiveAcid_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_CORROSIVE_ACID); + CorrosiveAcid_Timer = urand(15000, 25000); + } else CorrosiveAcid_Timer -= diff; + + if (Fear_Timer <= diff) + { + DoCast(me, SPELL_FEAR); + Fear_Timer = urand(20000, 35000); + } else Fear_Timer -= diff; + + if (IsHeroic()) + { + if (!Enraged && Enrage_Timer <= diff) + { + DoCast(me, SPELL_ENRAGE); + Enraged = true; + } else Enrage_Timer -= diff; + } + } + }; +}; + +void AddSC_boss_ambassador_hellmaw() +{ + new boss_ambassador_hellmaw(); +} \ No newline at end of file diff --git a/pool/shard006/C++/0078614_parser.cpp b/pool/shard006/C++/0078614_parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3853413fb72f3db77304347bf84a7792c4ce7f5 --- /dev/null +++ b/pool/shard006/C++/0078614_parser.cpp @@ -0,0 +1,157 @@ +/* Uses Jsoncpp, reference here: + * http://open-source-parsers.github.io/jsoncpp-docs/ + */ +#include "parser.h" +#include + + +Parser::Parser(std::string filename) +{ + init(); + + std::ifstream contents(filename, std::ifstream::binary); + + /* root is the top-level handle on the json object we parse */ + Json::Reader reader; + if (reader.parse(contents, root, false) == false) { + std::cerr << "Error parsing scene" << std::endl; + } +} + +Parser::Parser(Json::Value root) : root(root) +{ + init(); +} + +void Parser::init() +{ + /* We map object types to their JSON converters. */ + converters.insert( + std::make_pair("sphere", (json_converter)&Parser::json_to_sphere) + ); + converters.insert( + std::make_pair("box", (json_converter)&Parser::json_to_box) + ); + converters.insert( + std::make_pair("point_light", + (json_converter)&Parser::json_to_point_light) + ); +} + +bool Parser::valid_object_type(std::string type) +{ + /* Is the type in the map? */ + return converters.find(type) != converters.end(); +} + +vector3_t Parser::json_to_vector3(Json::Value json_vector) +{ + return vector3_t( + json_vector["x"].asDouble(), + json_vector["y"].asDouble(), + json_vector["z"].asDouble() + ); +} + +color_t Parser::json_to_color(Json::Value json_color) +{ + return color_t( + json_color["r"].asDouble(), + json_color["g"].asDouble(), + json_color["b"].asDouble(), + json_color["a"].asDouble() + ); +} + +material_t Parser::json_to_material(Json::Value json_material) +{ + material_t mat = material_t( + json_to_color(json_material["ambient"]), + json_to_color(json_material["diffuse"]), + json_to_color(json_material["specular"]), + json_to_color(json_material["emission"]), + json_material["reflection"].asDouble() + ); + + /* Pptionally set refraction amount, and index of refraction. + If unspecified default to 0 and 1 respectively. */ + mat.refraction = + json_material.get("refraction", Json::Value(0.0)).asDouble(); + mat.refraction_index = + json_material.get("refraction_index", Json::Value(1)).asDouble(); + mat.texture = json_material.get("texture", Json::Value(false)).asBool(); + + + return mat; +} + +Sphere *Parser::json_to_sphere(Json::Value json_sphere) +{ + return new Sphere( + json_to_vector3(json_sphere["loc"]), + json_to_material(json_sphere["material"]), + json_sphere["radius"].asDouble() + ); +} + +Box *Parser::json_to_box(Json::Value json_box) +{ + return new Box( + json_to_vector3(json_box["min"]), + json_to_vector3(json_box["max"]), + json_to_material(json_box["material"]) + ); +} + +PointLight *Parser::json_to_point_light(Json::Value json_point_light) { + + return new PointLight( + json_to_vector3(json_point_light["loc"]), + json_to_color(json_point_light["intensity"])); +} + +scene_t Parser::parse() +{ + scene_t scene; + + /* The list of scene objects is referenced by key: + * "scene_objects" + */ + Json::Value scene_objs_json = root["scene_objects"]; + /* Create scene_obj from each item in JSON "scene_objects"[] + * based on object_type; append object into scene_objs vector + */ + for (Json::ValueIterator itr = scene_objs_json.begin(); + itr != scene_objs_json.end(); itr++) { + + /* We branch based on the type of object we encounter + * in the scene file. + */ + std::string type = (*itr)["object_type"].asString(); + if (valid_object_type(type)) { + json_converter c = converters[type]; + scene.objects.push_back((this->*c)(*itr)); + } + else { + std::cerr << "UNKNOWN TYPE " << type << std::endl; + } + } + Json::Value scene_lights_json = root["scene_lights"]; + for (Json::ValueIterator itr = scene_lights_json.begin(); + itr != scene_lights_json.end(); itr++) { + + /* We branch based on the type of object we encounter + * in the scene file. + */ + std::string type = (*itr)["object_type"].asString(); + if (valid_object_type(type)) { + json_converter c = converters[type]; + scene.lights.push_back((this->*c)(*itr)); + } + else { + std::cerr << "UNKNOWN TYPE " << type << std::endl; + } + } + + return scene; +} diff --git a/pool/shard006/C++/0078616_DrawingElement.cpp b/pool/shard006/C++/0078616_DrawingElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f6bd15105fa8149827994bb4ba2383df78947b2 --- /dev/null +++ b/pool/shard006/C++/0078616_DrawingElement.cpp @@ -0,0 +1,230 @@ +// +// DrawingElement.cpp +// +// Sketchup C++ Wrapper for C API +// MIT License +// +// Copyright (c) 2017 Tom Kaneko +// +// 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. +// + +// Macro for getting rid of unused variables commonly for assert checking +#define _unused(x) ((void)(x)) + +#include "SUAPI-CppWrapper/model/DrawingElement.hpp" + +#include +#include + +#include "SUAPI-CppWrapper/model/Layer.hpp" +#include "SUAPI-CppWrapper/model/Material.hpp" +#include "SUAPI-CppWrapper/Geometry.hpp" + + +namespace CW { + +DrawingElement::DrawingElement(SUDrawingElementRef drawing_element, bool attached): + Entity(SUDrawingElementToEntity(drawing_element), attached) +{} + + +DrawingElement::DrawingElement(const DrawingElement& other, SUDrawingElementRef element_ref): + Entity(other, SUDrawingElementToEntity(element_ref)) +{} + +DrawingElement::DrawingElement(): + Entity() +{} + + +/** Copy assignment operator */ +DrawingElement& DrawingElement::operator=(const DrawingElement& other) { + if (!other.m_attached && SUIsValid(other.m_entity)) { + this->copy_properties_from(other); + } + Entity::operator=(other); + return (*this); +} + + +SUDrawingElementRef DrawingElement::ref() const { + return SUDrawingElementFromEntity(m_entity); +} + + +DrawingElement::operator SUDrawingElementRef() const { + return this->ref(); +} + + +BoundingBox3D DrawingElement::bounds() { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::bounds(): DrawingElement is null"); + } + SUBoundingBox3D box; + SUResult res = SUDrawingElementGetBoundingBox(this->ref(), &box); + assert(res == SU_ERROR_NONE); _unused(res); + return BoundingBox3D(box); +} + + +bool DrawingElement::copy_properties_from(const DrawingElement& element) { + bool success = this->casts_shadows(element.casts_shadows()); + if (!success) + return false; + success = this->hidden(element.hidden()); + if (!success) + return false; + success = this->receive_shadows(element.receive_shadows()); + if (!success) + return false; + Layer elem_layer = element.layer(); + success = this->layer(elem_layer); + if (!success) + return false; + success = this->material(element.material()); + if (!success) + return false; + + return true; +} + + +bool DrawingElement::casts_shadows() const { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::casts_shadows(): DrawingElement is null"); + } + bool cast_shadows_flag; + SUResult res = SUDrawingElementGetCastsShadows(this->ref(), &cast_shadows_flag); + assert(res == SU_ERROR_NONE); _unused(res); + return cast_shadows_flag; +} + + +bool DrawingElement::casts_shadows(bool casts_shadows) { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::casts_shadows(): DrawingElement is null"); + } + SUResult res = SUDrawingElementSetCastsShadows(this->ref(), casts_shadows); + if (res == SU_ERROR_NONE) { + return true; + } + return false; +} + + +bool DrawingElement::hidden() const { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::hidden(): DrawingElement is null"); + } + bool hide_flag; + SUDrawingElementGetHidden(this->ref(), &hide_flag); + return hide_flag; +} + + +bool DrawingElement::hidden(bool hidden) { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::hidden(): DrawingElement is null"); + } + SUResult res = SUDrawingElementSetHidden(this->ref(), hidden); + if (res == SU_ERROR_NONE) { + return true; + } + return false; +} + + +Layer DrawingElement::layer() const { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::layer(): DrawingElement is null"); + } + SULayerRef layer_ref = SU_INVALID; + SUResult res = SUDrawingElementGetLayer(this->ref(), &layer_ref); + if (res == SU_ERROR_NULL_POINTER_OUTPUT || res == SU_ERROR_NO_DATA) { + return Layer(); + } + assert(res == SU_ERROR_NONE); _unused(res); + return Layer(layer_ref, true); +} + + +bool DrawingElement::layer(Layer& layer){ + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::layer(): DrawingElement is null"); + } + SUResult res = SUDrawingElementSetLayer(this->ref(), layer); + if (res == SU_ERROR_NONE) { + layer.attached(true); + return true; + } + return false; +} + + +Material DrawingElement::material() const { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::material(): DrawingElement is null"); + } + SUMaterialRef material_ref = SU_INVALID; + SUResult res = SUDrawingElementGetMaterial(this->ref(), &material_ref); + if (res == SU_ERROR_NO_DATA || res == SU_ERROR_NULL_POINTER_OUTPUT) { + return Material(); + } + assert(res == SU_ERROR_NONE); _unused(res); + return Material(material_ref, true); +} + + +bool DrawingElement::material(const Material& material) { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::material(): DrawingElement is null"); + } + SUResult res = SUDrawingElementSetMaterial(this->ref(), material); + if (res == SU_ERROR_NONE) { + return true; + } + return false; +} + + +bool DrawingElement::receive_shadows() const { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::receive_shadows(): DrawingElement is null"); + } + bool receives_shadows_flag; + SUResult res = SUDrawingElementGetReceivesShadows(this->ref(), &receives_shadows_flag); + assert (res == SU_ERROR_NONE); _unused(res); + return receives_shadows_flag; +} + + +bool DrawingElement::receive_shadows(bool receives_shadows_flag) { + if (SUIsInvalid(m_entity)) { + throw std::logic_error("CW::DrawingElement::receive_shadows(): DrawingElement is null"); + } + SUResult res = SUDrawingElementSetReceivesShadows(this->ref(), receives_shadows_flag); + if (res == SU_ERROR_NONE) { + return true; + } + return false; +} + +} /* namespace CW */ diff --git a/pool/shard006/C++/0078617_stackdriver_client_test.cc b/pool/shard006/C++/0078617_stackdriver_client_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..aeddc8e778f26f5eb3074f5c4c4e87ba7b58e020 --- /dev/null +++ b/pool/shard006/C++/0078617_stackdriver_client_test.cc @@ -0,0 +1,215 @@ +/* Copyright 2020 Google LLC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + 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 "monitoring/stackdriver_client.h" + +#include +#include + +#include + +#include "google/monitoring/v3/metric_service_mock.grpc.pb.h" +#include "google/protobuf/util/json_util.h" + +namespace tensorflow { +namespace monitoring { + +using ::testing::_; +using ::testing::Return; + +namespace { +inline void SetPointValue(int64 value, Point* point) { + point->value_type = ValueType::kInt64; + point->int64_value = value; +} + +inline void SetPointValue(std::list value, Point* point) { + point->value_type = ValueType::kHistogram; + HistogramProto& histogram = point->histogram_value; + + // 2 buckets: (-oo, 0] and (0, +oo) + histogram.add_bucket_limit(0.0); + histogram.add_bucket(0.0); + histogram.add_bucket_limit(DBL_MAX); + histogram.add_bucket(0.0); + + if (value.empty()) { + return; + } + + histogram.set_min(value.front()); + histogram.set_max(value.front()); + histogram.set_num(value.size()); + for (double sample : value) { + histogram.set_min(std::min(histogram.min(), sample)); + histogram.set_max(std::max(histogram.max(), sample)); + histogram.set_sum(histogram.sum() + sample); + histogram.set_sum_squares(histogram.sum_squares() + sample * sample); + size_t bucket_id = (sample < 0.0) ? 0 : 1; + histogram.set_bucket(bucket_id, histogram.bucket(bucket_id) + 1); + } +} + +template +std::unique_ptr MakePointSet(std::string name, int64 time_millis, + std::initializer_list values) { + auto point_set = std::make_unique(); + point_set->metric_name = std::move(name); + for (auto& value : values) { + auto point = std::make_unique(); + SetPointValue(std::move(value), point.get()); + point->end_timestamp_millis = time_millis; + point_set->points.emplace_back(std::move(point)); + } + return point_set; +} + +MATCHER_P(EqualsRequest, expected, "The expected request does not match") { + *result_listener << "as the expected is " << expected.DebugString(); + return expected.SerializeAsString() == arg.SerializeAsString(); +} + +} // namespace + +TEST(StackdriverClientTest, CreateTimeSeries) { + std::map> point_set_map; + point_set_map["/metric_1"] = MakePointSet( + "/metric_1", // metric type is "custom.googleapis.com/metric_1" + 12345, // timestamp is 12 seconds and 345,000,000 nanoseconds + {33, 44}); // the first number 33 is exported as int64_value + point_set_map["/metric_2"] = MakePointSet( + "/metric_2", // metric type is "custom.googleapis.com/metric_2" + 12345, // timestamp is 12 seconds and 345,000,000 nanoseconds + {std::list{-1.0, 1.0}}); // one histogram containing {-1.0, 1.0} + + const std::string expected_request_json = R"( + { + "name": "projects/test_project", + "time_series": [ + { + "metric": { + "type": "custom.googleapis.com/metric_1", + }, + "resource": { + "type": "global" + }, + "points": { + "interval": { + "end_time": { + "seconds": 12, + "nanos": 345000000, + }, + }, + "value": { + "int64_value": 33, + }, + }, + }, + { + "metric": { + "type": "custom.googleapis.com/metric_2", + }, + "resource": { + "type": "global" + }, + "points": { + "interval": { + "end_time": { + "seconds": 12, + "nanos": 345000000, + }, + }, + "value": { + "distribution_value": { + "count": 2, + "mean": 0.0, + "sum_of_squared_deviation": 2.0, + "bucket_options": { + "explicit_buckets": { + "bounds": [ + 0.0, + ], + }, + }, + "bucket_counts": [ + 1, + 1, + ], + } + }, + }, + }, + ], + } + )"; + google::monitoring::v3::CreateTimeSeriesRequest expected_request; + auto status = google::protobuf::util::JsonStringToMessage( + expected_request_json, &expected_request); + ASSERT_TRUE(status.ok()) << status.error_message(); + + auto mock_metric_service = + std::make_unique(); + EXPECT_CALL(*mock_metric_service, + CreateTimeSeries(_, EqualsRequest(expected_request), _)) + .WillOnce(Return(::grpc::Status::OK)); + StackdriverClient client({"test_project"}, std::move(mock_metric_service)); + EXPECT_OK(client.CreateTimeSeries(point_set_map)); +} + +TEST(StackdriverClientTest, CreateMetricDescriptor) { + MetricDescriptor metric_descriptor{ + .name = "metric_1", + .description = "desc", + .label_names = {"a", "b"}, + .metric_kind = MetricKind::kCumulative, + .value_type = ValueType::kInt64, + }; + + const std::string expected_request_json = R"( + { + name: "projects/test_project", + metric_descriptor: { + name: "metric_1", + type: "custom.googleapis.commetric_1", + description: "desc", + labels: [ + { + key: "a" + }, + { + key: "b" + } + ], + metric_kind: 3, + value_type: 2, + }, + } + )"; + google::monitoring::v3::CreateMetricDescriptorRequest expected_request; + auto status = google::protobuf::util::JsonStringToMessage( + expected_request_json, &expected_request); + ASSERT_TRUE(status.ok()) << status.error_message(); + + auto mock_metric_service = + std::make_unique(); + EXPECT_CALL(*mock_metric_service, + CreateMetricDescriptor(_, EqualsRequest(expected_request), _)) + .WillOnce(Return(::grpc::Status::OK)); + StackdriverClient client({"test_project"}, std::move(mock_metric_service)); + EXPECT_OK(client.CreateMetricDescriptor(metric_descriptor)); +} + +} // namespace monitoring +} // namespace tensorflow diff --git a/pool/shard006/C++/0078620_qgsclassificationjenks.cpp b/pool/shard006/C++/0078620_qgsclassificationjenks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5211a1656015ce155e6718153c0feb0d429a33b3 --- /dev/null +++ b/pool/shard006/C++/0078620_qgsclassificationjenks.cpp @@ -0,0 +1,192 @@ +/*************************************************************************** + qgsclassificationjenks.h + --------------------- + begin : September 2019 + copyright : (C) 2019 by Denis Rouzaud + email : denis@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include +#include "qgsclassificationjenks.h" +#include "qgsapplication.h" + +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) +#include +#endif + +QgsClassificationJenks::QgsClassificationJenks() + : QgsClassificationMethod() +{ + +} + +QString QgsClassificationJenks::name() const +{ + return QObject::tr( "Natural Breaks (Jenks)" ); +} + +QString QgsClassificationJenks::id() const +{ + return QStringLiteral( "Jenks" ); +} + +QgsClassificationMethod *QgsClassificationJenks::clone() const +{ + QgsClassificationJenks *c = new QgsClassificationJenks(); + copyBase( c ); + return c; +} + +QIcon QgsClassificationJenks::icon() const +{ + return QgsApplication::getThemeIcon( "classification_methods/mClassificationNaturalBreak.svg" ); +} + + +QList QgsClassificationJenks::calculateBreaks( double &minimum, double &maximum, + const QList &values, int nclasses ) +{ + // Jenks Optimal (Natural Breaks) algorithm + // Based on the Jenks algorithm from the 'classInt' package available for + // the R statistical prgramming language, and from Python code from here: + // http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/ + // and is based on a JAVA and Fortran code available here: + // https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html + + // Returns class breaks such that classes are internally homogeneous while + // assuring heterogeneity among classes. + + if ( values.isEmpty() ) + return QList(); + + if ( nclasses <= 1 ) + { + return QList() << maximum; + } + + if ( nclasses >= values.size() ) + { + return values; + } + + QVector sample; + QVector sorted; + + // if we have lots of values, we need to take a random sample + if ( values.size() > mMaximumSize ) + { + // for now, sample at least maximumSize values or a 10% sample, whichever + // is larger. This will produce a more representative sample for very large + // layers, but could end up being computationally intensive... + + sample.resize( std::max( mMaximumSize, static_cast( values.size() ) / 10 ) ); + + QgsDebugMsgLevel( QStringLiteral( "natural breaks (jenks) sample size: %1" ).arg( sample.size() ), 2 ); + QgsDebugMsgLevel( QStringLiteral( "values:%1" ).arg( values.size() ), 2 ); + + sample[ 0 ] = minimum; + sample[ 1 ] = maximum; + + sorted = values.toVector(); + std::sort( sorted.begin(), sorted.end() ); + + int j = -1; + + // loop through all values in initial array + // skip the first value as it is a minimum one + // skip the last value as that one is a maximum one + // and those are already in the sample as items 0 and 1 + for ( int i = 1; i < sorted.size() - 2; i++ ) + { + if ( ( i * ( mMaximumSize - 2 ) / ( sorted.size() - 2 ) ) > j ) + { + j++; + sample[ j + 2 ] = sorted[ i ]; + } + } + } + else + { + sample = values.toVector(); + } + + const int n = sample.size(); + + // sort the sample values + std::sort( sample.begin(), sample.end() ); + + QVector< QVector > matrixOne( n + 1 ); + QVector< QVector > matrixTwo( n + 1 ); + + for ( int i = 0; i <= n; i++ ) + { + matrixOne[i].resize( nclasses + 1 ); + matrixTwo[i].resize( nclasses + 1 ); + } + + for ( int i = 1; i <= nclasses; i++ ) + { + matrixOne[0][i] = 1; + matrixOne[1][i] = 1; + matrixTwo[0][i] = 0.0; + for ( int j = 2; j <= n; j++ ) + { + matrixTwo[j][i] = std::numeric_limits::max(); + } + } + + for ( int l = 2; l <= n; l++ ) + { + double s1 = 0.0; + double s2 = 0.0; + int w = 0; + + double v = 0.0; + + for ( int m = 1; m <= l; m++ ) + { + const int i3 = l - m + 1; + + const double val = sample[ i3 - 1 ]; + + s2 += val * val; + s1 += val; + w++; + + v = s2 - ( s1 * s1 ) / static_cast< double >( w ); + const int i4 = i3 - 1; + if ( i4 != 0 ) + { + for ( int j = 2; j <= nclasses; j++ ) + { + if ( matrixTwo[l][j] >= v + matrixTwo[i4][j - 1] ) + { + matrixOne[l][j] = i4; + matrixTwo[l][j] = v + matrixTwo[i4][j - 1]; + } + } + } + } + matrixOne[l][1] = 1; + matrixTwo[l][1] = v; + } + + QVector breaks( nclasses ); + breaks[nclasses - 1] = sample[n - 1]; + + for ( int j = nclasses, k = n; j >= 2; j-- ) + { + const int id = matrixOne[k][j] - 1; + breaks[j - 2] = sample[id]; + k = matrixOne[k][j] - 1; + } + + return breaks.toList(); +} diff --git a/pool/shard006/C++/0078623_RPC.cpp b/pool/shard006/C++/0078623_RPC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..163f14e2b9bc9153afda45f02ad741f3397bd568 --- /dev/null +++ b/pool/shard006/C++/0078623_RPC.cpp @@ -0,0 +1,212 @@ +#include "RPC.h" +#include "../../../General/Driver/Network/LibEvent/ZNetworkLibEvent.h" +#include "../../../Core/Driver/Thread/Pthread/ZThreadPthread.h" +#include "../../../General/Misc/RemoteProxy.h" + +using namespace PaintsNow; + +class Foo : public TReflected { +public: + Foo() {} + + virtual TObject& operator () (IReflect& reflect) { + BaseClass::operator () (reflect); + if (reflect.IsReflectMethod()) { + ReflectMethod(RequestNewFoo)[ScriptMethod = "NewFoo"]; + } + + return *this; + } + + void RequestNewFoo(IScript::Request& request, int a, const String& str) { + + } +}; + +class PrefabFactory : public TWrapper { +public: + PrefabFactory(IThread& threadApi) : TWrapper(Wrap(this, &PrefabFactory::CreateObject)), thread(threadApi) {} + class Prefab : public TReflected { + public: + virtual TObject& operator () (IReflect& reflect) { + BaseClass::operator () (reflect); + if (reflect.IsReflectMethod()) { + ReflectMethod(Test)[ScriptMethod]; + ReflectMethod(Complete)[ScriptMethod]; + } + + return *this; + } + + void Test(IScript::Request& request, uint32_t p, const String& message, int value) { + printf("Message: %s : %d, %d\n", message.c_str(), p, value); + } + + void Complete(IScript::Request& request, const String& message) { + printf("Complete: %s\n", message.c_str()); + } + + virtual void ScriptUninitialize(IScript::Request& request) {} + }; + + IScript::Object* CreateObject(const String& entry) const { + printf("Hello %s \n", entry.c_str()); + return new Prefab(); + } + + IThread& thread; +}; + +void Then(IScript::Request& request) { + IScript::Request::ArrayStart ns; + request >> ns; + for (size_t i = 0; i < ns.count; i++) { + String name; + request >> begintable; + request << key("Name") >> name; + printf("Name: %s\n", name.c_str()); + IScript::Request::ArrayStart ts; + request << key("Arguments") >> ts; + for (size_t j = 0; j < ts.count; j++) { + request >> name; + printf("\tArg[%d]: %s\n", (int)j, name.c_str()); + } + request << endarray; + request << endtable; + } + request << endarray; +} + +void After(IScript::Request& request, IScript::Request::Ref prefab) { + request.DoLock(); + request.Push(); + request.Call(prefab, 0, String("abcasdfwhaodkjfo;asld;asdgihaosdfi")); + request.Pop(); + request.UnLock(); +} + +class MyPrefab : public TReflected { +public: + virtual TObject& operator () (IReflect& reflect) { + BaseClass::operator () (reflect); + if (reflect.IsReflectProperty()) { + ReflectProperty(Test)[ScriptRemoteMethod(&PrefabFactory::Prefab::Test)]; + ReflectProperty(Complete)[ScriptRemoteMethod(&PrefabFactory::Prefab::Complete)]; + } + return *this; + } + TWrapper Test; + TWrapper Complete; +} myPrefab; + +void OnFinish(IScript::Request& request) { + printf("FINISH!\n"); +} + +void OnQueryPrefab(IScript::Request& request, IReflectObject& inter, const IScript::Request::Ref& ref) { + assert(&myPrefab == &inter); + String s = "Hello, World"; + + request.DoLock(); + request.Push(); + myPrefab.Test(request.Adapt(Wrap(OnFinish)), request, 666, s, 1234); + request.Pop(); + request.Push(); + myPrefab.Complete(request.Adapt(Wrap(OnFinish)), request, s); + request.Pop(); + request.UnLock(); + + /* + request.DoLock(); + request.Push(); + request.Call(ref, 0, "abcasdfwhaodkjfo;asld;asdgihaosdfi"); + request.Pop(); + request.UnLock();*/ +} + +void OnQuery(IScript::Request& request, IReflectObject& inter, const IScript::Request::Ref& ref) { + RemoteFactory& testInterface = static_cast(inter); + IScript::Request::Ref prefab; + request.DoLock(); + request.Push(); + + // You can choose either sync or async call. + testInterface.NewObject(IScript::Request::Sync(), request, "Prefab"); + request >> prefab; + + request.QueryInterface(Wrap(OnQueryPrefab), myPrefab, prefab); + request.Pop(); + request.UnLock(); + + /* + if (prefab) { + request.Push(); + request.Call(prefab, 0, "abcasdfwhaodkjfo;asld;asdgihaosdfi"); + request.Pop(); + }*/ +} + +void OnConnect(IScript::Request& request, bool isServer, RemoteProxy::STATUS status, const String& info) { + // sync call + printf("Connecting ... %d, %d\n", isServer, status); +} + +void TestRPC() { +} + +bool RPC::Initialize() { + return true; +} + +bool RPC::Run(int randomSeed, int length) { + ZThreadPthread uniqueThreadApi; + Foo foo; + IScript::Library* module = foo.QueryInterface(UniqueType()); + IScript::Object* object = foo.QueryInterface(UniqueType()); + + ZNetworkLibEvent network(uniqueThreadApi); + ITunnel& tunnel = network; + + const PrefabFactory factory(uniqueThreadApi); + + RemoteProxy serverProxy(uniqueThreadApi, tunnel, factory, "127.0.0.1:16384", Wrap(OnConnect)); + serverProxy.Run(); + + for (int i = 0; i < length; i++) { + RemoteProxy clientProxy(uniqueThreadApi, tunnel, factory, "127.0.0.1:16385"); + clientProxy.Run(); + // async create request + IScript::Request* r = clientProxy.NewRequest("127.0.0.1:16384"); + if (r == nullptr) { + printf("Unable to connect RPC server. Stop.\n"); + break; + } + + r->Destroy(); + r = clientProxy.NewRequest("127.0.0.1:16384"); + + IScript::Request& request = *r; + request.DoLock(); + request.Push(); + IScript::Request::Ref global = request.Load("Global", "Initialize"); + RemoteFactory testInterface; + request.QueryInterface(Wrap(OnQuery), testInterface, global); + // parse result + request.Pop(); + request.UnLock(); + getchar(); + + // Close connection + r->Destroy(); + } + + return true; +} + +void RPC::Summary() {} + +TObject& RPC::operator () (IReflect& reflect) { + BaseClass::operator () (reflect); + + return *this; +} \ No newline at end of file diff --git a/pool/shard006/C++/0078634_checkpoints.cpp b/pool/shard006/C++/0078634_checkpoints.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3900164af7cae4176cb4f34695940d0aae195f0 --- /dev/null +++ b/pool/shard006/C++/0078634_checkpoints.cpp @@ -0,0 +1,146 @@ +// Copyright (c) 2009-2012 The GulfCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include // for 'map_list_of()' +#include + +#include "checkpoints.h" + +#include "main.h" +#include "uint256.h" + +namespace Checkpoints +{ + typedef std::map MapCheckpoints; + + // How many times we expect transactions after the last checkpoint to + // be slower. This number is a compromise, as it can't be accurate for + // every system. When reindexing from a fast disk with a slow CPU, it + // can be up to 20, while when downloading from a slow network with a + // fast multicore CPU, it won't be much higher than 1. + static const double fSigcheckVerificationFactor = 5.0; + + struct CCheckpointData { + const MapCheckpoints *mapCheckpoints; + int64 nTimeLastCheckpoint; + int64 nTransactionsLastCheckpoint; + double fTransactionsPerDay; + }; + + bool fEnabled = true; + + // What makes a good checkpoint block? + // + Is surrounded by blocks with reasonable timestamps + // (no blocks before with a timestamp after, none after with + // timestamp before) + // + Contains no strange transactions + static MapCheckpoints mapCheckpoints = + boost::assign::map_list_of + ( 0, uint256("0x00000000b37e82110be5b83b20707ddbb60ac0eb3e7d6f65cf29661a55128ed3")) + ( 6870, uint256("0x0000000000013e4806cf9d4c107afe309c750e346b4be4c10ce78a5f8eb4dbd3")) + ; + static const CCheckpointData data = { + &mapCheckpoints, + 1492065540, // * UNIX timestamp of last checkpoint block + 6900, // * total number of transactions between genesis and last checkpoint + }; + + static MapCheckpoints mapCheckpointsTestnet = + boost::assign::map_list_of + ( 0, uint256("00000000b37e82110be5b83b20707ddbb60ac0eb3e7d6f65cf29661a55128ed3")) + ; + static const CCheckpointData dataTestnet = { + &mapCheckpointsTestnet, + }; + + static MapCheckpoints mapCheckpointsRegtest = + boost::assign::map_list_of + ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")) + ; + static const CCheckpointData dataRegtest = { + &mapCheckpointsRegtest, + 0, + 0, + 0 + }; + + const CCheckpointData &Checkpoints() { + if (Params().NetworkID() == CChainParams::TESTNET) + return dataTestnet; + else if (Params().NetworkID() == CChainParams::MAIN) + return data; + else + return dataRegtest; + } + + bool CheckBlock(int nHeight, const uint256& hash) + { + if (!fEnabled) + return true; + + const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; + + MapCheckpoints::const_iterator i = checkpoints.find(nHeight); + if (i == checkpoints.end()) return true; + return hash == i->second; + } + + // Guess how far we are in the verification process at the given block index + double GuessVerificationProgress(CBlockIndex *pindex) { + if (pindex==NULL) + return 0.0; + + int64 nNow = time(NULL); + + double fWorkBefore = 0.0; // Amount of work done before pindex + double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) + // Work is defined as: 1.0 per transaction before the last checkoint, and + // fSigcheckVerificationFactor per transaction after. + + const CCheckpointData &data = Checkpoints(); + + if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { + double nCheapBefore = pindex->nChainTx; + double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; + double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; + fWorkBefore = nCheapBefore; + fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; + } else { + double nCheapBefore = data.nTransactionsLastCheckpoint; + double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; + double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; + fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; + fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; + } + + return fWorkBefore / (fWorkBefore + fWorkAfter); + } + + int GetTotalBlocksEstimate() + { + if (!fEnabled) + return 0; + + const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; + + return checkpoints.rbegin()->first; + } + + CBlockIndex* GetLastCheckpoint(const std::map& mapBlockIndex) + { + if (!fEnabled) + return NULL; + + const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; + + BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) + { + const uint256& hash = i.second; + std::map::const_iterator t = mapBlockIndex.find(hash); + if (t != mapBlockIndex.end()) + return t->second; + } + return NULL; + } +} diff --git a/pool/shard006/C++/0078638_ReactorAI.cpp b/pool/shard006/C++/0078638_ReactorAI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4cff996a8f11482bed1c5a338c726f8de226c94 --- /dev/null +++ b/pool/shard006/C++/0078638_ReactorAI.cpp @@ -0,0 +1,135 @@ +/** + * MaNGOS is a full featured server for World of Warcraft, supporting + * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 + * + * Copyright (C) 2005-2022 MaNGOS + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * World of Warcraft, and all World of Warcraft or Warcraft art, images, + * and lore are copyrighted by Blizzard Entertainment, Inc. + */ + +#include "ByteBuffer.h" +#include "ReactorAI.h" +#include "Errors.h" +#include "Creature.h" +#include "Map.h" +#include "Log.h" + +#define REACTOR_VISIBLE_RANGE (26.46f) + +int +ReactorAI::Permissible(const Creature* creature) +{ + if (creature->IsCivilian() || creature->IsNeutralToAll()) + { + return PERMIT_BASE_REACTIVE; + } + + return PERMIT_BASE_NO; +} + +void +ReactorAI::MoveInLineOfSight(Unit*) +{ +} + +void +ReactorAI::AttackStart(Unit* p) +{ + if (!p || !m_creature->CanInitiateAttack()) + { + return; + } + + if (m_creature->Attack(p, true)) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Tag unit GUID: %u (TypeId: %u) as a victim", p->GetGUIDLow(), p->GetTypeId()); + i_victimGuid = p->GetObjectGuid(); + m_creature->AddThreat(p); + + m_creature->SetInCombatWith(p); + p->SetInCombatWith(m_creature); + + HandleMovementOnAttackStart(p); + } +} + +bool +ReactorAI::IsVisible(Unit*) const +{ + return false; +} + +void +ReactorAI::UpdateAI(const uint32 /*time_diff*/) +{ + // update i_victimGuid if i_creature.getVictim() !=0 and changed + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + { + return; + } + + i_victimGuid = m_creature->getVictim()->GetObjectGuid(); + + DoMeleeAttackIfReady(); +} + +void +ReactorAI::EnterEvadeMode() +{ + if (!m_creature->IsAlive()) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, he is dead [guid=%u]", m_creature->GetGUIDLow()); + m_creature->GetMotionMaster()->MovementExpired(); + m_creature->GetMotionMaster()->MoveIdle(); + i_victimGuid.Clear(); + m_creature->CombatStop(true); + m_creature->DeleteThreatList(); + return; + } + + Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid); + + if (!victim) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, no victim [guid=%u]", m_creature->GetGUIDLow()); + } + else if (victim->HasStealthAura()) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in stealth [guid=%u]", m_creature->GetGUIDLow()); + } + else if (victim->IsTaxiFlying()) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in flight [guid=%u]", m_creature->GetGUIDLow()); + } + else + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim %s [guid=%u]", victim->IsAlive() ? "out run him" : "is dead", m_creature->GetGUIDLow()); + } + + m_creature->RemoveAllAurasOnEvade(); + m_creature->DeleteThreatList(); + i_victimGuid.Clear(); + m_creature->CombatStop(true); + m_creature->SetLootRecipient(NULL); + + // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead + if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) + { + m_creature->GetMotionMaster()->MoveTargetedHome(); + } +} diff --git a/pool/shard006/C++/0078641_test_metro_viewer_process_host.cc b/pool/shard006/C++/0078641_test_metro_viewer_process_host.cc new file mode 100644 index 0000000000000000000000000000000000000000..a5e3fbfa4037003e5aa51c5600f37e4a6e4d3bb0 --- /dev/null +++ b/pool/shard006/C++/0078641_test_metro_viewer_process_host.cc @@ -0,0 +1,50 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/test/test_metro_viewer_process_host.h" + +#include + +#include "base/logging.h" +#include "ui/aura/remote_root_window_host_win.h" +#include "ui/surface/accelerated_surface_win.h" + +namespace ash { +namespace test { + +TestMetroViewerProcessHost::TestMetroViewerProcessHost( + base::SingleThreadTaskRunner* ipc_task_runner) + : MetroViewerProcessHost(ipc_task_runner), closed_unexpectedly_(false) { +} + +TestMetroViewerProcessHost::~TestMetroViewerProcessHost() { +} + +void TestMetroViewerProcessHost::OnChannelError() { + closed_unexpectedly_ = true; + aura::RemoteRootWindowHostWin::Instance()->Disconnected(); +} + +void TestMetroViewerProcessHost::OnSetTargetSurface( + gfx::NativeViewId target_surface) { + DLOG(INFO) << __FUNCTION__ << ", target_surface = " << target_surface; + HWND hwnd = reinterpret_cast(target_surface); + aura::RemoteRootWindowHostWin::Instance()->Connected(this, hwnd); + + backing_surface_.reset(new AcceleratedSurface(hwnd)); +} + +void TestMetroViewerProcessHost::OnOpenURL(const string16& url) { +} + +void TestMetroViewerProcessHost::OnHandleSearchRequest( + const string16& search_string) { +} + +void TestMetroViewerProcessHost::OnWindowSizeChanged(uint32 width, + uint32 height) { +} + +} // namespace test +} // namespace ash diff --git a/pool/shard006/C++/0078643_Firm.cpp b/pool/shard006/C++/0078643_Firm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40ddec1e2121915867c2a388e9f0466449faac28 --- /dev/null +++ b/pool/shard006/C++/0078643_Firm.cpp @@ -0,0 +1,148 @@ +/* + Copyright (C) 2014-2020 Sven Willner + Christian Otto + + This file is part of Acclimate. + + Acclimate 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. + + Acclimate 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 Acclimate. If not, see . +*/ + +#include "model/Firm.h" + +#include +#include + +#include "acclimate.h" +#include "model/CapacityManager.h" +#include "model/EconomicAgent.h" +#include "model/PurchasingManager.h" +#include "model/SalesManager.h" +#include "model/Sector.h" +#include "model/Storage.h" + +namespace acclimate { + +Firm::Firm(id_t id_p, Sector* sector_p, Region* region_p, const Ratio& possible_overcapacity_ratio_beta_p) + : EconomicAgent(std::move(id_p), region_p, EconomicAgent::type_t::FIRM), + sector(sector_p), + capacity_manager(new CapacityManager(this, possible_overcapacity_ratio_beta_p)), + sales_manager(new SalesManager(this)) {} + +void Firm::produce_X() { + debug::assertstep(this, IterationStep::CONSUMPTION_AND_PRODUCTION); + production_X_ = capacity_manager->calc_production_X(); + assert(production_X_.get_quantity() >= 0.0); + sector->add_production_X(production_X_); +} + +void Firm::iterate_consumption_and_production() { + debug::assertstep(this, IterationStep::CONSUMPTION_AND_PRODUCTION); + produce_X(); + for (const auto& is : input_storages) { + Flow used_flow_U_current = round(production_X_ * is->get_technology_coefficient_a()); + if (production_X_.get_quantity() > 0.0) { + used_flow_U_current.set_price(is->get_possible_use_U_hat().get_price()); + } + is->use_content_S(used_flow_U_current); + is->iterate_consumption_and_production(); + } + sales_manager->distribute(); +} + +void Firm::iterate_expectation() { + debug::assertstep(this, IterationStep::EXPECTATION); + sales_manager->iterate_expectation(); + for (const auto& is : input_storages) { + const FlowQuantity& desired_production = + std::max(sales_manager->communicated_parameters().expected_production_X.get_quantity(), sales_manager->sum_demand_requests_D().get_quantity()); + is->set_desired_used_flow_U_tilde(round(desired_production * is->get_technology_coefficient_a())); + } +} + +void Firm::add_initial_production_X_star(const Flow& initial_production_flow_X_star) { + debug::assertstep(this, IterationStep::INITIALIZATION); + initial_production_X_star_ += initial_production_flow_X_star; + production_X_ += initial_production_flow_X_star; + sales_manager->add_initial_demand_request_D_star(initial_production_flow_X_star); + sector->add_initial_production_X(initial_production_flow_X_star); +} + +void Firm::subtract_initial_production_X_star(const Flow& initial_production_flow_X_star) { + debug::assertstep(this, IterationStep::INITIALIZATION); + initial_production_X_star_ -= initial_production_flow_X_star; + production_X_ -= initial_production_flow_X_star; + sales_manager->subtract_initial_demand_request_D_star(initial_production_flow_X_star); + sector->subtract_initial_production_X(initial_production_flow_X_star); +} + +void Firm::add_initial_total_use_U_star(const Flow& initial_use_flow_U_star) { + debug::assertstep(this, IterationStep::INITIALIZATION); + initial_total_use_U_star_ += initial_use_flow_U_star; +} + +void Firm::subtract_initial_total_use_U_star(const Flow& initial_use_flow_U_star) { + debug::assertstep(this, IterationStep::INITIALIZATION); + if (initial_total_use_U_star_.get_quantity() > initial_use_flow_U_star.get_quantity()) { + initial_total_use_U_star_ -= initial_use_flow_U_star; + } else { + initial_total_use_U_star_ = Flow(0.0); + } +} + +void Firm::iterate_purchase() { + debug::assertstep(this, IterationStep::PURCHASE); + for (const auto& is : input_storages) { + is->purchasing_manager->iterate_purchase(); + } +} + +void Firm::iterate_investment() { + // debug::assertstep(this, IterationStep::INVESTMENT); + // for (const auto& is : input_storages) { + // is->purchasing_manager->iterate_investment(); + // } +} + +Flow Firm::maximal_production_beta_X_star() const { return round(initial_production_X_star_ * capacity_manager->possible_overcapacity_ratio_beta); } + +FlowQuantity Firm::forced_maximal_production_quantity_lambda_beta_X_star() const { + return round(initial_production_X_star_.get_quantity() * (capacity_manager->possible_overcapacity_ratio_beta * forcing_m)); +} + +const BusinessConnection* Firm::self_supply_connection() const { + debug::assertstepnot(this, IterationStep::CONSUMPTION_AND_PRODUCTION); + return self_supply_connection_.get(); +} + +void Firm::self_supply_connection(std::shared_ptr self_supply_connection_p) { + debug::assertstep(this, IterationStep::INITIALIZATION); + self_supply_connection_ = std::move(self_supply_connection_p); +} + +const Flow& Firm::production_X() const { + debug::assertstepnot(this, IterationStep::CONSUMPTION_AND_PRODUCTION); + return production_X_; +} + +void Firm::debug_print_details() const { + if constexpr (options::DEBUGGING) { + log::info(this, "X_star= ", initial_production_X_star_.get_quantity(), ":"); + for (const auto& input_storage : input_storages) { + input_storage->purchasing_manager->debug_print_details(); + } + sales_manager->debug_print_details(); + } +} + +} // namespace acclimate diff --git a/pool/shard006/C++/0078645_max_size.pass.cpp b/pool/shard006/C++/0078645_max_size.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b58bac385a4399a0fac9001883057adfcc50dca --- /dev/null +++ b/pool/shard006/C++/0078645_max_size.pass.cpp @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// 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. +// +//===----------------------------------------------------------------------===// + +// + +// class unordered_multimap + +// size_type max_size() const; + +#include +#include +#include +#include + +#include "test_allocator.h" +#include "test_macros.h" + +int main() +{ + typedef std::pair KV; + { + typedef limited_allocator A; + typedef std::unordered_multimap, + std::equal_to, A> + C; + C c; + assert(c.max_size() <= 10); + LIBCPP_ASSERT(c.max_size() == 10); + } + { + typedef limited_allocator A; + typedef std::unordered_multimap, + std::equal_to, A> + C; + const C::difference_type max_dist = + std::numeric_limits::max(); + C c; + assert(c.max_size() <= max_dist); + LIBCPP_ASSERT(c.max_size() == max_dist); + } + { + typedef std::unordered_multimap C; + const C::difference_type max_dist = + std::numeric_limits::max(); + C c; + assert(c.max_size() <= max_dist); + assert(c.max_size() <= alloc_max_size(c.get_allocator())); + } +} diff --git a/pool/shard006/C++/0078646_gist.cpp b/pool/shard006/C++/0078646_gist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c7fb520388eaeb94fc852aa8d51835fda5f2f20 --- /dev/null +++ b/pool/shard006/C++/0078646_gist.cpp @@ -0,0 +1,120 @@ +/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ +/* + * Main authors: + * Guido Tack + * + * Copyright: + * Guido Tack, 2006 + * + * Last modified: + * $Date: 2011-08-25 10:43:31 +0200 (to, 25 aug 2011) $ by $Author: tack $ + * $Revision: 12352 $ + * + * 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 + +#include +#include +#include +#include + +namespace Gecode { namespace Gist { + + std::string + Inspector::name(void) { return "Inspector"; } + + void + Inspector::finalize(void) {} + + Inspector::~Inspector(void) {} + + std::string + Comparator::name(void) { return "Comparator"; } + + void + Comparator::finalize(void) {} + + Comparator::~Comparator(void) {} + + TextOutput::TextOutput(const std::string& name) + : t(NULL), n(name) {} + + void + TextOutput::finalize(void) { + delete t; + t = NULL; + } + + TextOutput::~TextOutput(void) { + delete t; + } + + std::string + TextOutput::name(void) { return n; } + + void + TextOutput::init(void) { + if (t == NULL) { + t = new TextOutputI(n); + } + t->setVisible(true); + } + + std::ostream& + TextOutput::getStream(void) { + return t->getStream(); + } + + void + TextOutput::flush(void) { + t->flush(); + } + + void + TextOutput::addHtml(const char* s) { + t->insertHtml(s); + } + + const Options Options::def; + + int + explore(Space* root, bool bab, const Options& opt) { + char argv0='\0'; char* argv1=&argv0; + int argc=0; + QApplication app(argc, &argv1); + GistMainWindow mw(root, bab, opt); + return app.exec(); + } + + void + stopBranch(Space& home) { + StopBrancher::post(home); + } + +}} + +// STATISTICS: gist-any diff --git a/pool/shard006/C++/0078662_lock_impl_unittest.cc b/pool/shard006/C++/0078662_lock_impl_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..9720f5c7664c24a1517c6a1df3afcabf7e9acca9 --- /dev/null +++ b/pool/shard006/C++/0078662_lock_impl_unittest.cc @@ -0,0 +1,199 @@ +// Copyright (c) 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 "chromeos/components/nearby/lock_impl.h" + +#include + +#include "base/bind.h" +#include "base/containers/flat_set.h" +#include "base/single_thread_task_runner.h" +#include "base/stl_util.h" +#include "base/task/post_task.h" +#include "base/task/thread_pool.h" +#include "base/test/gtest_util.h" +#include "base/test/task_environment.h" +#include "base/test/test_timeouts.h" +#include "base/threading/platform_thread.h" +#include "base/unguessable_token.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { + +namespace nearby { + +class LockImplTest : public testing::Test { + protected: + LockImplTest() + : lock_(std::make_unique()), + different_thread_task_runner_( + base::ThreadPool::CreateSingleThreadTaskRunner( + {base::MayBlock()})) {} + + // testing::Test + void SetUp() override { + // |different_thread_task_runner_| is expected to run on a different thread + // than the main test thread. + EXPECT_FALSE(different_thread_task_runner_->BelongsToCurrentThread()); + } + + void TearDown() override { + // Releases the test thread's ownership of |lock_|. + int times_to_unlock; + { + base::AutoLock al(lock_->bookkeeping_lock_); + times_to_unlock = lock_->num_acquisitions_; + } + for (int i = 0; i < times_to_unlock; ++i) + lock_->unlock(); + + // Makes sure that outstanding LockAndUnlockFromDifferentThread() tasks in + // |different_thread_task_runner_| finish running after the test thread + // relinquishes its ownership of |lock_|. + task_environment_.RunUntilIdle(); + + base::AutoLock al(lock_->bookkeeping_lock_); + EXPECT_EQ(0u, lock_->num_acquisitions_); + EXPECT_EQ(base::kInvalidThreadId, lock_->owning_thread_id_); + } + + void PostLockAndUnlockFromDifferentThread( + const base::UnguessableToken& attempt_id) { + different_thread_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&LockImplTest::LockAndUnlockFromDifferentThread, + base::Unretained(this), attempt_id)); + } + + // Invoked whenever attempting to verify that a parallel task has indeed + // blocked, since there's no way to deterministically find out if that task + // will ever unblock. + void TinyTimeout() { + base::PlatformThread::Sleep(TestTimeouts::tiny_timeout()); + } + + bool HasSuccessfullyLockedWithAttemptId( + const base::UnguessableToken& attempt_id) { + lock_->lock(); + bool contains_key = base::Contains(successful_lock_attempts_, attempt_id); + lock_->unlock(); + return contains_key; + } + + location::nearby::Lock* lock() { return lock_.get(); } + + base::test::TaskEnvironment task_environment_; + + private: + // Only meant to be posted via PostLockAndUnlockFromDifferentThread() on + // |different_thread_task_runner_|. + // + // This method will only insert |attempt_id| into |successful_lock_attempts_| + // if it succeeds in acquiring |lock_|. It will also immediately unlock() + // after doing so because unlock() may only be called from the same thread + // that originally called lock(). + void LockAndUnlockFromDifferentThread( + const base::UnguessableToken& attempt_id) { + lock_->lock(); + successful_lock_attempts_.insert(attempt_id); + lock_->unlock(); + } + + std::unique_ptr lock_; + scoped_refptr different_thread_task_runner_; + base::flat_set successful_lock_attempts_; + + DISALLOW_COPY_AND_ASSIGN(LockImplTest); +}; + +TEST_F(LockImplTest, LockOnce_UnlockOnce) { + lock()->lock(); + lock()->unlock(); +} + +TEST_F(LockImplTest, LockThrice_UnlockThrice) { + lock()->lock(); + lock()->lock(); + lock()->lock(); + lock()->unlock(); + lock()->unlock(); + lock()->unlock(); +} + +TEST_F(LockImplTest, + LockOnce_DisallowRelockingFromDifferentThreadUntilCurrentThreadUnlocks) { + // Lock on current thread. + lock()->lock(); + + // Try to lock again, but on different thread. + base::UnguessableToken attempt_id = base::UnguessableToken::Create(); + PostLockAndUnlockFromDifferentThread(attempt_id); + + // Wait for a little, then check to see if the lock attempt failed. + TinyTimeout(); + EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id)); + + // Outstanding lock attempt succeed after unlocking from current thread. + lock()->unlock(); + task_environment_.RunUntilIdle(); + EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id)); +} + +TEST_F( + LockImplTest, + LockThrice_DisallowRelockingFromDifferentThreadUntilCurrentThreadUnlocks) { + // Lock on current thread. + lock()->lock(); + lock()->lock(); + lock()->lock(); + + // Try to lock again, but on different thread. + base::UnguessableToken attempt_id = base::UnguessableToken::Create(); + PostLockAndUnlockFromDifferentThread(attempt_id); + + // Wait for a little, then check to see if the lock attempt failed. + TinyTimeout(); + EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id)); + + // Outstanding lock attempt succeed after unlocking from current thread. + lock()->unlock(); + lock()->unlock(); + lock()->unlock(); + task_environment_.RunUntilIdle(); + EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id)); +} + +TEST_F(LockImplTest, InterweavedLocking) { + base::UnguessableToken attempt_id1 = base::UnguessableToken::Create(); + base::UnguessableToken attempt_id2 = base::UnguessableToken::Create(); + base::UnguessableToken attempt_id3 = base::UnguessableToken::Create(); + + lock()->lock(); + PostLockAndUnlockFromDifferentThread(attempt_id1); + lock()->lock(); + PostLockAndUnlockFromDifferentThread(attempt_id2); + lock()->lock(); + PostLockAndUnlockFromDifferentThread(attempt_id3); + + TinyTimeout(); + EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id1)); + EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id2)); + EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id3)); + + lock()->unlock(); + lock()->unlock(); + lock()->unlock(); + task_environment_.RunUntilIdle(); + EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id1)); + EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id2)); + EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id3)); +} + +TEST_F(LockImplTest, CannotUnlockBeforeAnyLocks) { + EXPECT_DCHECK_DEATH(lock()->unlock()); +} + +} // namespace nearby + +} // namespace chromeos diff --git a/pool/shard006/C++/0078666_lanRouter.cc b/pool/shard006/C++/0078666_lanRouter.cc new file mode 100644 index 0000000000000000000000000000000000000000..561214dcbd6814e28fc16a2355945fe6729d9014 --- /dev/null +++ b/pool/shard006/C++/0078666_lanRouter.cc @@ -0,0 +1,129 @@ +/* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */ + +/* + * Copyright (C) 1998 by the University of Southern California + * $Id: lanRouter.cc,v 1.10 2005/08/25 18:58:07 johnh 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., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + * + * + * The copyright of this module includes the following + * linking-with-specific-other-licenses addition: + * + * In addition, as a special exception, the copyright holders of + * this module give you permission to combine (via static or + * dynamic linking) this module with free software programs or + * libraries that are released under the GNU LGPL and with code + * included in the standard release of ns-2 under the Apache 2.0 + * license or under otherwise-compatible licenses with advertising + * requirements (or modified versions of such code, with unchanged + * license). You may copy and distribute such a system following the + * terms of the GNU GPL for this module and the licenses of the + * other code concerned, provided that you include the source code of + * that other code when and as the GNU GPL requires distribution of + * source code. + * + * Note that people who make modified versions of this module + * are not obligated to grant this special exception for their + * modified versions; it is their choice whether to do so. The GNU + * General Public License gives permission to release a modified + * version without this exception; this exception also makes it + * possible to release a modified version which carries forward this + * exception. + * + */ + +#ifndef lint +static const char rcsid[] = + "@(#) $Header: /usr/src/mash/repository/vint/ns-2/lanRouter.cc"; +#endif + +#include +#include "lanRouter.h" +#include "address.h" +#include "ip.h" + +static class LanRouterClass : public TclClass { +public: + LanRouterClass() : TclClass("LanRouter") {} + TclObject* create(int, const char*const*) { + return (new LanRouter()); + } +} class_mac; + +int LanRouter::next_hop(Packet *p) { + if (switch_ && switch_->classify(p)==1) { + return -1; + } + if (!routelogic_) return -1; + + hdr_ip* iph= hdr_ip::access(p); + char* adst= Address::instance().print_nodeaddr(iph->daddr()); + int next_hopIP; + + if (enableHrouting_) { + char* bdst; + + routelogic_->lookup_hier(lanaddr_, adst, next_hopIP); + // hacking: get rid of the last "." + bdst = Address::instance().print_nodeaddr(next_hopIP); +// bdst[strlen(bdst)-1] = '\0'; + Tcl &tcl = Tcl::instance(); + tcl.evalf("[Simulator instance] get-node-id-by-addr %s", bdst); + sscanf(tcl.result(), "%d", &next_hopIP); + delete [] bdst; + } else { + routelogic_->lookup_flat(lanaddr_, adst, next_hopIP); + } + delete [] adst; + + return next_hopIP; +} +int LanRouter::command(int argc, const char*const* argv) +{ + // Tcl& tcl = Tcl::instance(); + if (argc == 3) { + // cmd lanaddr + if (strcmp(argv[1], "lanaddr") == 0) { + strcpy(lanaddr_, argv[2]); + return (TCL_OK); + } + // cmd routing hier|flat + if (strcmp(argv[1], "routing") == 0) { + if (strcmp(argv[2], "hier")==0) + enableHrouting_= true; + else if (strcmp(argv[2], "flat")==0) + enableHrouting_= false; + else return (TCL_ERROR); + return (TCL_OK); + } + // cmd switch + if (strcmp(argv[1], "switch") == 0) { + switch_ = (Classifier*) TclObject::lookup(argv[2]); + return (TCL_OK); + } + // cmd routelogic + if (strcmp(argv[1], "routelogic") == 0) { + routelogic_ = (RouteLogic*) TclObject::lookup(argv[2]); + return (TCL_OK); + } + } + return NsObject::command(argc, argv); +} + + + + + + diff --git a/pool/shard006/C++/0078667_EventFactory.cpp b/pool/shard006/C++/0078667_EventFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00a42d15bf560b6309884a2eb4b56a55ea379dee --- /dev/null +++ b/pool/shard006/C++/0078667_EventFactory.cpp @@ -0,0 +1,54 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2020 INRIA. + * + * 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 "EventFactory.hpp" +#include "SiconosException.hpp" +#include + + + +namespace EventFactory +{ + +Registry& Registry::get() +{ + static Registry instance; + return instance; +} + +void Registry::add(int type, object_creator creator) +{ + factory_map[type] = creator; +} + +SP::Event Registry::instantiate(double time, int type) +{ + MapFactoryIt it = factory_map.find(type) ; + + if(it == factory_map.end()) + THROW_EXCEPTION("Registry::instantiate (EventFactory) failed, no class with id: " + std::to_string(type)); + + return (it->second)(time, type) ; // run our factory +} + +Registration::Registration(int type, object_creator creator) +{ + Registry::get().add(type, creator) ; +} + +} diff --git a/pool/shard006/C++/0078671_testing_cgebrd.cpp b/pool/shard006/C++/0078671_testing_cgebrd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..080374c800db238ed40dd69e43d8f701d4a318c6 --- /dev/null +++ b/pool/shard006/C++/0078671_testing_cgebrd.cpp @@ -0,0 +1,202 @@ +/* + -- MAGMA (version 1.5.0-beta3) -- + Univ. of Tennessee, Knoxville + Univ. of California, Berkeley + Univ. of Colorado, Denver + @date July 2014 + + @generated from testing_zgebrd.cpp normal z -> c, Fri Jul 18 17:34:25 2014 + +*/ + +// includes, system +#include +#include +#include +#include +#include +#include + +// includes, project +#include "flops.h" +#include "magma.h" +#include "magma_lapack.h" +#include "testings.h" + +#define PRECISION_c + +/* //////////////////////////////////////////////////////////////////////////// + -- Testing cgebrd +*/ +int main( int argc, char** argv) +{ + TESTING_INIT(); + + real_Double_t gflops, gpu_perf, gpu_time, cpu_perf, cpu_time; + magmaFloatComplex *h_A, *h_Q, *h_PT, *h_work; + magmaFloatComplex *taup, *tauq; + float *diag, *offdiag; + float eps, result[3] = {0., 0., 0.}; + magma_int_t M, N, n2, lda, lhwork, info, minmn, nb; + magma_int_t ione = 1; + magma_int_t ISEED[4] = {0,0,0,1}; + + eps = lapackf77_slamch( "E" ); + magma_int_t status = 0; + + magma_opts opts; + parse_opts( argc, argv, &opts ); + + float tol = opts.tolerance * lapackf77_slamch("E"); + + printf(" M N CPU GFlop/s (sec) GPU GFlop/s (sec) |A-QBP'|/N|A| |I-QQ'|/N |I-PP'|/N\n"); + printf("=========================================================================================\n"); + for( int itest = 0; itest < opts.ntest; ++itest ) { + for( int iter = 0; iter < opts.niter; ++iter ) { + M = opts.msize[itest]; + N = opts.nsize[itest]; + minmn = min(M, N); + nb = magma_get_cgebrd_nb(N); + lda = M; + n2 = lda*N; + lhwork = (M + N)*nb; + gflops = FLOPS_CGEBRD( M, N ) / 1e9; + + TESTING_MALLOC_CPU( h_A, magmaFloatComplex, lda*N ); + TESTING_MALLOC_CPU( tauq, magmaFloatComplex, minmn ); + TESTING_MALLOC_CPU( taup, magmaFloatComplex, minmn ); + TESTING_MALLOC_CPU( diag, float, minmn ); + TESTING_MALLOC_CPU( offdiag, float, minmn-1 ); + + TESTING_MALLOC_PIN( h_Q, magmaFloatComplex, lda*N ); + TESTING_MALLOC_PIN( h_work, magmaFloatComplex, lhwork ); + + /* Initialize the matrices */ + lapackf77_clarnv( &ione, ISEED, &n2, h_A ); + lapackf77_clacpy( MagmaUpperLowerStr, &M, &N, h_A, &lda, h_Q, &lda ); + + /* ==================================================================== + Performs operation using MAGMA + =================================================================== */ + gpu_time = magma_wtime(); + magma_cgebrd( M, N, h_Q, lda, + diag, offdiag, tauq, taup, + h_work, lhwork, &info); + gpu_time = magma_wtime() - gpu_time; + gpu_perf = gflops / gpu_time; + if (info != 0) + printf("magma_cgebrd returned error %d: %s.\n", + (int) info, magma_strerror( info )); + + /* ===================================================================== + Check the factorization + =================================================================== */ + if ( opts.check ) { + // cungbr prefers minmn*NB + // cbdt01 needs M+N + // cunt01 prefers minmn*(minmn+1) to check Q and P + magma_int_t lwork_err; + magmaFloatComplex *h_work_err; + lwork_err = max( minmn * nb, M+N ); + lwork_err = max( lwork_err, minmn*(minmn+1) ); + TESTING_MALLOC_CPU( h_PT, magmaFloatComplex, lda*N ); + TESTING_MALLOC_CPU( h_work_err, magmaFloatComplex, lwork_err ); + + // cbdt01 needs M + // cunt01 needs minmn + #if defined(PRECISION_z) || defined(PRECISION_c) + float *rwork_err; + TESTING_MALLOC_CPU( rwork_err, float, M ); + #endif + + lapackf77_clacpy(MagmaUpperLowerStr, &M, &N, h_Q, &lda, h_PT, &lda); + + // generate Q & P' + lapackf77_cungbr("Q", &M, &minmn, &N, h_Q, &lda, tauq, h_work_err, &lwork_err, &info); + if (info != 0) + printf("lapackf77_cungbr #1 returned error %d: %s.\n", + (int) info, magma_strerror( info )); + lapackf77_cungbr("P", &minmn, &N, &M, h_PT, &lda, taup, h_work_err, &lwork_err, &info); + if (info != 0) + printf("lapackf77_cungbr #2 returned error %d: %s.\n", + (int) info, magma_strerror( info )); + + // Test 1: Check the decomposition A := Q * B * PT + // 2: Check the orthogonality of Q + // 3: Check the orthogonality of PT + #if defined(PRECISION_z) || defined(PRECISION_c) + lapackf77_cbdt01(&M, &N, &ione, + h_A, &lda, h_Q, &lda, + diag, offdiag, h_PT, &lda, + h_work_err, rwork_err, &result[0]); + lapackf77_cunt01("Columns", &M, &minmn, h_Q, &lda, h_work_err, &lwork_err, rwork_err, &result[1]); + lapackf77_cunt01("Rows", &minmn, &N, h_PT, &lda, h_work_err, &lwork_err, rwork_err, &result[2]); + #else + lapackf77_cbdt01(&M, &N, &ione, + h_A, &lda, h_Q, &lda, + diag, offdiag, h_PT, &lda, + h_work_err, &result[0]); + lapackf77_cunt01("Columns", &M, &minmn, h_Q, &lda, h_work_err, &lwork_err, &result[1]); + lapackf77_cunt01("Rows", &minmn, &N, h_PT, &lda, h_work_err, &lwork_err, &result[2]); + #endif + + TESTING_FREE_CPU( h_PT ); + TESTING_FREE_CPU( h_work_err ); + #if defined(PRECISION_z) || defined(PRECISION_c) + TESTING_FREE_CPU( rwork_err ); + #endif + } + + /* ===================================================================== + Performs operation using LAPACK + =================================================================== */ + if ( opts.lapack ) { + cpu_time = magma_wtime(); + lapackf77_cgebrd(&M, &N, h_A, &lda, + diag, offdiag, tauq, taup, + h_work, &lhwork, &info); + cpu_time = magma_wtime() - cpu_time; + cpu_perf = gflops / cpu_time; + if (info != 0) + printf("lapackf77_cgebrd returned error %d: %s.\n", + (int) info, magma_strerror( info )); + } + + /* ===================================================================== + Print performance and error. + =================================================================== */ + if ( opts.lapack ) { + printf("%5d %5d %7.2f (%7.2f) %7.2f (%7.2f)", + (int) M, (int) N, cpu_perf, cpu_time, gpu_perf, gpu_time ); + } + else { + printf("%5d %5d --- ( --- ) %7.2f (%7.2f)", + (int) M, (int) N, gpu_perf, gpu_time ); + } + if ( opts.check ) { + printf(" %8.2e %8.2e %8.2e %s\n", + result[0]*eps, result[1]*eps, result[2]*eps, + (result[0]*eps < tol && result[1]*eps < tol && result[2]*eps < tol ? "ok" : "failed") ); + status += ! (result[0]*eps < tol && result[1]*eps < tol && result[2]*eps < tol); + } else { + printf(" --- --- \n"); + } + + TESTING_FREE_CPU( h_A ); + TESTING_FREE_CPU( tauq ); + TESTING_FREE_CPU( taup ); + TESTING_FREE_CPU( diag ); + TESTING_FREE_CPU( offdiag ); + + TESTING_FREE_PIN( h_Q ); + TESTING_FREE_PIN( h_work ); + fflush( stdout ); + } + if ( opts.niter > 1 ) { + printf( "\n" ); + } + } + + TESTING_FINALIZE(); + return status; +} diff --git a/pool/shard006/C++/0078672_GraphNodeView.cpp b/pool/shard006/C++/0078672_GraphNodeView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..034a5864cc4bed878e78159945edc36719af9d9e --- /dev/null +++ b/pool/shard006/C++/0078672_GraphNodeView.cpp @@ -0,0 +1,228 @@ +#include "stdafx.h" + +#ifndef GRAPHNODEVIEW_H +#include "GraphNodeView.h" +#endif +#ifndef GRAPHEDGEVIEW_H +#include "stdafx.h" +#include "GraphEdgeView.h" +#endif +#ifndef PLANSTEPEX_H +#include "PlanStepEx.h" +#endif +#include "OlcbpPlanNodeData.h" + +using namespace IStrategizer; +using namespace std; + +GraphNodeView::GraphNodeView(PlanStepEx* pPlanStep, ConstOlcbpPlanNodeDataPtr pNodeData, QMenu *pContextMeun, QGraphicsItem *pParent /* = 0 */) : +QGraphicsRectItem(pParent), +m_modelId(pPlanStep->Id()), +m_isActive(false), +m_isOpen(false), +m_pNodeModel(pPlanStep), +m_pContextMenu(pContextMeun), +m_pNodeData(pNodeData), +m_SatisfyingGoalId(IOlcbpPlan::NullNodeID) +{ + _ASSERTE(m_pNodeModel); + + m_nodeTxt = QString::fromStdString(pPlanStep->ToString(true)); + m_tooltipTxt[0] = 0, + + m_style = GetStyle(); + + setBrush(m_style.BackgroundBrush); + setPen(m_style.BorderPen); + + // Measure text width and set the node width accordingly with small padding + QFontMetrics fontMetric(m_style.TxtFont); + + m_nodeHeight = fontMetric.height() + 40; + m_nodeWidth = fontMetric.width(m_nodeTxt) + 20; + + setFlag(QGraphicsItem::ItemIsSelectable); + setFlag(QGraphicsItem::ItemIsMovable); + setFlag(QGraphicsItem::ItemSendsGeometryChanges); + + m_nodeToString = m_pNodeModel->ToString().c_str(); + m_isGoal = BELONG(GoalType, m_pNodeModel->StepTypeId()); + + if (m_pNodeData != nullptr) + m_SatisfyingGoalId = m_pNodeData->SatisfyingGoal; + + if (m_pNodeData == nullptr) + setToolTip(QString::fromLocal8Bit(m_pNodeModel->ToString().c_str())); +} +//---------------------------------------------------------------------------------------------- +void GraphNodeView::AddEdge(GraphEdgeView* p_edge) +{ + m_edges.append(p_edge); +} +//---------------------------------------------------------------------------------------------- +void GraphNodeView::RemoveEdge(GraphEdgeView* p_edge) +{ + QList::iterator where = find(m_edges.begin(), m_edges.end(), p_edge); + + if (where != m_edges.end()) + m_edges.erase(where); +} +//---------------------------------------------------------------------------------------------- +QList GraphNodeView::Disconnect() +{ + GraphNodeView *other = NULL; + QList edges(m_edges); + + foreach(GraphEdgeView* edge, edges) + { + if (edge->StartNode() != this) + other = edge->StartNode(); + else + other = edge->EndNode(); + + other->RemoveEdge(edge); + this->RemoveEdge(edge); + } + + return edges; +} +//---------------------------------------------------------------------------------------------- +QVariant GraphNodeView::itemChange(GraphicsItemChange change, + const QVariant &value) +{ + if (change == QGraphicsItem::ItemPositionChange) + { + foreach(GraphEdgeView *edge, m_edges) + { + edge->UpdatePosition(); + } + } + + return value; +} +//---------------------------------------------------------------------------------------------- +void GraphNodeView::paint(QPainter *p_painter, const QStyleOptionGraphicsItem *p_option, QWidget *p_widget) +{ + QGraphicsRectItem::paint(p_painter, p_option, p_widget); + + m_style = GetStyle(); + + setBrush(m_style.BackgroundBrush); + setPen(m_style.BorderPen); + + QTextOption textOption; + textOption.setAlignment(Qt::AlignCenter); + + p_painter->setFont(m_style.TxtFont); + p_painter->setPen(m_style.TxtPen); + + // Measure text width and set the node width accordingly with small padding + QFontMetrics fontMetric(m_style.TxtFont); + + m_nodeHeight = fontMetric.height() + 20; + m_nodeWidth = fontMetric.width(m_nodeTxt) + 20; + + // Call setRect ONLY in case the node dimensions changed, if it is called each paint + // it will cause infinite loop (and lead to stack overflow) because setRect always + // case the node to repaint + if (rect().width() != m_nodeWidth || rect().height() != m_nodeHeight) + setRect(0, 0, m_nodeWidth, m_nodeHeight); + + setToolTip(QString::fromLocal8Bit(m_tooltipTxt)); + + p_painter->drawText(this->rect(), m_nodeTxt, textOption); +} +//---------------------------------------------------------------------------------------------- +void GraphNodeView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +{ + event->accept(); + scene()->clearSelection(); + setSelected(true); + if (m_pContextMenu != NULL) + m_pContextMenu->exec(event->screenPos()); +} +////////////////////////////////////////////////////////////////////////// +GraphNodeView::NodeStyle GraphNodeView::GetStyle() +{ + NodeStyle style; + + Qt::GlobalColor bgBrushColor = Qt::white; + Qt::GlobalColor txtPenColor = Qt::black; + Qt::GlobalColor borderColor = Qt::black; + auto fillPattern = Qt::SolidPattern; + + switch (m_state) + { + case ESTATE_Failed: + bgBrushColor = Qt::red; + break; + case ESTATE_Succeeded: + bgBrushColor = Qt::green; + break; + case ESTATE_NotPrepared: + if (m_isGoal) + { + if (!m_isOpen) + { + bgBrushColor = Qt::blue; + txtPenColor = Qt::white; + } + else + bgBrushColor = Qt::lightGray; + } + else + bgBrushColor = Qt::lightGray; + break; + case ESTATE_Pending: + bgBrushColor = Qt::yellow; + break; + case ESTATE_Executing: + bgBrushColor = Qt::blue; + txtPenColor = Qt::white; + break; + default: + bgBrushColor = Qt::white; + break; + } + + style.BackgroundBrush = QBrush(bgBrushColor, fillPattern); + style.BorderPen = QPen(QColor(borderColor)); + style.TxtPen = QPen(QColor(txtPenColor)); + + if (m_isGoal) + { + style.TxtFont.setBold(true); + style.TxtFont.setPixelSize(26); + style.BorderPen.setWidth(2); + + if (m_isActive) + { + style.TxtFont.setItalic(true); + style.TxtFont.setUnderline(true); + } + } + else + { + style.TxtFont.setPixelSize(22); + style.BorderPen.setWidth(1); + } + + return style; +} +////////////////////////////////////////////////////////////////////////// +void GraphNodeView::OnUpdate() +{ + m_state = m_pNodeModel->GetState(); + + if (m_pNodeData != nullptr) + { + m_isOpen = m_pNodeData->IsOpen; + + sprintf_s(m_tooltipTxt, "%s: O?%d, SG:%d, PC:%d, CC:%d", + m_nodeToString.c_str(), + m_pNodeData->IsOpen, + m_pNodeData->SatisfyingGoal, + m_pNodeData->WaitOnParentsCount, + m_pNodeData->WaitOnChildrenCount); + } +} \ No newline at end of file diff --git a/pool/shard006/C++/0078678_benchmarkudf.cc b/pool/shard006/C++/0078678_benchmarkudf.cc new file mode 100644 index 0000000000000000000000000000000000000000..25508fd8e1cb15feaf092e0143de08b8eac4d95f --- /dev/null +++ b/pool/shard006/C++/0078678_benchmarkudf.cc @@ -0,0 +1,140 @@ +/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- + * vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * Copyright (C) 2008 MySQL AB + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include + +using namespace std; +using namespace drizzled; + +class BenchmarkFunction :public Item_int_func +{ +public: + BenchmarkFunction() :Item_int_func() {} + int64_t val_int(); + virtual void print(String *str); + + const char *func_name() const + { + return "benchmark"; + } + + void fix_length_and_dec() + { + max_length= 1; + maybe_null= false; + } + + bool check_argument_count(int n) + { + return (n == 2); + } +}; + + +/* This function is just used to test speed of different functions */ +int64_t BenchmarkFunction::val_int() +{ + assert(fixed == true); + + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff), &my_charset_bin); + type::Decimal tmp_decimal; + uint64_t loop_count; + + loop_count= (uint64_t) args[0]->val_int(); + + if (args[0]->null_value || + (args[0]->unsigned_flag == false && (((int64_t) loop_count) < 0))) + { + if (args[0]->null_value == false) + { + internal::int64_t10_to_str((int64_t)loop_count, buff, -10); + push_warning_printf(&getSession(), DRIZZLE_ERROR::WARN_LEVEL_ERROR, + ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE), + "count", buff, "benchmark"); + } + + null_value= true; + return 0; + } + + null_value= false; + + uint64_t loop; + for (loop= 0 ; loop < loop_count && not getSession().getKilled(); loop++) + { + switch (args[1]->result_type()) + { + case REAL_RESULT: + (void) args[1]->val_real(); + break; + case INT_RESULT: + (void) args[1]->val_int(); + break; + case STRING_RESULT: + (void) args[1]->val_str(&tmp); + break; + case DECIMAL_RESULT: + (void) args[1]->val_decimal(&tmp_decimal); + break; + case ROW_RESULT: + default: + // This case should never be chosen + assert(0); + return 0; + } + } + return 0; +} + +void BenchmarkFunction::print(String *str) +{ + str->append(STRING_WITH_LEN("benchmark(")); + args[0]->print(str); + str->append(','); + args[1]->print(str); + str->append(')'); +} + +plugin::Create_function *benchmarkudf= NULL; + +static int initialize(module::Context &context) +{ + benchmarkudf= new plugin::Create_function("benchmark"); + context.add(benchmarkudf); + return 0; +} + +DRIZZLE_DECLARE_PLUGIN +{ + DRIZZLE_VERSION_ID, + "benchmark", + "1.0", + "Devananda van der Veen", + "Measure time for repeated calls to a function.", + PLUGIN_LICENSE_GPL, + initialize, /* Plugin Init */ + NULL, /* depends */ + NULL /* config options */ +} +DRIZZLE_DECLARE_PLUGIN_END; diff --git a/pool/shard006/C++/0078679_skinned_mesh.cpp b/pool/shard006/C++/0078679_skinned_mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ac9d8ef7a64a4d6e8aa6b776db26d90cd08039d --- /dev/null +++ b/pool/shard006/C++/0078679_skinned_mesh.cpp @@ -0,0 +1,89 @@ +#include + +#include +#include +#include + +#include + +namespace zombye { + skinned_mesh::skinned_mesh(rendering_system& rendering_system, const std::vector& source, const std::string& file_name) noexcept + : vbo_{0, GL_STATIC_DRAW}, ibo_{0, GL_STATIC_DRAW}, parallax_mapping_{false} { + auto data_ptr = source.data(); + + auto head = *reinterpret_cast(data_ptr); + if (head.magic != 0x31424D5A) { + throw std::runtime_error(file_name + " is not an zombye mesh file"); + } + + parallax_mapping_ = head.parallax_mapping; + + auto vertex_size = head.vertex_count * sizeof(skinned_vertex); + auto index_size = head.index_count * sizeof(uint32_t); + auto size = sizeof(header) + + vertex_size + + index_size + + head.submesh_count * sizeof(devtools::submesh); + + if (size != source.size()) { + throw std::runtime_error(file_name + " has not the apropriate size. expected size: " + + std::to_string(source.size()) + " calculated size: " + std::to_string(size)); + } + data_ptr += sizeof(header); + + vbo_.data(vertex_size, data_ptr); + data_ptr += vertex_size; + + ibo_.data(index_size, data_ptr); + data_ptr += index_size; + + for (auto i = 0; i < head.submesh_count; ++i) { + submesh s; + + s.index_count = *reinterpret_cast(data_ptr); + data_ptr += sizeof(uint64_t); + s.offset = *reinterpret_cast(data_ptr); + data_ptr += sizeof(uint64_t); + + auto texture_id = *reinterpret_cast(data_ptr); + auto texture_name = std::to_string(texture_id) + ".dds"; + s.diffuse = rendering_system.texture_manager().load("texture/" + texture_name); + if (!s.diffuse) { + throw std::runtime_error("could not load texure " + texture_name); + } + data_ptr += sizeof(uint64_t); + + texture_id = *reinterpret_cast(data_ptr); + texture_name = std::to_string(texture_id) + ".dds"; + s.normal = rendering_system.texture_manager().load("texture/" + texture_name); + if (!s.normal) { + throw std::runtime_error("could not load texure " + texture_name); + } + data_ptr += sizeof(uint64_t); + + texture_id = *reinterpret_cast(data_ptr); + texture_name = std::to_string(texture_id) + ".dds"; + s.material = rendering_system.texture_manager().load("texture/" + texture_name); + if (!s.material) { + throw std::runtime_error("could not load texure " + texture_name); + } + data_ptr += sizeof(uint64_t); + + submeshes_.emplace_back(s); + } + + vao_.bind_index_buffer(ibo_); + rendering_system.skinnedmesh_layout().setup_layout(vao_, &vbo_); + } + + void skinned_mesh::draw() const noexcept { + vao_.bind(); + for (auto& sub : submeshes_) { + sub.diffuse->bind(0); + sub.material->bind(1); + sub.normal->bind(2); + glDrawElements(GL_TRIANGLES, sub.index_count, GL_UNSIGNED_INT, + reinterpret_cast(sub.offset * sizeof(unsigned int))); + } + } +} diff --git a/pool/shard006/C++/0078685_2.cc b/pool/shard006/C++/0078685_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca42d2e4e18aa002f4f1adda428f55b437c893ac --- /dev/null +++ b/pool/shard006/C++/0078685_2.cc @@ -0,0 +1,43 @@ +// 1999-05-11 bkoz + +// Copyright (C) 1999, 2002, 2003 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 2, 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 COPYING. If not, write to the Free +// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, +// USA. + +// 21.3.3 string capacity + +#include +#include + +// libstdc++/4548 +// http://gcc.gnu.org/ml/libstdc++/2001-11/msg00150.html +void test02() +{ + bool test __attribute__((unused)) = true; + + std::string str01 = "twelve chars"; + // str01 becomes shared + std::string str02 = str01; + str01.reserve(1); + VERIFY( str01.capacity() == 12 ); +} + +int main() +{ + test02(); + return 0; +} diff --git a/pool/shard006/C++/0078686_EvaluationMetrics.cpp b/pool/shard006/C++/0078686_EvaluationMetrics.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ff374e3524e97c6ca111f21a2d7cd981ce2b8f39 --- /dev/null +++ b/pool/shard006/C++/0078686_EvaluationMetrics.cpp @@ -0,0 +1,75 @@ +/** + * 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 Glue +{ +namespace Model +{ + +EvaluationMetrics::EvaluationMetrics() : + m_transformType(TransformType::NOT_SET), + m_transformTypeHasBeenSet(false), + m_findMatchesMetricsHasBeenSet(false) +{ +} + +EvaluationMetrics::EvaluationMetrics(JsonView jsonValue) : + m_transformType(TransformType::NOT_SET), + m_transformTypeHasBeenSet(false), + m_findMatchesMetricsHasBeenSet(false) +{ + *this = jsonValue; +} + +EvaluationMetrics& EvaluationMetrics::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("TransformType")) + { + m_transformType = TransformTypeMapper::GetTransformTypeForName(jsonValue.GetString("TransformType")); + + m_transformTypeHasBeenSet = true; + } + + if(jsonValue.ValueExists("FindMatchesMetrics")) + { + m_findMatchesMetrics = jsonValue.GetObject("FindMatchesMetrics"); + + m_findMatchesMetricsHasBeenSet = true; + } + + return *this; +} + +JsonValue EvaluationMetrics::Jsonize() const +{ + JsonValue payload; + + if(m_transformTypeHasBeenSet) + { + payload.WithString("TransformType", TransformTypeMapper::GetNameForTransformType(m_transformType)); + } + + if(m_findMatchesMetricsHasBeenSet) + { + payload.WithObject("FindMatchesMetrics", m_findMatchesMetrics.Jsonize()); + + } + + return payload; +} + +} // namespace Model +} // namespace Glue +} // namespace Aws diff --git a/pool/shard006/C++/0078692_DateTimeFormatterTest.cpp b/pool/shard006/C++/0078692_DateTimeFormatterTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5df07b3d9067b11a6036bf20106c0bf358a5bcc --- /dev/null +++ b/pool/shard006/C++/0078692_DateTimeFormatterTest.cpp @@ -0,0 +1,229 @@ +// +// DateTimeFormatterTest.cpp +// +// $Id: //poco/svn/Foundation/testsuite/src/DateTimeFormatterTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// Permission is hereby granted, free of charge, to any person or organization +// obtaining a copy of the software and accompanying documentation covered by +// this license (the "Software") to use, reproduce, display, distribute, +// execute, and transmit the Software, and to prepare derivative works of the +// Software, and to permit third-parties to whom the Software is furnished to +// do so, all subject to the following: +// +// The copyright notices in the Software and this entire statement, including +// the above license grant, this restriction and the following disclaimer, +// must be included in all copies of the Software, in whole or in part, and +// all derivative works of the Software, unless such copies or derivative +// works are solely in the form of machine-executable object code generated by +// a source language processor. +// +// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. +// + + +#include "DateTimeFormatterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTime.h" +#include "Poco/Timespan.h" + + +using Poco::DateTime; +using Poco::Timespan; +using Poco::DateTimeFormat; +using Poco::DateTimeFormatter; + + +DateTimeFormatterTest::DateTimeFormatterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DateTimeFormatterTest::~DateTimeFormatterTest() +{ +} + + +void DateTimeFormatterTest::testISO8601() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT); + assert (str == "2005-01-08T12:30:00Z"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, 3600); + assert (str == "2005-01-08T12:30:00+01:00"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, -3600); + assert (str == "2005-01-08T12:30:00-01:00"); +} + + +void DateTimeFormatterTest::testRFC822() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT); + assert (str == "Sat, 8 Jan 05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, 3600); + assert (str == "Sat, 8 Jan 05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, -3600); + assert (str == "Sat, 8 Jan 05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC1123() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT); + assert (str == "Sat, 8 Jan 2005 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, 3600); + assert (str == "Sat, 8 Jan 2005 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, -3600); + assert (str == "Sat, 8 Jan 2005 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testHTTP() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT); + assert (str == "Sat, 08 Jan 2005 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, 3600); + assert (str == "Sat, 08 Jan 2005 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, -3600); + assert (str == "Sat, 08 Jan 2005 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC850() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT); + assert (str == "Saturday, 8-Jan-05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, 3600); + assert (str == "Saturday, 8-Jan-05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, -3600); + assert (str == "Saturday, 8-Jan-05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC1036() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT); + assert (str == "Saturday, 8 Jan 05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, 3600); + assert (str == "Saturday, 8 Jan 05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, -3600); + assert (str == "Saturday, 8 Jan 05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testASCTIME() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ASCTIME_FORMAT); + assert (str == "Sat Jan 8 12:30:00 2005"); +} + + +void DateTimeFormatterTest::testSORTABLE() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT); + assert (str == "2005-01-08 12:30:00"); +} + + +void DateTimeFormatterTest::testCustom() +{ + DateTime dt(2005, 1, 8, 12, 30, 00, 250); + + std::string str = DateTimeFormatter::format(dt, "%w/%W/%b/%B/%d/%e/%f/%m/%n/%o/%y/%Y/%H/%h/%a/%A/%M/%S/%i/%c/%z/%Z/%%"); + assert (str == "Sat/Saturday/Jan/January/08/8/ 8/01/1/ 1/05/2005/12/12/pm/PM/30/00/250/2/Z/GMT/%"); +} + + +void DateTimeFormatterTest::testTimespan() +{ + Timespan ts(1, 1, 1, 1, 1000); + std::string str = DateTimeFormatter::format(ts); + assert (str == "1d 01:01:01.001"); + + Timespan ts1(1, 24, 1, 1, 1000); + str = DateTimeFormatter::format(ts1); + assert (str == "2d 00:01:01.001"); + + Timespan ts2(1, 25, 1, 1, 1000); + str = DateTimeFormatter::format(ts2); + assert (str == "2d 01:01:01.001"); + + Timespan ts3(5, 4, 3, 2, 1000); + str = DateTimeFormatter::format(ts3, "%i.%S:%M:%H d%d %%"); + assert (str == "001.02:03:04 d5 %"); + + Timespan ts4(0, 24, 60, 60, 1001000); + str = DateTimeFormatter::format(ts4); + assert (str == "1d 01:01:01.001"); + + Timespan ts5(2, 11, 30, 20, 0); + str = DateTimeFormatter::format(ts5, "%h %m %s"); + assert (str == "59 3570 214220"); +} + + +void DateTimeFormatterTest::setUp() +{ +} + + +void DateTimeFormatterTest::tearDown() +{ +} + + +CppUnit::Test* DateTimeFormatterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeFormatterTest"); + + CppUnit_addTest(pSuite, DateTimeFormatterTest, testISO8601); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC822); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1123); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testHTTP); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC850); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1036); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testASCTIME); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testSORTABLE); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testCustom); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testTimespan); + + return pSuite; +} diff --git a/pool/shard006/C++/0078693_rotation.cc b/pool/shard006/C++/0078693_rotation.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d23a2835b889d361952fb33fec687124f409d6f --- /dev/null +++ b/pool/shard006/C++/0078693_rotation.cc @@ -0,0 +1,153 @@ +/* + * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. 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 "third_party/blink/renderer/platform/transforms/rotation.h" + +#include "third_party/blink/renderer/platform/geometry/blend.h" +#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h" +#include "ui/gfx/geometry/quaternion.h" + +namespace blink { + +using gfx::Quaternion; + +namespace { + +const double kEpsilon = 1e-5; +const double kAngleEpsilon = 1e-4; + +Quaternion ComputeQuaternion(const Rotation& rotation) { + return Quaternion::FromAxisAngle(rotation.axis.x(), rotation.axis.y(), + rotation.axis.z(), Deg2rad(rotation.angle)); +} + +FloatPoint3D NormalizeAxis(FloatPoint3D axis) { + FloatPoint3D normalized(axis); + double length = normalized.length(); + if (length > kEpsilon) { + normalized.Normalize(); + } else { + // Rotation angle is zero so the axis is arbitrary. + normalized.SetPoint(0, 0, 1); + } + return normalized; +} + +Rotation ComputeRotation(Quaternion q) { + double cos_half_angle = q.w(); + double interpolated_angle = Rad2deg(2 * std::acos(cos_half_angle)); + FloatPoint3D interpolated_axis = + NormalizeAxis(FloatPoint3D(q.x(), q.y(), q.z())); + return Rotation(interpolated_axis, interpolated_angle); +} + +} // namespace + +bool Rotation::GetCommonAxis(const Rotation& a, + const Rotation& b, + FloatPoint3D& result_axis, + double& result_angle_a, + double& result_angle_b) { + result_axis = FloatPoint3D(0, 0, 1); + result_angle_a = 0; + result_angle_b = 0; + + // We have to consider two definitions of "is zero" here, because we + // sometimes need to preserve (as an interpolation result) and expose + // to web content an axis that is associated with a zero angle. Thus + // we consider having a zero axis stronger than having a zero angle. + bool a_has_zero_axis = a.axis.IsZero(); + bool b_has_zero_axis = b.axis.IsZero(); + bool is_zero_a, is_zero_b; + if (a_has_zero_axis || b_has_zero_axis) { + is_zero_a = a_has_zero_axis; + is_zero_b = b_has_zero_axis; + } else { + is_zero_a = fabs(a.angle) < kAngleEpsilon; + is_zero_b = fabs(b.angle) < kAngleEpsilon; + } + + if (is_zero_a && is_zero_b) + return true; + + if (is_zero_a) { + result_axis = NormalizeAxis(b.axis); + result_angle_b = b.angle; + return true; + } + + if (is_zero_b) { + result_axis = NormalizeAxis(a.axis); + result_angle_a = a.angle; + return true; + } + + double dot = a.axis.Dot(b.axis); + if (dot < 0) + return false; + + double a_squared = a.axis.LengthSquared(); + double b_squared = b.axis.LengthSquared(); + double error = std::abs(1 - (dot * dot) / (a_squared * b_squared)); + if (error > kAngleEpsilon) + return false; + + result_axis = NormalizeAxis(a.axis); + result_angle_a = a.angle; + result_angle_b = b.angle; + return true; +} + +Rotation Rotation::Slerp(const Rotation& from, + const Rotation& to, + double progress) { + double from_angle; + double to_angle; + FloatPoint3D axis; + if (GetCommonAxis(from, to, axis, from_angle, to_angle)) + return Rotation(axis, blink::Blend(from_angle, to_angle, progress)); + + Quaternion qa = ComputeQuaternion(from); + Quaternion qb = ComputeQuaternion(to); + Quaternion qc = qa.Slerp(qb, progress); + + return ComputeRotation(qc); +} + +Rotation Rotation::Add(const Rotation& a, const Rotation& b) { + double angle_a; + double angle_b; + FloatPoint3D axis; + if (GetCommonAxis(a, b, axis, angle_a, angle_b)) + return Rotation(axis, angle_a + angle_b); + + Quaternion qa = ComputeQuaternion(a); + Quaternion qb = ComputeQuaternion(b); + Quaternion qc = qa * qb; + if (qc.w() < 0) { + // Choose the equivalent rotation with the smaller angle. + qc = qc.flip(); + } + + return ComputeRotation(qc); +} + +} // namespace blink diff --git a/pool/shard006/C++/0078711_get_bucket_lifecycle_result_unittest.cc b/pool/shard006/C++/0078711_get_bucket_lifecycle_result_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..8116d8ac114bdea9459fc8388c0165005a1917f9 --- /dev/null +++ b/pool/shard006/C++/0078711_get_bucket_lifecycle_result_unittest.cc @@ -0,0 +1,88 @@ +/* + * 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 "gtest/gtest.h" + +#include "oss_sdk_cpp/base/base.h" +#include "oss_sdk_cpp/message/get_bucket_lifecycle_result.h" + +namespace oss { + +static const char* kXmlContent = + "\n" + "\n" + " \n" + " test1\n" + " filter1\n" + " Enabled\n" + " \n" + " 25\n" + " \n" + " \n" + " \n" + " test2\n" + " filter2\n" + " Disabled\n" + " \n" + " 2015-12-03T00:00:00.000Z\n" + " \n" + " \n" + "\n" + ""; + +TEST(GetBucketLifecycleResult, Normal) { + GetBucketLifecycleResult result; + bool parse_ok = result.DeserializeFromXml(kXmlContent); + EXPECT_TRUE(parse_ok); + EXPECT_EQ(result.GetBucketLifecycle().size(), 2u); + + auto lifecycles = result.GetBucketLifecycle(); + { + auto& lifecycle = lifecycles.front(); + EXPECT_EQ(lifecycle.GetEnabled(), true); + EXPECT_EQ(lifecycle.GetExpirationDays(), 25); + EXPECT_EQ(lifecycle.GetId(), "test1"); + EXPECT_EQ(lifecycle.GetPrefix(), "filter1"); + } + + { + auto& lifecycle = lifecycles.back(); + EXPECT_EQ(lifecycle.GetEnabled(), false); + EXPECT_EQ(lifecycle.GetExpirationDate(), "2015-12-03T00:00:00.000Z"); + EXPECT_EQ(lifecycle.GetId(), "test2"); + EXPECT_EQ(lifecycle.GetPrefix(), "filter2"); + } +} + +TEST(GetBucketLifecycleResult, ParseFailed) { + GetBucketLifecycleResult result; + bool parse_ok = result.DeserializeFromXml("I am invalid xml text"); + EXPECT_FALSE(parse_ok); +} + +TEST(GetBucketLifecycleResult, XmlNoRoot) { + const char* kNoRootXml = + "\n" + "abc\n"; + GetBucketLifecycleResult result; + bool parse_ok = result.DeserializeFromXml(kNoRootXml); + EXPECT_FALSE(parse_ok); +} + +} // namespace oss diff --git a/pool/shard006/C++/0078713_moc_qnetworkaccessbackend_p.cpp b/pool/shard006/C++/0078713_moc_qnetworkaccessbackend_p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7451dc822499279d5e24f28227f733d7f804c3de --- /dev/null +++ b/pool/shard006/C++/0078713_moc_qnetworkaccessbackend_p.cpp @@ -0,0 +1,119 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'qnetworkaccessbackend_p.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../../../access/qnetworkaccessbackend_p.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'qnetworkaccessbackend_p.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.5. 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_QNetworkAccessBackend[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 9, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + // slots: signature, parameters, type, tag, flags + 28, 23, 22, 22, 0x0a, + 60, 22, 22, 22, 0x09, + 88, 71, 22, 22, 0x09, + 142, 131, 22, 22, 0x09, + 206, 201, 22, 22, 0x09, + 246, 22, 22, 22, 0x09, + 276, 264, 22, 22, 0x09, + 310, 303, 22, 22, 0x09, + 359, 338, 22, 22, 0x09, + + 0 // eod +}; + +static const char qt_meta_stringdata_QNetworkAccessBackend[] = { + "QNetworkAccessBackend\0\0data\0" + "writeDownstreamData(QIODevice*)\0" + "finished()\0code,errorString\0" + "error(QNetworkReply::NetworkError,QString)\0" + "proxy,auth\0" + "proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)\0" + "auth\0authenticationRequired(QAuthenticator*)\0" + "metaDataChanged()\0destination\0" + "redirectionRequested(QUrl)\0errors\0" + "sslErrors(QList)\0" + "bytesSent,bytesTotal\0" + "emitReplyUploadProgress(qint64,qint64)\0" +}; + +void QNetworkAccessBackend::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + QNetworkAccessBackend *_t = static_cast(_o); + switch (_id) { + case 0: _t->writeDownstreamData((*reinterpret_cast< QIODevice*(*)>(_a[1]))); break; + case 1: _t->finished(); break; + case 2: _t->error((*reinterpret_cast< QNetworkReply::NetworkError(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; + case 3: _t->proxyAuthenticationRequired((*reinterpret_cast< const QNetworkProxy(*)>(_a[1])),(*reinterpret_cast< QAuthenticator*(*)>(_a[2]))); break; + case 4: _t->authenticationRequired((*reinterpret_cast< QAuthenticator*(*)>(_a[1]))); break; + case 5: _t->metaDataChanged(); break; + case 6: _t->redirectionRequested((*reinterpret_cast< const QUrl(*)>(_a[1]))); break; + case 7: _t->sslErrors((*reinterpret_cast< const QList(*)>(_a[1]))); break; + case 8: _t->emitReplyUploadProgress((*reinterpret_cast< qint64(*)>(_a[1])),(*reinterpret_cast< qint64(*)>(_a[2]))); break; + default: ; + } + } +} + +const QMetaObjectExtraData QNetworkAccessBackend::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject QNetworkAccessBackend::staticMetaObject = { + { &QObject::staticMetaObject, qt_meta_stringdata_QNetworkAccessBackend, + qt_meta_data_QNetworkAccessBackend, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &QNetworkAccessBackend::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *QNetworkAccessBackend::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *QNetworkAccessBackend::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_QNetworkAccessBackend)) + return static_cast(const_cast< QNetworkAccessBackend*>(this)); + return QObject::qt_metacast(_clname); +} + +int QNetworkAccessBackend::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QObject::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 9) + qt_static_metacall(this, _c, _id, _a); + _id -= 9; + } + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard006/C++/0078719_FalSpinner.cpp b/pool/shard006/C++/0078719_FalSpinner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3c13a1ccb4c8319d3f1a1113049c504b19ed91f --- /dev/null +++ b/pool/shard006/C++/0078719_FalSpinner.cpp @@ -0,0 +1,91 @@ +/************************************************************************ + filename: FalSpinner.cpp + created: Tue Jul 5 2005 + author: Paul D Turner +*************************************************************************/ +/************************************************************************* + Crazy Eddie's GUI System (http://www.cegui.org.uk) + Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) + + 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 +*************************************************************************/ +#include "StdInc.h" +#include "FalSpinner.h" +#include "falagard/CEGUIFalWidgetLookManager.h" +#include "falagard/CEGUIFalWidgetLookFeel.h" +#include "CEGUIWindowManager.h" +#include "elements/CEGUIPushButton.h" +#include "elements/CEGUIEditbox.h" + +// Start of CEGUI namespace section +namespace CEGUI +{ + const utf8 FalagardSpinner::WidgetTypeName[] = "Falagard/Spinner"; + + FalagardSpinner::FalagardSpinner(const String& type, const String& name) : + Spinner(type, name) + { + } + + FalagardSpinner::~FalagardSpinner() + { + } + + void FalagardSpinner::populateRenderCache() + { + // get WidgetLookFeel for the assigned look. + const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); + // try and get imagery for the approprite state. + const StateImagery* imagery = &wlf.getStateImagery(isDisabled() ? "Disabled" : "Enabled"); + // peform the rendering operation + imagery->render(*this); + } + + PushButton* FalagardSpinner::createIncreaseButton(const String& name) const + { + // return component created by look'n'feel assignment. + return static_cast(WindowManager::getSingleton().getWindow(name)); + } + + PushButton* FalagardSpinner::createDecreaseButton(const String& name) const + { + // return component created by look'n'feel assignment. + return static_cast(WindowManager::getSingleton().getWindow(name)); + } + + Editbox* FalagardSpinner::createEditbox(const String& name) const + { + // return component created by look'n'feel assignment. + return static_cast(WindowManager::getSingleton().getWindow(name)); + } + + ////////////////////////////////////////////////////////////////////////// + /************************************************************************* + + Factory Methods + + *************************************************************************/ + ////////////////////////////////////////////////////////////////////////// + Window* FalagardSpinnerFactory::createWindow(const String& name) + { + return new FalagardSpinner(d_type, name); + } + + void FalagardSpinnerFactory::destroyWindow(Window* window) + { + delete window; + } + +} // End of CEGUI namespace section diff --git a/pool/shard006/C++/0078720_validation_block_tests.cpp b/pool/shard006/C++/0078720_validation_block_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44432cd0a1c9471a7641088c3909a213b1504bb7 --- /dev/null +++ b/pool/shard006/C++/0078720_validation_block_tests.cpp @@ -0,0 +1,187 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct RegtestingSetup : public TestingSetup { + RegtestingSetup() : TestingSetup(CBaseChainParams::REGTEST) {} +}; + +BOOST_FIXTURE_TEST_SUITE(validation_block_tests, RegtestingSetup) + +struct TestSubscriber : public CValidationInterface { + uint256 m_expected_tip; + + explicit TestSubscriber(uint256 tip) : m_expected_tip(tip) {} + + void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override + { + BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash()); + } + + void BlockConnected(const std::shared_ptr& block, const CBlockIndex* pindex, const std::vector& txnConflicted) override + { + BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock); + BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash()); + + m_expected_tip = block->GetHash(); + } + + void BlockDisconnected(const std::shared_ptr& block) override + { + BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash()); + + m_expected_tip = block->hashPrevBlock; + } +}; + +std::shared_ptr Block(const uint256& prev_hash) +{ + static int i = 0; + static uint64_t time = Params().GenesisBlock().nTime; + + CScript pubKey; + pubKey << i++ << OP_TRUE; + + auto ptemplate = BlockAssembler(Params()).CreateNewBlock(pubKey); + auto pblock = std::make_shared(ptemplate->block); + pblock->hashPrevBlock = prev_hash; + pblock->nTime = ++time; + + CMutableTransaction txCoinbase(*pblock->vtx[0]); + txCoinbase.vout.resize(1); + txCoinbase.vin[0].scriptWitness.SetNull(); + pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); + + return pblock; +} + +std::shared_ptr FinalizeBlock(std::shared_ptr pblock) +{ + pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); + + while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) { + ++(pblock->nNonce); + } + + return pblock; +} + +// construct a valid block +const std::shared_ptr GoodBlock(const uint256& prev_hash) +{ + return FinalizeBlock(Block(prev_hash)); +} + +// construct an invalid block (but with a valid header) +const std::shared_ptr BadBlock(const uint256& prev_hash) +{ + auto pblock = Block(prev_hash); + + CMutableTransaction coinbase_spend; + coinbase_spend.vin.push_back(CTxIn(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0)); + coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]); + + CTransactionRef tx = MakeTransactionRef(coinbase_spend); + pblock->vtx.push_back(tx); + + auto ret = FinalizeBlock(pblock); + return ret; +} + +void BuildChain(const uint256& root, int height, const unsigned int invalid_rate, const unsigned int branch_rate, const unsigned int max_size, std::vector>& blocks) +{ + if (height <= 0 || blocks.size() >= max_size) return; + + bool gen_invalid = InsecureRandRange(100) < invalid_rate; + bool gen_fork = InsecureRandRange(100) < branch_rate; + + const std::shared_ptr pblock = gen_invalid ? BadBlock(root) : GoodBlock(root); + blocks.push_back(pblock); + if (!gen_invalid) { + BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks); + } + + if (gen_fork) { + blocks.push_back(GoodBlock(root)); + BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks); + } +} + +BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering) +{ + // build a large-ish chain that's likely to have some forks + std::vector> blocks; + while (blocks.size() < 50) { + blocks.clear(); + BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks); + } + + bool ignored; + CValidationState state; + std::vector headers; + std::transform(blocks.begin(), blocks.end(), std::back_inserter(headers), [](std::shared_ptr b) { return b->GetBlockHeader(); }); + + // Process all the headers so we understand the toplogy of the chain + BOOST_CHECK(ProcessNewBlockHeaders(headers, state, Params())); + + // Connect the genesis block and drain any outstanding events + BOOST_CHECK(ProcessNewBlock(Params(), std::make_shared(Params().GenesisBlock()), true, &ignored)); + SyncWithValidationInterfaceQueue(); + + // subscribe to events (this subscriber will validate event ordering) + const CBlockIndex* initial_tip = nullptr; + { + LOCK(cs_main); + initial_tip = chainActive.Tip(); + } + TestSubscriber sub(initial_tip->GetBlockHash()); + RegisterValidationInterface(&sub); + + // create a bunch of threads that repeatedly process a block generated above at random + // this will create parallelism and randomness inside validation - the ValidationInterface + // will subscribe to events generated during block validation and assert on ordering invariance + std::vector threads; + for (int i = 0; i < 10; i++) { + threads.emplace_back([&blocks]() { + bool ignored; + FastRandomContext insecure; + for (int i = 0; i < 1000; i++) { + auto block = blocks[insecure.randrange(blocks.size() - 1)]; + ProcessNewBlock(Params(), block, true, &ignored); + } + + // to make sure that eventually we process the full chain - do it here + for (auto block : blocks) { + if (block->vtx.size() == 1) { + bool processed = ProcessNewBlock(Params(), block, true, &ignored); + assert(processed); + } + } + }); + } + + for (auto& t : threads) { + t.join(); + } + while (GetMainSignals().CallbacksPending() > 0) { + MilliSleep(100); + } + + UnregisterValidationInterface(&sub); + + BOOST_CHECK_EQUAL(sub.m_expected_tip, chainActive.Tip()->GetBlockHash()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard006/C++/0078722_CompositionEvent.cpp b/pool/shard006/C++/0078722_CompositionEvent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e8a0dd291eb41ea3f6b6c8cf2e329e2f0f1f505 --- /dev/null +++ b/pool/shard006/C++/0078722_CompositionEvent.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2009 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. ``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 "config.h" +#include "CompositionEvent.h" + +#include "EventNames.h" + +namespace WebCore { + +CompositionEvent::CompositionEvent() +{ +} + +CompositionEvent::CompositionEvent(const AtomicString& type, AbstractView* view, const String& data) + : UIEvent(type, true, true, view, 0) + , m_data(data) +{ +} + +CompositionEvent::CompositionEvent(const AtomicString& type, const CompositionEventInit& initializer) + : UIEvent(type, initializer) + , m_data(initializer.data) +{ +} + +CompositionEvent::~CompositionEvent() +{ +} + +void CompositionEvent::initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view, const String& data) +{ + if (dispatched()) + return; + + initUIEvent(type, canBubble, cancelable, view, 0); + + m_data = data; +} + +EventInterface CompositionEvent::eventInterface() const +{ + return CompositionEventInterfaceType; +} + +} // namespace WebCore diff --git a/pool/shard006/C++/0078723_qgs3dmapcanvas.cpp b/pool/shard006/C++/0078723_qgs3dmapcanvas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f6615b5a05a2545eb25b0c2fc23f7b0c716b165 --- /dev/null +++ b/pool/shard006/C++/0078723_qgs3dmapcanvas.cpp @@ -0,0 +1,216 @@ +/*************************************************************************** + qgs3dmapcanvas.cpp + -------------------------------------- + Date : July 2017 + Copyright : (C) 2017 by Martin Dobias + Email : wonder dot sk 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 "qgs3dmapcanvas.h" + +#include +#include +#include +#include + + +#include "qgscameracontroller.h" +#include "qgs3dmapsettings.h" +#include "qgs3dmapscene.h" +#include "qgs3dmaptool.h" +#include "qgswindow3dengine.h" +#include "qgs3dnavigationwidget.h" +#include "qgssettings.h" +#include "qgstemporalcontroller.h" + +Qgs3DMapCanvas::Qgs3DMapCanvas( QWidget *parent ) + : QWidget( parent ) +{ + QgsSettings setting; + mEngine = new QgsWindow3DEngine( this ); + + connect( mEngine, &QgsAbstract3DEngine::imageCaptured, this, [ = ]( const QImage & image ) + { + image.save( mCaptureFileName, mCaptureFileFormat.toLocal8Bit().data() ); + emit savedAsImage( mCaptureFileName ); + } ); + + mContainer = QWidget::createWindowContainer( mEngine->window() ); + mNavigationWidget = new Qgs3DNavigationWidget( this ); + + QHBoxLayout *hLayout = new QHBoxLayout( this ); + hLayout->setContentsMargins( 0, 0, 0, 0 ); + hLayout->addWidget( mContainer, 1 ); + hLayout->addWidget( mNavigationWidget ); + this->setOnScreenNavigationVisibility( + setting.value( QStringLiteral( "/3D/navigationWidget/visibility" ), true, QgsSettings::Gui ).toBool() + ); + + mEngine->window()->setCursor( Qt::OpenHandCursor ); +} + +Qgs3DMapCanvas::~Qgs3DMapCanvas() +{ + if ( mMapTool ) + mMapTool->deactivate(); + // make sure the scene is deleted while map settings object is still alive + delete mScene; + mScene = nullptr; + delete mMap; + mMap = nullptr; +} + +void Qgs3DMapCanvas::resizeEvent( QResizeEvent *ev ) +{ + QWidget::resizeEvent( ev ); + + if ( !mScene ) + return; + + QRect viewportRect( QPoint( 0, 0 ), size() ); + mScene->cameraController()->setViewport( viewportRect ); +} + +void Qgs3DMapCanvas::setMap( Qgs3DMapSettings *map ) +{ + // TODO: eventually we want to get rid of this + Q_ASSERT( !mMap ); + Q_ASSERT( !mScene ); + + //QRect viewportRect( QPoint( 0, 0 ), size() ); + Qgs3DMapScene *newScene = new Qgs3DMapScene( *map, mEngine ); + + mEngine->setRootEntity( newScene ); + + if ( mScene ) + mScene->deleteLater(); + mScene = newScene; + + delete mMap; + mMap = map; + + resetView(); + + // Connect the camera to the navigation widget. + QObject::connect( + this->cameraController(), + &QgsCameraController::cameraChanged, + mNavigationWidget, + [ = ] + { + mNavigationWidget->updateFromCamera(); + } + ); + + emit mapSettingsChanged(); +} + +QgsCameraController *Qgs3DMapCanvas::cameraController() +{ + return mScene ? mScene->cameraController() : nullptr; +} + +void Qgs3DMapCanvas::resetView() +{ + mScene->viewZoomFull(); +} + +void Qgs3DMapCanvas::setViewFromTop( const QgsPointXY ¢er, float distance, float rotation ) +{ + float worldX = center.x() - mMap->origin().x(); + float worldY = center.y() - mMap->origin().y(); + mScene->cameraController()->setViewFromTop( worldX, -worldY, distance, rotation ); +} + +void Qgs3DMapCanvas::saveAsImage( const QString fileName, const QString fileFormat ) +{ + if ( !fileName.isEmpty() ) + { + mCaptureFileName = fileName; + mCaptureFileFormat = fileFormat; + mEngine->requestCaptureImage(); + } +} + +void Qgs3DMapCanvas::setMapTool( Qgs3DMapTool *tool ) +{ + if ( tool == mMapTool ) + return; + + // For Camera Control tool + if ( mMapTool && !tool ) + { + mEngine->window()->removeEventFilter( this ); + mScene->cameraController()->setEnabled( true ); + mEngine->window()->setCursor( Qt::OpenHandCursor ); + } + else if ( !mMapTool && tool ) + { + mEngine->window()->installEventFilter( this ); + mScene->cameraController()->setEnabled( tool->allowsCameraControls() ); + } + + if ( mMapTool ) + mMapTool->deactivate(); + + mMapTool = tool; + + if ( mMapTool ) + { + mMapTool->activate(); + mEngine->window()->setCursor( mMapTool->cursor() ); + } + +} + +bool Qgs3DMapCanvas::eventFilter( QObject *watched, QEvent *event ) +{ + if ( !mMapTool ) + return false; + + Q_UNUSED( watched ) + switch ( event->type() ) + { + case QEvent::MouseButtonPress: + mMapTool->mousePressEvent( static_cast( event ) ); + break; + case QEvent::MouseButtonRelease: + mMapTool->mouseReleaseEvent( static_cast( event ) ); + break; + case QEvent::MouseMove: + mMapTool->mouseMoveEvent( static_cast( event ) ); + break; + default: + break; + } + return false; +} + +void Qgs3DMapCanvas::setOnScreenNavigationVisibility( bool visibility ) +{ + mNavigationWidget->setVisible( visibility ); + QgsSettings setting; + setting.setValue( QStringLiteral( "/3D/navigationWidget/visibility" ), visibility, QgsSettings::Gui ); +} + +void Qgs3DMapCanvas::setTemporalController( QgsTemporalController *temporalController ) +{ + if ( mTemporalController ) + disconnect( mTemporalController, &QgsTemporalController::updateTemporalRange, this, &Qgs3DMapCanvas::updateTemporalRange ); + + mTemporalController = temporalController; + connect( mTemporalController, &QgsTemporalController::updateTemporalRange, this, &Qgs3DMapCanvas::updateTemporalRange ); +} + +void Qgs3DMapCanvas::updateTemporalRange( const QgsDateTimeRange &temporalrange ) +{ + mMap->setTemporalRange( temporalrange ); + mScene->updateTemporal(); +} diff --git a/pool/shard006/C++/0078727_combinations.cpp b/pool/shard006/C++/0078727_combinations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1bfad76d8073d97aa6e96ccf9ef4a9a8f916b3ea --- /dev/null +++ b/pool/shard006/C++/0078727_combinations.cpp @@ -0,0 +1,63 @@ +/* +http://oj.leetcode.com/problems/combinations/ +Fri Jan 31 01:48:09 EST 2014 + + +Combinations + +Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. + +For example, +If n = 4 and k = 2, a solution is: + +[ + [2,4], + [3,4], + [2,3], + [1,2], + [1,3], + [1,4], +] +*/ + +#include +#include +#include + +using namespace std; + +class Solution { +public: + void combineSub(vector> &coll, vector &v, int n, int k, int start) { + if (k == 0) { + coll.push_back(std::move(v)); + return; + } + for (int i = start; i <= n-k+1; ++i) { + vector nv(v); + nv.push_back(i); + combineSub(coll, nv, n, k-1, i+1); + } + } + vector > combine(int n, int k) { + vector> coll; + vector v; + combineSub(coll, v, n, k, 1); + return coll; + } +}; + +int main(int argc, char **argv) { + if (argc < 3) + return 1; + int n = atoi(argv[1]); + int k = atoi(argv[2]); + Solution s; + auto vvi = s.combine(n, k); + for (auto &x : vvi) { + for (auto &y : x) + cout << y << " "; + cout << endl; + } + return 0; +} diff --git a/pool/shard006/C++/0078730_graph_community_network_edges.cc b/pool/shard006/C++/0078730_graph_community_network_edges.cc new file mode 100644 index 0000000000000000000000000000000000000000..fb243bb6824eb7fcab08886343d5dde0745d4b7b --- /dev/null +++ b/pool/shard006/C++/0078730_graph_community_network_edges.cc @@ -0,0 +1,84 @@ +// graph-tool -- a general graph modification and manipulation thingy +// +// Copyright (C) 2006-2015 Tiago de Paula Peixoto +// +// 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 "graph_python_interface.hh" +#include "graph_filtering.hh" +#include "graph.hh" +#include "graph_selectors.hh" +#include "graph_properties.hh" + +#include +#include +#include +#include + +#include "graph_community_network.hh" + +using namespace std; +using namespace boost; + +using namespace graph_tool; + +typedef ConstantPropertyMap no_eweight_map_t; +typedef property_map_type::apply::type::unchecked_t ecount_map_t; + +struct get_community_network_edges_dispatch +{ + get_community_network_edges_dispatch(bool self_loops, bool parallel_edges) + : _self_loops(self_loops), _parallel_edges(parallel_edges) {} + bool _self_loops; + bool _parallel_edges; + + template + void operator()(const Graph& g, CommunityGraph& cg, EdgeIndex cedge_index, + CommunityMap s_map, boost::any acs_map, + EdgeWeightMap eweight, boost::any ecount) const + { + typename CommunityMap::checked_t cs_map = boost::any_cast(acs_map); + + typedef typename boost::mpl::if_, + ecount_map_t, EdgeWeightMap>::type eweight_t; + + typename eweight_t::checked_t edge_count = boost::any_cast(ecount); + get_community_network_edges()(g, cg, cedge_index, s_map, + cs_map, eweight, edge_count, + _self_loops, _parallel_edges); + } +}; + + +void community_network_edges(GraphInterface& gi, GraphInterface& cgi, + boost::any community_property, + boost::any condensed_community_property, + boost::any edge_count, boost::any eweight, + bool self_loops, bool parallel_edges) +{ + typedef boost::mpl::push_back::type + eweight_properties; + + if (eweight.empty()) + eweight = no_eweight_map_t(1); + + run_action<>() + (gi, std::bind(get_community_network_edges_dispatch(self_loops, parallel_edges), + placeholders::_1, std::ref(cgi.get_graph()), cgi.get_edge_index(), + placeholders::_2, condensed_community_property, + placeholders::_3, edge_count), + writable_vertex_properties(), eweight_properties()) + (community_property, eweight); +} diff --git a/pool/shard006/C++/0078738_SVGFEMerge.cpp b/pool/shard006/C++/0078738_SVGFEMerge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..caae33d5d637454c5c6641aa209c4caba19e0468 --- /dev/null +++ b/pool/shard006/C++/0078738_SVGFEMerge.cpp @@ -0,0 +1,61 @@ +/* + Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann + 2004, 2005 Rob Buis + 2005 Eric Seidel + + This file is part of the KDE project + + 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 + aint 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(SVG) && ENABLE(SVG_EXPERIMENTAL_FEATURES) +#include "SVGFEMerge.h" +#include "TextStream.h" + +namespace WebCore { + +const Vector& SVGFEMerge::mergeInputs() const +{ + return m_mergeInputs; +} + +void SVGFEMerge::setMergeInputs(const Vector& mergeInputs) +{ + m_mergeInputs = mergeInputs; +} + +TextStream& SVGFEMerge::externalRepresentation(TextStream& ts) const +{ + ts << "[type=MERGE] "; + SVGFilterEffect::externalRepresentation(ts); + ts << "[merge inputs=["; + unsigned x = 0; + unsigned size = m_mergeInputs.size(); + while (x < size) { + ts << m_mergeInputs[x]; + x++; + if (x < m_mergeInputs.size()) + ts << ", "; + } + ts << "]]"; + return ts; +} + +} // namespace WebCore + +#endif // ENABLE(SVG) && ENABLE(SVG_EXPERIMENTAL_FEATURES) diff --git a/pool/shard006/C++/0078742_NuPIC.cpp b/pool/shard006/C++/0078742_NuPIC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0ab614b3045c4385ee3783454c55d31b1e321b5 --- /dev/null +++ b/pool/shard006/C++/0078742_NuPIC.cpp @@ -0,0 +1,82 @@ +/* --------------------------------------------------------------------- + * Numenta Platform for Intelligent Computing (NuPIC) + * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement + * with Numenta, Inc., for a separate license for this software code, the + * following terms and conditions apply: + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero Public License for more details. + * + * You should have received a copy of the GNU Affero Public License + * along with this program. If not, see http://www.gnu.org/licenses. + * + * http://numenta.org/licenses/ + * --------------------------------------------------------------------- + */ + +/* @file Implementation of NuPIC init/shutdown operations */ + +// TODO -- thread safety + +#include +#include +#include + +namespace nupic { + +std::set NuPIC::networks_; +bool NuPIC::initialized_ = false; + +void NuPIC::init() { + if (isInitialized()) + return; + + // internal consistency check. Nonzero should be impossible. + NTA_CHECK(networks_.size() == 0) << "Internal error in NuPIC::init()"; + + initialized_ = true; +} + +void NuPIC::shutdown() { + if (!isInitialized()) { + NTA_THROW << "NuPIC::shutdown -- NuPIC has not been initialized"; + } + + if (!networks_.empty()) { + NTA_THROW << "NuPIC::shutdown -- cannot shut down NuPIC because " + << networks_.size() << " networks still exist."; + } + + RegionImplFactory::getInstance().cleanup(); + initialized_ = false; +} + +void NuPIC::registerNetwork(Network *net) { + if (!isInitialized()) { + NTA_THROW + << "Attempt to create a network before NuPIC has been initialized -- " + "call NuPIC::init() before creating any networks"; + } + + auto n = networks_.find(net); + // This should not be possible + NTA_CHECK(n == networks_.end()) + << "Internal error -- double registration of network"; + networks_.insert(net); +} + +void NuPIC::unregisterNetwork(Network *net) { + auto n = networks_.find(net); + NTA_CHECK(n != networks_.end()) << "Internal error -- network not registered"; + networks_.erase(n); +} + +bool NuPIC::isInitialized() { return initialized_; } + +} // namespace nupic diff --git a/pool/shard006/C++/0078744_main.cpp b/pool/shard006/C++/0078744_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7d650c9695cfbdbc633e781715133c51b96ada8 --- /dev/null +++ b/pool/shard006/C++/0078744_main.cpp @@ -0,0 +1,65 @@ +//William Tustumi + +#include "main.hpp" + +int main (){ + + char mode; + uint64_t text; + uint64_t key; + + cin >> mode; + + if(mode == 'e'){ + cin >> hex >> text >> key; + cout << "TEXT: " << hex << text << endl; + cout << "KEY: " << hex << key << endl; + + uint8_t *text_array; + uint8_t *key_array; + + text_array = utin64touint8(text); + key_array = utin64touint8(key); + + double clock = encryptBlock(text_array, key_array); + + cout << "Cypher text:" << endl; + cout << hex << uint8touint64(text_array) << endl; + + cout << "Number of clocks: " << clock << endl << endl; + + delete [] text_array; + delete [] key_array; + + }else if(mode == 'd'){ + cin >> hex >> text >> key; + + cout << "TEXT: " << hex << text << endl; + cout << "KEY: " << hex << key << endl; + + uint8_t *text_array; + uint8_t *key_array; + + text_array = utin64touint8(text); + key_array = utin64touint8(key); + + double clock = decryptBlock(text_array, key_array); + + cout << "Cypher text:" << endl; + cout << hex << uint8touint64(text_array) << endl; + + cout << "Number of clocks: " << clock << endl << endl; + + delete [] text_array; + delete [] key_array; + + }else if(mode == 'c'){ + testComp(); + }else if(mode == 't'){ + testTime(); + }else{ + cout << ERR_MSG << endl; + } + + return 0; +} diff --git a/pool/shard006/C++/0078745_moc_diagramtextitem.cpp b/pool/shard006/C++/0078745_moc_diagramtextitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7eb35d41f8f287de2fe4c8baa99ab5d3ad9a785 --- /dev/null +++ b/pool/shard006/C++/0078745_moc_diagramtextitem.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'diagramtextitem.h' +** +** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../cs240-lab7-src/diagramtextitem.h" +#include +#include +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'diagramtextitem.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 67 +#error "This file was generated using the moc from 5.5.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 +struct qt_meta_stringdata_DiagramTextItem_t { + QByteArrayData data[7]; + char stringdata0[79]; +}; +#define QT_MOC_LITERAL(idx, ofs, len) \ + Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ + qptrdiff(offsetof(qt_meta_stringdata_DiagramTextItem_t, stringdata0) + ofs \ + - idx * sizeof(QByteArrayData)) \ + ) +static const qt_meta_stringdata_DiagramTextItem_t qt_meta_stringdata_DiagramTextItem = { + { +QT_MOC_LITERAL(0, 0, 15), // "DiagramTextItem" +QT_MOC_LITERAL(1, 16, 9), // "lostFocus" +QT_MOC_LITERAL(2, 26, 0), // "" +QT_MOC_LITERAL(3, 27, 16), // "DiagramTextItem*" +QT_MOC_LITERAL(4, 44, 4), // "item" +QT_MOC_LITERAL(5, 49, 14), // "selectedChange" +QT_MOC_LITERAL(6, 64, 14) // "QGraphicsItem*" + + }, + "DiagramTextItem\0lostFocus\0\0DiagramTextItem*\0" + "item\0selectedChange\0QGraphicsItem*" +}; +#undef QT_MOC_LITERAL + +static const uint qt_meta_data_DiagramTextItem[] = { + + // content: + 7, // revision + 0, // classname + 0, 0, // classinfo + 2, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 2, // signalCount + + // signals: name, argc, parameters, tag, flags + 1, 1, 24, 2, 0x06 /* Public */, + 5, 1, 27, 2, 0x06 /* Public */, + + // signals: parameters + QMetaType::Void, 0x80000000 | 3, 4, + QMetaType::Void, 0x80000000 | 6, 4, + + 0 // eod +}; + +void DiagramTextItem::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + DiagramTextItem *_t = static_cast(_o); + Q_UNUSED(_t) + switch (_id) { + case 0: _t->lostFocus((*reinterpret_cast< DiagramTextItem*(*)>(_a[1]))); break; + case 1: _t->selectedChange((*reinterpret_cast< QGraphicsItem*(*)>(_a[1]))); break; + default: ; + } + } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { + switch (_id) { + default: *reinterpret_cast(_a[0]) = -1; break; + case 0: + switch (*reinterpret_cast(_a[1])) { + default: *reinterpret_cast(_a[0]) = -1; break; + case 0: + *reinterpret_cast(_a[0]) = qRegisterMetaType< DiagramTextItem* >(); break; + } + break; + case 1: + switch (*reinterpret_cast(_a[1])) { + default: *reinterpret_cast(_a[0]) = -1; break; + case 0: + *reinterpret_cast(_a[0]) = qRegisterMetaType< QGraphicsItem* >(); break; + } + break; + } + } else if (_c == QMetaObject::IndexOfMethod) { + int *result = reinterpret_cast(_a[0]); + void **func = reinterpret_cast(_a[1]); + { + typedef void (DiagramTextItem::*_t)(DiagramTextItem * ); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&DiagramTextItem::lostFocus)) { + *result = 0; + } + } + { + typedef void (DiagramTextItem::*_t)(QGraphicsItem * ); + if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&DiagramTextItem::selectedChange)) { + *result = 1; + } + } + } +} + +const QMetaObject DiagramTextItem::staticMetaObject = { + { &QGraphicsTextItem::staticMetaObject, qt_meta_stringdata_DiagramTextItem.data, + qt_meta_data_DiagramTextItem, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} +}; + + +const QMetaObject *DiagramTextItem::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; +} + +void *DiagramTextItem::qt_metacast(const char *_clname) +{ + if (!_clname) return Q_NULLPTR; + if (!strcmp(_clname, qt_meta_stringdata_DiagramTextItem.stringdata0)) + return static_cast(const_cast< DiagramTextItem*>(this)); + return QGraphicsTextItem::qt_metacast(_clname); +} + +int DiagramTextItem::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QGraphicsTextItem::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; + } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { + if (_id < 2) + qt_static_metacall(this, _c, _id, _a); + _id -= 2; + } + return _id; +} + +// SIGNAL 0 +void DiagramTextItem::lostFocus(DiagramTextItem * _t1) +{ + void *_a[] = { Q_NULLPTR, const_cast(reinterpret_cast(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 0, _a); +} + +// SIGNAL 1 +void DiagramTextItem::selectedChange(QGraphicsItem * _t1) +{ + void *_a[] = { Q_NULLPTR, const_cast(reinterpret_cast(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 1, _a); +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard006/C++/0078748_rpc_rendezvous_mgr_test.cc b/pool/shard006/C++/0078748_rpc_rendezvous_mgr_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..25ff6512a03f5adf6aa1f584801b0793dc58e279 --- /dev/null +++ b/pool/shard006/C++/0078748_rpc_rendezvous_mgr_test.cc @@ -0,0 +1,203 @@ +/* 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/distributed_runtime/rpc/rpc_rendezvous_mgr.h" + +#include "tensorflow/core/common_runtime/process_util.h" +#include "tensorflow/core/framework/control_flow.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { + +// string -> Tensor +Tensor V(const string& content) { + Tensor tensor(DT_STRING, TensorShape({})); + tensor.scalar()() = content; + return tensor; +} + +// Tensor -> string +string V(const Tensor& tensor) { + CHECK_EQ(tensor.dtype(), DT_STRING); + CHECK(TensorShapeUtils::IsScalar(tensor.shape())); + return tensor.scalar()(); +} + +Rendezvous::ParsedKey MakeKey(const string& s) { + Rendezvous::ParsedKey key; + CHECK(Rendezvous::ParseKey(s, &key).ok()); + return key; +} + +namespace { +// Fake cache implementation for WorkerEnv. +class DummyWorkerCache : public WorkerCacheInterface { + void ListWorkers(std::vector* workers) const override {} + WorkerInterface* CreateWorker(const string& target) override { + return nullptr; + } + bool GetDeviceLocalityNonBlocking(const string& device, + DeviceLocality* locality) override { + return false; + } + void GetDeviceLocalityAsync(const string& device, DeviceLocality* locality, + StatusCallback done) override {} +}; +} // namespace + +class RpcRendezvousMgrTest : public ::testing::Test { + protected: + RpcRendezvousMgrTest() + : cache_(new DummyWorkerCache), + worker_session_("rpc_session", "/job:mnist/replica:1/task:2", + std::unique_ptr(cache_), + std::unique_ptr(), + std::unique_ptr()), + rmgr_(&env) { + env.env = Env::Default(); + } + + DummyWorkerCache* cache_; // Managed by worker_session. + WorkerEnv env; + + WorkerSession worker_session_; + RpcRendezvousMgr rmgr_; +}; + +TEST_F(RpcRendezvousMgrTest, LocalSendRecv) { + const int64 step_id = 123; + const Rendezvous::ParsedKey key = MakeKey(Rendezvous::CreateKey( + "/job:mnist/replica:1/task:2/cpu:0", 7890, + "/job:mnist/replica:1/task:2/cpu:1", "foo", FrameAndIter(0, 0))); + { + RemoteRendezvous* rendez = rmgr_.Find(step_id); + TF_ASSERT_OK(rendez->Initialize(&worker_session_)); + core::ScopedUnref unref(rendez); + Rendezvous::Args args; + TF_ASSERT_OK(rendez->Send(key, args, V("peach"), false)); + } + { + Tensor val(DT_FLOAT); + bool val_dead = false; + TF_ASSERT_OK(rmgr_.RecvLocal(step_id, key, &val, &val_dead)); + EXPECT_EQ(V(val), "peach"); + } + rmgr_.Cleanup(step_id); +} + +TEST_F(RpcRendezvousMgrTest, LocalAbort) { + const Rendezvous::ParsedKey key = MakeKey(Rendezvous::CreateKey( + "/job:mnist/replica:1/task:2/cpu:0", 7890, + "/job:mnist/replica:1/task:2/cpu:1", "foo", FrameAndIter(0, 0))); + { // Explicit Abort(). + const int64 step_id = 123; + RemoteRendezvous* rendez = rmgr_.Find(step_id); + core::ScopedUnref unref(rendez); + SchedClosure([this, rendez]() { + env.env->SleepForMicroseconds(100 * 1000); + rendez->StartAbort(errors::Aborted("")); + }); + Tensor val(DT_STRING); + bool val_dead = false; + Rendezvous::Args args; + TF_ASSERT_OK(rendez->Initialize(&worker_session_)); + EXPECT_TRUE(errors::IsAborted(rendez->Recv(key, args, &val, &val_dead))); + } + { // Cleanup causes Abort(). + const int64 step_id = 321; + RemoteRendezvous* rendez = rmgr_.Find(step_id); + core::ScopedUnref unref(rendez); + SchedClosure([this, step_id]() { + env.env->SleepForMicroseconds(100 * 1000); + rmgr_.Cleanup(step_id); + }); + Tensor val(DT_STRING); + bool val_dead = false; + Rendezvous::Args args; + TF_ASSERT_OK(rendez->Initialize(&worker_session_)); + EXPECT_TRUE(errors::IsAborted(rendez->Recv(key, args, &val, &val_dead))); + } +} + +TEST_F(RpcRendezvousMgrTest, CleanupAll) { + const Rendezvous::ParsedKey key = MakeKey(Rendezvous::CreateKey( + "/job:mnist/replica:1/task:2/cpu:0", 7890, + "/job:mnist/replica:1/task:2/cpu:1", "foo", FrameAndIter(0, 0))); + { + const int64 step_id = 123; + RemoteRendezvous* rendez = rmgr_.Find(step_id); + TF_ASSERT_OK(rendez->Initialize(&worker_session_)); + core::ScopedUnref unref(rendez); + Rendezvous::Args args; + TF_ASSERT_OK(rendez->Send(key, args, V("peach"), false)); + rmgr_.CleanupAll(); + Tensor val(DT_STRING); + bool val_dead = false; + EXPECT_TRUE(errors::IsAborted(rendez->Recv(key, args, &val, &val_dead))); + } +} + +class DummyDeviceContext : public DeviceContext { + public: + explicit DummyDeviceContext(int stream_id) : stream_id_(stream_id) {} + ~DummyDeviceContext() override {} + int stream_id() const { return stream_id_; } + + private: + const int stream_id_; +}; + +TEST_F(RpcRendezvousMgrTest, TransferDummyDeviceContext) { + DummyDeviceContext* dc = new DummyDeviceContext(123); + + const int64 step_id = 123; + const Rendezvous::ParsedKey key = MakeKey(Rendezvous::CreateKey( + "/job:mnist/replica:1/task:2/cpu:0", 7890, + "/job:mnist/replica:1/task:2/cpu:1", "foo", FrameAndIter(0, 0))); + { + RemoteRendezvous* rendez = rmgr_.Find(step_id); + core::ScopedUnref unref(rendez); + Rendezvous::Args args; + args.device_context = dc; + TF_ASSERT_OK(rendez->Initialize(&worker_session_)); + TF_ASSERT_OK(rendez->Send(key, args, V("peach"), false)); + } + { + Notification n; + rmgr_.RecvLocalAsync( + step_id, key, + [&n](const Status& s, const Rendezvous::Args send_args, + const Rendezvous::Args recv_args, const Tensor& val, + bool is_dead) { + auto send_dev_context = + static_cast(send_args.device_context); + CHECK_EQ(123, send_dev_context->stream_id()); + CHECK_EQ(V(val), "peach"); + n.Notify(); + }); + n.WaitForNotification(); + } + rmgr_.Cleanup(step_id); + dc->Unref(); +} + +// NOTE: Remote Send/Recv is better tested in worker_test.cc + +} // namespace tensorflow diff --git a/pool/shard006/C++/0078758_HalfEdgeMesh2DSquared.cpp b/pool/shard006/C++/0078758_HalfEdgeMesh2DSquared.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e65edc5d95a31d0d658d1e5b6d4a074665bef5c6 --- /dev/null +++ b/pool/shard006/C++/0078758_HalfEdgeMesh2DSquared.cpp @@ -0,0 +1,198 @@ +#include +#include +#include +#include "HalfEdgeMesh2DSquared.h" +#include "Vertex.h" +#include "Edge.h" +#include "Face.h" +#include +#include +#include +#include "Optimization.h" + +using namespace cop4530; + + +HalfEdgeMesh2DSquared::HalfEdgeMesh2DSquared() +{ + vertexPool.CreatePoolParty(); + edgePool.CreatePoolParty(); + facePool.CreatePoolParty(); +} + +HalfEdgeMesh2DSquared::~HalfEdgeMesh2DSquared() +{ +} + +void HalfEdgeMesh2DSquared::Construct(std::string map, const int width, const int height) +{ + Vector allFaces; + allFaces.reserve(height*width); + Face* emptyFace = facePool.PoolPartyAlloc(); + + for (int y = 0; y < height; y++) + { + //if (map[y*width] == '/' || map[y*width] == ';' || map[y*width] == '#') continue; /* ignore comment line */ + for (int x = 0; x < width; x++) + { + int currentCell = y*width + x; + if (!map[currentCell]) + { + allFaces.push_back(emptyFace); + } + else + { + //connecting + + //let's get vertices we wanna work with + Vertex* vertice1 = vertexPool.PoolPartyAlloc(); + Vertex* vertice2 = vertexPool.PoolPartyAlloc(); + Vertex* vertice3 = vertexPool.PoolPartyAlloc(); + Vertex* vertice4 = vertexPool.PoolPartyAlloc(); + + vertice1->pos = Vector2(x, (y + 1)); + vertice2->pos = Vector2(x, y); + vertice3->pos = Vector2((x + 1), y); + vertice4->pos = Vector2((x + 1), (y + 1)); + + //create new edges + Edge* leftEdge = edgePool.PoolPartyAlloc(); + Edge* topEdge = edgePool.PoolPartyAlloc(); + Edge* rightEdge = edgePool.PoolPartyAlloc(); + Edge* bottomEdge = edgePool.PoolPartyAlloc(); + + //connect vertices to edges + leftEdge->vertex = vertice1; + topEdge->vertex = vertice2; + rightEdge->vertex = vertice3; + bottomEdge->vertex = vertice4; + + //connect edges with next + leftEdge->next = topEdge; + topEdge->next = rightEdge; + rightEdge->next = bottomEdge; + bottomEdge->next = leftEdge; + + //connect edges with previous + leftEdge->prev = bottomEdge; + topEdge->prev = leftEdge; + rightEdge->prev = topEdge; + bottomEdge->prev = rightEdge; + + edges.push_back(leftEdge); + edges.push_back(topEdge); + edges.push_back(rightEdge); + edges.push_back(bottomEdge); + + //is not at x boundaries? + if (x > 0) + { + //is cell to the left walkable? + int cellToTheLeft = y*width + (x - 1); + if (map[cellToTheLeft]) + { + //pair with the left one + Edge* lastFaceRightEdge = faces.back()->edge->next->next; + lastFaceRightEdge->pair = leftEdge; + leftEdge->pair = lastFaceRightEdge; + } + } + + //is not at y boundaries? + if (y > 0) + { + //is cell above walkable? + int cellAbove = (y - 1)*width + x; + if (map[cellAbove]) + { + //pair with the cell above + Edge* aboveFaceBottomEdge = allFaces[cellAbove]->edge->next->next->next; + aboveFaceBottomEdge->pair = topEdge; + topEdge->pair = aboveFaceBottomEdge; + } + } + + vertices.push_back(vertice1); + vertices.push_back(vertice2); + vertices.push_back(vertice3); + vertices.push_back(vertice4); + + Face* newFace = facePool.PoolPartyAlloc(); + newFace->edge = rightEdge; + + rightEdge->face = newFace; + rightEdge->next->face = newFace; + rightEdge->next->next->face = newFace; + rightEdge->next->next->next->face = newFace; + + faces.push_back(newFace); + allFaces.push_back(newFace); + + if (map[currentCell] == 'S') + { + startFace = newFace; + //startFacePos = newFace->edge->vertex->pos; + startFacePos = newFace->getMidPointAverage(); + } + if (map[currentCell] == 'G') + { + goals.push_back(newFace); + goalsPos.push_back(newFace->getMidPointAverage()); + endFace = newFace; + //endFacePos = newFace2->edge->vertex->pos; + endFacePos = newFace->getMidPointAverage(); + } + } + } + } + + /* + for (int i = 0; i < edges.size(); i++) //error check, if we connected the edge to itself as pair + { + if (edges.at(i)->next == edges.at(i)->pair) + { + printf("error %d \n", i); + } + } + */ +} + +void HalfEdgeMesh2DSquared::ConstructFromFile(const char * path) +{ + std::ifstream file1(path); + std::string str; + std::string map = ""; + int width = 0; + int height = 0; + //loading the map into a single buffer + while (std::getline(file1, str)) + { + map += str; + height++; + width = str.length(); + } + + file1.close(); + + Construct(map, width, height); +} + +Face* HalfEdgeMesh2DSquared::findNode(const Vector2& point) +{ + return Optimization::findNode(point, faces); +} + +bool HalfEdgeMesh2DSquared::isPointInNode(const Vector2& point, Face* node) +{ + return Optimization::isPointInNode(point, node); +} + +void HalfEdgeMesh2DSquared::quadrangulate() +{ + Optimization::quadrangulate(faces); +} + +void HalfEdgeMesh2DSquared::optimizeMesh() +{ + Optimization::optimizeMesh(faces); +} \ No newline at end of file diff --git a/pool/shard006/C++/0078772_mitkRigidRegistrationPresetTest.cpp b/pool/shard006/C++/0078772_mitkRigidRegistrationPresetTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41136b950cb728af8ebc2074c03c0c25d78aa358 --- /dev/null +++ b/pool/shard006/C++/0078772_mitkRigidRegistrationPresetTest.cpp @@ -0,0 +1,102 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkRigidRegistrationPreset.h" +#include + +int mitkRigidRegistrationPresetTest(int /*argc*/, char * /*argv*/ []) +{ + typedef itk::Array ArrayType; + + mitk::RigidRegistrationPreset *rrp = new mitk::RigidRegistrationPreset; + std::cout << "[PASSED]" << std::endl; + + // Check if the default presets (in the Functionality directory) can be loaded. + std::cout << "Testing default parameter loading...\n"; + if (!rrp->LoadPreset()) + { + std::cout << "[FAILED]" << std::endl; + return EXIT_FAILURE; + } + std::cout << "[PASSED]" << std::endl; + + // Check if an exemplary parameter set can be extracted from the read presets. + std::cout << "Testing if exemplary default values match default parameters...\n"; + + ArrayType transformValues = rrp->getTransformValues("ITK Image Registration 12"); + ArrayType metricValues = rrp->getMetricValues("ITK Image Registration 12"); + ArrayType optimizerValues = rrp->getOptimizerValues("ITK Image Registration 12"); + ArrayType interpolatorValues = rrp->getInterpolatorValues("ITK Image Registration 12"); + + std::cout << transformValues[5] << metricValues[1] << optimizerValues[4] << interpolatorValues[0] << std::endl; + + if (!(transformValues[5] == 0.001) || !(metricValues[1] == 1) || !(optimizerValues[4] == 0.1) || + !(interpolatorValues[0] == 0)) + { + std::cout << "[FAILED]" << std::endl; + return EXIT_FAILURE; + } + std::cout << "[PASSED]" << std::endl; + + // Testing if a save operation can be performed. + std::cout << "Testing if saving is possible...\n"; + if (!rrp->newPresets(rrp->getTransformValuesPresets(), + rrp->getMetricValuesPresets(), + rrp->getOptimizerValuesPresets(), + rrp->getInterpolatorValuesPresets(), + "TestPresets.xml")) + { + std::cout << "[FAILED]" << std::endl; + return EXIT_FAILURE; + } + std::cout << "[PASSED]" << std::endl; + + // Testing what happens if we now repeat the test with the previously written xml file + delete rrp; + + mitk::RigidRegistrationPreset *rrp2 = new mitk::RigidRegistrationPreset; + std::cout << "[PASSED]" << std::endl; + + // Check if the default presets (in the Functionality directory) can be loaded. + std::cout << "Testing default parameter loading, second time...\n"; + if (!rrp2->LoadPreset("TestPresets.xml")) + { + std::cout << "[FAILED]" << std::endl; + return EXIT_FAILURE; + } + std::cout << "[PASSED]" << std::endl; + + // Check if an exemplary parameter set can be extracted from the read presets. + std::cout << "Testing if exemplary default values match default parameters, second time...\n"; + + transformValues = rrp2->getTransformValues("ITK Image Registration 12"); + metricValues = rrp2->getMetricValues("ITK Image Registration 12"); + optimizerValues = rrp2->getOptimizerValues("ITK Image Registration 12"); + interpolatorValues = rrp2->getInterpolatorValues("ITK Image Registration 12"); + + if (!(transformValues[5] == 0.001) || !(metricValues[1] == 1) || !(optimizerValues[4] == 0.1) || + !(interpolatorValues[0] == 0)) + { + std::cout << "[FAILED]" << std::endl; + return EXIT_FAILURE; + } + std::cout << "[PASSED]" << std::endl; + + delete rrp2; + + std::cout << "[TEST DONE]" << std::endl; + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C++/0078773_MainPage.xaml.cpp b/pool/shard006/C++/0078773_MainPage.xaml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fb54df518144e6ba54b7da4b57ccdff0514392d --- /dev/null +++ b/pool/shard006/C++/0078773_MainPage.xaml.cpp @@ -0,0 +1,41 @@ +// +// MainPage.xaml.cpp +// Implementation of the MainPage class. +// + +#include "pch.h" +#include "MainPage.xaml.h" + +using namespace RoutedEvents1; + +using namespace Platform; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::UI; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Controls::Primitives; +using namespace Windows::UI::Xaml::Data; +using namespace Windows::UI::Xaml::Input; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Navigation; + +MainPage::MainPage() +{ + InitializeComponent(); + srand(int(time(NULL))); +} + +void MainPage::OnGridTapped(Object^ sender, TappedRoutedEventArgs^ args) +{ + TextBlock^ txtblk = dynamic_cast(args->OriginalSource); + + if (txtblk != nullptr) + { + unsigned char r = unsigned char((rand() % 256)); + unsigned char g = unsigned char((rand() % 256)); + unsigned char b = unsigned char((rand() % 256)); + Color clr = ColorHelper::FromArgb(255, r, g, b); + txtblk->Foreground = ref new SolidColorBrush(clr); + } +} \ No newline at end of file diff --git a/pool/shard006/C++/0078781_CyPy_Atlas.cpp b/pool/shard006/C++/0078781_CyPy_Atlas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7136500b56b4decb80e32b536d054baf8d156aa1 --- /dev/null +++ b/pool/shard006/C++/0078781_CyPy_Atlas.cpp @@ -0,0 +1,58 @@ +/* + Copyright (C) 2018 Erik Ogenvik + + 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 "CyPy_Atlas.h" +#include "CyPy_Element.h" +#include "CyPy_Operation.h" +#include "CyPy_Oplist.h" +#include "CyPy_RootEntity.h" +#include "CyPy_Location.h" +#include "CyPy_EntityLocation.h" +#include "CyPy_Root.h" + +CyPy_Atlas::CyPy_Atlas() : ExtensionModule("atlas") +{ + + CyPy_ElementMap::init_type(); + CyPy_ElementList::init_type(); + CyPy_Root::init_type(); + CyPy_Operation::init_type(); + CyPy_Oplist::init_type(); + CyPy_RootEntity::init_type(); + + + initialize("Atlas"); + + Py::Dict d(moduleDictionary()); + + d["Operation"] = CyPy_Operation::type(); + d["Root"] = CyPy_Root::type(); + d["Oplist"] = CyPy_Oplist::type(); + d["Entity"] = CyPy_RootEntity::type(); + d["ElementList"] = CyPy_ElementList::type(); + d["ElementMap"] = CyPy_ElementMap::type(); +} + +std::string CyPy_Atlas::init() +{ + PyImport_AppendInittab("atlas", []() { + static auto module = new CyPy_Atlas(); + return module->module().ptr(); + }); + return "atlas"; +} diff --git a/pool/shard006/C++/0078782_tst_float.cpp b/pool/shard006/C++/0078782_tst_float.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43b72c3913705b5774d0691bd3a079d8db07326e --- /dev/null +++ b/pool/shard006/C++/0078782_tst_float.cpp @@ -0,0 +1,122 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +class tst_float: public QObject +{ + Q_OBJECT +private slots: + void floatComparisons() const; + void floatComparisons_data() const; + void compareFloatTests() const; + void compareFloatTests_data() const; +}; + +void tst_float::floatComparisons() const +{ + QFETCH(float, operandLeft); + QFETCH(float, operandRight); + + QCOMPARE(operandLeft, operandRight); +} + +void tst_float::floatComparisons_data() const +{ + QTest::addColumn("operandLeft"); + QTest::addColumn("operandRight"); + + QTest::newRow("should SUCCEED 1") + << float(0) + << float(0); + + QTest::newRow("should FAIL 1") + << float(1.00000) + << float(3.00000); + + QTest::newRow("should FAIL 2") + << float(1.00000e-7f) + << float(3.00000e-7f); + + // QCOMPARE for floats uses qFuzzyCompare(), which succeeds if the numbers + // differ by no more than 1/100,000th of the smaller value. Thus + // QCOMPARE(99998, 99999) should fail, while QCOMPARE(100001, 100002) + // should pass. + + QTest::newRow("should FAIL 3") + << float(99998) + << float(99999); + + QTest::newRow("should SUCCEED 2") + << float(100001) + << float(100002); +} + +void tst_float::compareFloatTests() const +{ + QFETCH(float, t1); + + // Create two more values + // t2 differs from t1 by 1 ppm (part per million) + // t3 differs from t1 by 200% + // we should consider that t1 == t2 and t1 != t3 + const float t2 = t1 + (t1 / 1e6); + const float t3 = 3 * t1; + + QCOMPARE(t1, t2); + + /* Should FAIL. */ + QCOMPARE(t1, t3); +} + +void tst_float::compareFloatTests_data() const +{ + QTest::addColumn("t1"); + QTest::newRow("1e0") << 1e0f; + QTest::newRow("1e-7") << 1e-7f; + QTest::newRow("1e+7") << 1e+7f; +} + +QTEST_MAIN(tst_float) + +#include "tst_float.moc" diff --git a/pool/shard006/C++/0078783_address.cpp b/pool/shard006/C++/0078783_address.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffd3bd5288dcb24a94b8bcaed71b5df2abc23eb3 --- /dev/null +++ b/pool/shard006/C++/0078783_address.cpp @@ -0,0 +1,124 @@ + +#include "address.h" + +using namespace network; + +Address::Address() : + m_address(0), + m_port(0) +{ +} + +Address::Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) +{ + m_address = (a << 24) | (b << 16) | (c << 8) | d; + m_port = port; +} + +Address::Address(const char* address, uint16_t port) +{ + set(address, port); +} + +Address::Address(uint32_t address, uint16_t port) : + m_address(address), + m_port(port) +{ +} + +void Address::set(uint32_t address, uint16_t port) +{ + m_address = address; + m_port = port; +} + +void Address::set(const char* address, uint16_t port) +{ + uint8_t a = 0; + uint8_t b = 0; + uint8_t c = 0; + uint8_t d = 0; + + if (strcmp(address, "localhost") == 0) + { + a = 127; + b = 0; + c = 0; + d = 1; + } + else + { + char* str = _strdup(address); + char* context = nullptr; + char* token = strtok_s(str, ".", &context); + std::string parts[4]; + int i = 0; + while (token != nullptr) + { + parts[i] = token; + token = strtok_s(nullptr, ".", &context); + i++; + } + free(str); + a = static_cast(std::stoi(parts[0])); + b = static_cast(std::stoi(parts[1])); + c = static_cast(std::stoi(parts[2])); + d = static_cast(std::stoi(parts[3])); + } + + m_address = (a << 24) | (b << 16) | (c << 8) | d; + m_port = port; +} + +uint32_t Address::getAddress() const +{ + return m_address; +} + +uint8_t Address::getA() const +{ + return static_cast(m_address >> 24); +} + +uint8_t Address::getB() const +{ + return static_cast(m_address >> 16); +} + +uint8_t Address::getC() const +{ + return static_cast(m_address >> 8); +} + +uint8_t Address::getD() const +{ + return static_cast(m_address); +} + +uint16_t Address::getPort() const +{ + return m_port; +} + +std::string Address::toString() const +{ + return std::to_string(getA()) + "." + std::to_string(getB()) + "." + std::to_string(getC()) + "." + std::to_string(getD()) + ":" + std::to_string(getPort()); +} + +bool Address::isFromLAN() const +{ + return getA() == 127 + && getB() == 0 + && getC() == 0 + && getD() == 1; +} + +bool Address::operator==(const Address& other) const +{ + return (m_address == other.getAddress()) && (m_port == other.getPort()); +} + +bool Address::operator!=(const Address& other) const +{ + return !(*this == other); +} diff --git a/pool/shard006/C++/0078787_filepath.cpp b/pool/shard006/C++/0078787_filepath.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f2b7e853db700a0abd428e0c499dafab1a0f5df --- /dev/null +++ b/pool/shard006/C++/0078787_filepath.cpp @@ -0,0 +1,111 @@ +#include "filepath.h" +#include "system/base/eastlextend.h" +#include "system/base/debug/debug.h" + +//----------------------------------------------------------------------------- + +ZString ZFilePath::s_sPathSeparator = "/"; + +//----------------------------------------------------------------------------- + +ZFilePath::ZFilePath() + : m_bIsValid(false) +{ + +} + +ZFilePath::ZFilePath(const ZString& sPath) + : m_bIsValid(false) +{ + char fullPath[MAX_PATH]; + _fullpath(fullPath, sPath.c_str(), MAX_PATH); + + ZString sPathNormalized = fullPath; + replace_all(sPathNormalized, ZString("\\"), PathSeparator()); + ZString sDummy; + if (!split_first(sPathNormalized, m_sDrive, sDummy, ZString(":"))) + { + m_sDrive = ""; + } + + ZString sPathSeparator = ZString() + PathSeparator(); + if (!split_last(sPathNormalized, sDummy, m_sExtension, ZString("."))) + { + // directory + m_sDirectory = sPath; + } + else if(!split_last(sPathNormalized, m_sDirectory, m_sFileName, sPathSeparator)) + { + return; + } + + m_bIsValid = true; +} + +ZFilePath::~ZFilePath() +{ + +} + +//----------------------------------------------------------------------------- + +ZFilePath& ZFilePath::operator+=(const ZFilePath& path) +{ + *this = *this + path.ToFullPath(); + return *this; +} + +ZFilePath ZFilePath::operator+(const ZFilePath& path) const +{ + return *this + path.ToFullPath(); +} + +ZFilePath& ZFilePath::operator+=(const ZString& sPath) +{ + *this = *this + sPath; + return *this; +} + +ZFilePath ZFilePath::operator+(const ZString& sPath) const +{ + return ZFilePath(ToFullPath() + PathSeparator() + sPath); +} + +bool ZFilePath::IsValid() const +{ + return m_bIsValid; +} +const ZString& ZFilePath::GetDrive() const +{ + ZASSERT(IsValid()); + return m_sDrive; +} + +const ZString& ZFilePath::GetFileName() const +{ + ZASSERT(IsValid()); + return m_sFileName; +} + +const ZString& ZFilePath::GetExtension() const +{ + ZASSERT(IsValid()); + return m_sExtension; +} + +const ZString& ZFilePath::GetDirectory() const +{ + ZASSERT(IsValid()); + return m_sDirectory; +} + +ZString ZFilePath::PathSeparator() +{ + return s_sPathSeparator; +} + +ZString ZFilePath::ToFullPath() const +{ + ZASSERT(IsValid()); + return m_sDirectory + s_sPathSeparator + m_sFileName; +} \ No newline at end of file diff --git a/pool/shard006/C++/0078790_sysview_index.cc b/pool/shard006/C++/0078790_sysview_index.cc new file mode 100644 index 0000000000000000000000000000000000000000..111ef64bef89ef2e6c23fc3a26841c9f6e10645e --- /dev/null +++ b/pool/shard006/C++/0078790_sysview_index.cc @@ -0,0 +1,238 @@ +/* + * 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 ``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 + * 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 "sysview_index.h" +#include "schema.h" +#include "space.h" +#include "tuple.h" +#include "session.h" + +struct sysview_iterator { + struct iterator base; + struct iterator *source; + struct space *space; +}; + +static inline struct sysview_iterator * +sysview_iterator(struct iterator *ptr) +{ + return (struct sysview_iterator *) ptr; +} + +static void +sysview_iterator_free(struct iterator *ptr) +{ + struct sysview_iterator *it = sysview_iterator(ptr); + if (it->source != NULL) { + it->source->free(it->source); + } + free(it); +} + +static struct tuple * +sysview_iterator_next(struct iterator *iterator) +{ + assert(iterator->free == sysview_iterator_free); + struct sysview_iterator *it = sysview_iterator(iterator); + if (it->source->sc_version != sc_version) + return NULL; /* invalidate iterator */ + class SysviewIndex *index = (class SysviewIndex *) iterator->index; + struct tuple *tuple; + while ((tuple = it->source->next(it->source)) != NULL) { + if (index->filter(it->space, tuple)) + return tuple; + } + return NULL; +} + +SysviewIndex::SysviewIndex(struct key_def *key_def, uint32_t source_space_id, + uint32_t source_index_id, sysview_filter_f filter) + : Index(key_def), source_space_id(source_space_id), + source_index_id(source_index_id), filter(filter) +{ +} + +SysviewIndex::~SysviewIndex() +{ +} + +struct iterator * +SysviewIndex::allocIterator() const +{ + struct sysview_iterator *it = (struct sysview_iterator *) + calloc(1, sizeof(*it)); + if (it == NULL) { + tnt_raise(ClientError, ER_MEMORY_ISSUE, + sizeof(struct sysview_iterator), + "SysviewIndex", "iterator"); + } + it->base.free = sysview_iterator_free; + return (struct iterator *) it; +} + +void +SysviewIndex::initIterator(struct iterator *iterator, + enum iterator_type type, + const char *key, uint32_t part_count) const +{ + assert(iterator->free == sysview_iterator_free); + struct sysview_iterator *it = sysview_iterator(iterator); + struct space *source = space_cache_find(source_space_id); + class Index *pk = index_find(source, source_index_id); + /* + * Explicitly validate that key matches source's key_def. + * It is possible to change a source space without changing + * the view. + */ + key_validate(pk->key_def, type, key, part_count); + /* Re-allocate iterator if schema was changed */ + if (it->source != NULL && it->source->sc_version != ::sc_version) { + it->source->free(it->source); + it->source = NULL; + } + if (it->source == NULL) { + it->source = pk->allocIterator(); + it->source->sc_version = ::sc_version; + } + pk->initIterator(it->source, type, key, part_count); + iterator->index = (Index *) this; + iterator->next = sysview_iterator_next; + it->space = source; +} + +struct tuple * +SysviewIndex::findByKey(const char *key, uint32_t part_count) const +{ + struct space *source = space_cache_find(source_space_id); + class Index *pk = index_find(source, source_index_id); + if (!pk->key_def->is_unique) + tnt_raise(ClientError, ER_MORE_THAN_ONE_TUPLE); + primary_key_validate(pk->key_def, key, part_count); + struct tuple *tuple = pk->findByKey(key, part_count); + if (tuple == NULL || !filter(source, tuple)) + return NULL; + return tuple; +} + +struct tuple * +SysviewIndex::replace(struct tuple *old_tuple, struct tuple *new_tuple, + enum dup_replace_mode mode) +{ + (void) old_tuple; + (void) new_tuple; + (void) mode; + tnt_raise(ClientError, ER_UNSUPPORTED, "SysviewIndex", "replace()"); +} + +static bool +vspace_filter(struct space *source, struct tuple *tuple) +{ + struct credentials *cr = current_user(); + if (PRIV_R & cr->universal_access) + return true; /* read access to unverse */ + if (PRIV_R & source->access[cr->auth_token].effective) + return true; /* read access to original space */ + + uint32_t space_id = tuple_field_u32(tuple, 0); + struct space *space = space_cache_find(space_id); + uint8_t effective = space->access[cr->auth_token].effective; + return ((PRIV_R | PRIV_W) & (cr->universal_access | effective) || + space->def.uid == cr->uid); +} + +SysviewVspaceIndex::SysviewVspaceIndex(struct key_def *key_def) + : SysviewIndex(key_def, SC_SPACE_ID, key_def->iid, vspace_filter) +{ +} + +SysviewVindexIndex::SysviewVindexIndex(struct key_def *key_def) + : SysviewIndex(key_def, SC_INDEX_ID, key_def->iid, vspace_filter) +{ +} + +static bool +vuser_filter(struct space *source, struct tuple *tuple) +{ + struct credentials *cr = current_user(); + if (PRIV_R & cr->universal_access) + return true; /* read access to unverse */ + if (PRIV_R & source->access[cr->auth_token].effective) + return true; /* read access to original space */ + + uint32_t uid = tuple_field_u32(tuple, 0); + uint32_t owner_id = tuple_field_u32(tuple, 1); + return uid == cr->uid || owner_id == cr->uid; +} + +SysviewVuserIndex::SysviewVuserIndex(struct key_def *key_def) + : SysviewIndex(key_def, SC_USER_ID, key_def->iid, vuser_filter) +{ +} + +static bool +vpriv_filter(struct space *source, struct tuple *tuple) +{ + struct credentials *cr = current_user(); + if (PRIV_R & cr->universal_access) + return true; /* read access to unverse */ + if (PRIV_R & source->access[cr->auth_token].effective) + return true; /* read access to original space */ + + uint32_t grantor_id = tuple_field_u32(tuple, 0); + uint32_t grantee_id = tuple_field_u32(tuple, 1); + return grantor_id == cr->uid || grantee_id == cr->uid; +} + +SysviewVprivIndex::SysviewVprivIndex(struct key_def *key_def) + : SysviewIndex(key_def, SC_PRIV_ID, key_def->iid, vpriv_filter) +{ +} + +static bool +vfunc_filter(struct space *source, struct tuple *tuple) +{ + struct credentials *cr = current_user(); + if ((PRIV_R | PRIV_X) & cr->universal_access) + return true; /* read or execute access to unverse */ + if (PRIV_R & source->access[cr->auth_token].effective) + return true; /* read access to original space */ + + const char *name = tuple_field_cstr(tuple, 2); + uint32_t name_len = strlen(name); + struct func_def *func = func_by_name(name, name_len); + assert(func != NULL); + uint8_t effective = func->access[cr->auth_token].effective; + if (func->uid == cr->uid || (PRIV_X & effective)) + return true; + return false; +} + +SysviewVfuncIndex::SysviewVfuncIndex(struct key_def *key_def) + : SysviewIndex(key_def, SC_FUNC_ID, key_def->iid, vfunc_filter) +{ +} diff --git a/pool/shard006/C++/0078796_coneheadzombie.cpp b/pool/shard006/C++/0078796_coneheadzombie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24499d7f747a0e870714b7e8755b332403d4dfd7 --- /dev/null +++ b/pool/shard006/C++/0078796_coneheadzombie.cpp @@ -0,0 +1,124 @@ +#include "coneheadzombie.h" +#include "mainwindow.h" +#include "gameobject.h" +#include +#include + +ConeheadZombie::ConeheadZombie() //Default constructor +{ + width = 40; + height = 62; + life = 10; + armour = 18; + attack = 1; + rate = 0.5; + speed = 0.288; + speedIsSlower = false; + objectType = "ConeheadZombie"; + imageUrl = ":/images/cone-head-zombie.gif"; //File location of the cone head zombie + imageUrlWidth = 33; //Width of the image + imageUrlHeight = 61; //Height of the image + imageUrlAlt = ":/images/normal-zombie-gif"; //File location of the normal zombie + imageUrlAltWidth = 40; //Width of the image + imageUrlAltHeight = 62; //Height of the image + //Create a new label to show the zombie gif + gameObjectGif = new QLabel(); + //Create timer to attack based on zombie rate + multiUseTimer = new QTimer(); + //Set as single shot + multiUseTimer->setSingleShot(true); + //Don't start the timer + multiUseTimer->stop(); +} + +ConeheadZombie::~ConeheadZombie() //Destructor +{} + +void ConeheadZombie::setupGameObject() +{ + //Set the label to have a transparent background + gameObjectGif->setAttribute(Qt::WA_TranslucentBackground,true); + //Create a new qmovie with the zombie gif + QMovie *zombie_gif = new QMovie(imageUrl); + //Set the position and size of the zombie gif + gameObjectGif->setGeometry(this->scenePos().x()+5,this->scenePos().y()+5,imageUrlWidth,imageUrlHeight); + //Set the zombie gif to the label + gameObjectGif->setMovie(zombie_gif); + //Start the gif + gameObjectGif->movie()->start(); + //Add the label to the game scene + MainWindow::gameScene->addWidget(gameObjectGif); +} + +QRectF ConeheadZombie::boundingRect() const +{ + return QRectF(0,0,width,height); +} + +void ConeheadZombie::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + //Loop through all plant zombies + for (int i = 0; i < MainWindow::plantObjects.size(); i++) + { + //If the zombie collides with a plant + if (this->collidesWithItem(MainWindow::plantObjects.at(i)) && !multiUseTimer->isActive()) + { + //Stop the x velocity of the zombie + this->setXVelocity(0); + //Subtract health from plant object + MainWindow::plantObjects.at(i)->setLife(MainWindow::plantObjects.at(i)->getLife() - attack); + //Check life of plant + if (MainWindow::plantObjects.at(i)->getLife() <= 0) + { + this->setXVelocity(speed); + break; + } + //Set the X velocity + this->setXVelocity(0.5); + //Start the timer to attack the zombie + multiUseTimer->start(rate * 1000); + break; + } + } + //Check timer + if (multiUseTimer->isActive() && multiUseTimer->remainingTime() <= (rate / 2 * 1000)) + { + this->setXVelocity(-0.5); + } + //Set the position of the zombie gif to match the position of the game object + gameObjectGif->setGeometry(this->scenePos().x()+5,this->scenePos().y()+5,imageUrlWidth,imageUrlHeight); + //Check if the zombie armour is less than or equal to zero + if (this->getArmour() <= 0/*need something else here*/) + { + //Create a new qmovie with the zombie gif + QMovie *zombie_gif = new QMovie(imageUrlAlt); + //Set the position and size of the zombie gif + gameObjectGif->setGeometry(this->scenePos().x()+5,this->scenePos().y()+5,imageUrlAltWidth,imageUrlAltHeight); + //Set the zombie gif to the label + gameObjectGif->setMovie(zombie_gif); + //Start the gif + gameObjectGif->movie()->start(); + } + //Check if the zombies health is less than or equal to zero + if (this->getLife() <= 0) + { + //Delete the game label holding the gif + delete gameObjectGif; + gameObjectGif = 0; + //Remove the game object from the game scene + MainWindow::gameScene->removeItem(this); + //Remove the game object from the zombie list + for (int i = 0; i < MainWindow::zombieObjects.size(); i++) + { + if (this == MainWindow::zombieObjects.at(i)) + { + MainWindow::zombieObjects.removeAt(i); + break; + } + } + } + //Set the game object to be transparent + painter->setOpacity(0); + //Set the size of the game object + painter->drawRect(boundingRect()); +} diff --git a/pool/shard006/C++/0078799_copy_file.cpp b/pool/shard006/C++/0078799_copy_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92e4f22580f0b423567c81d74d1a4d8c20e084b2 --- /dev/null +++ b/pool/shard006/C++/0078799_copy_file.cpp @@ -0,0 +1,153 @@ +/*************************************************************** + * + * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, + * University of Wisconsin-Madison, WI. + * + * 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 "condor_common.h" +#include "condor_debug.h" + +int copy_file(const char *old_filename, const char *new_filename); +int hardlink_or_copy_file(const char *old_filename, const char *new_filename); + +int +copy_file(const char *old_filename, const char *new_filename) +{ +#if defined(WIN32) + // overwrite destination path + BOOL retval; + retval = CopyFile(old_filename, new_filename, FALSE); + + if (retval == 0) { + // failure + dprintf(D_ALWAYS, "CopyFile() failed with error=%li\n", + GetLastError()); + return -1; + } + else { return 0; } // success + +#else + int rc; + int num_bytes; + int in_fd = -1; + int out_fd = -1; + int new_file_created = 0; + char buff[1024]; + struct stat fs; + mode_t old_umask; + + old_umask = umask(0); + + rc = stat( old_filename, &fs ); + if ( rc < 0 ) { + dprintf( D_ALWAYS, "stat(%s) failed with errno %d\n", + old_filename, errno ); + goto copy_file_err; + } + fs.st_mode &= S_IRWXU | S_IRWXG | S_IRWXO; + + in_fd = safe_open_wrapper_follow( old_filename, O_RDONLY | O_LARGEFILE, 0644 ); + if ( in_fd < 0 ) { + dprintf( D_ALWAYS, "safe_open_wrapper(%s, O_RDONLY|O_LARGEFILE) failed with errno %d\n", + old_filename, errno ); + goto copy_file_err; + } + + out_fd = safe_open_wrapper_follow( new_filename, O_WRONLY | O_CREAT | O_TRUNC | O_LARGEFILE, fs.st_mode ); + if ( out_fd < 0 ) { + dprintf( D_ALWAYS, "safe_open_wrapper(%s, O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, %d) failed with errno %d\n", + new_filename, fs.st_mode, errno ); + goto copy_file_err; + } + + new_file_created = 1; + + errno = 0; + rc = read( in_fd, buff, sizeof(buff) ); + while ( rc > 0 ) { + num_bytes = rc; + rc = write( out_fd, buff, num_bytes ); + if ( rc < num_bytes ) { + dprintf( D_ALWAYS, "write(%d) to file %s return %d, errno %d\n", + num_bytes, new_filename, rc, errno ); + goto copy_file_err; + } + rc = read( in_fd, buff, sizeof(buff) ); + } + + if ( rc < 0 ) { + dprintf( D_ALWAYS, "read() from file %s failed with errno %d\n", + old_filename, errno ); + goto copy_file_err; + } + + close (in_fd); + close (out_fd); + + umask( old_umask ); + + return 0; + + copy_file_err: + if ( in_fd != -1 ) { + close( in_fd ); + } + if ( out_fd != -1 ) { + close( out_fd ); + } + if ( new_file_created ) { + unlink( new_filename ); + } + umask( old_umask ); + return -1; +#endif +} + +int +hardlink_or_copy_file(const char *old_filename, const char *new_filename) +{ +#if defined(WIN32) + /* There are no hardlinks under Windows, so just copy the file. */ + return copy_file(old_filename,new_filename); +#else + if(link(old_filename,new_filename) == -1) { + if(errno == EEXIST) { + //We definitely do not want to call copy_file() if the target + //file already exists, because the target might be a hard link + //to old_filename, and copy_file() will open and truncate it. + + if(remove(new_filename) == -1) { + dprintf(D_ALWAYS,"Failed to remove %s (errno %d), so cannot create hard link from %s\n",new_filename,errno,old_filename); + return -1; + } + if(link(old_filename,new_filename) == 0) { + return 0; + } + if(errno == EEXIST) { + dprintf(D_ALWAYS,"Removed %s, but hard linking from %s still fails with errno %d\n",new_filename,old_filename,errno); + return -1; + } + } + + // Hardlink may fail for a number of reasons, some of which + // can be solved by doing a plain old copy instead. No harm + // in trying. + return copy_file(old_filename,new_filename); + } + return 0; +#endif +} diff --git a/pool/shard006/C++/0078800_JsonRpcServer.cpp b/pool/shard006/C++/0078800_JsonRpcServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2deea603023001fc783ec73a2fb53dbbcc7b80b3 --- /dev/null +++ b/pool/shard006/C++/0078800_JsonRpcServer.cpp @@ -0,0 +1,177 @@ +// Copyright (c) 2011-2015 The Cryptonote developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "JsonRpcServer.h" + +#include +#include +#include +#include +#include +#include "HTTP/HttpParserErrorCodes.h" + +#include +#include +#include +#include +#include "HTTP/HttpParser.h" +#include "HTTP/HttpResponse.h" + +#include "Common/JsonValue.h" +#include "Serialization/JsonInputValueSerializer.h" +#include "Serialization/JsonOutputStreamSerializer.h" + +namespace CryptoNote { + +JsonRpcServer::JsonRpcServer(System::Dispatcher& sys, System::Event& stopEvent, Logging::ILogger& loggerGroup) : + HttpServer(sys, loggerGroup), + system(sys), + stopEvent(stopEvent), + logger(loggerGroup, "JsonRpcServer") +{ +} + +void JsonRpcServer::start(const std::string& bindAddress, uint16_t bindPort) { + HttpServer::start(bindAddress, bindPort); + stopEvent.wait(); + HttpServer::stop(); +} + +void JsonRpcServer::processRequest(const CryptoNote::HttpRequest& req, CryptoNote::HttpResponse& resp) { + try { + logger(Logging::TRACE) << "HTTP request came: \n" << req; + + if (req.getUrl() == "/json_rpc") { + std::istringstream jsonInputStream(req.getBody()); + Common::JsonValue jsonRpcRequest; + Common::JsonValue jsonRpcResponse(Common::JsonValue::OBJECT); + + try { + jsonInputStream >> jsonRpcRequest; + } catch (std::runtime_error&) { + logger(Logging::DEBUGGING) << "Couldn't parse request: \"" << req.getBody() << "\""; + makeJsonParsingErrorResponse(jsonRpcResponse); + resp.setStatus(CryptoNote::HttpResponse::STATUS_200); + resp.setBody(jsonRpcResponse.toString()); + return; + } + + processJsonRpcRequest(jsonRpcRequest, jsonRpcResponse); + + std::ostringstream jsonOutputStream; + jsonOutputStream << jsonRpcResponse; + + resp.setStatus(CryptoNote::HttpResponse::STATUS_200); + resp.setBody(jsonOutputStream.str()); + + } else { + logger(Logging::WARNING) << "Requested url \"" << req.getUrl() << "\" is not found"; + resp.setStatus(CryptoNote::HttpResponse::STATUS_404); + return; + } + } catch (std::exception& e) { + logger(Logging::WARNING) << "Error while processing http request: " << e.what(); + resp.setStatus(CryptoNote::HttpResponse::STATUS_500); + } +} + +void JsonRpcServer::prepareJsonResponse(const Common::JsonValue& req, Common::JsonValue& resp) { + using Common::JsonValue; + + if (req.contains("id")) { + resp.insert("id", req("id")); + } + + resp.insert("jsonrpc", "2.0"); +} + +void JsonRpcServer::makeErrorResponse(const std::error_code& ec, Common::JsonValue& resp) { + using Common::JsonValue; + + JsonValue error(JsonValue::OBJECT); + + JsonValue code; + code = static_cast(-32000); //Application specific error code + + JsonValue message; + message = ec.message(); + + JsonValue data(JsonValue::OBJECT); + JsonValue appCode; + appCode = static_cast(ec.value()); + data.insert("application_code", appCode); + + error.insert("code", code); + error.insert("message", message); + error.insert("data", data); + + resp.insert("error", error); +} + +void JsonRpcServer::makeGenericErrorReponse(Common::JsonValue& resp, const char* what, int errorCode) { + using Common::JsonValue; + + JsonValue error(JsonValue::OBJECT); + + JsonValue code; + code = static_cast(errorCode); + + std::string msg; + if (what) { + msg = what; + } else { + msg = "Unknown application error"; + } + + JsonValue message; + message = msg; + + error.insert("code", code); + error.insert("message", message); + + resp.insert("error", error); + +} + +void JsonRpcServer::makeMethodNotFoundResponse(Common::JsonValue& resp) { + using Common::JsonValue; + + JsonValue error(JsonValue::OBJECT); + + JsonValue code; + code = static_cast(-32601); //ambigous declaration of JsonValue::operator= (between int and JsonValue) + + JsonValue message; + message = "Method not found"; + + error.insert("code", code); + error.insert("message", message); + + resp.insert("error", error); +} + +void JsonRpcServer::fillJsonResponse(const Common::JsonValue& v, Common::JsonValue& resp) { + resp.insert("result", v); +} + +void JsonRpcServer::makeJsonParsingErrorResponse(Common::JsonValue& resp) { + using Common::JsonValue; + + resp = JsonValue(JsonValue::OBJECT); + resp.insert("jsonrpc", "2.0"); + resp.insert("id", nullptr); + + JsonValue error(JsonValue::OBJECT); + JsonValue code; + code = static_cast(-32700); //ambigous declaration of JsonValue::operator= (between int and JsonValue) + + JsonValue message = "Parse error"; + + error.insert("code", code); + error.insert("message", message); + + resp.insert("error", error); +} + +} diff --git a/pool/shard006/C++/0078803_VectorTest.cpp b/pool/shard006/C++/0078803_VectorTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..578166ab70fa72fc70eb8c540600b4976ac41a67 --- /dev/null +++ b/pool/shard006/C++/0078803_VectorTest.cpp @@ -0,0 +1,108 @@ +#include +#include +using namespace Aurora; + +void dumpVec4(const Vector4D& v) +{ + printf("v = (%f, %f, %f, %f)\n", v.getX(), v.getY(), v.getZ(), v.getW()); +} + +int main() +{ + /* + Vector2D v1(1.f, 2.f); + Vector2D v2(5.f); + Vector2D v3(0.f); + Real allOnes[] = { 1.f, 1.f }; + Real randomness[] = { 22.f, 33.f }; + + Vector2D v4(allOnes); + Vector2D v5(randomness); + Vector2D v6; + + Vector2D ang1(0.f, 10.f), ang2(1.f, 1.f); + ang1.normalize(); + ang2.normalize(); + + printf("len %f %f\n", ang1.getLength(), ang2.getLength()); + + printf("|v1| = %f, |v2] = %f, |v3| = %f,\n |v4| = %f, |v5| = %f, |v6| = %f\n", + v1.getLength(), v2.getLength(), v3.getLength(), v4.getLength(), v5.getLength(), v6.getLength()); + + printf("|v1|2 = %f, |v2]2 = %f, |v3|2 = %f,\n |v4|2 = %f, |v5|2 = %f, |v6|2 = %f\n", + v1.getLengthSquared(), v2.getLengthSquared(), v3.getLengthSquared(), v4.getLengthSquared(), v5.getLengthSquared(), v6.getLengthSquared()); + + v5.normalize(); + printf("v5 = (%f, %f)\n", v5.getX(), v5.getY()); + + printf("v1 to v2: %f\n", Real(Degree(ang1.getAngleTo(ang2)))); + + Vector2D t1(4.f, 7.f); + float l = t1.getLengthSquared(); + + printf("t1 l**2=%f l=%f rl=%f\n", l, Math::sqrt(l), t1.getLength()); + + t1.setX(20.f); + l = t1.getLength(); + printf("t1 l**2=%f rl**2=%f l=%f\n", t1.getLengthSquared(), l*l, l); + */ + /* + Vector3D v1(5.f, 0.f, 0.f); + Vector3D v2(0.f, 0.f, 12.f); + + Vector3D result = v2.crossProduct(v1); + printf("result = (%f, %f, %f)\n", result.getX(), result.getY(), result.getZ()); + + Vector3D a1(0.f, 1.f, 0.f), a2(0.f, 1.f, 1.f), a3(1.f, 0.f, 0.f); + printf("y to yz = %f, y to x = %f, x to yz = %f\n", + Real(Degree(a2.getAngleTo(a1))), + Real(Degree(a1.getAngleTo(a3))), + Real(Degree(a2.getAngleTo(a3))));*/ + + Vector4D op1(4.f, -5.f, 9.f, 2.f); + Vector4D op2(-9.f, 7.f, 4.f, 3.f); + + Vector4D res(op1+op2); + + float *a, *b, *c; + c = new float[4]; + a = new float[4]; + b = new float[4]; + + a[0] = 1.f; + a[1] = 2.f; + a[2] = 3.f; + a[3] = 4.f; + + b[0] = 4.f; + b[1] = 5.f; + b[2] = 6.f; + b[3] = 7.f; + + __asm + { + mov eax, a; + mov ebx, b; + + movups xmm0, [eax]; + movups xmm1, [ebx]; + addps xmm0, xmm1; + mov eax, c; + movups [eax], xmm0; + } + float fa = 1.f, fb = 3.f, fc; + fc=fa+fb; + printf("manual add %f %f %f %f\n", c[0],c[1],c[2],c[3]); + SSE::packedDivide(a,b,c); + printf("SSE::packedDivide %f %f %f %f\n", c[0],c[1],c[2],c[3]); + dumpVec4(res); + dumpVec4(op1+op2); + dumpVec4(op1-op2); + dumpVec4(op1*op2); + dumpVec4(op1/op2); + dumpVec4(op1*4); + dumpVec4(op2*-3); + + system("pause >nul"); + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0078808_mediaconstraintsinterface.cc b/pool/shard006/C++/0078808_mediaconstraintsinterface.cc new file mode 100644 index 0000000000000000000000000000000000000000..90a957cfa48c5f38013d50aed9dfc74367d3876e --- /dev/null +++ b/pool/shard006/C++/0078808_mediaconstraintsinterface.cc @@ -0,0 +1,275 @@ +/* + * Copyright 2013 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "api/mediaconstraintsinterface.h" + +#include "api/peerconnectioninterface.h" +#include "rtc_base/stringencode.h" + +namespace { + +// Find the highest-priority instance of the T-valued constraint named by +// |key| and return its value as |value|. |constraints| can be null. +// If |mandatory_constraints| is non-null, it is incremented if the key appears +// among the mandatory constraints. +// Returns true if the key was found and has a valid value for type T. +// If the key appears multiple times as an optional constraint, appearances +// after the first are ignored. +// Note: Because this uses FindFirst, repeated optional constraints whose +// first instance has an unrecognized value are not handled precisely in +// accordance with the specification. +template +bool FindConstraint(const webrtc::MediaConstraintsInterface* constraints, + const std::string& key, + T* value, + size_t* mandatory_constraints) { + std::string string_value; + if (!FindConstraint(constraints, key, &string_value, mandatory_constraints)) { + return false; + } + return rtc::FromString(string_value, value); +} + +// Specialization for std::string, since a string doesn't need conversion. +template <> +bool FindConstraint(const webrtc::MediaConstraintsInterface* constraints, + const std::string& key, + std::string* value, + size_t* mandatory_constraints) { + if (!constraints) { + return false; + } + if (constraints->GetMandatory().FindFirst(key, value)) { + if (mandatory_constraints) { + ++*mandatory_constraints; + } + return true; + } + if (constraints->GetOptional().FindFirst(key, value)) { + return true; + } + return false; +} + +// Converts a constraint (mandatory takes precedence over optional) to an +// rtc::Optional. +template +void ConstraintToOptional(const webrtc::MediaConstraintsInterface* constraints, + const std::string& key, + rtc::Optional* value_out) { + T value; + bool present = FindConstraint(constraints, key, &value, nullptr); + if (present) { + *value_out = value; + } +} +} // namespace + +namespace webrtc { + +const char MediaConstraintsInterface::kValueTrue[] = "true"; +const char MediaConstraintsInterface::kValueFalse[] = "false"; + +// Constraints declared as static members in mediastreaminterface.h +// Specified by draft-alvestrand-constraints-resolution-00b +const char MediaConstraintsInterface::kMinAspectRatio[] = "minAspectRatio"; +const char MediaConstraintsInterface::kMaxAspectRatio[] = "maxAspectRatio"; +const char MediaConstraintsInterface::kMaxWidth[] = "maxWidth"; +const char MediaConstraintsInterface::kMinWidth[] = "minWidth"; +const char MediaConstraintsInterface::kMaxHeight[] = "maxHeight"; +const char MediaConstraintsInterface::kMinHeight[] = "minHeight"; +const char MediaConstraintsInterface::kMaxFrameRate[] = "maxFrameRate"; +const char MediaConstraintsInterface::kMinFrameRate[] = "minFrameRate"; + +// Audio constraints. +const char MediaConstraintsInterface::kEchoCancellation[] = + "echoCancellation"; +const char MediaConstraintsInterface::kGoogEchoCancellation[] = + "googEchoCancellation"; +const char MediaConstraintsInterface::kExtendedFilterEchoCancellation[] = + "googEchoCancellation2"; +const char MediaConstraintsInterface::kDAEchoCancellation[] = + "googDAEchoCancellation"; +const char MediaConstraintsInterface::kAutoGainControl[] = + "googAutoGainControl"; +const char MediaConstraintsInterface::kExperimentalAutoGainControl[] = + "googAutoGainControl2"; +const char MediaConstraintsInterface::kNoiseSuppression[] = + "googNoiseSuppression"; +const char MediaConstraintsInterface::kExperimentalNoiseSuppression[] = + "googNoiseSuppression2"; +const char MediaConstraintsInterface::kIntelligibilityEnhancer[] = + "intelligibilityEnhancer"; +const char MediaConstraintsInterface::kLevelControl[] = "levelControl"; +const char MediaConstraintsInterface::kLevelControlInitialPeakLevelDBFS[] = + "levelControlInitialPeakLevelDBFS"; +const char MediaConstraintsInterface::kHighpassFilter[] = + "googHighpassFilter"; +const char MediaConstraintsInterface::kTypingNoiseDetection[] = + "googTypingNoiseDetection"; +const char MediaConstraintsInterface::kAudioMirroring[] = "googAudioMirroring"; +const char MediaConstraintsInterface::kAudioNetworkAdaptorConfig[] = + "googAudioNetworkAdaptorConfig"; + +// Google-specific constraint keys for a local video source (getUserMedia). +const char MediaConstraintsInterface::kNoiseReduction[] = "googNoiseReduction"; + +// Constraint keys for CreateOffer / CreateAnswer defined in W3C specification. +const char MediaConstraintsInterface::kOfferToReceiveAudio[] = + "OfferToReceiveAudio"; +const char MediaConstraintsInterface::kOfferToReceiveVideo[] = + "OfferToReceiveVideo"; +const char MediaConstraintsInterface::kVoiceActivityDetection[] = + "VoiceActivityDetection"; +const char MediaConstraintsInterface::kIceRestart[] = + "IceRestart"; +// Google specific constraint for BUNDLE enable/disable. +const char MediaConstraintsInterface::kUseRtpMux[] = + "googUseRtpMUX"; + +// Below constraints should be used during PeerConnection construction. +const char MediaConstraintsInterface::kEnableDtlsSrtp[] = + "DtlsSrtpKeyAgreement"; +const char MediaConstraintsInterface::kEnableRtpDataChannels[] = + "RtpDataChannels"; +// Google-specific constraint keys. +const char MediaConstraintsInterface::kEnableDscp[] = "googDscp"; +const char MediaConstraintsInterface::kEnableIPv6[] = "googIPv6"; +const char MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate[] = + "googSuspendBelowMinBitrate"; +const char MediaConstraintsInterface::kCombinedAudioVideoBwe[] = + "googCombinedAudioVideoBwe"; +const char MediaConstraintsInterface::kScreencastMinBitrate[] = + "googScreencastMinBitrate"; +// TODO(ronghuawu): Remove once cpu overuse detection is stable. +const char MediaConstraintsInterface::kCpuOveruseDetection[] = + "googCpuOveruseDetection"; +const char MediaConstraintsInterface::kPayloadPadding[] = "googPayloadPadding"; + + +// Set |value| to the value associated with the first appearance of |key|, or +// return false if |key| is not found. +bool MediaConstraintsInterface::Constraints::FindFirst( + const std::string& key, std::string* value) const { + for (Constraints::const_iterator iter = begin(); iter != end(); ++iter) { + if (iter->key == key) { + *value = iter->value; + return true; + } + } + return false; +} + +bool FindConstraint(const MediaConstraintsInterface* constraints, + const std::string& key, bool* value, + size_t* mandatory_constraints) { + return ::FindConstraint(constraints, key, value, mandatory_constraints); +} + +bool FindConstraint(const MediaConstraintsInterface* constraints, + const std::string& key, + int* value, + size_t* mandatory_constraints) { + return ::FindConstraint(constraints, key, value, mandatory_constraints); +} + +void CopyConstraintsIntoRtcConfiguration( + const MediaConstraintsInterface* constraints, + PeerConnectionInterface::RTCConfiguration* configuration) { + // Copy info from constraints into configuration, if present. + if (!constraints) { + return; + } + + bool enable_ipv6; + if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6, + &enable_ipv6, nullptr)) { + configuration->disable_ipv6 = !enable_ipv6; + } + FindConstraint(constraints, MediaConstraintsInterface::kEnableDscp, + &configuration->media_config.enable_dscp, nullptr); + FindConstraint( + constraints, MediaConstraintsInterface::kCpuOveruseDetection, + &configuration->media_config.video.enable_cpu_overuse_detection, nullptr); + FindConstraint(constraints, MediaConstraintsInterface::kEnableRtpDataChannels, + &configuration->enable_rtp_data_channel, nullptr); + // Find Suspend Below Min Bitrate constraint. + FindConstraint(constraints, + MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate, + &configuration->media_config.video.suspend_below_min_bitrate, + nullptr); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kScreencastMinBitrate, + &configuration->screencast_min_bitrate); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kCombinedAudioVideoBwe, + &configuration->combined_audio_video_bwe); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kEnableDtlsSrtp, + &configuration->enable_dtls_srtp); +} + +void CopyConstraintsIntoAudioOptions( + const MediaConstraintsInterface* constraints, + cricket::AudioOptions* options) { + if (!constraints) { + return; + } + + ConstraintToOptional(constraints, + MediaConstraintsInterface::kGoogEchoCancellation, + &options->echo_cancellation); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kExtendedFilterEchoCancellation, + &options->extended_filter_aec); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kDAEchoCancellation, + &options->delay_agnostic_aec); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kAutoGainControl, + &options->auto_gain_control); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kExperimentalAutoGainControl, + &options->experimental_agc); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kNoiseSuppression, + &options->noise_suppression); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kExperimentalNoiseSuppression, + &options->experimental_ns); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kIntelligibilityEnhancer, + &options->intelligibility_enhancer); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kLevelControl, + &options->level_control); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kHighpassFilter, + &options->highpass_filter); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kTypingNoiseDetection, + &options->typing_detection); + ConstraintToOptional(constraints, + MediaConstraintsInterface::kAudioMirroring, + &options->stereo_swapping); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kLevelControlInitialPeakLevelDBFS, + &options->level_control_initial_peak_level_dbfs); + ConstraintToOptional( + constraints, MediaConstraintsInterface::kAudioNetworkAdaptorConfig, + &options->audio_network_adaptor_config); + // When |kAudioNetworkAdaptorConfig| is defined, it both means that audio + // network adaptor is desired, and provides the config string. + if (options->audio_network_adaptor_config) { + options->audio_network_adaptor = true; + } +} + +} // namespace webrtc diff --git a/pool/shard006/C++/0078809_math_stubs_long_double.cc b/pool/shard006/C++/0078809_math_stubs_long_double.cc new file mode 100644 index 0000000000000000000000000000000000000000..98ca5417d00456b9b0ba042b89aa5f4c0892e882 --- /dev/null +++ b/pool/shard006/C++/0078809_math_stubs_long_double.cc @@ -0,0 +1,224 @@ +// Stub definitions for long double math. + +// Copyright (C) 2001-2013 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. + +// Under Section 7 of GPL version 3, you are granted additional +// permissions described in the GCC Runtime Library Exception, version +// 3.1, as published by the Free Software Foundation. + +// You should have received a copy of the GNU General Public License and +// a copy of the GCC Runtime Library Exception along with this program; +// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +// . + +#include + +// For targets which do not have support for long double versions, +// we use the following crude approximations. We keep saying that we'll do +// better later, but never do. + +extern "C" +{ +#ifndef _GLIBCXX_HAVE_FABSL + long double + fabsl(long double x) + { + return fabs((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_ACOSL + long double + acosl(long double x) + { + return acos((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_ASINL + long double + asinl(long double x) + { + return asin((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_ATANL + long double + atanl(long double x) + { + return atan ((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_ATAN2L + long double + atan2l(long double x, long double y) + { + return atan2((double) x, (double) y); + } +#endif + +#ifndef _GLIBCXX_HAVE_CEILL + long double + ceill(long double x) + { + return ceil((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_COSL + long double + cosl(long double x) + { + return cos((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_COSHL + long double + coshl(long double x) + { + return cosh((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_EXPL + long double + expl(long double x) + { + return exp((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_FLOORL + long double + floorl(long double x) + { + return floor((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_FMODL + long double + fmodl(long double x, long double y) + { + return fmod((double) x, (double) y); + } +#endif + +#ifndef _GLIBCXX_HAVE_FREXPL + long double + frexpl(long double x, int *exp) + { + return frexp((double) x, exp); + } +#endif + +#ifndef _GLIBCXX_HAVE_SQRTL + long double + sqrtl(long double x) + { + return sqrt((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_HYPOTL + long double + hypotl(long double x, long double y) + { + long double s = fabsl(x) + fabsl(y); + if (s == 0.0L) + return s; + x /= s; y /= s; + return s * sqrtl(x * x + y * y); + } +#endif + +#ifndef _GLIBCXX_HAVE_LDEXPL + long double + ldexpl(long double x, int exp) + { + return ldexp((double) x, exp); + } +#endif + +#ifndef _GLIBCXX_HAVE_LOGL + long double + logl(long double x) + { + return log((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_LOG10L + long double + log10l(long double x) + { + return log10((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_MODFL + long double + modfl(long double x, long double *iptr) + { + double result, temp; + + result = modf((double) x, &temp); + *iptr = temp; + return result; + } +#endif + +#ifndef _GLIBCXX_HAVE_POWL + long double + powl(long double x, long double y) + { + return pow((double) x, (double) y); + } +#endif + +#ifndef _GLIBCXX_HAVE_SINL + long double + sinl(long double x) + { + return sin((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_SINHL + long double + sinhl(long double x) + { + return sinh((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_TANL + long double + tanl(long double x) + { + return tan((double) x); + } +#endif + +#ifndef _GLIBCXX_HAVE_TANHL + long double + tanhl(long double x) + { + return tanh((double) x); + } +#endif +} // extern "C" diff --git a/pool/shard006/C++/0078818_Odometer.cpp b/pool/shard006/C++/0078818_Odometer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53be3f612443ce67a0c0937ec6e441818c67b0af --- /dev/null +++ b/pool/shard006/C++/0078818_Odometer.cpp @@ -0,0 +1,75 @@ +#include "Odometer.h" + +volatile int Odometer::leftInt; +volatile int Odometer::rightInt; +volatile unsigned long Odometer::rightTime; +volatile unsigned long Odometer::leftTime; +volatile double Odometer::leftAngularVelocity; +volatile double Odometer::rightAngularVelocity; +volatile int16_t Odometer::encValRight; +volatile int16_t Odometer::encValLeft; +int8_t Odometer::lookup_table[16]; +SpeedControl* Odometer::theSpeedCtl; + + +Odometer::Odometer(int leftInterruptPinA, int leftInterruptPinB, int rightInterruptPinA, int rightInterruptPinB) : +leftInterruptPinA(leftInterruptPinA), +leftInterruptPinB(leftInterruptPinB), +rightInterruptPinA(rightInterruptPinA), +rightInterruptPinB(rightInterruptPinB) { } + +void Odometer::leftISR() { + Odometer::encoderISR(&leftTime, leftInt, encValLeft, encMaskLeft, leftAngularVelocity, 5); +} + +void Odometer::rightISR() { + Odometer::encoderISR(&rightTime, rightInt, encValRight, encMaskRight, rightAngularVelocity, 5); +} + +void Odometer::encoderISR( + volatile unsigned long* time, + volatile int& interrupts, + volatile int16_t& encVal, + int16_t encMask, + volatile double& angularVelocity, + int interruptThreshold) { + + if (*time == 0) { + *time = millis(); + } + + encVal = encVal << 2; + encVal = encVal | ((PIND & encMask) >> ( encMask == encMaskLeft ? 0 : 2)); //Left encoder doesn't need right-shift + + interrupts = interrupts + lookup_table[encVal & 0b1111]; + + if (interrupts % interruptThreshold == 0) { + *time = millis() - *time; + angularVelocity = (((float)interruptThreshold / 920.0f) * TWO_PI) / (*time / 1000.0); + *time = millis(); + theSpeedCtl->updatePID(); + } + +} + +void Odometer::enable() { + Odometer::leftInt = 0; + Odometer::rightInt = 0; + Odometer::leftTime = 0; + Odometer::rightTime = 0; + Odometer::encValRight = 0; + Odometer::encValLeft = 0; + attachInterrupt(digitalPinToInterrupt(leftInterruptPinA), &Odometer::leftISR, CHANGE); + attachInterrupt(digitalPinToInterrupt(leftInterruptPinB), &Odometer::leftISR, CHANGE); + attachInterrupt(digitalPinToInterrupt(rightInterruptPinA), &Odometer::rightISR, CHANGE); + attachInterrupt(digitalPinToInterrupt(rightInterruptPinB), &Odometer::rightISR, CHANGE); +} + +void Odometer::disable() { + detachInterrupt(digitalPinToInterrupt(leftInterruptPinA)); + detachInterrupt(digitalPinToInterrupt(leftInterruptPinB)); + detachInterrupt(digitalPinToInterrupt(rightInterruptPinA)); + detachInterrupt(digitalPinToInterrupt(rightInterruptPinB)); +} + + diff --git a/pool/shard006/C++/0078825_remove_freed.cc b/pool/shard006/C++/0078825_remove_freed.cc new file mode 100644 index 0000000000000000000000000000000000000000..a6f5a76244154b99987ccf87dc3385ed25697893 --- /dev/null +++ b/pool/shard006/C++/0078825_remove_freed.cc @@ -0,0 +1,94 @@ +// { dg-options "-std=gnu++11" } + +// 2010-08-11 Paolo Carlini +// +// Copyright (C) 2010-2015 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 + +// 23.3.3.5 forward_list operations [forwardlist.ops] + +// Used to cause many Valgrind errors: LWG 526-type situation. +void test01() +{ + bool test __attribute__((unused)) = true; + + std::forward_list fl1; + + fl1.push_front(1); + fl1.push_front(2); + fl1.push_front(3); + fl1.push_front(4); + fl1.push_front(1); + + fl1.remove(*fl1.begin()); + + VERIFY( std::distance(fl1.begin(), fl1.end()) == 3 ); + + auto it1 = fl1.begin(); + + VERIFY( *it1 == 4 ); + ++it1; + VERIFY( *it1 == 3 ); + ++it1; + VERIFY( *it1 == 2 ); + + std::forward_list fl2; + + fl2.push_front(3); + fl2.push_front(3); + fl2.push_front(3); + fl2.push_front(3); + fl2.push_front(3); + + auto it2 = fl2.begin(); + ++it2; + ++it2; + + fl2.remove(*it2); + + VERIFY( std::distance(fl2.begin(), fl2.end()) == 0 ); + + std::forward_list fl3; + + fl3.push_front(1); + fl3.push_front(2); + fl3.push_front(3); + fl3.push_front(3); + fl3.push_front(3); + + auto it3 = fl3.begin(); + ++it3; + ++it3; + + fl3.remove(*it3); + + VERIFY( std::distance(fl3.begin(), fl3.end()) == 2 ); + + it3 = fl3.begin(); + VERIFY( *it3 == 2 ); + ++it3; + VERIFY( *it3 == 1 ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard006/C++/0078833_BitStream.cpp b/pool/shard006/C++/0078833_BitStream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee76915248bca2abf5e5752506a34572c5d8f24f --- /dev/null +++ b/pool/shard006/C++/0078833_BitStream.cpp @@ -0,0 +1,110 @@ +#include "BitStream.h" +#include + +inline void BitOutStream::put() +{ + if(nBits == MAX_BITS) + { + exit->putByte(bits); + nBits=0; + } +} + +void BitOutStream::putBit1() +{ + bits <<= 1; + bits |= 1; + ++nBits; + put(); +#ifdef _DEBUG + printf("1,"); +#endif +} + +void BitOutStream::putBit0() +{ + bits <<= 1; + ++nBits; + put(); +#ifdef _DEBUG + printf("0,"); +#endif +} + +void BitOutStream::putBits(unsigned val, size_t len) +{ +#ifdef _DEBUG + printf("%d,", val); + if (len == 8) + printf("(%c)\n", val); +#endif + assert(exit); + + if(len < MAX_BITS-nBits) + { + bits <<= len; + bits |= val; + nBits += len; + return; + } + if(nBits > 0) + { + size_t rest = MAX_BITS - nBits; + bits <<= rest; + bits |= (val >> (len-rest)); + exit->putByte(bits); + len -= rest; + } + + for(; len >= MAX_BITS ; len-=MAX_BITS) + exit->putByte(val >> (len-MAX_BITS)); + + nBits = len; + bits = (Bits)val; +} + +void BitOutStream::close() +{ + assert(exit); + + if(nBits>0) + exit->putByte(bits << (MAX_BITS-nBits)); + + exit->close(); +} + +bool BitInStream::getBit() +{ + assert(entry); + + if(nBits == 0) + { + nBits = MAX_BITS; + int c = entry->getByte(); + + assert(c != EOF); + + bits = (Bits)c; + } + + bool res = (bits & 0x80) != 0; + bits <<= 1; + --nBits; + + return res; +} + +unsigned BitInStream::getBits(size_t len) +{ + assert(entry); + // Esta implementação pode ser optimizada + unsigned res = 0; + for(; len>0 ; --len) + { + res <<= 1; + if(getBit()) + res |= 1; + } + + return res; +} \ No newline at end of file diff --git a/pool/shard006/C++/0078835_KoShapeMoveCommand.cpp b/pool/shard006/C++/0078835_KoShapeMoveCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b040271db49c7adb90176219703797e293c3142 --- /dev/null +++ b/pool/shard006/C++/0078835_KoShapeMoveCommand.cpp @@ -0,0 +1,75 @@ +/* This file is part of the KDE project + * Copyright (C) 2006 Thomas Zander + * Copyright (C) 2006 Jan Hambrecht + * + * 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 "KoShapeMoveCommand.h" + +#include +#include + +class KoShapeMoveCommand::Private +{ +public: + QList shapes; + QList previousPositions, newPositions; +}; + +KoShapeMoveCommand::KoShapeMoveCommand(const QList &shapes, QList &previousPositions, QList &newPositions, KUndo2Command *parent) + : KUndo2Command(parent), + d(new Private()) +{ + d->shapes = shapes; + d->previousPositions = previousPositions; + d->newPositions = newPositions; + Q_ASSERT(d->shapes.count() == d->previousPositions.count()); + Q_ASSERT(d->shapes.count() == d->newPositions.count()); + + setText(kundo2_i18n("Move shapes")); +} + +KoShapeMoveCommand::~KoShapeMoveCommand() +{ + delete d; +} + +void KoShapeMoveCommand::redo() +{ + KUndo2Command::redo(); + for (int i = 0; i < d->shapes.count(); i++) { + d->shapes.at(i)->update(); + d->shapes.at(i)->setPosition(d->newPositions.at(i)); + d->shapes.at(i)->update(); + } +} + +void KoShapeMoveCommand::undo() +{ + KUndo2Command::undo(); + for (int i = 0; i < d->shapes.count(); i++) { + d->shapes.at(i)->update(); + d->shapes.at(i)->setPosition(d->previousPositions.at(i)); + d->shapes.at(i)->update(); + } +} + +/// update newPositions list with new postions. +void KoShapeMoveCommand::setNewPositions(QList newPositions) +{ + d->newPositions = newPositions; +} diff --git a/pool/shard006/C++/0078841_qtlocalpeer.cpp b/pool/shard006/C++/0078841_qtlocalpeer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccd975a71575851b773d8ac06510137337781ee4 --- /dev/null +++ b/pool/shard006/C++/0078841_qtlocalpeer.cpp @@ -0,0 +1,178 @@ +/**************************************************************************** +** +** 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 "qtlocalpeer.h" + +#include +#include +#include + +#if defined(Q_OS_WIN) +#include +#include +typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); +static PProcessIdToSessionId pProcessIdToSessionId = 0; +#endif + +#if defined(Q_OS_UNIX) +#include +#include +#endif + +namespace SharedTools { + +static const char ack[] = "ack"; + +QString QtLocalPeer::appSessionId(const QString &appId) +{ + QByteArray idc = appId.toUtf8(); + quint16 idNum = qChecksum(idc.constData(), idc.size()); + //### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best. + + QString res = QLatin1String("qtsingleapplication-") + + QString::number(idNum, 16); +#if defined(Q_OS_WIN) + if (!pProcessIdToSessionId) { + QLibrary lib(QLatin1String("kernel32")); + pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); + } + if (pProcessIdToSessionId) { + DWORD sessionId = 0; + pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + res += QLatin1Char('-') + QString::number(sessionId, 16); + } +#else + res += QLatin1Char('-') + QString::number(::getuid(), 16); +#endif + return res; +} + +QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId) + : QObject(parent), id(appId) +{ + if (id.isEmpty()) + id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win + + socketName = appSessionId(id); + server = new QLocalServer(this); + QString lockName = QDir(QDir::tempPath()).absolutePath() + + QLatin1Char('/') + socketName + + QLatin1String("-lockfile"); + lockFile.setFileName(lockName); + lockFile.open(QIODevice::ReadWrite); +} + +bool QtLocalPeer::isClient() +{ + if (lockFile.isLocked()) + return false; + + if (!lockFile.lock(QtLockedFile::WriteLock, false)) + return true; + + if (!QLocalServer::removeServer(socketName)) + qWarning("QtSingleCoreApplication: could not cleanup socket"); + bool res = server->listen(socketName); + if (!res) + qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); + QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); + return false; +} + +bool QtLocalPeer::sendMessage(const QString &message, int timeout, bool block) +{ + if (!isClient()) + return false; + + QLocalSocket socket; + bool connOk = false; + for (int i = 0; i < 2; i++) { + // Try twice, in case the other instance is just starting up + socket.connectToServer(socketName); + connOk = socket.waitForConnected(timeout/2); + if (connOk || i) + break; + int ms = 250; +#if defined(Q_OS_WIN) + Sleep(DWORD(ms)); +#else + struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; + nanosleep(&ts, NULL); +#endif + } + if (!connOk) + return false; + + QByteArray uMsg(message.toUtf8()); + QDataStream ds(&socket); + ds.writeBytes(uMsg.constData(), uMsg.size()); + bool res = socket.waitForBytesWritten(timeout); + res &= socket.waitForReadyRead(timeout); // wait for ack + res &= (socket.read(qstrlen(ack)) == ack); + if (block) // block until peer disconnects + socket.waitForDisconnected(-1); + return res; +} + +void QtLocalPeer::receiveConnection() +{ + QLocalSocket* socket = server->nextPendingConnection(); + if (!socket) + return; + + // Why doesn't Qt have a blocking stream that takes care of this shait??? + while (socket->bytesAvailable() < static_cast(sizeof(quint32))) { + if (!socket->isValid()) // stale request + return; + socket->waitForReadyRead(1000); + } + QDataStream ds(socket); + QByteArray uMsg; + quint32 remaining; + ds >> remaining; + uMsg.resize(remaining); + int got = 0; + char* uMsgBuf = uMsg.data(); + //qDebug() << "RCV: remaining" << remaining; + do { + got = ds.readRawData(uMsgBuf, remaining); + remaining -= got; + uMsgBuf += got; + //qDebug() << "RCV: got" << got << "remaining" << remaining; + } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); + //### error check: got<0 + if (got < 0) { + qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString(); + delete socket; + return; + } + // ### async this + QString message = QString::fromUtf8(uMsg.constData(), uMsg.size()); + socket->write(ack, qstrlen(ack)); + socket->waitForBytesWritten(1000); + emit messageReceived(message, socket); // ##(might take a long time to return) +} + +} // namespace SharedTools diff --git a/pool/shard006/C++/0078849_gtstparameterschat.cpp b/pool/shard006/C++/0078849_gtstparameterschat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d994158988ec4e9d6c38c87751e821518fa1024 --- /dev/null +++ b/pool/shard006/C++/0078849_gtstparameterschat.cpp @@ -0,0 +1,81 @@ +//--------------------------------------------------------------------------- +/* +GTST, Game Theory Server +Copyright (C) 2011-2015 Richel Bilderbeek + +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 . +*/ +//--------------------------------------------------------------------------- +//From http://www.richelbilderbeek.nl/ProjectGtst.htm +//--------------------------------------------------------------------------- +#include +#include +#include + +#include "gtstparameterschat.h" + +ribi::gtst::ParametersChat::ParametersChat() + : m_duration(5) +{ + +} + +int ribi::gtst::ParametersChat::GetDuration() const +{ + assert(m_duration >= 0); + return m_duration; +} + +void ribi::gtst::ParametersChat::SetDuration(const int time) +{ + m_duration = time; + assert(m_duration >= 0); +} + +///Parse a line +void ribi::gtst::ParametersChat::Parse(const std::string& s) +{ + //Chat time + if (s.size() > 9 && s.substr(0,9) == "duration=") + { + const std::string t = s.substr(9,s.size()-9); + try + { + std::stoi(t); + //std::stoi(t); + } + catch (std::exception&) + { + throw std::runtime_error("chat_duration must be an integer"); + } + const int time = std::stoi(t); + //const int time = std::stoi(t); + if (time < 0) throw std::runtime_error("chat_duration must be zero or posive"); + SetDuration(time); + return; + } +} + +std::ostream& ribi::gtst::operator<<(std::ostream& os,const ParametersChat& parameters) +{ + os + << "" + << "" + << parameters.GetDuration() + << "" + << ""; + + return os; +} + + diff --git a/pool/shard006/C++/0078854_HdfsTest.cpp b/pool/shard006/C++/0078854_HdfsTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ec789454979a985b8aa118367b908ff324eb0df --- /dev/null +++ b/pool/shard006/C++/0078854_HdfsTest.cpp @@ -0,0 +1,141 @@ +/* + * This file is part of Hootenanny. + * + * Hootenanny 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 . + * + * -------------------------------------------------------------------- + * + * The following copyright notices are generated automatically. If you + * have a new notice to add, please use the format: + * " * @copyright Copyright ..." + * This will properly maintain the copyright information. DigitalGlobe + * copyrights will be updated automatically. + * + * @copyright Copyright (C) 2012, 2013, 2014 DigitalGlobe (http://www.digitalglobe.com/) + */ + +// CPP Unit +#include +#include +#include +#include + +// Hoot +#include +using namespace pp; + +// Standard +#include +#include + +class HdfsTest : public CppUnit::TestFixture +{ + CPPUNIT_TEST_SUITE(HdfsTest); + CPPUNIT_TEST(testWrite); + CPPUNIT_TEST(testReadAll); + CPPUNIT_TEST(testReadSeek); + CPPUNIT_TEST_SUITE_END(); + +public: + + const static int count = 1000000; + + void testWrite() + { + Hdfs hdfs("default", 0); + + if (hdfs.exists("sequence.txt")) + { + hdfs.remove("sequence.txt"); + } + + auto_ptr osPtr(hdfs.create("sequence.txt")); + ostream& os = *osPtr; + + char buf[12]; + for (int i = 0; i < count; i++) + { + snprintf(buf, 12, "%8d\n", i); + os << buf; + } + os.flush(); + + CPPUNIT_ASSERT_EQUAL(true, hdfs.exists("sequence.txt")); + } + + void testReadAll() + { + Hdfs hdfs("default", 0); + + auto_ptr isPtr(hdfs.open("sequence.txt")); + istream& is = *isPtr; + + string bufIn, bufExpected; + bufIn.resize(12); + bufExpected.resize(12); + for (int i = 0; i < 12; i++) + { + bufIn[i] = 0; + } + for (int i = 0; i < count; i++) + { + snprintf((char*)bufExpected.data(), 12, "%8d\n", i); + is.read((char*)bufIn.data(), 9); + CPPUNIT_ASSERT_EQUAL(9l, is.gcount()); + CPPUNIT_ASSERT_EQUAL(false, is.eof()); + CPPUNIT_ASSERT_EQUAL(bufExpected, bufIn); + } + + // attempt to read again, this should cause us to hit the EOF. + is.read((char*)bufIn.data(), 1); + CPPUNIT_ASSERT_EQUAL(0l, is.gcount()); + CPPUNIT_ASSERT_EQUAL(true, is.eof()); + } + + void testReadSeek() + { + Hdfs hdfs("default", 0); + + auto_ptr isPtr(hdfs.open("sequence.txt")); + istream& is = *isPtr; + + is.seekg(0, ios_base::end); + CPPUNIT_ASSERT_EQUAL(count * 9, (int)is.tellg()); + is.seekg(0, ios_base::beg); + CPPUNIT_ASSERT_EQUAL(0, (int)is.tellg()); + + string bufIn, bufExpected; + bufIn.resize(12); + bufExpected.resize(12); + for (int i = 0; i < 12; i++) + { + bufIn[i] = 0; + } + + for (int i = 0; i < 1000; i++) + { + int l = rand() % count; + snprintf((char*)bufExpected.data(), 12, "%8d\n", l); + is.seekg(l * 9, ios_base::beg); + CPPUNIT_ASSERT_EQUAL(l * 9, (int)is.tellg()); + is.read((char*)bufIn.data(), 9); + CPPUNIT_ASSERT_EQUAL(9l, is.gcount()); + CPPUNIT_ASSERT_EQUAL(false, is.eof()); + CPPUNIT_ASSERT_EQUAL(bufExpected, bufIn); + } + } +}; + +CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(HdfsTest, "slow"); + diff --git a/pool/shard006/C++/0078865_merge_add.cpp b/pool/shard006/C++/0078865_merge_add.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8a88c37edd75cb5053d357bf2899b876225260a --- /dev/null +++ b/pool/shard006/C++/0078865_merge_add.cpp @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2015-2018 Skymind, Inc. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ******************************************************************************/ + +// +// Created by raver119 on 24.11.17. +// + +#include +#if NOT_EXCLUDED(OP_mergeadd) + +#include +#include + +namespace nd4j { +namespace ops { + +OP_IMPL(mergeadd, -1, 1, false) { + + REQUIRE_OK(this->validateInputDimensionsMatch(block)); + + auto output = OUTPUT_VARIABLE(0); + + std::vector inArrs(block.width()); + + for(int i = 0; i < block.width(); ++i) + inArrs[i] = INPUT_VARIABLE(i); + + helpers::mergeAdd(block.launchContext(), inArrs, *output); + + return Status::OK(); +} + +DECLARE_SYN(mergesum, mergeadd); +DECLARE_SYN(add_n, mergeadd); +DECLARE_SYN(addn, mergeadd); +DECLARE_SYN(accumulaten, mergeadd); +DECLARE_SYN(accumulate_n, mergeadd); + + DECLARE_TYPES(mergeadd) { + getOpDescriptor() + ->setAllowedInputTypes(nd4j::DataType::ANY) + ->setAllowedOutputTypes(nd4j::DataType::ANY); + } +} +} + +#endif \ No newline at end of file diff --git a/pool/shard006/C++/0078867_VariableDeclAST.cpp b/pool/shard006/C++/0078867_VariableDeclAST.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18241b03a3351fc3418e2ee8c3b65299935ebd34 --- /dev/null +++ b/pool/shard006/C++/0078867_VariableDeclAST.cpp @@ -0,0 +1,89 @@ +#include "VariableDeclAST.h" + +namespace swing +{ + DeclAST::DeclPtr VariableDeclAST::Create(TokenIter& iter) + { + /// TODO : Struct를 만들 때 Struct에 해당하는 변수여야 하니까 이거 처리해야함. + /// TODO : 현재 콘텍스트가 전역인지 로컬인지 Struct안인지 알아야 한다. + + /// 전역이면 GlobalVariable. + auto* ast = new VariableDeclAST(); + + std::string name; + llvm::Type* type = nullptr; + std::string typeName = ""; + bool optional = false; + + if (iter->Is(TokenID::Type_Var)) + { + ++iter; + iter->Expect(TokenID::Identifier); + name = iter++->_name; + + /// 타입을 명시적으로 선언한 경우, + if (iter->Is(TokenID::Colon)) + { + ++iter; + typeName = iter++->_name; + //type = g_SwingCompiler->GetType(typeName); + + if (iter->Is(TokenID::Optional_Nilable)) + optional = true; + + if (iter->Is(TokenID::Assignment)) + { + ++iter; + ast->_initValue = ExprAST::CreateTopLevelExpr(iter); + //if (type != ast->_initValue->GetType()) + // throw ParsingError(*iter, "VariableDeclAST error, expression type is different from the specified type."); + } + } + /// 타입 추론이 필요한 경우, + else + { + iter++->Expect(TokenID::Assignment); + ast->_initValue = ExprAST::CreateTopLevelExpr(iter); + type = ast->_initValue->GetType(); + } + + ast->_variable = new Variable(typeName, name, false, false, optional); + } + //else if (iter->Is(TokenID::Type_Let)) + //{ + // if (type == nullptr) + // g_SwingCompiler->_globalTable.AddVariable(new Variable(type, name, true, false, optional)); + // else + // g_SwingCompiler->_globalTable.AddVariable(new Variable(typeName, name, true, false, optional)); + //} + else + throw ParsingError(*iter, "Unexpected Token, VariableDeclAST, expect var or let."); + + return DeclPtr(ast); + } + + llvm::Value* VariableDeclAST::CodeGen() + { + g_SwingCompiler->_globalTable.AddVariable(_variable); + + if (_variable->_type == nullptr && _initValue != nullptr) + { + _variable->_type = _initValue->GetType(); + _variable->_isIncompleteType = false; + } + + /// Alloca 수행. + _variable->CreateAlloca(); + + /// 초기값이 있으면 초기값을 할당. (Store) + if (_initValue != nullptr) + { + if (_variable->_type != _initValue->GetType()) + throw Error("VariableDeclAST error, expression type is different from the specified type."); + + g_Builder.CreateStore(_initValue->CodeGen(), _variable->_value); + } + + return nullptr; + } +} diff --git a/pool/shard006/C++/0078870_GPU_Engine.measurement.cpp b/pool/shard006/C++/0078870_GPU_Engine.measurement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ac8ef6417ff91686c01810ba68d8ae1d22fc8cd --- /dev/null +++ b/pool/shard006/C++/0078870_GPU_Engine.measurement.cpp @@ -0,0 +1,110 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// INCLUDE: +/////////////////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////// +// Header: +#include "GPU_Engine.cuh" + +/////////// + + + + + + +/////////////////////////////////////////////////////////////////////////////////////////////// +// NAMESPACE: +/////////////////////////////////////////////////////////////////////////////////////////////// +using std::cout; +using std::left; +using std::right; +using std::endl; + +using std::ofstream; +using std::ios_base; +/////////// + + + + + + +/////////////////////////////////////////////////////////////////////////////////////////////// +// CLASS: +/////////////////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////// +// Psi: +bool GPU_Engine::get_success() { + return THIS(success); +} + +/////////////////////////////////// +// Psi: + +Cplx* GPU_Engine::get_hostPsi() { + Cplx* h_ptr = new Cplx[ THIS(get_psiSize()) ]; + ERRCHK_CUDA_F(cudaMemcpy(h_ptr, THIS(d_psi), THIS(get_psiSizeInBytes()), cudaMemcpyDeviceToHost), &THIS(success)); + + /////////////////////////////////// + RETURN h_ptr; +} + +size_t GPU_Engine::get_psiSize() { + return THIS(grid).nx * THIS(grid).ny * THIS(grid).nz; +} + +size_t GPU_Engine::get_psiSizeInBytes() { + return THIS(get_psiSize()) * sizeof(Cplx); +} + +/////////////////////////////////// +// Data output / input: + +void GPU_Engine::save_psi() { + Cplx* h_ptr = MY_NULLPTR; + h_ptr = THIS(get_hostPsi()); + + /////////////////////////////////// + if (h_ptr != MY_NULLPTR){ +# define WIDTH_Q 5 +# define SAVE_SEPARATOR //<< " :" + + ofstream outPutFile("psi.txt", ios_base::out); + outPutFile.width(WIDTH_Q); + outPutFile << right << THIS(grid).nx SAVE_SEPARATOR; + outPutFile.width(WIDTH_Q); + outPutFile << right << THIS(grid).ny SAVE_SEPARATOR; + outPutFile.width(WIDTH_Q); + outPutFile << right << THIS(grid).nz SAVE_SEPARATOR << endl << endl; + + size_t idx = 0; + for (int z = 0; z < THIS(grid).nz; z++) { + for (int y = 0; y < THIS(grid).ny; y++) { + for (int x = 0; x < THIS(grid).nx; x++) { + idx = THIS(grid).ny * THIS(grid).nx * z + THIS(grid).nx * y + x; + + outPutFile.width(WIDTH_Q); + outPutFile << right << x SAVE_SEPARATOR; + outPutFile.width(WIDTH_Q); + outPutFile << right << y SAVE_SEPARATOR; + outPutFile.width(WIDTH_Q); + outPutFile << right << z SAVE_SEPARATOR; + + outPutFile.width(WIDTH_Q + 3); + outPutFile << right << h_ptr[idx].x SAVE_SEPARATOR; + outPutFile.width(WIDTH_Q + 3); + outPutFile << right << h_ptr[idx].y SAVE_SEPARATOR << endl; + } + } + } + +# undef SAVE_SEP +# undef WIDTH_Q + outPutFile.close(); + } + + /////////////////////////////////// + delete[] h_ptr; +} \ No newline at end of file diff --git a/pool/shard006/C++/0078872_MockTxPacket.cpp b/pool/shard006/C++/0078872_MockTxPacket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab4f0282703a4cb02fd60e092a5c8abb60ac5eb5 --- /dev/null +++ b/pool/shard006/C++/0078872_MockTxPacket.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2004-present, 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 "fboss/agent/hw/mock/MockTxPacket.h" + +#include + +#include "fboss/agent/packet/EthHdr.h" + +using folly::IOBuf; + +namespace facebook { namespace fboss { + +MockTxPacket::MockTxPacket(uint32_t size) { + buf_ = IOBuf::create(size); + buf_->append(size); +} + +std::unique_ptr MockTxPacket::clone() const { + auto ret = std::make_unique(buf_->capacity()); + ret->buf()->clear(); + ret->buf()->advance(EthHdr::SIZE); + memcpy( + ret->buf()->writableData(), + buf_->data(), + buf_->length()); + ret->buf()->append(buf_->length()); + + return ret; +} + +}} // facebook::fboss diff --git a/pool/shard006/C++/0078882_settings_api_bubble_helper_views.cc b/pool/shard006/C++/0078882_settings_api_bubble_helper_views.cc new file mode 100644 index 0000000000000000000000000000000000000000..341dc6124bff781ab9d1861ac6e3c582ef118f0b --- /dev/null +++ b/pool/shard006/C++/0078882_settings_api_bubble_helper_views.cc @@ -0,0 +1,127 @@ +// Copyright (c) 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/ui/views/settings_api_bubble_helper_views.h" + +#include "chrome/browser/extensions/ntp_overridden_bubble_controller.h" +#include "chrome/browser/extensions/settings_api_bubble_controller.h" +#include "chrome/browser/extensions/settings_api_helpers.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/views/extensions/extension_message_bubble_view.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/settings_api_bubble_helper_views.h" +#include "chrome/browser/ui/views/toolbar/home_button.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "chrome/browser/ui/views/toolbar/wrench_toolbar_button.h" +#include "chrome/common/extensions/manifest_handlers/settings_overrides_handler.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/browser_url_handler.h" +#include "content/public/browser/navigation_entry.h" + +namespace extensions { + +namespace { + +void ShowSettingsApiBubble(SettingsApiOverrideType type, + const std::string& extension_id, + Profile* profile, + views::View* anchor_view, + views::BubbleBorder::Arrow arrow) { + scoped_ptr settings_api_bubble( + new SettingsApiBubbleController(profile, type)); + if (!settings_api_bubble->ShouldShow(extension_id)) + return; + + SettingsApiBubbleController* controller = settings_api_bubble.get(); + ExtensionMessageBubbleView* bubble_delegate = new ExtensionMessageBubbleView( + anchor_view, arrow, settings_api_bubble.Pass()); + views::BubbleDelegateView::CreateBubble(bubble_delegate); + controller->Show(bubble_delegate); +} + +} // namespace + +void MaybeShowExtensionControlledHomeNotification(Browser* browser) { +#if !defined(OS_WIN) + return; +#endif + + const Extension* extension = + GetExtensionOverridingHomepage(browser->profile()); + if (extension) { + // The bubble will try to anchor itself against the home button + views::View* anchor_view = BrowserView::GetBrowserViewForBrowser(browser)-> + toolbar()->home_button(); + ShowSettingsApiBubble(BUBBLE_TYPE_HOME_PAGE, + extension->id(), + browser->profile(), + anchor_view, + views::BubbleBorder::TOP_LEFT); + } +} + +void MaybeShowExtensionControlledSearchNotification( + Profile* profile, + content::WebContents* web_contents, + const AutocompleteMatch& match) { +#if !defined(OS_WIN) + return; +#endif + + if (AutocompleteMatch::IsSearchType(match.type) && + match.type != AutocompleteMatchType::SEARCH_OTHER_ENGINE) { + const Extension* extension = GetExtensionOverridingSearchEngine(profile); + if (extension) { + ToolbarView* toolbar = + BrowserView::GetBrowserViewForBrowser( + chrome::FindBrowserWithWebContents(web_contents))->toolbar(); + ShowSettingsApiBubble(BUBBLE_TYPE_SEARCH_ENGINE, + extension->id(), + profile, + toolbar->app_menu(), + views::BubbleBorder::TOP_RIGHT); + } + } +} + +void MaybeShowExtensionControlledNewTabPage( + Browser* browser, content::WebContents* web_contents) { +#if !defined(OS_WIN) + return; +#endif + + content::NavigationEntry* entry = + web_contents->GetController().GetActiveEntry(); + if (!entry) + return; + GURL active_url = entry->GetURL(); + if (!active_url.SchemeIs("chrome-extension")) + return; // Not a URL that we care about. + + // See if the current active URL matches a transformed NewTab URL. + GURL ntp_url(chrome::kChromeUINewTabURL); + bool ignored_param; + content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary( + &ntp_url, + web_contents->GetBrowserContext(), + &ignored_param); + if (ntp_url != active_url) + return; // Not being overridden by an extension. + + scoped_ptr ntp_overridden_bubble( + new NtpOverriddenBubbleController(browser->profile())); + if (!ntp_overridden_bubble->ShouldShow(ntp_url.host())) + return; + + NtpOverriddenBubbleController* controller = ntp_overridden_bubble.get(); + ExtensionMessageBubbleView* bubble_delegate = new ExtensionMessageBubbleView( + BrowserView::GetBrowserViewForBrowser(browser)->toolbar()->app_menu(), + views::BubbleBorder::TOP_RIGHT, + ntp_overridden_bubble.Pass()); + views::BubbleDelegateView::CreateBubble(bubble_delegate); + controller->Show(bubble_delegate); +} + +} // namespace extensions diff --git a/pool/shard006/C++/0078891_Merge_Intervals.cpp b/pool/shard006/C++/0078891_Merge_Intervals.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62c006e47f1352027cdcdb5857aafee4e80aea13 --- /dev/null +++ b/pool/shard006/C++/0078891_Merge_Intervals.cpp @@ -0,0 +1,33 @@ +bool cmp(Interval a,Interval b){ + return a.start ans; + vector merge(vector &intervals) { + int len=intervals.size(); + if(len<=1) return intervals; + Interval tmp; + bool f=false; + sort(intervals.begin(),intervals.end(),cmp); + for(int i=0;i tmp.end ){ + ans.push_back(tmp); + f=false; + i--; + } + else{ + tmp.end=(tmp.end>intervals[i].end?tmp.end:intervals[i].end); + } + } + } + ans.push_back(tmp); + return ans; + } +}; \ No newline at end of file diff --git a/pool/shard006/C++/0078895_sendcoinsentry.cpp b/pool/shard006/C++/0078895_sendcoinsentry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2473fa8e4d6742a0939d60c76858b2f0c74ded61 --- /dev/null +++ b/pool/shard006/C++/0078895_sendcoinsentry.cpp @@ -0,0 +1,172 @@ +#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 +#include + +SendCoinsEntry::SendCoinsEntry(QWidget *parent) : + QFrame(parent), + ui(new Ui::SendCoinsEntry), + model(0) +{ + ui->setupUi(this); + +#ifdef Q_WS_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 shoecoin address (they start with an 'm')")); +#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())); + + 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(); + + 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/shard006/C++/0078898_GetAccountSummaryResult.cpp b/pool/shard006/C++/0078898_GetAccountSummaryResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d175f53f5c71ef93c261ff091d02be24bb83b4c --- /dev/null +++ b/pool/shard006/C++/0078898_GetAccountSummaryResult.cpp @@ -0,0 +1,72 @@ +/* +* 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::IAM::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +GetAccountSummaryResult::GetAccountSummaryResult() +{ +} + +GetAccountSummaryResult::GetAccountSummaryResult(const AmazonWebServiceResult& result) +{ + *this = result; +} + +GetAccountSummaryResult& GetAccountSummaryResult::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "GetAccountSummaryResult") + { + resultNode = rootNode.FirstChild("GetAccountSummaryResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode summaryMapNode = resultNode.FirstChild("SummaryMap"); + + if(!summaryMapNode.IsNull()) + { + XmlNode summaryMapEntry = summaryMapNode.FirstChild("entry"); + while(!summaryMapEntry.IsNull()) + { + XmlNode keyNode = summaryMapEntry.FirstChild("key"); + XmlNode valueNode = summaryMapEntry.FirstChild("value"); + m_summaryMap[SummaryKeyTypeMapper::GetSummaryKeyTypeForName(StringUtils::Trim(keyNode.GetText().c_str()))] = + StringUtils::ConvertToInt32(StringUtils::Trim(valueNode.GetText().c_str()).c_str()); + summaryMapEntry = summaryMapEntry.NextNode("entry"); + } + + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::IAM::Model::GetAccountSummaryResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard006/C++/0078904_bitcoin.cpp b/pool/shard006/C++/0078904_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b79d81db40db61014e8df5230350dd1020a30fb8 --- /dev/null +++ b/pool/shard006/C++/0078904_bitcoin.cpp @@ -0,0 +1,275 @@ +/* + * W.J. van der Laan 2011-2012 + */ +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "messagemodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "intro.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. GlassCoin 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); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + app.setOrganizationName("GlassCoin"); + //XXX app.setOrganizationDomain(""); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + app.setApplicationName("GlassCoin-Qt-testnet"); + else + app.setApplicationName("GlassCoin-Qt"); + + // 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); + + // Command-line options take precedence: + ParseParameters(argc, argv); + + // User language is set up: pick a data directory + Intro::pickDataDirectory(); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + QMessageBox::critical(0, "GlassCoin", + QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // ... then GUI settings: + OptionsModel optionsModel; + + // 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(). + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + MessageModel messageModel(pwalletMain, &walletModel); + + window.setClientModel(&clientModel); + window.setWalletModel(&walletModel); + window.setMessageModel(&messageModel); + + // 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); + window.setMessageModel(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/shard006/C++/0078909_thread.cpp b/pool/shard006/C++/0078909_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae94a2d4c540d723f97d24e1927940d0dd625f0a --- /dev/null +++ b/pool/shard006/C++/0078909_thread.cpp @@ -0,0 +1,156 @@ +#include "generateMoves.hpp" +#include "search.hpp" +#include "thread.hpp" +#include "usi.hpp" + +using namespace Search; + +ThreadPool Threads; // Global object + +Thread::Thread() { + + resetCalls = exit = false; + maxPly = callsCnt = 0; + history.clear(); + counterMoves.clear(); + idx = Threads.size(); // Start from 0 + + std::unique_lock lk(mutex); + searching = true; + nativeThread = std::thread(&Thread::idle_loop, this); + sleepCondition.wait(lk, [&] { return !searching; }); +} + + +/// Thread destructor waits for thread termination before returning + +Thread::~Thread() { + + mutex.lock(); + exit = true; + sleepCondition.notify_one(); + mutex.unlock(); + nativeThread.join(); +} + + +/// Thread::wait_for_search_finished() waits on sleep condition +/// until not searching + +void Thread::wait_for_search_finished() { + + std::unique_lock lk(mutex); + sleepCondition.wait(lk, [&] { return !searching; }); +} + + +/// Thread::wait() waits on sleep condition until condition is true + +void Thread::wait(std::atomic_bool& condition) { + + std::unique_lock lk(mutex); + sleepCondition.wait(lk, [&] { return bool(condition); }); +} + + +/// Thread::start_searching() wakes up the thread that will start the search + +void Thread::start_searching(bool resume) { + + std::unique_lock lk(mutex); + + if (!resume) + searching = true; + + sleepCondition.notify_one(); +} + +void Thread::idle_loop() { + + while (!exit) + { + std::unique_lock lk(mutex); + + searching = false; + + while (!searching && !exit) + { + sleepCondition.notify_one(); // Wake up any waiting thread + sleepCondition.wait(lk); + } + + lk.unlock(); + + if (!exit) + search(); + } +} + +void ThreadPool::init() { + push_back(new MainThread); + readUSIOptions(); +} + +void ThreadPool::exit() { + while (size()) + delete back(), pop_back(); +} + +void ThreadPool::readUSIOptions() { + const size_t requested = Options["Threads"]; + + assert(0 < requested); + + while (size() < requested) + push_back(new Thread); + + while (requested < size()) { + delete back(), pop_back(); + } +} + +int64_t ThreadPool::nodes_searched() { + + int64_t nodes = 0; + for (Thread* th : *this) + nodes += th->rootPos.nodesSearched(); + return nodes; +} + +void ThreadPool::startThinking(const Position& pos, const Search::LimitsType& limits, + const std::vector& searchMoves) +{ +#if defined LEARN +#else + main()->wait_for_search_finished(); +#endif + + Search::Signals.stopOnPonderhit = Search::Signals.stop = false; + Search::Limits = limits; + + main()->rootMoves.clear(); + main()->rootPos = pos; + +#if defined LEARN + // searchMoves を直接使う。 + RootMoves.push_back(RootMove(searchMoves[0])); +#else + const MoveType MT = Legal; + for (MoveList ml(pos); !ml.end(); ++ml) { + if (searchMoves.empty() + || std::find(searchMoves.begin(), searchMoves.end(), ml.move()) != searchMoves.end()) + { + main()->rootMoves.push_back(RootMove(ml.move())); + } + } +#endif + +#if defined LEARN + // 浅い探索なので、thread 生成、破棄のコストが高い。余分な thread を生成せずに直接探索を呼び出す。 + Search::think(); +#else + + main()->start_searching(); +#endif +} + diff --git a/pool/shard006/C++/0078912_dict0stats_bg.cc b/pool/shard006/C++/0078912_dict0stats_bg.cc new file mode 100644 index 0000000000000000000000000000000000000000..6f01c37977651cd43f31ae6657d12d25f49c0c6d --- /dev/null +++ b/pool/shard006/C++/0078912_dict0stats_bg.cc @@ -0,0 +1,367 @@ +/***************************************************************************** + +Copyright (c) 2012, 2016, Oracle and/or its affiliates. All Rights Reserved. + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License 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, Suite 500, Boston, MA 02110-1335 USA + +*****************************************************************************/ + +/**************************************************//** +@file dict/dict0stats_bg.cc +Code used for background table and index stats gathering. + +Created Apr 25, 2012 Vasil Dimov +*******************************************************/ + +#include "row0mysql.h" +#include "srv0start.h" +#include "dict0stats.h" +#include "dict0stats_bg.h" + +#ifdef UNIV_NONINL +# include "dict0stats_bg.ic" +#endif + +#include + +/** Minimum time interval between stats recalc for a given table */ +#define MIN_RECALC_INTERVAL 10 /* seconds */ + +#define SHUTTING_DOWN() (srv_shutdown_state != SRV_SHUTDOWN_NONE) + +/** Event to wake up the stats thread */ +UNIV_INTERN os_event_t dict_stats_event = NULL; + +/** This mutex protects the "recalc_pool" variable. */ +static ib_mutex_t recalc_pool_mutex; +#ifdef HAVE_PSI_INTERFACE +static mysql_pfs_key_t recalc_pool_mutex_key; +#endif /* HAVE_PSI_INTERFACE */ + +/** The number of tables that can be added to "recalc_pool" before +it is enlarged */ +static const ulint RECALC_POOL_INITIAL_SLOTS = 128; + +/** The multitude of tables whose stats are to be automatically +recalculated - an STL vector */ +typedef std::vector recalc_pool_t; +static recalc_pool_t recalc_pool; + +typedef recalc_pool_t::iterator recalc_pool_iterator_t; + +/*****************************************************************//** +Initialize the recalc pool, called once during thread initialization. */ +static +void +dict_stats_recalc_pool_init() +/*=========================*/ +{ + ut_ad(!srv_read_only_mode); + + recalc_pool.reserve(RECALC_POOL_INITIAL_SLOTS); +} + +/*****************************************************************//** +Free the resources occupied by the recalc pool, called once during +thread de-initialization. */ +static +void +dict_stats_recalc_pool_deinit() +/*===========================*/ +{ + ut_ad(!srv_read_only_mode); + + recalc_pool.clear(); +} + +/*****************************************************************//** +Add a table to the recalc pool, which is processed by the +background stats gathering thread. Only the table id is added to the +list, so the table can be closed after being enqueued and it will be +opened when needed. If the table does not exist later (has been DROPped), +then it will be removed from the pool and skipped. */ +UNIV_INTERN +void +dict_stats_recalc_pool_add( +/*=======================*/ + const dict_table_t* table) /*!< in: table to add */ +{ + ut_ad(!srv_read_only_mode); + + mutex_enter(&recalc_pool_mutex); + + /* quit if already in the list */ + for (recalc_pool_iterator_t iter = recalc_pool.begin(); + iter != recalc_pool.end(); + ++iter) { + + if (*iter == table->id) { + mutex_exit(&recalc_pool_mutex); + return; + } + } + + recalc_pool.push_back(table->id); + + mutex_exit(&recalc_pool_mutex); + + os_event_set(dict_stats_event); +} + +/*****************************************************************//** +Get a table from the auto recalc pool. The returned table id is removed +from the pool. +@return true if the pool was non-empty and "id" was set, false otherwise */ +static +bool +dict_stats_recalc_pool_get( +/*=======================*/ + table_id_t* id) /*!< out: table id, or unmodified if list is + empty */ +{ + ut_ad(!srv_read_only_mode); + + mutex_enter(&recalc_pool_mutex); + + if (recalc_pool.empty()) { + mutex_exit(&recalc_pool_mutex); + return(false); + } + + *id = recalc_pool[0]; + + recalc_pool.erase(recalc_pool.begin()); + + mutex_exit(&recalc_pool_mutex); + + return(true); +} + +/*****************************************************************//** +Delete a given table from the auto recalc pool. +dict_stats_recalc_pool_del() */ +UNIV_INTERN +void +dict_stats_recalc_pool_del( +/*=======================*/ + const dict_table_t* table) /*!< in: table to remove */ +{ + ut_ad(!srv_read_only_mode); + ut_ad(mutex_own(&dict_sys->mutex)); + + mutex_enter(&recalc_pool_mutex); + + ut_ad(table->id > 0); + + for (recalc_pool_iterator_t iter = recalc_pool.begin(); + iter != recalc_pool.end(); + ++iter) { + + if (*iter == table->id) { + /* erase() invalidates the iterator */ + recalc_pool.erase(iter); + break; + } + } + + mutex_exit(&recalc_pool_mutex); +} + +/*****************************************************************//** +Wait until background stats thread has stopped using the specified table. +The caller must have locked the data dictionary using +row_mysql_lock_data_dictionary() and this function may unlock it temporarily +and restore the lock before it exits. +The background stats thread is guaranteed not to start using the specified +table after this function returns and before the caller unlocks the data +dictionary because it sets the BG_STAT_IN_PROGRESS bit in table->stats_bg_flag +under dict_sys->mutex. */ +UNIV_INTERN +void +dict_stats_wait_bg_to_stop_using_table( +/*===================================*/ + dict_table_t* table, /*!< in/out: table */ + trx_t* trx) /*!< in/out: transaction to use for + unlocking/locking the data dict */ +{ + while (!dict_stats_stop_bg(table)) { + DICT_STATS_BG_YIELD(trx); + } +} + +/*****************************************************************//** +Initialize global variables needed for the operation of dict_stats_thread() +Must be called before dict_stats_thread() is started. */ +UNIV_INTERN +void +dict_stats_thread_init() +/*====================*/ +{ + ut_a(!srv_read_only_mode); + + dict_stats_event = os_event_create(); + + /* The recalc_pool_mutex is acquired from: + 1) the background stats gathering thread before any other latch + and released without latching anything else in between (thus + any level would do here) + 2) from row_update_statistics_if_needed() + and released without latching anything else in between. We know + that dict_sys->mutex (SYNC_DICT) is not acquired when + row_update_statistics_if_needed() is called and it may be acquired + inside that function (thus a level <=SYNC_DICT would do). + 3) from row_drop_table_for_mysql() after dict_sys->mutex (SYNC_DICT) + and dict_operation_lock (SYNC_DICT_OPERATION) have been locked + (thus a level mutex); + + table = dict_table_open_on_id(table_id, TRUE, DICT_TABLE_OP_NORMAL); + + if (table == NULL) { + /* table does not exist, must have been DROPped + after its id was enqueued */ + mutex_exit(&dict_sys->mutex); + return; + } + + /* Check whether table is corrupted */ + if (table->corrupted) { + dict_table_close(table, TRUE, FALSE); + mutex_exit(&dict_sys->mutex); + return; + } + + table->stats_bg_flag = BG_STAT_IN_PROGRESS; + + mutex_exit(&dict_sys->mutex); + + /* ut_time() could be expensive, the current function + is called once every time a table has been changed more than 10% and + on a system with lots of small tables, this could become hot. If we + find out that this is a problem, then the check below could eventually + be replaced with something else, though a time interval is the natural + approach. */ + + if (ut_difftime(ut_time(), table->stats_last_recalc) + < MIN_RECALC_INTERVAL) { + + /* Stats were (re)calculated not long ago. To avoid + too frequent stats updates we put back the table on + the auto recalc list and do nothing. */ + + dict_stats_recalc_pool_add(table); + + } else { + + dict_stats_update(table, DICT_STATS_RECALC_PERSISTENT); + } + + mutex_enter(&dict_sys->mutex); + + table->stats_bg_flag = BG_STAT_NONE; + + dict_table_close(table, TRUE, FALSE); + + mutex_exit(&dict_sys->mutex); +} + +/*****************************************************************//** +This is the thread for background stats gathering. It pops tables, from +the auto recalc list and proceeds them, eventually recalculating their +statistics. +@return this function does not return, it calls os_thread_exit() */ +extern "C" UNIV_INTERN +os_thread_ret_t +DECLARE_THREAD(dict_stats_thread)( +/*==============================*/ + void* arg MY_ATTRIBUTE((unused))) /*!< in: a dummy parameter + required by os_thread_create */ +{ + ut_a(!srv_read_only_mode); + + srv_dict_stats_thread_active = TRUE; + + while (!SHUTTING_DOWN()) { + + /* Wake up periodically even if not signaled. This is + because we may lose an event - if the below call to + dict_stats_process_entry_from_recalc_pool() puts the entry back + in the list, the os_event_set() will be lost by the subsequent + os_event_reset(). */ + os_event_wait_time( + dict_stats_event, MIN_RECALC_INTERVAL * 1000000); + + if (SHUTTING_DOWN()) { + break; + } + + dict_stats_process_entry_from_recalc_pool(); + + os_event_reset(dict_stats_event); + } + + srv_dict_stats_thread_active = FALSE; + + /* We count the number of threads in os_thread_exit(). A created + thread should always use that to exit instead of return(). */ + os_thread_exit(NULL); + + OS_THREAD_DUMMY_RETURN; +} diff --git a/pool/shard006/C++/0078913_Console.cpp b/pool/shard006/C++/0078913_Console.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97b8befcdc19e8f975ae414ca34f1c8ce774e928 --- /dev/null +++ b/pool/shard006/C++/0078913_Console.cpp @@ -0,0 +1,47 @@ +#include "Console.h" + +//-------------------------------------------------------------------------------------- + +#include + +//////////////////////////////////////////////////////////////////////////////////////// + +NL::Scene::Objects::Console::Console() +{ + lines.clear(); +}; + +NL::Scene::Objects::Console::~Console() +{ + +}; + +void NL::Scene::Objects::Console::Initialize() +{ + /*CEGUI::Window* Console = CEGUI::WindowManager::getSingleton().loadWindowLayout("Data/GUI/layouts/Console.layout"); + Console->setVisible(false); + + CEGUI::WindowManager::getSingleton().getWindow("Root")->addChildWindow(Console); + + CEGUI::WindowManager::getSingleton().getWindow("List")->setText((CEGUI::utf8 *)"");*/ +}; + +/*NL::String &NL::Scene::Objects::Console::operator [] (size_t n) +{ + // Проверка на выход за границы! + return lines[n]; +};*/ + +bool NL::Scene::Objects::Console::Update(float fElapsedTime) +{ + String res = ""; + + for (int i = (int)lines.size()-1; i >= 0; i--) + { + res += lines[i] + "\n"; + } + + CEGUI::WindowManager::getSingleton().getWindow("List")->setText((CEGUI::utf8 *)res.c_str()); + + return true; +}; \ No newline at end of file diff --git a/pool/shard006/C++/0078916_CQIllustratorCreateTextMode.cpp b/pool/shard006/C++/0078916_CQIllustratorCreateTextMode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d9f390f7fbe1bcfd204c706365aa15b679e0b0c --- /dev/null +++ b/pool/shard006/C++/0078916_CQIllustratorCreateTextMode.cpp @@ -0,0 +1,286 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +CQIllustratorCreateTextMode:: +CQIllustratorCreateTextMode(CQIllustrator *illustrator) : + CQIllustratorMode(illustrator, (uint) CQIllustrator::Mode::TEXT), text_("Hello") +{ + setCursor(text_bits, textmask_bits, 2, 2); +} + +CQIllustratorCreateTextToolbar * +CQIllustratorCreateTextMode:: +createToolbar() +{ + toolbar_ = new CQIllustratorCreateTextToolbar(this); + + return toolbar_; +} + +CQIllustratorCreateTextSizer * +CQIllustratorCreateTextMode:: +createSizer() +{ + sizer_ = new CQIllustratorCreateTextSizer(this); + + return sizer_; +} + +CQMenuItem * +CQIllustratorCreateTextMode:: +createMenuItem(CQMenu *menu) +{ + QIcon icon = CQPixmapCacheInst->getIcon("TEXT"); + + menuItem_ = new CQMenuItem(menu, icon, "&Text", CQMenuItem::CHECKABLE); + + menuItem_->setStatusTip("Create Text"); + + connect(menuItem_->getAction(), SIGNAL(toggled(bool)), this, SLOT(menuItemSlot())); + + return menuItem_; +} + +void +CQIllustratorCreateTextMode:: +handleMouseRelease(const MouseEvent &e) +{ + CPoint2D p2 = CQUtil::fromQPoint(e.window); + + if (dragging_) { + if (! moving_) { + selectControlPoint(e); + } + // dragging finished so commit + else { + illustrator_->getSandbox()->commit(CQIllustratorData::ChangeType::GEOMETRY); + } + } + // not dragging so do a select + else { + CPoint2D p1 = CQUtil::fromQPoint(press_wpos_); + + // point click - select at point + if (! moving_) { + (void) illustrator_->selectAt(p2, e.event->isControlKey(), e.event->isShiftKey()); + } + // drag then create text using specified bbox + else { + CBBox2D bbox(p1, p2); + + if (e.event->isShiftKey()) { + double w = bbox.getWidth (); + double h = bbox.getHeight(); + + if (w > h) + bbox.setHeight(w); + else + bbox.setWidth(h); + } + + CQIllustratorTextShape *text = + illustrator_->createTextShape(bbox.getLL(), bbox.getUR(), text_.toStdString()); + + CQIllustratorShapeStroke stroke; + CQIllustratorShapeFill fill; + + stroke.setOpacity(0.0); + fill .setColor (CRGBA(0,0,0)); + + text->setStroke(stroke); + text->setFill (fill); + + text->setFont(CQFontUtil::fromQFont(toolbar_->getFont())); + + illustrator_->addShape(text); + + illustrator_->setSelectShape(text); + } + } + + dragging_ = false; + + illustrator_->redraw(); +} + +void +CQIllustratorCreateTextMode:: +handleMouseDrag(const MouseEvent &e) +{ + if (dragging_) { + CQIllustratorShape *shape = illustrator_->getSandbox()->frontShape(); + + sizer_->updatePoint(shape, e.window); + } + else { + CPoint2D p1 = CQUtil::fromQPoint(press_wpos_); + CPoint2D p2 = CQUtil::fromQPoint(curr_wpos_); + + CBBox2D bbox(p1, p2); + + equalSize_ = e.event->isShiftKey(); + + if (equalSize_) { + double w = bbox.getWidth (); + double h = bbox.getHeight(); + + if (w > h) + bbox.setHeight(w); + else + bbox.setWidth(h); + } + + toolbar_->setSize(bbox); + } + + illustrator_->redrawOverlay(); +} + +bool +CQIllustratorCreateTextMode:: +handleKeyPress(const KeyEvent &e) +{ + CQIllustratorSelectedShapes *selection = illustrator_->getSelection(); + + if (selection->size() != 1) return false; + + const CQIllustratorSelectedShape &sshape = selection->front(); + + const CQIllustratorShape *shape = sshape.getShape(); + + const auto *text = dynamic_cast(shape); + + if (! text) return false; + + std::string str = text->getText(); + std::string str1 = str; + + CKeyType key = e.event->getType(); + + if (key >= CKEY_TYPE_Space && key <= CKEY_TYPE_AsciiTilde) { + str1 += (char) key; + } + else if (key == CKEY_TYPE_Return) { + str1 += '\n'; + } + else if (key == CKEY_TYPE_BackSpace) { + if (str1 != "") + str1 = str1.substr(0, str1.size() - 1); + } + else + return CQIllustratorMode::handleKeyPress(e); + + if (str != str1) { + auto *text1 = const_cast(text); + + illustrator_->checkoutShape(text1, CQIllustratorData::ChangeType::GEOMETRY); + + text1->setText(str1); + + illustrator_->checkinShape(text1, CQIllustratorData::ChangeType::GEOMETRY); + } + + return true; +} + +void +CQIllustratorCreateTextMode:: +drawOverlay(CQIllustratorShapeDrawer *drawer) +{ + QPainter *painter = drawer->getPainter(); + + if (! dragging_) { + // draw creation rubber band + if (pressed_) { + QPointF current_wpos = illustrator_->getITransform().map(QPointF(curr_ppos_)); + + QPen pen; + + pen.setColor(QColor(0,0,0)); + pen.setStyle(Qt::DashLine); + pen.setWidth(0); + + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + + painter->drawRect(QRectF(press_wpos_, current_wpos)); + } + + //------ + + // draw handles for single selected shape + CQIllustratorSelectedShapes *selection = illustrator_->getSelection(); + + if (selection->size() == 1) { + const CQIllustratorSelectedShape &sshape = selection->front(); + + const CQIllustratorShape *shape = sshape.getShape(); + + sizer_->draw(painter, shape); + + sizer_->drawSelectionHandles(painter, sshape); + } + } + else { + CQIllustratorShape *shape = illustrator_->getSandbox()->frontShape(); + + sizer_->draw(painter, shape); + } +} + +void +CQIllustratorCreateTextMode:: +setText(const QString &text) +{ + text_ = text; +} + +//------ + +CQIllustratorCreateTextSizer:: +CQIllustratorCreateTextSizer(CQIllustratorCreateTextMode *mode) : + CQIllustratorModeSizer(mode) +{ + CQIllustrator *illustrator = mode_->getIllustrator(); + + ll_handle_ = new CQIllustratorControlPointHandle(illustrator); + ur_handle_ = new CQIllustratorControlPointHandle(illustrator); + + addHandle(ll_handle_); + addHandle(ur_handle_); +} + +void +CQIllustratorCreateTextSizer:: +drawHandles(QPainter *painter, const CQIllustratorShape *shape) +{ + const auto *text = dynamic_cast(shape); + + if (text) { + CQIllustratorShape::ControlPointList controlPoints; + + text->getControlPoints(controlPoints); + + ll_handle_->draw(text, controlPoints[0], painter); + ur_handle_->draw(text, controlPoints[1], painter); + } +} diff --git a/pool/shard006/C++/0078919_seedpointgenerator.cpp b/pool/shard006/C++/0078919_seedpointgenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23e31f893f59fd8751cd93d9b6bf5908c65c73d3 --- /dev/null +++ b/pool/shard006/C++/0078919_seedpointgenerator.cpp @@ -0,0 +1,224 @@ +/********************************************************************************* + * + * Inviwo - Interactive Visualization Workshop + * + * Copyright (c) 2015-2021 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 + +#include +#include + +#define RND 1 +#define PLANE 2 +#define LINE 3 +#define SPHERE 4 + +namespace inviwo { + +// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme +const ProcessorInfo SeedPointGenerator::processorInfo_{ + "org.inviwo.SeedPointGenerator3D", // Class identifier + "Seed Point Generator 3D", // Display name + "Data Creation", // Category + CodeState::Stable, // Code state + "CPU, Seed Points, Generator", // Tags +}; +const ProcessorInfo SeedPointGenerator::getProcessorInfo() const { return processorInfo_; } + +SeedPointGenerator::SeedPointGenerator() + : Processor() + , seedPoints_("seedPoints") + , lineGroup_("line", "Line") + , planeGroup_("plane", "Plane") + , sphereGroup_("sphere", "Sphere") + , numberOfPoints_("numberOfPoints", "Number of Points", 10, 1, 1000) + , planeResolution_("planeResolution", "Resolution", vec2(4, 4), vec2(2, 2), vec2(100, 100)) + , planeOrigin_("planeOrigin_", "Origin", vec3(0.0f, 0.0f, 0.5f), vec3(-1, -1, -1), + vec3(1, 1, 1)) + , planeE1_("planeP1_", "Offset 1", vec3(1.0f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) + , planeE2_("planeP2_", "Offset 2", vec3(0.0f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) + , sphereCenter_("sphereCenter", "Center", vec3(0.5f, 0.5f, 0.5f), vec3(0, 0, 0), vec3(1, 1, 1)) + , sphereRadius_("sphereRadius", "Radius") + , lineStart_("lineStart", "Start", vec3(0.5f, 0.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) + , lineEnd_("lineEnd_", "End", vec3(0.5f, 1.0f, 0.5f), vec3(-1, -1, -1), vec3(1, 1, 1)) + , generator_("generator", "Generator") + , randomness_("randomness", "Randomness") + , useSameSeed_("useSameSeed", "Use same seed", true) + , seed_("seed", "Seed", 1, 0, 1000) + , rd_() + , mt_(rd_()) { + addPort(seedPoints_); + + generator_.addOption("random", "Random", RND); + generator_.addOption("line", "Line", LINE); + generator_.addOption("plane", "Plane", PLANE); + generator_.addOption("sphere", "Sphere", SPHERE); + generator_.setCurrentStateAsDefault(); + generator_.onChange([this]() { onGeneratorChange(); }); + addProperty(generator_); + + lineGroup_.addProperty(lineStart_); + lineGroup_.addProperty(lineEnd_); + addProperty(lineGroup_); + + planeGroup_.addProperty(planeResolution_); + planeGroup_.addProperty(planeOrigin_); + planeGroup_.addProperty(planeE1_); + planeGroup_.addProperty(planeE2_); + addProperty(planeGroup_); + + sphereGroup_.addProperty(sphereCenter_); + sphereGroup_.addProperty(sphereRadius_); + sphereRadius_.set(vec2(0.45, 0.55)); + sphereRadius_.setCurrentStateAsDefault(); + addProperty(sphereGroup_); + + addProperty(numberOfPoints_); + + addProperty(randomness_); + randomness_.addProperty(useSameSeed_); + randomness_.addProperty(seed_); + useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); }); + + onGeneratorChange(); +} + +void SeedPointGenerator::process() { + if (useSameSeed_.get()) { + mt_.seed(seed_.get()); + } + + switch (generator_.get()) { + case RND: + randomPoints(); + break; + case PLANE: + planePoints(); + break; + case LINE: + linePoints(); + break; + case SPHERE: + spherePoints(); + break; + default: + LogWarn("No points generated since given type is not yet implemented"); + break; + } +} + +void SeedPointGenerator::onGeneratorChange() { + bool rnd = generator_.get() == RND; + bool plane = generator_.get() == PLANE; + bool line = generator_.get() == LINE; + bool sphere = generator_.get() == SPHERE; + + numberOfPoints_.setVisible(rnd || line || sphere); + + planeResolution_.setVisible(plane); + planeOrigin_.setVisible(plane); + planeE1_.setVisible(plane); + planeE2_.setVisible(plane); + + sphereCenter_.setVisible(sphere); + sphereRadius_.setVisible(sphere); + + lineStart_.setVisible(line); + lineEnd_.setVisible(line); +} + +void SeedPointGenerator::spherePoints() { + auto T = [](auto&& r) { return util::randomNumber(r, 0, glm::two_pi()); }; + auto cos_phi = [](auto&& r) { return util::randomNumber(r, -1, 1); }; + auto R = [](auto&& r) { return util::randomNumber(r, 0, 1); }; + + auto points = std::make_shared>(); + + for (int i = 0; i < numberOfPoints_.get(); i++) { + float theta = T(mt_); + float phi = std::acos(cos_phi(mt_)); + + vec2 range = sphereRadius_.get(); + float r = std::pow(R(mt_), 1.0f / 3.0f); + r = range.x + r * (range.y - range.x); + + float ct = std::cos(theta); + float st = std::sin(theta); + float sp = std::sin(phi); + float cp = std::cos(phi); + + vec3 g = vec3(ct * sp, st * sp, cp); + vec3 p = g * r + sphereCenter_.get(); + + points->push_back(p); + } + + seedPoints_.setData(points); +} + +void SeedPointGenerator::linePoints() { + auto points = std::make_shared>(); + float dt = 1.0f / (numberOfPoints_.get() - 1); + for (int i = 0; i < numberOfPoints_.get(); i++) { + auto p = lineStart_.get() + (lineEnd_.get() - lineStart_.get()) * (i * dt); + points->push_back(p); + } + seedPoints_.setData(points); +} + +void SeedPointGenerator::planePoints() { + auto points = std::make_shared>(); + float dx = 1.0f / (planeResolution_.get().x - 1); + float dy = 1.0f / (planeResolution_.get().y - 1); + + vec3 ox = planeE1_.get(); + vec3 oy = planeE2_.get(); + + for (int i = 0; i < planeResolution_.get().x; i++) { + for (int j = 0; j < planeResolution_.get().y; j++) { + vec3 p = planeOrigin_.get(); + p += ox * (i * dx); + p += oy * (j * dy); + points->push_back(p); + } + } + seedPoints_.setData(points); +} + +void SeedPointGenerator::randomPoints() { + auto points = std::make_shared>(); + for (int i = 0; i < numberOfPoints_.get(); i++) { + const float x = util::randomNumber(mt_); + const float y = util::randomNumber(mt_); + const float z = util::randomNumber(mt_); + points->emplace_back(x, y, z); + } + seedPoints_.setData(points); +} + +} // namespace inviwo diff --git a/pool/shard006/C++/0078922_mediastreaminterface.cc b/pool/shard006/C++/0078922_mediastreaminterface.cc new file mode 100644 index 0000000000000000000000000000000000000000..fac3baaf9153dc88e128a87ed37ba695a4eec7ef --- /dev/null +++ b/pool/shard006/C++/0078922_mediastreaminterface.cc @@ -0,0 +1,61 @@ +/* + * Copyright 2017 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 BOSS_WEBRTC_U_api__mediastreaminterface_h //original-code:"api/mediastreaminterface.h" +#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" +#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" + +namespace webrtc { + +const char MediaStreamTrackInterface::kVideoKind[] = "video"; +const char MediaStreamTrackInterface::kAudioKind[] = "audio"; + +void AudioProcessorInterface::GetStats(AudioProcessorStats* /*stats*/) { + RTC_NOTREACHED() << "Old-style GetStats() is called but it has no " + << "implementation."; + RTC_LOG(LS_ERROR) << "Old-style GetStats() is called but it has no " + << "implementation."; +} + +// TODO(ivoc): Remove this when the function becomes pure virtual. +AudioProcessorInterface::AudioProcessorStatistics +AudioProcessorInterface::GetStats(bool /*has_remote_tracks*/) { + AudioProcessorStats stats; + GetStats(&stats); + AudioProcessorStatistics new_stats; + new_stats.apm_statistics.divergent_filter_fraction = + stats.aec_divergent_filter_fraction; + new_stats.apm_statistics.delay_median_ms = stats.echo_delay_median_ms; + new_stats.apm_statistics.delay_standard_deviation_ms = + stats.echo_delay_std_ms; + new_stats.apm_statistics.echo_return_loss = stats.echo_return_loss; + new_stats.apm_statistics.echo_return_loss_enhancement = + stats.echo_return_loss_enhancement; + new_stats.apm_statistics.residual_echo_likelihood = + stats.residual_echo_likelihood; + new_stats.apm_statistics.residual_echo_likelihood_recent_max = + stats.residual_echo_likelihood_recent_max; + return new_stats; +} + +VideoTrackInterface::ContentHint VideoTrackInterface::content_hint() const { + return ContentHint::kNone; +} + +bool AudioTrackInterface::GetSignalLevel(int* level) { + return false; +} + +rtc::scoped_refptr +AudioTrackInterface::GetAudioProcessor() { + return nullptr; +} + +} // namespace webrtc diff --git a/pool/shard006/C++/0078926_check_multiplicable_test.cpp b/pool/shard006/C++/0078926_check_multiplicable_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dcf765fc6b0b72b10cbcf69c8947ee570f71954 --- /dev/null +++ b/pool/shard006/C++/0078926_check_multiplicable_test.cpp @@ -0,0 +1,81 @@ +#include +#include +#include + +TEST(ErrorHandlingMatrix, checkMultiplicableMatrix) { + Eigen::Matrix y; + Eigen::Matrix x; + + y.resize(3,3); + x.resize(3,3); + EXPECT_NO_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y)); + x.resize(3,2); + y.resize(2,4); + EXPECT_NO_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y)); + + y.resize(1,2); + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); + + x.resize(2,2); + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); +} + +TEST(ErrorHandlingMatrix, checkMultiplicableMatrix_0) { + Eigen::Matrix y; + Eigen::Matrix x; + + x.resize(3,0); + y.resize(0,3); + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); + + x.resize(0,4); + y.resize(4,3); + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); + + x.resize(3,4); + y.resize(4,0); + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); +} + +TEST(ErrorHandlingMatrix, checkMultiplicableMatrix_nan) { + Eigen::Matrix y; + Eigen::Matrix x; + double nan = std::numeric_limits::quiet_NaN(); + + y.resize(3,3); + x.resize(3,3); + y << nan, nan, nan,nan, nan, nan,nan, nan, nan; + x << nan, nan, nan,nan, nan, nan,nan, nan, nan; + EXPECT_NO_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y)); + x.resize(3,2); + y.resize(2,4); + y << nan, nan, nan,nan, nan, nan,nan, nan; + x << nan, nan, nan,nan, nan, nan; + EXPECT_NO_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y)); + + y.resize(1,2); + y << nan, nan; + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); + + x.resize(2,2); + x << nan, nan, nan, nan; + EXPECT_THROW(stan::math::check_multiplicable("checkMultiplicable", "x", x, + "y", y), + std::invalid_argument); +} diff --git a/pool/shard006/C++/0078934_read_buffer_test.cpp b/pool/shard006/C++/0078934_read_buffer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13f9eb34c981e31b2ef94d80a192c7e771d14328 --- /dev/null +++ b/pool/shard006/C++/0078934_read_buffer_test.cpp @@ -0,0 +1,64 @@ +#include + +#include "base_test.hpp" +#include "mock_socket.hpp" + +#include "server/read_buffer.hpp" + +namespace opossum { + +class ReadBufferTest : public BaseTest { + protected: + void SetUp() override { + _mocked_socket = std::make_shared(); + _read_buffer = std::make_shared>(_mocked_socket->get_socket()); + } + + std::shared_ptr _mocked_socket; + std::shared_ptr> _read_buffer; +}; + +TEST_F(ReadBufferTest, Full) { + EXPECT_FALSE(_read_buffer->full()); + _mocked_socket->write(std::string(_read_buffer->maximum_capacity(), 'a')); + _read_buffer->get_string(1, HasNullTerminator::No); + EXPECT_FALSE(_read_buffer->full()); +} + +TEST_F(ReadBufferTest, GetSize) { + EXPECT_EQ(_read_buffer->size(), 0u); + _mocked_socket->write("random"); + _read_buffer->template get_value(); + EXPECT_EQ(_read_buffer->size(), 5); +} + +TEST_F(ReadBufferTest, ReadValues) { + const auto converted_short = htons(16); + const auto converted = htonl(32); + _mocked_socket->write(std::string(reinterpret_cast(&converted_short), sizeof(uint16_t))); + _mocked_socket->write(std::string(reinterpret_cast(&converted), sizeof(uint32_t))); + _mocked_socket->write("A"); + + EXPECT_EQ(_read_buffer->get_value(), 16); + EXPECT_EQ(_read_buffer->get_value(), 32); + EXPECT_EQ(_read_buffer->get_value(), 'A'); +} + +TEST_F(ReadBufferTest, ReadString) { + const std::string original_content = {"somerandom\0string\0", 19}; + _mocked_socket->write(original_content); + EXPECT_EQ(_read_buffer->get_string(4, HasNullTerminator::No), "some"); + EXPECT_EQ(_read_buffer->get_string(), "random"); + EXPECT_EQ(_read_buffer->get_string(7), "string"); +} + +TEST_F(ReadBufferTest, ReadLargeString) { + const std::string original_content = std::string(SERVER_BUFFER_SIZE + 2u, 'a'); + _mocked_socket->write(original_content); + EXPECT_EQ(_read_buffer->get_string(original_content.size(), HasNullTerminator::No), original_content); + _mocked_socket->write(original_content); + _mocked_socket->write(std::string{"\0", 1}); + EXPECT_EQ(_read_buffer->get_string(), original_content); +} + +} // namespace opossum diff --git a/pool/shard006/C++/0078935_csharp_bootstrap_unittest.cc b/pool/shard006/C++/0078935_csharp_bootstrap_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c38e52fe16f477d00e5d22f1a3132995e9e5bb7 --- /dev/null +++ b/pool/shard006/C++/0078935_csharp_bootstrap_unittest.cc @@ -0,0 +1,200 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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. + +// This test insures that +// csharp/src/Google.Protobuf/Reflection/Descriptor.cs match exactly +// what would be generated by the protocol compiler. The file is not +// generated automatically at build time. +// +// If this test fails, run the script +// "generate_descriptor_proto.sh" and add the changed files under +// csharp/src/ to your changelist. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +namespace { + +class MockErrorCollector : public MultiFileErrorCollector { + public: + MockErrorCollector() {} + ~MockErrorCollector() {} + + string text_; + + // implements ErrorCollector --------------------------------------- + void AddError(const string& filename, int line, int column, + const string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", + filename, line, column, message); + } +}; + +class MockGeneratorContext : public GeneratorContext { + public: + MockGeneratorContext() {} + ~MockGeneratorContext() { + STLDeleteValues(&files_); + } + + void ExpectFileMatches(const string& virtual_filename, + const string& physical_filename) { + string* expected_contents = FindPtrOrNull(files_, virtual_filename); + ASSERT_TRUE(expected_contents != NULL) + << "Generator failed to generate file: " << virtual_filename; + + string actual_contents; + GOOGLE_CHECK_OK( + File::GetContents(TestSourceDir() + "/" + physical_filename, + &actual_contents, true)) + << "Unable to get " << physical_filename; + EXPECT_TRUE(actual_contents == *expected_contents) + << physical_filename << " needs to be regenerated. Please run " + "generate_descriptor_proto.sh. Then add this file " + "to your CL."; + } + + // implements GeneratorContext -------------------------------------- + + virtual io::ZeroCopyOutputStream* Open(const string& filename) { + string** map_slot = &files_[filename]; + delete *map_slot; + *map_slot = new string; + + return new io::StringOutputStream(*map_slot); + } + + private: + std::map files_; +}; + +class GenerateAndTest { + public: + GenerateAndTest() {} + void Run(const FileDescriptor* proto_file, string file1, string file2) { + ASSERT_TRUE(proto_file != NULL) << TestSourceDir(); + ASSERT_TRUE(generator_.Generate(proto_file, parameter_, + &context_, &error_)); + context_.ExpectFileMatches(file1, file2); + } + void SetParameter(string parameter) { + parameter_ = parameter; + } + + private: + Generator generator_; + MockGeneratorContext context_; + string error_; + string parameter_; +}; + +TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) { + // Skip this whole test if the csharp directory doesn't exist (i.e., a C++11 + // only distribution). + string descriptor_file_name = + "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs"; + if (!File::Exists(TestSourceDir() + "/" + descriptor_file_name)) { + return; + } + + MockErrorCollector error_collector; + DiskSourceTree source_tree; + Importer importer(&source_tree, &error_collector); + GenerateAndTest generate_test; + + generate_test.SetParameter("base_namespace=Google.Protobuf"); + source_tree.MapPath("", TestSourceDir()); + generate_test.Run(importer.Import("google/protobuf/descriptor.proto"), + "Reflection/Descriptor.cs", + "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs"); + generate_test.Run(importer.Import("google/protobuf/any.proto"), + "WellKnownTypes/Any.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Any.cs"); + generate_test.Run(importer.Import("google/protobuf/api.proto"), + "WellKnownTypes/Api.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Api.cs"); + generate_test.Run(importer.Import("google/protobuf/duration.proto"), + "WellKnownTypes/Duration.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs"); + generate_test.Run(importer.Import("google/protobuf/empty.proto"), + "WellKnownTypes/Empty.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs"); + generate_test.Run(importer.Import("google/protobuf/field_mask.proto"), + "WellKnownTypes/FieldMask.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs"); + generate_test.Run(importer.Import("google/protobuf/source_context.proto"), + "WellKnownTypes/SourceContext.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs"); + generate_test.Run(importer.Import("google/protobuf/struct.proto"), + "WellKnownTypes/Struct.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs"); + generate_test.Run(importer.Import("google/protobuf/timestamp.proto"), + "WellKnownTypes/Timestamp.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs"); + generate_test.Run(importer.Import("google/protobuf/type.proto"), + "WellKnownTypes/Type.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Type.cs"); + generate_test.Run(importer.Import("google/protobuf/wrappers.proto"), + "WellKnownTypes/Wrappers.cs", + "../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs"); + + generate_test.SetParameter(""); + source_tree.MapPath("", TestSourceDir() + "/../conformance"); + generate_test.Run(importer.Import("conformance.proto"), + "Conformance.cs", + "../csharp/src/Google.Protobuf.Conformance/Conformance.cs"); + + EXPECT_EQ("", error_collector.text_); +} + +} // namespace + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/pool/shard006/C++/0078966_main_normal.cpp b/pool/shard006/C++/0078966_main_normal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50ab1f58682cae84b8e9cb3b93824b63d6d91a27 --- /dev/null +++ b/pool/shard006/C++/0078966_main_normal.cpp @@ -0,0 +1,127 @@ + +#include "net/server.h" +#include "net/connpool.h" +#include "net/http/http.h" +#include +using namespace std; + +class MyHandler : public SHttpRequestHandler +{ +public: + MyHandler() + { + cerr << "Creating request handler..." << endl; + } + + virtual ~MyHandler() + { + cerr << "Destroying request handler..." << endl; + } + + virtual bool ProcessRequest(SHttpRequest &request, SHttpResponse &response); +}; + +class MyConnPool : public SConnPool +{ +public: + virtual SHttpConnHandler *NewHandler() + { + SHttpConnHandler *pHandler = SConnPool::NewHandler(); + pHandler->RegisterRequestHandler(new MyHandler(), REQUEST_HANDLER); + return pHandler; + } + + virtual void ReleaseHandler(SConnHandler *pHandler) + { + SHttpConnHandler *pHttpHandler = dynamic_cast(pHandler); + if (pHttpHandler != NULL) + { + SHttpRequestHandler *pReqHandler = pHttpHandler->UnRegisterRequestHandler(REQUEST_HANDLER); + delete pReqHandler; + } + SConnPool::ReleaseHandler(pHandler); + } +}; + +int main(int argc, char *argv[]) +{ + SServer *pServer = new SServer(argc <= 1 ? 80 : atoi(argv[1])); + + pServer->SetConnectionFactory(new MyConnPool()); + + cerr << "Server Started ..." << endl; + pServer->Start(); + cerr << "Server Finished..." << endl; + + return 0; +} + +bool MyHandler::ProcessRequest(SHttpRequest &request, SHttpResponse &response) +{ + std::string title; + std::string body; + std::string bgcolor="#ffffff"; + std::string links = + "

red " + "
blue " + "
form " + "
authentication example [use adp as username and gmbh as password" + "
show some HTTP header details " + ; + + if(request.Resource() == "/") { + + title = "Web Server Example"; + body = "I wonder what you're going to click" + links; + } + else if (request.Resource() == "/red") { + + bgcolor = "#ff4444"; + title = "You chose red"; + body = "

Red

" + links; + } + else if (request.Resource() == "/blue") { + + bgcolor = "#4444ff"; + title = "You chose blue"; + body = "

Blue

" + links; + } + else if (request.Resource() == "/form") { + + title = "Fill a form"; + + body = "

Fill a form

"; + body += "
" + "" + "" + "" + "" + "
Field 1
Field 2
Field 3
" + "
"; + + + for (std::map::const_iterator i = request.FirstHeader(); + i != request.LastHeader(); + i++) + { + body += "
" + i->first + " = " + i->second; + } + + body += "
" + links; + } + else { + response.SetStatus(404, "Not Found"); + title = "Wrong URL"; + body = "

Wrong URL

"; + body += "Path is : >" + request.Resource() + "<"; + } + + // response.SetHeader("Connection", "Close"); + response.SetBody(""); + response.AppendToBody(title); + response.AppendToBody(""); + response.AppendToBody(body); + response.AppendToBody(""); + + return false; +} diff --git a/pool/shard006/C++/0078971_moc_qgraphicsscenebsptreeindex_p.cpp b/pool/shard006/C++/0078971_moc_qgraphicsscenebsptreeindex_p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83f3363ea7f82d6e9a334a8203a226cb1900b13f --- /dev/null +++ b/pool/shard006/C++/0078971_moc_qgraphicsscenebsptreeindex_p.cpp @@ -0,0 +1,128 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'qgraphicsscenebsptreeindex_p.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../../../graphicsview/qgraphicsscenebsptreeindex_p.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'qgraphicsscenebsptreeindex_p.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.5. 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_QGraphicsSceneBspTreeIndex[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 3, 14, // methods + 1, 29, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + // slots: signature, parameters, type, tag, flags + 33, 28, 27, 27, 0x09, + 57, 27, 27, 27, 0x08, + 78, 27, 27, 27, 0x08, + + // properties: name, type, flags + 99, 95, 0x02095103, + + 0 // eod +}; + +static const char qt_meta_stringdata_QGraphicsSceneBspTreeIndex[] = { + "QGraphicsSceneBspTreeIndex\0\0rect\0" + "updateSceneRect(QRectF)\0_q_updateSortCache()\0" + "_q_updateIndex()\0int\0bspTreeDepth\0" +}; + +void QGraphicsSceneBspTreeIndex::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + QGraphicsSceneBspTreeIndex *_t = static_cast(_o); + switch (_id) { + case 0: _t->updateSceneRect((*reinterpret_cast< const QRectF(*)>(_a[1]))); break; + case 1: _t->d_func()->_q_updateSortCache(); break; + case 2: _t->d_func()->_q_updateIndex(); break; + default: ; + } + } +} + +const QMetaObjectExtraData QGraphicsSceneBspTreeIndex::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject QGraphicsSceneBspTreeIndex::staticMetaObject = { + { &QGraphicsSceneIndex::staticMetaObject, qt_meta_stringdata_QGraphicsSceneBspTreeIndex, + qt_meta_data_QGraphicsSceneBspTreeIndex, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &QGraphicsSceneBspTreeIndex::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *QGraphicsSceneBspTreeIndex::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *QGraphicsSceneBspTreeIndex::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_QGraphicsSceneBspTreeIndex)) + return static_cast(const_cast< QGraphicsSceneBspTreeIndex*>(this)); + return QGraphicsSceneIndex::qt_metacast(_clname); +} + +int QGraphicsSceneBspTreeIndex::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QGraphicsSceneIndex::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 3) + qt_static_metacall(this, _c, _id, _a); + _id -= 3; + } +#ifndef QT_NO_PROPERTIES + else if (_c == QMetaObject::ReadProperty) { + void *_v = _a[0]; + switch (_id) { + case 0: *reinterpret_cast< int*>(_v) = bspTreeDepth(); break; + } + _id -= 1; + } else if (_c == QMetaObject::WriteProperty) { + void *_v = _a[0]; + switch (_id) { + case 0: setBspTreeDepth(*reinterpret_cast< int*>(_v)); break; + } + _id -= 1; + } else if (_c == QMetaObject::ResetProperty) { + _id -= 1; + } else if (_c == QMetaObject::QueryPropertyDesignable) { + _id -= 1; + } else if (_c == QMetaObject::QueryPropertyScriptable) { + _id -= 1; + } else if (_c == QMetaObject::QueryPropertyStored) { + _id -= 1; + } else if (_c == QMetaObject::QueryPropertyEditable) { + _id -= 1; + } else if (_c == QMetaObject::QueryPropertyUser) { + _id -= 1; + } +#endif // QT_NO_PROPERTIES + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard006/C++/0078973_sync_global_error_unittest.cc b/pool/shard006/C++/0078973_sync_global_error_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e7af93fd458fd944c75aa2ea9434de100a672453 --- /dev/null +++ b/pool/shard006/C++/0078973_sync_global_error_unittest.cc @@ -0,0 +1,174 @@ +// 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/sync_global_error.h" + +#include + +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/sync/profile_sync_test_util.h" +#include "chrome/browser/sync/sync_global_error_factory.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/global_error/global_error_service_factory.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" +#include "chrome/test/base/browser_with_test_window_test.h" +#include "chrome/test/base/testing_profile.h" +#include "components/sync_driver/sync_error_controller.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "content/public/browser/notification_source.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::NiceMock; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::_; + +namespace { + +class FakeLoginUIService: public LoginUIService { + public: + FakeLoginUIService() : LoginUIService(NULL) {} +}; + +class FakeLoginUI : public LoginUIService::LoginUI { + public: + FakeLoginUI() : focus_ui_call_count_(0) {} + + ~FakeLoginUI() override {} + + int focus_ui_call_count() const { return focus_ui_call_count_; } + + private: + // Overridden from LoginUIService::LoginUI: + void FocusUI() override { ++focus_ui_call_count_; } + + int focus_ui_call_count_; +}; + +std::unique_ptr BuildMockLoginUIService( + content::BrowserContext* profile) { + return base::WrapUnique(new FakeLoginUIService()); +} + +// Same as BrowserWithTestWindowTest, but uses MockBrowser to test calls to +// ExecuteCommand method. +class SyncGlobalErrorTest : public BrowserWithTestWindowTest { + public: + SyncGlobalErrorTest() {} + ~SyncGlobalErrorTest() override {} + + void SetUp() override { + profile_ = MakeSignedInTestingProfile(); + + BrowserWithTestWindowTest::SetUp(); + } + + Profile* profile() { return profile_.get(); } + + private: + std::unique_ptr profile_; + + DISALLOW_COPY_AND_ASSIGN(SyncGlobalErrorTest); +}; + +// Utility function to test that SyncGlobalError behaves correctly for the given +// error condition. +void VerifySyncGlobalErrorResult(ProfileSyncServiceMock* service, + FakeLoginUIService* login_ui_service, + Browser* browser, + SyncErrorController* error, + SyncGlobalError* global_error, + GoogleServiceAuthError::State error_state, + bool is_signed_in, + bool is_error) { + EXPECT_CALL(*service, IsFirstSetupComplete()) + .WillRepeatedly(Return(is_signed_in)); + + GoogleServiceAuthError auth_error(error_state); + EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(ReturnRef(auth_error)); + + error->OnStateChanged(); + EXPECT_EQ(is_error, error->HasError()); + + // If there is an error then a menu item and bubble view should be shown. + EXPECT_EQ(is_error, global_error->HasMenuItem()); + EXPECT_EQ(is_error, global_error->HasBubbleView()); + + // If there is an error then labels should not be empty. + EXPECT_NE(0, global_error->MenuItemCommandID()); + EXPECT_NE(is_error, global_error->MenuItemLabel().empty()); + EXPECT_NE(is_error, global_error->GetBubbleViewAcceptButtonLabel().empty()); + + // We never have a cancel button. + EXPECT_TRUE(global_error->GetBubbleViewCancelButtonLabel().empty()); + // We always return a hardcoded title. + EXPECT_FALSE(global_error->GetBubbleViewTitle().empty()); + + // Test message handler. + if (is_error) { + FakeLoginUI* login_ui = static_cast( + login_ui_service->current_login_ui()); + global_error->ExecuteMenuItem(browser); + ASSERT_GT(login_ui->focus_ui_call_count(), 0); + global_error->BubbleViewAcceptButtonPressed(browser); + global_error->BubbleViewDidClose(browser); + } +} + +} // namespace + +// Test that SyncGlobalError shows an error if a passphrase is required. +TEST_F(SyncGlobalErrorTest, PassphraseGlobalError) { + ProfileSyncServiceMock service( + CreateProfileSyncServiceParamsForTest(profile())); + + FakeLoginUIService* login_ui_service = static_cast( + LoginUIServiceFactory::GetInstance()->SetTestingFactoryAndUse( + profile(), BuildMockLoginUIService)); + FakeLoginUI login_ui; + login_ui_service->SetLoginUI(&login_ui); + + SyncErrorController error(&service); + SyncGlobalError global_error( + GlobalErrorServiceFactory::GetForProfile(profile()), login_ui_service, + &error, &service); + + browser_sync::SyncBackendHost::Status status; + EXPECT_CALL(service, QueryDetailedSyncStatus(_)) + .WillRepeatedly(Return(false)); + + EXPECT_CALL(service, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(service, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(true)); + VerifySyncGlobalErrorResult( + &service, login_ui_service, browser(), &error, &global_error, + GoogleServiceAuthError::NONE, true /* signed in*/, true /* error */); + + // Check that no menu item is shown if there is no error. + EXPECT_CALL(service, IsPassphraseRequired()) + .WillRepeatedly(Return(false)); + EXPECT_CALL(service, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(false)); + VerifySyncGlobalErrorResult( + &service, login_ui_service, browser(), &error, &global_error, + GoogleServiceAuthError::NONE, true /* signed in */, false /* no error */); + + // Check that no menu item is shown if sync setup is not completed. + EXPECT_CALL(service, IsPassphraseRequired()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(service, IsPassphraseRequiredForDecryption()) + .WillRepeatedly(Return(true)); + VerifySyncGlobalErrorResult( + &service, login_ui_service, browser(), &error, &global_error, + GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS, + false /* not signed in */, false /* no error */); + + global_error.Shutdown(); +} diff --git a/pool/shard006/C++/0078978_testApp.cpp b/pool/shard006/C++/0078978_testApp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfa4ff9395a9900c8eba5fc458cc5ab02574d796 --- /dev/null +++ b/pool/shard006/C++/0078978_testApp.cpp @@ -0,0 +1,44 @@ +#include "testApp.h" + +using namespace ofxCv; +using namespace cv; + +void testApp::setup() { + ofSetVerticalSync(true); + ofSetFrameRate(120); + finder.setup("haarcascade_frontalface_alt2.xml"); + finder.setPreset(ObjectFinder::Fast); + finder.getTracker().setSmoothingRate(.3); + cam.setup(640, 480,false); + sunglasses.loadImage("sunglasses.png"); + ofEnableAlphaBlending(); +} + +void testApp::update() { + frame = cam.grab(); + if(!frame.empty()) { + finder.update(frame); + } +} + +void testApp::draw() { + if(!frame.empty()){ + drawMat(frame,0, 0); + + for(int i = 0; i < finder.size(); i++) { + ofRectangle object = finder.getObjectSmoothed(i); + sunglasses.setAnchorPercent(.5, .5); + float scaleAmount = .85 * object.width / sunglasses.getWidth(); + ofPushMatrix(); + ofTranslate(object.x + object.width / 2., object.y + object.height * .42); + ofScale(scaleAmount, scaleAmount); + sunglasses.draw(0, 0); + ofPopMatrix(); + ofPushMatrix(); + ofTranslate(object.getPosition()); + ofDrawBitmapStringHighlight(ofToString(finder.getLabel(i)), 0, 0); + ofLine(ofVec2f(), toOf(finder.getVelocity(i)) * 10); + ofPopMatrix(); + } + } +} diff --git a/pool/shard006/C++/0078982_RRoutines.cpp b/pool/shard006/C++/0078982_RRoutines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9630c0f6f41300f9376a8a97fc10f372285ddf65 --- /dev/null +++ b/pool/shard006/C++/0078982_RRoutines.cpp @@ -0,0 +1,94 @@ +/* + * RRoutines.cpp + * + * Copyright (C) 2009-12 by RStudio, Inc. + * + * Unless you have received this program directly from RStudio pursuant + * to the terms of a commercial license agreement with RStudio, then + * this program is licensed to you under the terms of version 3 of the + * GNU Affero General Public License. This program is distributed WITHOUT + * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the + * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. + * + */ + +#include +#include + +#include + +namespace rstudio { +namespace r { +namespace routines { + +namespace { + std::vector s_cMethods; + std::vector s_callMethods; +} + +void addCMethod(const R_CMethodDef method) +{ + s_cMethods.push_back(method); +} + +void addCallMethod(const R_CallMethodDef method) +{ + s_callMethods.push_back(method); +} + +void registerCallMethod(const char* name, + DL_FUNC fun, + int numArgs) +{ + R_CallMethodDef callMethodDef; + callMethodDef.name = name; + callMethodDef.fun = fun; + callMethodDef.numArgs = numArgs; + addCallMethod(callMethodDef); +} + +void registerAll() +{ + // c methods + R_CMethodDef* pCMethods = NULL; + if (s_cMethods.size() > 0) + { + R_CMethodDef nullMethodDef ; + nullMethodDef.name = NULL ; + nullMethodDef.fun = NULL ; + nullMethodDef.numArgs = 0 ; + nullMethodDef.types = NULL; + nullMethodDef.styles = NULL; + s_cMethods.push_back(nullMethodDef); + pCMethods = &s_cMethods[0]; + } + + // call methods + R_CallMethodDef* pCallMethods = NULL; + if (s_callMethods.size() > 0) + { + R_CallMethodDef nullMethodDef ; + nullMethodDef.name = NULL ; + nullMethodDef.fun = NULL ; + nullMethodDef.numArgs = 0 ; + s_callMethods.push_back(nullMethodDef); + pCallMethods = &s_callMethods[0]; + } + + DllInfo *info = R_getEmbeddingDllInfo() ; + R_registerRoutines(info, pCMethods, pCallMethods, NULL, NULL); + + exec::RFunction registerNativeRoutines(".rs.registerNativeRoutines"); + core::Error error = registerNativeRoutines.call(); + if (error) + LOG_ERROR(error); +} + + +} // namespace routines +} // namespace r +} // namespace rstudio + + + diff --git a/pool/shard006/C++/0078983_Tone.cpp b/pool/shard006/C++/0078983_Tone.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d4ddc406dbf23ed607d99b4ad04d28d78e10aee --- /dev/null +++ b/pool/shard006/C++/0078983_Tone.cpp @@ -0,0 +1,225 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + SAMD51 support added by Adafruit - Copyright (c) 2018 Dean Miller for Adafruit Industries + + 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 +*/ + +#include "Tone.h" +#include "variant.h" + +uint32_t toneMaxFrequency = F_CPU / 2; +uint32_t lastOutputPin = 0xFFFFFFFF; + +volatile uint32_t *portToggleRegister; +volatile uint32_t *portClearRegister; +volatile uint32_t portBitMask; +volatile int64_t toggleCount; +volatile bool toneIsActive = false; +volatile bool firstTimeRunning = false; + +#if defined(__SAMD51__) + #define TONE_TC TC0 + #define TONE_TC_IRQn TC0_IRQn + #define TONE_TC_GCLK_ID TC0_GCLK_ID + #define Tone_Handler TC0_Handler + + #define WAIT_TC16_REGS_SYNC(x) while(x->COUNT16.SYNCBUSY.bit.ENABLE); + +#else + #define TONE_TC TC5 + #define TONE_TC_IRQn TC5_IRQn + #define Tone_Handler TC5_Handler + + #define WAIT_TC16_REGS_SYNC(x) while(x->COUNT16.STATUS.bit.SYNCBUSY); +#endif + +#define TONE_TC_TOP 0xFFFF +#define TONE_TC_CHANNEL 0 + +static inline void resetTC (Tc* TCx) +{ + // Disable TCx + TCx->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; + WAIT_TC16_REGS_SYNC(TCx) + + // Reset TCx + TCx->COUNT16.CTRLA.reg = TC_CTRLA_SWRST; + WAIT_TC16_REGS_SYNC(TCx) + while (TCx->COUNT16.CTRLA.bit.SWRST); +} + +void toneAccurateClock (uint32_t accurateSystemCoreClockFrequency) +{ + toneMaxFrequency = accurateSystemCoreClockFrequency / 2; +} + +void tone (uint32_t outputPin, uint32_t frequency, uint32_t duration) +{ + + // Avoid divide by zero error by calling 'noTone' instead + if (frequency == 0) + { + noTone(outputPin); + return; + } + + // Configure interrupt request + NVIC_DisableIRQ(TONE_TC_IRQn); + NVIC_ClearPendingIRQ(TONE_TC_IRQn); + + if(!firstTimeRunning) + { + firstTimeRunning = true; + + NVIC_SetPriority(TONE_TC_IRQn, 5); + +#if defined(__SAMD51__) + GCLK->PCHCTRL[TONE_TC_GCLK_ID].reg = GCLK_PCHCTRL_GEN_GCLK0_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); +#else + // Enable GCLK for TC4 and TC5 (timer counter input clock) + GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TC4_TC5)); + while (GCLK->STATUS.bit.SYNCBUSY); +#endif + } + + if (toneIsActive && (outputPin != lastOutputPin)) + noTone(lastOutputPin); + + // + // Calculate best prescaler divider and comparator value for a 16 bit TC peripheral + // + + uint32_t prescalerConfigBits; + uint32_t ccValue; + + ccValue = toneMaxFrequency / frequency - 1; + prescalerConfigBits = TC_CTRLA_PRESCALER_DIV1; + + uint8_t i = 0; + + while(ccValue > TONE_TC_TOP) + { + ccValue = toneMaxFrequency / frequency / (2< 0 ? frequency * duration * 2 / 1000UL : -1LL); + + resetTC(TONE_TC); + + uint16_t tmpReg = 0; + tmpReg |= TC_CTRLA_MODE_COUNT16; // Set Timer counter Mode to 16 bits + +#if defined(__SAMD51__) + TONE_TC->COUNT16.WAVE.reg = TC_WAVE_WAVEGEN_MFRQ; // Set TONE_TC mode as match frequency +#else + tmpReg |= TC_CTRLA_WAVEGEN_MFRQ; // Set TONE_TC mode as match frequency +#endif + tmpReg |= prescalerConfigBits; + TONE_TC->COUNT16.CTRLA.reg |= tmpReg; + WAIT_TC16_REGS_SYNC(TONE_TC) + + TONE_TC->COUNT16.CC[TONE_TC_CHANNEL].reg = (uint16_t) ccValue; + WAIT_TC16_REGS_SYNC(TONE_TC) + + portToggleRegister = &(PORT->Group[g_APinDescription[outputPin].ulPort].OUTTGL.reg); + portClearRegister = &(PORT->Group[g_APinDescription[outputPin].ulPort].OUTCLR.reg); + portBitMask = (1ul << g_APinDescription[outputPin].ulPin); + + // Enable the TONE_TC interrupt request + TONE_TC->COUNT16.INTENSET.bit.MC0 = 1; + + if (outputPin != lastOutputPin) + { + lastOutputPin = outputPin; + digitalWrite(outputPin, LOW); + pinMode(outputPin, OUTPUT); + toneIsActive = true; + } + + // Enable TONE_TC + TONE_TC->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE; + WAIT_TC16_REGS_SYNC(TONE_TC) + + NVIC_EnableIRQ(TONE_TC_IRQn); +} + +void noTone (uint32_t outputPin) +{ + /* 'tone' need to run at least once in order to enable GCLK for + * the timers used for the tone-functionality. If 'noTone' is called + * without ever calling 'tone' before then 'WAIT_TC16_REGS_SYNC(TCx)' + * will wait infinitely. The variable 'firstTimeRunning' is set the + * 1st time 'tone' is set so it can be used to detect wether or not + * 'tone' has been called before. + */ + if(firstTimeRunning) + { + resetTC(TONE_TC); + digitalWrite(outputPin, LOW); + toneIsActive = false; + } +} + +#ifdef __cplusplus +extern "C" { +#endif + +void Tone_Handler (void) +{ + if (toggleCount != 0) + { + // Toggle the ouput pin + *portToggleRegister = portBitMask; + + if (toggleCount > 0) + --toggleCount; + + // Clear the interrupt + TONE_TC->COUNT16.INTFLAG.bit.MC0 = 1; + } + else + { + resetTC(TONE_TC); + *portClearRegister = portBitMask; + toneIsActive = false; + } +} + +#ifdef __cplusplus +} +#endif diff --git a/pool/shard006/C++/0078987_dlgTextEntry.cpp b/pool/shard006/C++/0078987_dlgTextEntry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b70588660540fc8df26d87551df48b1aef195b77 --- /dev/null +++ b/pool/shard006/C++/0078987_dlgTextEntry.cpp @@ -0,0 +1,269 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2013 The XCSoar 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 "Dialogs/TextEntry.hpp" +#include "Dialogs/XML.hpp" +#include "Dialogs/CallBackTable.hpp" +#include "Dialogs/DialogSettings.hpp" +#include "Screen/Canvas.hpp" +#include "Screen/Key.h" +#include "Form/Form.hpp" +#include "Form/Draw.hpp" +#include "Form/Button.hpp" +#include "MapSettings.hpp" +#include "Asset.hpp" +#include "Util/StringUtil.hpp" +#include "Util/CharUtil.hpp" +#include "UIGlobals.hpp" +#include "Look/DialogLook.hpp" +#include "Util/Macros.hpp" + +#include + +static WndForm *wf = NULL; +static WndOwnerDrawFrame *wGrid = NULL; + +static constexpr size_t MAX_TEXTENTRY = 40; +static unsigned int cursor = 0; +static int lettercursor = 0; +static size_t max_width; + +static TCHAR edittext[MAX_TEXTENTRY]; + +static constexpr TCHAR EntryLetters[] = + _T(" ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-"); + +#define MAXENTRYLETTERS (ARRAY_SIZE(EntryLetters) - 1) + +static void +OnTextPaint(gcc_unused WndOwnerDrawFrame *Sender, Canvas &canvas) +{ + const PixelRect rc = Sender->GetClientRect(); + + canvas.Clear(Color(0x40, 0x40, 0x00)); + + // Do the actual painting of the text + const DialogLook &look = UIGlobals::GetDialogLook(); + canvas.Select(*look.text_font); + + PixelSize tsize = canvas.CalcTextSize(edittext); + PixelSize tsizec = canvas.CalcTextSize(edittext, cursor); + PixelSize tsizea = canvas.CalcTextSize(edittext, cursor + 1); + + RasterPoint p[5]; + p[0].x = 10; + p[0].y = (rc.bottom - rc.top - tsize.cy - 5) / 2; + + p[2].x = p[0].x + tsizec.cx; + p[2].y = p[0].y + tsize.cy + 5; + + p[3].x = p[0].x + tsizea.cx; + p[3].y = p[0].y + tsize.cy + 5; + + p[1].x = p[2].x; + p[1].y = p[2].y - 2; + + p[4].x = p[3].x; + p[4].y = p[3].y - 2; + + canvas.SelectWhitePen(); + canvas.DrawPolyline(p + 1, 4); + + canvas.SetBackgroundTransparent(); + canvas.SetTextColor(COLOR_WHITE); + canvas.DrawText(p[0].x, p[0].y, edittext); +} + +static void +UpdateCursor() +{ + if (lettercursor >= (int)MAXENTRYLETTERS) + lettercursor = 0; + + if (lettercursor < 0) + lettercursor = MAXENTRYLETTERS - 1; + + edittext[cursor] = EntryLetters[lettercursor]; + + if (wGrid != NULL) + wGrid->Invalidate(); +} + +/** + * Find a letter in the list and returns its index. Returns 0 + * (i.e. the index of the space character) if the given letter is + * unknown. + */ +gcc_const +static unsigned +FindEntryLetter(TCHAR ch) +{ + for (unsigned i = 0; i < (int)MAXENTRYLETTERS; ++i) + if (EntryLetters[i] == ch) + return i; + + return 0; +} + +static void +MoveCursor() +{ + if (cursor >= _tcslen(edittext)) + edittext[cursor + 1] = 0; + + lettercursor = FindEntryLetter(ToUpperASCII(edittext[cursor])); + + UpdateCursor(); +} + +static bool +FormKeyDown(unsigned key_code) +{ + switch (key_code) { + case KEY_UP: + case KEY_LEFT: + if ((key_code == KEY_LEFT) ^ IsAltair()) { + if (cursor < 1) + return true; // min width + + cursor--; + MoveCursor(); + return true; + } else { + lettercursor--; + UpdateCursor(); + return true; + } + + case KEY_DOWN: + case KEY_RIGHT: + if ((key_code == KEY_RIGHT) ^ IsAltair()) { + if (cursor + 2 >= max_width) + return true; // max width + + cursor++; + MoveCursor(); + return true; + } else { + lettercursor++; + UpdateCursor(); + return true; + } + case KEY_RETURN: + wf->SetModalResult(mrOK); + return true; + + default: + return false; + } +} + +static void +OnLeftClicked() +{ + FormKeyDown(IsAltair() ? KEY_UP : KEY_LEFT); +} + +static void +OnRightClicked() +{ + FormKeyDown(IsAltair() ? KEY_DOWN : KEY_RIGHT); +} + +static void +OnUpClicked() +{ + FormKeyDown(!IsAltair() ? KEY_UP : KEY_LEFT); +} + +static void +OnDownClicked() +{ + FormKeyDown(!IsAltair() ? KEY_DOWN : KEY_RIGHT); +} + +static constexpr CallBackTableEntry CallBackTable[] = { + DeclareCallBackEntry(OnTextPaint), + DeclareCallBackEntry(OnLeftClicked), + DeclareCallBackEntry(OnRightClicked), + DeclareCallBackEntry(OnUpClicked), + DeclareCallBackEntry(OnDownClicked), + DeclareCallBackEntry(NULL) +}; + +static void +dlgTextEntryHighscoreType(TCHAR *text, size_t width, + const TCHAR* caption) +{ + wf = NULL; + wGrid = NULL; + + if (width == 0) + width = MAX_TEXTENTRY; + + max_width = std::min(MAX_TEXTENTRY, width); + + wf = LoadDialog(CallBackTable, UIGlobals::GetMainWindow(), + _T("IDR_XML_TEXTENTRY")); + assert(wf != nullptr); + + if (caption) + wf->SetCaption(caption); + + wGrid = (WndOwnerDrawFrame*)wf->FindByName(_T("frmGrid")); + + cursor = 0; + CopyString(edittext, text, max_width); + MoveCursor(); + + wf->SetKeyDownFunction(FormKeyDown); + + if (wf->ShowModal() == mrOK) { + TrimRight(edittext); + CopyString(text, edittext, max_width); + } + + delete wf; +} + +bool +dlgTextEntryShowModal(TCHAR *text, size_t width, + const TCHAR* caption, AllowedCharacters accb) +{ + switch (UIGlobals::GetDialogSettings().text_input_style) { + case DialogSettings::TextInputStyle::Default: + case DialogSettings::TextInputStyle::Keyboard: + if (HasPointer()) + return dlgTextEntryKeyboardShowModal(text, width, caption, accb); + else { + dlgTextEntryHighscoreType(text, width, caption); + return true; + } + + case DialogSettings::TextInputStyle::HighScore: + dlgTextEntryHighscoreType(text, width, caption); + return true; + } + + return false; +} diff --git a/pool/shard006/C++/0078990_jump.cpp b/pool/shard006/C++/0078990_jump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f65d1e62df374487c1820abd0d127143b1d2cd2b --- /dev/null +++ b/pool/shard006/C++/0078990_jump.cpp @@ -0,0 +1,168 @@ +#include +using namespace std; +typedef long long lli; +const double INF = 1e18; + +struct line { + int type; + lli m, c; + mutable long double left; + long double l; + line(int t, lli a, lli b, long double x) { + type = t; + m = a, c = b; + l = left = x; + } + bool operator<(const line& a) const { + if (type == 0) { + if (m == a.m) + return c < a.c; + return m > a.m; + } + else + return l < a.l; + } +}; + +struct ConvexHullDynamic { + set hull; + set queries; + typedef set::iterator lit; + + int bad(lit y) { + if (hull.size() <= 2) + return 0; + else if (y == hull.begin() || next(y) == hull.end()) + return 0; + else { + lit x = prev(y), z = next(y); + return (y->c - x->c) * (x->m - z->m) >= (z->c - x->c) * (x->m - y->m); + } + } + + long double setleft(lit y) { + if (y == hull.begin()) + return y->left = -INF; + else { + lit x = prev(y); + y->left = (x->c - y->c) / (long double) (y->m - x->m); + return y->left; + } + } + + void insert(lli m, lli c) { + lit y = hull.insert(line(0, m, c, 0.0)).first; + lit x, z; + + if (y != hull.begin()) { + x = prev(y); + if (x->m == y->m) { + hull.erase(y); + return; + } + } + + if (next(y) != hull.end()) { + z = next(y); + if (z->m == y->m) { + queries.erase(line(1, z->m, z->c, z->left)); + hull.erase(z); + } + } + + if (bad(y)) { + hull.erase(y); + return; + } + + while (next(y) != hull.end() && bad(next(y))) { + z = next(y); + queries.erase(line(1, z->m, z->c, z->left)); + hull.erase(z); + } + + if (next(y) != hull.end()) { + z = next(y); + long double pl = z->left; + long double l = setleft(z); + queries.erase(line(1, z->m, z->c, pl)); + queries.insert(line(1, z->m, z->c, l)); + } + + while (y != hull.begin() && bad(prev(y))) { + x = prev(y); + queries.erase(line(1, x->m, x->c, x->left)); + hull.erase(x); + } + + long double l = setleft(y); + queries.insert(line(1, m, c, l)); + } + + lli find(lli x) { + if (queries.empty()) + return LLONG_MAX; + lit y = queries.upper_bound(line(1, 0, 0, x)); + y = prev(y); + return (y->m * x) + y->c; + } +}; + +ConvexHullDynamic tree[600000 * 4]; + +int p[500100]; +int a[500100]; +int h[500100]; +pair ord[500100]; +lli dp[500100]; +int n; + + +void update(int l, lli m, lli c, int id = 1, int cl = 1, int cr = n) { + tree[id].insert(m, c); + if (cl < cr) { + int mid = (cl + cr) / 2; + if (l <= mid) + update(l, m, c, 2*id, cl, mid); + else + update(l, m, c, 2*id +1, mid + 1, cr); + } +} + +lli query(int l, int r, lli x, int id = 1, int cl = 1, int cr = n) { + if (cl > r || cr < l) + return LLONG_MAX; + else if (cl >= l && cr <= r) { + lli val = tree[id].find(x); + return val; + } + else { + int mid = (cl + cr) / 2; + lli left = query(l, r, x, 2*id, cl, mid); + lli right = query(l, r, x, 2*id + 1, mid + 1, cr); + return min(left, right); + } +} + +int main(void) { + scanf("%d", &n); + for (int i = 1; i <= n; i++) { + scanf("%d", p+i); + ord[i] = make_pair(p[i], i); + } + for (int i = 1; i <= n; i++) + scanf("%d", a+i); + for (int i = 1; i <= n; i++) + scanf("%d", h+i); + + sort(ord + 1, ord + n + 1); + dp[1] = a[1]; + update(1, -2 * h[1], dp[1] + h[1] * (long long)h[1]); + for (int i = 2; i <= n; i++) { + int x = ord[i].first, r = ord[i].second; + dp[r] = query(1, r - 1, h[r]) + a[r] + h[r] * (long long) h[r]; + update(r, -2 * h[r], dp[r] + h[r] * (long long) h[r]); + } + printf("%lld\n", dp[n]); + return 0; +} diff --git a/pool/shard006/C++/0078991_main.cpp b/pool/shard006/C++/0078991_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a30b277ded3d79c8ab0f1c7c41e2111eaa90eb5 --- /dev/null +++ b/pool/shard006/C++/0078991_main.cpp @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include + +#include + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QWidget rootWidget; + + QVBoxLayout *layout = new QVBoxLayout(); + rootWidget.setLayout(layout); + + QQuickView *view = new QQuickView(); + view->setResizeMode(QQuickView::SizeRootObjectToView); + view->setSource(QUrl(QStringLiteral("qrc:///embeddedinwidgets/main.qml"))); + + QWidget *container = QWidget::createWindowContainer(view); + container->setMinimumSize(view->size()); + container->setFocusPolicy(Qt::TabFocus); + + layout->addWidget(new QLineEdit(QStringLiteral("A QLineEdit"))); + layout->addWidget(container); + layout->addWidget(new QLineEdit(QStringLiteral("A QLineEdit"))); + + rootWidget.show(); + + return app.exec(); +} diff --git a/pool/shard006/C++/0079002_wayland_screen.cc b/pool/shard006/C++/0079002_wayland_screen.cc new file mode 100644 index 0000000000000000000000000000000000000000..81af6275b27003db976ff5ea2a3e673f7538618b --- /dev/null +++ b/pool/shard006/C++/0079002_wayland_screen.cc @@ -0,0 +1,211 @@ +// 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 "ui/ozone/platform/wayland/host/wayland_screen.h" + +#include +#include + +#include "base/stl_util.h" +#include "ui/display/display.h" +#include "ui/display/display_finder.h" +#include "ui/display/display_observer.h" +#include "ui/gfx/geometry/point.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/ozone/platform/wayland/host/wayland_connection.h" +#include "ui/ozone/platform/wayland/host/wayland_cursor_position.h" +#include "ui/ozone/platform/wayland/host/wayland_window.h" + +namespace ui { + +WaylandScreen::WaylandScreen(WaylandConnection* connection) + : connection_(connection), weak_factory_(this) { + DCHECK(connection_); +} + +WaylandScreen::~WaylandScreen() = default; + +void WaylandScreen::OnOutputAdded(uint32_t output_id) { + display_list_.AddDisplay(display::Display(output_id), + display::DisplayList::Type::NOT_PRIMARY); +} + +void WaylandScreen::OnOutputRemoved(uint32_t output_id) { + if (output_id == GetPrimaryDisplay().id()) { + // First, set a new primary display as required by the |display_list_|. It's + // safe to set any of the displays to be a primary one. Once the output is + // completely removed, Wayland updates geometry of other displays. And a + // display, which became the one to be nearest to the origin will become a + // primary one. + for (const auto& display : display_list_.displays()) { + if (display.id() != output_id) { + display_list_.AddOrUpdateDisplay(display, + display::DisplayList::Type::PRIMARY); + break; + } + } + } + display_list_.RemoveDisplay(output_id); +} + +void WaylandScreen::OnOutputMetricsChanged(uint32_t output_id, + const gfx::Rect& new_bounds, + int32_t device_pixel_ratio) { + display::Display changed_display(output_id); + if (!display::Display::HasForceDeviceScaleFactor()) + changed_display.set_device_scale_factor(device_pixel_ratio); + changed_display.set_bounds(new_bounds); + changed_display.set_work_area(new_bounds); + + bool is_primary = false; + display::Display display_nearest_origin = + GetDisplayNearestPoint(gfx::Point(0, 0)); + // If bounds of the nearest to origin display are empty, it must have been the + // very first and the same display added before. + if (display_nearest_origin.bounds().IsEmpty()) { + DCHECK_EQ(display_nearest_origin.id(), changed_display.id()); + is_primary = true; + } else if (changed_display.bounds().origin() < + display_nearest_origin.bounds().origin()) { + // If changed display is nearer to the origin than the previous display, + // that one must become a primary display. + is_primary = true; + } else if (changed_display.bounds().OffsetFromOrigin() == + display_nearest_origin.bounds().OffsetFromOrigin()) { + // If changed display has the same origin as the nearest to origin display, + // |changed_display| must become a primary one or it has already been the + // primary one. If a user changed positions of two displays (the second at + // x,x was set to 0,0), the second change will modify geometry of the + // display, which used to be the one nearest to the origin. + is_primary = true; + } + + display_list_.UpdateDisplay( + changed_display, is_primary ? display::DisplayList::Type::PRIMARY + : display::DisplayList::Type::NOT_PRIMARY); + + auto* wayland_window_manager = connection_->wayland_window_manager(); + for (auto* window : wayland_window_manager->GetWindowsOnOutput(output_id)) + window->UpdateBufferScale(true); +} + +base::WeakPtr WaylandScreen::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +const std::vector& WaylandScreen::GetAllDisplays() const { + return display_list_.displays(); +} + +display::Display WaylandScreen::GetPrimaryDisplay() const { + auto iter = display_list_.GetPrimaryDisplayIterator(); + DCHECK(iter != display_list_.displays().end()); + return *iter; +} + +display::Display WaylandScreen::GetDisplayForAcceleratedWidget( + gfx::AcceleratedWidget widget) const { + auto* window = connection_->wayland_window_manager()->GetWindow(widget); + // A window might be destroyed by this time on shutting down the browser. + if (!window) + return GetPrimaryDisplay(); + + const auto* parent_window = window->parent_window(); + const auto entered_outputs_ids = window->entered_outputs_ids(); + // Although spec says a surface receives enter/leave surface events on + // create/move/resize actions, this might be called right after a window is + // created, but it has not been configured by a Wayland compositor and it has + // not received enter surface events yet. Another case is when a user switches + // between displays in a single output mode - Wayland may not send enter + // events immediately, which can result in empty container of entered ids + // (check comments in WaylandWindow::RemoveEnteredOutputId). In this case, + // it's also safe to return the primary display. + // A child window will most probably enter the same display than its parent + // so we return the parent's display if there is a parent. + if (entered_outputs_ids.empty()) { + if (parent_window) + return GetDisplayForAcceleratedWidget(parent_window->GetWidget()); + return GetPrimaryDisplay(); + } + + DCHECK(!display_list_.displays().empty()); + + // A widget can be located on two or more displays. It would be better if the + // most in DIP occupied display was returned, but it's impossible to do so in + // Wayland. Thus, return the one that was used the earliest. + for (const auto& display : display_list_.displays()) { + if (display.id() == *entered_outputs_ids.begin()) + return display; + } + + NOTREACHED(); + return GetPrimaryDisplay(); +} + +gfx::Point WaylandScreen::GetCursorScreenPoint() const { + // Wayland does not provide either location of surfaces in global space + // coordinate system or location of a pointer. Instead, only locations of + // mouse/touch events are known. Given that Chromium assumes top-level windows + // are located at origin, always provide a cursor point in regards to + // surfaces' location. + // + // If a pointer is located in any of the existing wayland windows, return the + // last known cursor position. Otherwise, return such a point, which is not + // contained by any of the windows. + auto* cursor_position = connection_->wayland_cursor_position(); + if (connection_->wayland_window_manager()->GetCurrentFocusedWindow() && + cursor_position) + return cursor_position->GetCursorSurfacePoint(); + + auto* window = + connection_->wayland_window_manager()->GetWindowWithLargestBounds(); + DCHECK(window); + const gfx::Rect bounds = window->GetBounds(); + return gfx::Point(bounds.width() + 10, bounds.height() + 10); +} + +gfx::AcceleratedWidget WaylandScreen::GetAcceleratedWidgetAtScreenPoint( + const gfx::Point& point) const { + // It is safe to check only for focused windows and test if they contain the + // point or not. + auto* window = + connection_->wayland_window_manager()->GetCurrentFocusedWindow(); + if (window && window->GetBounds().Contains(point)) + return window->GetWidget(); + return gfx::kNullAcceleratedWidget; +} + +gfx::AcceleratedWidget WaylandScreen::GetLocalProcessWidgetAtPoint( + const gfx::Point& point, + const std::set& ignore) const { + auto widget = GetAcceleratedWidgetAtScreenPoint(point); + return !widget || base::Contains(ignore, widget) ? gfx::kNullAcceleratedWidget + : widget; +} + +display::Display WaylandScreen::GetDisplayNearestPoint( + const gfx::Point& point) const { + return *FindDisplayNearestPoint(display_list_.displays(), point); +} + +display::Display WaylandScreen::GetDisplayMatching( + const gfx::Rect& match_rect) const { + if (match_rect.IsEmpty()) + return GetDisplayNearestPoint(match_rect.origin()); + + const display::Display* display_matching = + display::FindDisplayWithBiggestIntersection(display_list_.displays(), + match_rect); + return display_matching ? *display_matching : GetPrimaryDisplay(); +} + +void WaylandScreen::AddObserver(display::DisplayObserver* observer) { + display_list_.AddObserver(observer); +} + +void WaylandScreen::RemoveObserver(display::DisplayObserver* observer) { + display_list_.RemoveObserver(observer); +} + +} // namespace ui diff --git a/pool/shard006/C++/0079005_QRErrorCorrectionLevel.cpp b/pool/shard006/C++/0079005_QRErrorCorrectionLevel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..277a8b55ff3d56a4ec4b0f7a2e6c2a35f69bf86e --- /dev/null +++ b/pool/shard006/C++/0079005_QRErrorCorrectionLevel.cpp @@ -0,0 +1,70 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +/* + * ErrorCorrectionLevel.cpp + * zxing + * + * Created by Christian Brunschen on 15/05/2008. + * Copyright 2008-2011 ZXing 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 + +using std::string; + +namespace zxing { +namespace qrcode { + +ErrorCorrectionLevel::ErrorCorrectionLevel(int inOrdinal, + int bits, + char const* name) : + ordinal_(inOrdinal), bits_(bits), name_(name) +{} + +ErrorCorrectionLevel::ErrorCorrectionLevel(const ErrorCorrectionLevel &other) : + ordinal_(other.ordinal()), bits_(other.bits()), name_(other.name()) +{} + +int ErrorCorrectionLevel::ordinal() const { + return ordinal_; +} + +int ErrorCorrectionLevel::bits() const { + return bits_; +} + +string const& ErrorCorrectionLevel::name() const { + return name_; +} + +ErrorCorrectionLevel::operator string const& () const { + return name_; +} + +ErrorCorrectionLevel& ErrorCorrectionLevel::forBits(int bits) { + if (bits < 0 || bits >= N_LEVELS) { + throw ReaderException("Ellegal error correction level bits"); + } + return *FOR_BITS[bits]; +} + + ErrorCorrectionLevel ErrorCorrectionLevel::L(0, 0x01, "L"); + ErrorCorrectionLevel ErrorCorrectionLevel::M(1, 0x00, "M"); + ErrorCorrectionLevel ErrorCorrectionLevel::Q(2, 0x03, "Q"); + ErrorCorrectionLevel ErrorCorrectionLevel::H(3, 0x02, "H"); +ErrorCorrectionLevel *ErrorCorrectionLevel::FOR_BITS[] = { &M, &L, &H, &Q }; +int ErrorCorrectionLevel::N_LEVELS = 4; + +} +} diff --git a/pool/shard006/C++/0079006_qmailfoldersortkey.cpp b/pool/shard006/C++/0079006_qmailfoldersortkey.cpp new file mode 100644 index 0000000000000000000000000000000000000000..462908c662641971d352b30c31cf9876c20e89b2 --- /dev/null +++ b/pool/shard006/C++/0079006_qmailfoldersortkey.cpp @@ -0,0 +1,306 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Messaging Framework. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmailfoldersortkey.h" +#include "qmailfoldersortkey_p.h" + + +/*! + \class QMailFolderSortKey + + \preliminary + \brief The QMailFolderSortKey class defines the parameters used for sorting a subset of + queried folders from the mail store. + \ingroup messaginglibrary + + A QMailFolderSortKey is composed of a folder property to sort and a sort order. + The QMailFolderSortKey class is used in conjunction with the QMailStore::queryFolders() + function to sort folder results according to the criteria defined by the sort key. + + For example: + To create a query for all folders sorted by the path in ascending order: + \code + QMailFolderSortKey sortKey(QMailFolderSortKey::path(Qt::Ascending)); + QMailIdList results = QMailStore::instance()->queryFolders(QMailFolderKey(), sortKey); + \endcode + + \sa QMailStore, QMailFolderKey +*/ + +/*! + \enum QMailFolderSortKey::Property + + This enum type describes the sortable data properties of a QMailFolder. + + \value Id The ID of the folder. + \value Path The path of the folder in native form. + \value ParentFolderId The ID of the parent folder for a given folder. + \value ParentAccountId The ID of the parent account for a given folder. + \value DisplayName The name of the folder, designed for display to users. + \value Status The status value of the folder. + \value ServerCount The number of messages reported to be on the server for the folder. + \value ServerUnreadCount The number of unread messages reported to be on the server for the folder. + \value ServerUndiscoveredCount The number of undiscovered messages reported to be on the server for the folder. +*/ + +/*! + \typedef QMailFolderSortKey::ArgumentType + + Defines the type used to represent a single sort criterion of a folder sort key. +*/ + +/*! + Create a QMailFolderSortKey with specifying matching parameters. + + A default-constructed key (one for which isEmpty() returns true) sorts no folders. + + The result of combining an empty key with a non-empty key is the same as the original + non-empty key. + + The result of combining two empty keys is an empty key. +*/ +QMailFolderSortKey::QMailFolderSortKey() + : d(new QMailFolderSortKeyPrivate()) +{ +} + +/*! \internal */ +QMailFolderSortKey::QMailFolderSortKey(Property p, Qt::SortOrder order, quint64 mask) + : d(new QMailFolderSortKeyPrivate(p, order, mask)) +{ +} + +/*! \internal */ +QMailFolderSortKey::QMailFolderSortKey(const QList &args) + : d(new QMailFolderSortKeyPrivate(args)) +{ +} + +/*! + Create a copy of the QMailFolderSortKey \a other. +*/ +QMailFolderSortKey::QMailFolderSortKey(const QMailFolderSortKey& other) + : d(new QMailFolderSortKeyPrivate()) +{ + this->operator=(other); +} + +/*! + Destroys this QMailFolderSortKey. +*/ +QMailFolderSortKey::~QMailFolderSortKey() +{ +} + +/*! + Returns a key that is the logical AND of this key and the value of key \a other. +*/ +QMailFolderSortKey QMailFolderSortKey::operator&(const QMailFolderSortKey& other) const +{ + return QMailFolderSortKey(d->arguments() + other.d->arguments()); +} + +/*! + Performs a logical AND with this key and the key \a other and assigns the result + to this key. +*/ +QMailFolderSortKey& QMailFolderSortKey::operator&=(const QMailFolderSortKey& other) +{ + *this = *this & other; + return *this; +} + +/*! + Returns \c true if the value of this key is the same as the key \a other. Returns + \c false otherwise. +*/ +bool QMailFolderSortKey::operator==(const QMailFolderSortKey& other) const +{ + return (*d == *other.d); +} + +/*! + Returns \c true if the value of this key is not the same as the key \a other. Returns + \c false otherwise. +*/ +bool QMailFolderSortKey::operator!=(const QMailFolderSortKey& other) const +{ + return !(*this == other); +} + +/*! + Assign the value of the QMailFolderSortKey \a other to this. +*/ +QMailFolderSortKey& QMailFolderSortKey::operator=(const QMailFolderSortKey& other) +{ + d = other.d; + return *this; +} + +/*! + Returns true if the key remains empty after default construction; otherwise returns false. +*/ +bool QMailFolderSortKey::isEmpty() const +{ + return d->isEmpty(); +} + +/*! + Returns the list of arguments to this QMailFolderSortKey. +*/ +const QList &QMailFolderSortKey::arguments() const +{ + return d->arguments(); +} + +/*! + \fn QMailFolderSortKey::serialize(Stream &stream) const + + Writes the contents of a QMailFolderSortKey to a \a stream. +*/ +template void QMailFolderSortKey::serialize(Stream &stream) const +{ + d->serialize(stream); +} + +/*! + \fn QMailFolderSortKey::deserialize(Stream &stream) + + Reads the contents of a QMailFolderSortKey from \a stream. +*/ +template void QMailFolderSortKey::deserialize(Stream &stream) +{ + d->deserialize(stream); +} + +/*! + Returns a key that sorts folders by their identifiers, according to \a order. + + \sa QMailFolder::id() +*/ +QMailFolderSortKey QMailFolderSortKey::id(Qt::SortOrder order) +{ + return QMailFolderSortKey(Id, order); +} + +/*! + Returns a key that sorts folders by their paths, according to \a order. + + \sa QMailFolder::path() +*/ +QMailFolderSortKey QMailFolderSortKey::path(Qt::SortOrder order) +{ + return QMailFolderSortKey(Path, order); +} + +/*! + Returns a key that sorts folders by their parent folders' identifiers, according to \a order. + + \sa QMailFolder::parentFolderId() +*/ +QMailFolderSortKey QMailFolderSortKey::parentFolderId(Qt::SortOrder order) +{ + return QMailFolderSortKey(ParentFolderId, order); +} + +/*! + Returns a key that sorts folders by their parent accounts' identifiers, according to \a order. + + \sa QMailFolder::parentAccountId() +*/ +QMailFolderSortKey QMailFolderSortKey::parentAccountId(Qt::SortOrder order) +{ + return QMailFolderSortKey(ParentAccountId, order); +} + +/*! + Returns a key that sorts folders by their display name, according to \a order. + + \sa QMailFolder::displayName() +*/ +QMailFolderSortKey QMailFolderSortKey::displayName(Qt::SortOrder order) +{ + return QMailFolderSortKey(DisplayName, order); +} + +/*! + Returns a key that sorts folders by their message count on server, according to \a order. + + \sa QMailFolder::status() +*/ +QMailFolderSortKey QMailFolderSortKey::serverCount(Qt::SortOrder order) +{ + return QMailFolderSortKey(ServerCount, order); +} + +/*! + Returns a key that sorts folders by their message unread count on server, according to \a order. + + \sa QMailFolder::status() +*/ +QMailFolderSortKey QMailFolderSortKey::serverUnreadCount(Qt::SortOrder order) +{ + return QMailFolderSortKey(ServerUnreadCount, order); +} + +/*! + Returns a key that sorts folders by their message undiscovered count on server, according to \a order. + + \sa QMailFolder::status() +*/ +QMailFolderSortKey QMailFolderSortKey::serverUndiscoveredCount(Qt::SortOrder order) +{ + return QMailFolderSortKey(ServerUndiscoveredCount, order); +} + +/*! + Returns a key that sorts folders by comparing their status value bitwise ANDed with \a mask, according to \a order. + + \sa QMailFolder::status() +*/ +QMailFolderSortKey QMailFolderSortKey::status(quint64 mask, Qt::SortOrder order) +{ + return QMailFolderSortKey(Status, order, mask); +} + + +Q_IMPLEMENT_USER_METATYPE(QMailFolderSortKey) + diff --git a/pool/shard006/C++/0079007_REGFHeader.cpp b/pool/shard006/C++/0079007_REGFHeader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb5ddc24697093a8309d0d39a3b322793a7a77f0 --- /dev/null +++ b/pool/shard006/C++/0079007_REGFHeader.cpp @@ -0,0 +1,108 @@ +/* + * + * The Sleuth Kit + * + * Copyright 2013-2015 Basis Technology Corp. + * Contact: carrier sleuthkit org + * + * 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 C++ port of the Rejistry library developed by Willi Ballenthin. + * See https://github.com/williballenthin/Rejistry for the original Java version. + */ + +/** + * \file REGFHeader.cpp + */ + +// Local includes +#include "REGFHeader.h" +#include "RejistryException.h" + +namespace Rejistry { + + + REGFHeader::REGFHeader(RegistryByteBuffer& buf, const uint32_t offset) : BinaryBlock(buf, offset) { + uint64_t magic = getDWord(offset); + + if (magic != 0x66676572) { + throw RegistryParseException("REGF magic value not found"); + } + } + + bool REGFHeader::isSynchronized() const { + return (getDWord(SEQ1_OFFSET) == getDWord(SEQ2_OFFSET)); + } + + uint32_t REGFHeader::getMajorVersion() const { + return getDWord(MAJOR_VERSION_OFFSET); + } + + uint32_t REGFHeader::getMinorVersion() const { + return getDWord(MINOR_VERSION_OFFSET); + } + + std::wstring REGFHeader::getHiveName() const { + return getUTF16String(HIVE_NAME_OFFSET, 0x40); + } + + uint32_t REGFHeader::getLastHbinOffset() const { + return getDWord(LAST_HBIN_OFFSET_OFFSET); + } + + HBIN::HBINPtrList REGFHeader::getHBINs() const { + uint32_t nextHBINOffset = FIRST_HBIN_OFFSET; + HBIN::HBINPtrList hbinList; + + do { + if (getDWord(nextHBINOffset) != 0x6E696268) { + // Terminate if this doesn't have the correct magic number. + break; + } + + HBIN * nextHBIN = new HBIN(this, _buf, getAbsoluteOffset(nextHBINOffset)); + hbinList.push_back(nextHBIN); + nextHBINOffset += nextHBIN->getRelativeOffsetNextHBIN(); + } + while (nextHBINOffset <= getLastHbinOffset()); + + return hbinList; + } + + HBIN::HBINPtr REGFHeader::getFirstHBIN() const { + if (getDWord(FIRST_HBIN_OFFSET) != 0x6E696268) { + throw RegistryParseException("HBIN magic value not found."); + } + + return new HBIN(this, _buf, getAbsoluteOffset(FIRST_HBIN_OFFSET)); + } + + /** + * @throws RegistryParseException in case of error. + */ + NKRecord::NKRecordPtr REGFHeader::getRootNKRecord() const { + int32_t firstCellOffset = (int32_t)(getDWord(FIRST_KEY_OFFSET_OFFSET)); + std::auto_ptr< HBIN > firstHBIN(getFirstHBIN()); + if (firstHBIN.get() != NULL) { + std::auto_ptr< Cell > cellPtr(firstHBIN->getCellAtOffset(firstCellOffset)); + + if (cellPtr.get() == NULL) { + throw RegistryParseException("Failed to get first cell."); + } + return cellPtr->getNKRecord(); + } + else { + throw RegistryParseException("Failed to get first HBIN."); + } + } +}; diff --git a/pool/shard006/C++/0079008_pdf_metafile_skia.cc b/pool/shard006/C++/0079008_pdf_metafile_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4027ed35d48167ea057f15118b2467f92d20605 --- /dev/null +++ b/pool/shard006/C++/0079008_pdf_metafile_skia.cc @@ -0,0 +1,247 @@ +// 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 "printing/pdf_metafile_skia.h" + +#include "base/file_descriptor_posix.h" +#include "base/file_util.h" +#include "base/hash_tables.h" +#include "base/metrics/histogram.h" +#include "base/posix/eintr_wrapper.h" +#include "base/safe_numerics.h" +#include "skia/ext/vector_platform_device_skia.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkScalar.h" +#include "third_party/skia/include/core/SkStream.h" +#include "third_party/skia/include/core/SkTypeface.h" +#include "third_party/skia/include/pdf/SkPDFDevice.h" +#include "third_party/skia/include/pdf/SkPDFDocument.h" +#include "ui/gfx/point.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" + +#if defined(OS_MACOSX) +#include "printing/pdf_metafile_cg_mac.h" +#endif + +namespace printing { + +struct PdfMetafileSkiaData { + SkRefPtr current_page_; + SkPDFDocument pdf_doc_; + SkDynamicMemoryWStream pdf_stream_; +#if defined(OS_MACOSX) + PdfMetafileCg pdf_cg_; +#endif +}; + +PdfMetafileSkia::~PdfMetafileSkia() {} + +bool PdfMetafileSkia::Init() { + return true; +} +bool PdfMetafileSkia::InitFromData(const void* src_buffer, + uint32 src_buffer_size) { + return data_->pdf_stream_.write(src_buffer, src_buffer_size); +} + +SkDevice* PdfMetafileSkia::StartPageForVectorCanvas( + const gfx::Size& page_size, const gfx::Rect& content_area, + const float& scale_factor) { + DCHECK(!page_outstanding_); + page_outstanding_ = true; + + // Adjust for the margins and apply the scale factor. + SkMatrix transform; + transform.setTranslate(SkIntToScalar(content_area.x()), + SkIntToScalar(content_area.y())); + transform.preScale(SkFloatToScalar(scale_factor), + SkFloatToScalar(scale_factor)); + + SkISize pdf_page_size = SkISize::Make(page_size.width(), page_size.height()); + SkISize pdf_content_size = + SkISize::Make(content_area.width(), content_area.height()); + SkRefPtr pdf_device = + new skia::VectorPlatformDeviceSkia(pdf_page_size, pdf_content_size, + transform); + data_->current_page_ = pdf_device; + return pdf_device.get(); +} + +bool PdfMetafileSkia::StartPage(const gfx::Size& page_size, + const gfx::Rect& content_area, + const float& scale_factor) { + NOTREACHED(); + return false; +} + +bool PdfMetafileSkia::FinishPage() { + DCHECK(data_->current_page_.get()); + + data_->pdf_doc_.appendPage(data_->current_page_.get()); + page_outstanding_ = false; + return true; +} + +bool PdfMetafileSkia::FinishDocument() { + // Don't do anything if we've already set the data in InitFromData. + if (data_->pdf_stream_.getOffset()) + return true; + + if (page_outstanding_) + FinishPage(); + + data_->current_page_ = NULL; + + int font_counts[SkAdvancedTypefaceMetrics::kNotEmbeddable_Font + 1]; + data_->pdf_doc_.getCountOfFontTypes(font_counts); + for (int type = 0; + type <= SkAdvancedTypefaceMetrics::kNotEmbeddable_Font; + type++) { + for (int count = 0; count < font_counts[type]; count++) { + UMA_HISTOGRAM_ENUMERATION( + "PrintPreview.FontType", type, + SkAdvancedTypefaceMetrics::kNotEmbeddable_Font + 1); + } + } + + return data_->pdf_doc_.emitPDF(&data_->pdf_stream_); +} + +uint32 PdfMetafileSkia::GetDataSize() const { + return base::checked_numeric_cast(data_->pdf_stream_.getOffset()); +} + +bool PdfMetafileSkia::GetData(void* dst_buffer, + uint32 dst_buffer_size) const { + if (dst_buffer_size < GetDataSize()) + return false; + + SkAutoDataUnref data(data_->pdf_stream_.copyToData()); + memcpy(dst_buffer, data->bytes(), dst_buffer_size); + return true; +} + +bool PdfMetafileSkia::SaveTo(const base::FilePath& file_path) const { + DCHECK_GT(data_->pdf_stream_.getOffset(), 0U); + SkAutoDataUnref data(data_->pdf_stream_.copyToData()); + if (file_util::WriteFile(file_path, + reinterpret_cast(data->data()), + GetDataSize()) != static_cast(GetDataSize())) { + DLOG(ERROR) << "Failed to save file " << file_path.value().c_str(); + return false; + } + return true; +} + +gfx::Rect PdfMetafileSkia::GetPageBounds(unsigned int page_number) const { + // TODO(vandebo) add a method to get the page size for a given page to + // SkPDFDocument. + NOTIMPLEMENTED(); + return gfx::Rect(); +} + +unsigned int PdfMetafileSkia::GetPageCount() const { + // TODO(vandebo) add a method to get the number of pages to SkPDFDocument. + NOTIMPLEMENTED(); + return 0; +} + +gfx::NativeDrawingContext PdfMetafileSkia::context() const { + NOTREACHED(); + return NULL; +} + +#if defined(OS_WIN) +bool PdfMetafileSkia::Playback(gfx::NativeDrawingContext hdc, + const RECT* rect) const { + NOTREACHED(); + return false; +} + +bool PdfMetafileSkia::SafePlayback(gfx::NativeDrawingContext hdc) const { + NOTREACHED(); + return false; +} + +HENHMETAFILE PdfMetafileSkia::emf() const { + NOTREACHED(); + return NULL; +} +#elif defined(OS_MACOSX) +/* TODO(caryclark): The set up of PluginInstance::PrintPDFOutput may result in + rasterized output. Even if that flow uses PdfMetafileCg::RenderPage, + the drawing of the PDF into the canvas may result in a rasterized output. + PDFMetafileSkia::RenderPage should be not implemented as shown and instead + should do something like the following CL in PluginInstance::PrintPDFOutput: +http://codereview.chromium.org/7200040/diff/1/webkit/plugins/ppapi/ppapi_plugin_instance.cc +*/ +bool PdfMetafileSkia::RenderPage(unsigned int page_number, + CGContextRef context, + const CGRect rect, + const MacRenderPageParams& params) const { + DCHECK_GT(data_->pdf_stream_.getOffset(), 0U); + if (data_->pdf_cg_.GetDataSize() == 0) { + SkAutoDataUnref data(data_->pdf_stream_.copyToData()); + data_->pdf_cg_.InitFromData(data->bytes(), data->size()); + } + return data_->pdf_cg_.RenderPage(page_number, context, rect, params); +} +#endif + +#if defined(OS_CHROMEOS) +bool PdfMetafileSkia::SaveToFD(const base::FileDescriptor& fd) const { + DCHECK_GT(data_->pdf_stream_.getOffset(), 0U); + + if (fd.fd < 0) { + DLOG(ERROR) << "Invalid file descriptor!"; + return false; + } + + bool result = true; + SkAutoDataUnref data(data_->pdf_stream_.copyToData()); + if (file_util::WriteFileDescriptor(fd.fd, + reinterpret_cast(data->data()), + GetDataSize()) != + static_cast(GetDataSize())) { + DLOG(ERROR) << "Failed to save file with fd " << fd.fd; + result = false; + } + + if (fd.auto_close) { + if (HANDLE_EINTR(close(fd.fd)) < 0) { + DPLOG(WARNING) << "close"; + result = false; + } + } + return result; +} +#endif + +PdfMetafileSkia::PdfMetafileSkia() + : data_(new PdfMetafileSkiaData), + page_outstanding_(false) { +} + +PdfMetafileSkia* PdfMetafileSkia::GetMetafileForCurrentPage() { + SkPDFDocument pdf_doc(SkPDFDocument::kDraftMode_Flags); + SkDynamicMemoryWStream pdf_stream; + if (!pdf_doc.appendPage(data_->current_page_.get())) + return NULL; + + if (!pdf_doc.emitPDF(&pdf_stream)) + return NULL; + + SkAutoDataUnref data(pdf_stream.copyToData()); + if (data->size() == 0) + return NULL; + + PdfMetafileSkia* metafile = new PdfMetafileSkia; + metafile->InitFromData(data->bytes(), + base::checked_numeric_cast(data->size())); + return metafile; +} + +} // namespace printing diff --git a/pool/shard006/C++/0079009_cornerhandler.cpp b/pool/shard006/C++/0079009_cornerhandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03da006771743e6a492fdc4fa851658736da56c8 --- /dev/null +++ b/pool/shard006/C++/0079009_cornerhandler.cpp @@ -0,0 +1,193 @@ +/******************************************************************* + +Part of the Fritzing project - http://fritzing.org +Copyright (c) 2007-2014 Fachhochschule Potsdam - http://fh-potsdam.de + +Fritzing 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. + +Fritzing 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 Fritzing. If not, see . + +******************************************************************** + +$Revision: 6904 $: +$Author: irascibl@gmail.com $: +$Date: 2013-02-26 16:26:03 +0100 (Di, 26. Feb 2013) $ + +********************************************************************/ + +#include +#include +#include +#include + +#include "cornerhandler.h" +#include "connectorrectangle.h" +#include "../debugdialog.h" + +QHash CornerHandler::pixmapHash; +double CornerHandler::Size = 4; + +CornerHandler::CornerHandler(ConnectorRectangle *parent, QGraphicsItem* parentItem, Qt::Corner corner) + : QGraphicsRectItem(parentItem) +{ + m_parent = parent; + m_corner = corner; + m_resizing = false; + + initPixmapHash(); + + setFlag(QGraphicsItem::ItemIgnoresTransformations); + setFlag(QGraphicsItem::ItemClipsChildrenToShape); + setAcceptHoverEvents(true); + + doSetVisible(false); +} + +void CornerHandler::doSetVisible(bool visible) { + if(visible) { + setBrush(QBrush(QColor::fromRgb(0,250,0))); + } else { + setBrush(QBrush()); + } + m_isVisible = visible; +} + +void CornerHandler::initPixmapHash() { + if(pixmapHash.isEmpty()) { + pixmapHash[Qt::TopLeftCorner] = + QPixmap(":/resources/images/itemselection/cornerHandlerActiveTopLeft.png"); + pixmapHash[Qt::TopRightCorner] = + QPixmap(":/resources/images/itemselection/cornerHandlerActiveTopRight.png"); + pixmapHash[Qt::BottomRightCorner] = + QPixmap(":/resources/images/itemselection/cornerHandlerActiveBottomRight.png"); + pixmapHash[Qt::BottomLeftCorner] = + QPixmap(":/resources/images/itemselection/cornerHandlerActiveBottomLeft.png"); + } +} + +void CornerHandler::resize(const QPointF &mousePos) { + QRectF rect = m_parent->owner()->boundingRect(); + + double oldX1 = rect.x(); + double oldY1 = rect.y(); + double oldX2 = oldX1+rect.width(); + double oldY2 = oldY1+rect.height(); + double newX = mapToItem(m_parent->owner(),mousePos).x(); + double newY = mapToItem(m_parent->owner(),mousePos).y(); + + switch(m_corner) { + case Qt::TopLeftCorner: + m_parent->resizeRect(newX,newY,oldX2,oldY2); break; + case Qt::TopRightCorner: + m_parent->resizeRect(oldX1,newY,newX,oldY2); break; + case Qt::BottomRightCorner: + m_parent->resizeRect(oldX1,oldY1,newX,newY); break; + case Qt::BottomLeftCorner: + m_parent->resizeRect(newX,oldY1,oldX2,newY); break; + default: break; + } +} + +Qt::Corner CornerHandler::corner() { + return m_corner; +} + +void CornerHandler::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { + if(m_parent->isResizable() && m_resizing) { + resize(event->pos()); + scene()->update(); + } else { + QGraphicsRectItem::mouseMoveEvent(event); + } +} + +void CornerHandler::mousePressEvent(QGraphicsSceneMouseEvent *event) { + if(m_isVisible) { + if(m_parent->isResizable()) { + m_parent->resizingStarted(); + m_resizing = true; + setFlag(QGraphicsItem::ItemIgnoresTransformations,false); + } else { + QGraphicsRectItem::mousePressEvent(event); + } + } else { + QGraphicsRectItem::mousePressEvent(event); + } +} + +void CornerHandler::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { + if(m_parent->isResizable() && m_resizing) { + setFlag(QGraphicsItem::ItemIgnoresTransformations,true); + m_resizing = false; + m_parent->resizingFinished(); + } + QGraphicsRectItem::mouseReleaseEvent(event); +} + +void CornerHandler::hoverEnterEvent(QGraphicsSceneHoverEvent * event) { + QGraphicsRectItem::hoverEnterEvent(event); + if(m_isVisible && m_parent->isResizable()) { + setCursor(QCursor(cursorForCorner(m_corner))); + } +} + +void CornerHandler::hoverLeaveEvent(QGraphicsSceneHoverEvent * event) { + if(m_isVisible && m_parent->isResizable()) { + unsetCursor(); + } + QGraphicsRectItem::hoverLeaveEvent(event); +} + +Qt::CursorShape CornerHandler::cursorForCorner(Qt::Corner corner) { + Qt::CursorShape cursorShape = Qt::SizeFDiagCursor; + switch(corner) { + case Qt::TopLeftCorner: + case Qt::BottomRightCorner: + cursorShape = Qt::SizeFDiagCursor; + break; + case Qt::TopRightCorner: + case Qt::BottomLeftCorner: + cursorShape = Qt::SizeBDiagCursor; + break; + default: + throw "CornerHandler::cursorForCorner unknown corner"; + } + return cursorShape; +} + +bool CornerHandler::isBeingDragged() { + return m_resizing; +} + +void CornerHandler::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { + Q_UNUSED(option); + Q_UNUSED(widget); + if(m_isVisible && m_parent->isResizable()) { + doPaint(painter); + } +} + +void CornerHandler::doPaint(QPainter *painter) { + if(m_isVisible) { + QRectF trgRect = m_parent->handlerRect(m_corner); + //DebugDialog::debug("handler rect ", trgRect); + QPixmap pm = pixmapHash[m_corner]; + QRectF srcRect = QRectF(pm.rect()); + //painter->drawRect(rect); + painter->drawPixmap(trgRect,pm,srcRect); + } +} + +void CornerHandler::doSetRect(const QRectF &newRect) { + setFlag(QGraphicsItem::ItemIgnoresTransformations,false); + setRect(mapFromParent(newRect).boundingRect()); +} diff --git a/pool/shard006/C++/0079011_WebSocketClient.cpp b/pool/shard006/C++/0079011_WebSocketClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6abb1a4635e17510ed9f74c8047f711ce6b2b60b --- /dev/null +++ b/pool/shard006/C++/0079011_WebSocketClient.cpp @@ -0,0 +1,132 @@ +/******************************************************************************* +The content of this file includes portions of the AUDIOKINETIC Wwise Technology +released in source code form as part of the SDK installer package. + +Commercial License Usage + +Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology +may use this file in accordance with the end user license agreement provided +with the software or, alternatively, in accordance with the terms contained in a +written agreement between you and Audiokinetic Inc. + +Copyright (c) 2020 Audiokinetic Inc. +*******************************************************************************/ + +#include "AK/WwiseAuthoringAPI/AkAutobahn/WebSocketClient.h" + +#if defined(_WIN32) || defined(_WIN64) +#include +#include +#endif + +#include "AK/WwiseAuthoringAPI/AkAutobahn/civetweb.h" + +#include "AK/WwiseAuthoringAPI/AkAutobahn/IWebSocketClientHandler.h" + +namespace AK +{ + namespace WwiseAuthoringAPI + { + bool WebSocketClient::m_isNetworkInitialized = false; + + bool WebSocketClient::InitializeNetwork() + { +#if defined(_WIN32) || defined(_WIN64) + + WSADATA data; + return (WSAStartup(MAKEWORD(2, 2), &data) == 0); +#else + return true; +#endif + } + + int WebSocketClient::OnMessage( + mg_connection *conn, + int flags, + char *data, + size_t data_len, + void *user_data) + { + mg_context* ctx = mg_get_context(conn); + WebSocketClient* that = reinterpret_cast(mg_get_user_data(ctx)); + AKASSERT(that != nullptr); + that->m_handler->OnMessage(std::string(data, data_len)); + + return 1; + } + + void WebSocketClient::OnClose(const struct mg_connection* conn, void* user_data) + { + mg_context* ctx = mg_get_context(conn); + WebSocketClient* that = reinterpret_cast(mg_get_user_data(ctx)); + AKASSERT(that != nullptr); + + if (that->m_connection != nullptr) + { + that->m_handler->OnConnectionLost(); + } + } + + bool WebSocketClient::SendUTF8(const std::string& message, std::string& out_errorMessage) + { + if (m_connection == nullptr) + { + out_errorMessage = "Could not send message, the connection is not established."; + return false; + } + + AKASSERT(!message.empty()); + int bytesSent = mg_websocket_client_write(m_connection, WEBSOCKET_OPCODE_TEXT, message.c_str(), message.length()); + + if (bytesSent != message.length()) + { + out_errorMessage = "Could not send websocket message."; + return false; + } + + return true; + } + + bool WebSocketClient::Connect(const char* host, const int port) + { + AKASSERT(host != nullptr); + AKASSERT(host[0] != 0); + AKASSERT(port != 0); + + if (!EnsureNetworkInit()) + { + return false; + } + + char errorBuffer[256]; + + /* Then connect a first client */ + m_connection = mg_connect_websocket_client( + host, + port, + 0, + errorBuffer, + sizeof(errorBuffer), + "/waapi", + NULL, + OnMessage, + OnClose, + this); + + return (m_connection != nullptr); + } + + void WebSocketClient::Close() + { + if (m_connection != nullptr) + { + // Make sure we don't call OnClose when explicitly closing. + auto tmpConnection = m_connection; + m_connection = nullptr; + // There is a thread join in mg_close_connection, thus we are guaranteed + // that OnClose callback has completed before leaving Close. + mg_close_connection(tmpConnection); + } + } + } +} diff --git a/pool/shard006/C++/0079012_valid_parentheses_unittest.cc b/pool/shard006/C++/0079012_valid_parentheses_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c79fb8bfc9b1759766ca4e864678ed2a490a8e9 --- /dev/null +++ b/pool/shard006/C++/0079012_valid_parentheses_unittest.cc @@ -0,0 +1,29 @@ +#include +using namespace std; + +#include + +#include "valid_parentheses.h" + +namespace { + TEST(ValidParenthesesTest, Case1) { + string s = ""; + ValidParentheses solution; + + EXPECT_TRUE(solution.isValid(s)); + }; + + TEST(ValidPalindromeTest, Case2) { + string s = "()[]{}"; + ValidParentheses solution; + + EXPECT_TRUE(solution.isValid(s)); + }; + + TEST(ValidPalindromeTest, Case3) { + string s = "([)]"; + ValidParentheses solution; + + EXPECT_FALSE(solution.isValid(s)); + }; +} \ No newline at end of file diff --git a/pool/shard006/C++/0079021_piercingpointdialog.cpp b/pool/shard006/C++/0079021_piercingpointdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c70f94943d286089e1aeb8d19de885d3acbe4bfd --- /dev/null +++ b/pool/shard006/C++/0079021_piercingpointdialog.cpp @@ -0,0 +1,168 @@ +// + +#include "piercingpointdialog.h" +#include "ui_piercingpointdialog.h" + +#include +#include +#include + +#include + +#include + +PiercingPointDialog::PiercingPointDialog(QWidget *parent) : + QDialog(parent), + logger("PiercingPointDialog"), + ui(new Ui::PiercingPointDialog), + correctGain(false), + useROI(false) +{ + ui->setupUi(this); + ui->widgetEstimationROI->setROIColor("limegreen"); + ui->widgetEstimationROI->setAutoHideROI(true); + ui->widgetEstimationROI->registerViewer(ui->viewer); +} + +PiercingPointDialog::~PiercingPointDialog() +{ + delete ui; +} + +int PiercingPointDialog::exec(ReconConfig &config) +{ + roi = config.ProjectionInfo.projection_roi; + + position.first = config.ProjectionInfo.fpPoint[0]; + position.second = config.ProjectionInfo.fpPoint[1]; + + ProjectionReader reader; + + try { + ob=reader.Read(config.ProjectionInfo.sReferencePath, + config.ProjectionInfo.sOBFileMask, + config.ProjectionInfo.nOBFirstIndex, + config.ProjectionInfo.eFlip, + config.ProjectionInfo.eRotate, + 1, + {}); + } + catch (ReconException &e) + { + QMessageBox::critical(this,"Load error","Could not load open beam image"); + return 1; + } + catch (kipl::base::KiplException &e) + { + QMessageBox::critical(this,"Load error","Could not load open beam image"); + return 1; + } + catch (std::exception &e) + { + QMessageBox::critical(this,"Load error","Could not load open beam image"); + return 1; + } + catch (...) + { + QMessageBox::critical(this,"Load error","Could not load open beam image"); + return 1; + } + + try { + dc=reader.Read(config.ProjectionInfo.sReferencePath, + config.ProjectionInfo.sDCFileMask, + config.ProjectionInfo.nDCFirstIndex, + config.ProjectionInfo.eFlip, + config.ProjectionInfo.eRotate, + 1, + {}); + } + catch (ReconException &e) + { + QMessageBox::critical(this,"Load error","Could not load dark current image"); + return 1; + } + catch (kipl::base::KiplException &e) + { + QMessageBox::critical(this,"Load error","Could not load dark current image"); + return 1; + } + catch (std::exception &e) + { + QMessageBox::critical(this,"Load error","Could not load dark current image"); + return 1; + } + catch (...) + { + QMessageBox::critical(this,"Load error","Could not load dark current image"); + return 1; + } + + UpdateDialog(); + ui->viewer->set_image(ob.GetDataPtr(),ob.dims()); + + int res=QDialog::exec(); + + if (res==QDialog::Accepted) { + UpdateConfig(); + } + + return res; +} + +void PiercingPointDialog::on_checkBox_useROI_toggled(bool checked) +{ + ui->widgetEstimationROI->setVisible(checked); + useROI=checked; +} + +void PiercingPointDialog::UpdateConfig() +{ + useROI = ui->checkBox_useROI->isChecked(); + correctGain = ui->checkBox_gainCorrection->isChecked(); + ui->widgetEstimationROI->getROI(roi); + + position.first = ui->doubleSpinBox_posX->value(); + position.second = ui->doubleSpinBox_posY->value(); +} + +void PiercingPointDialog::UpdateDialog() +{ + ui->checkBox_useROI->setChecked(useROI); + on_checkBox_useROI_toggled(useROI); + ui->checkBox_gainCorrection->setChecked(correctGain); + ui->widgetEstimationROI->setROI(roi); + + ui->doubleSpinBox_posX->setValue(position.first); + ui->doubleSpinBox_posY->setValue(position.second); +} + +void PiercingPointDialog::on_pushButton_estimate_clicked() +{ + ImagingAlgorithms::PiercingPointEstimator pe; + + UpdateConfig(); + logger(logger.LogMessage,"Pre estimate"); + + if (useROI) + position=pe(ob,dc,correctGain, roi ); + else + position=pe(ob,dc,correctGain, {} ); + + logger(logger.LogMessage,"post estimate"); + std::ostringstream msg; + msg<<"Found pp at ["<viewer->set_marker(QtAddons::QMarker(QtAddons::PlotGlyph_Plus,pos,QColor("red"),10),0); + } + else { + logger(logger.LogWarning,"Estimated PP outside image, will not be marked."); + } +} diff --git a/pool/shard006/C++/0079023_biosig_reader.cpp b/pool/shard006/C++/0079023_biosig_reader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c914aae6bdecdef259f270c8b1ea3861319eeaf --- /dev/null +++ b/pool/shard006/C++/0079023_biosig_reader.cpp @@ -0,0 +1,281 @@ +#include "biosig_reader.h" +#include "biosig_basic_header.h" +#include "file_handler_factory_registrator.h" +#include "gui/progress_bar.h" +#include "base/fixed_data_block.h" + + +#include "biosig.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace std; + +namespace SigViewer_ +{ + +//----------------------------------------------------------------------------- +FILE_SIGNAL_READER_REGISTRATION(gdf, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(edf, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(bdf, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(dat, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(cnt, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(vhdr, BioSigReader); +FILE_SIGNAL_READER_REGISTRATION(bkr, BioSigReader); + +FILE_SIGNAL_READER_REGISTRATION(evt, BioSigReader); + +FILE_SIGNAL_READER_DEFAULT_REGISTRATION(BioSigReader); + +//----------------------------------------------------------------------------- +BioSigReader::BioSigReader() : + basic_header_ (0), + biosig_header_ (0), + buffered_all_channels_ (false), + buffered_all_events_ (false) +{ + qDebug () << "Constructed BioSigReader"; + // nothing to do here +} + +//----------------------------------------------------------------------------- +BioSigReader::~BioSigReader() +{ + doClose(); +} + +//----------------------------------------------------------------------------- +QPair BioSigReader::createInstance (QString const& file_path) +{ + BioSigReader* reader (new BioSigReader); + if (file_path.section('.', -1) == "evt") + reader->buffered_all_channels_ = true; + QString error = reader->open (file_path); + if (error.size() > 0) + { + qDebug () << error; + //QMessageBox::critical(0, QObject::tr("Error"), error); + return QPair (0, error); + } + else + return QPair (reader, ""); +} + + +//----------------------------------------------------------------------------- +void BioSigReader::doClose () const +{ + if (biosig_header_) + { + sclose (biosig_header_); + destructHDR (biosig_header_); + } + biosig_header_ = 0; +} + +//----------------------------------------------------------------------------- +QSharedPointer BioSigReader::getSignalData (ChannelID channel_id, + unsigned start_sample, + unsigned length) const +{ + QMutexLocker lock (&mutex_); + + if (!buffered_all_channels_) + bufferAllChannels(); + + if (!channel_map_.contains(channel_id)) + return QSharedPointer (0); + + if (length == basic_header_->getNumberOfSamples() && + start_sample == 0) + return channel_map_[channel_id]; + else + return channel_map_[channel_id]->createSubBlock (start_sample, length); +} + +//----------------------------------------------------------------------------- +QList > BioSigReader::getEvents () const +{ + QMutexLocker lock (&mutex_); + QList > empty_list; + if (!biosig_header_) + return empty_list; + + if (!buffered_all_events_) + bufferAllEvents(); + + return events_; +} + +//----------------------------------------------------------------------------- +QString BioSigReader::open (QString const& file_name) +{ + + QMutexLocker lock (&mutex_); + return loadFixedHeader (file_name); +} + +//----------------------------------------------------------------------------- +QString BioSigReader::loadFixedHeader(const QString& file_name) +{ + QMutexLocker locker (&biosig_access_lock_); + char *c_file_name = new char[file_name.length() + 1]; + strcpy (c_file_name, file_name.toLocal8Bit ().data()); + c_file_name[file_name.length()] = '\0'; + + tzset(); + + // set flags + if(biosig_header_==NULL) + { + biosig_header_ = constructHDR (0,0); + biosig_header_->FLAG.UCAL = 0; + biosig_header_->FLAG.OVERFLOWDETECTION = 0; + } + + biosig_header_ = sopen(c_file_name, "r", biosig_header_ ); + + basic_header_ = QSharedPointer + (new BiosigBasicHeader (biosig_header_, file_name)); + + /// waldesel: REMOVE OLD STUFF from here downwards + /// and move it into BiosigBasicHeader!!! + if (biosig_header_ == NULL || serror()) + { + sclose (biosig_header_); + destructHDR(biosig_header_); + biosig_header_ = 0; + delete c_file_name; + return "file not supported"; + } + + // (C) 2008 AS: EVENT.DUR and EVENT.CHN are optional in SOPEN, but SigViewer needs them. + convert2to4_eventtable(biosig_header_); + + //hdr2ascii(biosig_header_,stdout,4); + + delete c_file_name; + c_file_name = 0; + + uint16_t NS=0; // count number of selected channels - status channels are already converted to event table + for (uint16_t k=0; kNS; k++) + { + if (biosig_header_->CHANNEL[k].OnOff) NS++; + } + + basic_header_->setNumberEvents(biosig_header_->EVENT.N); + + // Hack Hack: Transforming Events to have the same sample rate as the signals + /*if (biosig_header_->EVENT.SampleRate) + basic_header_->setEventSamplerate(biosig_header_->EVENT.SampleRate); + else*/ + basic_header_->setEventSamplerate(biosig_header_->SampleRate); + +//#ifdef CHOLMOD_H +// if (biosig_header_->Calib==NULL) { +//#endif +// uint16_t chan=0; +// for (uint16_t channel_index = 0; channel_index < biosig_header_->NS; ++channel_index) +// if (biosig_header_->CHANNEL[channel_index].OnOff) // show only selected channels - status channels are not shown. +// { +// SignalChannel* channel = new SignalChannel(chan++, +// biosig_header_->SPR, +// biosig_header_->CHANNEL[channel_index]); +// basic_header_->addChannel(channel); +// } +//#ifdef CHOLMOD_H +// } else +// for (uint16_t channel_index = 0; channel_index < biosig_header_->Calib->ncol; ++channel_index) +// { +// SignalChannel* channel = new SignalChannel(channel_index, +// biosig_header_->SPR, +// biosig_header_->rerefCHANNEL[channel_index]); +// basic_header_->addChannel(channel); +// } +//#endif + return ""; +} + +//----------------------------------------------------------------------------- +QSharedPointer BioSigReader::getBasicHeader () +{ + //QMutexLocker lock (&mutex_); + return basic_header_; +} + +//----------------------------------------------------------------------------- +void BioSigReader::bufferAllChannels () const +{ + uint32 length = biosig_header_->NRec * biosig_header_->SPR; + biosig_data_type* read_data = new biosig_data_type[length]; + + biosig_header_->FLAG.ROW_BASED_CHANNELS = 0; + + for (unsigned channel_id_sub = 0; channel_id_sub < basic_header_->getNumberChannels(); ++channel_id_sub) + biosig_header_->CHANNEL[channel_id_sub].OnOff = 0; + + QString progress_name = QObject::tr("Loading data..."); + + for (unsigned channel_id = 0; channel_id < basic_header_->getNumberChannels(); + ++channel_id) + { + ProgressBar::instance().increaseValue (1, progress_name); + if (channel_id > 0) + biosig_header_->CHANNEL[channel_id-1].OnOff = 0; + biosig_header_->CHANNEL[channel_id].OnOff = 1; + + sread (read_data, 0, length / biosig_header_->SPR, biosig_header_); + + QSharedPointer > raw_data (new QVector (basic_header_->getNumberOfSamples())); + + for (unsigned data_index = 0; data_index < basic_header_->getNumberOfSamples(); data_index++) + raw_data->operator [](data_index) = read_data[data_index]; + + QSharedPointer data_block (new FixedDataBlock (raw_data, + basic_header_->getSampleRate())); + channel_map_[channel_id] = data_block; + } + + buffered_all_channels_ = true; + if (buffered_all_events_) + doClose(); + delete[] read_data; +} + +//------------------------------------------------------------------------- +void BioSigReader::bufferAllEvents () const +{ + unsigned number_events = biosig_header_->EVENT.N; + for (unsigned index = 0; index < number_events; index++) + { + // Hack Hack: Transforming Events to have the same sample rate as the signals + double rate_transition = basic_header_->getEventSamplerate() / biosig_header_->EVENT.SampleRate; + QSharedPointer event (new SignalEvent (biosig_header_->EVENT.POS[index] * rate_transition, + biosig_header_->EVENT.TYP[index], + biosig_header_->EVENT.SampleRate * rate_transition)); + if (biosig_header_->EVENT.CHN) + { + if (biosig_header_->EVENT.CHN[index] == 0) + event->setChannel (UNDEFINED_CHANNEL); + else + event->setChannel (biosig_header_->EVENT.CHN[index] - 1); + event->setDuration (biosig_header_->EVENT.DUR[index] * rate_transition); + } + events_.append (event); + } + + buffered_all_events_ = true; + if (buffered_all_channels_) + doClose(); +} + +} diff --git a/pool/shard006/C++/0079033_ex11_08.cc b/pool/shard006/C++/0079033_ex11_08.cc new file mode 100644 index 0000000000000000000000000000000000000000..90e88fd6d6d0d2bf0b1a642b61005c41ae913b54 --- /dev/null +++ b/pool/shard006/C++/0079033_ex11_08.cc @@ -0,0 +1,31 @@ +/**************************************************************************** + * + * Copyright (c) 2016 Henry Zhang. All rights reserved. + * + ****************************************************************************/ + +/** + * @file ex11_08.cc + * + * Exercise 11.08 // Write a program that stores the excluded words in a vector + * instead of in a set. What are the advantages to using a set? + * @author Herny Zhang + */ + + +#include +#include +#include +#include + +int main(int argc, char const *argv[]) +{ + std::vector exclude = { "aa", "bb", "bb", "cc", "dd", "ee", "ff" }; + for (std::string word; std::cout << "Enter plz:\n", std::cin >> word; ) { + auto is_excluded = std::binary_search(exclude.cbegin(), exclude.cend(), word); + auto reply = is_excluded ? "excluded" : "not excluded"; + std::cout << reply << std::endl; + } + + return 0; +} diff --git a/pool/shard006/C++/0079035_HexagonVectorPrint.cpp b/pool/shard006/C++/0079035_HexagonVectorPrint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65a8dcd75bdca430acd9d000fd90aa0a61bb7548 --- /dev/null +++ b/pool/shard006/C++/0079035_HexagonVectorPrint.cpp @@ -0,0 +1,208 @@ +//===- HexagonVectorPrint.cpp - Generate vector printing instructions -----===// +// +// 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 pass adds the capability to generate pseudo vector/predicate register +// printing instructions. These pseudo instructions should be used with the +// simulator, NEVER on hardware. +// +//===----------------------------------------------------------------------===// + +#include "HexagonInstrInfo.h" +#include "HexagonSubtarget.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/CodeGen/MachineBasicBlock.h" +#include "llvm/CodeGen/MachineFunction.h" +#include "llvm/CodeGen/MachineFunctionPass.h" +#include "llvm/CodeGen/MachineInstr.h" +#include "llvm/CodeGen/MachineInstrBuilder.h" +#include "llvm/CodeGen/MachineOperand.h" +#include "llvm/CodeGen/TargetOpcodes.h" +#include "llvm/IR/DebugLoc.h" +#include "llvm/IR/InlineAsm.h" +#include "llvm/Pass.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include +#include + +using namespace llvm; + +#define DEBUG_TYPE "hexagon-vector-print" + +static cl::opt TraceHexVectorStoresOnly("trace-hex-vector-stores-only", + cl::Hidden, cl::ZeroOrMore, cl::init(false), + cl::desc("Enables tracing of vector stores")); + +namespace llvm { + +FunctionPass *createHexagonVectorPrint(); +void initializeHexagonVectorPrintPass(PassRegistry&); + +} // end namespace llvm + +namespace { + +class HexagonVectorPrint : public MachineFunctionPass { + const HexagonSubtarget *QST = nullptr; + const HexagonInstrInfo *QII = nullptr; + const HexagonRegisterInfo *QRI = nullptr; + +public: + static char ID; + + HexagonVectorPrint() : MachineFunctionPass(ID) { + initializeHexagonVectorPrintPass(*PassRegistry::getPassRegistry()); + } + + StringRef getPassName() const override { return "Hexagon VectorPrint pass"; } + + bool runOnMachineFunction(MachineFunction &Fn) override; +}; + +} // end anonymous namespace + +char HexagonVectorPrint::ID = 0; + +static bool isVecReg(unsigned Reg) { + return (Reg >= Hexagon::V0 && Reg <= Hexagon::V31) + || (Reg >= Hexagon::W0 && Reg <= Hexagon::W15) + || (Reg >= Hexagon::Q0 && Reg <= Hexagon::Q3); +} + +static std::string getStringReg(unsigned R) { + if (R >= Hexagon::V0 && R <= Hexagon::V31) { + static const char* S[] = { "20", "21", "22", "23", "24", "25", "26", "27", + "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", + "30", "31", "32", "33", "34", "35", "36", "37", + "38", "39", "3a", "3b", "3c", "3d", "3e", "3f"}; + return S[R-Hexagon::V0]; + } + if (R >= Hexagon::Q0 && R <= Hexagon::Q3) { + static const char* S[] = { "00", "01", "02", "03"}; + return S[R-Hexagon::Q0]; + + } + llvm_unreachable("valid vreg"); +} + +static void addAsmInstr(MachineBasicBlock *MBB, unsigned Reg, + MachineBasicBlock::instr_iterator I, + const DebugLoc &DL, const HexagonInstrInfo *QII, + MachineFunction &Fn) { + std::string VDescStr = ".long 0x1dffe0" + getStringReg(Reg); + const char *cstr = Fn.createExternalSymbolName(VDescStr); + unsigned ExtraInfo = InlineAsm::Extra_HasSideEffects; + BuildMI(*MBB, I, DL, QII->get(TargetOpcode::INLINEASM)) + .addExternalSymbol(cstr) + .addImm(ExtraInfo); +} + +static bool getInstrVecReg(const MachineInstr &MI, unsigned &Reg) { + if (MI.getNumOperands() < 1) return false; + // Vec load or compute. + if (MI.getOperand(0).isReg() && MI.getOperand(0).isDef()) { + Reg = MI.getOperand(0).getReg(); + if (isVecReg(Reg)) + return !TraceHexVectorStoresOnly; + } + // Vec store. + if (MI.mayStore() && MI.getNumOperands() >= 3 && MI.getOperand(2).isReg()) { + Reg = MI.getOperand(2).getReg(); + if (isVecReg(Reg)) + return true; + } + // Vec store post increment. + if (MI.mayStore() && MI.getNumOperands() >= 4 && MI.getOperand(3).isReg()) { + Reg = MI.getOperand(3).getReg(); + if (isVecReg(Reg)) + return true; + } + return false; +} + +bool HexagonVectorPrint::runOnMachineFunction(MachineFunction &Fn) { + bool Changed = false; + QST = &Fn.getSubtarget(); + QRI = QST->getRegisterInfo(); + QII = QST->getInstrInfo(); + std::vector VecPrintList; + for (auto &MBB : Fn) + for (auto &MI : MBB) { + if (MI.isBundle()) { + MachineBasicBlock::instr_iterator MII = MI.getIterator(); + for (++MII; MII != MBB.instr_end() && MII->isInsideBundle(); ++MII) { + if (MII->getNumOperands() < 1) + continue; + unsigned Reg = 0; + if (getInstrVecReg(*MII, Reg)) { + VecPrintList.push_back((&*MII)); + LLVM_DEBUG(dbgs() << "Found vector reg inside bundle \n"; + MII->dump()); + } + } + } else { + unsigned Reg = 0; + if (getInstrVecReg(MI, Reg)) { + VecPrintList.push_back(&MI); + LLVM_DEBUG(dbgs() << "Found vector reg \n"; MI.dump()); + } + } + } + + Changed = !VecPrintList.empty(); + if (!Changed) + return Changed; + + for (auto *I : VecPrintList) { + DebugLoc DL = I->getDebugLoc(); + MachineBasicBlock *MBB = I->getParent(); + LLVM_DEBUG(dbgs() << "Evaluating V MI\n"; I->dump()); + unsigned Reg = 0; + if (!getInstrVecReg(*I, Reg)) + llvm_unreachable("Need a vector reg"); + MachineBasicBlock::instr_iterator MII = I->getIterator(); + if (I->isInsideBundle()) { + LLVM_DEBUG(dbgs() << "add to end of bundle\n"; I->dump()); + while (MBB->instr_end() != MII && MII->isInsideBundle()) + MII++; + } else { + LLVM_DEBUG(dbgs() << "add after instruction\n"; I->dump()); + MII++; + } + if (MBB->instr_end() == MII) + continue; + + if (Reg >= Hexagon::V0 && Reg <= Hexagon::V31) { + LLVM_DEBUG(dbgs() << "adding dump for V" << Reg - Hexagon::V0 << '\n'); + addAsmInstr(MBB, Reg, MII, DL, QII, Fn); + } else if (Reg >= Hexagon::W0 && Reg <= Hexagon::W15) { + LLVM_DEBUG(dbgs() << "adding dump for W" << Reg - Hexagon::W0 << '\n'); + addAsmInstr(MBB, Hexagon::V0 + (Reg - Hexagon::W0) * 2 + 1, + MII, DL, QII, Fn); + addAsmInstr(MBB, Hexagon::V0 + (Reg - Hexagon::W0) * 2, + MII, DL, QII, Fn); + } else if (Reg >= Hexagon::Q0 && Reg <= Hexagon::Q3) { + LLVM_DEBUG(dbgs() << "adding dump for Q" << Reg - Hexagon::Q0 << '\n'); + addAsmInstr(MBB, Reg, MII, DL, QII, Fn); + } else + llvm_unreachable("Bad Vector reg"); + } + return Changed; +} + +//===----------------------------------------------------------------------===// +// Public Constructor Functions +//===----------------------------------------------------------------------===// +INITIALIZE_PASS(HexagonVectorPrint, "hexagon-vector-print", + "Hexagon VectorPrint pass", false, false) + +FunctionPass *llvm::createHexagonVectorPrint() { + return new HexagonVectorPrint(); +} diff --git a/pool/shard006/C++/0079037_octave-config.in.cc b/pool/shard006/C++/0079037_octave-config.in.cc new file mode 100644 index 0000000000000000000000000000000000000000..3a077e64d17d4dd77b38bbd9147ed7bb3caa5fbc --- /dev/null +++ b/pool/shard006/C++/0079037_octave-config.in.cc @@ -0,0 +1,172 @@ +// %NO_EDIT_WARNING% +/* + +Copyright (C) 2008-2013 Michael Goffioul + +This file is part of Octave. + +Octave 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. + +Octave 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 Octave; see the file COPYING. If not, see +. + +*/ + +#if defined (HAVE_CONFIG_H) +#include +#endif + +#include +#include +#include +#include +#include + +#ifndef OCTAVE_PREFIX +#define OCTAVE_PREFIX %OCTAVE_PREFIX% +#endif + +#include "shared-fcns.h" + +static std::map vars; + +static std::string usage_msg = "usage: octave-config [options]"; + +static std::string help_msg = +"\n" +"Options:\n" +"\n" +" -h, -?, --help Print this message.\n" +"\n" +" --m-site-dir Print the name of the directory where Octave\n" +" expects to find locally installed .m files.\n" +"\n" +" --oct-site-dir Print the name of the directory where Octave\n" +" expects to find locally installed .oct files.\n" +"\n" +" -p VAR, --print VAR Print the value of the given configuration\n" +" variable VAR. Recognized variables are:\n" +"\n" +" API_VERSION LOCALAPIOCTFILEDIR\n" +" ARCHLIBDIR LOCALARCHLIBDIR\n" +" BINDIR LOCALFCNFILEDIR\n" +" CANONICAL_HOST_TYPE LOCALOCTFILEDIR\n" +" DATADIR LOCALSTARTUPFILEDIR\n" +" DATAROOTDIR LOCALVERARCHLIBDIR\n" +" DEFAULT_PAGER LOCALVERFCNFILEDIR\n" +" EXEC_PREFIX LOCALVEROCTFILEDIR\n" +" FCNFILEDIR MAN1DIR\n" +" IMAGEDIR MAN1EXT\n" +" INCLUDEDIR MANDIR\n" +" INFODIR OCTFILEDIR\n" +" INFOFILE OCTINCLUDEDIR\n" +" LIBDIR OCTLIBDIR\n" +" LIBEXECDIR PREFIX\n" +" LOCALAPIARCHLIBDIR STARTUPFILEDIR\n" +" LOCALAPIFCNFILEDIR VERSION\n" +"\n" +" -v, --version Print the Octave version number.\n" +"\n"; + +static void +initialize (void) +{ + vars["OCTAVE_HOME"] = get_octave_home (); + vars["PREFIX"] = OCTAVE_PREFIX; + + vars["API_VERSION"] = %OCTAVE_API_VERSION%; + vars["CANONICAL_HOST_TYPE"] = %OCTAVE_CANONICAL_HOST_TYPE%; + vars["DEFAULT_PAGER"] = %OCTAVE_DEFAULT_PAGER%; + vars["MAN1EXT"] = %OCTAVE_MAN1EXT%; + vars["VERSION"] = %OCTAVE_VERSION%; + + vars["ARCHLIBDIR"] = subst_octave_home (%OCTAVE_ARCHLIBDIR%); + vars["BINDIR"] = subst_octave_home (%OCTAVE_BINDIR%); + vars["DATADIR"] = subst_octave_home (%OCTAVE_DATADIR%); + vars["DATAROOTDIR"] = subst_octave_home (%OCTAVE_DATAROOTDIR%); + vars["EXEC_PREFIX"] = subst_octave_home (%OCTAVE_EXEC_PREFIX%); + vars["FCNFILEDIR"] = subst_octave_home (%OCTAVE_FCNFILEDIR%); + vars["IMAGEDIR"] = subst_octave_home (%OCTAVE_IMAGEDIR%); + vars["INCLUDEDIR"] = subst_octave_home (%OCTAVE_INCLUDEDIR%); + vars["INFODIR"] = subst_octave_home (%OCTAVE_INFODIR%); + vars["INFOFILE"] = subst_octave_home (%OCTAVE_INFOFILE%); + vars["LIBDIR"] = subst_octave_home (%OCTAVE_LIBDIR%); + vars["LIBEXECDIR"] = subst_octave_home (%OCTAVE_LIBEXECDIR%); + vars["LOCALAPIARCHLIBDIR"] = subst_octave_home (%OCTAVE_LOCALAPIARCHLIBDIR%); + vars["LOCALAPIFCNFILEDIR"] = subst_octave_home (%OCTAVE_LOCALAPIFCNFILEDIR%); + vars["LOCALAPIOCTFILEDIR"] = subst_octave_home (%OCTAVE_LOCALAPIOCTFILEDIR%); + vars["LOCALARCHLIBDIR"] = subst_octave_home (%OCTAVE_LOCALARCHLIBDIR%); + vars["LOCALFCNFILEDIR"] = subst_octave_home (%OCTAVE_LOCALFCNFILEDIR%); + vars["LOCALOCTFILEDIR"] = subst_octave_home (%OCTAVE_LOCALOCTFILEDIR%); + vars["LOCALSTARTUPFILEDIR"] = subst_octave_home (%OCTAVE_LOCALSTARTUPFILEDIR%); + vars["LOCALVERARCHLIBDIR"] = subst_octave_home (%OCTAVE_LOCALVERARCHLIBDIR%); + vars["LOCALVERFCNFILEDIR"] = subst_octave_home (%OCTAVE_LOCALVERFCNFILEDIR%); + vars["LOCALVEROCTFILEDIR"] = subst_octave_home (%OCTAVE_LOCALVEROCTFILEDIR%); + vars["MAN1DIR"] = subst_octave_home (%OCTAVE_MAN1DIR%); + vars["MANDIR"] = subst_octave_home (%OCTAVE_MANDIR%); + vars["OCTFILEDIR"] = subst_octave_home (%OCTAVE_OCTFILEDIR%); + vars["OCTINCLUDEDIR"] = subst_octave_home (%OCTAVE_OCTINCLUDEDIR%); + vars["OCTLIBDIR"] = subst_octave_home (%OCTAVE_OCTLIBDIR%); + vars["STARTUPFILEDIR"] = subst_octave_home (%OCTAVE_STARTUPFILEDIR%); +} + +int +main (int argc, char **argv) +{ + initialize (); + + if (argc == 1) + { + std::cout << usage_msg << std::endl; + return 1; + } + + for (int i = 1; i < argc; i++) + { + std::string arg (argv[i]); + + if (arg == "-h" || arg == "-?" || arg == "--help") + { + std::cout << usage_msg << std::endl; + std::cout << help_msg; + return 0; + } + else if (arg == "--m-site-dir") + std::cout << vars["LOCALVERFCNFILEDIR"] << std::endl; + else if (arg == "--oct-site-dir") + std::cout << vars["LOCALVEROCTFILEDIR"] << std::endl; + else if (arg == "-v" || arg == "--version") + std::cout << vars["VERSION"] << std::endl; + else if (arg == "-p" || arg == "--print") + { + if (i < argc-1) + { + arg = argv[++i]; + std::cout << vars[arg] << std::endl; + } + else + { + std::cerr << "octave-config: " << arg + << " options requires argument" << std::endl; + return 1; + } + } + else + { + std::cerr << "octave-config: unrecognized argument " << arg + << std::endl; + return 1; + } + } + + return 0; +} diff --git a/pool/shard006/C++/0079042_settings_sync_processor.cc b/pool/shard006/C++/0079042_settings_sync_processor.cc new file mode 100644 index 0000000000000000000000000000000000000000..96ef468619a774a635224001ea14f6d3d070c4be --- /dev/null +++ b/pool/shard006/C++/0079042_settings_sync_processor.cc @@ -0,0 +1,111 @@ +// 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/extensions/api/storage/settings_sync_processor.h" +#include "chrome/browser/extensions/api/storage/settings_sync_util.h" +#include "content/public/browser/browser_thread.h" +#include "extensions/browser/api/storage/settings_namespace.h" +#include "sync/api/sync_change_processor.h" +#include "sync/api/sync_data.h" +#include "sync/protocol/extension_setting_specifics.pb.h" + +using content::BrowserThread; + +namespace extensions { + +SettingsSyncProcessor::SettingsSyncProcessor( + const std::string& extension_id, + syncer::ModelType type, + syncer::SyncChangeProcessor* sync_processor) + : extension_id_(extension_id), + type_(type), + sync_processor_(sync_processor), + initialized_(false) { + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + CHECK(type == syncer::EXTENSION_SETTINGS || type == syncer::APP_SETTINGS); + CHECK(sync_processor); +} + +SettingsSyncProcessor::~SettingsSyncProcessor() { + DCHECK_CURRENTLY_ON(BrowserThread::FILE); +} + +void SettingsSyncProcessor::Init(const base::DictionaryValue& initial_state) { + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + CHECK(!initialized_) << "Init called multiple times"; + + for (base::DictionaryValue::Iterator i(initial_state); !i.IsAtEnd(); + i.Advance()) + synced_keys_.insert(i.key()); + + initialized_ = true; +} + +syncer::SyncError SettingsSyncProcessor::SendChanges( + const ValueStoreChangeList& changes) { + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + CHECK(initialized_) << "Init not called"; + + syncer::SyncChangeList sync_changes; + std::set added_keys; + std::set deleted_keys; + + for (ValueStoreChangeList::const_iterator i = changes.begin(); + i != changes.end(); ++i) { + const std::string& key = i->key(); + const base::Value* value = i->new_value(); + if (value) { + if (synced_keys_.count(key)) { + // New value, key is synced; send ACTION_UPDATE. + sync_changes.push_back(settings_sync_util::CreateUpdate( + extension_id_, key, *value, type_)); + } else { + // New value, key is not synced; send ACTION_ADD. + sync_changes.push_back(settings_sync_util::CreateAdd( + extension_id_, key, *value, type_)); + added_keys.insert(key); + } + } else { + if (synced_keys_.count(key)) { + // Clearing value, key is synced; send ACTION_DELETE. + sync_changes.push_back(settings_sync_util::CreateDelete( + extension_id_, key, type_)); + deleted_keys.insert(key); + } else { + LOG(WARNING) << "Deleted " << key << " but not in synced_keys_"; + } + } + } + + if (sync_changes.empty()) + return syncer::SyncError(); + + syncer::SyncError error = + sync_processor_->ProcessSyncChanges(FROM_HERE, sync_changes); + if (error.IsSet()) + return error; + + synced_keys_.insert(added_keys.begin(), added_keys.end()); + for (std::set::iterator i = deleted_keys.begin(); + i != deleted_keys.end(); ++i) { + synced_keys_.erase(*i); + } + + return syncer::SyncError(); +} + +void SettingsSyncProcessor::NotifyChanges(const ValueStoreChangeList& changes) { + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + CHECK(initialized_) << "Init not called"; + + for (ValueStoreChangeList::const_iterator i = changes.begin(); + i != changes.end(); ++i) { + if (i->new_value()) + synced_keys_.insert(i->key()); + else + synced_keys_.erase(i->key()); + } +} + +} // namespace extensions diff --git a/pool/shard006/C++/0079047_pow.cpp b/pool/shard006/C++/0079047_pow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be885696418c598ab34b1f2c364be0b3f9138c9c --- /dev/null +++ b/pool/shard006/C++/0079047_pow.cpp @@ -0,0 +1,233 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 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 "pow.h" + +#include "chain.h" +#include "chainparams.h" +#include "primitives/block.h" +#include "uint256.h" +#include "util.h" +#include + +unsigned int GetNextWorkRequiredOld(const CBlockIndex* pindexLast, const CBlockHeader *pblock) +{ + unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact(); + + // Genesis block + if (pindexLast == NULL) + return nProofOfWorkLimit; + + // Only change once per interval + if ((pindexLast->nHeight+1) % Params().Interval() != 0) + { + if (Params().AllowMinDifficultyBlocks()) + { + // Special difficulty rule for testnet: + // If the new block's timestamp is more than 2* 10 minutes + // then allow mining of a min-difficulty block. + if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2) + return nProofOfWorkLimit; + else + { + // Return the last non-special-min-difficulty-rules-block + const CBlockIndex* pindex = pindexLast; + while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit) + pindex = pindex->pprev; + return pindex->nBits; + } + } + return pindexLast->nBits; + } + + // Dotcoin: This fixes an issue where a 51% attack can change difficulty at will. + // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz + int blockstogoback = Params().Interval()-1; + /*if ((pindexLast->nHeight+1) != Params().Interval()) + blockstogoback = Params().Interval();*/ + + // Go back by what we want to be 14 days worth of blocks + const CBlockIndex* pindexFirst = pindexLast; + for (int i = 0; pindexFirst && i < blockstogoback; i++) + pindexFirst = pindexFirst->pprev; + assert(pindexFirst); + + // Limit adjustment step + int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); + LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan); + if (nActualTimespan < Params().TargetTimespan()/4) + nActualTimespan = Params().TargetTimespan()/4; + if (nActualTimespan > Params().TargetTimespan()*4) + nActualTimespan = Params().TargetTimespan()*4; + + // Retarget + uint256 bnNew; + uint256 bnOld; + bnNew.SetCompact(pindexLast->nBits); + bnOld = bnNew; + // Dotcoin: intermediate uint256 can overflow by 1 bit + bool fShift = bnNew.bits() > 235; + if (fShift) + bnNew >>= 1; + bnNew *= nActualTimespan; + bnNew /= Params().TargetTimespan(); + if (fShift) + bnNew <<= 1; + + if (bnNew > Params().ProofOfWorkLimit()) + bnNew = Params().ProofOfWorkLimit(); + + /// debug print + LogPrintf("GetNextWorkRequired RETARGET\n"); + LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan); + LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString()); + LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString()); + + return bnNew.GetCompact(); +} + +#include "bignum.h" + +unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64 TargetBlocksSpacingSeconds, uint64 PastBlocksMin, uint64 PastBlocksMax) +{ + /* current difficulty formula - kimoto gravity well */ + const CBlockIndex *BlockLastSolved = pindexLast; + const CBlockIndex *BlockReading = pindexLast; + const CBlockHeader *BlockCreating = pblock; + BlockCreating = BlockCreating; + uint64 PastBlocksMass = 0; + int64 PastRateActualSeconds = 0; + int64 PastRateTargetSeconds = 0; + double PastRateAdjustmentRatio = double(1); + CBigNum PastDifficultyAverage; + CBigNum PastDifficultyAveragePrev; + double EventHorizonDeviation; + double EventHorizonDeviationFast; + double EventHorizonDeviationSlow; + CBigNum bnProofOfWorkLimit(Params().ProofOfWorkLimit()); + + if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); } + + for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) + { + if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } + + PastBlocksMass++; + + if (i == 1) + { + PastDifficultyAverage.SetCompact(BlockReading->nBits); + } + else + { + PastDifficultyAverage = ((CBigNum().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; + } + PastDifficultyAveragePrev = PastDifficultyAverage; + + PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); + PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass; + PastRateAdjustmentRatio = double(1); + if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } + if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) + { + PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); + } + EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228)); + EventHorizonDeviationFast = EventHorizonDeviation; + EventHorizonDeviationSlow = 1 / EventHorizonDeviation; + + if (PastBlocksMass >= PastBlocksMin) + { + if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) + { + assert(BlockReading); + break; + } + } + + if (BlockReading->pprev == NULL) + { + assert(BlockReading); + break; + } + BlockReading = BlockReading->pprev; + } + + CBigNum bnNew(PastDifficultyAverage); + if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) + { + bnNew *= PastRateActualSeconds; + bnNew /= PastRateTargetSeconds; + } + if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; } + + /// debug print + LogPrintf("Difficulty Retarget - Kimoto Gravity Well\n"); + LogPrintf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio); + LogPrintf("Before: %08x %s\n", BlockLastSolved->nBits, CBigNum().SetCompact(BlockLastSolved->nBits).getuint256().ToString().c_str()); + LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); + + return bnNew.GetCompact(); +} + +unsigned int static GetNextWorkRequiredNew(const CBlockIndex* pindexLast, const CBlockHeader *pblock) +{ + static const int64_t BlocksTargetSpacing = 1.5 * 60; // 1.5 minutes + unsigned int TimeDaySeconds = 60 * 60 * 24; + int64_t PastSecondsMin = TimeDaySeconds * 0.25; + int64_t PastSecondsMax = TimeDaySeconds * 7; + uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing; + uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing; + return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax); +} + +unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock) +{ + if (pindexLast->nHeight+1 >= 18000) + { + return GetNextWorkRequiredNew(pindexLast, pblock); //KGW + } + else + { + return GetNextWorkRequiredOld(pindexLast, pblock); + } +} + +bool CheckProofOfWork(uint256 hash, unsigned int nBits) +{ + bool fNegative; + bool fOverflow; + uint256 bnTarget; + + if (Params().SkipProofOfWorkCheck()) + return true; + + bnTarget.SetCompact(nBits, &fNegative, &fOverflow); + + // Check range + if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit()) + return error("CheckProofOfWork() : nBits below minimum work"); + + // Check proof of work matches claimed amount + if (hash > bnTarget) + return error("CheckProofOfWork() : hash doesn't match nBits"); + + return true; +} + +uint256 GetBlockProof(const CBlockIndex& block) +{ + uint256 bnTarget; + bool fNegative; + bool fOverflow; + bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); + if (fNegative || fOverflow || bnTarget == 0) + return 0; + // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 + // as it's too large for a uint256. However, as 2**256 is at least as large + // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, + // or ~bnTarget / (nTarget+1) + 1. + return (~bnTarget / (bnTarget + 1)) + 1; +} diff --git a/pool/shard006/C++/0079055_auction_list.cpp b/pool/shard006/C++/0079055_auction_list.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df0d9157da761fcb329ce107aef35b60629cec31 --- /dev/null +++ b/pool/shard006/C++/0079055_auction_list.cpp @@ -0,0 +1,107 @@ +/* +=========================================================================== + + Copyright (c) 2010-2014 Darkstar Dev Teams + + 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 http://www.gnu.org/licenses/ + + This file is part of DarkStar-server source code. + +=========================================================================== +*/ +#include + +#include "../../common/showmsg.h" +#include "../../common/socket.h" + +#include "../data_loader.h" + +#include "auction_list.h" + + +/************************************************************************ +* * +* Если количество отправляемых предметов превышает 20, то отправляем * +* их несколькими пакетами, в каждый их коротых записываем смещение * +* * +************************************************************************/ + +CAHItemsListPacket::CAHItemsListPacket(uint16 offset) +{ + m_count = 0; + m_offset = offset; + + memset(m_PData, 0, sizeof(m_PData)); + + WBUFB(m_PData,(0x0B)) = 0x95; // packet type +} + +/************************************************************************ +* * +* Добавляем предмет в пакет (по 10 байт на предмер) * +* * +************************************************************************/ + +void CAHItemsListPacket::AddItem(ahItem* item) +{ + WBUFW(m_PData,(0x18 + 0x0A*m_count) + 0) = item->ItemID; + WBUFL(m_PData,(0x18 + 0x0A*m_count) + 2) = item->SinglAmount; + WBUFL(m_PData,(0x18 + 0x0A*m_count) + 6) = item->StackAmount; + + m_count++; + delete item; +} + +/************************************************************************ +* * +* Устанавливаем общее количество отправляемых предметов * +* * +************************************************************************/ + +void CAHItemsListPacket::SetItemCount(uint16 count) +{ + WBUFW(m_PData,(0x0E)) = count; + + if ((count - m_offset) <= 20) + { + WBUFB(m_PData,(0x0A)) = 0x80; + WBUFW(m_PData,(0x08)) = 0x18 + 0x0A*(count - m_offset); + } + else + { + WBUFW(m_PData,(0x08)) = 0x18 + 0x0A*20; + } +} + +/************************************************************************ +* * +* Возвращаем собранный пакет * +* * +************************************************************************/ + +uint8* CAHItemsListPacket::GetData() +{ + return m_PData; +} + +/************************************************************************ +* * +* Возвращаем размер отправляемого пакета * +* * +************************************************************************/ + +uint16 CAHItemsListPacket::GetSize() +{ + return 0x18 + 0x0A*m_count + 28; +} \ No newline at end of file diff --git a/pool/shard006/C++/0079063_test_semaphore.cpp b/pool/shard006/C++/0079063_test_semaphore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..463acc0f2b1ba4cc8767a6144c88ace6f27a9161 --- /dev/null +++ b/pool/shard006/C++/0079063_test_semaphore.cpp @@ -0,0 +1,71 @@ +#include "test_semaphore.hpp" +#include +#include + +namespace oonet +{ + namespace test + { + test_semaphore test_semaphore_inst; + + class TestThreadSemaphore : mt::thread + { + + }; + + bool test_semaphore::TestLockTimeOut::operator()() + { mt::semaphore mySema; + + mySema.wait(3000); + return false; + } + + bool test_semaphore::TestInitialState::operator()() + { mt::semaphore mySema(3); + + // We can wait 3 times + mySema.wait(3000); + mySema.wait(3000); + mySema.wait(3000); + + // 4th must timeout! + try { mySema.wait(3000); } + catch(ExceptionTimeOut & e) + { e = e; return true; } + + return false; + } + + bool test_semaphore::TestPostWait::operator()() + { mt::semaphore mySema; + + // Post 5 times + mySema.post(); + mySema.post(); + mySema.post(); + mySema.post(); + mySema.post(); + + // Wait 5 times + mySema.wait(); + mySema.wait(); + mySema.wait(); + mySema.wait(); + mySema.wait(); + + // 6th must timeout! + try { mySema.wait(3000); } + catch(ExceptionTimeOut & e) + { e = e; return true; } + + return false; + } + + bool test_semaphore::TestDestructorSignaled::operator()() + { mt::semaphore mySema; + + mySema.post(); // Signale it and wait to destruct on exit of function + return true; + } + }; // !test namespace +}; // !oonet namespace diff --git a/pool/shard006/C++/0079066_wrap_PolygonShape.cpp b/pool/shard006/C++/0079066_wrap_PolygonShape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3dee6d1480bb0fc34495c1d2601cbc2aa709033 --- /dev/null +++ b/pool/shard006/C++/0079066_wrap_PolygonShape.cpp @@ -0,0 +1,61 @@ +/** +* Copyright (c) 2006-2012 LOVE Development Team +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +**/ + +#include "wrap_PolygonShape.h" + +namespace love +{ +namespace physics +{ +namespace box2d +{ + PolygonShape * luax_checkpolygonshape(lua_State * L, int idx) + { + return luax_checktype(L, idx, "PolygonShape", PHYSICS_POLYGON_SHAPE_T); + } + + int w_PolygonShape_getPoints(lua_State * L) + { + PolygonShape * t = luax_checkpolygonshape(L, 1); + lua_remove(L, 1); + return t->getPoints(L); + } + + static const luaL_Reg functions[] = { + { "getPoints", w_PolygonShape_getPoints }, + // From Shape. + { "getType", w_Shape_getType }, + { "getRadius", w_Shape_getRadius }, + { "getChildCount", w_Shape_getChildCount }, + { "testPoint", w_Shape_testPoint }, + { "rayCast", w_Shape_rayCast }, + { "computeAABB", w_Shape_computeAABB }, + { "computeMass", w_Shape_computeMass }, + { 0, 0 } + }; + + extern "C" int luaopen_polygonshape(lua_State * L) + { + return luax_register_type(L, "PolygonShape", functions); + } + +} // box2d +} // physics +} // love diff --git a/pool/shard006/C++/0079068_bond_morse_omp.cpp b/pool/shard006/C++/0079068_bond_morse_omp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0203de0d6e71e33ea4dac17c39528d5ac2b63d5 --- /dev/null +++ b/pool/shard006/C++/0079068_bond_morse_omp.cpp @@ -0,0 +1,130 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + http://lammps.sandia.gov, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing author: Axel Kohlmeyer (Temple U) +------------------------------------------------------------------------- */ + +#include "bond_morse_omp.h" +#include "atom.h" +#include "comm.h" +#include "force.h" +#include "neighbor.h" +#include "domain.h" + +#include + +#include "suffix.h" +using namespace LAMMPS_NS; + +/* ---------------------------------------------------------------------- */ + +BondMorseOMP::BondMorseOMP(class LAMMPS *lmp) + : BondMorse(lmp), ThrOMP(lmp,THR_BOND) +{ + suffix_flag |= Suffix::OMP; +} + +/* ---------------------------------------------------------------------- */ + +void BondMorseOMP::compute(int eflag, int vflag) +{ + ev_init(eflag,vflag); + + const int nall = atom->nlocal + atom->nghost; + const int nthreads = comm->nthreads; + const int inum = neighbor->nbondlist; + +#if defined(_OPENMP) +#pragma omp parallel default(none) shared(eflag,vflag) +#endif + { + int ifrom, ito, tid; + + loop_setup_thr(ifrom, ito, tid, inum, nthreads); + ThrData *thr = fix->get_thr(tid); + thr->timer(Timer::START); + ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr); + + if (inum > 0) { + if (evflag) { + if (eflag) { + if (force->newton_bond) eval<1,1,1>(ifrom, ito, thr); + else eval<1,1,0>(ifrom, ito, thr); + } else { + if (force->newton_bond) eval<1,0,1>(ifrom, ito, thr); + else eval<1,0,0>(ifrom, ito, thr); + } + } else { + if (force->newton_bond) eval<0,0,1>(ifrom, ito, thr); + else eval<0,0,0>(ifrom, ito, thr); + } + } + thr->timer(Timer::BOND); + reduce_thr(this, eflag, vflag, thr); + } // end of omp parallel region +} + +template +void BondMorseOMP::eval(int nfrom, int nto, ThrData * const thr) +{ + int i1,i2,n,type; + double delx,dely,delz,ebond,fbond; + double rsq,r,dr,ralpha; + + const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; + dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; + const int3_t * _noalias const bondlist = (int3_t *) neighbor->bondlist[0]; + const int nlocal = atom->nlocal; + ebond = 0.0; + + for (n = nfrom; n < nto; n++) { + i1 = bondlist[n].a; + i2 = bondlist[n].b; + type = bondlist[n].t; + + delx = x[i1].x - x[i2].x; + dely = x[i1].y - x[i2].y; + delz = x[i1].z - x[i2].z; + + rsq = delx*delx + dely*dely + delz*delz; + r = sqrt(rsq); + + dr = r - r0[type]; + ralpha = exp(-alpha[type]*dr); + + // force & energy + + if (r > 0.0) fbond = -2.0*d0[type]*alpha[type]*(1-ralpha)*ralpha/r; + else fbond = 0.0; + + if (EFLAG) ebond = d0[type]*(1-ralpha)*(1-ralpha); + + // apply force to each of 2 atoms + + if (NEWTON_BOND || i1 < nlocal) { + f[i1].x += delx*fbond; + f[i1].y += dely*fbond; + f[i1].z += delz*fbond; + } + + if (NEWTON_BOND || i2 < nlocal) { + f[i2].x -= delx*fbond; + f[i2].y -= dely*fbond; + f[i2].z -= delz*fbond; + } + + if (EVFLAG) ev_tally_thr(this,i1,i2,nlocal,NEWTON_BOND, + ebond,fbond,delx,dely,delz,thr); + } +} diff --git a/pool/shard006/C++/0079073_pull.cpp b/pool/shard006/C++/0079073_pull.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e00f14ca5c3825ce64b70daad9e5ec2bd816c6bf --- /dev/null +++ b/pool/shard006/C++/0079073_pull.cpp @@ -0,0 +1,78 @@ +/* + Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file + + This file is part of libzmq, the ZeroMQ core engine in C++. + + libzmq is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + As a special exception, the Contributors give you permission to link + this library with independent modules to produce an executable, + regardless of the license terms of these independent modules, and to + copy and distribute the resulting executable under terms of your choice, + provided that you also meet, for each linked independent module, the + terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. + If you modify this library, you must extend this exception to your + version of the library. + + libzmq 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 "precompiled.hpp" +#include "macros.hpp" +#include "pull.hpp" +#include "err.hpp" +#include "msg.hpp" +#include "pipe.hpp" + +zmq::pull_t::pull_t (class ctx_t *parent_, uint32_t tid_, int sid_) : + socket_base_t (parent_, tid_, sid_) +{ + options.type = ZMQ_PULL; +} + +zmq::pull_t::~pull_t () +{ +} + +void zmq::pull_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_) +{ + LIBZMQ_UNUSED (subscribe_to_all_); + + zmq_assert (pipe_); + fq.attach (pipe_); +} + +void zmq::pull_t::xread_activated (pipe_t *pipe_) +{ + fq.activated (pipe_); +} + +void zmq::pull_t::xpipe_terminated (pipe_t *pipe_) +{ + fq.pipe_terminated (pipe_); +} + +int zmq::pull_t::xrecv (msg_t *msg_) +{ + return fq.recv (msg_); +} + +bool zmq::pull_t::xhas_in () +{ + return fq.has_in (); +} + +zmq::blob_t zmq::pull_t::get_credential () const +{ + return fq.get_credential (); +} diff --git a/pool/shard006/C++/0079074_tol_barad.cpp b/pool/shard006/C++/0079074_tol_barad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8101ddf6f6a75e8589aad93cbe1162223d9842e6 --- /dev/null +++ b/pool/shard006/C++/0079074_tol_barad.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (C) Likan Mod (https://github.com/ChaosDevLikan/) + * Copyright (C) Prydev (http://sourceforge.net/projects/prydevserver) + * Copyright (C) TrinityCore (http://www.trinitycore.org) + * Copyright (C) MaNGOS (http://www.getmangos.com) + * Copyright (C) ArkCORE (http://www.arkania.net) + * Copyright (C) SkyFireEMU (http://www.projectskyfire.org) + * + * World of Warcraft + * You can edit but you can not delete this copyright. + * Genesis Emulator - Genesis Database + * + * + * By Likan Developer Core C++, SQL (FUN, WoTLK, Cata Realm) of Genesis Server + */ + + +#include "ScriptPCH.h" +#include "BattlefieldMgr.h" +#include "BattlefieldTB.h" +#include "Battlefield.h" +#include "ScriptSystem.h" +#include "WorldSession.h" +#include "ObjectMgr.h" + +enum eTBqueuenpctext +{ + TB_NPCQUEUE_TEXT_H_NOWAR = 110006, + TB_NPCQUEUE_TEXT_H_QUEUE = 110002, + TB_NPCQUEUE_TEXT_H_WAR = 110005, + TB_NPCQUEUE_TEXT_A_NOWAR = 110003, + TB_NPCQUEUE_TEXT_A_QUEUE = 110001, + TB_NPCQUEUE_TEXT_A_WAR = 110004, + TB_NPCQUEUE_TEXTOPTION_JOIN = -1732009, +}; + +class npc_tb_spiritguide : public CreatureScript +{ +public: + npc_tb_spiritguide() : CreatureScript("npc_tb_spiritguide") { } + + bool OnGossipHello(Player* player, Creature* creature) + { + if (creature->isQuestGiver()) + player->PrepareQuestMenu(creature->GetGUID()); + + BattlefieldTB* BfTB = (BattlefieldTB*)sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_TB); + if (BfTB) + { + GraveYardVect gy = BfTB->GetGraveYardVect(); + for (uint8 i = 0; iGetControlTeamId() == player->GetTeamId()) + { + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, sObjectMgr->GetSkyFireStringForDBCLocale(((BfGraveYardTB*)gy[i])->GetTextId()), GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+i); + } + } + } + + player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); + return true; + } + + bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) + { + player->CLOSE_GOSSIP_MENU(); + + BattlefieldTB* BfTB = (BattlefieldTB*)sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_TB); + if (BfTB) + { + GraveYardVect gy = BfTB->GetGraveYardVect(); + for (uint8 i = 0; iGetControlTeamId() == player->GetTeamId()) + { + const WorldSafeLocsEntry* ws = sWorldSafeLocsStore.LookupEntry(gy[i]->GetGraveYardId()); + player->TeleportTo(ws->map_id, ws->x, ws->y, ws->z, 0); + } + } + } + return true; + } +}; + +class npc_tol_barad_battlemage : public CreatureScript +{ + public: + npc_tol_barad_battlemage() : CreatureScript("npc_tol_barad_battlemage") { } + + bool OnGossipHello(Player* player, Creature* creature) + { + if (creature->isQuestGiver()) + player->PrepareQuestMenu(creature->GetGUID()); + + BattlefieldTB* BfTB = (BattlefieldTB*)sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_TB); + if (BfTB) + { + if (BfTB->IsWarTime()) + { + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, sObjectMgr->GetSkyFireStringForDBCLocale(TB_NPCQUEUE_TEXTOPTION_JOIN), GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(BfTB->GetDefenderTeam() ? TB_NPCQUEUE_TEXT_H_WAR : TB_NPCQUEUE_TEXT_A_WAR, creature->GetGUID()); + } + else + { + uint32 uiTime = BfTB->GetTimer()/1000; + player->SendUpdateWorldState(5332, time(NULL)+uiTime); + if (uiTime < 15 * MINUTE) + { + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, sObjectMgr->GetSkyFireStringForDBCLocale(TB_NPCQUEUE_TEXTOPTION_JOIN), GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(BfTB->GetDefenderTeam() ? TB_NPCQUEUE_TEXT_H_QUEUE : TB_NPCQUEUE_TEXT_A_QUEUE, creature->GetGUID()); + } + else + { + player->SEND_GOSSIP_MENU(BfTB->GetDefenderTeam() ? TB_NPCQUEUE_TEXT_H_NOWAR:TB_NPCQUEUE_TEXT_A_NOWAR, creature->GetGUID()); + } + } + } + return true; + } + + bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/) + { + player->CLOSE_GOSSIP_MENU(); + + BattlefieldTB* BfTB = (BattlefieldTB*)sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_TB); + if (BfTB) + { + if (BfTB->IsWarTime()) + { + BfTB->InvitePlayerToWar(player); + } + else + { + uint32 uiTime = BfTB->GetTimer()/1000; + if (uiTime < 15 * MINUTE) + BfTB->InvitePlayerToQueue(player); + } + } + return true; + } +}; + +void AddSC_tol_barad() +{ + new npc_tol_barad_battlemage(); + new npc_tb_spiritguide(); +} diff --git a/pool/shard006/C++/0079080_ai_industry.cpp b/pool/shard006/C++/0079080_ai_industry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81e01da77a931d63b3417f5e0f7dea1dd66ba095 --- /dev/null +++ b/pool/shard006/C++/0079080_ai_industry.cpp @@ -0,0 +1,212 @@ +/* $Id: ai_industry.cpp 21888 2011-01-22 10:33:16Z rubidium $ */ + +/* + * This file is part of OpenCoaster Tycoon. + * OpenCoaster Tycoon 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. + * OpenCoaster Tycoon 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 OpenCoaster Tycoon. If not, see . + */ + +/** @file ai_industry.cpp Implementation of AIIndustry. */ + +#include "../../stdafx.h" +#include "ai_industry.hpp" +#include "ai_cargo.hpp" +#include "ai_map.hpp" +#include "../../industry.h" +#include "../../strings_func.h" +#include "../../station_base.h" +#include "../../newgrf_industries.h" +#include "table/strings.h" + +/* static */ int32 AIIndustry::GetIndustryCount() +{ + return (int32)::Industry::GetNumItems(); +} + +/* static */ bool AIIndustry::IsValidIndustry(IndustryID industry_id) +{ + return ::Industry::IsValidID(industry_id); +} + +/* static */ IndustryID AIIndustry::GetIndustryID(TileIndex tile) +{ + if (!::IsValidTile(tile) || !::IsTileType(tile, MP_INDUSTRY)) return INVALID_INDUSTRY; + return ::GetIndustryIndex(tile); +} + +/* static */ char *AIIndustry::GetName(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return NULL; + static const int len = 64; + char *industry_name = MallocT(len); + + ::SetDParam(0, industry_id); + ::GetString(industry_name, STR_INDUSTRY_NAME, &industry_name[len - 1]); + + return industry_name; +} + +/* static */ AIIndustry::CargoAcceptState AIIndustry::IsCargoAccepted(IndustryID industry_id, CargoID cargo_id) +{ + if (!IsValidIndustry(industry_id)) return CAS_NOT_ACCEPTED; + if (!AICargo::IsValidCargo(cargo_id)) return CAS_NOT_ACCEPTED; + + Industry *i = ::Industry::Get(industry_id); + + for (byte j = 0; j < lengthof(i->accepts_cargo); j++) { + if (i->accepts_cargo[j] == cargo_id) { + if (IndustryTemporarilyRefusesCargo(i, cargo_id)) return CAS_TEMP_REFUSED; + return CAS_ACCEPTED; + } + } + + return CAS_NOT_ACCEPTED; +} + +/* static */ int32 AIIndustry::GetStockpiledCargo(IndustryID industry_id, CargoID cargo_id) +{ + if (!IsValidIndustry(industry_id)) return -1; + if (!AICargo::IsValidCargo(cargo_id)) return -1; + + Industry *ind = ::Industry::Get(industry_id); + for (uint i = 0; i < lengthof(ind->accepts_cargo); i++) { + CargoID cid = ind->accepts_cargo[i]; + if (cid == cargo_id) { + return ind->incoming_cargo_waiting[i]; + } + } + + return -1; +} + +/* static */ int32 AIIndustry::GetLastMonthProduction(IndustryID industry_id, CargoID cargo_id) +{ + if (!IsValidIndustry(industry_id)) return -1; + if (!AICargo::IsValidCargo(cargo_id)) return -1; + + const Industry *i = ::Industry::Get(industry_id); + + for (byte j = 0; j < lengthof(i->produced_cargo); j++) { + if (i->produced_cargo[j] == cargo_id) return i->last_month_production[j]; + } + + return -1; +} + +/* static */ int32 AIIndustry::GetLastMonthTransported(IndustryID industry_id, CargoID cargo_id) +{ + if (!IsValidIndustry(industry_id)) return -1; + if (!AICargo::IsValidCargo(cargo_id)) return -1; + + const Industry *i = ::Industry::Get(industry_id); + + for (byte j = 0; j < lengthof(i->produced_cargo); j++) { + if (i->produced_cargo[j] == cargo_id) return i->last_month_transported[j]; + } + + return -1; +} + +/* static */ int32 AIIndustry::GetLastMonthTransportedPercentage(IndustryID industry_id, CargoID cargo_id) +{ + if (!IsValidIndustry(industry_id)) return -1; + if (!AICargo::IsValidCargo(cargo_id)) return -1; + + const Industry *i = ::Industry::Get(industry_id); + + for (byte j = 0; j < lengthof(i->produced_cargo); j++) { + if (i->produced_cargo[j] == cargo_id) return ::ToPercent8(i->last_month_pct_transported[j]); + } + + return -1; +} + +/* static */ TileIndex AIIndustry::GetLocation(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return INVALID_TILE; + + return ::Industry::Get(industry_id)->location.tile; +} + +/* static */ int32 AIIndustry::GetAmountOfStationsAround(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return -1; + + Industry *ind = ::Industry::Get(industry_id); + StationList stations; + ::FindStationsAroundTiles(ind->location, &stations); + return (int32)stations.Length(); +} + +/* static */ int32 AIIndustry::GetDistanceManhattanToTile(IndustryID industry_id, TileIndex tile) +{ + if (!IsValidIndustry(industry_id)) return -1; + + return AIMap::DistanceManhattan(tile, GetLocation(industry_id)); +} + +/* static */ int32 AIIndustry::GetDistanceSquareToTile(IndustryID industry_id, TileIndex tile) +{ + if (!IsValidIndustry(industry_id)) return -1; + + return AIMap::DistanceSquare(tile, GetLocation(industry_id)); +} + +/* static */ bool AIIndustry::IsBuiltOnWater(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return false; + + return (::GetIndustrySpec(::Industry::Get(industry_id)->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0; +} + +/* static */ bool AIIndustry::HasHeliport(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return false; + + return (::GetIndustrySpec(::Industry::Get(industry_id)->type)->behaviour & INDUSTRYBEH_AI_AIRSHIP_ROUTES) != 0; +} + +/* static */ TileIndex AIIndustry::GetHeliportLocation(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return INVALID_TILE; + if (!HasHeliport(industry_id)) return INVALID_TILE; + + const Industry *ind = ::Industry::Get(industry_id); + TILE_AREA_LOOP(tile_cur, ind->location) { + if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) { + return tile_cur; + } + } + + return INVALID_TILE; +} + +/* static */ bool AIIndustry::HasDock(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return false; + + return (::GetIndustrySpec(::Industry::Get(industry_id)->type)->behaviour & INDUSTRYBEH_AI_AIRSHIP_ROUTES) != 0; +} + +/* static */ TileIndex AIIndustry::GetDockLocation(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return INVALID_TILE; + if (!HasDock(industry_id)) return INVALID_TILE; + + const Industry *ind = ::Industry::Get(industry_id); + TILE_AREA_LOOP(tile_cur, ind->location) { + if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) { + return tile_cur; + } + } + + return INVALID_TILE; +} + +/* static */ IndustryType AIIndustry::GetIndustryType(IndustryID industry_id) +{ + if (!IsValidIndustry(industry_id)) return INVALID_INDUSTRYTYPE; + + return ::Industry::Get(industry_id)->type; +} diff --git a/pool/shard006/C++/0079081_HttpListenCommand.cc b/pool/shard006/C++/0079081_HttpListenCommand.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b59193441666b0ace6923a224c3c9acf49e9ccb --- /dev/null +++ b/pool/shard006/C++/0079081_HttpListenCommand.cc @@ -0,0 +1,120 @@ +/* */ +#include "HttpListenCommand.h" +#include "DownloadEngine.h" +#include "RecoverableException.h" +#include "message.h" +#include "Logger.h" +#include "LogFactory.h" +#include "SocketCore.h" +#include "HttpServerCommand.h" +#include "CUIDCounter.h" +#include "RequestGroupMan.h" +#include "prefs.h" +#include "Option.h" +#include "util.h" +#include "A2STR.h" +#include "fmt.h" + +namespace aria2 { + +HttpListenCommand::HttpListenCommand(cuid_t cuid, DownloadEngine* e, + int family, bool secure) + : Command(cuid), + e_(e), + family_(family), + secure_(secure) +{} + +HttpListenCommand::~HttpListenCommand() +{ + if(serverSocket_) { + e_->deleteSocketForReadCheck(serverSocket_, this); + } +} + +bool HttpListenCommand::execute() +{ + if(e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) { + return true; + } + try { + if(serverSocket_->isReadable(0)) { + std::shared_ptr socket(serverSocket_->acceptConnection()); + socket->setTcpNodelay(true); + std::pair peerInfo; + socket->getPeerInfo(peerInfo); + + A2_LOG_INFO(fmt("RPC: Accepted the connection from %s:%u.", + peerInfo.first.c_str(), peerInfo.second)); + + e_->setNoWait(true); + e_->addCommand(make_unique + (e_->newCUID(), e_, socket, secure_)); + } + } catch(RecoverableException& e) { + A2_LOG_DEBUG_EX(fmt(MSG_ACCEPT_FAILURE, getCuid()), e); + } + e_->addCommand(std::unique_ptr(this)); + return false; +} + +bool HttpListenCommand::bindPort(uint16_t port) +{ + if(serverSocket_) { + e_->deleteSocketForReadCheck(serverSocket_, this); + } + serverSocket_.reset(new SocketCore()); + const int ipv = (family_ == AF_INET) ? 4 : 6; + try { + int flags = 0; + if(e_->getOption()->getAsBool(PREF_RPC_LISTEN_ALL)) { + flags = AI_PASSIVE; + } + serverSocket_->bind(nullptr, port, family_, flags); + serverSocket_->beginListen(); + A2_LOG_INFO(fmt(MSG_LISTENING_PORT, + getCuid(), port)); + e_->addSocketForReadCheck(serverSocket_, this); + A2_LOG_NOTICE(fmt(_("IPv%d RPC: listening on TCP port %u"), ipv, port)); + return true; + } catch(RecoverableException& e) { + A2_LOG_ERROR_EX(fmt("IPv%d RPC: failed to bind TCP port %u", ipv, port), e); + serverSocket_->closeConnection(); + } + return false; +} + +} // namespace aria2 diff --git a/pool/shard006/C++/0079090_UnitFormSearchAndDestroyChess2Menu.cpp b/pool/shard006/C++/0079090_UnitFormSearchAndDestroyChess2Menu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55fd29e294010db539d04f55cc4e3480beeca3a8 --- /dev/null +++ b/pool/shard006/C++/0079090_UnitFormSearchAndDestroyChess2Menu.cpp @@ -0,0 +1,135 @@ +//--------------------------------------------------------------------------- +/* + SearchAndDestroyChess 2, Kriegspiel/Dark Chess game + Copyright (C) 2008 Richel Bilderbeek + + 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 . +*/ +//--------------------------------------------------------------------------- +// From http://www.richelbilderbeek.nl +//--------------------------------------------------------------------------- +#include +#include "UnitChessBoard.h" +#include "UnitChessPiece.h" +#include +#pragma hdrstop + +#include "UnitFormSearchAndDestroyChess2Menu.h" +#include "UnitFormAbout.h" +#include "UnitFormSearchAndDestroyChess2.h" +//--------------------------------------------------------------------------- +#pragma package(smart_init) +#pragma resource "*.dfm" +TFormSearchAndDestroyChessMenu *FormSearchAndDestroyChessMenu; +//--------------------------------------------------------------------------- +__fastcall TFormSearchAndDestroyChessMenu::TFormSearchAndDestroyChessMenu(TComponent* Owner) + : TForm(Owner) +{ + /* + this->Width = Screen->Width / 2; + this->Height = Screen->Height / 2; + this->Left = Screen->Width / 4; + this->Top = Screen->Height / 4; + */ + this->Width = 430; + this->Height = 430; + this->Left = (Screen->Width - 430) / 2; + this->Top = (Screen->Height - 430) / 2; + + OnResize(0); +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::PanelQuitClick( + TObject *Sender) +{ + Close(); +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::PanelAboutClick( + TObject *Sender) +{ + boost::shared_ptr form(new TFormAbout(0)); + form->ShowModal(); + +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::PanelStartClick( + TObject *Sender) +{ + const bool isWhiteHuman = ImageWhiteHuman->Visible; + const bool isBlackHuman = ImageBlackHuman->Visible; + boost::shared_ptr form( + new TFormSearchAndDestroyChess2(0, isWhiteHuman, isBlackHuman)); + form->ShowModal(); + +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::FormKeyDown( + TObject *Sender, WORD &Key, TShiftState Shift) +{ + if (Key == 's' || Key == 'S') PanelStartClick(0); + if (Key == 'a' || Key == 'A') PanelAboutClick(0); + if (Key == 'q' || Key == 'Q') PanelQuitClick(0); +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::ImageWhiteClick( + TObject *Sender) +{ + ImageWhiteHuman->Visible = !ImageWhiteHuman->Visible; + ImageWhiteComputer->Visible = !ImageWhiteComputer->Visible; +} +//--------------------------------------------------------------------------- +void __fastcall TFormSearchAndDestroyChessMenu::ImageBlackClick( + TObject *Sender) +{ + ImageBlackHuman->Visible = !ImageBlackHuman->Visible; + ImageBlackComputer->Visible = !ImageBlackComputer->Visible; +} +//--------------------------------------------------------------------------- + +void __fastcall TFormSearchAndDestroyChessMenu::FormResize(TObject *Sender) +{ + const int height = ClientHeight; + const int panelHeight = height / 6; + PanelTitle->Height = panelHeight * 2; + PanelVersus->Height = panelHeight; + PanelStart->Height = panelHeight; + PanelAbout->Height = panelHeight; + PanelQuit->Height = panelHeight; + const int imageHeight = panelHeight - 2; + const int imageWidth = panelHeight - 2; + ImageBlackKing->Height = imageHeight; + ImageWhiteKing->Height = imageHeight; + ImageBlackQueen->Height = imageHeight; + ImageWhiteQueen->Height = imageHeight; + ImageBlackPawn->Height = imageHeight; + ImageWhitePawn->Height = imageHeight; + ImageWhiteHuman->Height = imageHeight; + ImageBlackHuman->Height = imageHeight; + ImageWhiteComputer->Height = imageHeight; + ImageBlackComputer->Height = imageHeight; + + ImageBlackKing->Width = imageWidth; + ImageWhiteKing->Width = imageWidth; + ImageBlackQueen->Width = imageWidth; + ImageWhiteQueen->Width = imageWidth; + ImageBlackPawn->Width = imageWidth; + ImageWhitePawn->Width = imageWidth; + ImageWhiteHuman->Width = imageWidth; + ImageBlackHuman->Width = imageWidth; + ImageWhiteComputer->Width = imageWidth; + ImageBlackComputer->Width = imageWidth; + +} +//--------------------------------------------------------------------------- + diff --git a/pool/shard006/C++/0079095_AlarmManager.cpp b/pool/shard006/C++/0079095_AlarmManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3cbfc64865317ddda2bef70f707c1fa4c635f1e --- /dev/null +++ b/pool/shard006/C++/0079095_AlarmManager.cpp @@ -0,0 +1,161 @@ +#include "AlarmManager.h" + +namespace Alarming { + ValueForHandler AlarmManager::valueFor = 0; + + Element& operator++(Element& element) { + element = static_cast(element + 1); + + return element; + } + + Element& operator++(Element& element, int) { + Element result = element; + ++element; + return result; + } + + int ranges[][2] = { + {0, 59}, // Second + {0, 59}, // Minute + {0, 23}, // Hour + {1, 31}, // Day + {1, 12}, // Month + {1, 7}, // Weekday + {1970, 2099} // Year + }; + + AlarmManager::AlarmManager() { + alarms = new LinkedList(); + } + + AlarmManager::~AlarmManager() { + delete alarms; + } + + bool AlarmManager::matchElement(String target, Element element) { + if(target == "") { + if(element == YEAR) return true; + else return false; + } + if(target == "*") return true; + + if((element == DAY || element == WEEKDAY) && target == "?") return true; + + value_t current; + valueFor(element, ¤t); + + if(target.indexOf(',') >= 0) { + StringStream targetStream = StringStream(target); + String part = targetStream.readStringUntil(','); + + while(part != "") { + if(matchElement(part, element)) return true; + part = targetStream.readStringUntil(','); + } + + return false; + } + + if(target.indexOf('/') >= 0) { + value_t start = target.substring(0, target.indexOf('/')).toInt(); + value_t interval = target.substring(target.indexOf('/') + 1).toInt(); + + start = constrain(start, ranges[(int)element][0], ranges[(int)element][1]); + + for(uint8_t i = 0; i <= ranges[(int)element][1]; i += interval) { + if(i == current) return true; + } + + return false; + } + + if(target.indexOf('-') >= 0) { + value_t start = target.substring(0, target.indexOf('-')).toInt(); + value_t end = target.substring(target.indexOf('-') + 1).toInt(); + + start = constrain(start, ranges[(int)element][0], ranges[(int)element][1]); + end = constrain(end, ranges[(int)element][0], ranges[(int)element][1]); + + if(start <= current && current <= end) return true; + + return false; + } + + return constrain(target.toInt(), ranges[(int)element][0], ranges[(int)element][1]) == current; + } + + bool AlarmManager::check() { + for(uint32_t i = 0; i < alarms->size(); i++) { + Element element; + StringStream alarm = StringStream(alarms->get(i)); + + for(element = MINUTE; element != LAST; element++) { + String target = alarm.readStringUntil(' '); + + if(!matchElement(target, element)) break; + } + + if(element == LAST) return true; + } + + return false; + } + + bool AlarmManager::add(String value) { + for(uint32_t i = 0; i < alarms->size(); i++) { + String alarm = alarms->get(i); + + if(alarm == value) return false; + } + + alarms->add(String(value)); + + return true; + } + + bool AlarmManager::remove(String value) { + if(alarms->size() == 0) return false; + + uint32_t index = -1; + for(uint32_t i = 0; i < alarms->size(); i ++) { + String alarm = alarms->get(i); + + if(alarm == value) { + index = i; + break; + } + } + + if(index >= 0) { + alarms->remove(index); + + return true; + } + + return false; + } + + bool AlarmManager::clear() { + if(alarms->size() == 0) return false; + + alarms->clear(); + + return true; + } + + size_t AlarmManager::printTo(Print& p) const { + size_t result = 0; + + if(alarms->size() > 0) { + for(uint32_t i = 0; i < alarms->size(); i++) { + String value = alarms->get(i); + + result += p.println(value); + } + } + + return result; + } +} + diff --git a/pool/shard006/C++/0079100_wordPickInit.cpp b/pool/shard006/C++/0079100_wordPickInit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e564c2f1409c81636cdc5fa61ac0766130bb4ded --- /dev/null +++ b/pool/shard006/C++/0079100_wordPickInit.cpp @@ -0,0 +1,155 @@ +/********************************************************************* + * + * This file part of WordPick - A Adobe Acrobat/Reader plugin for text + * extraction by mouse click. + * 2006 Dewolf Xue + * 2006 Hu Zheng + * + * This plugin is special for StarDict + * + * Compile under Acrobat SDK 7 + M$ VS 2003. + * + * Copyright 2011 kubtek + * + * This file is part of StarDict. + * + * StarDict 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. + * + * StarDict 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 StarDict. If not, see . + * +*********************************************************************/ +#include "PIHeaders.h" +#include "PIRequir.h" +#include "wordPickUI.h" +#include "../../InterProcessCommunication.h" + +/*------------------------------------------------------- + Constants/Declarations +-------------------------------------------------------*/ + +/*------------------------------------------------------- + Core Handshake Callbacks +-------------------------------------------------------*/ +ACCB1 ASBool ACCB2 PluginExportHFTs(void) +{ + return true; +} + +ACCB1 ASBool ACCB2 PluginImportReplaceAndRegister(void) +{ + return true; +} + +/* PluginInit +** ------------------------------------------------------ +** */ +/** + ** The main initialization routine. + ** + ** @return true to continue loading the plug-in + ** @return false to cause plug-in loading to stop. + ** */ +ACCB1 ASBool ACCB2 PluginInit(void) +{ + ThTypes_Init(); + SetUpUI(); + return true; +} + +/* PluginUnload +** ------------------------------------------------------ +** */ +/** + ** The unload routine. + ** Called when your plug-in is being unloaded when the application quits. + ** Use this routine to release any system resources you may have + ** allocated. + ** + ** Returning false will cause an alert to display that unloading failed. + ** @return true to indicate the plug-in unloaded. +*/ +ACCB1 ASBool ACCB2 PluginUnload(void) +{ + CleanUpUI(); + Thtypes_End(); + return true; +} + +/* GetExtensionName +** ------------------------------------------------------ +** */ +/** + ** Return the unique ASAtom associated with your plug-in. + ** @return the plug-in 's name as an ASAtom. + ** + ** @see ASAtomFromString +*/ +ASAtom GetExtensionName() +{ + return ASAtomFromString("ADBE:WordPick"); +} + +/* +** PIHandshake +** */ +/** + ** Function that provides the initial interface between your plug-in and the application. + ** This function provides the callback functions to the application that allow it to + ** register the plug-in with the application environment. + ** + ** Required Plug-in handshaking routine: Do not change its name! + ** + ** @param handshakeVersion the version this plug-in works with. There are two versions possible, the plug-in version + ** and the application version. The application calls the main entry point for this plug-in with its version. + ** The main entry point will call this function with the version that is earliest. + ** @param handshakeData OUT the data structure used to provide the primary entry points for the plug-in. These + ** entry points are used in registering the plug-in with the application and allowing the plug-in to register for + ** other plug-in services and offer its own. + ** @return true to indicate success, false otherwise (the plug-in will not load). + ** */ +ACCB1 ASBool ACCB2 PIHandshake(Uns32 handshakeVersion, void *handshakeData) +{ + if (handshakeVersion == HANDSHAKE_V0200) { + /* Cast handshakeData to the appropriate type */ + PIHandshakeData_V0200 *hsData = (PIHandshakeData_V0200 *)handshakeData; + + /* Set the name we want to go by */ + hsData->extensionName = GetExtensionName(); + + /* If you export your own HFT, do so in here */ + hsData->exportHFTsCallback = ASCallbackCreateProto(PIExportHFTsProcType, &PluginExportHFTs); + + /* + ** If you import plug-in HFTs, replace functionality, and/or want to register for notifications before + ** the user has a chance to do anything, do so in here. + */ + hsData->importReplaceAndRegisterCallback = ASCallbackCreateProto(PIImportReplaceAndRegisterProcType, + &PluginImportReplaceAndRegister); + + /* Perform your plug-in's initialization in here */ + hsData->initCallback = ASCallbackCreateProto(PIInitProcType, &PluginInit); + + /* Perform any memory freeing or state saving on "quit" in here */ + hsData->unloadCallback = ASCallbackCreateProto(PIUnloadProcType, &PluginUnload); + + /* All done */ + return true; + + } /* Each time the handshake version changes, add a new "else if" branch */ + + /* + ** If we reach here, then we were passed a handshake version number we don't know about. + ** This shouldn't ever happen since our main() routine chose the version number. + */ + AVAlertNote("Error in hand shake"); + return false; +} diff --git a/pool/shard006/C++/0079105_seh.cpp b/pool/shard006/C++/0079105_seh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b5a116f7aaae260007cce5273313e443b580aeb --- /dev/null +++ b/pool/shard006/C++/0079105_seh.cpp @@ -0,0 +1,391 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/*++ + + + +Module Name: + + seh.cpp + +Abstract: + + Implementation of exception API functions. + + + +--*/ + +#include "pal/thread.hpp" +#include "pal/handleapi.hpp" +#include "pal/seh.hpp" +#include "pal/dbgmsg.h" +#include "pal/critsect.h" +#include "pal/debug.h" +#include "pal/init.h" +#include "pal/process.h" +#include "pal/malloc.hpp" +#include "signal.hpp" + +#if HAVE_MACH_EXCEPTIONS +#include "machexception.h" +#else +#include +#endif + +#include +#include +#include +#include + +using namespace CorUnix; + +SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); + +/* Constant and type definitions **********************************************/ + +/* Bit 28 of exception codes is reserved. */ +const UINT RESERVED_SEH_BIT = 0x800000; + +/* Internal variables definitions **********************************************/ + +PHARDWARE_EXCEPTION_HANDLER g_hardwareExceptionHandler = NULL; +// Function to check if an activation can be safely injected at a specified context +PHARDWARE_EXCEPTION_SAFETY_CHECK_FUNCTION g_safeExceptionCheckFunction = NULL; + +PGET_GCMARKER_EXCEPTION_CODE g_getGcMarkerExceptionCode = NULL; + +/* Internal function definitions **********************************************/ + +/*++ +Function : + SEHInitialize + + Initialize all SEH-related stuff (signals, etc) + +Parameters : + CPalThread * pthrCurrent : reference to the current thread. + PAL initialize flags + +Return value : + TRUE if SEH support initialization succeeded + FALSE otherwise +--*/ +BOOL +SEHInitialize (CPalThread *pthrCurrent, DWORD flags) +{ +#if !HAVE_MACH_EXCEPTIONS + if (!SEHInitializeSignals()) + { + ERROR("SEHInitializeSignals failed!\n"); + SEHCleanup(); + return FALSE; + } +#endif + + return TRUE; +} + +/*++ +Function : + SEHCleanup + + Undo work done by SEHInitialize + +Parameters : + None + + (no return value) + +--*/ +VOID +SEHCleanup() +{ + TRACE("Cleaning up SEH\n"); + +#if HAVE_MACH_EXCEPTIONS + SEHCleanupExceptionPort(); +#else + SEHCleanupSignals(); +#endif +} + +/*++ +Function: + PAL_SetHardwareExceptionHandler + + Register a hardware exception handler. + +Parameters: + handler - exception handler + +Return value: + None +--*/ +VOID +PALAPI +PAL_SetHardwareExceptionHandler( + IN PHARDWARE_EXCEPTION_HANDLER exceptionHandler, + IN PHARDWARE_EXCEPTION_SAFETY_CHECK_FUNCTION exceptionCheckFunction) +{ + g_hardwareExceptionHandler = exceptionHandler; + g_safeExceptionCheckFunction = exceptionCheckFunction; +} + +/*++ +Function: + PAL_SetGetGcMarkerExceptionCode + + Register a function that determines if the specified IP has code that is a GC marker for GCCover. + +Parameters: + getGcMarkerExceptionCode - the function to register + +Return value: + None +--*/ +VOID +PALAPI +PAL_SetGetGcMarkerExceptionCode( + IN PGET_GCMARKER_EXCEPTION_CODE getGcMarkerExceptionCode) +{ + g_getGcMarkerExceptionCode = getGcMarkerExceptionCode; +} + +EXTERN_C void ThrowExceptionFromContextInternal(CONTEXT* context, PAL_SEHException* ex); + +/*++ +Function: + PAL_ThrowExceptionFromContext + + This function creates a stack frame right below the target frame, restores all callee + saved registers from the passed in context, sets the RSP to that frame and sets the + return address to the target frame's RIP. + Then it uses the ThrowExceptionHelper to throw the passed in exception from that context. + +Parameters: + CONTEXT* context - context from which the exception will be thrown + PAL_SEHException* ex - the exception to throw. +--*/ +VOID +PALAPI +PAL_ThrowExceptionFromContext(CONTEXT* context, PAL_SEHException* ex) +{ + // We need to make a copy of the exception off stack, since the "ex" is located in one of the stack + // frames that will become obsolete by the ThrowExceptionFromContextInternal and the ThrowExceptionHelper + // could overwrite the "ex" object by stack e.g. when allocating the low level exception object for "throw". + static __thread BYTE threadLocalExceptionStorage[sizeof(PAL_SEHException)]; + ThrowExceptionFromContextInternal(context, new (threadLocalExceptionStorage) PAL_SEHException(*ex)); +} + +/*++ +Function: + ThrowExceptionHelper + + Helper function to throw the passed in exception. + It is called from the assembler function ThrowExceptionFromContextInternal + +Parameters: + PAL_SEHException* ex - the exception to throw. +--*/ +extern "C" +void ThrowExceptionHelper(PAL_SEHException* ex) +{ + throw *ex; +} + +/*++ +Function: + SEHProcessException + + Build the PAL exception and sent it to any handler registered. + +Parameters: + PEXCEPTION_POINTERS pointers + +Return value: + Returns only if the exception is unhandled +--*/ +VOID +SEHProcessException(PEXCEPTION_POINTERS pointers) +{ + if (!IsInDebugBreak(pointers->ExceptionRecord->ExceptionAddress)) + { + PAL_SEHException exception(pointers->ExceptionRecord, pointers->ContextRecord); + + if (g_hardwareExceptionHandler != NULL) + { + _ASSERTE(g_safeExceptionCheckFunction != NULL); + // Check if it is safe to handle the hardware exception (the exception happened in managed code + // or in a jitter helper or it is a debugger breakpoint) + if (g_safeExceptionCheckFunction(pointers->ContextRecord, pointers->ExceptionRecord)) + { + if (pointers->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) + { + // Check if the failed access has hit a stack guard page. In such case, it + // was a stack probe that detected that there is not enough stack left. + void* stackLimit = CPalThread::GetStackLimit(); + void* stackGuard = (void*)((size_t)stackLimit - getpagesize()); + void* violationAddr = (void*)pointers->ExceptionRecord->ExceptionInformation[1]; + if ((violationAddr >= stackGuard) && (violationAddr < stackLimit)) + { + // The exception happened in the page right below the stack limit, + // so it is a stack overflow + write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1); + PROCAbort(); + } + } + + // The following callback returns only in case the exception was a single step or + // a breakpoint and it was not handled by the debugger. + g_hardwareExceptionHandler(&exception); + } + } + + if (CatchHardwareExceptionHolder::IsEnabled()) + { + PAL_ThrowExceptionFromContext(&exception.ContextRecord, &exception); + } + } + + // Unhandled hardware exception pointers->ExceptionRecord->ExceptionCode at pointers->ExceptionRecord->ExceptionAddress +} + +/*++ +Function : + SEHEnable + + Enable SEH-related stuff on this thread + +Parameters: + CPalThread * pthrCurrent : reference to the current thread. + +Return value : + TRUE if enabling succeeded + FALSE otherwise +--*/ +extern "C" +PAL_ERROR SEHEnable(CPalThread *pthrCurrent) +{ +#if HAVE_MACH_EXCEPTIONS + return pthrCurrent->EnableMachExceptions(); +#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) + // TODO: This needs to be implemented. Cannot put an ASSERT here + // because it will make other parts of PAL fail. + return NO_ERROR; +#else// HAVE_MACH_EXCEPTIONS +#error not yet implemented +#endif // HAVE_MACH_EXCEPTIONS +} + +/*++ +Function : + SEHDisable + + Disable SEH-related stuff on this thread + +Parameters: + CPalThread * pthrCurrent : reference to the current thread. + +Return value : + TRUE if enabling succeeded + FALSE otherwise +--*/ +extern "C" +PAL_ERROR SEHDisable(CPalThread *pthrCurrent) +{ +#if HAVE_MACH_EXCEPTIONS + return pthrCurrent->DisableMachExceptions(); + // TODO: This needs to be implemented. Cannot put an ASSERT here + // because it will make other parts of PAL fail. +#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) + return NO_ERROR; +#else // HAVE_MACH_EXCEPTIONS +#error not yet implemented +#endif // HAVE_MACH_EXCEPTIONS +} + +/*++ + + CatchHardwareExceptionHolder implementation + +--*/ + +CatchHardwareExceptionHolder::CatchHardwareExceptionHolder() +{ + CPalThread *pThread = InternalGetCurrentThread(); + ++pThread->m_hardwareExceptionHolderCount; +} + +CatchHardwareExceptionHolder::~CatchHardwareExceptionHolder() +{ + CPalThread *pThread = InternalGetCurrentThread(); + --pThread->m_hardwareExceptionHolderCount; +} + +bool CatchHardwareExceptionHolder::IsEnabled() +{ + CPalThread *pThread = InternalGetCurrentThread(); + return pThread->IsHardwareExceptionsEnabled(); +} + +/*++ + + NativeExceptionHolderBase implementation + +--*/ + +#ifdef __llvm__ +__thread +#else // __llvm__ +__declspec(thread) +#endif // !__llvm__ +static NativeExceptionHolderBase *t_nativeExceptionHolderHead = nullptr; + +NativeExceptionHolderBase::NativeExceptionHolderBase() +{ + m_head = nullptr; + m_next = nullptr; +} + +NativeExceptionHolderBase::~NativeExceptionHolderBase() +{ + // Only destroy if Push was called + if (m_head != nullptr) + { + *m_head = m_next; + m_head = nullptr; + m_next = nullptr; + } +} + +void +NativeExceptionHolderBase::Push() +{ + NativeExceptionHolderBase **head = &t_nativeExceptionHolderHead; + m_head = head; + m_next = *head; + *head = this; +} + +NativeExceptionHolderBase * +NativeExceptionHolderBase::FindNextHolder(NativeExceptionHolderBase *currentHolder, void *stackLowAddress, void *stackHighAddress) +{ + NativeExceptionHolderBase *holder = (currentHolder == nullptr) ? t_nativeExceptionHolderHead : currentHolder->m_next; + + while (holder != nullptr) + { + if (((void *)holder > stackLowAddress) && ((void *)holder < stackHighAddress)) + { + return holder; + } + // Get next holder + holder = holder->m_next; + } + + return nullptr; +} + +#include "seh-unwind.cpp" diff --git a/pool/shard006/C++/0079109_ephemeralshadingresultframebufferfactory.cpp b/pool/shard006/C++/0079109_ephemeralshadingresultframebufferfactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa0d6124b29a393bdec1d5f6e1fb3c0aae8dbd72 --- /dev/null +++ b/pool/shard006/C++/0079109_ephemeralshadingresultframebufferfactory.cpp @@ -0,0 +1,79 @@ + +// +// 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-2015 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 "ephemeralshadingresultframebufferfactory.h" + +// appleseed.renderer headers. +#include "renderer/kernel/aov/imagestack.h" +#include "renderer/kernel/rendering/shadingresultframebuffer.h" +#include "renderer/modeling/frame/frame.h" + +// appleseed.foundation headers. +#include "foundation/image/image.h" +#include "foundation/image/tile.h" + +using namespace foundation; + +namespace renderer +{ + +void EphemeralShadingResultFrameBufferFactory::release() +{ + delete this; +} + +ShadingResultFrameBuffer* EphemeralShadingResultFrameBufferFactory::create( + const Frame& frame, + const size_t tile_x, + const size_t tile_y, + const AABB2u& tile_bbox) +{ + const Tile& tile = frame.image().tile(tile_x, tile_y); + + ShadingResultFrameBuffer* framebuffer = + new ShadingResultFrameBuffer( + tile.get_width(), + tile.get_height(), + frame.aov_images().size(), + tile_bbox, + frame.get_filter()); + + framebuffer->clear(); + + return framebuffer; +} + +void EphemeralShadingResultFrameBufferFactory::destroy( + ShadingResultFrameBuffer* framebuffer) +{ + delete framebuffer; +} + +} // namespace renderer diff --git a/pool/shard006/C++/0079118_main.cpp b/pool/shard006/C++/0079118_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..517efe182412f0e45674e43a59c9b7a5dde45d73 --- /dev/null +++ b/pool/shard006/C++/0079118_main.cpp @@ -0,0 +1,111 @@ +#include +#include +#include +using namespace std; + +double f(double x) +{ + return pow(x, 3) - 2 * pow(x, 2) - 11 * x + 12; +} + +double fh(double x) +{ + return 3 * pow(x, 2) - 4 * x - 11; +} + +double findHord(double a, double b, double e) // a, b - ïðåäåëû õîðäû, e - íåîáõîäèìàÿ ïîãðåøíîñòü +{ + int count = 0; + while (fabs(b - a) >= e) + { + count++; + a = b - (b - a) * f(b) / (f(b) - f(a)); // i-1 + b = a - (a - b) * f(a) / (f(a) - f(b)); // i + } + cout << '\t' << count << '\t'; + return b; +} + +double findIter(double x, double e) // x - òî÷êà âõîäà, e - íåîáõîäèìàÿ ïîãðåøíîñòü +{ + int count = 0; + double l, x_prev; + l = 1 / fh(x); + do { + if ((fh(x) > 0 && l < 0) || (fh(x) < 0 && l > 0)) l *= -1; + x_prev = x; + x = x-l*f(x); + count++; + } while (fabs(x_prev - x) >= e); + cout << '\t' << count<< '\t'; + return x; +} + +int main() +{ + setlocale(LC_ALL, "Russian"); + double a = 0., b = 0., e = 0., x = 0.; + + cout << "Äëÿ óðàâíåíèÿ x^3-2x^2-11x+12. // -3 1 4" << endl; + cout << "Ââåäèòå äàííûå î îòðåçêå, íà êîòîðîì áóäåì èñêàòü ïðîìåæóòêè: "; + cin >> a >> b; + + bool isRun = false; + do{ + + int m = 0; + + cout << "Ââåäèòå ïîãðåøíîñòü: "; + cin >> e; + + cout << "\nÂûáèðèòå ìåòîä: 0 - õîðä, 1 - ïðîñòûõ èòåðàöèé\nÂàø âûáîð: "; + cin >> m; + + if (m == 0) + { + double now = f(a), fut = 0.; + for (double i = a; i < b; i+=1.5) + { + fut = f(i + 1); + + if ((now >= 0 && fut <= 0) || (now <= 0 && fut >= 0)) + { + double zn = findHord(i, i + 1, e); + if (zn < 999 || zn > 999) + { + //cout << "Îòëàäêà: " << now << ", " << fut << ", èíòåðâàë (" << i << "," << i + 1 << ")\n"; + cout << "Òî÷êà ïåðå÷å÷åíèÿ íà îòðåçêå [" << i << ", " << i + 1 << "], ïðèõîäèòñÿ íà (" << zn << ", 0)." << endl; + } + } + now = fut; + } + } + else + { + double now = f(a), fut = 0.; + for (double i = a; i < b; i ++) + { + fut = f(i + 1); + if ((now >= 0 && fut <= 0) || (now <= 0 && fut >= 0)) + { + double zn = findIter(i, e); + if (zn < 999 || zn > 999) + { + //cout << "Îòëàäêà: " << now << ", " << fut << ", èíòåðâàë (" << i << "," << i + 1 << ")\n"; + cout << "Òî÷êà ïåðå÷å÷åíèÿ, ïðè âõîæå â òî÷êå " << i << ", ïðèõîäèòñÿ íà (" << zn << ", 0)." << endl; + } + } + now = fut; + } + } + char run; + cout << "Õîòèòå ïðîäîëæèòü? (Y|N) "; + cin >> run; + if (run == 'Y' || run == 'y') isRun = true; + else isRun = false; + } while (isRun); + + return 0; + cin.get(); + cin.get(); +} \ No newline at end of file diff --git a/pool/shard006/C++/0079119_osd_info.cc b/pool/shard006/C++/0079119_osd_info.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d99ab811fd5774b12de53719411b9384856b71c --- /dev/null +++ b/pool/shard006/C++/0079119_osd_info.cc @@ -0,0 +1,134 @@ +/* + Copyright (C) iNuron - info@openvstorage.com + This file is part of Open vStorage. For license information, see +*/ + + +#include "osd_info.h" +#include "alba_logger.h" +#include "llio.h" +#include "stuff.h" +#include + +namespace alba { +namespace llio { + +template <> void from(message &m, proxy_protocol::OsdInfo &info) { + uint8_t version; + from(m, version); + if (version != 3) { + throw deserialisation_exception( + "unexpected version while deserializing OsdInfo"); + } + std::string inner_s; + from(m, inner_s); + auto mb = message_buffer::from_string(inner_s); + std::vector inner_v(inner_s.begin(), inner_s.end()); + message inner(mb); + + uint8_t kind; + from(inner, kind); + if (kind != 1) { + info.kind_asd = false; + return; + } + info.kind_asd = true; + from(inner, info.ips); + from(inner, info.port); + from(inner, info.use_tls); + from(inner, info.use_rdma); + from(inner, info.long_id); + from(inner, info.node_id); + /* +TODO could someday also deserialize the following properties (if they would be +useful here): +decommissioned +other +total +used +seen +read +write +errors +checksum_errors +*/ +} + +template <> void from(message &m, proxy_protocol::OsdCapabilities &caps) { + uint32_t size; + from(m, size); + for (uint i = 0; i < size; i++) { + uint8_t version; + from(m, version); + + uint32_t length; + if (version == 1) { + length = 0; + } else if (version == 2) { + from(m, length); + } else { + throw deserialisation_exception( + "unexpected version while deserializing OsdCapabilities"); + } + uint32_t pos0 = m.get_pos(); + + uint8_t tag; + from(m, tag); + switch (tag) { + case 1: { + }; break; // for now, we don't care + case 2: { + }; break; + case 3: { + uint32_t port; + from(m, port); + caps.rora_port.emplace(port); + }; break; + case 4: { + std::vector rora_ips; + from(m, rora_ips); + caps.rora_ips.emplace(rora_ips); + uint32_t port; + from(m, port); + caps.rora_port.emplace(port); + std::string transport; + from(m, transport); + caps.rora_transport.emplace(transport); + } + default: { + if (length == 0) { + throw deserialisation_exception("OsdCapabilities"); + } + }; + } + + if (length != 0) { + uint32_t pos1 = m.get_pos(); + uint32_t actual_length = pos1 - pos0; + if (actual_length > length) { + throw deserialisation_exception("OsdCapabilities"); + } else if (actual_length < length) { + m.skip(length - actual_length); + } + } + } +} +} +namespace proxy_protocol { +std::ostream &operator<<(std::ostream &os, const OsdInfo &info) { + using alba::stuff::operator<<; + os << "OsdInfo(" + << " port=" << info.port << ", ips= " << info.ips + << ", use_tls=" << info.use_tls << ", use_rdma=" << info.use_rdma << ")"; + return os; +} + +std::ostream &operator<<(std::ostream &os, const OsdCapabilities &caps) { + using alba::stuff::operator<<; + os << "OsdCapabilities( rora_port= " << caps.rora_port + << ", rora_transport= " << caps.rora_transport + << ", rora_ips=" << caps.rora_ips << ")"; + return os; +} +} +} diff --git a/pool/shard006/C++/0079121_qgsmaptooldeletepart.cpp b/pool/shard006/C++/0079121_qgsmaptooldeletepart.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68061506c7a4da6903bee9aaa5a822326b72c2db --- /dev/null +++ b/pool/shard006/C++/0079121_qgsmaptooldeletepart.cpp @@ -0,0 +1,210 @@ +/*************************************************************************** + qgsmaptooldeletepart.cpp - delete a part from multipart geometry + --------------------- + begin : April 2009 + copyright : (C) 2009 by Richard Kostecky + email : csf dot kostej at mail 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 "qgsmaptooldeletepart.h" + +#include "qgsmapcanvas.h" +#include "qgsvertexmarker.h" +#include "qgsvectorlayer.h" +#include "qgsgeometry.h" +#include "qgssnappingutils.h" +#include "qgstolerance.h" +#include "qgisapp.h" + +#include + +QgsMapToolDeletePart::QgsMapToolDeletePart( QgsMapCanvas* canvas ) + : QgsMapToolEdit( canvas ) + , vlayer( nullptr ) + , mRubberBand( nullptr ) + , mPressedFid( 0 ) + , mPressedPartNum( 0 ) +{ + mToolName = tr( "Delete part" ); +} + +QgsMapToolDeletePart::~QgsMapToolDeletePart() +{ + delete mRubberBand; +} + +void QgsMapToolDeletePart::canvasMoveEvent( QgsMapMouseEvent* e ) +{ + Q_UNUSED( e ); + //nothing to do +} + +void QgsMapToolDeletePart::canvasPressEvent( QgsMapMouseEvent* e ) +{ + mPressedFid = -1; + mPressedPartNum = -1; + delete mRubberBand; + mRubberBand = nullptr; + + QgsMapLayer* currentLayer = mCanvas->currentLayer(); + if ( !currentLayer ) + return; + + vlayer = qobject_cast( currentLayer ); + if ( !vlayer ) + { + notifyNotVectorLayer(); + return; + } + + if ( !vlayer->isEditable() ) + { + notifyNotEditableLayer(); + return; + } + + QgsGeometry* geomPart = partUnderPoint( e->pos(), mPressedFid, mPressedPartNum ); + + if ( mPressedFid != -1 ) + { + mRubberBand = createRubberBand( vlayer->geometryType() ); + + mRubberBand->setToGeometry( geomPart, vlayer ); + mRubberBand->show(); + } + + delete geomPart; +} + +void QgsMapToolDeletePart::canvasReleaseEvent( QgsMapMouseEvent* e ) +{ + Q_UNUSED( e ); + + delete mRubberBand; + mRubberBand = nullptr; + + if ( !vlayer || !vlayer->isEditable() ) + { + return; + } + + if ( mPressedFid == -1 ) + return; + + QgsFeature f; + vlayer->getFeatures( QgsFeatureRequest().setFilterFid( mPressedFid ) ).nextFeature( f ); + QgsGeometry* g = f.geometry(); + + if ( g->deletePart( mPressedPartNum ) ) + { + vlayer->beginEditCommand( tr( "Part of multipart feature deleted" ) ); + vlayer->changeGeometry( f.id(), g ); + vlayer->endEditCommand(); + vlayer->triggerRepaint(); + } + else + { + emit messageEmitted( tr( "Couldn't remove the selected part." ) ); + } + return; +} + +QgsGeometry* QgsMapToolDeletePart::partUnderPoint( QPoint point, QgsFeatureId& fid, int& partNum ) +{ + QgsFeature f; + QgsGeometry* geomPart = new QgsGeometry(); + + switch ( vlayer->geometryType() ) + { + case QGis::Point: + case QGis::Line: + { + QgsPointLocator::Match match = mCanvas->snappingUtils()->snapToCurrentLayer( point, QgsPointLocator::Vertex | QgsPointLocator::Edge ); + if ( !match.isValid() ) + return geomPart; + + int snapVertex = match.vertexIndex(); + vlayer->getFeatures( QgsFeatureRequest().setFilterFid( match.featureId() ) ).nextFeature( f ); + const QgsGeometry* g = f.constGeometry(); + if ( !g->isMultipart() ) + { + fid = match.featureId(); + delete geomPart; + return QgsGeometry::fromPoint( match.point() ); + } + if ( g->wkbType() == QGis::WKBMultiPoint || g->wkbType() == QGis::WKBMultiPoint25D ) + { + fid = match.featureId(); + partNum = snapVertex; + delete geomPart; + return QgsGeometry::fromPoint( match.point() ); + } + if ( g->wkbType() == QGis::WKBMultiLineString || g->wkbType() == QGis::WKBMultiLineString25D ) + { + QgsMultiPolyline mline = g->asMultiPolyline(); + for ( int part = 0; part < mline.count(); part++ ) + { + if ( snapVertex < mline[part].count() ) + { + fid = match.featureId(); + partNum = part; + delete geomPart; + return QgsGeometry::fromPolyline( mline[part] ); + } + snapVertex -= mline[part].count(); + } + } + break; + } + case QGis::Polygon: + { + QgsPoint layerCoords = toLayerCoordinates( vlayer, point ); + double searchRadius = QgsTolerance::vertexSearchRadius( mCanvas->currentLayer(), mCanvas->mapSettings() ); + QgsRectangle selectRect( layerCoords.x() - searchRadius, layerCoords.y() - searchRadius, + layerCoords.x() + searchRadius, layerCoords.y() + searchRadius ); + QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectRect ) ); + fit.nextFeature( f ); + const QgsGeometry* g = f.constGeometry(); + if ( !g ) + return geomPart; + if ( !g->isMultipart() ) + { + fid = f.id(); + return geomPart; + } + QgsMultiPolygon mpolygon = g->asMultiPolygon(); + for ( int part = 0; part < mpolygon.count(); part++ ) // go through the polygons + { + const QgsPolygon& polygon = mpolygon[part]; + QgsGeometry* partGeo = QgsGeometry::fromPolygon( polygon ); + if ( partGeo->contains( &layerCoords ) ) + { + fid = f.id(); + partNum = part; + delete geomPart; + return partGeo; + } + delete partGeo; + } + break; + } + default: + { + break; + } + } + return geomPart; +} + +void QgsMapToolDeletePart::deactivate() +{ + QgsMapTool::deactivate(); +} + diff --git a/pool/shard006/C++/0079125_ScenarioTrainCacla.cpp b/pool/shard006/C++/0079125_ScenarioTrainCacla.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6efc04ec17c430e27daf577ad25f622240c6c73 --- /dev/null +++ b/pool/shard006/C++/0079125_ScenarioTrainCacla.cpp @@ -0,0 +1,147 @@ +#include "ScenarioTrainCacla.h" +#include "ScenarioExpCacla.h" +#include "util/FileUtil.h" +#include "sim/BaseControllerCacla.h" +#include "learning/CaclaTrainer.h" +#include "learning/AsyncCaclaTrainer.h" +#include "learning/ACLearner.h" + +cScenarioTrainCacla::cScenarioTrainCacla() +{ + mTrainerParams.mPoolSize = 1; +} + +cScenarioTrainCacla::~cScenarioTrainCacla() +{ +} + +void cScenarioTrainCacla::ParseArgs(const cArgParser& parser) +{ + cScenarioTrain::ParseArgs(parser); + parser.ParseString("critic_solver", mCriticSolverFile); + parser.ParseString("critic_net", mCriticNetFile); + parser.ParseString("critic_model", mCriticModelFile); + + mActorSolverFile = mTrainerParams.mSolverFile; + mActorNetFile = mTrainerParams.mNetFile; + mActorModelFile = mPoliModelFile; + + mTrainerParams.mSolverFile = mCriticSolverFile; + mTrainerParams.mNetFile = mCriticNetFile; +} + +std::string cScenarioTrainCacla::GetName() const +{ + return "Train Cacla"; +} + +void cScenarioTrainCacla::BuildTrainer(std::shared_ptr& out_trainer) +{ + if (mEnableAsyncMode) + { + auto trainer = std::shared_ptr(new cAsyncCaclaTrainer()); + trainer->SetActorFiles(mActorSolverFile, mActorNetFile); + out_trainer = trainer; + } + else + { + auto trainer = std::shared_ptr(new cCaclaTrainer()); + trainer->SetActorFiles(mActorSolverFile, mActorNetFile); + out_trainer = trainer; + } +} + +void cScenarioTrainCacla::LoadModel() +{ + if (mCriticModelFile != "") + { + mTrainer->LoadCriticModel(mCriticModelFile); + } + + if (mActorModelFile != "") + { + mTrainer->LoadActorModel(mActorModelFile); + } +} + +void cScenarioTrainCacla::BuildExpScene(std::shared_ptr& out_exp) const +{ + out_exp = std::shared_ptr(new cScenarioExpCacla()); +} + +void cScenarioTrainCacla::SetupLearner(const std::shared_ptr& character, std::shared_ptr& out_learner) const +{ + cScenarioTrain::SetupLearner(character, out_learner); + + auto ac_ctrl = std::dynamic_pointer_cast(character->GetController()); + if (ac_ctrl != nullptr) + { + auto ac_learner = std::static_pointer_cast(out_learner); + cNeuralNet& critic = ac_ctrl->GetCritic(); + ac_learner->SetCriticNet(&critic); + } + else + { + assert(false); // controller does not support actor-critic + } +} + +void cScenarioTrainCacla::SetupTrainerOutputOffsetScale() +{ + SetupTrainerCriticOutputOffsetScale(); + SetupTrainerActorOutputOffsetScale(); +} + +void cScenarioTrainCacla::SetupTrainerCriticOutputOffsetScale() +{ + bool valid_init_model = mTrainer->HasCriticInitModel(); + if (!valid_init_model) + { + int critic_output_size = mTrainer->GetCriticOutputSize(); + + const std::shared_ptr& ctrl = GetRefController(); + std::shared_ptr cacla_ctrl = std::dynamic_pointer_cast(ctrl); + + if (cacla_ctrl != nullptr) + { + Eigen::VectorXd critic_output_offset; + Eigen::VectorXd critic_output_scale; + cacla_ctrl->BuildCriticOutputOffsetScale(critic_output_offset, critic_output_scale); + + assert(critic_output_offset.size() == critic_output_size); + assert(critic_output_scale.size() == critic_output_size); + mTrainer->SetCriticOutputOffsetScale(critic_output_offset, critic_output_scale); + } + else + { + assert(false); // controller does not implement actor-critic interface + } + } +} + +void cScenarioTrainCacla::SetupTrainerActorOutputOffsetScale() +{ + bool valid_init_model = mTrainer->HasCriticInitModel(); + if (!valid_init_model) + { + int actor_output_size = mTrainer->GetActorOutputSize(); + + const std::shared_ptr& ctrl = GetRefController(); + std::shared_ptr cacla_ctrl = std::dynamic_pointer_cast(ctrl); + + if (cacla_ctrl != nullptr) + { + Eigen::VectorXd actor_output_offset; + Eigen::VectorXd actor_output_scale; + cacla_ctrl->BuildActorOutputOffsetScale(actor_output_offset, actor_output_scale); + + assert(actor_output_offset.size() == actor_output_size); + assert(actor_output_scale.size() == actor_output_size); + mTrainer->SetActorOutputOffsetScale(actor_output_offset, actor_output_scale); + } + else + { + assert(false); // controller does not support CACLA + } + } +} \ No newline at end of file diff --git a/pool/shard006/C++/0079127_frame_audible_voter.cc b/pool/shard006/C++/0079127_frame_audible_voter.cc new file mode 100644 index 0000000000000000000000000000000000000000..238b0415166663b06937af258765f576f3c2a9e9 --- /dev/null +++ b/pool/shard006/C++/0079127_frame_audible_voter.cc @@ -0,0 +1,59 @@ +// 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 "components/performance_manager/execution_context_priority/frame_audible_voter.h" + +#include + +#include "components/performance_manager/public/execution_context/execution_context_registry.h" + +namespace performance_manager { +namespace execution_context_priority { + +namespace { + +const execution_context::ExecutionContext* GetExecutionContext( + const FrameNode* frame_node) { + return execution_context::ExecutionContextRegistry::GetFromGraph( + frame_node->GetGraph()) + ->GetExecutionContextForFrameNode(frame_node); +} + +// Returns a vote with the appropriate priority depending on if the frame is +// audible. +Vote GetVote(bool is_audible) { + base::TaskPriority priority = is_audible ? base::TaskPriority::USER_BLOCKING + : base::TaskPriority::LOWEST; + return Vote(priority, FrameAudibleVoter::kFrameAudibleReason); +} + +} // namespace + +// static +const char FrameAudibleVoter::kFrameAudibleReason[] = "Frame audible."; + +FrameAudibleVoter::FrameAudibleVoter() = default; + +FrameAudibleVoter::~FrameAudibleVoter() = default; + +void FrameAudibleVoter::SetVotingChannel(VotingChannel voting_channel) { + voting_channel_ = std::move(voting_channel); +} + +void FrameAudibleVoter::OnFrameNodeAdded(const FrameNode* frame_node) { + const Vote vote = GetVote(frame_node->IsAudible()); + voting_channel_.SubmitVote(GetExecutionContext(frame_node), vote); +} + +void FrameAudibleVoter::OnBeforeFrameNodeRemoved(const FrameNode* frame_node) { + voting_channel_.InvalidateVote(GetExecutionContext(frame_node)); +} + +void FrameAudibleVoter::OnIsAudibleChanged(const FrameNode* frame_node) { + const Vote new_vote = GetVote(frame_node->IsAudible()); + voting_channel_.ChangeVote(GetExecutionContext(frame_node), new_vote); +} + +} // namespace execution_context_priority +} // namespace performance_manager diff --git a/pool/shard006/C++/0079129_delete-exp.cpp b/pool/shard006/C++/0079129_delete-exp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5044e5b16ad9ed8464cd5eeb357ef5de23c2d645 --- /dev/null +++ b/pool/shard006/C++/0079129_delete-exp.cpp @@ -0,0 +1,69 @@ +#include "stdafx.h" +#include +#include +#include +#include "benchmark-util.cpp" +#include "multimodal.cpp" + +PSOut StdOut = TStdOut::New(); + +template +void DelNodeExp(const PGraph& Graph, const TStrV& DeletedNStrV, const TStrIntH& NStrH) { + for (int i = 0; i < DeletedNStrV.Len(); i++) { + TStr NStr = DeletedNStrV[i]; + TInt NId = NStrH.GetDat(NStr); + Graph->DelNode(NId); + } +} + +int main(int argc, char* argv[]) { + TEnv Env(argc, argv); + TStr PrefixPath = Env.GetArgs() > 1 ? Env.GetArg(1) : TStr(""); + + double ts1 = Tick(); + TTableContext Context; + TVec NodeTblV = TVec(); + TVec > EdgeTblV = TVec >(); + Schema NodeSchema = Schema(); + Schema EdgeSchema = Schema(); + LoadFlickrTables(PrefixPath, Context, NodeTblV, NodeSchema, EdgeTblV, EdgeSchema); + + double ts2 = Tick(); + + TStrV DeletedNStrV; + LoadMixedTypeNodeList(PrefixPath, TStr("rand_node_ids_deleted.tsv"), DeletedNStrV); + + double ts3 = Tick(); + + TStrIntH NStrH; + TIntStrH NIdH; + CreateIdHashes(NodeTblV, NStrH, NIdH); + + double ts4 = Tick(); + + double convertTime = 0; + double deleteTime = 0; + int nExps = 10; + + for (int i = 0; i < nExps; i++) { + double t1 = Tick(); + //PNEANet Graph = LoadGraph(NodeTblV, EdgeTblV, NStrH, NIdH); + PMVNet Graph = LoadGraphMNet(NodeTblV, EdgeTblV, NStrH, NIdH); + StdOut->PutStrFmtLn("Size %d-%d", Graph->GetNodes(), Graph->GetEdges()); + double t2 = Tick(); + DelNodeExp(Graph, DeletedNStrV, NStrH); + double t3 = Tick(); + StdOut->PutStrFmtLn("Size %d-%d", Graph->GetNodes(), Graph->GetEdges()); + convertTime += (t2-t1); + deleteTime += (t3-t2); + } + + PSOut TimeOut = TFOut::New(PrefixPath + TStr("time.txt"), true); + TimeOut->PutStrFmtLn("Loading Graph Tables = %f s", GetCPUTimeUsage(ts1, ts2)); + TimeOut->PutStrFmtLn("Loading Deleted Nodes = %f s", GetCPUTimeUsage(ts2, ts3)); + TimeOut->PutStrFmtLn("Preprocessing = %f s", GetCPUTimeUsage(ts3, ts4)); + TimeOut->PutStrFmtLn("Conversion = %f s", convertTime/nExps); + TimeOut->PutStrFmtLn("Node Deletion = %f s", deleteTime/nExps); + + return 0; +} diff --git a/pool/shard006/C++/0079132_zm_font.cpp b/pool/shard006/C++/0079132_zm_font.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ecaaa6b1c020e64cf707734102089ec18a76657 --- /dev/null +++ b/pool/shard006/C++/0079132_zm_font.cpp @@ -0,0 +1,122 @@ +/* + * This file is part of the ZoneMinder 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, see . + */ + +#include "zm_font.h" + +#include +#include + +constexpr uint8 kRequiredZmFntVersion = 1; + +constexpr uint8 FontVariant::kMaxNumCodePoints; +constexpr uint8 FontVariant::kMaxCharHeight; +constexpr uint8 FontVariant::kMaxCharWidth; + +FontVariant::FontVariant() : char_height_(0), char_width_(0), char_padding_(0), codepoint_count_(0) {} + +FontVariant::FontVariant(uint16 char_height, uint16 char_width, uint8 char_padding, std::vector bitmap) + : char_height_(char_height), char_width_(char_width), char_padding_(char_padding), bitmap_(std::move(bitmap)) { + if (char_height_ > kMaxCharHeight) { + throw std::invalid_argument("char_height > kMaxCharHeight"); + } + + if (char_width_ > kMaxCharWidth) { + throw std::invalid_argument("char_width > kMaxCharWidth"); + } + + if (bitmap_.size() % char_height_ != 0) { + throw std::invalid_argument("bitmap has wrong length"); + } + + codepoint_count_ = bitmap_.size() / char_height; +} + +nonstd::span FontVariant::GetCodepoint(uint8 idx) const { + static constexpr std::array empty_bitmap = {}; + + if (idx >= GetCodepointsCount()) { + return {empty_bitmap.begin(), GetCharHeight()}; + } + + return {bitmap_.begin() + (idx * GetCharHeight()), GetCharHeight()}; +} + +std::ifstream &operator>>(std::ifstream &stream, FontBitmapHeader &bm_header) { + stream.read(reinterpret_cast(&bm_header), sizeof(bm_header)); + + return stream; +} + +std::ifstream &operator>>(std::ifstream &stream, FontFileHeader &header) { + stream.read(header.magic, sizeof(header.magic)); + stream.read(reinterpret_cast(&header.version), sizeof(header.version)); + stream.seekg(sizeof(header.pad), std::ifstream::cur); + + for (FontBitmapHeader &bm_header : header.bitmap_header) + stream >> bm_header; + + return stream; +} + +FontLoadError ZmFont::LoadFontFile(const std::string &loc) { + std::ifstream font_file(loc, std::ifstream::binary); + font_file.exceptions(std::ifstream::badbit); + + if (!font_file.is_open()) { + return FontLoadError::kFileNotFound; + } + + FontFileHeader file_header = {}; + font_file >> file_header; + + if (font_file.fail()) { + return FontLoadError::kInvalidFile; + } + + if (memcmp(file_header.magic, "ZMFNT", 5) != 0 || file_header.version != kRequiredZmFntVersion) { + return FontLoadError::kInvalidFile; + } + + for (int i = 0; i < kNumFontSizes; i++) { + FontBitmapHeader bitmap_header = file_header.bitmap_header[i]; + + if (bitmap_header.char_width > FontVariant::kMaxCharWidth + || bitmap_header.char_height > FontVariant::kMaxCharHeight + || bitmap_header.number_of_code_points > FontVariant::kMaxNumCodePoints) { + return FontLoadError::kInvalidFile; + } + + std::vector bitmap; + bitmap.resize(bitmap_header.number_of_code_points * bitmap_header.char_height); + + std::size_t bitmap_bytes = bitmap.size() * sizeof(uint64); + font_file.read(reinterpret_cast(bitmap.data()), static_cast(bitmap_bytes)); + + variants_[i] = + {bitmap_header.char_height, bitmap_header.char_width, bitmap_header.char_padding, std::move(bitmap)}; + } + + if (font_file.fail()) { + return FontLoadError::kInvalidFile; + } + + return FontLoadError::kOk; +} + +const FontVariant &ZmFont::GetFontVariant(uint8 idx) const { + return variants_.at(idx); +} diff --git a/pool/shard006/C++/0079134_mock_media_constraint_factory.cc b/pool/shard006/C++/0079134_mock_media_constraint_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..5708d50bf2f1e061da480cdbcbfa729a2795df4c --- /dev/null +++ b/pool/shard006/C++/0079134_mock_media_constraint_factory.cc @@ -0,0 +1,101 @@ +// 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 "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/renderer/media/mock_media_constraint_factory.h" +#include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h" + +namespace content { + +namespace { + +static const char kValueTrue[] = "true"; +static const char kValueFalse[] = "false"; + +} // namespace + +MockMediaConstraintFactory::MockMediaConstraintFactory() { +} + +MockMediaConstraintFactory::~MockMediaConstraintFactory() { +} + +blink::WebMediaConstraints +MockMediaConstraintFactory::CreateWebMediaConstraints() { + blink::WebVector mandatory(mandatory_); + blink::WebVector optional(optional_); + blink::WebMediaConstraints constraints; + constraints.initialize(optional, mandatory); + return constraints; +} + +void MockMediaConstraintFactory::AddMandatory(const std::string& key, + int value) { + mandatory_.push_back(blink::WebMediaConstraint(base::UTF8ToUTF16(key), + base::IntToString16(value))); +} + +void MockMediaConstraintFactory::AddMandatory(const std::string& key, + double value) { + mandatory_.push_back(blink::WebMediaConstraint( + base::UTF8ToUTF16(key), + base::UTF8ToUTF16(base::DoubleToString(value)))); +} + +void MockMediaConstraintFactory::AddMandatory(const std::string& key, + const std::string& value) { + mandatory_.push_back(blink::WebMediaConstraint( + base::UTF8ToUTF16(key), base::UTF8ToUTF16(value))); +} + +void MockMediaConstraintFactory::AddMandatory(const std::string& key, + bool value) { + const std::string string_value = value ? kValueTrue : kValueFalse; + AddMandatory(key, string_value); +} + +void MockMediaConstraintFactory::AddOptional(const std::string& key, + int value) { + optional_.push_back(blink::WebMediaConstraint(base::UTF8ToUTF16(key), + base::IntToString16(value))); +} + +void MockMediaConstraintFactory::AddOptional(const std::string& key, + double value) { + optional_.push_back(blink::WebMediaConstraint( + base::UTF8ToUTF16(key), + base::UTF8ToUTF16(base::DoubleToString(value)))); +} + +void MockMediaConstraintFactory::AddOptional(const std::string& key, + const std::string& value) { + optional_.push_back(blink::WebMediaConstraint( + base::UTF8ToUTF16(key), base::UTF8ToUTF16(value))); +} + +void MockMediaConstraintFactory::AddOptional(const std::string& key, + bool value) { + const std::string string_value = value ? kValueTrue : kValueFalse; + AddOptional(key, string_value); +} + +void MockMediaConstraintFactory::DisableDefaultAudioConstraints() { + static const char* kDefaultAudioConstraints[] = { + webrtc::MediaConstraintsInterface::kEchoCancellation, + webrtc::MediaConstraintsInterface::kExperimentalEchoCancellation, + webrtc::MediaConstraintsInterface::kAutoGainControl, + webrtc::MediaConstraintsInterface::kExperimentalAutoGainControl, + webrtc::MediaConstraintsInterface::kNoiseSuppression, + webrtc::MediaConstraintsInterface::kHighpassFilter, + webrtc::MediaConstraintsInterface::kTypingNoiseDetection, + webrtc::MediaConstraintsInterface::kExperimentalNoiseSuppression + }; + MockMediaConstraintFactory factory; + for (size_t i = 0; i < arraysize(kDefaultAudioConstraints); ++i) { + AddMandatory(kDefaultAudioConstraints[i], false); + } +} + +} // namespace content diff --git a/pool/shard006/C++/0079140_examine_ffmpeg_subtitles_job.cc b/pool/shard006/C++/0079140_examine_ffmpeg_subtitles_job.cc new file mode 100644 index 0000000000000000000000000000000000000000..b2bba11cd05707acf1c32647e48dc2754bcd3d2a --- /dev/null +++ b/pool/shard006/C++/0079140_examine_ffmpeg_subtitles_job.cc @@ -0,0 +1,112 @@ +/* + Copyright (C) 2019 Carl Hetherington + + This file is part of DCP-o-matic. + + DCP-o-matic 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. + + DCP-o-matic 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 DCP-o-matic. If not, see . + +*/ + +#include "examine_ffmpeg_subtitles_job.h" +#include "ffmpeg_content.h" +#include "ffmpeg_subtitle_stream.h" +#include "text_content.h" +#include "cross.h" +extern "C" { +#include +#include +} +#include + +#include "i18n.h" + +using std::string; +using std::cout; +using boost::shared_ptr; + +ExamineFFmpegSubtitlesJob::ExamineFFmpegSubtitlesJob (shared_ptr film, shared_ptr c) + : Job (film) + , FFmpeg (c) + , _content (c) +{ + +} + +ExamineFFmpegSubtitlesJob::~ExamineFFmpegSubtitlesJob () +{ + stop_thread (); +} + +string +ExamineFFmpegSubtitlesJob::name () const +{ + return _("Examining subtitles"); +} + +string +ExamineFFmpegSubtitlesJob::json_name () const +{ + return N_("examine_subtitles"); +} + +void +ExamineFFmpegSubtitlesJob::run () +{ + int64_t const len = _file_group.length (); + while (true) { + int r = av_read_frame (_format_context, &_packet); + if (r < 0) { + break; + } + + if (len > 0) { + set_progress (float(_format_context->pb->pos) / len); + } else { + set_progress_unknown (); + } + + if (_content->subtitle_stream() && _content->subtitle_stream()->uses_index(_format_context, _packet.stream_index) && _content->only_text()->use()) { + int got_subtitle; + AVSubtitle sub; + if (avcodec_decode_subtitle2(subtitle_codec_context(), &sub, &got_subtitle, &_packet) >= 0 && got_subtitle) { + for (unsigned int i = 0; i < sub.num_rects; ++i) { + AVSubtitleRect const * rect = sub.rects[i]; + if (rect->type == SUBTITLE_BITMAP) { +#ifdef DCPOMATIC_HAVE_AVSUBTITLERECT_PICT + /* sub_p looks up into a BGRA palette which is here + (i.e. first byte B, second G, third R, fourth A) + */ + uint8_t const * palette = rect->pict.data[1]; +#else + /* sub_p looks up into a BGRA palette which is here + (i.e. first byte B, second G, third R, fourth A) + */ + uint8_t const * palette = rect->data[1]; +#endif + for (int j = 0; j < rect->nb_colors; ++j) { + RGBA c (palette[2], palette[1], palette[0], palette[3]); + _content->subtitle_stream()->set_colour (c, c); + palette += 4; + } + } + } + } + } + + av_packet_unref (&_packet); + } + + set_progress (1); + set_state (FINISHED_OK); +} diff --git a/pool/shard006/C++/0079150_bloom.cpp b/pool/shard006/C++/0079150_bloom.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6221c34676132f5b126657e33a0059165f9c5fa --- /dev/null +++ b/pool/shard006/C++/0079150_bloom.cpp @@ -0,0 +1,199 @@ +// Copyright (c) 2012-2014 The Octocoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "bloom.h" + +#include "primitives/transaction.h" +#include "hash.h" +#include "script/script.h" +#include "script/standard.h" +#include "streams.h" + +#include +#include + +#include + +#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455 +#define LN2 0.6931471805599453094172321214581765680755001343602552 + +using namespace std; + +CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) : +/** + * The ideal size for a bloom filter with a given number of elements and false positive rate is: + * - nElements * log(fp rate) / ln(2)^2 + * We ignore filter parameters which will create a bloom filter larger than the protocol limits + */ +vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8), +/** + * The ideal number of hash functions is filter size * ln(2) / number of elements + * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits + * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas + */ +isFull(false), +isEmpty(false), +nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)), +nTweak(nTweakIn), +nFlags(nFlagsIn) +{ +} + +inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector& vDataToHash) const +{ + // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values. + return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8); +} + +void CBloomFilter::insert(const vector& vKey) +{ + if (isFull) + return; + for (unsigned int i = 0; i < nHashFuncs; i++) + { + unsigned int nIndex = Hash(i, vKey); + // Sets bit nIndex of vData + vData[nIndex >> 3] |= (1 << (7 & nIndex)); + } + isEmpty = false; +} + +void CBloomFilter::insert(const COutPoint& outpoint) +{ + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << outpoint; + vector data(stream.begin(), stream.end()); + insert(data); +} + +void CBloomFilter::insert(const uint256& hash) +{ + vector data(hash.begin(), hash.end()); + insert(data); +} + +bool CBloomFilter::contains(const vector& vKey) const +{ + if (isFull) + return true; + if (isEmpty) + return false; + for (unsigned int i = 0; i < nHashFuncs; i++) + { + unsigned int nIndex = Hash(i, vKey); + // Checks bit nIndex of vData + if (!(vData[nIndex >> 3] & (1 << (7 & nIndex)))) + return false; + } + return true; +} + +bool CBloomFilter::contains(const COutPoint& outpoint) const +{ + CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); + stream << outpoint; + vector data(stream.begin(), stream.end()); + return contains(data); +} + +bool CBloomFilter::contains(const uint256& hash) const +{ + vector data(hash.begin(), hash.end()); + return contains(data); +} + +void CBloomFilter::clear() +{ + vData.assign(vData.size(),0); + isFull = false; + isEmpty = true; +} + +bool CBloomFilter::IsWithinSizeConstraints() const +{ + return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS; +} + +bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx) +{ + bool fFound = false; + // Match if the filter contains the hash of tx + // for finding tx when they appear in a block + if (isFull) + return true; + if (isEmpty) + return false; + const uint256& hash = tx.GetHash(); + if (contains(hash)) + fFound = true; + + for (unsigned int i = 0; i < tx.vout.size(); i++) + { + const CTxOut& txout = tx.vout[i]; + // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx + // If this matches, also add the specific output that was matched. + // This means clients don't have to update the filter themselves when a new relevant tx + // is discovered in order to find spending transactions, which avoids round-tripping and race conditions. + CScript::const_iterator pc = txout.scriptPubKey.begin(); + vector data; + while (pc < txout.scriptPubKey.end()) + { + opcodetype opcode; + if (!txout.scriptPubKey.GetOp(pc, opcode, data)) + break; + if (data.size() != 0 && contains(data)) + { + fFound = true; + if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL) + insert(COutPoint(hash, i)); + else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY) + { + txnouttype type; + vector > vSolutions; + if (Solver(txout.scriptPubKey, type, vSolutions) && + (type == TX_PUBKEY || type == TX_MULTISIG)) + insert(COutPoint(hash, i)); + } + break; + } + } + } + + if (fFound) + return true; + + BOOST_FOREACH(const CTxIn& txin, tx.vin) + { + // Match if the filter contains an outpoint tx spends + if (contains(txin.prevout)) + return true; + + // Match if the filter contains any arbitrary script data element in any scriptSig in tx + CScript::const_iterator pc = txin.scriptSig.begin(); + vector data; + while (pc < txin.scriptSig.end()) + { + opcodetype opcode; + if (!txin.scriptSig.GetOp(pc, opcode, data)) + break; + if (data.size() != 0 && contains(data)) + return true; + } + } + + return false; +} + +void CBloomFilter::UpdateEmptyFull() +{ + bool full = true; + bool empty = true; + for (unsigned int i = 0; i < vData.size(); i++) + { + full &= vData[i] == 0xff; + empty &= vData[i] == 0; + } + isFull = full; + isEmpty = empty; +} diff --git a/pool/shard006/C++/0079155_c30-A-vanya-and-books.cpp b/pool/shard006/C++/0079155_c30-A-vanya-and-books.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6524b763b68a60f6f8c9168b57b593e013230f2b --- /dev/null +++ b/pool/shard006/C++/0079155_c30-A-vanya-and-books.cpp @@ -0,0 +1,63 @@ +/*********************************************************************************/ +/** **/ +/** Leonardo Haddad nº 7295361 **/ +/** Desafios de Programação - Contest 30 Professor Marcel **/ +/** Problema A - Vanya and Books Curso: BCC **/ +/** https://www.codepit.io/#/problems/561dce7a921926e63b4daf8d/view?index=0 **/ +/** **/ +/*********************************************************************************/ + +// #include +#include +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include +#include +// #include +// #include +#define debug_off 1 + +using namespace std; + +long long n; +long long digits; + +#ifdef debug_on +/* print arguments */ +void printArgs () { + printf("Arguments:\n"); + printf(" n=%d;\n",n); +} +#endif + +int main () { + long long loop, aux; + + #ifdef debug_on + printf("\n| C28.A - Vanya and Books |\n"); + #endif + + /* read program arguments */ + scanf("%lld", &n); + + #ifdef debug_on + printArgs(); + printf("\nProblem Solution:\n"); + #endif + + /* solution */ + digits = 0; + for (loop=1, aux=1; loop<=10; loop++, aux *= 10) + digits += max(0ll, min(n, aux * 10 - 1) - aux + 1) * loop; + printf("%lld\n", digits); + + #ifdef debug_on + printf("\n--------------------\n"); + #endif + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0079157_MemoryMappedFileInputSource.cpp b/pool/shard006/C++/0079157_MemoryMappedFileInputSource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38664be15c08b64c42cfbe0d88edc45c003c0241 --- /dev/null +++ b/pool/shard006/C++/0079157_MemoryMappedFileInputSource.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015 Stephen F. Booth + * All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +#include "MemoryMappedFileInputSource.h" + +#pragma mark Creation and Destruction + +SFB::MemoryMappedFileInputSource::MemoryMappedFileInputSource(CFURLRef url) + : InputSource(url), mMemory(nullptr), mCurrentPosition(nullptr) +{ + memset(&mFilestats, 0, sizeof(mFilestats)); +} + +bool SFB::MemoryMappedFileInputSource::_Open(CFErrorRef *error) +{ + UInt8 buf [PATH_MAX]; + Boolean success = CFURLGetFileSystemRepresentation(GetURL(), FALSE, buf, PATH_MAX); + if(!success) { + if(error) + *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, EIO, nullptr); + return false; + } + + auto file = std::unique_ptr(std::fopen((const char *)buf, "r"), std::fclose); + if(!file) { + if(error) + *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, nullptr); + return false; + } + + if(-1 == fstat(::fileno(file.get()), &mFilestats)) { + if(error) + *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, nullptr); + return false; + } + + // Only regular files can be mapped + if(!S_ISREG(mFilestats.st_mode)) { + if(error) + *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, EBADF, nullptr); + return false; + } + + // Map the file to memory + size_t map_size = (size_t)mFilestats.st_size; + mMemory = unique_mappedmem_ptr((int8_t *)mmap(0, map_size, PROT_READ, MAP_FILE | MAP_SHARED, ::fileno(file.get()), 0), std::bind(munmap, std::placeholders::_1, map_size)); + + if(MAP_FAILED == mMemory.get()) { + if(error) + *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, nullptr); + return false; + } + + mCurrentPosition = mMemory.get(); + + return true; +} + +bool SFB::MemoryMappedFileInputSource::_Close(CFErrorRef *error) +{ + memset(&mFilestats, 0, sizeof(mFilestats)); + mMemory.reset(); + mCurrentPosition = nullptr; + + return true; +} + +SInt64 SFB::MemoryMappedFileInputSource::_Read(void *buffer, SInt64 byteCount) +{ + ptrdiff_t remaining = (mMemory.get() + mFilestats.st_size) - mCurrentPosition; + + if(byteCount > remaining) + byteCount = remaining; + + memcpy(buffer, mCurrentPosition, (size_t)byteCount); + mCurrentPosition += byteCount; + return byteCount; +} + +bool SFB::MemoryMappedFileInputSource::_SeekToOffset(SInt64 offset) +{ + if(offset > mFilestats.st_size) + return false; + + mCurrentPosition = mMemory.get() + offset; + return true; +} diff --git a/pool/shard006/C++/0079162_ring_hash_lb.cc b/pool/shard006/C++/0079162_ring_hash_lb.cc new file mode 100644 index 0000000000000000000000000000000000000000..28b64bdefd753054b3bfe6ded936cd5102b4bc68 --- /dev/null +++ b/pool/shard006/C++/0079162_ring_hash_lb.cc @@ -0,0 +1,202 @@ +#include "common/upstream/ring_hash_lb.h" + +#include +#include +#include +#include + +#include "envoy/config/cluster/v3/cluster.pb.h" + +#include "common/common/assert.h" +#include "common/upstream/load_balancer_impl.h" + +#include "absl/container/inlined_vector.h" +#include "absl/strings/string_view.h" + +namespace Envoy { +namespace Upstream { + +RingHashLoadBalancer::RingHashLoadBalancer( + const PrioritySet& priority_set, ClusterStats& stats, Stats::Scope& scope, + Runtime::Loader& runtime, Random::RandomGenerator& random, + const absl::optional& config, + const envoy::config::cluster::v3::Cluster::CommonLbConfig& common_config) + : ThreadAwareLoadBalancerBase(priority_set, stats, runtime, random, common_config), + scope_(scope.createScope("ring_hash_lb.")), stats_(generateStats(*scope_)), + min_ring_size_(config ? PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.value(), minimum_ring_size, + DefaultMinRingSize) + : DefaultMinRingSize), + max_ring_size_(config ? PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.value(), maximum_ring_size, + DefaultMaxRingSize) + : DefaultMaxRingSize), + hash_function_(config ? config.value().hash_function() + : HashFunction::Cluster_RingHashLbConfig_HashFunction_XX_HASH), + use_hostname_for_hashing_( + common_config.has_consistent_hashing_lb_config() + ? common_config.consistent_hashing_lb_config().use_hostname_for_hashing() + : false) { + // It's important to do any config validation here, rather than deferring to Ring's ctor, + // because any exceptions thrown here will be caught and handled properly. + if (min_ring_size_ > max_ring_size_) { + throw EnvoyException(fmt::format("ring hash: minimum_ring_size ({}) > maximum_ring_size ({})", + min_ring_size_, max_ring_size_)); + } +} + +RingHashLoadBalancerStats RingHashLoadBalancer::generateStats(Stats::Scope& scope) { + return {ALL_RING_HASH_LOAD_BALANCER_STATS(POOL_GAUGE(scope))}; +} + +HostConstSharedPtr RingHashLoadBalancer::Ring::chooseHost(uint64_t h, uint32_t attempt) const { + if (ring_.empty()) { + return nullptr; + } + + // Ported from https://github.com/RJ/ketama/blob/master/libketama/ketama.c (ketama_get_server) + // I've generally kept the variable names to make the code easier to compare. + // NOTE: The algorithm depends on using signed integers for lowp, midp, and highp. Do not + // change them! + int64_t lowp = 0; + int64_t highp = ring_.size(); + int64_t midp = 0; + while (true) { + midp = (lowp + highp) / 2; + + if (midp == static_cast(ring_.size())) { + midp = 0; + break; + } + + uint64_t midval = ring_[midp].hash_; + uint64_t midval1 = midp == 0 ? 0 : ring_[midp - 1].hash_; + + if (h <= midval && h > midval1) { + break; + } + + if (midval < h) { + lowp = midp + 1; + } else { + highp = midp - 1; + } + + if (lowp > highp) { + midp = 0; + break; + } + } + + // If a retry host predicate is being applied, behave as if this host was not in the ring. + // Note that this does not guarantee a different host: e.g., attempt == ring_.size() or + // when the offset causes us to select the same host at another location in the ring. + if (attempt > 0) { + midp = (midp + attempt) % ring_.size(); + } + + return ring_[midp].host_; +} + +using HashFunction = envoy::config::cluster::v3::Cluster::RingHashLbConfig::HashFunction; +RingHashLoadBalancer::Ring::Ring(const NormalizedHostWeightVector& normalized_host_weights, + double min_normalized_weight, uint64_t min_ring_size, + uint64_t max_ring_size, HashFunction hash_function, + bool use_hostname_for_hashing, RingHashLoadBalancerStats& stats) + : stats_(stats) { + ENVOY_LOG(trace, "ring hash: building ring"); + + // We can't do anything sensible with no hosts. + if (normalized_host_weights.empty()) { + return; + } + + // Scale up the number of hashes per host such that the least-weighted host gets a whole number + // of hashes on the ring. Other hosts might not end up with whole numbers, and that's fine (the + // ring-building algorithm below can handle this). This preserves the original implementation's + // behavior: when weights aren't provided, all hosts should get an equal number of hashes. In + // the case where this number exceeds the max_ring_size, it's scaled back down to fit. + const double scale = + std::min(std::ceil(min_normalized_weight * min_ring_size) / min_normalized_weight, + static_cast(max_ring_size)); + + // Reserve memory for the entire ring up front. + const uint64_t ring_size = std::ceil(scale); + ring_.reserve(ring_size); + + // Populate the hash ring by walking through the (host, weight) pairs in + // normalized_host_weights, and generating (scale * weight) hashes for each host. Since these + // aren't necessarily whole numbers, we maintain running sums -- current_hashes and + // target_hashes -- which allows us to populate the ring in a mostly stable way. + // + // For example, suppose we have 4 hosts, each with a normalized weight of 0.25, and a scale of + // 6.0 (because the max_ring_size is 6). That means we want to generate 1.5 hashes per host. + // We start the outer loop with current_hashes = 0 and target_hashes = 0. + // - For the first host, we set target_hashes = 1.5. After one run of the inner loop, + // current_hashes = 1. After another run, current_hashes = 2, so the inner loop ends. + // - For the second host, target_hashes becomes 3.0, and current_hashes is 2 from before. + // After only one run of the inner loop, current_hashes = 3, so the inner loop ends. + // - Likewise, the third host gets two hashes, and the fourth host gets one hash. + // + // For stats reporting, keep track of the minimum and maximum actual number of hashes per host. + // Users should hopefully pay attention to these numbers and alert if min_hashes_per_host is too + // low, since that implies an inaccurate request distribution. + + absl::InlinedVector hash_key_buffer; + double current_hashes = 0.0; + double target_hashes = 0.0; + uint64_t min_hashes_per_host = ring_size; + uint64_t max_hashes_per_host = 0; + for (const auto& entry : normalized_host_weights) { + const auto& host = entry.first; + const std::string& address_string = + use_hostname_for_hashing ? host->hostname() : host->address()->asString(); + ASSERT(!address_string.empty()); + + hash_key_buffer.assign(address_string.begin(), address_string.end()); + hash_key_buffer.emplace_back('_'); + auto offset_start = hash_key_buffer.end(); + + // As noted above: maintain current_hashes and target_hashes as running sums across the entire + // host set. `i` is needed only to construct the hash key, and tally min/max hashes per host. + target_hashes += scale * entry.second; + uint64_t i = 0; + while (current_hashes < target_hashes) { + const std::string i_str = absl::StrCat("", i); + hash_key_buffer.insert(offset_start, i_str.begin(), i_str.end()); + + absl::string_view hash_key(static_cast(hash_key_buffer.data()), + hash_key_buffer.size()); + + const uint64_t hash = + (hash_function == HashFunction::Cluster_RingHashLbConfig_HashFunction_MURMUR_HASH_2) + ? MurmurHash::murmurHash2(hash_key, MurmurHash::STD_HASH_SEED) + : HashUtil::xxHash64(hash_key); + + ENVOY_LOG(trace, "ring hash: hash_key={} hash={}", hash_key.data(), hash); + ring_.push_back({hash, host}); + ++i; + ++current_hashes; + hash_key_buffer.erase(offset_start, hash_key_buffer.end()); + } + min_hashes_per_host = std::min(i, min_hashes_per_host); + max_hashes_per_host = std::max(i, max_hashes_per_host); + } + + std::sort(ring_.begin(), ring_.end(), [](const RingEntry& lhs, const RingEntry& rhs) -> bool { + return lhs.hash_ < rhs.hash_; + }); + if (ENVOY_LOG_CHECK_LEVEL(trace)) { + for (const auto& entry : ring_) { + ENVOY_LOG(trace, "ring hash: host={} hash={}", + use_hostname_for_hashing ? entry.host_->hostname() + : entry.host_->address()->asString(), + entry.hash_); + } + } + + stats_.size_.set(ring_size); + stats_.min_hashes_per_host_.set(min_hashes_per_host); + stats_.max_hashes_per_host_.set(max_hashes_per_host); +} + +} // namespace Upstream +} // namespace Envoy diff --git a/pool/shard006/C++/0079167_va_android.cpp b/pool/shard006/C++/0079167_va_android.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f0324bd545289f062dafc2cfc7ae138564387c7 --- /dev/null +++ b/pool/shard006/C++/0079167_va_android.cpp @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2007 Intel Corporation. All Rights Reserved. + * + * 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, sub license, 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 NON-INFRINGEMENT. + * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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 _GNU_SOURCE 1 +#include "sysdeps.h" +#include "va.h" +#include "va_backend.h" +#include "va_trace.h" +#include "va_fool.h" +#include "va_android.h" +#include "va_drmcommon.h" +#include "va_drm_utils.h" +#include +#include +#include +#include +#include +#include +#include + + +#define CHECK_SYMBOL(func) { if (!func) printf("func %s not found\n", #func); return VA_STATUS_ERROR_UNKNOWN; } +#define DEVICE_NAME "/dev/dri/renderD128" + +static int open_device (char *dev_name) +{ + struct stat st; + int fd; + + if (-1 == stat (dev_name, &st)) + { + printf ("Cannot identify '%s': %d, %s\n", + dev_name, errno, strerror (errno)); + return -1; + } + + if (!S_ISCHR (st.st_mode)) + { + printf ("%s is no device\n", dev_name); + return -1; + } + + fd = open (dev_name, O_RDWR); + + if (-1 == fd) + { + fprintf (stderr, "Cannot open '%s': %d, %s\n", + dev_name, errno, strerror (errno)); + return -1; + } + + return fd; +} + +static int va_DisplayContextIsValid ( + VADisplayContextP pDisplayContext + ) +{ + return (pDisplayContext != NULL && + pDisplayContext->pDriverContext != NULL); +} + +static void va_DisplayContextDestroy ( + VADisplayContextP pDisplayContext +) +{ + struct drm_state *drm_state; + + if (pDisplayContext == NULL) + return; + + /* close the open-ed DRM fd */ + drm_state = (struct drm_state *)pDisplayContext->pDriverContext->drm_state; + close(drm_state->fd); + + free(pDisplayContext->pDriverContext->drm_state); + free(pDisplayContext->pDriverContext); + free(pDisplayContext); +} + +static VAStatus va_DisplayContextGetDriverName ( + VADisplayContextP pDisplayContext, + char **driver_name +) +{ + VADriverContextP const ctx = pDisplayContext->pDriverContext; + struct drm_state * drm_state = (struct drm_state *)ctx->drm_state; + + memset(drm_state, 0, sizeof(*drm_state)); + drm_state->fd = open_device((char *)DEVICE_NAME); + + if (drm_state->fd < 0) { + fprintf(stderr,"can't open DRM devices\n"); + return VA_STATUS_ERROR_UNKNOWN; + } + drm_state->auth_type = VA_DRM_AUTH_CUSTOM; + + return VA_DRM_GetDriverName(ctx, driver_name); +} + + +VADisplay vaGetDisplay ( + void *native_dpy /* implementation specific */ +) +{ + VADisplay dpy = NULL; + VADisplayContextP pDisplayContext; + + if (!native_dpy) + return NULL; + + if (!dpy) + { + /* create new entry */ + VADriverContextP pDriverContext = 0; + struct drm_state *drm_state = 0; + pDisplayContext = (VADisplayContextP)calloc(1, sizeof(*pDisplayContext)); + pDriverContext = (VADriverContextP)calloc(1, sizeof(*pDriverContext)); + drm_state = (struct drm_state*)calloc(1, sizeof(*drm_state)); + if (pDisplayContext && pDriverContext && drm_state) + { + pDisplayContext->vadpy_magic = VA_DISPLAY_MAGIC; + + pDriverContext->native_dpy = (void *)native_dpy; + pDriverContext->display_type = VA_DISPLAY_ANDROID; + pDisplayContext->pDriverContext = pDriverContext; + pDisplayContext->vaIsValid = va_DisplayContextIsValid; + pDisplayContext->vaDestroy = va_DisplayContextDestroy; + pDisplayContext->vaGetDriverName = va_DisplayContextGetDriverName; + pDriverContext->drm_state = drm_state; + dpy = (VADisplay)pDisplayContext; + } + else + { + if (pDisplayContext) + free(pDisplayContext); + if (pDriverContext) + free(pDriverContext); + if (drm_state) + free(drm_state); + } + } + + return dpy; +} + +#define CTX(dpy) (((VADisplayContextP)dpy)->pDriverContext) +#define CHECK_DISPLAY(dpy) if( !vaDisplayIsValid(dpy) ) { return VA_STATUS_ERROR_INVALID_DISPLAY; } + + +extern "C" { + extern int fool_postp; /* do nothing for vaPutSurface if set */ + extern int trace_flag; /* trace vaPutSurface parameters */ + + void va_TracePutSurface ( + VADisplay dpy, + VASurfaceID surface, + void *draw, /* the target Drawable */ + short srcx, + short srcy, + unsigned short srcw, + unsigned short srch, + short destx, + short desty, + unsigned short destw, + unsigned short desth, + VARectangle *cliprects, /* client supplied clip list */ + unsigned int number_cliprects, /* number of clip rects in the clip list */ + unsigned int flags /* de-interlacing flags */ + ); +} + +VAStatus vaPutSurface ( + VADisplay dpy, + VASurfaceID surface, + sp draw, /* Android Native Window */ + short srcx, + short srcy, + unsigned short srcw, + unsigned short srch, + short destx, + short desty, + unsigned short destw, + unsigned short desth, + VARectangle *cliprects, /* client supplied clip list */ + unsigned int number_cliprects, /* number of clip rects in the clip list */ + unsigned int flags /* de-interlacing flags */ +) +{ + VADriverContextP ctx; + + if (fool_postp) + return VA_STATUS_SUCCESS; + + if (draw == NULL) + return VA_STATUS_ERROR_UNKNOWN; + + CHECK_DISPLAY(dpy); + ctx = CTX(dpy); + + VA_TRACE_LOG(va_TracePutSurface, dpy, surface, static_cast(&draw), srcx, srcy, srcw, srch, + destx, desty, destw, desth, + cliprects, number_cliprects, flags ); + + return ctx->vtable->vaPutSurface( ctx, surface, static_cast(&draw), srcx, srcy, srcw, srch, + destx, desty, destw, desth, + cliprects, number_cliprects, flags ); +} diff --git a/pool/shard006/C++/0079172_b2CircleContact.cpp b/pool/shard006/C++/0079172_b2CircleContact.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd9184347a832324db12438b067bf8278f1661b0 --- /dev/null +++ b/pool/shard006/C++/0079172_b2CircleContact.cpp @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "b2CircleContact.h" +#include "../b2Body.h" +#include "../b2Fixture.h" +#include "../b2WorldCallbacks.h" +#include "../../Common/b2BlockAllocator.h" +#include "../../Collision/b2TimeOfImpact.h" + +#include +using namespace std; + +b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) +{ + void* mem = allocator->Allocate(sizeof(b2CircleContact)); + return new (mem) b2CircleContact(fixtureA, fixtureB); +} + +void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) +{ + ((b2CircleContact*)contact)->~b2CircleContact(); + allocator->Free(contact, sizeof(b2CircleContact)); +} + +b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) + : b2Contact(fixtureA, 0, fixtureB, 0) +{ + b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); +} + +void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) +{ + b2CollideCircles(manifold, + (b2CircleShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); +} diff --git a/pool/shard006/C++/0079176_reverse_string.cpp b/pool/shard006/C++/0079176_reverse_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a0431467f8bffdb4ba5fc7f8b32a648c2bd37ed --- /dev/null +++ b/pool/shard006/C++/0079176_reverse_string.cpp @@ -0,0 +1,36 @@ +#include + +void Reverse(char* str) { + if (str) { + char* i = str; // first letter + char* j = str; // last letter + + // find the end of the string + while (*j) { + j++; + } + + // don't point to the null terminator + j--; + + char tmp; + + // swap chars to reverse the string + while (i < j) { + tmp = *i; + *i++ = *j; + *j-- = tmp; + } + } +} + +int main() { + char test0[] = ""; + char test1[] = "foo"; + Reverse(NULL); + Reverse(test0); + Reverse(test1); + printf("%s \n", test0); + printf("%s \n", test1); + return 0; +} diff --git a/pool/shard006/C++/0079178_Shader.cpp b/pool/shard006/C++/0079178_Shader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa77e52619a5d989dacdbc457361196b061191d1 --- /dev/null +++ b/pool/shard006/C++/0079178_Shader.cpp @@ -0,0 +1,142 @@ +#include "src\Engine\Shader\Shader.h" +#include +#include +#include "glm\glm.hpp" + +using glm::mat4; + +void Shader::installShader(){ + +} + +void Shader::startProgram(){ + + glUseProgram(programID); +} + +void Shader::stopProgram(){ + + glUseProgram(0); +} + +void Shader::initialize(Scene &scene){ + + this->scene = &scene; +} + +void Shader::render(Entity &entity){ + +} + +void Shader::cleanUp(){ + + glDetachShader(programID, vertexShaderID); + glDetachShader(programID, fragmentShaderID); + + glDeleteShader(vertexShaderID); + glDeleteShader(fragmentShaderID); + + glDeleteProgram(programID); +} + + +std::string Shader::readShaderCode(const GLchar* fileName){ + + std::ifstream input(fileName); + if (!input.good()){ + std::cout << "File failed to load"<(input), std::istreambuf_iterator()); +} + + +GLint Shader::getUniformLocation(std::string &uniformName){ + + const GLchar* adapter[1]; + std::string temp = uniformName.c_str(); + adapter[0] = temp.c_str(); + return glGetUniformLocation(programID, adapter[0]); +} + +void Shader::getAllUniformLocations(){ + +} + + +void Shader::loadToUniform(GLuint &location, bool &data){ + + if (data == true){ + glUniform1f(location, data); + } + else { + glUniform1f(location, data); + } + +} +void Shader::loadToUniform(GLuint &location, GLfloat &data){ + + glUniform1f(location, data); +} + +void Shader::loadToUniform(GLuint &location, glm::vec3 &data){ + + glUniform3fv(location, 1, &data[0]); +} + +void Shader::loadToUniform(GLuint &location, glm::mat4 &data){ + + glUniformMatrix4fv(location, 1, GL_FALSE, &data[0][0]); +} + + +bool Shader::checkStatus(GLuint objectID, PFNGLGETSHADERIVPROC objectPropertyGetter, + PFNGLGETSHADERINFOLOGPROC getInfoLogFun, GLenum statusType){ + + GLint status; + objectPropertyGetter(objectID, statusType, &status); + if (status != GL_TRUE){ + GLint infoLogLength; + objectPropertyGetter(objectID, GL_INFO_LOG_LENGTH, &infoLogLength); + GLchar* buffer = new GLchar[infoLogLength]; + GLsizei bufferSize; + getInfoLogFun(objectID, infoLogLength, &bufferSize, buffer); + + std::cout << buffer << std::endl; + + delete[] buffer; + return false; + } + return true; +} + +bool Shader::checkShaderStatus(GLuint ShaderID){ + + return checkStatus(ShaderID, glGetShaderiv, glGetShaderInfoLog, GL_COMPILE_STATUS); +} + +bool Shader::checkProgramStatus(GLuint programID){ + + return checkStatus(programID, glGetProgramiv, glGetProgramInfoLog, GL_LINK_STATUS); + +} + +void Shader::loadTransformationMatrix(glm::mat4 &matrix){ + + loadToUniform(location_transformationMatrix, matrix); + +} +void Shader::loadProjectionMatrix(){ + + loadToUniform(location_projectionMatrix, scene->getProjectionMatrix()); +} +void Shader::loadViewMatrix(){ + + loadToUniform(location_viewMatrix, scene->getViewMatrix()); +} +void Shader::loadShineDamper(GLfloat){ + +} +void Shader::loadCameraPosition(glm::vec3 position){ + +} \ No newline at end of file diff --git a/pool/shard006/C++/0079179_NPC_misc.cpp b/pool/shard006/C++/0079179_NPC_misc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28a24cb69e85b3a9b43e91a4d3f3fae6c2c20bd4 --- /dev/null +++ b/pool/shard006/C++/0079179_NPC_misc.cpp @@ -0,0 +1,97 @@ +/* +This file is part of Jedi Academy. + + Jedi Academy 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. + + Jedi Academy 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 Jedi Academy. If not, see . +*/ +// Copyright 2001-2013 Raven Software + +// +// NPC_misc.cpp +// + +// leave this line at the top for all NPC_xxxx.cpp files... +#include "g_headers.h" + + + + +#include "b_local.h" +#include "../qcommon/q_shared.h" +/* +Debug_Printf +*/ +void Debug_Printf (cvar_t *cv, int debugLevel, char *fmt, ...) +{ + char *color; + va_list argptr; + char msg[1024]; + + if (cv->value < debugLevel) + return; + + if (debugLevel == DEBUG_LEVEL_DETAIL) + color = S_COLOR_WHITE; + else if (debugLevel == DEBUG_LEVEL_INFO) + color = S_COLOR_GREEN; + else if (debugLevel == DEBUG_LEVEL_WARNING) + color = S_COLOR_YELLOW; + else if (debugLevel == DEBUG_LEVEL_ERROR) + color = S_COLOR_RED; + else + color = S_COLOR_RED; + + va_start (argptr,fmt); + Q_vsnprintf (msg, sizeof(msg), fmt, argptr); + va_end (argptr); + + gi.Printf("%s%5i:%s", color, level.time, msg); +} + + +/* +Debug_NPCPrintf +*/ +void Debug_NPCPrintf (gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt, ...) +{ + int color; + va_list argptr; + char msg[1024]; + + if (cv->value < debugLevel) + { + return; + } + + if ( debugNPCName->string[0] && Q_stricmp( debugNPCName->string, printNPC->targetname) != 0 ) + { + return; + } + + if (debugLevel == DEBUG_LEVEL_DETAIL) + color = COLOR_WHITE; + else if (debugLevel == DEBUG_LEVEL_INFO) + color = COLOR_GREEN; + else if (debugLevel == DEBUG_LEVEL_WARNING) + color = COLOR_YELLOW; + else if (debugLevel == DEBUG_LEVEL_ERROR) + color = COLOR_RED; + else + color = COLOR_RED; + + va_start (argptr,fmt); + Q_vsnprintf (msg, sizeof(msg), fmt, argptr); + va_end (argptr); + + gi.Printf ("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); +} diff --git a/pool/shard006/C++/0079181_about.cpp b/pool/shard006/C++/0079181_about.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8e78c0349771be93e80ffa0102facc0e472997b --- /dev/null +++ b/pool/shard006/C++/0079181_about.cpp @@ -0,0 +1,42 @@ +/* MultiTerminal (TCP or Serial terminal emulator with filtering capabilites) + * Copyright (C) 2014 Jeroen Lodder + * + * 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. + * + * http://www.gnu.org/licenses/gpl-2.0.txt + */ +#include "about.h" +#include "ui_about.h" + +About::About(QWidget *parent) : + QDialog(parent), + ui(new Ui::About) +{ + ui->setupUi(this); + // Insert poor mans version number + QString content = ui->textBrowser->toHtml(); + content.replace("__DATE__",__DATE__); + content.replace("__TIME__",__TIME__); + ui->textBrowser->clear(); + ui->textBrowser->insertHtml(content); + // Hide this window + this->hide(); +} + +About::~About() +{ + delete ui; +} + +void About::on_pushButton_clicked() +{ + this->hide(); +} diff --git a/pool/shard006/C++/0079182_quic_url.cc b/pool/shard006/C++/0079182_quic_url.cc new file mode 100644 index 0000000000000000000000000000000000000000..f7f6b2a56a7d5813c0d860665e2d65f88f8d80ab --- /dev/null +++ b/pool/shard006/C++/0079182_quic_url.cc @@ -0,0 +1,101 @@ +// 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 "net/third_party/quic/tools/quic_url.h" + +#include "net/third_party/quic/platform/api/quic_str_cat.h" +#include "net/third_party/quic/platform/api/quic_text_utils.h" + +namespace quic { + +static constexpr size_t kMaxHostNameLength = 256; + +QuicUrl::QuicUrl(QuicStringPiece url) : url_(static_cast(url)) {} + +QuicUrl::QuicUrl(QuicStringPiece url, QuicStringPiece default_scheme) + : QuicUrl(url) { + if (url_.has_scheme()) { + return; + } + + url_ = GURL(QuicStrCat(default_scheme, "://", url)); +} + +QuicString QuicUrl::ToString() const { + if (IsValid()) { + return url_.spec(); + } + return ""; +} + +bool QuicUrl::IsValid() const { + if (!url_.is_valid() || !url_.has_scheme()) { + return false; + } + + if (url_.has_host() && url_.host().length() > kMaxHostNameLength) { + return false; + } + + return true; +} + +QuicString QuicUrl::HostPort() const { + if (!IsValid() || !url_.has_host()) { + return ""; + } + + QuicString host = url_.host(); + int port = url_.IntPort(); + if (port == url::PORT_UNSPECIFIED) { + return host; + } + return QuicStrCat(host, ":", port); +} + +QuicString QuicUrl::PathParamsQuery() const { + if (!IsValid() || !url_.has_path()) { + return "/"; + } + + return url_.PathForRequest(); +} + +QuicString QuicUrl::scheme() const { + if (!IsValid()) { + return ""; + } + + return url_.scheme(); +} + +QuicString QuicUrl::host() const { + if (!IsValid()) { + return ""; + } + + return url_.HostNoBrackets(); +} + +QuicString QuicUrl::path() const { + if (!IsValid()) { + return ""; + } + + return url_.path(); +} + +uint16_t QuicUrl::port() const { + if (!IsValid()) { + return 0; + } + + int port = url_.EffectiveIntPort(); + if (port == url::PORT_UNSPECIFIED) { + return 0; + } + return port; +} + +} // namespace quic diff --git a/pool/shard006/C++/0079186_tabbed_pane_unittest.cc b/pool/shard006/C++/0079186_tabbed_pane_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..7152f7eb4f081205e4716b629db38ed46ec291e1 --- /dev/null +++ b/pool/shard006/C++/0079186_tabbed_pane_unittest.cc @@ -0,0 +1,96 @@ +// 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/tabbed_pane/tabbed_pane.h" + +#include + +#include "base/macros.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/utf_string_conversions.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/test/views_test_base.h" + +using base::ASCIIToUTF16; + +namespace views { + +namespace { + +// A view for testing that takes a fixed preferred size upon construction. +class FixedSizeView : public View { + public: + explicit FixedSizeView(const gfx::Size& size) + : size_(size) {} + + // Overridden from View: + gfx::Size GetPreferredSize() const override { return size_; } + + private: + const gfx::Size size_; + + DISALLOW_COPY_AND_ASSIGN(FixedSizeView); +}; + +typedef ViewsTestBase TabbedPaneTest; + +// Tests TabbedPane::GetPreferredSize() and TabbedPane::Layout(). +TEST_F(TabbedPaneTest, SizeAndLayout) { + std::unique_ptr tabbed_pane(new TabbedPane()); + View* child1 = new FixedSizeView(gfx::Size(20, 10)); + tabbed_pane->AddTab(ASCIIToUTF16("tab1"), child1); + View* child2 = new FixedSizeView(gfx::Size(5, 5)); + tabbed_pane->AddTab(ASCIIToUTF16("tab2"), child2); + tabbed_pane->SelectTabAt(0); + + // The |tabbed_pane| implementation of Views has no border by default. + // Therefore it should be as wide as the widest tab. The native Windows + // tabbed pane has a border that used up extra space. Therefore the preferred + // width is larger than the largest child. + gfx::Size pref(tabbed_pane->GetPreferredSize()); + EXPECT_GE(pref.width(), 20); + EXPECT_GT(pref.height(), 10); + + // The bounds of our children should be smaller than the tabbed pane's bounds. + tabbed_pane->SetBounds(0, 0, 100, 200); + RunPendingMessages(); + gfx::Rect bounds(child1->bounds()); + EXPECT_GT(bounds.width(), 0); + // The |tabbed_pane| has no border. Therefore the children should be as wide + // as the |tabbed_pane|. + EXPECT_LE(bounds.width(), 100); + EXPECT_GT(bounds.height(), 0); + EXPECT_LT(bounds.height(), 200); + + // If we switch to the other tab, it should get assigned the same bounds. + tabbed_pane->SelectTabAt(1); + EXPECT_EQ(bounds, child2->bounds()); +} + +TEST_F(TabbedPaneTest, AddAndSelect) { + std::unique_ptr tabbed_pane(new TabbedPane()); + // Add several tabs; only the first should be a selected automatically. + for (int i = 0; i < 3; ++i) { + View* tab = new View(); + tabbed_pane->AddTab(ASCIIToUTF16("tab"), tab); + EXPECT_EQ(i + 1, tabbed_pane->GetTabCount()); + EXPECT_EQ(0, tabbed_pane->selected_tab_index()); + } + + // Select each tab. + for (int i = 0; i < tabbed_pane->GetTabCount(); ++i) { + tabbed_pane->SelectTabAt(i); + EXPECT_EQ(i, tabbed_pane->selected_tab_index()); + } + + // Add a tab at index 0, it should not be selected automatically. + View* tab0 = new View(); + tabbed_pane->AddTabAtIndex(0, ASCIIToUTF16("tab0"), tab0); + EXPECT_NE(tab0, tabbed_pane->GetSelectedTab()); + EXPECT_NE(0, tabbed_pane->selected_tab_index()); +} + +} // namespace + +} // namespace views diff --git a/pool/shard006/C++/0079190_AlgorithmFactory.cpp b/pool/shard006/C++/0079190_AlgorithmFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cbaa125ff966feadc206b9130ac22d6654b87010 --- /dev/null +++ b/pool/shard006/C++/0079190_AlgorithmFactory.cpp @@ -0,0 +1,151 @@ +#include "MantidAPI/AlgorithmFactory.h" +#include "MantidAPI/Algorithm.h" +#include "MantidAPI/FileLoaderRegistry.h" +#include "MantidKernel/WarningSuppressions.h" +#include "MantidPythonInterface/kernel/GetPointer.h" +#include "MantidPythonInterface/kernel/PythonObjectInstantiator.h" + +#include +#include +#include +#include +#include +#include + +// Python frameobject. This is under the boost includes so that boost will have +// done the +// include of Python.h which it ensures is done correctly +#include + +using namespace Mantid::API; +using namespace boost::python; +using Mantid::Kernel::AbstractInstantiator; +using Mantid::PythonInterface::PythonObjectInstantiator; + +GET_POINTER_SPECIALIZATION(AlgorithmFactoryImpl) + +namespace { +///@cond + +//------------------------------------------------------------------------------------------------------ +/** + * A Python friendly version of get_keys that returns the registered algorithms + * as + * a dictionary where the key is the algorithm name and the value is a list + * of version numbers + * @param self :: Enables it to be called as a member function on the + * AlgorithmFactory class + * @param includeHidden :: If true hidden algorithms are included + */ +dict getRegisteredAlgorithms(AlgorithmFactoryImpl &self, bool includeHidden) { + std::vector keys = self.getKeys(includeHidden); + const size_t nkeys = keys.size(); + dict inventory; + for (size_t i = 0; i < nkeys; ++i) { + auto algInfo = self.decodeName(keys[i]); + object name( + handle<>(to_python_value()(algInfo.first))); + object ver(handle<>(to_python_value()(algInfo.second))); + // There seems to be no way to "promote" the return of .get to a list + // without copying it + object versions; + if (inventory.has_key(name)) { + versions = inventory.get(name); + } else { + versions = list(); + inventory[name] = versions; + } + versions.attr("append")(ver); + } + return inventory; +} + +//------------------------------------------------------------------------------ +// Python algorithm subscription +//------------------------------------------------------------------------------ + +// Python algorithm registration mutex in anonymous namespace (aka static) +std::recursive_mutex PYALG_REGISTER_MUTEX; + +// clang-format off +GCC_DIAG_OFF(cast-qual) +// clang-format on + +/** + * A free function to subscribe a Python algorithm into the factory + * @param obj :: A Python object that should either be a class type derived from + * PythonAlgorithm + * or an instance of a class type derived from PythonAlgorithm + */ +void subscribe(AlgorithmFactoryImpl &self, const boost::python::object &obj) { + std::lock_guard lock(PYALG_REGISTER_MUTEX); + + static PyObject *const pyAlgClass = + (PyObject *) + converter::registered::converters.to_python_target_type(); + // obj could be or instance/class, check instance first + PyObject *classObject(nullptr); + if (PyObject_IsInstance(obj.ptr(), pyAlgClass)) { + classObject = PyObject_GetAttrString(obj.ptr(), "__class__"); + } else if (PyObject_IsSubclass(obj.ptr(), pyAlgClass)) { + classObject = obj.ptr(); // We need to ensure the type of lifetime + // management so grab the raw pointer + } else { + throw std::invalid_argument( + "Cannot register an algorithm that does not derive from Algorithm."); + } + boost::python::object classType(handle<>(borrowed(classObject))); + // Takes ownership of instantiator and replaces any existing algorithm + auto descr = + self.subscribe(new PythonObjectInstantiator(classType), + AlgorithmFactoryImpl::OverwriteCurrent); + + // Python algorithms cannot yet act as loaders so remove any registered ones + // from the FileLoaderRegistry + FileLoaderRegistry::Instance().unsubscribe(descr.first, descr.second); +} +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-pragmas" +#pragma clang diagnostic ignored "-Wunused-local-typedef" +#endif +// Ignore -Wconversion warnings coming from boost::python +// Seen with GCC 7.1.1 and Boost 1.63.0 +GCC_DIAG_OFF(conversion) +BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(existsOverloader, exists, 1, 2) +GCC_DIAG_ON(conversion) +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +///@endcond +} +// clang-format off +GCC_DIAG_ON(cast-qual) +// clang-format on + +void export_AlgorithmFactory() { + + class_("AlgorithmFactoryImpl", + no_init) + .def("exists", &AlgorithmFactoryImpl::exists, + existsOverloader((arg("name"), arg("version") = -1), + "Returns true if the given algorithm exists with " + "an option to specify the version")) + + .def("getRegisteredAlgorithms", &getRegisteredAlgorithms, + (arg("self"), arg("include_hidden")), + "Returns a Python dictionary of currently registered algorithms") + .def("highestVersion", &AlgorithmFactoryImpl::highestVersion, + (arg("self"), arg("algorithm_name")), + "Returns the highest version of the named algorithm. Throws " + "ValueError if no algorithm can be found") + .def("subscribe", &subscribe, (arg("self"), arg("object")), + "Register a Python class derived from " + "PythonAlgorithm into the factory") + + .def("Instance", &AlgorithmFactory::Instance, + return_value_policy(), + "Returns a reference to the AlgorithmFactory singleton") + .staticmethod("Instance"); +} diff --git a/pool/shard006/C++/0079214_resource_bundle_linux.cc b/pool/shard006/C++/0079214_resource_bundle_linux.cc new file mode 100644 index 0000000000000000000000000000000000000000..5806fb0501e6af5b6521cd5a6bedfdc77c2afaff --- /dev/null +++ b/pool/shard006/C++/0079214_resource_bundle_linux.cc @@ -0,0 +1,136 @@ +// 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 "ui/base/resource/resource_bundle.h" + +#include + +#include "base/base_paths.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/i18n/rtl.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/string_piece.h" +#include "base/string_util.h" +#include "base/synchronization/lock.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/base/ui_base_paths.h" +#include "ui/gfx/font.h" +#include "ui/gfx/gtk_util.h" +#include "ui/gfx/image.h" + +namespace ui { + +namespace { + +// Convert the raw image data into a GdkPixbuf. The GdkPixbuf that is returned +// has a ref count of 1 so the caller must call g_object_unref to free the +// memory. +GdkPixbuf* LoadPixbuf(RefCountedStaticMemory* data, bool rtl_enabled) { + ScopedGObject::Type loader(gdk_pixbuf_loader_new()); + bool ok = data && gdk_pixbuf_loader_write(loader.get(), + reinterpret_cast(data->front()), data->size(), NULL); + if (!ok) + return NULL; + // Calling gdk_pixbuf_loader_close forces the data to be parsed by the + // loader. We must do this before calling gdk_pixbuf_loader_get_pixbuf. + ok = gdk_pixbuf_loader_close(loader.get(), NULL); + if (!ok) + return NULL; + GdkPixbuf* pixbuf = gdk_pixbuf_loader_get_pixbuf(loader.get()); + if (!pixbuf) + return NULL; + + if (base::i18n::IsRTL() && rtl_enabled) { + // |pixbuf| will get unreffed and destroyed (see below). The returned value + // has ref count 1. + return gdk_pixbuf_flip(pixbuf, TRUE); + } else { + // The pixbuf is owned by the loader, so add a ref so when we delete the + // loader (when the ScopedGObject goes out of scope), the pixbuf still + // exists. + g_object_ref(pixbuf); + return pixbuf; + } +} + +} // namespace + +// static +FilePath ResourceBundle::GetResourcesFilePath() { + FilePath resources_file_path; + PathService::Get(ui::FILE_RESOURCES_PAK, &resources_file_path); + return resources_file_path; +} + +// static +FilePath ResourceBundle::GetLargeIconResourcesFilePath() { + // Not supported. + return FilePath(); +} + +// static +FilePath ResourceBundle::GetLocaleFilePath(const std::string& app_locale) { + FilePath locale_file_path; + PathService::Get(ui::DIR_LOCALES, &locale_file_path); + if (locale_file_path.empty()) + return locale_file_path; + if (app_locale.empty()) + return FilePath(); + locale_file_path = locale_file_path.AppendASCII(app_locale + ".pak"); + if (!file_util::PathExists(locale_file_path)) + return FilePath(); + return locale_file_path; +} + +gfx::Image& ResourceBundle::GetNativeImageNamed(int resource_id) { + return *GetPixbufImpl(resource_id, false); +} + +gfx::Image* ResourceBundle::GetPixbufImpl(int resource_id, bool rtl_enabled) { + // Use the negative |resource_id| for the key for BIDI-aware images. + int key = rtl_enabled ? -resource_id : resource_id; + + // Check to see if the image is already in the cache. + { + base::AutoLock lock_scope(*lock_); + ImageMap::const_iterator found = images_.find(key); + if (found != images_.end()) + return found->second; + } + + scoped_refptr data( + LoadDataResourceBytes(resource_id)); + GdkPixbuf* pixbuf = LoadPixbuf(data.get(), rtl_enabled); + + // The load was successful, so cache the image. + if (pixbuf) { + base::AutoLock lock_scope(*lock_); + + // Another thread raced the load and has already cached the image. + if (images_.count(key)) { + g_object_unref(pixbuf); + return images_[key]; + } + + gfx::Image* image = new gfx::Image(pixbuf); // Takes ownership. + images_[key] = image; + return image; + } + + LOG(WARNING) << "Unable to pixbuf with id " << resource_id; + NOTREACHED(); // Want to assert in debug mode. + return GetEmptyImage(); +} + +GdkPixbuf* ResourceBundle::GetPixbufNamed(int resource_id) { + return *GetPixbufImpl(resource_id, false); +} + +GdkPixbuf* ResourceBundle::GetRTLEnabledPixbufNamed(int resource_id) { + return *GetPixbufImpl(resource_id, true); +} + +} // namespace ui diff --git a/pool/shard006/C++/0079216_test_time_service_impl.cc b/pool/shard006/C++/0079216_test_time_service_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..5dc90f79aa5c393573b548fc5feb01a009f90998 --- /dev/null +++ b/pool/shard006/C++/0079216_test_time_service_impl.cc @@ -0,0 +1,45 @@ +// 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 "base/time/time.h" +#include "mojo/application/public/cpp/application_impl.h" +#include "mojo/services/test_service/test_request_tracker.mojom.h" +#include "mojo/services/test_service/test_time_service_impl.h" +#include "mojo/services/test_service/tracked_service.h" + +namespace mojo { +namespace test { + +TestTimeServiceImpl::TestTimeServiceImpl( + ApplicationImpl* app_impl, + InterfaceRequest request) + : app_impl_(app_impl), binding_(this, request.Pass()) { +} + +TestTimeServiceImpl::~TestTimeServiceImpl() { +} + +void TestTimeServiceImpl::StartTrackingRequests( + const mojo::Callback& callback) { + TestRequestTrackerPtr tracker; + mojo::URLRequestPtr request(mojo::URLRequest::New()); + request->url = mojo::String::From("mojo:test_request_tracker_app"); + app_impl_->ConnectToService(request.Pass(), &tracker); + tracking_.reset(new TrackedService(tracker.Pass(), Name_, callback)); +} + +void TestTimeServiceImpl::GetPartyTime( + const mojo::Callback& callback) { + if (tracking_) + tracking_->RecordNewRequest(); + base::Time frozen_time(base::Time::UnixEpoch() + + base::TimeDelta::FromDays(10957) + + base::TimeDelta::FromHours(7) + + base::TimeDelta::FromMinutes(59)); + int64 time(frozen_time.ToInternalValue()); + callback.Run(time); +} + +} // namespace test +} // namespace mojo diff --git a/pool/shard006/C++/0079235_MCP3008.cpp b/pool/shard006/C++/0079235_MCP3008.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e34b7f1c2abeee83a5a3c2d6216f2c5ba21f037 --- /dev/null +++ b/pool/shard006/C++/0079235_MCP3008.cpp @@ -0,0 +1,104 @@ + + +#include "hw_interface/MCP3008.h" +#include "util.h" +#include +#include + +#include + +using namespace std; + +#define MCP3008_SPI_CPOL_CPHA 0b00 +//datasheet p14, Figure 4.2, Max clock freq to maintain less than 0.1 LS deviation +#define MCP3008_SPI_SPEED 500000 +#define MCP3008_SPI_DELAY 0 +#define MCP3008_SPI_WL 0 + +#define ADC_DELAY_BETWEEN_READ 50 + +MCP3008::MCP3008(int channel) + : SPI_Device(channel, + MCP3008_SPI_CPOL_CPHA, + MCP3008_SPI_SPEED, + MCP3008_SPI_DELAY, + MCP3008_SPI_WL) +{ + LOG << "init MCP 3008..." << std::endl; + + shouldRun_ = false; + for (int i=0; i= 0 && channel < NUM_OF_CHANNELS){ + enabled_[channel] = true; + LOG "enable ADC chan : " << channel << std::endl; + } +} + +void MCP3008::disable_channel(unsigned int channel){ + if (channel >= 0 && channel < NUM_OF_CHANNELS){ + enabled_[channel] = false; + values_[channel] = -1; + } +} + +int MCP3008::get_value(unsigned int channel){ + if (channel >= 0 && channel < NUM_OF_CHANNELS){ + return values_[channel]; + } + return -1; +} + +int MCP3008::threadHandler(){ + while (shouldRun_){ + for (int i=0; i x(cmd[i]); + std::cout << "cmd[" << i << "] : " << x << std::endl; + } +#endif + char rx_buff[3]; + send_buff(cmd, rx_buff, 3); +#if 0 + for (int i=0; i<3; i++){ + std::bitset<8> x(rx_buff[i]); + std::cout << "rx[" << i << "] : " << x << std::endl; + } +#endif + uint16_t v = 0; + memcpy(&v, rx_buff + 1, 2); + v = ntohs(v); + v = v & 0b1111111111; + values_[i] = v; + + //LOG << "adc read : " << v << " / values_[i] : " << values_[i] << std::endl; + + std::this_thread::sleep_for(std::chrono::milliseconds(ADC_DELAY_BETWEEN_READ)); + } + } + return 0; +}; diff --git a/pool/shard006/C++/0079243_common.cpp b/pool/shard006/C++/0079243_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cedda6c9ba5fc5ca215bdebe915267985ebe2609 --- /dev/null +++ b/pool/shard006/C++/0079243_common.cpp @@ -0,0 +1,222 @@ +/* +Copyright (c) 2013, Illumina 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 Illumina, 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 +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "common.h" +#include +#include "errors.h" +#include + +#ifndef __MACH__ +#define BOOST_KARMA_NUMERICS_LOOP_UNROLL 6 +#include +using namespace boost::spirit; +using boost::spirit::karma::int_; +using boost::spirit::karma::lit; +#endif + +using namespace es3; + +static int global_verbosity_level = 0; +mutex_t logger_lock_; + +mutex_t& es3::get_logger_lock() +{ + return logger_lock_; +} + +es3::logger::logger(int lvl) + : verbosity_(lvl), stream_(new std::ostringstream()) +{ +} + +es3::logger::~logger() +{ + guard_t g(logger_lock_); + std::cerr + << static_cast(stream_.get())->str() + << std::endl; +} + +void es3::logger::set_verbosity(int lvl) +{ + global_verbosity_level = lvl; +} + +bool es3::logger::is_log_on(int lvl) +{ + return lvl<=global_verbosity_level; +} + +std::string es3::int_to_string(int64_t in) +{ + char buffer[64]; +#ifdef __MACH__ + sprintf(buffer, "%lld", in); + return buffer; +#else + char *ptr = buffer; + karma::generate(ptr, int_, in); + *ptr = '\0'; + return std::string(buffer, ptr-buffer); +#endif +} + +void es3::append_int_to_string(int64_t in, std::string &out) +{ + char buffer[64]; +#ifdef __MACH__ + sprintf(buffer, "%lld", in); + out.append(buffer); +#else + char *ptr = buffer; + karma::generate(ptr, int_, in); + *ptr = '\0'; + out.append(buffer, ptr); +#endif +} + +std::string es3::trim(const std::string &str) +{ + std::string res; + bool hit_non_ws=false; + int ws_span=0; + for(std::string::const_iterator iter=str.begin();iter!=str.end();++iter) + { + const char c=*iter; + + if (c==' ' || c=='\n' || c=='\r' || c=='\t') + { + ws_span++; + } else + { + if (ws_span!=0 && hit_non_ws) + res.append(ws_span, ' '); + ws_span=0; + hit_non_ws=true; + + res.append(1, c); + } + } + return res; +} + +std::string es3::tobinhex(const unsigned char* data, size_t ln) +{ + static const char alphabet[17]="0123456789abcdef"; + std::string res; + res.resize(ln*2); + for(size_t f=0;f + #include + #include + #include + #include + #include + + static std::string demangle(const char* symbol) + { + char temp[256]; + + //first, try to demangle a c++ name + if (1 == sscanf(symbol, "%*[^(]%*[^_]%127[^)+]", temp)) + { + size_t size; + int status=0; + char* demangled=abi::__cxa_demangle(temp, NULL, &size, &status); + if (demangled) + { + std::string result(demangled); + free(demangled); + return result; + } + } + return symbol; + } + + void es3::backtrace_it(void) + { + #define MAX_FRAMES 100 + void* addresses[MAX_FRAMES]; + const int size = backtrace(addresses, MAX_FRAMES); + char** symbols = backtrace_symbols(addresses, size); + for (int x = 0; x < size; ++x) + fprintf(stderr, "%s\n", demangle(symbols[x]).c_str()); + free(symbols); + } +#else + void es3::backtrace_it(void) {} +#endif diff --git a/pool/shard006/C++/0079266_dvdfrfetcher.cpp b/pool/shard006/C++/0079266_dvdfrfetcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b849a7fc5634e99193a98b4d42585bfe75a9cfaf --- /dev/null +++ b/pool/shard006/C++/0079266_dvdfrfetcher.cpp @@ -0,0 +1,190 @@ +/*************************************************************************** + Copyright (C) 2010 Robby Stephenson + ***************************************************************************/ + +/*************************************************************************** + * * + * 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) 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 14 of version 3 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, see . * + * * + ***************************************************************************/ + +#include "dvdfrfetcher.h" +#include "../translators/xslthandler.h" +#include "../translators/tellicoimporter.h" +#include "../utils/string_utils.h" +#include "../tellico_debug.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + static const int DVDFR_MAX_RETURNS_TOTAL = 20; + static const char* DVDFR_SEARCH_API_URL = "http://www.dvdfr.com/api/search.php"; + static const char* DVDFR_DETAIL_API_URL = "http://www.dvdfr.com/api/dvd.php"; +} + +using namespace Tellico; +using Tellico::Fetch::DVDFrFetcher; + +DVDFrFetcher::DVDFrFetcher(QObject* parent_) + : XMLFetcher(parent_) { + setLimit(DVDFR_MAX_RETURNS_TOTAL); + setXSLTFilename(QStringLiteral("dvdfr2tellico.xsl")); +} + +DVDFrFetcher::~DVDFrFetcher() { +} + +QString DVDFrFetcher::source() const { + return m_name.isEmpty() ? defaultName() : m_name; +} + +bool DVDFrFetcher::canFetch(int type) const { + return type == Data::Collection::Video; +} + +QUrl DVDFrFetcher::searchUrl() { + QUrl u(QString::fromLatin1(DVDFR_SEARCH_API_URL)); + + QUrlQuery q; + switch(request().key) { + case Title: + // DVDfr requires the title string to be in iso-8859-15 + { + QTextCodec* codec = QTextCodec::codecForName("iso-8859-15"); + Q_ASSERT(codec); + q.addQueryItem(QStringLiteral("title"), QString::fromUtf8(codec->fromUnicode(request().value))); + } + break; + + case UPC: + q.addQueryItem(QStringLiteral("gencode"), request().value); + break; + + default: + myWarning() << "key not recognized: " << request().key; + return QUrl(); + } + u.setQuery(q); +// myDebug() << "url: " << u.url(); + return u; +} + +Tellico::Data::EntryPtr DVDFrFetcher::fetchEntryHookData(Data::EntryPtr entry_) { + Q_ASSERT(entry_); + + const QString id = entry_->field(QStringLiteral("dvdfr-id")); + if(id.isEmpty()) { + myDebug() << "no dvdfr id found"; + return entry_; + } + + QUrl u(QString::fromLatin1(DVDFR_DETAIL_API_URL)); + QUrlQuery q; + q.addQueryItem(QStringLiteral("id"), id); + u.setQuery(q); +// myDebug() << "url: " << u; + + // quiet + QString output = FileHandler::readXMLFile(u, true); + +#if 0 + myWarning() << "Remove output debug from dvdfrfetcher.cpp"; + QFile f(QLatin1String("/tmp/test.xml")); + if(f.open(QIODevice::WriteOnly)) { + QTextStream t(&f); + t.setCodec("UTF-8"); + t << output; + } + f.close(); +#endif + + Import::TellicoImporter imp(xsltHandler()->applyStylesheet(output)); + // be quiet when loading images + imp.setOptions(imp.options() ^ Import::ImportShowImageErrors); + Data::CollPtr coll = imp.collection(); +// getTracks(entry); + if(!coll) { + myWarning() << "no collection pointer"; + return entry_; + } + if(coll->entryCount() == 0) { + myWarning() << "no entries"; + return entry_; + } + + if(coll->entryCount() > 1) { + myDebug() << "weird, more than one entry found"; + } + + // don't want to include id + coll->removeField(QStringLiteral("dvdfr-id")); + return coll->entries().front(); +} + +Tellico::Fetch::FetchRequest DVDFrFetcher::updateRequest(Data::EntryPtr entry_) { + QString title = entry_->field(QStringLiteral("title")); + if(!title.isEmpty()) { + return FetchRequest(Title, title); + } + return FetchRequest(); +} + +Tellico::Fetch::ConfigWidget* DVDFrFetcher::configWidget(QWidget* parent_) const { + return new DVDFrFetcher::ConfigWidget(parent_, this); +} + +QString DVDFrFetcher::defaultName() { + return QStringLiteral("DVDFr.com"); +} + +QString DVDFrFetcher::defaultIcon() { + return favIcon("http://www.dvdfr.com"); +} + +Tellico::StringHash DVDFrFetcher::allOptionalFields() { + StringHash hash; + hash[QStringLiteral("origtitle")] = i18n("Original Title"); + hash[QStringLiteral("dvdfr")] = i18n("DVDFr Link"); + hash[QStringLiteral("alttitle")] = i18n("Alternative Titles"); + return hash; +} + +DVDFrFetcher::ConfigWidget::ConfigWidget(QWidget* parent_, const DVDFrFetcher* fetcher_) + : Fetch::ConfigWidget(parent_) { + QVBoxLayout* l = new QVBoxLayout(optionsWidget()); + l->addWidget(new QLabel(i18n("This source has no options."), optionsWidget())); + l->addStretch(); + + // now add additional fields widget + addFieldsWidget(DVDFrFetcher::allOptionalFields(), fetcher_ ? fetcher_->optionalFields() : QStringList()); +} + +void DVDFrFetcher::ConfigWidget::saveConfigHook(KConfigGroup&) { +} + +QString DVDFrFetcher::ConfigWidget::preferredName() const { + return DVDFrFetcher::defaultName(); +} diff --git a/pool/shard006/C++/0079270_readmessage.cpp b/pool/shard006/C++/0079270_readmessage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e4d2519d532bbbe50f127b5f7d44b37203c3505 --- /dev/null +++ b/pool/shard006/C++/0079270_readmessage.cpp @@ -0,0 +1,16 @@ +#include +#include + +int main(int argc, char *argv[]){ + SysMessageQueue smqObj; + smqObj.Open(argv[1], 256, 20, O_RDONLY); + if(smqObj.IsOpened()){ + std::cout << "No Of Available Message is " << smqObj.NoOfMessagesInQueue() << std::endl; + char msg[512]={0x00}; +// smqObj.Read(msg, 511); + perror("mq:"); + std::cout << "1st Message In Queue is " << msg << std::endl; + smqObj.Close(); + } + return 0; +} diff --git a/pool/shard006/C++/0079281_snakelogindialog.cpp b/pool/shard006/C++/0079281_snakelogindialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8d827ff95646f1e069a4c29fc107cce7b650478 --- /dev/null +++ b/pool/shard006/C++/0079281_snakelogindialog.cpp @@ -0,0 +1,35 @@ +// +// C++ Implementation: snakelogindialog +// +// Description: +// +// +// Author: Daniel Bengtsson , (C) 2006 +// +// Copyright: See COPYING file that comes with this distribution +// +// +#include "snakelogindialog.h" + +#include "qlineedit.h" +#include "qpixmap.h" + +SnakeLoginDialog::SnakeLoginDialog(QWidget* parent) + : LoginDialog(parent) +{ + QPixmap ico("/usr/share/app-install/icons/snakenet.png"); + if( !ico.isNull() ) + setIcon(ico); +} + +SnakeLoginDialog::~SnakeLoginDialog() +{ +} + +void SnakeLoginDialog::accept() +{ + emit login(m_username->text(), m_password->text()); + LoginDialog::accept(); +} + +#include "snakelogindialog.moc" diff --git a/pool/shard006/C++/0079286_Jit_LoadStorePaired.cpp b/pool/shard006/C++/0079286_Jit_LoadStorePaired.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1129d5e83342a7a13790120ea62aa308cf42438f --- /dev/null +++ b/pool/shard006/C++/0079286_Jit_LoadStorePaired.cpp @@ -0,0 +1,104 @@ +// Copyright 2013 Dolphin Emulator Project +// Licensed under GPLv2 +// Refer to the license.txt file included. + +// TODO(ector): Tons of pshufb optimization of the loads/stores, for SSSE3+, possibly SSE4, only. +// Should give a very noticeable speed boost to paired single heavy code. + +#include "Common/Common.h" +#include "Common/CPUDetect.h" + +#include "Core/PowerPC/Jit64/Jit.h" +#include "Core/PowerPC/Jit64/JitAsm.h" +#include "Core/PowerPC/Jit64/JitRegCache.h" + +using namespace Gen; + +// The big problem is likely instructions that set the quantizers in the same block. +// We will have to break block after quantizers are written to. +void Jit64::psq_st(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITLoadStorePairedOff); + FALLBACK_IF(js.memcheck || !inst.RA); + + bool update = inst.OPCD == 61; + + int offset = inst.SIMM_12; + int a = inst.RA; + int s = inst.RS; // Fp numbers + + gpr.FlushLockX(EAX, EDX); + gpr.FlushLockX(ECX); + if (update) + gpr.BindToRegister(inst.RA, true, true); + fpr.BindToRegister(inst.RS, true, false); + MOV(32, R(ECX), gpr.R(inst.RA)); + if (offset) + ADD(32, R(ECX), Imm32((u32)offset)); + if (update && offset) + MOV(32, gpr.R(a), R(ECX)); + // Some games (e.g. Dirt 2) incorrectly set the unused bits which breaks the lookup table code. + // Hence, we need to mask out the unused bits. The layout of the GQR register is + // UU[SCALE]UUUUU[TYPE] where SCALE is 6 bits and TYPE is 3 bits, so we have to AND with + // 0b0011111100000111, or 0x3F07. + MOV(32, R(EAX), Imm32(0x3F07)); + AND(32, R(EAX), M(&PowerPC::ppcState.spr[SPR_GQR0 + inst.I])); + MOVZX(32, 8, EDX, R(AL)); + + // FIXME: Fix ModR/M encoding to allow [EDX*4+disp32] without a base register! + if (inst.W) + { + // One value + PXOR(XMM0, R(XMM0)); // TODO: See if we can get rid of this cheaply by tweaking the code in the singleStore* functions. + CVTSD2SS(XMM0, fpr.R(s)); + CALLptr(MScaled(EDX, SCALE_8, (u32)(u64)asm_routines.singleStoreQuantized)); + } + else + { + // Pair of values + CVTPD2PS(XMM0, fpr.R(s)); + CALLptr(MScaled(EDX, SCALE_8, (u32)(u64)asm_routines.pairedStoreQuantized)); + } + gpr.UnlockAll(); + gpr.UnlockAllX(); +} + +void Jit64::psq_l(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITLoadStorePairedOff); + FALLBACK_IF(js.memcheck || !inst.RA); + + bool update = inst.OPCD == 57; + int offset = inst.SIMM_12; + + gpr.FlushLockX(EAX, EDX); + gpr.FlushLockX(ECX); + gpr.BindToRegister(inst.RA, true, update && offset); + fpr.BindToRegister(inst.RS, false, true); + if (offset) + LEA(32, ECX, MDisp(gpr.RX(inst.RA), offset)); + else + MOV(32, R(ECX), gpr.R(inst.RA)); + if (update && offset) + MOV(32, gpr.R(inst.RA), R(ECX)); + MOV(32, R(EAX), Imm32(0x3F07)); + AND(32, R(EAX), M(((char *)&GQR(inst.I)) + 2)); + MOVZX(32, 8, EDX, R(AL)); + if (inst.W) + OR(32, R(EDX), Imm8(8)); + + ABI_AlignStack(0); + CALLptr(MScaled(EDX, SCALE_8, (u32)(u64)asm_routines.pairedLoadQuantized)); + ABI_RestoreStack(0); + + // MEMCHECK_START // FIXME: MMU does not work here because of unsafe memory access + + CVTPS2PD(fpr.RX(inst.RS), R(XMM0)); + + // MEMCHECK_END + + gpr.UnlockAll(); + gpr.UnlockAllX(); +} diff --git a/pool/shard006/C++/0079288_imagepreviewdialog.cpp b/pool/shard006/C++/0079288_imagepreviewdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1261fd917342800aa38827ecd75f789b19442e9 --- /dev/null +++ b/pool/shard006/C++/0079288_imagepreviewdialog.cpp @@ -0,0 +1,155 @@ +#include "imagepreviewdialog.h" +#include "ui_imagepreviewdialog.h" + +#include +#include +#include +#include + +#include "imagewrapper.h" + +ImagePreviewDialog::ImagePreviewDialog(QDir initDir) : + QDialog(0), + ui(new Ui::ImagePreviewDialog) +{ + ui->setupUi(this); + + QColor c(255,255,255,0); + QSize s(20,20); + image = new ImageWrapper(s, c); + preview_widget = new ImageHighlight(this, image); + preview_widget->setMaximumHeight(200); + + ui->preview_layout->addWidget(preview_widget); + + curDir = QDir(initDir); + ui->current_dir_text->setText(curDir.absolutePath()); + + doList(); +} + +ImagePreviewDialog::~ImagePreviewDialog() +{ + delete ui; + delete image; + delete preview_widget; +} + +void ImagePreviewDialog::doList() +{ + ui->listWidget->clear(); + QStringList list = curDir.entryList(); + for(int i=0;ilistWidget->addItem(list.at(i)); + } + ui->current_dir_text->setText(curDir.absolutePath()); +} + +void ImagePreviewDialog::on_listWidget_doubleClicked(const QModelIndex &index) +{ + QString item = index.data().toString(); + QDir dir = curDir; + if(dir.cd(item)) + { + curDir = dir; + doList(); + } else { + accept(); + } +} + +void ImagePreviewDialog::on_up_button_clicked() +{ + if(curDir.cd("..")) + doList(); +} + +void ImagePreviewDialog::on_go_button_clicked() +{ + if(ui->listWidget->hasFocus() && ui->listWidget->selectedItems().size()>0) + { + QString item = ui->listWidget->selectedItems().at(0)->text(); + QFileInfo info(curDir.absoluteFilePath(item)); + if( info.exists() && info.isFile() ) + { + accept(); + return; + } + ui->current_dir_text->setText( curDir.absoluteFilePath( item ) ); + } + + QDir d(ui->current_dir_text->text()); + if(d.exists()) + curDir = d; + doList(); +} + +void ImagePreviewDialog::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *) +{ + if(!current) return; + QString item = current->text(); + QFile file( curDir.absoluteFilePath(item) ); + if(checkValidFile(file)) + { + doPreview(file); + } else { + QColor c(255,255,255,0); + image->fill(c); +// QPixmap pix(1,1); +// pix.fill(c); +// ui->info_image_preview_label->setPixmap(pix); + ui->info_bitspixel_value_label->setText("0 bits"); + ui->info_dim_value_label->setText("0 x 0 px"); + } +} + +void ImagePreviewDialog::doPreview(QFile &file) +{ + QString filename = file.fileName(); + image->load(filename); + QSize size = image->getSize(); + ui->info_dim_value_label->setText( QString::number(size.width()) + " x " + QString::number(size.height()) + " px" ); + ui->info_bitspixel_value_label->setText( QString::number( image->getQImage()->depth()) + " bits" ); +} + +void ImagePreviewDialog::accept() +{ + if(!ui->listWidget->currentItem()) + { + QMessageBox::information(0, tr("Alert"), tr("Please, select a file!")); + return; + } + QString item = ui->listWidget->currentItem()->text(); + QFile file( curDir.absoluteFilePath(item) ); + if(checkValidFile(file)) + { + selectedFile = file.fileName(); + QDialog::accept(); + } else { + QMessageBox::information(0, tr("Alert"), tr("No suitable file selected!")); + } +} + +bool ImagePreviewDialog::checkValidFile(QFile &file) +{ + bool fileExtValid = file.fileName().endsWith(".jpg") || + file.fileName().endsWith(".png") || + file.fileName().endsWith(".bmp") || + file.fileName().endsWith(".ims"); + + return file.exists() && fileExtValid; +} + +QString ImagePreviewDialog::getSelectedImage() +{ + return selectedFile; +} + +void ImagePreviewDialog::keyPressEvent(QKeyEvent *event) +{ + if(event->key()==Qt::Key_Return && ( ui->current_dir_text->hasFocus() || ui->listWidget->hasFocus() ) ) + on_go_button_clicked(); + else + QDialog::keyPressEvent(event); +} diff --git a/pool/shard006/C++/0079293_wskazniki-2.cpp b/pool/shard006/C++/0079293_wskazniki-2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32fe0af2a2f3131b125c24a3173018ced07194c0 --- /dev/null +++ b/pool/shard006/C++/0079293_wskazniki-2.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +class Node { + public: + int value; + Node* next; + + Node(int val, Node* n) { + value = val; + next = n; + } +}; + +int howManyElemInNumBase(int num, int elem, int base) { + int counter = 0; + while(num > 0) { + if ((num % base) == elem) counter++; + num /= base; + } + return counter; +} + +bool is8odd5(int n) { + return howManyElemInNumBase(n, 5, 8) % 2 == 1; +} + +Node* moveFront8odd5(Node* head) { + + if (head == nullptr) return head; + + Node* h = head; + Node* newbegin; + + while(h->next != nullptr) { + + if(is8odd5(h->next->value)) { + + newbegin = h->next; + h->next = h->next->next; + newbegin->next = head; + head = newbegin; + + } + h = h->next; + + } + return head; + +} + +int main() { + + return 0; +} diff --git a/pool/shard006/C++/0079301_vtkSmoothErrorMetricWrap.cc b/pool/shard006/C++/0079301_vtkSmoothErrorMetricWrap.cc new file mode 100644 index 0000000000000000000000000000000000000000..5e241ba13deab6763055b6f6cc0f15596e30aca4 --- /dev/null +++ b/pool/shard006/C++/0079301_vtkSmoothErrorMetricWrap.cc @@ -0,0 +1,222 @@ +/* this file has been autogenerated by vtkNodeJsWrap */ +/* editing this might proof futile */ + +#define VTK_WRAPPING_CXX +#define VTK_STREAMS_FWD_ONLY +#include + +#include "vtkGenericSubdivisionErrorMetricWrap.h" +#include "vtkSmoothErrorMetricWrap.h" +#include "vtkObjectWrap.h" +#include "../../plus/plus.h" + +using namespace v8; + +extern Nan::Persistent vtkNodeJsNoWrap; +Nan::Persistent VtkSmoothErrorMetricWrap::ptpl; + +VtkSmoothErrorMetricWrap::VtkSmoothErrorMetricWrap() +{ } + +VtkSmoothErrorMetricWrap::VtkSmoothErrorMetricWrap(vtkSmartPointer _native) +{ native = _native; } + +VtkSmoothErrorMetricWrap::~VtkSmoothErrorMetricWrap() +{ } + +void VtkSmoothErrorMetricWrap::Init(v8::Local exports) +{ + Nan::SetAccessor(exports, Nan::New("vtkSmoothErrorMetric").ToLocalChecked(), ConstructorGetter); + Nan::SetAccessor(exports, Nan::New("SmoothErrorMetric").ToLocalChecked(), ConstructorGetter); +} + +void VtkSmoothErrorMetricWrap::ConstructorGetter( + v8::Local property, + const Nan::PropertyCallbackInfo& info) +{ + InitPtpl(); + info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); +} + +void VtkSmoothErrorMetricWrap::InitPtpl() +{ + if (!ptpl.IsEmpty()) return; + v8::Local tpl = Nan::New(New); + VtkGenericSubdivisionErrorMetricWrap::InitPtpl( ); + tpl->Inherit(Nan::New(VtkGenericSubdivisionErrorMetricWrap::ptpl)); + tpl->SetClassName(Nan::New("VtkSmoothErrorMetricWrap").ToLocalChecked()); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + Nan::SetPrototypeMethod(tpl, "GetAngleTolerance", GetAngleTolerance); + Nan::SetPrototypeMethod(tpl, "getAngleTolerance", GetAngleTolerance); + + Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); + Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); + + Nan::SetPrototypeMethod(tpl, "IsA", IsA); + Nan::SetPrototypeMethod(tpl, "isA", IsA); + + Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); + Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); + + Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); + Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); + + Nan::SetPrototypeMethod(tpl, "SetAngleTolerance", SetAngleTolerance); + Nan::SetPrototypeMethod(tpl, "setAngleTolerance", SetAngleTolerance); + +#ifdef VTK_NODE_PLUS_VTKSMOOTHERRORMETRICWRAP_INITPTPL + VTK_NODE_PLUS_VTKSMOOTHERRORMETRICWRAP_INITPTPL +#endif + ptpl.Reset( tpl ); +} + +void VtkSmoothErrorMetricWrap::New(const Nan::FunctionCallbackInfo& info) +{ + if(!info.IsConstructCall()) + { + Nan::ThrowError("Constructor not called in a construct call."); + return; + } + + if(info.Length() == 0) + { + vtkSmartPointer native = vtkSmartPointer::New(); + VtkSmoothErrorMetricWrap* obj = new VtkSmoothErrorMetricWrap(native); + obj->Wrap(info.This()); + } + else + { + if(info[0]->ToObject() != vtkNodeJsNoWrap ) + { + Nan::ThrowError("Parameter Error"); + return; + } + } + + info.GetReturnValue().Set(info.This()); +} + +void VtkSmoothErrorMetricWrap::GetAngleTolerance(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + double r; + if(info.Length() != 0) + { + Nan::ThrowError("Too many parameters."); + return; + } + r = native->GetAngleTolerance(); + info.GetReturnValue().Set(Nan::New(r)); +} + +void VtkSmoothErrorMetricWrap::GetClassName(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + char const * r; + if(info.Length() != 0) + { + Nan::ThrowError("Too many parameters."); + return; + } + r = native->GetClassName(); + info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); +} + +void VtkSmoothErrorMetricWrap::IsA(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + if(info.Length() > 0 && info[0]->IsString()) + { + Nan::Utf8String a0(info[0]); + int r; + if(info.Length() != 1) + { + Nan::ThrowError("Too many parameters."); + return; + } + r = native->IsA( + *a0 + ); + info.GetReturnValue().Set(Nan::New(r)); + return; + } + Nan::ThrowError("Parameter mismatch"); +} + +void VtkSmoothErrorMetricWrap::NewInstance(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + vtkSmoothErrorMetric * r; + if(info.Length() != 0) + { + Nan::ThrowError("Too many parameters."); + return; + } + r = native->NewInstance(); + VtkSmoothErrorMetricWrap::InitPtpl(); + v8::Local argv[1] = + { Nan::New(vtkNodeJsNoWrap) }; + v8::Local cons = + Nan::New(VtkSmoothErrorMetricWrap::ptpl)->GetFunction(); + v8::Local wo = cons->NewInstance(1, argv); + VtkSmoothErrorMetricWrap *w = new VtkSmoothErrorMetricWrap(); + w->native = r; + w->Wrap(wo); + info.GetReturnValue().Set(wo); +} + +void VtkSmoothErrorMetricWrap::SafeDownCast(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) + { + VtkObjectWrap *a0 = ObjectWrap::Unwrap(info[0]->ToObject()); + vtkSmoothErrorMetric * r; + if(info.Length() != 1) + { + Nan::ThrowError("Too many parameters."); + return; + } + r = native->SafeDownCast( + (vtkObject *) a0->native.GetPointer() + ); + VtkSmoothErrorMetricWrap::InitPtpl(); + v8::Local argv[1] = + { Nan::New(vtkNodeJsNoWrap) }; + v8::Local cons = + Nan::New(VtkSmoothErrorMetricWrap::ptpl)->GetFunction(); + v8::Local wo = cons->NewInstance(1, argv); + VtkSmoothErrorMetricWrap *w = new VtkSmoothErrorMetricWrap(); + w->native = r; + w->Wrap(wo); + info.GetReturnValue().Set(wo); + return; + } + Nan::ThrowError("Parameter mismatch"); +} + +void VtkSmoothErrorMetricWrap::SetAngleTolerance(const Nan::FunctionCallbackInfo& info) +{ + VtkSmoothErrorMetricWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); + vtkSmoothErrorMetric *native = (vtkSmoothErrorMetric *)wrapper->native.GetPointer(); + if(info.Length() > 0 && info[0]->IsNumber()) + { + if(info.Length() != 1) + { + Nan::ThrowError("Too many parameters."); + return; + } + native->SetAngleTolerance( + info[0]->NumberValue() + ); + return; + } + Nan::ThrowError("Parameter mismatch"); +} + diff --git a/pool/shard006/C++/0079307_kexiinternalpart.cpp b/pool/shard006/C++/0079307_kexiinternalpart.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1c19584b2865519b449f9230b04797d75da76a9 --- /dev/null +++ b/pool/shard006/C++/0079307_kexiinternalpart.cpp @@ -0,0 +1,233 @@ +/* This file is part of the KDE project + Copyright (C) 2004 Lucijan Busch + Copyright (C) 2004-2009 Jarosław Staniek + + 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 "kexiinternalpart.h" +#include "kexipartmanager.h" + +#include "KexiWindow.h" +#include "KexiView.h" +#include "KexiMainWindowIface.h" + +#include + +#include +#include + +#include +#include + +#include + +//---------------------------------------------- + +class KexiInternalPart::Private +{ +public: + Private(); + ~Private(); + + //! Unique dialog - we're using guarded ptr for the dialog so can know if it has been closed + QPointer uniqueWidget; + bool uniqueWindow; //!< true if createWidgetInstance() should return only one window + bool cancelled; //!< Used in cancelled() +}; + +KexiInternalPart::Private::Private() : uniqueWindow(true) + ,cancelled(false) +{ +} + +KexiInternalPart::Private::~Private() +{ +} + +KexiInternalPart::KexiInternalPart(QObject *parent, const QVariantList &list) + : KexiPart::PartBase(parent, list) + , d(new Private) +{ +} + +KexiInternalPart::~KexiInternalPart() +{ + delete d; +} + +//static +KexiInternalPart* KexiInternalPart::part(KexiDB::MessageHandler *msgHdr, const QString &className) +{ + KexiInternalPart *part = Kexi::partManager().internalPartForClass(className); + if (!part) { + if (msgHdr) { + msgHdr->showErrorMessage(&Kexi::partManager()); + } + } + return part; +} + +//static +QWidget* KexiInternalPart::createWidgetInstance(const QString &className, + const char* widgetClass, KexiDB::MessageHandler *msgHdr, + QWidget *parent, const char *objName, QMap* args) +{ + KexiInternalPart *part = KexiInternalPart::part(msgHdr, className); + if (!part) + return 0; //fatal! + return part->createWidget(widgetClass, parent, + objName ? objName : className.toLatin1().constData(), args); +} + +KexiWindow* KexiInternalPart::findOrCreateKexiWindow( + const char *objName) +{ + if (d->uniqueWindow && !d->uniqueWidget.isNull()) + return dynamic_cast((QWidget*)d->uniqueWidget); + KexiWindow * wnd = new KexiWindow(); + KexiView *view = createView(0, objName); + if (!view) + return 0; + + if (d->uniqueWindow) + d->uniqueWidget = wnd; //recall unique! + wnd->addView(view); + wnd->setWindowTitle(view->windowTitle()); + wnd->resize(view->sizeHint()); + wnd->setMinimumSize(view->minimumSizeHint().width(), view->minimumSizeHint().height()); + wnd->setId(KexiMainWindowIface::global()->project()->generatePrivateID()); + wnd->registerWindow(); + return wnd; +} + +//static +QWidget* KexiInternalPart::createWidgetInstance(const QString &className, + KexiDB::MessageHandler *msgHdr, + QWidget *parent, const char *objName, + QMap* args) +{ + return createWidgetInstance(className, 0, msgHdr, parent, objName, args); +} + +//static +KexiWindow* KexiInternalPart::createKexiWindowInstance( + const QString &className, + KexiDB::MessageHandler *msgHdr, const char *objName) +{ + KexiInternalPart *part = KexiInternalPart::part(msgHdr, className); + if (!part) { + kWarning() << "!part"; + return 0; //fatal! + } + return part->findOrCreateKexiWindow(objName ? objName : className.toLatin1().constData()); +} + +//static +QDialog* KexiInternalPart::createModalDialogInstance(const QString &className, + const char* dialogClass, KexiDB::MessageHandler *msgHdr, + const char *objName, QMap* args) +{ + KexiInternalPart *part = KexiInternalPart::part(msgHdr, className); + if (!part) { + kWarning() << "!part"; + return 0; //fatal! + } + QWidget *w; + if (part->uniqueWindow() && !part->d->uniqueWidget.isNull()) + w = part->d->uniqueWidget; + else + w = part->createWidget(dialogClass, KexiMainWindowIface::global()->thisWidget(), + objName ? objName : className.toLatin1().constData(), args); + + if (dynamic_cast(w)) { + if (part->uniqueWindow()) + part->d->uniqueWidget = w; + return dynamic_cast(w); + } + //sanity + if (!(part->uniqueWindow() && !part->d->uniqueWidget.isNull())) + delete w; + return 0; +} + +//static +QDialog* KexiInternalPart::createModalDialogInstance(const QString &className, + KexiDB::MessageHandler *msgHdr, const char *objName, + QMap* args) +{ + return createModalDialogInstance(className, 0, msgHdr, objName, args); +} + +//static +bool KexiInternalPart::executeCommand(const QString &className, + const char* commandName, QMap* args) +{ + KexiInternalPart *part = KexiInternalPart::part(0, className); + if (!part) { + kWarning() << "!part"; + return 0; //fatal! + } + return part->executeCommand(commandName, args); +} + +QWidget* KexiInternalPart::createWidget(const char* widgetClass, + QWidget * parent, const char * objName, QMap* args) +{ + Q_UNUSED(widgetClass); + Q_UNUSED(parent); + Q_UNUSED(objName); + Q_UNUSED(args); + return 0; +} + +KexiView* KexiInternalPart::createView(QWidget * parent, + const char * objName) +{ + Q_UNUSED(parent); + Q_UNUSED(objName); + return 0; +} + +bool KexiInternalPart::executeCommand(const char* commandName, + QMap* args) +{ + Q_UNUSED(commandName); + Q_UNUSED(args); + return false; +} + +bool KexiInternalPart::uniqueWindow() const +{ + return d->uniqueWindow; +} + +void KexiInternalPart::setUniqueWindow(bool set) +{ + d->uniqueWindow = set; +} + +bool KexiInternalPart::cancelled() const +{ + return d->cancelled; +} + +void KexiInternalPart::setCancelled(bool set) +{ + d->cancelled = set; +} + +#include "kexiinternalpart.moc" diff --git a/pool/shard006/C++/0079310_Solution.cpp b/pool/shard006/C++/0079310_Solution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fe825519fbb85422871b8dbb186c862c682922b --- /dev/null +++ b/pool/shard006/C++/0079310_Solution.cpp @@ -0,0 +1,24 @@ +class Solution { +private: + void helper(vector& res, string str, int a, int b) { + if (a == 0 && b == 0) { + res.push_back(str); + } else if (a == 0) { + helper(res, str + ")", a, b - 1); + } else { + helper(res, str + "(", a - 1, b); + if (a < b) { + helper(res, str + ")", a, b - 1); + } + } + return; + } + +public: + vector generateParenthesis(int n) { + vector res; + string str = ""; + helper(res, str, n, n); + return res; + } +}; diff --git a/pool/shard006/C++/0079334_DelayEffect.cpp b/pool/shard006/C++/0079334_DelayEffect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82eea249e98aaf4ce1219cd084c2522c09be74a6 --- /dev/null +++ b/pool/shard006/C++/0079334_DelayEffect.cpp @@ -0,0 +1,170 @@ +/* + * delayeffect.cpp - definition of the DelayEffect class. The Delay Plugin + * + * Copyright (c) 2014 David French + * + * This file is part of LMMS - https://lmms.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program (see COPYING); if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA. + * + */ + +#include "DelayEffect.h" + +#include "Engine.h" +#include "embed.h" +#include "interpolation.h" + +extern "C" +{ + + Plugin::Descriptor PLUGIN_EXPORT delay_plugin_descriptor + = {STRINGIFY(PLUGIN_NAME), + "Delay", + QT_TRANSLATE_NOOP("pluginBrowser", "A native delay plugin"), + "Dave French " + "", + 0x0100, + Plugin::Effect, + new PluginPixmapLoader("logo"), + NULL, + NULL}; + + DelayEffect::DelayEffect( + Model* parent, + const Plugin::Descriptor::SubPluginFeatures::Key* key) : + Effect(&delay_plugin_descriptor, parent, key), + m_delayControls(this) + { + m_delay = 0; + m_delay = new StereoDelay(20, + Engine::mixer()->processingSampleRate()); + m_lfo = new Lfo(Engine::mixer()->processingSampleRate()); + m_outGain = 1.0; + } + + DelayEffect::~DelayEffect() + { + if(m_delay) + { + delete m_delay; + } + if(m_lfo) + { + delete m_lfo; + } + } + + bool DelayEffect::processAudioBuffer(sampleFrame* buf, const fpp_t frames) + { + bool smoothBegin, smoothEnd; + if(!shouldProcessAudioBuffer(buf, frames, smoothBegin, smoothEnd)) + return false; + + const real_t sr = Engine::mixer()->processingSampleRate(); + real_t lPeak = 0.; + real_t rPeak = 0.; + real_t length = m_delayControls.m_delayTimeModel.value(); + real_t amplitude = m_delayControls.m_lfoAmountModel.value() * sr; + real_t lfoTime = 1.0 / m_delayControls.m_lfoTimeModel.value(); + real_t feedback = m_delayControls.m_feedbackModel.value(); + /*const*/ ValueBuffer* lengthBuffer + = m_delayControls.m_delayTimeModel.valueBuffer(); + /*const*/ ValueBuffer* feedbackBuffer + = m_delayControls.m_feedbackModel.valueBuffer(); + /*const*/ ValueBuffer* lfoTimeBuffer + = m_delayControls.m_lfoTimeModel.valueBuffer(); + /*const*/ ValueBuffer* lfoAmountBuffer + = m_delayControls.m_lfoAmountModel.valueBuffer(); + int lengthInc = lengthBuffer ? 1 : 0; + int amplitudeInc = lfoAmountBuffer ? 1 : 0; + int lfoTimeInc = lfoTimeBuffer ? 1 : 0; + int feedbackInc = feedbackBuffer ? 1 : 0; + + real_t* lengthPtr + // = lengthBuffer ? &(lengthBuffer->values()[0]) : + // &length; + = lengthBuffer ? lengthBuffer->values() : &length; + real_t* amplitudePtr + = lfoAmountBuffer ? lfoAmountBuffer->values() : &litude; + real_t* lfoTimePtr + = lfoTimeBuffer ? lfoTimeBuffer->values() : &lfoTime; + real_t* feedbackPtr + = feedbackBuffer ? feedbackBuffer->values() : &feedback; + + if(m_delayControls.m_outGainModel.isValueChanged()) + { + m_outGain = dbfsToAmp(m_delayControls.m_outGainModel.value()); + } + + int sampleLength; + for(fpp_t f = 0; f < frames; ++f) + { + real_t w0, d0, w1, d1; + computeWetDryLevels(f, frames, smoothBegin, smoothEnd, w0, d0, w1, + d1); + + sample_t dryS[2] = {buf[f][0], buf[f][1]}; + + m_delay->setFeedback(*feedbackPtr); + m_lfo->setFrequency(*lfoTimePtr); + sampleLength + = *lengthPtr * Engine::mixer()->processingSampleRate(); + m_currentLength = sampleLength; + m_delay->setLength(m_currentLength + + (*amplitudePtr * real_t(m_lfo->tick()))); + m_delay->tick(buf[f]); + + buf[f][0] *= m_outGain; + buf[f][1] *= m_outGain; + + lPeak = buf[f][0] > lPeak ? buf[f][0] : lPeak; + rPeak = buf[f][1] > rPeak ? buf[f][1] : rPeak; + + buf[f][0] = (d0 * dryS[0]) + (w0 * buf[f][0]); + buf[f][1] = (d1 * dryS[1]) + (w1 * buf[f][1]); + + lengthPtr += lengthInc; + amplitudePtr += amplitudeInc; + lfoTimePtr += lfoTimeInc; + feedbackPtr += feedbackInc; + } + + m_delayControls.m_outPeakL = lPeak; + m_delayControls.m_outPeakR = rPeak; + + return true; + } + + void DelayEffect::changeSampleRate() + { + m_lfo->setSampleRate(Engine::mixer()->processingSampleRate()); + m_delay->setSampleRate(Engine::mixer()->processingSampleRate()); + } + + extern "C" + { + + // needed for getting plugin out of shared lib + Plugin* PLUGIN_EXPORT lmms_plugin_main(Model* parent, void* data) + { + return new DelayEffect( + parent, + static_cast(data)); + } + } +} diff --git a/pool/shard006/C++/0079347_serialize.cc b/pool/shard006/C++/0079347_serialize.cc new file mode 100644 index 0000000000000000000000000000000000000000..7c3d15f07a29f7e6b1d1c421d44372a640189b63 --- /dev/null +++ b/pool/shard006/C++/0079347_serialize.cc @@ -0,0 +1,51 @@ +// { dg-options "-std=gnu++11" } +// { dg-require-cstdint "" } +// +// 2012-01-28 Edward M. Smith-Rowland <3dw4rd@verizon.net> +// +// Copyright (C) 2012-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 +// . + +// Class template rice_distribution +// 26.5.1.6 Random number distribution requirements [rand.req.dist] + +#include +#include +#include + +void +test01() +{ + bool test __attribute__((unused)) = true; + + std::stringstream str; + __gnu_cxx::rice_distribution u(1.5, 3.0), v; + std::minstd_rand0 rng; + + u(rng); // advance + str << u; + + str >> v; + VERIFY( u == v ); +} + +int +main() +{ + test01(); + return 0; +} diff --git a/pool/shard006/C++/0079352_strided_memcpy_test.cc b/pool/shard006/C++/0079352_strided_memcpy_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a6ca82d16f216c98055fb92b4575a357b8b10348 --- /dev/null +++ b/pool/shard006/C++/0079352_strided_memcpy_test.cc @@ -0,0 +1,161 @@ +/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/strided_memcpy.h" +#include "gtest/gtest.h" +#include "paddle/fluid/memory/memory.h" + +namespace paddle { +namespace operators { + +TEST(StridedMemcpy, CPUCrop) { + // clang-format off + int src[] = { + 0, 1, 2, 0, 0, + 0, 3, 4, 0, 0, + 0, 0, 0, 0, 0, + }; + // clang-format on + + framework::DDim src_stride({5, 1}); + + int dst[4]; + framework::DDim dst_dim({2, 2}); + framework::DDim dst_stride({2, 1}); + + platform::CPUDeviceContext ctx; + StridedMemcpy(ctx, src + 1, src_stride, dst_dim, dst_stride, dst); + + ASSERT_EQ(1, dst[0]); + ASSERT_EQ(2, dst[1]); + ASSERT_EQ(3, dst[2]); + ASSERT_EQ(4, dst[3]); +} + +TEST(StridedMemcpy, CPUConcat) { + // clang-format off + int src[] = { + 1, 2, + 3, 4 + }; + // clang-format on + + int dst[8]; + + framework::DDim src_stride({2, 1}); + framework::DDim dst_dim({2, 2}); + framework::DDim dst_stride({4, 1}); + platform::CPUDeviceContext ctx; + + StridedMemcpy(ctx, src, src_stride, dst_dim, dst_stride, dst); + StridedMemcpy(ctx, src, src_stride, dst_dim, dst_stride, dst + 2); + + // clang-format off + int expect_dst[] = { + 1, 2, 1, 2, + 3, 4, 3, 4 + }; + // clang-format on + for (size_t i = 0; i < sizeof(expect_dst) / sizeof(int); ++i) { + ASSERT_EQ(expect_dst[i], dst[i]); + } +} + +#ifdef PADDLE_WITH_CUDA +TEST(StridedMemcpy, GPUCrop) { + // clang-format off + int src[] = { + 0, 1, 2, 0, 0, + 0, 3, 4, 0, 0, + 0, 0, 0, 0, 0, + }; + // clang-format on + + platform::CUDAPlace gpu0(0); + platform::CPUPlace cpu; + + platform::CUDADeviceContext ctx(gpu0); + + int* gpu_src = reinterpret_cast(memory::Alloc(gpu0, sizeof(src))); + memory::Copy(gpu0, gpu_src, cpu, src, sizeof(src), ctx.stream()); + + framework::DDim src_stride({5, 1}); + + int dst[4]; + int* gpu_dst = reinterpret_cast(memory::Alloc(gpu0, sizeof(dst))); + + framework::DDim dst_dim({2, 2}); + framework::DDim dst_stride({2, 1}); + + StridedMemcpy(ctx, gpu_src + 1, src_stride, dst_dim, dst_stride, + gpu_dst); + + memory::Copy(cpu, dst, gpu0, gpu_dst, sizeof(dst), ctx.stream()); + ctx.Wait(); + + ASSERT_EQ(1, dst[0]); + ASSERT_EQ(2, dst[1]); + ASSERT_EQ(3, dst[2]); + ASSERT_EQ(4, dst[3]); + + memory::Free(gpu0, gpu_dst); + memory::Free(gpu0, gpu_src); +} + +TEST(StridedMemcpy, GPUConcat) { + // clang-format off + int src[] = { + 1, 2, + 3, 4 + }; + // clang-format on + + platform::CUDAPlace gpu0(0); + platform::CPUPlace cpu; + platform::CUDADeviceContext ctx(gpu0); + + int* gpu_src = reinterpret_cast(memory::Alloc(gpu0, sizeof(src))); + memory::Copy(gpu0, gpu_src, cpu, src, sizeof(src), ctx.stream()); + + int dst[8]; + int* gpu_dst = reinterpret_cast(memory::Alloc(gpu0, sizeof(dst))); + + framework::DDim src_stride({2, 1}); + framework::DDim dst_dim({2, 2}); + framework::DDim dst_stride({4, 1}); + + StridedMemcpy(ctx, gpu_src, src_stride, dst_dim, dst_stride, gpu_dst); + StridedMemcpy(ctx, gpu_src, src_stride, dst_dim, dst_stride, + gpu_dst + 2); + + memory::Copy(cpu, dst, gpu0, gpu_dst, sizeof(dst), ctx.stream()); + ctx.Wait(); + + // clang-format off + int expect_dst[] = { + 1, 2, 1, 2, + 3, 4, 3, 4 + }; + // clang-format on + for (size_t i = 0; i < sizeof(expect_dst) / sizeof(int); ++i) { + ASSERT_EQ(expect_dst[i], dst[i]); + } + + memory::Free(gpu0, gpu_dst); + memory::Free(gpu0, gpu_src); +} + +#endif +} // namespace operators +} // namespace paddle diff --git a/pool/shard006/C++/0079358_hello_xml.cpp b/pool/shard006/C++/0079358_hello_xml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00e1b6c8e17e223978fb83ce8968b7510e899558 --- /dev/null +++ b/pool/shard006/C++/0079358_hello_xml.cpp @@ -0,0 +1,87 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +#include +#include +#include +#include +#include + +#include +#include +using std::stringstream; + +using namespace qpid::messaging; + +int main(int argc, char** argv) { + std::string broker = argc > 1 ? argv[1] : "localhost:5672"; + std::string connectionOptions = argc > 2 ? argv[2] : ""; + + std::string query = + "let $w := ./weather " + "return $w/station = 'Raleigh-Durham International Airport (KRDU)' " + " and $w/temperature_f > 50" + " and $w/temperature_f - $w/dewpoint > 5" + " and $w/wind_speed_mph > 7" + " and $w/wind_speed_mph < 20"; + + stringstream address; + + address << "xml-exchange; {" + " create: always, " // This line and the next are not in docs + " node: { type: topic, x-declare: { type: xml } }, " // Added so it works "out of the box" + " link: { " + " x-bindings: [{ exchange: xml-exchange, key: weather, arguments: { xquery:\"" + << query + << "\"} }] " + " } " + "}"; + + Connection connection(broker, connectionOptions); + try { + connection.open(); + Session session = connection.createSession(); + + Receiver receiver = session.createReceiver(address.str()); + + Message message; + message.setContent( + "" + "Raleigh-Durham International Airport (KRDU)" + "16" + "70" + "35" + ""); + Sender sender = session.createSender("xml-exchange/weather"); + sender.send(message); + + Message response = receiver.fetch(); + + std::cout << response.getContent() << std::endl; + + connection.close(); + return 0; + } catch(const std::exception& error) { + std::cerr << error.what() << std::endl; + connection.close(); + return 1; + } +} diff --git a/pool/shard006/C++/0079362_altidset.cpp b/pool/shard006/C++/0079362_altidset.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1616d9cd9dd9432a0b8c394243aedf5a8e6ee642 --- /dev/null +++ b/pool/shard006/C++/0079362_altidset.cpp @@ -0,0 +1,288 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Source last modified: $Id: altidset.cpp,v 1.2 2005/03/10 20:59:16 bobclark Exp $ + * + * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. + * + * The contents of this file, and the files included with this file, + * are subject to the current version of the RealNetworks Public + * Source License (the "RPSL") available at + * http://www.helixcommunity.org/content/rpsl unless you have licensed + * the file under the current version of the RealNetworks Community + * Source License (the "RCSL") available at + * http://www.helixcommunity.org/content/rcsl, in which case the RCSL + * will apply. You may also obtain the license terms directly from + * RealNetworks. You may not use this file except in compliance with + * the RPSL or, if you have a valid RCSL with RealNetworks applicable + * to this file, the RCSL. Please see the applicable RPSL or RCSL for + * the rights, obligations and limitations governing use of the + * contents of the file. + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL") in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your version of + * this file only under the terms of the GPL, and not to allow others + * to use your version of this file under the terms of either the RPSL + * or RCSL, indicate your decision by deleting the provisions above + * and replace them with the notice and other provisions required by + * the GPL. 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 + * RPSL, the RCSL or the GPL. + * + * This file is part of the Helix DNA Technology. RealNetworks is the + * developer of the Original Code and owns the copyrights in the + * portions it created. + * + * This file, and the files included with this file, is distributed + * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY + * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS + * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET + * ENJOYMENT OR NON-INFRINGEMENT. + * + * Technology Compatibility Kit Test Suite(s) Location: + * http://www.helixcommunity.org/content/tck + * + * Contributor(s): + * + * ***** END LICENSE BLOCK ***** */ +#include "altidset.h" + +CHXAltIDSet::CHXAltIDSet() : + m_uCount(0), + m_pAltIDs(NULL) +{} + +CHXAltIDSet::~CHXAltIDSet() +{ + Clear(); +} + +HX_RESULT +CHXAltIDSet::AddID(UINT32 uAltID) +{ + HX_RESULT res = HXR_OUTOFMEMORY; + + // Create a bigger buffer for the new AltID + UINT32* pNew = new UINT32[m_uCount + 1]; + + if (pNew) + { + HXBOOL bAlreadyInSet = FALSE; + + // Copy existing info and check to see if uAltID is + // already in the set + for (UINT32 i = 0; !bAlreadyInSet && (i < m_uCount); i++) + { + if (uAltID == m_pAltIDs[i]) + { + bAlreadyInSet = TRUE; + } + else + { + pNew[i] = m_pAltIDs[i]; + } + } + + if (!bAlreadyInSet) + { + // Add new info + pNew[m_uCount] = uAltID; + + // destroy old info + delete [] m_pAltIDs; + + // update member variables + m_pAltIDs = pNew; + m_uCount++; + } + else + { + // We didn't need to insert the + // ID because it was already in + // the set + delete [] pNew; + pNew = NULL; + } + + res = HXR_OK; + } + + return res; +} + +HX_RESULT CHXAltIDSet::Copy(const CHXAltIDSet& rhs) +{ + HX_RESULT res = HXR_OK; + + if (&rhs != this) + { + Clear(); + m_uCount = rhs.m_uCount; + + if (m_uCount) + { + m_pAltIDs = new UINT32[m_uCount]; + + if (m_pAltIDs) + { + for (UINT32 i = 0; i < rhs.m_uCount; i++) + { + m_pAltIDs[i] = rhs.m_pAltIDs[i]; + } + + res = HXR_OK; + } + else + { + res = HXR_OUTOFMEMORY; + } + } + else + { + res = HXR_OK; + } + } + + return res; +} + +HX_RESULT +CHXAltIDSet::Union(const CHXAltIDSet& rhs) +{ + HX_RESULT res = HXR_OK; + UINT32 uCount = rhs.GetCount(); + + // Check to see if rhs is not empty + if (uCount) + { + // Get all the AltIDs from rhs and add them to this + // set. Note that AddID() checks for AltIDs that are + // already in the set + for (UINT32 i = 0; (HXR_OK == res) && (i < uCount); i++) + { + UINT32 uAltID; + + res = rhs.GetAltID(i, uAltID); + + if (HXR_OK == res) + { + res = AddID(uAltID); + } + } + } + + return res; +} + +HX_RESULT +CHXAltIDSet::Intersect(const CHXAltIDSet& rhs) +{ + HX_RESULT res = HXR_OK; + UINT32 uCount = rhs.GetCount(); + + if (uCount) + { + // Create a new set that contains the common + // AltIDs + CHXAltIDSet newSet; + + // Get all the AltIDs from rhs and see if they are + // in this set. If so add the AltID to newSet + for (UINT32 i = 0; (HXR_OK == res) && (i < uCount); i++) + { + UINT32 uAltID; + + res = rhs.GetAltID(i, uAltID); + + if ((HXR_OK == res) && HasAltID(uAltID)) + { + res = newSet.AddID(uAltID); + } + } + + if (HXR_OK == res) + { + // Copy the new set into this object + res = Copy(newSet); + } + } + + return res; +} + +void CHXAltIDSet::Clear() +{ + m_uCount = 0; + delete [] m_pAltIDs; + m_pAltIDs = NULL; +} + +UINT32 CHXAltIDSet::GetCount() const +{ + return m_uCount; +} + +HX_RESULT +CHXAltIDSet::GetAltID(UINT32 uIndex, UINT32& uAltID) const +{ + HX_RESULT res = HXR_INVALID_PARAMETER; + + if (uIndex < m_uCount) + { + uAltID = m_pAltIDs[uIndex]; + res = HXR_OK; + } + + return res; +} + +HXBOOL +CHXAltIDSet::HasAltID(UINT32 uAltID) const +{ + HXBOOL bRet = FALSE; + + // Scan through the AltIDs in this set to + // see if we can find a match + for (UINT32 i = 0; !bRet && (i < m_uCount); i++) + { + if (uAltID == m_pAltIDs[i]) + { + bRet = TRUE; + } + } + + return bRet; +} + +HXBOOL +CHXAltIDSet::IsSubset(const CHXAltIDSet& rhs) +{ + HXBOOL bRet = TRUE; + + if (rhs.GetCount()) + { + // Iterate over all the AltIDs in this set + for (UINT32 i = 0; bRet && (i < m_uCount); i++) + { + if (!rhs.HasAltID(m_pAltIDs[i])) + { + // We have found an AltID in this set + // that is not in the rhs set. That + // means that this set isn't + // a subset of rhs + bRet = FALSE; + } + } + } + else if (m_uCount) + { + // rhs is an empty set + // and this set AltIDs so this + // object isn't a subset of + // rhs + bRet = FALSE; + } + + return bRet; +} diff --git a/pool/shard006/C++/0079364_login_database_ios_unittest.cc b/pool/shard006/C++/0079364_login_database_ios_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..856cf9f28ff0ab61dbc02e3dcdb0d52cff4ea579 --- /dev/null +++ b/pool/shard006/C++/0079364_login_database_ios_unittest.cc @@ -0,0 +1,188 @@ +// 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 "components/password_manager/core/browser/login_database.h" + +#include +#include + +#include "base/files/scoped_temp_dir.h" +#include "base/ios/ios_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/macros.h" +#include "base/strings/utf_string_conversions.h" +#include "components/autofill/core/common/password_form.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" + +using base::ScopedCFTypeRef; +using autofill::PasswordForm; + +namespace password_manager { + +class LoginDatabaseIOSTest : public PlatformTest { + public: + void SetUp() override { + ClearKeychain(); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath login_db_path = + temp_dir_.path().AppendASCII("temp_login.db"); + login_db_.reset(new password_manager::LoginDatabase(login_db_path)); + login_db_->Init(); + } + + void TearDown() override { ClearKeychain(); } + + // Removes all passwords from the keychain. Since the unit test + // executable does not share the keychain with anything else on iOS, clearing + // the keychain will not affect any other applications. + void ClearKeychain(); + + // Returns the number of items in the keychain. + size_t GetKeychainSize(); + + protected: + base::ScopedTempDir temp_dir_; + std::unique_ptr login_db_; +}; + +void LoginDatabaseIOSTest::ClearKeychain() { + const void* queryKeys[] = {kSecClass}; + const void* queryValues[] = {kSecClassGenericPassword}; + ScopedCFTypeRef query(CFDictionaryCreate( + NULL, queryKeys, queryValues, arraysize(queryKeys), + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + OSStatus status = SecItemDelete(query); + // iOS7 returns an error of |errSecItemNotFound| if you try to clear an empty + // keychain. + ASSERT_TRUE(status == errSecSuccess || status == errSecItemNotFound); +} + +size_t LoginDatabaseIOSTest::GetKeychainSize() { + // Verify that the keychain now contains exactly one item. + ScopedCFTypeRef query( + CFDictionaryCreateMutable(NULL, 4, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); + CFDictionarySetValue(query, kSecClass, kSecClassGenericPassword); + CFDictionarySetValue(query, kSecReturnAttributes, kCFBooleanTrue); + CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll); + CFDictionarySetValue(query, kSecAttrAccessible, + kSecAttrAccessibleWhenUnlocked); + + CFTypeRef result; + OSStatus status = SecItemCopyMatching(query, &result); + if (status == errSecItemNotFound) + return 0; + + EXPECT_EQ(errSecSuccess, status); + size_t size = CFArrayGetCount((CFArrayRef)result); + CFRelease(result); + return size; +} + +TEST_F(LoginDatabaseIOSTest, KeychainStorage) { + base::string16 test_passwords[] = { + base::ASCIIToUTF16("foo"), base::ASCIIToUTF16("bar"), + base::WideToUTF16(L"\u043F\u0430\u0440\u043E\u043B\u044C"), + base::string16(), + }; + + for (unsigned int i = 0; i < arraysize(test_passwords); i++) { + std::string encrypted; + EXPECT_EQ(LoginDatabase::ENCRYPTION_RESULT_SUCCESS, + login_db_->EncryptedString(test_passwords[i], &encrypted)); + base::string16 decrypted; + EXPECT_EQ(LoginDatabase::ENCRYPTION_RESULT_SUCCESS, + login_db_->DecryptedString(encrypted, &decrypted)); + EXPECT_STREQ(UTF16ToUTF8(test_passwords[i]).c_str(), + UTF16ToUTF8(decrypted).c_str()); + } +} + +TEST_F(LoginDatabaseIOSTest, UpdateLogin) { + PasswordForm form; + form.origin = GURL("http://0.com"); + form.signon_realm = "http://www.example.com"; + form.action = GURL("http://www.example.com/action"); + form.password_element = base::ASCIIToUTF16("pwd"); + form.password_value = base::ASCIIToUTF16("example"); + + ignore_result(login_db_->AddLogin(form)); + + form.password_value = base::ASCIIToUTF16("secret"); + + password_manager::PasswordStoreChangeList changes = + login_db_->UpdateLogin(form); + ASSERT_EQ(1u, changes.size()); + + form.password_value = base::string16(); + + ScopedVector forms; + EXPECT_TRUE(login_db_->GetLogins(form, &forms)); + + ASSERT_EQ(1U, forms.size()); + EXPECT_STREQ("secret", UTF16ToUTF8(forms[0]->password_value).c_str()); + ASSERT_EQ(1U, GetKeychainSize()); +} + +TEST_F(LoginDatabaseIOSTest, RemoveLogin) { + PasswordForm form; + form.signon_realm = "www.example.com"; + form.action = GURL("www.example.com/action"); + form.password_element = base::ASCIIToUTF16("pwd"); + form.password_value = base::ASCIIToUTF16("example"); + + ignore_result(login_db_->AddLogin(form)); + + ignore_result(login_db_->RemoveLogin(form)); + + ScopedVector forms; + EXPECT_TRUE(login_db_->GetLogins(form, &forms)); + + ASSERT_EQ(0U, forms.size()); + ASSERT_EQ(0U, GetKeychainSize()); +} + +TEST_F(LoginDatabaseIOSTest, RemoveLoginsCreatedBetween) { + PasswordForm forms[3]; + forms[0].origin = GURL("http://0.com"); + forms[0].signon_realm = "http://www.example.com"; + forms[0].username_element = base::ASCIIToUTF16("login0"); + forms[0].date_created = base::Time::FromDoubleT(100); + forms[0].password_value = base::ASCIIToUTF16("pass0"); + + forms[1].origin = GURL("http://1.com"); + forms[1].signon_realm = "http://www.example.com"; + forms[1].username_element = base::ASCIIToUTF16("login1"); + forms[1].date_created = base::Time::FromDoubleT(200); + forms[1].password_value = base::ASCIIToUTF16("pass1"); + + forms[2].origin = GURL("http://2.com"); + forms[2].signon_realm = "http://www.example.com"; + forms[2].username_element = base::ASCIIToUTF16("login2"); + forms[2].date_created = base::Time::FromDoubleT(300); + forms[2].password_value = base::ASCIIToUTF16("pass2"); + + for (size_t i = 0; i < arraysize(forms); i++) { + ignore_result(login_db_->AddLogin(forms[i])); + } + + login_db_->RemoveLoginsCreatedBetween(base::Time::FromDoubleT(150), + base::Time::FromDoubleT(250)); + + PasswordForm form; + form.signon_realm = "http://www.example.com"; + ScopedVector logins; + EXPECT_TRUE(login_db_->GetLogins(form, &logins)); + + ASSERT_EQ(2U, logins.size()); + ASSERT_EQ(2U, GetKeychainSize()); + + EXPECT_STREQ("login0", UTF16ToUTF8(logins[0]->username_element).c_str()); + EXPECT_STREQ("pass0", UTF16ToUTF8(logins[0]->password_value).c_str()); + EXPECT_STREQ("login2", UTF16ToUTF8(logins[1]->username_element).c_str()); + EXPECT_STREQ("pass2", UTF16ToUTF8(logins[1]->password_value).c_str()); +} + +} // namespace password_manager diff --git a/pool/shard006/C++/0079365_DocumentClass.cpp b/pool/shard006/C++/0079365_DocumentClass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec4d619f615d1c203258a1054bb94c9e2ac896dd --- /dev/null +++ b/pool/shard006/C++/0079365_DocumentClass.cpp @@ -0,0 +1,137 @@ +#include + +#ifndef INCLUDED_DocumentClass +#include +#endif +#ifndef INCLUDED_Main +#include +#endif +#ifndef INCLUDED_openfl__legacy_Lib +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_DisplayObject +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_DisplayObjectContainer +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_IBitmapDrawable +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_InteractiveObject +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_MovieClip +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_Sprite +#include +#endif +#ifndef INCLUDED_openfl__legacy_display_Stage +#include +#endif +#ifndef INCLUDED_openfl__legacy_events_EventDispatcher +#include +#endif +#ifndef INCLUDED_openfl__legacy_events_IEventDispatcher +#include +#endif + +Void DocumentClass_obj::__construct() +{ +HX_STACK_FRAME("DocumentClass","new",0x4aeb0a6f,"DocumentClass.new","ApplicationMain.hx",217,0x0780ded5) +HX_STACK_THIS(this) +{ + HX_STACK_LINE(217) + super::__construct(); +} +; + return null(); +} + +//DocumentClass_obj::~DocumentClass_obj() { } + +Dynamic DocumentClass_obj::__CreateEmpty() { return new DocumentClass_obj; } +hx::ObjectPtr< DocumentClass_obj > DocumentClass_obj::__new() +{ hx::ObjectPtr< DocumentClass_obj > _result_ = new DocumentClass_obj(); + _result_->__construct(); + return _result_;} + +Dynamic DocumentClass_obj::__Create(hx::DynamicArray inArgs) +{ hx::ObjectPtr< DocumentClass_obj > _result_ = new DocumentClass_obj(); + _result_->__construct(); + return _result_;} + +::openfl::_legacy::display::Stage DocumentClass_obj::get_stage( ){ + HX_STACK_FRAME("DocumentClass","get_stage",0xea357664,"DocumentClass.get_stage","ApplicationMain.hx",286,0x0780ded5) + HX_STACK_THIS(this) + HX_STACK_LINE(286) + ::openfl::_legacy::display::MovieClip tmp = ::openfl::_legacy::Lib_obj::get_current(); HX_STACK_VAR(tmp,"tmp"); + HX_STACK_LINE(286) + ::openfl::_legacy::display::Stage tmp1 = tmp->get_stage(); HX_STACK_VAR(tmp1,"tmp1"); + HX_STACK_LINE(286) + return tmp1; +} + + + +DocumentClass_obj::DocumentClass_obj() +{ +} + +Dynamic DocumentClass_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) +{ + switch(inName.length) { + case 9: + if (HX_FIELD_EQ(inName,"get_stage") ) { return get_stage_dyn(); } + } + return super::__Field(inName,inCallProp); +} + +#if HXCPP_SCRIPTABLE +static hx::StorageInfo *sMemberStorageInfo = 0; +static hx::StaticInfo *sStaticStorageInfo = 0; +#endif + +static ::String sMemberFields[] = { + HX_HCSTRING("get_stage","\x15","\xc7","\xb4","\xc7"), + ::String(null()) }; + +static void sMarkStatics(HX_MARK_PARAMS) { + HX_MARK_MEMBER_NAME(DocumentClass_obj::__mClass,"__mClass"); +}; + +#ifdef HXCPP_VISIT_ALLOCS +static void sVisitStatics(HX_VISIT_PARAMS) { + HX_VISIT_MEMBER_NAME(DocumentClass_obj::__mClass,"__mClass"); +}; + +#endif + +hx::Class DocumentClass_obj::__mClass; + +void DocumentClass_obj::__register() +{ + hx::Static(__mClass) = new hx::Class_obj(); + __mClass->mName = HX_HCSTRING("DocumentClass","\xfd","\xa6","\x03","\x3e"); + __mClass->mSuper = &super::__SGetClass(); + __mClass->mConstructEmpty = &__CreateEmpty; + __mClass->mConstructArgs = &__Create; + __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; + __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; + __mClass->mMarkFunc = sMarkStatics; + __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); + __mClass->mMembers = hx::Class_obj::dupFunctions(sMemberFields); + __mClass->mCanCast = hx::TCanCast< DocumentClass_obj >; +#ifdef HXCPP_VISIT_ALLOCS + __mClass->mVisitFunc = sVisitStatics; +#endif +#ifdef HXCPP_SCRIPTABLE + __mClass->mMemberStorageInfo = sMemberStorageInfo; +#endif +#ifdef HXCPP_SCRIPTABLE + __mClass->mStaticStorageInfo = sStaticStorageInfo; +#endif + hx::RegisterClass(__mClass->mName, __mClass); +} + diff --git a/pool/shard006/C++/0079367_chunktrimmer_main.cc b/pool/shard006/C++/0079367_chunktrimmer_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..67e27df6ea7feebb1e13812573dc756aa907175d --- /dev/null +++ b/pool/shard006/C++/0079367_chunktrimmer_main.cc @@ -0,0 +1,247 @@ +//---------------------------------------------------------- -*- Mode: C++ -*- +// $Id: chunktrimmer_main.cc 403 2010-11-30 00:27:26Z sriramsrao $ +// +// Created 2008/06/11 +// +// +// Copyright 2008 Quantcast Corp. +// +// This file is part of Kosmos File System (KFS). +// +// 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. +// +// \brief This works only on Linux: Whenever chunks are moved to +// lost+found, it is likely because we had trouble reading data off +// disk. We'd like to leave the "bad" sectors pinned while freeing up +// the other readable sectors. This takes out the bad sectors from +// allocation while improving disk health. On Linux, we use XFS +// ioctl's to punch holes for all the readable data from a file, while +// leaving the regions that return EIO pinned on disk. +// +//---------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(KFS_OS_NAME_LINUX) && defined(KFS_USE_XFS) +#include +#endif + +using std::cout; +using std::endl; +using std::string; +using boost::scoped_array; + +static void trimFile(string &fn, off_t filesz, bool verbose); + +int main(int argc, char **argv) +{ + char optchar; + bool help = false; + string pathname = ""; + int res, count; + int ndaysOld = 5; + struct dirent **entries; + struct stat statBuf; + bool verbose = false; + + while ((optchar = getopt(argc, argv, "hvd:n:")) != -1) + { + switch (optchar) + { + case 'd': + pathname = optarg; + break; + case 'v': + verbose = true; + break; + case 'n': + ndaysOld = atoi(optarg); + break; + case 'h': + default: + help = true; + break; + } + } + + if ((help) || (pathname == "")) + { + cout << "Usage: " << argv[0] << " -d {-n } {-v} " << endl; + cout << "where, files older than n days are pruned" << endl; + exit(-1); + } + + time_t now = time(0); + + res = stat(pathname.c_str(), &statBuf); + if (res < 0) + { + cout << "Unable to open: " << pathname << endl; + exit(-1); + } + if (S_ISREG(statBuf.st_mode)) + { + if ((now - statBuf.st_mtime) < (ndaysOld * 24 * 60 * 60)) + { + cout << "Ignoring file: " << pathname << " since it is not old enough for pruning" << endl; + exit(0); + } + trimFile(pathname, statBuf.st_size, verbose); + exit(0); + } + + count = scandir(pathname.c_str(), &entries, 0, alphasort); + if (count < 0) + { + cout << "Unable to open: " << pathname << endl; + exit(-1); + } + + + for (int i = 0; i < count; i++) + { + string fn = pathname; + fn = fn + "/" + entries[i]->d_name; + res = stat(fn.c_str(), &statBuf); + free(entries[i]); + if ((res < 0) || (!S_ISREG(statBuf.st_mode)) || + (fn.rfind(".corrupt") != string::npos)) + { + // either it is not a file or it has been trimmed earlier + // and renamed to .corrupt + continue; + } + if ((now - statBuf.st_mtime) < (ndaysOld * 24 * 60 * 60)) + { + cout << "Ignoring file: " << fn << " since it is not old enough for pruning" << endl; + continue; + } + trimFile(fn, statBuf.st_size, verbose); + } + free(entries); + exit(0); +} + +#if defined(KFS_OS_NAME_LINUX) && defined(KFS_USE_XFS) + +static const int oneMB = 1 << 20; +static const int fourK = 4096; + +static int trimPart(int fd, off_t startP, off_t endP, int blkSz, int &numFreed, int &numKept); + +static void trimFile(string &fn, off_t filesz, bool verbose) +{ + int fd, res; + int numFreed = 0, numKept = 0; + + fd = open(fn.c_str(), O_RDWR | O_DIRECT); + // fd = open(fn.c_str(), O_RDONLY | O_DIRECT); + if (fd < 0) + { + cout << "Unable to open: " << fn << endl; + return; + } + bool shouldPreserveFile = false; + off_t filePos = 0; + int dummy; + while (1) + { + // remember the filePos, since on a successful read it will be updated + filePos = lseek(fd, 0, SEEK_CUR); + // read in big chunks; if any fail, we will switch down to + // reading in 4k and pinning only the unreadable 4k blocks + res = trimPart(fd, filePos, filePos + oneMB, oneMB, numFreed, dummy); + if ((res == 0) || (filePos > filesz)) + { + // hit EOF + break; + } + if (res < 0) + { + filePos = lseek(fd, filePos, SEEK_SET); + shouldPreserveFile = true; + trimPart(fd, filePos, filePos + oneMB, fourK, numFreed, numKept); + } + } + close(fd); + if (shouldPreserveFile) + { + string corruptFn = fn + ".corrupt"; + rename(fn.c_str(), corruptFn.c_str()); + cout << "Renamed: " << fn << " -> " << corruptFn << endl; + cout << "Filesize: " << filePos << endl; + cout << "Num 4k-blocks kept: " << numKept << endl; + cout << "Num 4k-blocks freed: " << numFreed << endl; + } + else + { + cout << "Non-corrupt file: " << fn << " ; so nuking" << endl; + unlink(fn.c_str()); + } +} + +static int +trimPart(int fd, off_t startP, off_t endP, int blkSz, int &numFreed, int &numKept) +{ + static char *data = NULL; + xfs_flock64_t theFree = {0}; + off_t currP = startP; + int retval = 1, res; + + if (data == NULL) + { + data = (char *) memalign(fourK, oneMB * sizeof(char)); + } + while (currP < endP) + { + if (currP >= endP) + break; + res = read(fd, data, blkSz); + if (res == 0) + return (retval == -1 ? -1 : 0); + if (res < 0) + { + // we couldn't read a block; so, reset the position and skip over the block + // we failed to read + currP = lseek(fd, currP + blkSz, SEEK_SET); + cout << "Couldn't read block at: " << currP - blkSz << " of len = " << blkSz << endl; + numKept += (blkSz / 4096); + // file needs to be preserved + retval = -1; + continue; + } + // got data, so free the block and punch a hole in the file + theFree.l_whence = 0; + theFree.l_start = currP; + theFree.l_len = res; + xfsctl(0, fd, XFS_IOC_UNRESVSP64, &theFree); + numFreed += (res / 4096); + currP += res; + } + return retval; +} + +#else +static void trimFile(string &fn, off_t filesz, bool verbose) +{ + +} +#endif diff --git a/pool/shard006/C++/0079373_ConvexHullStructures.cpp b/pool/shard006/C++/0079373_ConvexHullStructures.cpp new file mode 100644 index 0000000000000000000000000000000000000000..505bea2e08073dfe0731af24f4d96a6258d1adfd --- /dev/null +++ b/pool/shard006/C++/0079373_ConvexHullStructures.cpp @@ -0,0 +1,239 @@ +/* + * ConvexHullStructures.cpp + * + * Created on: Nov 10, 2011 + * Author: Martin Uhrin + */ + +#include "spl/analysis/ConvexHullStructures.h" + +#ifdef SPL_USE_CGAL + +#define DEBUG_CONVEX_HULL_STRUCTURES + +# include + +#include "spl/utility/TransformFunctions.h" + +namespace spl { +namespace analysis { +namespace detail { + +class StableStructuresIterator : public ::boost::iterator_facade< + StableStructuresIterator, const common::Structure *, + ::boost::forward_traversal_tag, const common::Structure *> +{ +public: + StableStructuresIterator() : + myHullStructures(NULL) + { + } + + explicit + StableStructuresIterator(const ConvexHullStructures * hullStructures) : + myHullStructures(hullStructures) + { + myIt = myHullStructures->structuresBegin(); + goToFirstStable(); + } + +private: + + const common::Structure * + dereference() const + { + return *myIt; + } + + void + increment() + { + ++myIt; + goToFirstStable(); + } + + bool + equal(const StableStructuresIterator & other) const + { + if(isAtEnd() && other.isAtEnd()) + return true; + + return myIt == other.myIt; + } + + void + goToFirstStable() + { + // Find the next stable structure + for(; myIt != myHullStructures->structuresEnd(); ++myIt) + { + if(myHullStructures->getStability(**myIt) + == ConvexHullStructures::Stability::STABLE) + break; + } + } + + bool + isAtEnd() const + { + // If we don't have hull structures then we're an end iterator, + // oterwise check if we're at the end of the hull structures + return + myHullStructures == NULL ? + true : myIt == myHullStructures->structuresEnd(); + } + + const ConvexHullStructures * myHullStructures; + ConvexHullStructures::StructuresIterator myIt; + + friend class boost::iterator_core_access; +}; + +} // namespace detail + +ConvexHullStructures::ConvexHullStructures(const EndpointLabels & endpoints) : + myConvexHull(endpoints) +{ +} + +ConvexHullStructures::ConvexHullStructures(const EndpointLabels & endpoints, + utility::Key< double> & convexProperty) : + myConvexHull(endpoints, convexProperty) +{ +} + +ConvexHullStructures::StructuresIterator +ConvexHullStructures::insert(common::Structure * structure) +{ + const ConvexHull::PointId id = myConvexHull.addStructure(*structure); + if(id == -1) + return structuresEnd(); + + return StructuresIterator( + myStructures.insert(::std::make_pair(structure, id)).first); +} + +ConvexHullStructures::StructuresIterator +ConvexHullStructures::structuresBegin() const +{ + return StructuresIterator(myStructures.begin()); +} + +ConvexHullStructures::StructuresIterator +ConvexHullStructures::structuresEnd() const +{ + return StructuresIterator(myStructures.end()); +} + +size_t +ConvexHullStructures::numStable() const +{ + return ::std::distance(stableStructuresBegin(), stableStructuresEnd()); +} + +ConvexHullStructures::StableStructuresIterator +ConvexHullStructures::stableStructuresBegin() const +{ + return detail::StableStructuresIterator(this); +} + +ConvexHullStructures::StableStructuresIterator +ConvexHullStructures::stableStructuresEnd() const +{ + return StableStructuresIterator(); +} + +const ConvexHull & +ConvexHullStructures::getHull() const +{ + return myConvexHull; +} + +ConvexHullStructures::Stability::Value +ConvexHullStructures::getStability(const common::Structure & structure) const +{ + const Structures::const_iterator it = myStructures.find( + const_cast< common::Structure *>(&structure)); + SSLIB_ASSERT(it != myStructures.end()); + + if(it->second == -1) + return Stability::NOT_HULL_STRUCTURE; + else if(*myConvexHull.isStable(it->second)) + return Stability::STABLE; + else + return Stability::UNSTABLE; +} + +double +ConvexHullStructures::getFormationEnthalpy( + const StructuresIterator structure) const +{ + return getFormationEnthalpy(structure.base()->second); +} + +void +ConvexHullStructures::populateFormationEnthalpies() +{ + BOOST_FOREACH(Structures::reference s, myStructures) + { + s.first->properties()[common::structure_properties::general::FORMATION_ENTHALPY] = + getFormationEnthalpy(s.second); + } +} + +void +ConvexHullStructures::populateHullDistances() +{ + OptionalDouble dist; + BOOST_FOREACH(Structures::reference s, myStructures) + { + dist = myConvexHull.distanceToHull(s.second); + if(dist) + s.first->properties()[common::structure_properties::general::HULL_DISTANCE] = + *dist; + } +} + +OptionalDouble +ConvexHullStructures::distanceToHull(const common::Structure & structure) const +{ + const Structures::const_iterator it = myStructures.find( + const_cast< common::Structure *>(&structure)); + if(it == myStructures.end()) + return myConvexHull.distanceToHull(structure); + else + return myConvexHull.distanceToHull(it->second); // It's faster to calculate if we know the id +} + +::std::string +ConvexHullStructures::getLabel(const ConvexHull & convexHull, + const ConvexHull::PointId pointId) const +{ + typedef utility::TakeSecond< const Structures::value_type> TakeSecond; + typedef ::boost::transform_iterator< TakeSecond, Structures::const_iterator> IdsIterator; + + static const TakeSecond TAKE_SECOND = TakeSecond(); + + SSLIB_ASSERT(&convexHull == &myConvexHull); + + const IdsIterator it = ::std::find( + IdsIterator(myStructures.begin(), TAKE_SECOND), + IdsIterator(myStructures.end(), TAKE_SECOND), pointId); + + if(it.base() == myStructures.end()) + return ::std::string(); + + return it.base()->first->getComposition().toString(); +} + +double +ConvexHullStructures::getFormationEnthalpy(const ConvexHull::PointId id) const +{ + return CGAL::to_double( + (*myConvexHull.getEntry(id).getPoint())[myConvexHull.dims() - 1]); +} + +} +} + +#endif // SPL_USE_CGAL diff --git a/pool/shard006/C++/0079375_events_default.cc b/pool/shard006/C++/0079375_events_default.cc new file mode 100644 index 0000000000000000000000000000000000000000..7d55e8e790f8146be62ce2d8930fe9b43e165896 --- /dev/null +++ b/pool/shard006/C++/0079375_events_default.cc @@ -0,0 +1,173 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/events/event.h" +#include "ui/events/event_constants.h" +#include "ui/events/event_utils.h" + +namespace ui { + +void UpdateDeviceList() { NOTIMPLEMENTED(); } + +base::TimeDelta EventTimeFromNative(const base::NativeEvent& native_event) { + const ui::Event* event = static_cast(native_event); + return event->time_stamp(); +} + +int EventFlagsFromNative(const base::NativeEvent& native_event) { + const ui::Event* event = static_cast(native_event); + return event->flags(); +} + +EventType EventTypeFromNative(const base::NativeEvent& native_event) { + const ui::Event* event = static_cast(native_event); + return event->type(); +} + +gfx::Point EventSystemLocationFromNative( + const base::NativeEvent& native_event) { + const ui::LocatedEvent* e = + static_cast(native_event); + DCHECK(e->IsMouseEvent() || e->IsTouchEvent() || e->IsGestureEvent() || + e->IsScrollEvent()); + return e->location(); +} + +gfx::Point EventLocationFromNative(const base::NativeEvent& native_event) { + return EventSystemLocationFromNative(native_event); +} + +int GetChangedMouseButtonFlagsFromNative( + const base::NativeEvent& native_event) { + const ui::MouseEvent* event = + static_cast(native_event); + DCHECK(event->IsMouseEvent() || event->IsScrollEvent()); + return event->changed_button_flags(); +} + +PointerDetails GetMousePointerDetailsFromNative( + const base::NativeEvent& native_event) { + const ui::MouseEvent* event = + static_cast(native_event); + DCHECK(event->IsMouseEvent() || event->IsScrollEvent()); + return event->pointer_details(); +} + +KeyboardCode KeyboardCodeFromNative(const base::NativeEvent& native_event) { + const ui::KeyEvent* event = static_cast(native_event); + DCHECK(event->IsKeyEvent()); + return event->key_code(); +} + +DomCode CodeFromNative(const base::NativeEvent& native_event) { + const ui::KeyEvent* event = static_cast(native_event); + DCHECK(event->IsKeyEvent()); + return event->code(); +} + +bool IsCharFromNative(const base::NativeEvent& native_event) { + const ui::KeyEvent* event = static_cast(native_event); + DCHECK(event->IsKeyEvent()); + return event->is_char(); +} + +gfx::Vector2d GetMouseWheelOffset(const base::NativeEvent& native_event) { + const ui::MouseWheelEvent* event = + static_cast(native_event); + DCHECK(event->type() == ET_MOUSEWHEEL); + return event->offset(); +} + +base::NativeEvent CopyNativeEvent(const base::NativeEvent& event) { + return NULL; +} + +void ReleaseCopiedNativeEvent(const base::NativeEvent& event) { +} + +void ClearTouchIdIfReleased(const base::NativeEvent& xev) { +} + +int GetTouchId(const base::NativeEvent& native_event) { + const ui::TouchEvent* event = + static_cast(native_event); + DCHECK(event->IsTouchEvent()); + return event->touch_id(); +} + +float GetTouchRadiusX(const base::NativeEvent& native_event) { + const ui::TouchEvent* event = + static_cast(native_event); + DCHECK(event->IsTouchEvent()); + return event->pointer_details().radius_x(); +} + +float GetTouchRadiusY(const base::NativeEvent& native_event) { + const ui::TouchEvent* event = + static_cast(native_event); + DCHECK(event->IsTouchEvent()); + return event->pointer_details().radius_y(); +} + +float GetTouchAngle(const base::NativeEvent& native_event) { + const ui::TouchEvent* event = + static_cast(native_event); + DCHECK(event->IsTouchEvent()); + return event->rotation_angle(); +} + +float GetTouchForce(const base::NativeEvent& native_event) { + const ui::TouchEvent* event = + static_cast(native_event); + DCHECK(event->IsTouchEvent()); + return event->pointer_details().force(); +} + +bool GetScrollOffsets(const base::NativeEvent& native_event, + float* x_offset, + float* y_offset, + float* x_offset_ordinal, + float* y_offset_ordinal, + int* finger_count) { + const ui::ScrollEvent* event = + static_cast(native_event); + DCHECK(event->IsScrollEvent()); + if (x_offset) + *x_offset = event->x_offset(); + if (y_offset) + *y_offset = event->y_offset(); + if (x_offset_ordinal) + *x_offset_ordinal = event->x_offset_ordinal(); + if (y_offset_ordinal) + *y_offset_ordinal = event->y_offset_ordinal(); + if (finger_count) + *finger_count = event->finger_count(); + + return true; +} + +bool GetFlingData(const base::NativeEvent& native_event, + float* vx, + float* vy, + float* vx_ordinal, + float* vy_ordinal, + bool* is_cancel) { + const ui::ScrollEvent* event = + static_cast(native_event); + DCHECK(event->IsScrollEvent()); + if (vx) + *vx = event->x_offset(); + if (vy) + *vy = event->y_offset(); + if (vx_ordinal) + *vx_ordinal = event->x_offset_ordinal(); + if (vy_ordinal) + *vy_ordinal = event->y_offset_ordinal(); + if (is_cancel) + *is_cancel = event->type() == ET_SCROLL_FLING_CANCEL; + + return true; +} + +} // namespace ui diff --git a/pool/shard006/C++/0079377_target_injector_example.cpp b/pool/shard006/C++/0079377_target_injector_example.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b63bd9bdd6ab2e11d171437d2645d71c55cd811b --- /dev/null +++ b/pool/shard006/C++/0079377_target_injector_example.cpp @@ -0,0 +1,192 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using std::shared_ptr; +using namespace flitr; +using namespace std; + +class BackgroundTriggerThread : public FThread { +public: + BackgroundTriggerThread(ImageProducer* p) : + Producer_(p), + ShouldExit_(false) {} + + void run() + { + while(!ShouldExit_) + { + if (!Producer_->trigger()) FThread::microSleep(5000); + } + } + + void setExit() { ShouldExit_ = true; } + +private: + ImageProducer* Producer_; + bool ShouldExit_; +}; + +//#define USE_BACKGROUND_TRIGGER_THREAD 1 + +class KeyPressedHandler : public osgGA::GUIEventHandler +{ + public: + + KeyPressedHandler(shared_ptr osgc) : osgc_(osgc), count_(0) {} + ~KeyPressedHandler() {} + + bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) + { + osgViewer::Viewer* viewer = dynamic_cast(&aa); + if (!viewer) return false; + + switch(ea.getEventType()) + { + case(osgGA::GUIEventAdapter::KEYUP): + { + if (ea.getKey()=='c') + { + osg::Image *theImage; + theImage = osgc_->getOSGImage(0, 0); + theImage->flipHorizontal(); + theImage->flipVertical(); + std::string s = "frame_cap_" + std::to_string(count_) + ".png"; + osgDB::writeImageFile(*theImage, s); + count_++; + } + } + default: + return false; + } + + return true; + } + + shared_ptr osgc_; + int count_; +}; + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + std::cout << "Usage: " << argv[0] << " video_file\n"; + return 1; + } + + shared_ptr ffp(new FFmpegProducer(argv[1], ImageFormat::FLITR_PIX_FMT_Y_8)); + if (!ffp->init()) { + std::cerr << "Could not load " << argv[1] << "\n"; + exit(-1); + } + +#ifdef USE_BACKGROUND_TRIGGER_THREAD + shared_ptr btt(new BackgroundTriggerThread(ffp.get())); + btt->startThread(); +#endif + + shared_ptr targetInjector(new TargetInjector(*ffp, 1)); + if (!targetInjector->init()) { + std::cerr << "Could not initialise the target injector.\n"; + exit(-1); + } + + targetInjector->setTargetBrightness(255.0f); + + targetInjector->addTarget(TargetInjector::SyntheticTarget(targetInjector->getDownstreamFormat(0).getWidth()*0.5f-targetInjector->getDownstreamFormat(0).getHeight()*0.5f, 0.5f, + 1.0f, 1.0f, 0.1f, + 0.8f, 0.4f, + 0.0f, 0.0f)); + + targetInjector->startTriggerThread(); + + + shared_ptr osgc(new MultiOSGConsumer(*targetInjector,1)); + if (!osgc->init()) { + std::cerr << "Could not init OSG consumer\n"; + exit(-1); + } + + shared_ptr mffc(new MultiFFmpegConsumer(*targetInjector,1)); + if (!mffc->init()) { + std::cerr << "Could not init FFmpeg consumer\n"; + exit(-1); + } + std::stringstream filenameStringStream; + filenameStringStream << argv[1] << "_ti"; + mffc->openFiles(filenameStringStream.str()); + mffc->startWriting(); + + osg::Group *root_node = new osg::Group; + + shared_ptr quad(new TexturedQuad(osgc->getOutputTexture())); + root_node->addChild(quad->getRoot().get()); + + osgViewer::Viewer viewer; + viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); + viewer.addEventHandler(new osgViewer::StatsHandler); + viewer.setSceneData(root_node); + + // add the pick handler + viewer.addEventHandler(new KeyPressedHandler(osgc)); + + //viewer.setUpViewInWindow(480+40, 40, 640, 480); + viewer.realize(); + + const int use_trackball = 0; + if (use_trackball) { + osgGA::TrackballManipulator* tb = new osgGA::TrackballManipulator; + viewer.setCameraManipulator(tb); + adjustCameraManipulatorHomeForYUp(tb); + } else { + + ImageFormat imf = ffp->getFormat(); + OrthoTextureManipulator* om = new OrthoTextureManipulator(imf.getWidth(), imf.getHeight()); + viewer.setCameraManipulator(om); + } + + while((!viewer.done())&&(ffp->getCurrentImage()<(ffp->getNumImages()*0.9f))) { +#ifndef USE_BACKGROUND_TRIGGER_THREAD + //Read from the video, but don't get more than 10 frames ahead. + if (ffp->getLeastNumReadSlotsAvailable()<10) + { + ffp->trigger(); + } +#endif + + if (!(targetInjector->isTriggerThreadStarted())) + { + targetInjector->trigger(); + } + + if (osgc->getNext()) { + viewer.frame(); + } + } + + mffc->stopWriting(); + mffc->closeFiles(); + +#ifdef USE_BACKGROUND_TRIGGER_THREAD + btt->setExit(); + btt->join(); +#endif + + return 0; +} diff --git a/pool/shard006/C++/0079380_RecordView.cpp b/pool/shard006/C++/0079380_RecordView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d722d911d3d41a0c05076feb94a48bf9922806b9 --- /dev/null +++ b/pool/shard006/C++/0079380_RecordView.cpp @@ -0,0 +1,120 @@ +/* + The GTKWorkbook Project + Copyright (C) 2008, 2009 John Bellone, Jr. + + 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 PRACTICAL 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 library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA +*/ +#include "RecordView.hpp" +#include +#include +#include + +static guint +DeleteEventCallback (GtkWindow * window, GdkEvent * event, gpointer data) { + RecordView * view = (RecordView *) data; + + // The RecordView object needs to be deleted. At this point we are destroying the + // window object inside of GTK. We can use the delete_event as a closure invocation. + delete view; + + return FALSE; +} + +RecordView::RecordView (Application * appstate) { + this->appstate = appstate; + this->gtk_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + this->gtk_vbox = gtk_vbox_new (FALSE, 0); + this->wb = workbook_open (this->gtk_window, "recordview"); + + gtk_window_set_title (GTK_WINDOW (this->gtk_window), "Record View"); + gtk_window_set_destroy_with_parent (GTK_WINDOW (this->gtk_window), TRUE); + gtk_window_set_default_size (GTK_WINDOW (this->gtk_window), 400, 600); + + gtk_box_pack_start (GTK_BOX (this->gtk_vbox), this->wb->gtk_notebook, TRUE, TRUE, 0); + + gtk_container_add (GTK_CONTAINER (this->gtk_window), this->gtk_vbox); + + // Take care of the object once we close the dialog. + g_signal_connect (G_OBJECT (this->gtk_window), "delete_event", + G_CALLBACK (DeleteEventCallback), this); +} + +RecordView::~RecordView (void) { + this->wb->destroy (this->wb); + gtk_widget_destroy (this->gtk_window); +} + +void +RecordView::AddSheetRecord (Sheet * sheet) { + ASSERT (sheet != NULL); + GtkSheet * gtksheet = GTK_SHEET (sheet->gtk_sheet); + GtkSheetRange range = {gtksheet->range.row0, 0, gtksheet->range.rowi, 0}; + Row * tuple = row_new (gtksheet->maxcol + 1); + gint sheet_rows = 1; + + // More than one row is selected; we must transpose them all into the RV sheet. + if (range.row0 != range.rowi) { + sheet_rows = range.rowi - range.row0 + 1; + } + + Sheet * record_sheet = this->wb->add_new_sheet (this->wb,sheet->name,gtksheet->maxcol + 1,sheet_rows); + int column = 0, row = 0; + + do { + sheet->get_row (sheet, range.row0, tuple->cells, tuple->size); + + // Change the titles of the columns to the row titles. This is only going to work if the + // row titles have been explicitly set somewhere inside of the plugin. + record_sheet->set_column_title (record_sheet, + row, + sheet->row_titles->cells[range.row0]->value->str); + + for (int ii = 0; ii < tuple->size; ii++) { + // We only need to change the row titles once. This can happen on our last iteration. + if (range.row0 == range.rowi) { + record_sheet->set_row_title (record_sheet, + ii, + sheet->column_titles->cells[ii]->value->str); + + } + + record_sheet->set_cell (record_sheet, + ii, + column, + tuple->cells[ii]->value->str); + + if (sheet->cells[range.row0][ii]->attributes.highlighted == TRUE) { + record_sheet->set_cell_background (record_sheet, ii, column, "#ffffcc"); + } + else if (((ii + 1) % 2) == 0) { + record_sheet->set_cell_background (record_sheet, ii, column, "#f9f7f9"); + } + } + + range.row0++; column++; row++; + } while (range.row0 <= range.rowi); + + tuple->destroy (tuple); +} + +GtkWidget * +RecordView::window (void) const { + return this->gtk_window; +} + +Application * +RecordView::app (void) const { + return this->appstate; +} diff --git a/pool/shard006/C++/0079381_Player.cpp b/pool/shard006/C++/0079381_Player.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07cc49e81afa7e529f73f3b98215c07411903773 --- /dev/null +++ b/pool/shard006/C++/0079381_Player.cpp @@ -0,0 +1,106 @@ +// Cyphesis Online RPG Server and AI Engine +// Copyright (C) 2000,2001 Alistair Riddoch +// +// 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 + +// $Id$ + +#include "Player.h" + +#include +#include + +#include "common/compose.hpp" + +std::set Player::playableTypes; + +using Atlas::Message::Element; +using Atlas::Message::MapType; +using Atlas::Message::ListType; +using Atlas::Objects::Root; +using Atlas::Objects::Entity::RootEntity; + +/// \brief Constructor +/// +/// @param conn the Connection this account is being created by. +/// @param username a string giving the username. +/// @param passwd a string giving the password. +/// @param id a string giving the identifier of the account. +/// @param intId an integer giving the identifier of the account. +Player::Player(Connection * conn, + const std::string & username, + const std::string & passwd, + const std::string & id, + long intId) : + Account(conn, username, passwd, id, intId) +{ +} + +Player::~Player() +{ +} + +const char * Player::getType() const +{ + return "player"; +} + +void Player::addToMessage(MapType & omap) const +{ + Account::addToMessage(omap); + ListType & typeList = (omap["character_types"] = ListType()).asList(); + std::set::const_iterator I = Player::playableTypes.begin(); + std::set::const_iterator Iend = Player::playableTypes.end(); + for (; I != Iend; ++I) { + typeList.push_back(Element(*I)); + } +} + +void Player::addToEntity(const Atlas::Objects::Entity::RootEntity & ent) const +{ + Account::addToEntity(ent); + ListType typeList; + std::set::const_iterator I = Player::playableTypes.begin(); + std::set::const_iterator Iend = Player::playableTypes.end(); + for (; I != Iend; ++I) { + typeList.push_back(Element(*I)); + } + ent->setAttr("character_types", typeList); +} + +int Player::characterError(const Operation & op, + const Root & ent, OpVector & res) const +{ + if (ent->isDefaultName()) { + error(op, "Entity to be created has no name", res, getId()); + return -1; + } + const std::string & name = ent->getName(); + if (name.compare(0,5,"admin") == 0) { + error(op, "Entity to be created cannot start with admin", res, getId()); + return -1; + } + + // Parents must have been checked already before calling this method + const std::string & type = ent->getParents().front(); + if (Player::playableTypes.find(type) == Player::playableTypes.end()) { + error(op, + String::compose("You cannot create a character of type \"%1\".", + type), + res, getId()); + return -1; + } + return 0; +} diff --git a/pool/shard006/C++/0079406_PublishRequest.cpp b/pool/shard006/C++/0079406_PublishRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3799af394feb0d11a3ab828cb21f7ead1a7f301d --- /dev/null +++ b/pool/shard006/C++/0079406_PublishRequest.cpp @@ -0,0 +1,82 @@ +/* +* Copyright 2010-2016 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::SNS::Model; +using namespace Aws::Utils; + +PublishRequest::PublishRequest() : + m_topicArnHasBeenSet(false), + m_targetArnHasBeenSet(false), + m_phoneNumberHasBeenSet(false), + m_messageHasBeenSet(false), + m_subjectHasBeenSet(false), + m_messageStructureHasBeenSet(false), + m_messageAttributesHasBeenSet(false) +{ +} + +Aws::String PublishRequest::SerializePayload() const +{ + Aws::StringStream ss; + ss << "Action=Publish&"; + if(m_topicArnHasBeenSet) + { + ss << "TopicArn=" << StringUtils::URLEncode(m_topicArn.c_str()) << "&"; + } + + if(m_targetArnHasBeenSet) + { + ss << "TargetArn=" << StringUtils::URLEncode(m_targetArn.c_str()) << "&"; + } + + if(m_phoneNumberHasBeenSet) + { + ss << "PhoneNumber=" << StringUtils::URLEncode(m_phoneNumber.c_str()) << "&"; + } + + if(m_messageHasBeenSet) + { + ss << "Message=" << StringUtils::URLEncode(m_message.c_str()) << "&"; + } + + if(m_subjectHasBeenSet) + { + ss << "Subject=" << StringUtils::URLEncode(m_subject.c_str()) << "&"; + } + + if(m_messageStructureHasBeenSet) + { + ss << "MessageStructure=" << StringUtils::URLEncode(m_messageStructure.c_str()) << "&"; + } + + if(m_messageAttributesHasBeenSet) + { + unsigned messageAttributesCount = 1; + for(auto& item : m_messageAttributes) + { + ss << "MessageAttributes.entry." << messageAttributesCount << ".Name=" + << StringUtils::URLEncode(item.first.c_str()) << "&"; + item.second.OutputToStream(ss, "MessageAttributes.entry.", messageAttributesCount, ".Value"); + messageAttributesCount++; + } + } + + ss << "Version=2010-03-31"; + return ss.str(); +} + diff --git a/pool/shard006/C++/0079407_pepper_flash_font_file_host.cc b/pool/shard006/C++/0079407_pepper_flash_font_file_host.cc new file mode 100644 index 0000000000000000000000000000000000000000..39537fc75d9892b70660f57571d845aab72fc6c6 --- /dev/null +++ b/pool/shard006/C++/0079407_pepper_flash_font_file_host.cc @@ -0,0 +1,75 @@ +// 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/renderer/pepper/pepper_flash_font_file_host.h" + +#include "build/build_config.h" +#include "content/public/renderer/renderer_ppapi_host.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/host/dispatch_host_message.h" +#include "ppapi/host/host_message_context.h" +#include "ppapi/host/ppapi_host.h" +#include "ppapi/proxy/ppapi_messages.h" +#include "ppapi/proxy/serialized_structs.h" + +#if defined(OS_LINUX) || defined(OS_OPENBSD) +#include "content/public/common/child_process_sandbox_support_linux.h" +#endif + +PepperFlashFontFileHost::PepperFlashFontFileHost( + content::RendererPpapiHost* host, + PP_Instance instance, + PP_Resource resource, + const ppapi::proxy::SerializedFontDescription& description, + PP_PrivateFontCharset charset) + : ResourceHost(host->GetPpapiHost(), instance, resource), + renderer_ppapi_host_(host) { +#if defined(OS_LINUX) || defined(OS_OPENBSD) + fd_.reset(content::MatchFontWithFallback( + description.face.c_str(), + description.weight >= PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD, + description.italic, + charset, + PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT)); +#endif // defined(OS_LINUX) || defined(OS_OPENBSD) +} + +PepperFlashFontFileHost::~PepperFlashFontFileHost() {} + +int32_t PepperFlashFontFileHost::OnResourceMessageReceived( + const IPC::Message& msg, + ppapi::host::HostMessageContext* context) { + PPAPI_BEGIN_MESSAGE_MAP(PepperFlashFontFileHost, msg) + PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFontFile_GetFontTable, + OnGetFontTable) + PPAPI_END_MESSAGE_MAP() + return PP_ERROR_FAILED; +} + +int32_t PepperFlashFontFileHost::OnGetFontTable( + ppapi::host::HostMessageContext* context, + uint32_t table) { + std::string contents; + int32_t result = PP_ERROR_FAILED; +#if defined(OS_LINUX) || defined(OS_OPENBSD) + int fd = fd_.get(); + if (fd != -1) { + size_t length = 0; + if (content::GetFontTable(fd, table, 0 /* offset */, NULL, &length)) { + contents.resize(length); + uint8_t* contents_ptr = + reinterpret_cast(const_cast(contents.c_str())); + if (content::GetFontTable( + fd, table, 0 /* offset */, contents_ptr, &length)) { + result = PP_OK; + } else { + contents.clear(); + } + } + } +#endif // defined(OS_LINUX) || defined(OS_OPENBSD) + + context->reply_msg = PpapiPluginMsg_FlashFontFile_GetFontTableReply(contents); + return result; +} diff --git a/pool/shard006/C++/0079415_Lua.cpp b/pool/shard006/C++/0079415_Lua.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f635f877e4149a3b18560633e936da9834ed2194 --- /dev/null +++ b/pool/shard006/C++/0079415_Lua.cpp @@ -0,0 +1,94 @@ +extern "C" +{ + #include + #include + #include +}; + +#include +#include +#include +#include + +lua_State* l = NULL; + +bool LuaInit() +{ + n_assert(!l); + l = luaL_newstate(); + //luaL_openlibs(l); + return !!l; +} + +void LuaRelease() +{ + if (l) + { + lua_close(l); + l = NULL; + } +} + +// Saves Lua data to stream +static int SaveLua(lua_State* L, const void* p, size_t sz, void* ud) +{ + n_assert(ud); + Data::CStream* pOut = (Data::CStream*)ud; + return (pOut->Write(p, sz) == sz) ? 0 : 1; +} + +bool LuaCompile(char* pData, uint Size, LPCSTR Name, LPCSTR pFileOut) +{ + if (!l) LuaInit(); + + if (luaL_loadbuffer(l, pData, Size, Name) != 0) + { + n_printf("Error parsing Lua file '%s': %s\n", Name, lua_tostring(l, -1)); + lua_pop(l, 1); // Error msg + FAIL; + } + + int Result = 1; + + Data::CFileStream Out; + if (Out.Open(pFileOut, Data::SAM_WRITE, Data::SAP_SEQUENTIAL)) + { + Result = lua_dump(l, SaveLua, (Data::CStream*)&Out); + Out.Close(); + } + + return !Result; +} + +bool LuaCompileClass(Data::CParams& LoadedHRD, LPCSTR Name, LPCSTR pFileOut) +{ + nString Code = LoadedHRD.Get(CStrID("Code"), NULL); + + if (Code.IsValid()) + { + if (luaL_loadbuffer(l, Code.Get(), Code.Length(), Name) != 0) + { + n_printf("Error parsing Lua file '%s': %s\n", Name, lua_tostring(l, -1)); + lua_pop(l, 1); // Error msg + FAIL; + } + + int Result = 1; + + Data::CMemStream Out; + if (Out.Open(Data::SAM_WRITE, Data::SAP_SEQUENTIAL)) + { + Result = lua_dump(l, SaveLua, (Data::CStream*)&Out); + Data::CBuffer Buffer(Out.GetPtr(), Out.GetSize()); + Out.Close(); + if (Result != 0) FAIL; + + LoadedHRD.Set(CStrID("Code"), Buffer); + } + else FAIL; + } + + DataSrv->SavePRM(pFileOut, &LoadedHRD); + + OK; +} \ No newline at end of file diff --git a/pool/shard006/C++/0079423_airTouch.cpp b/pool/shard006/C++/0079423_airTouch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0cfbfecb1c90b1eb3ce652f4727d88fae23cf18 --- /dev/null +++ b/pool/shard006/C++/0079423_airTouch.cpp @@ -0,0 +1,188 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "fflog.h" +#include + +#define CURSOR_SET_DATA 0x5810 +#define CURSOR_GET_DATA 0x5811 +#define CURSOR_SET_KEY 0x5811 + +typedef unsigned char u8; + +struct packets +{ + u8 start_h,start_l;/*接收包起始码 正确为 0xff 0xff*/ + u8 y_h,y_l; /*Y轴高低共12bit有效数据*/ + u8 x_h,x_l; /*x轴高低共12bit有效数据*/ + u8 press,cmd; /*按键按下标志,预留命令*/ + u8 end_h,end_l; /*接收包尾码 正确为 0xfe 0xfe*/ +}pAriTouch; /**/ + + + + +extern "C" { +int x,y; + + +void initCoord() { + int coordX = 550; + int coordY = 1700; + pAriTouch.start_h = 0xff; + pAriTouch.start_l = 0xff; + pAriTouch.y_h = (coordY) >> 8; + pAriTouch.y_l = coordY & 0xFF; + pAriTouch.x_h = coordX >> 8; + pAriTouch.x_l = coordX & 0xFF; + pAriTouch.press = 0x55; + pAriTouch.end_h = 0xfe; + pAriTouch.end_l = 0xfe; +} +void setCoord(int coordX, int coordY) { + x = coordX; + y = coordY; + pAriTouch.y_h = (coordY) >> 8; + pAriTouch.y_l = coordY & 0xFF; + pAriTouch.x_h = coordX >> 8; + pAriTouch.x_l = coordX & 0xFF; + pAriTouch.press = 0x55; + +} + +int ioctlClick() { + int fd_gesture, ret; + fd_gesture = open("/dev/gesture", O_RDWR); /*open device*/ //修改设备名为 gesture + if (fd_gesture == -1) { + printf("open device fd error!\n"); + return 0; + } + pAriTouch.press = 0x55; + LOGFI("click x %d y %d",x,y); + ret = ioctl(fd_gesture, CURSOR_SET_DATA, &pAriTouch); + pAriTouch.press = 0x80; + ret = ioctl(fd_gesture, CURSOR_SET_DATA, &pAriTouch); + + close(fd_gesture); + + LOGFI("fd %d ret %d",fd_gesture,ret); +// sleep(1); + return ret; +} + +int ioctlSetKey(int keyValue) { + int fd_gesture, ret; + fd_gesture = open("/dev/gesture", O_RDWR); /*open device*/ //修改设备名为 gesture + if (fd_gesture == -1) { + printf("open device fd error!\n"); + return 0; + } + + ret = ioctl(fd_gesture, CURSOR_SET_KEY, &keyValue); + close(fd_gesture); + + LOGFI("fd %d ret %d",fd_gesture,ret); +// sleep(1); + return ret; +} +JNIEXPORT jstring JNICALL +Java_com_touchclick_AirTouchJNI_clickFromJNI( + JNIEnv *env, + jobject /* this */) { + + int ret; + LOGFI("jni in"); + + initCoord(); + + setCoord(550,1700);//移动打卡 将产生浮窗 + ret = ioctlClick(); + + setCoord(1080-825,445);//todo 关闭加班浮窗 坐标未知 + ret += ioctlClick(); + setCoord(1080-825,580);//todo 关闭加班浮窗 坐标未知 + ret += ioctlClick(); + setCoord(1080-250,1150);//todo 关闭排名浮窗 坐标未知 + ret += ioctlClick(); + setCoord(1080-70,170);//todo 关闭打卡分享 + ret += ioctlClick(); + + + if (ret < 0) + return env->NewStringUTF("finish"); + else + return env->NewStringUTF("finish"); + +} + +JNIEXPORT jstring JNICALL +Java_com_touchclick_AirTouchJNI_stayWackupFromJNI( + JNIEnv *env, + jobject /* this */) { + + int ret; + LOGFI("jni in"); + + initCoord(); + + + setCoord(1080-825,445);//todo 关闭加班浮窗 坐标未知 + ret += ioctlClick(); + setCoord(1080-825,580);//todo 关闭加班浮窗 坐标未知 + ret += ioctlClick(); + + if (ret < 0) + return env->NewStringUTF("finish"); + else + return env->NewStringUTF("finish"); + +} + +JNIEXPORT jstring JNICALL +Java_com_touchclick_AirTouchJNI_mainFromJNI( + JNIEnv *env, + jobject /* this */) { + char hello[100] = {"fd "}; + int ret; + initCoord(); + LOGFI("jni in"); + + int fd_gesture; + fd_gesture = open("/dev/gesture", O_RDWR); /*open device*/ //修改设备名为 gesture + if (fd_gesture == -1) { + printf("open device fd error!\n"); + return 0; + } + ret = ioctl(fd_gesture, CURSOR_SET_DATA, &pAriTouch); + pAriTouch.press = 0x80; + ret = ioctl(fd_gesture, CURSOR_SET_DATA, &pAriTouch); + + close(fd_gesture); + + + char temp[64]; + + sprintf(temp, "%d", fd_gesture); + strcat(hello, temp); + + strcat(hello, " ret "); + sprintf(temp, "%d", ret); + strcat(hello, temp); + + LOGFI("fd %d ret %d",fd_gesture,ret); + + if (ret < 0) + return env->NewStringUTF(hello); + else + return env->NewStringUTF(hello); + +} +} \ No newline at end of file diff --git a/pool/shard006/C++/0079431_AuditWrapper.cpp b/pool/shard006/C++/0079431_AuditWrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36711dc644c04624c22bbd25edb0285170198f3e --- /dev/null +++ b/pool/shard006/C++/0079431_AuditWrapper.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/Audit/AuditWrapper.cpp + * @author Aleksander Zdyb + * @version 1.0 + */ + + #include + +#include +extern int _audit_syscalladded; // God bless them + +#include "AuditWrapper.h" + +namespace Audit { + +int AuditWrapper::audit_open(void) { + return ::audit_open(); +} + +void AuditWrapper::audit_close(int fd) { + ::audit_close(fd); +} + +int AuditWrapper::audit_add_rule_data(int fd, struct audit_rule_data *rule, int flags, int action) { + return ::audit_add_rule_data(fd, rule, flags, action); +} + +int AuditWrapper::audit_delete_rule_data(int fd, struct audit_rule_data *rule, int flags, + int action) +{ + return ::audit_delete_rule_data(fd, rule, flags, action); +} + +int AuditWrapper::audit_rule_syscallbyname_data(struct audit_rule_data *rule, const char *scall) { + auto ret = ::audit_rule_syscallbyname_data(rule, scall); + if (ret == 0) + _audit_syscalladded = 1; + return ret; +} + +int AuditWrapper::audit_rule_fieldpair_data(struct audit_rule_data **rulep, const char *pair, + int flags) { + return ::audit_rule_fieldpair_data(rulep, pair, flags); +} + +void AuditWrapper::audit_rule_free_data(struct audit_rule_data *rule) { + ::audit_rule_free_data(rule); +} + +audit_rule_data *AuditWrapper::create_rule_data() { + return static_cast(calloc(1, sizeof(struct audit_rule_data))); +} + +int AuditWrapper::MAX_AUDIT_MESSAGE_LENGTH_CONST() const { + return MAX_AUDIT_MESSAGE_LENGTH; +} + +int AuditWrapper::AUDIT_FILTER_EXIT_CONST() const { + return AUDIT_FILTER_EXIT; +} + +int AuditWrapper::AUDIT_ALWAYS_CONST() const { + return AUDIT_ALWAYS; +} + +} /* namespace Audit */ diff --git a/pool/shard006/C++/0079439_ranclass.cpp b/pool/shard006/C++/0079439_ranclass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88fca3cabfd90b9f3c41f8ed04b27d7eb4083538 --- /dev/null +++ b/pool/shard006/C++/0079439_ranclass.cpp @@ -0,0 +1,257 @@ +/*-----------------------------------------------------------------------------*\ +| Matpack random generator class ranclass.cpp | +| | +| Last change: Nov 5, 2005 | +| | +| Matpack Library Release 1.9.0 | +| Copyright (C) 1991-2005 by Berndt M. Gammel | +| | +| Permission to use, copy, and distribute Matpack in its entirety and its | +| documentation for non-commercial purpose and without fee is hereby granted, | +| provided that this license information and copyright notice appear unmodified | +| in all copies. This software is provided 'as is' without express or implied | +| warranty. In no event will the author be held liable for any damages arising | +| from the use of this software. | +| Note that distributing Matpack 'bundled' in with any product is considered to | +| be a 'commercial purpose'. | +| The software may be modified for your own purposes, but modified versions may | +| not be distributed without prior consent of the author. | +| | +| Read the COPYRIGHT and README files in this distribution about registration | +| and installation of Matpack. | +| | +\*-----------------------------------------------------------------------------*/ + +//----------------------------------------------------------------------------// +// Matpack's includes +//----------------------------------------------------------------------------// + +#include "mprandom.h" +#include "md5.h" + +//----------------------------------------------------------------------------// +// system includes +//----------------------------------------------------------------------------// + +#include +#include + +#if defined( WIN32) + +// Windows specific +#include +#include + +#else + +// Unix and Linux specific +#include +#include +#include + +#endif + +namespace MATPACK { + +//----------------------------------------------------------------------------// +// unsigned long RandomGenerator::UniqueSeed (void) +//----------------------------------------------------------------------------// +// Generate an unique seed using the process id, the parents process id, +// time and clock ticks. +// +// The seed returned is positive with 0 < seed < 2^31. +// +// NOTE: Never use repeated calls to the seed generator as a substitute for +// generating a random sequence! Always use one of the random +// generators for this purpose. This function is very slow. +// +// HINT: It is in general not sufficient to use the function time() to get +// a seed, because of the intrinsic resolution of one second. Thus if +// more than one initialization of the same random number generator +// is done in one second then the same sequence would be generated. +// Therefore also a call to the processor clock() is performed to get a +// unique time stamp. The result is combined with the value of time(). +// All this will fail if the time resolution of clock() is so bad, +// that more than one initialization within two clock ticks can be done. +// This happens indeed on fast machines if new seeds are requested +// in a short time interval. To overcome this difficulty the seed +// generated previously is mixed into the new seed to make it unique. +// All this will fail if for instance the program (not this function) +// is called two times within one second. Then the value of time() might +// not have changed and clock() always starts counting from zero each +// time the program is started. +// For this reason the process id and the parents process id is mixed +// into the seed. These values should be unique. +// Additionally, the system information available with getrusage() +// is mixed into the seed. This includes random events like page faults, +// swaps, signals received, system times, user times, and many other. +// Now the seed should be really unique ! +//----------------------------------------------------------------------------// + +unsigned long RandomGenerator::UniqueSeed (void) +{ + // the static pool of randomness - with some arbitrary initialization value + static unsigned char digest[16] = { + 0xd1, 0x98, 0x2f, 0xd0, 0xb8, 0x6a, 0xba, 0xf1, + 0x24, 0xb3, 0x08, 0x85, 0x63, 0x71, 0xa4, 0xf4 }; + + // a static random counter which is mixed into the pool every time this + // function is called. This ensures at least deterministic randomness even + // if all system calls fail to provide true randomness. + static unsigned long randcnt = 1; + +once_again: + + // initialize the MD5 hashing with the random pool + struct MD5Context context; + MD5Init(&context); + MD5Update(&context,digest,sizeof(digest)); + + // increment counter and mix value into pool + randcnt++; + MD5Update(&context,(unsigned char*)&randcnt,sizeof(randcnt)); + + // Now mix random system values into the pool + clock_t clk = clock(); // cpu time [clock] + MD5Update(&context,(unsigned char*)&clk,sizeof(clock_t)); + + +#if defined( WIN32 ) + + // MS Windows specific + int pid = _getpid(); // process id + MD5Update(&context,(unsigned char*)&pid,sizeof(int)); + + struct _timeb timeb; // time at a high resolution + _ftime(&timeb); + MD5Update(&context,(unsigned char*)&timeb,sizeof(struct _timeb)); + + +#else + + // Unix/Linux specific + pid_t pid = getpid(); // process id + MD5Update(&context,(unsigned char*)&pid,sizeof(pid_t)); + + pid = getppid(); // parent process id + MD5Update(&context,(unsigned char*)&pid,sizeof(pid_t)); + + struct timeval tim; // time at high resolution + gettimeofday(&tim,NULL); + MD5Update(&context,(unsigned char*)&tim,sizeof(struct timeval)); + + struct rusage rus; // sys resource usage + getrusage(RUSAGE_SELF,&rus); + MD5Update(&context,(unsigned char*)&rus,sizeof(struct rusage)); + +#endif + + + // finalize hash calculation, i.e. value is saved in digest + MD5Final(digest,&context); + + // convert bytes to number within 0 < seed < 2^31. + unsigned long unique_seed = *((unsigned long*) digest) & 0x7fffffff; + if (unique_seed == 0) goto once_again; // extremly rare, but possible + + return unique_seed; +} + +//----------------------------------------------------------------------------// +// RandomGenerator default: combined congruential with shuffle +//----------------------------------------------------------------------------// +// +// Returns an integer random number uniformly distributed within [1,2147483562] +// +// Reference: +// (1) This is the long period ( > 2.3 * 10^18 ) random number generator of +// P. L'Ecuyer, Commun. ACM 31, 743 (1988), but with Bays-Durham shuffle +// and "added safeguards" as proposed by +// (2) William H. Press and Saul A. Teukolsky, +// "Portable Random Number Generators", +// Computers in Physics, Vol. 6, No. 5, Sep/Oct 1992, Algorithm "ran2" +// (3) This generator has been validated also by +// G. Marsaglia and A. Zaman, +// "Some portable very-long-period random number generators", +// Computers in Physics, Vol. 8, No. 1, Jan/Feb 1994. +// +// Notes: +// - William Press and Saul Teukolsky think that this is a "perfect" +// random generator and will pay $1000 for the first one who convinces +// them otherwise. +// +// - This generator is very slow +// +//----------------------------------------------------------------------------// + +static const int NTAB = 32; + +static const long IM1 = 2147483563L, + IM2 = 2147483399L, + IA1 = 40014L, + IA2 = 40692L, + IQ1 = 53668L, + IQ2 = 52774L, + IR1 = 12211L, + IR2 = 3791L, + IMM1 = IM1-1L; + +//----------------------------------------------------------------------------// + +void RandomGenerator::Init (void) +{ + // requires at least 32 bit arithmetics + assert( sizeof(unsigned long) >= 4 ); + + // initialize the maximum value: max_val + max_val = IMM1; + + // initialize shuffle table using the seed: iv and idum,idum2,iy + idum = (seed > 1L) ? seed : 1L; // Be sure to prevent idum = 0 + idum2 = idum; // was previously: idum2 = 123456789L; + + for (int j = NTAB+7; j >= 0; j--) { // Load shuffle table (after 8 warm-ups) + long k = idum/IQ1; + idum = IA1 * (idum - k * IQ1) - IR1 * k; + if (idum < 0) idum += IM1; + if (j < NTAB) iv[j] = idum; + } + iy = iv[0]; +} + +//----------------------------------------------------------------------------// + +unsigned long RandomGenerator::Long (void) +{ + long j, k; + + k = idum/IQ1; // Start here when not initializing + idum = IA1*(idum-k*IQ1)-IR1*k; // Compute idum=mod(IA1*idum,IM1) without + // overflows by Schrage's method + if (idum < 0) idum += IM1; + + k = idum2/IQ2; // Compute idum2=mod(IA2*idum2,IM2) likewise + idum2 = IA2*(idum2-k*IQ2)-IR2*k; // Compute idum=mod(IA1*idum,IM1) without + // overflows by Schrage's method + if (idum2 < 0) idum2 += IM2; + + j = iy/(1L+IMM1/NTAB); // Will be in the range 0..NTAB-1 + iy = iv[j]-idum2; // Output previously stored value and + // refill the shuffle table + iv[j] = idum; + if (iy < 1) iy += IMM1; + + return iy; +} + +//----------------------------------------------------------------------------// + +//----------------------------------------------------------------------------// +// The Default RandomGenerator +//----------------------------------------------------------------------------// + +RandomGenerator Random; + +} // namespace MATPACK + +//----------------------------------------------------------------------------// diff --git a/pool/shard006/C++/0079441_view.cpp b/pool/shard006/C++/0079441_view.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc10d0c19f76fa4280c097365f6a24c54dcc690d --- /dev/null +++ b/pool/shard006/C++/0079441_view.cpp @@ -0,0 +1,54 @@ +#include "view.h" + + +//funcion de draw que no hace nada +void viewNullDraw(renderer::DrawContext /*context*/,renderer::drawable* /*drawableObject*/){} + +void initView(view *v,event::EventLoop* defaultLoop){ + if(v){ + v->renderDrawable = &viewNullDraw; + + v->loop = defaultLoop; + } +} +void runView(view **view, bool* stop){ + if(view && stop){ + SDL_Event e; + bool noEvent; + event::EventLoop* loop; + while (!*stop) { + noEvent = true; + while(SDL_PollEvent(&e)){ + noEvent = false; + loop = (*view)->loop; + while (loop) { + if(loop->d(loop,&e) == 0){ + loop = (event::EventLoop*)loop->next; + }else break; + } + } + if(noEvent){ + loop = (*view)->loop; + while (loop) { + if(loop->d(loop,NULL) == 0){ + loop = (event::EventLoop*)loop->next; + }else break; + } + } + } + } +} + + +void setPoss(view *v, SDL_Point p){ + if(v){ + v->r.x = p.x; + v->r.y = p.y; + } +} +void setSize(view *v, Size s){ + if(v && s.h && s.w){ + v->r.w = s.w; + v->r.h = s.h; + } +} diff --git a/pool/shard006/C++/0079444_task1.cpp b/pool/shard006/C++/0079444_task1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78bf608e1232bcfba14a7a37d5d62b405968b65c --- /dev/null +++ b/pool/shard006/C++/0079444_task1.cpp @@ -0,0 +1,135 @@ +#include "plant.h" + +#include +#include +#include +#include +#include +#include + +using namespace std; + +stack readStackFromTextFile(const string& filename) +{ + ifstream plantsInput(filename); + stack plants; + Plant plant; + + while (plantsInput >> plant) + plants.push(plant); + + return plants; +} + +template +list stackToList(stack items) +{ + list listItems; + while (!items.empty()) + { + listItems.push_front(items.top()); + items.pop(); + } + return listItems; +} + +queue> dispatch(stack plantsStack, stack temperatures) +{ + list plants = stackToList(plantsStack); + queue> dispatched; + + Plant plant; + stack currentStack; + while (!temperatures.empty()) + { + currentStack = stack(); + double temperature = temperatures.top(); + temperatures.pop(); + + list::iterator it = plants.begin(); + while (it != plants.end()) + { + plant = *it; + if (plant.minTemperature <= temperature && plant.maxTemperature >= temperature) + { + currentStack.push(plant); + it = plants.erase(it); + } + else + { + ++it; + } + } + + dispatched.push(currentStack); + } + + return dispatched; +} + +void writeListToBinary(list plants, const string& filename) +{ + ofstream out(filename, ios::binary); + for (const Plant& plant : plants) + writeToBinary(out, plant); +} + +list filterPlants(list plants, double temperature) +{ + plants.remove_if([temperature] (const Plant& plant) + { + return fabs(plant.averageTemperature() - temperature) > 2; + }); + return plants; +} + +void writeFilteredToFile(stack plantsStack, double temperature) +{ + const string filename = "botanic.bin"; + list plants = stackToList(plantsStack); + plants = filterPlants(plants, temperature); + writeListToBinary(plants, filename); +} + +int main() +{ + + //Examples + + stack plants = readStackFromTextFile("plants.txt"); + stack temperatures; + temperatures.push(18); + temperatures.push(25); + temperatures.push(10); + + queue> dispatched = dispatch(plants, temperatures); + while (!dispatched.empty()) + { + stack currentStack = dispatched.front(); + cout << "START OF STACK" << endl; + while (!currentStack.empty()) + { + cout << currentStack.top() << endl; + currentStack.pop(); + } + cout << "END OF STACK" << endl; + dispatched.pop(); + } + + writeFilteredToFile(plants, 25); + + ifstream in("botanic.bin", ios::binary); + Plant plant; + while (readFromBinary(in, plant)) + { + cout << plant << endl; + } + + // while (!plants.empty()) + // { + // cout << plants.top() << endl; + // plants.pop(); + // } + + return 0; +} diff --git a/pool/shard006/C++/0079451_CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54a.cpp b/pool/shard006/C++/0079451_CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7383de9c48254c79bf72334711e6c63f475ce761 --- /dev/null +++ b/pool/shard006/C++/0079451_CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54a.cpp @@ -0,0 +1,105 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54a.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml +Template File: sources-sinks-54a.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: Allocate data using new [] + * GoodSource: Allocate data using malloc() + * Sinks: + * GoodSink: Deallocate data using delete [] + * BadSink : Deallocate data using free() + * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files + * + * */ + +#include "std_testcase.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink_b(int64_t * data); + +void bad() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ + data = new int64_t[100]; + badSink_b(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink_b(int64_t * data); + +static void goodG2B() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + /* FIX: Allocate memory from the heap using malloc() */ + data = (int64_t *)malloc(100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + goodG2BSink_b(data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink_b(int64_t * data); + +static void goodB2G() +{ + int64_t * data; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ + data = new int64_t[100]; + goodB2GSink_b(data); +} + +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 CWE762_Mismatched_Memory_Management_Routines__new_array_free_int64_t_54; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C++/0079454_ev_root_ca_metadata_unittest.cc b/pool/shard006/C++/0079454_ev_root_ca_metadata_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a1ef351dbe4beb69970be500dc18e05d9e050c6 --- /dev/null +++ b/pool/shard006/C++/0079454_ev_root_ca_metadata_unittest.cc @@ -0,0 +1,94 @@ +// 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 "net/base/ev_root_ca_metadata.h" + +#include "net/base/cert_test_util.h" +#include "net/base/x509_cert_types.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { + +static const char kVerisignPolicy[] = "2.16.840.1.113733.1.7.23.6"; +static const char kThawtePolicy[] = "2.16.840.1.113733.1.7.48.1"; +static const char kFakePolicy[] = "2.16.840.1.42"; +static const SHA1Fingerprint kVerisignFingerprint = + { { 0x74, 0x2c, 0x31, 0x92, 0xe6, 0x07, 0xe4, 0x24, 0xeb, 0x45, + 0x49, 0x54, 0x2b, 0xe1, 0xbb, 0xc5, 0x3e, 0x61, 0x74, 0xe2 } }; +static const SHA1Fingerprint kFakeFingerprint = + { { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99 } }; + +#if defined(USE_NSS) + +TEST(EVRootCAMetadataTest, Basic) { + EVRootCAMetadata* ev_metadata(EVRootCAMetadata::GetInstance()); + std::vector oids; + + EXPECT_TRUE(ev_metadata->GetPolicyOIDsForCA(kVerisignFingerprint, &oids)); + EXPECT_LT(0u, oids.size()); + oids.clear(); + + EXPECT_FALSE(ev_metadata->GetPolicyOIDsForCA(kFakeFingerprint, &oids)); + EXPECT_EQ(0u, oids.size()); +} + +TEST(EVRootCAMetadataTest, AddRemove) { + EVRootCAMetadata* ev_metadata(EVRootCAMetadata::GetInstance()); + std::vector oids; + + EXPECT_FALSE(ev_metadata->GetPolicyOIDsForCA(kFakeFingerprint, &oids)); + + { + ScopedTestEVPolicy test_ev_policy(ev_metadata, kFakeFingerprint, + kFakePolicy); + + EXPECT_TRUE(ev_metadata->GetPolicyOIDsForCA(kFakeFingerprint, &oids)); + EXPECT_EQ(1u, oids.size()); + } + + EXPECT_FALSE(ev_metadata->GetPolicyOIDsForCA(kFakeFingerprint, &oids)); +} + +#elif defined(OS_WIN) + +TEST(EVRootCAMetadataTest, Basic) { + EVRootCAMetadata* ev_metadata(EVRootCAMetadata::GetInstance()); + + EXPECT_TRUE(ev_metadata->IsEVPolicyOID(kVerisignPolicy)); + EXPECT_FALSE(ev_metadata->IsEVPolicyOID(kFakePolicy)); + EXPECT_TRUE(ev_metadata->HasEVPolicyOID(kVerisignFingerprint, + kVerisignPolicy)); + EXPECT_FALSE(ev_metadata->HasEVPolicyOID(kFakeFingerprint, + kVerisignPolicy)); + EXPECT_FALSE(ev_metadata->HasEVPolicyOID(kVerisignFingerprint, + kFakePolicy)); + EXPECT_FALSE(ev_metadata->HasEVPolicyOID(kVerisignFingerprint, + kThawtePolicy)); +} + +TEST(EVRootCAMetadataTest, AddRemove) { + EVRootCAMetadata* ev_metadata(EVRootCAMetadata::GetInstance()); + + EXPECT_FALSE(ev_metadata->IsEVPolicyOID(kFakePolicy)); + EXPECT_FALSE(ev_metadata->HasEVPolicyOID(kFakeFingerprint, + kFakePolicy)); + + { + ScopedTestEVPolicy test_ev_policy(ev_metadata, kFakeFingerprint, + kFakePolicy); + + EXPECT_TRUE(ev_metadata->IsEVPolicyOID(kFakePolicy)); + EXPECT_TRUE(ev_metadata->HasEVPolicyOID(kFakeFingerprint, + kFakePolicy)); + } + + EXPECT_FALSE(ev_metadata->IsEVPolicyOID(kFakePolicy)); + EXPECT_FALSE(ev_metadata->HasEVPolicyOID(kFakeFingerprint, + kFakePolicy)); +} + +#endif // defined(OS_WIN) + +} // namespace net diff --git a/pool/shard006/C++/0079456_GLProgram.cpp b/pool/shard006/C++/0079456_GLProgram.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d630726ef9515bf7c542d99afd35a79ec87dfa5 --- /dev/null +++ b/pool/shard006/C++/0079456_GLProgram.cpp @@ -0,0 +1,155 @@ +/** + * Copyright Kyle Parkinson 2016. All rights reserved. + */ + +#include "GLProgram.h" + +Peon::GLProgram::GLProgram() : mLinked(false), mEnabled(false), mId(0) { +} + +Peon::GLProgram::~GLProgram() { + glDeleteProgram(mId); +} + +void Peon::GLProgram::AddShader(GLuint type, const string & file) { + this->AddShaderSource(type, Peon::ReadFile(file)); +} + +void Peon::GLProgram::AddShaderSource(GLuint type, const string & source) { + GLint success = 0; + GLchar errorLog[512]; + GLuint shader = glCreateShader(type); + const char* code = source.c_str(); + glShaderSource(shader, 1, &code, 0); + glCompileShader(shader); + glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(shader, 512, 0, errorLog); + glDeleteShader(shader); + LOG_ERROR("Unable to compile shader source. " << errorLog); + } + mShaders.push_back(shader); +} + +void Peon::GLProgram::LinkProgram() { + assert(!mLinked); + mId = glCreateProgram(); + for (GLuint shader : mShaders) { + glAttachShader(mId, shader); + } + glLinkProgram(mId); + GLint linkSuccess = GL_TRUE; + glGetProgramiv(mId, GL_LINK_STATUS, &linkSuccess); + for (GLuint shader : mShaders) { + glDetachShader(mId, shader); + glDeleteShader(shader); + } + mShaders.clear(); + if (!linkSuccess) { + GLchar errorLog[512]; + glGetShaderInfoLog(mId, 512, 0, errorLog); + LOG_ERROR("Unable to link program. " << errorLog); + return; + } + mLinked = true; +} + +void Peon::GLProgram::Enable() { + assert(mLinked); + glUseProgram(mId); + mEnabled = true; +} + +void Peon::GLProgram::Disable() { + assert(mLinked); + assert(mEnabled); + glUseProgram(0); + mEnabled = false; +} + +bool Peon::GLProgram::IsLinked() { + return mLinked; +} + +void Peon::GLProgram::SetUniform(const string & uniform, const mat4 & matrix) { + if (mUniforms.find(uniform) != mUniforms.end()) { + glUniformMatrix4fv(mUniforms[uniform], 1, GL_FALSE, glm::value_ptr(matrix)); + return; + } + GLint location = glGetUniformLocation(mId, uniform.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniform << " on GLShader program with id -- " << mId); + return; + } + glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix)); + mUniforms[uniform] = location; +} + +void Peon::GLProgram::SetUniform(const string & uniform, const vec3 & vector) { + if (mUniforms.find(uniform) != mUniforms.end()) { + glUniform3fv(mUniforms[uniform], 1, glm::value_ptr(vector)); + return; + } + GLint location = glGetUniformLocation(mId, uniform.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniform << " on GLShader program with id -- " << mId); + return; + } + glUniform3fv(location, 1, glm::value_ptr(vector)); + mUniforms[uniform] = location; +} + +void Peon::GLProgram::SetUniform(const string & uniform, const vec4 & vector) { + if (mUniforms.find(uniform) != mUniforms.end()) { + glUniform4fv(mUniforms[uniform], 1, glm::value_ptr(vector)); + return; + } + GLint location = glGetUniformLocation(mId, uniform.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniform << " on GLShader program with id -- " << mId); + return; + } + glUniform4fv(location, 1, glm::value_ptr(vector)); + mUniforms[uniform] = location; +} + +void Peon::GLProgram::SetUniform(const string & uniform, float value) { + if (mUniforms.find(uniform) != mUniforms.end()) { + glUniform1f(mUniforms[uniform], value); + return; + } + GLint location = glGetUniformLocation(mId, uniform.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniform << " on GLShader program with id -- " << mId); + return; + } + glUniform1f(location, value); + mUniforms[uniform] = location; +} + +void Peon::GLProgram::SetUniform(const string & uniform, int value) { + if (mUniforms.find(uniform) != mUniforms.end()) { + glUniform1i(mUniforms[uniform], value); + return; + } + GLint location = glGetUniformLocation(mId, uniform.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniform << " on GLShader program with id -- " << mId); + return; + } + glUniform1i(location, value); + mUniforms[uniform] = location; +} + +GLint Peon::GLProgram::GetUniformLocation(const string & uniformName) { + if (mUniforms.find(uniformName) != mUniforms.end()) { + return mUniforms[uniformName]; + } + GLint location = glGetUniformLocation(mId, uniformName.c_str()); + if (location == -1) { + LOG_ERROR("Unable to locate uniform -- " << uniformName << " on GLShader program with id -- " << mId); + } else { + mUniforms[uniformName] = location; + } + return location; +} \ No newline at end of file diff --git a/pool/shard006/C++/0079459_mugsmash.cpp b/pool/shard006/C++/0079459_mugsmash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12222aadc99c4b975555ac303c391d249f64a714 --- /dev/null +++ b/pool/shard006/C++/0079459_mugsmash.cpp @@ -0,0 +1,148 @@ +// license:BSD-3-Clause +// copyright-holders:David Haywood +/* video/mugsmash.c - see drivers/mugsmash.c for more info */ + +#include "emu.h" +#include "includes/mugsmash.h" + +void mugsmash_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect ) +{ + /* Each Sprite takes 16 bytes, 5 used? */ + + /* ---- ---- xxxx xxxx ---- ---- aaaa aaaa ---- ---- NNNN NNNN ---- ---- nnnn nnnn ---- ---- yyyy yyyy (rest unused?) */ + + /* x = xpos LSB + y = ypos LSB + N = tile number MSB + n = tile number LSB + a = attribute / extra + f?XY cccc + + f = x-flip + ? = unknown, probably y-flip + X = xpos MSB + y = ypos MSB + c = colour + + */ + + const uint16_t *source = m_spriteram; + const uint16_t *finish = source + 0x2000; + gfx_element *gfx = m_gfxdecode->gfx(0); + + while (source < finish) + { + int xpos = source[0] & 0x00ff; + int ypos = source[4] & 0x00ff; + int num = (source[3] & 0x00ff) | ((source[2] & 0x00ff) << 8); + int attr = source[1]; + int flipx = (attr & 0x0080) >> 7; + int colour = (attr & 0x000f); + + xpos += ((attr & 0x0020) >> 5) * 0x100; + ypos += ((attr & 0x0010) >> 4) * 0x100; + + xpos -= 28; + ypos -= 16; + + + gfx->transpen( + bitmap, + cliprect, + num, + colour, + flipx,0, + xpos,ypos,0 + ); + + source += 0x8; + } +} + +TILE_GET_INFO_MEMBER(mugsmash_state::get_mugsmash_tile_info1) +{ + /* fF-- cccc nnnn nnnn */ + + /* c = colour? + n = number? + F = flip-X + f = flip-Y + */ + + int tileno, colour, fx; + + tileno = m_videoram1[tile_index * 2 + 1]; + colour = m_videoram1[tile_index * 2] & 0x000f; + fx = (m_videoram1[tile_index * 2] & 0xc0) >> 6; + + tileinfo.set(1, tileno, colour, TILE_FLIPYX(fx)); +} + +void mugsmash_state::mugsmash_videoram1_w(offs_t offset, uint16_t data) +{ + m_videoram1[offset] = data; + m_tilemap1->mark_tile_dirty(offset / 2); +} + +TILE_GET_INFO_MEMBER(mugsmash_state::get_mugsmash_tile_info2) +{ + /* fF-- cccc nnnn nnnn */ + + /* c = colour? + n = number? + F = flip-X + f = flip-Y + */ + + int tileno, colour, fx; + + tileno = m_videoram2[tile_index * 2 + 1]; + colour = m_videoram2[tile_index * 2] & 0x000f; + fx = (m_videoram2[tile_index * 2] & 0xc0) >> 6; + + tileinfo.set(1, tileno, 16 + colour, TILE_FLIPYX(fx)); +} + +void mugsmash_state::mugsmash_videoram2_w(offs_t offset, uint16_t data) +{ + m_videoram2[offset] = data; + m_tilemap2->mark_tile_dirty(offset / 2); +} + +void mugsmash_state::mugsmash_reg_w(offs_t offset, uint16_t data) +{ + m_regs1[offset] = data; +// popmessage ("Regs %04x, %04x, %04x, %04x", mugsmash_regs1[0], mugsmash_regs1[1],mugsmash_regs1[2], mugsmash_regs1[3]); + + switch (offset) + { + case 0: + m_tilemap2->set_scrollx(0, m_regs1[2] + 7); + break; + case 1: + m_tilemap2->set_scrolly(0, m_regs1[3] + 4); + break; + case 2: + m_tilemap1->set_scrollx(0, m_regs1[0] + 3); + break; + case 3: + m_tilemap1->set_scrolly(0, m_regs1[1] + 4); + break; + } +} + +void mugsmash_state::video_start() +{ + m_tilemap1 = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(mugsmash_state::get_mugsmash_tile_info1)), TILEMAP_SCAN_ROWS, 16, 16, 32, 32); + m_tilemap1->set_transparent_pen(0); + + m_tilemap2 = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(mugsmash_state::get_mugsmash_tile_info2)), TILEMAP_SCAN_ROWS, 16, 16, 32, 32); +} + +uint32_t mugsmash_state::screen_update_mugsmash(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) +{ + m_tilemap2->draw(screen, bitmap, cliprect, 0, 0); + m_tilemap1->draw(screen, bitmap, cliprect, 0, 0); + draw_sprites(bitmap, cliprect); + return 0; +} diff --git a/pool/shard006/C++/0079462_SnapOverlayOp.cpp b/pool/shard006/C++/0079462_SnapOverlayOp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba45bb26bce447bd1d894dbbc0279b2ef831a493 --- /dev/null +++ b/pool/shard006/C++/0079462_SnapOverlayOp.cpp @@ -0,0 +1,111 @@ +/********************************************************************** + * $Id: SnapOverlayOp.cpp 3538 2011-12-09 10:44:54Z strk $ + * + * GEOS - Geometry Engine Open Source + * http://geos.refractions.net + * + * 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/overlay/snap/SnapOverlayOp.java r320 (JTS-1.12) + * + **********************************************************************/ + +#include +#include +#include +#include + +#include +#include // for numeric_limits +#include // for auto_ptr + +#ifndef GEOS_DEBUG +#define GEOS_DEBUG 0 +#endif + +using namespace std; +using namespace geos::geom; + +namespace geos { +namespace operation { // geos.operation +namespace overlay { // geos.operation.overlay +namespace snap { // geos.operation.overlay.snap + +/* private */ +void +SnapOverlayOp::computeSnapTolerance() +{ + snapTolerance = GeometrySnapper::computeOverlaySnapTolerance(geom0, + geom1); + + // cout << "Snap tol = " << snapTolerance << endl; +} + +/* public */ +auto_ptr +SnapOverlayOp::getResultGeometry(OverlayOp::OpCode opCode) +{ + geom::GeomPtrPair prepGeom; + snap(prepGeom); + GeomPtr result ( OverlayOp::overlayOp(prepGeom.first.get(), + prepGeom.second.get(), opCode) ); + prepareResult(*result); + return result; +} + +/* private */ +void +SnapOverlayOp::snap(geom::GeomPtrPair& snapGeom) +{ + geom::GeomPtrPair remGeom; + removeCommonBits(geom0, geom1, remGeom); + + GeometrySnapper::snap(*remGeom.first, *remGeom.second, + snapTolerance, snapGeom); + + // MD - may want to do this at some point, but it adds cycles +// checkValid(snapGeom[0]); +// checkValid(snapGeom[1]); + + /* + System.out.println("Snapped geoms: "); + System.out.println(snapGeom[0]); + System.out.println(snapGeom[1]); + */ + +} + +/* private */ +void +SnapOverlayOp::removeCommonBits(const geom::Geometry& geom0, + const geom::Geometry& geom1, + geom::GeomPtrPair& remGeom) +{ + cbr.reset(new precision::CommonBitsRemover()); + cbr->add(&geom0); + cbr->add(&geom1); + + remGeom.first.reset( cbr->removeCommonBits(geom0.clone()) ); + remGeom.second.reset( cbr->removeCommonBits(geom1.clone()) ); +} + +/*private*/ +void +SnapOverlayOp::prepareResult(geom::Geometry& geom) +{ + cbr->addCommonBits(&geom); +} + + +} // namespace geos.operation.snap +} // namespace geos.operation.overlay +} // namespace geos.operation +} // namespace geos + diff --git a/pool/shard006/C++/0079473_Window.cpp b/pool/shard006/C++/0079473_Window.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03bc57479ff82600d0505f07b1fa86cd4ebfae3a --- /dev/null +++ b/pool/shard006/C++/0079473_Window.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2009 Magnus Sjöstrand + * + * This file is part of manix. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include +#include +#include + +#include "manix/x/Window.h" + +namespace manix { +namespace x { + + Window::Window( + xcb_connection_t* connection, + xcb_screen_t* screen, + xcb_window_t parent, + uint32_t eventMask, + uint32_t x, + uint32_t y, + uint32_t width, + uint32_t height) + : mConn(connection) + { + assert(mConn != NULL); + + mWindow = xcb_generate_id(connection); + + uint32_t mask = XCB_CW_EVENT_MASK; + uint32_t values[] = { eventMask }; + xcb_create_window( + connection, + screen->root_depth, + mWindow, + parent, + x, y, width, height, + 0, // border + XCB_WINDOW_CLASS_INPUT_OUTPUT, + screen->root_visual, + mask, values); + } + + Window::Window( + xcb_connection_t* connection, + xcb_window_t window) + : mConn(connection) + , mWindow(window) + { + assert(mConn != NULL); + } + + void + Window::getGeometry( + uint32_t& width, + uint32_t& height, + int32_t& x, + int32_t& y) + { + xcb_get_geometry_cookie_t cookie = xcb_get_geometry(mConn, mWindow); + + xcb_generic_error_t* error; + xcb_get_geometry_reply_t* reply = xcb_get_geometry_reply(mConn, cookie, &error); + + width = reply->width; + height = reply->height; + x = reply->x; + y = reply->y; + } + + void + Window::reparent( + x::Window* parent, + int32_t x, + int32_t y) + { + xcb_reparent_window(mConn, mWindow, parent->mWindow, x, y); + } + + void + Window::setBackgroundColor( + uint32_t background) + { + uint32_t mask = XCB_CW_BACK_PIXEL; + uint32_t values[] = { background }; + xcb_change_window_attributes(mConn, mWindow, mask, values); + } + + void + Window::setBackground( + xcb_pixmap_t pixmap) + { + uint32_t mask = XCB_CW_BACK_PIXMAP; + uint32_t values[1] = { pixmap }; + xcb_change_window_attributes(mConn, mWindow, mask, values); + } + + void + Window::moveTo( + int32_t x, + int32_t y) + { + uint32_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y; + int32_t values[] = { x, y }; + + xcb_configure_window(mConn, mWindow, mask, (uint32_t*) values); + } + + void + Window::resizeTo( + uint32_t width, + uint32_t height) + { + uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT; + uint32_t values[] = { width, height }; + + xcb_configure_window(mConn, mWindow, mask, values); + } + + void + Window::show() + { + xcb_map_window(mConn, mWindow); + } + + void + Window::showWithSubs() + { + xcb_map_window(mConn, mWindow); + xcb_map_subwindows(mConn, mWindow); + } + +} // x +} // manix diff --git a/pool/shard006/C++/0079485_rocblas_copy.cpp b/pool/shard006/C++/0079485_rocblas_copy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..268fb65089dcacad0effb4ca029e751a512a38bf --- /dev/null +++ b/pool/shard006/C++/0079485_rocblas_copy.cpp @@ -0,0 +1,171 @@ +/* ************************************************************************ + * Copyright 2016 Advanced Micro Devices, Inc. + * ************************************************************************ */ +#include + +#include "rocblas.h" + +#include "definitions.h" +#include "handle.h" +#include "logging.h" +#include "utility.h" + +#define NB_X 256 + +template +__global__ void copy_kernel(rocblas_int n, const T* x, rocblas_int incx, T* y, rocblas_int incy) +{ + int tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; + // bound + if(incx >= 0 && incy >= 0) + { + if(tid < n) + { + y[tid * incy] = x[tid * incx]; + } + } + else if(incx < 0 && incy < 0) + { + if(tid < n) + { + y[(1 - n + tid) * incy] = x[(1 - n + tid) * incx]; + } + } + else if(incx >= 0) + { + if(tid < n) + { + y[(1 - n + tid) * incy] = x[tid * incx]; + } + } + else + { + if(tid < n) + { + y[tid * incy] = x[(1 - n + tid) * incx]; + } + } +} + +/*! \brief BLAS Level 1 API + + \details + copy copies the vector x[i] into the vector y[i], for i = 1 , … , n + + y := x, + + @param[in] + handle rocblas_handle. + handle to the rocblas library context queue. + @param[in] + n rocblas_int. + if n <= 0 quick return with rocblas_status_success + @param[in] + x pointer storing vector x on the GPU. + @param[in] + incx specifies the increment for the elements of x. + @param[out] + y pointer storing vector y on the GPU. + @param[in] + incy rocblas_int + specifies the increment for the elements of y. + + ********************************************************************/ + +template +rocblas_status rocblas_copy_template( + rocblas_handle handle, rocblas_int n, const T* x, rocblas_int incx, T* y, rocblas_int incy) +{ + if(handle == nullptr) + return rocblas_status_invalid_handle; + + log_function( + handle, replaceX("rocblas_Xcopy"), n, (const void*&)x, incx, (const void*&)y, incy); + + log_bench(handle, + "./rocblas-bench -f copy -r", + replaceX("X"), + "-n", + n, + "--incx", + incx, + "--incy", + incy); + + if(x == nullptr) + return rocblas_status_invalid_pointer; + else if(y == nullptr) + return rocblas_status_invalid_pointer; + + /* + * Quick return if possible. + */ + if(n <= 0) + return rocblas_status_success; + + int blocks = (n - 1) / NB_X + 1; + + dim3 grid(blocks, 1, 1); + dim3 threads(NB_X, 1, 1); + + hipStream_t rocblas_stream = handle->rocblas_stream; + + hipLaunchKernelGGL( + copy_kernel, dim3(grid), dim3(threads), 0, rocblas_stream, n, x, incx, y, incy); + + return rocblas_status_success; +} + +/* ============================================================================================ */ + +/* + * =========================================================================== + * C wrapper + * =========================================================================== + */ + +extern "C" rocblas_status rocblas_scopy(rocblas_handle handle, + rocblas_int n, + const float* x, + rocblas_int incx, + float* y, + rocblas_int incy) +{ + + return rocblas_copy_template(handle, n, x, incx, y, incy); +} + +extern "C" rocblas_status rocblas_dcopy(rocblas_handle handle, + rocblas_int n, + const double* x, + rocblas_int incx, + double* y, + rocblas_int incy) +{ + + return rocblas_copy_template(handle, n, x, incx, y, incy); +} + +extern "C" rocblas_status rocblas_ccopy(rocblas_handle handle, + rocblas_int n, + const rocblas_float_complex* x, + rocblas_int incx, + rocblas_float_complex* y, + rocblas_int incy) +{ + + return rocblas_copy_template(handle, n, x, incx, y, incy); +} + +extern "C" rocblas_status rocblas_zcopy(rocblas_handle handle, + rocblas_int n, + const rocblas_double_complex* x, + rocblas_int incx, + rocblas_double_complex* y, + rocblas_int incy) +{ + + return rocblas_copy_template(handle, n, x, incx, y, incy); +} + +/* ============================================================================================ */ diff --git a/pool/shard006/C++/0079494_AirspaceSorter.cpp b/pool/shard006/C++/0079494_AirspaceSorter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c73c357853c5ccb1d3238206d97e9d79afd6eef8 --- /dev/null +++ b/pool/shard006/C++/0079494_AirspaceSorter.cpp @@ -0,0 +1,119 @@ +#include "AirspaceSorter.hpp" +#include "Airspace/Airspaces.hpp" +#include "AbstractAirspace.hpp" +#include "AirspaceVisitor.hpp" +#include "Geo/GeoVector.hpp" +#include "Util/StringAPI.hpp" + +#include + +void +AirspaceSelectInfo::ResetVector() +{ + vec.SetInvalid(); +} + +const GeoVector & +AirspaceSelectInfo::GetVector(const GeoPoint &location, + const FlatProjection &projection) const +{ + if (!vec.IsValid()) { + const GeoPoint closest_loc = airspace->ClosestPoint(location, projection); + vec = GeoVector(location, closest_loc); + } + + return vec; +} + +bool +AirspaceFilterData::Match(const GeoPoint &location, + const FlatProjection &projection, + const AbstractAirspace &as) const +{ + if (cls != AirspaceClass::AIRSPACECLASSCOUNT && as.GetType() != cls) + return false; + + if (name_prefix != nullptr && !as.MatchNamePrefix(name_prefix)) + return false; + + if (!negative(direction.Native())) { + const GeoPoint closest = as.ClosestPoint(location, projection); + const Angle bearing = location.Bearing(closest); + fixed direction_error = (bearing - direction).AsDelta().AbsoluteDegrees(); + if (direction_error > fixed(18)) + return false; + } + + if (!negative(distance)) { + const GeoPoint closest = as.ClosestPoint(location, projection); + const fixed distance = location.Distance(closest); + if (distance > distance) + return false; + } + + return true; +} + +class AirspaceFilterVisitor final : public AirspaceVisitor { + GeoPoint location; + const FlatProjection &projection; + const AirspaceFilterData &filter; + +public: + AirspaceSelectInfoVector result; + + AirspaceFilterVisitor(const GeoPoint &_location, + const FlatProjection &_projection, + const AirspaceFilterData &_filter) + :location(_location), projection(_projection), filter(_filter) {} + + virtual void Visit(const AbstractAirspace &as) { + if (filter.Match(location, projection, as)) + result.emplace_back(as); + } +}; + +static void +SortByDistance(AirspaceSelectInfoVector &vec, const GeoPoint &location, + const FlatProjection &projection) +{ + auto compare = [&] (const AirspaceSelectInfo &elem1, + const AirspaceSelectInfo &elem2) { + return elem1.GetVector(location, projection).distance < + elem2.GetVector(location, projection).distance; + }; + + std::sort(vec.begin(), vec.end(), compare); +} + +static void +SortByName(AirspaceSelectInfoVector &vec) +{ + auto compare = [&] (const AirspaceSelectInfo &elem1, + const AirspaceSelectInfo &elem2) { + return StringCollate(elem1.GetAirspace().GetName(), + elem2.GetAirspace().GetName()) < 0; + }; + + std::sort(vec.begin(), vec.end(), compare); +} + +AirspaceSelectInfoVector +FilterAirspaces(const Airspaces &airspaces, const GeoPoint &location, + const AirspaceFilterData &filter) +{ + AirspaceFilterVisitor visitor(location, airspaces.GetProjection(), filter); + + if (!negative(filter.distance)) + airspaces.VisitWithinRange(location, filter.distance, visitor); + else + for (const auto &i : airspaces) + visitor.Visit(i.GetAirspace()); + + if (negative(filter.direction.Native()) && negative(filter.distance)) + SortByName(visitor.result); + else + SortByDistance(visitor.result, location, airspaces.GetProjection()); + + return visitor.result; +} diff --git a/pool/shard006/C++/0079495_object_pool.cpp b/pool/shard006/C++/0079495_object_pool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6152c4749f3b60023450bf909800ea1da4487fcd --- /dev/null +++ b/pool/shard006/C++/0079495_object_pool.cpp @@ -0,0 +1,117 @@ +/** + * @purpose A simple object pool example + * + * @author Ashish + * @license MIT license + * @version 1.0, Doxygen compatible comments + */ + +#include +#include +#include +using namespace std; + +class Car { + private: + bool in_use_; + string rentee_; + string last_rentee_; + + public: + Car() + : in_use_(false), + last_rentee_("NONE"), + rentee_("NONE") { + } + + void set_in_use(bool status) { + in_use_ = true; + } + + bool in_use(void) { + return in_use_; + } + + void set_rentee(const string& given_rentee) { + rentee_ = given_rentee; + } + + string rentee(void) { + return rentee_; + } + + void set_last_rentee(const string& given_rentee) { + last_rentee_ = given_rentee; + } + + string last_rentee(void) { + return last_rentee_; + } +}; + +class CarPool : public Car { + private: + list car_list; /// list STL to store object pointers + + public: + static CarPool& get_instance() { /// singleton objectpool instance + static CarPool instance; + return instance; + } + + Car* get_car() { + Car* car = NULL; + + if (car_list.empty()) { /// case 1: Henry gets a brand new car for the first customer + car = new Car; + } else { + car = car_list.front(); /// case 2: Henry allots an already existing car to the customer + car_list.pop_front(); + } + + car->set_in_use(true); + return car; + } + + Car* return_car(Car *given_car) { + if (given_car != NULL) { + given_car->set_in_use(false); + given_car->set_last_rentee(given_car->rentee()); /// Henry notes the previous customer name + given_car->set_rentee("NONE"); + + car_list.push_back(given_car); /// The car has been returned to Henry's car lot + return NULL; + } + } + + protected: + CarPool() { + } +}; + +int main() { + CarPool henrys_car_rental = CarPool::get_instance(); /// henry starts a car rental service + + /// usecase 1 - alice is the first customer, she gets a brand new car + Car* alices = henrys_car_rental.get_car(); /// alice gets a car from henry's rental service + cout << "Alice's car was last rented to = " << alices->last_rentee() << endl; + alices->set_rentee("ALICE"); /// alice is now registered as the rentee and can drive the car + cout << "Alice's car is now rented to = " << alices->rentee() << endl; + + /// usecase 2 - bob is the next customer, he also gets a new car + Car* bobs = henrys_car_rental.get_car(); /// bob also gets a car from henry's rental service + cout << "Bob's car was last rented to = " << bobs->last_rentee() << endl; + bobs->set_rentee("BOB"); /// the car is now resitered to BOB as rentee + cout << "Bob's car is now rented to = " << alices->rentee() << endl; + bobs = henrys_car_rental.return_car(bobs); /// bob returns the car to henry's rental service + + /// usecase 3 - fred is a customer, who gets the car bob has returned + Car* freds = henrys_car_rental.get_car(); /// fred gets bob's returned car from henry's rental service + cout << "Fred's car was last rented to = " << freds->last_rentee() << endl; + freds->set_rentee("FRED"); /// the car is now resitered to FRED as rentee + cout << "Fred's car is now rented to = " << freds->rentee() << endl; + freds = henrys_car_rental.return_car(freds); /// fred returns the car to henry's rental service + + return 0; +} + diff --git a/pool/shard006/C++/0079500_hostuapi.cpp b/pool/shard006/C++/0079500_hostuapi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d9d3528f48fe8de5593f2c96d03de86cb0b7e2a --- /dev/null +++ b/pool/shard006/C++/0079500_hostuapi.cpp @@ -0,0 +1,124 @@ +/*************************************************************************** + * Copyright 2010 by Davide Bettio * + * * + * 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 . * + *************************************************************************** + * Name: hostuapi.cpp * + ***************************************************************************/ + +#include + +#include +#ifndef ARCH_IA32 +#include +#endif +#include +#include +#include +#include +#include +#include + +char *hostName; +char *domainName; + +void HostUAPI::init() +{ +#ifndef ARCH_IA32 + SyscallsManager::registerSyscall(__NR_SETHOSTNAME, (void *) sethostname); + SyscallsManager::registerSyscall(__NR_SETDOMAINNAME, (void *) setdomainname); + SyscallsManager::registerSyscall(__NR_UNAME, (void *) uname); +#endif +} + +int HostUAPI::sethostname(userptr const char *name, size_t len) +{ + if (Scheduler::currentThread()->parentProcess->uid == 0){ + int newLen = MIN(len, 256); + char *newHostName = (char *) malloc(newLen + 1); + int ret = memcpyFromUser(newHostName, name, newLen); + if (UNLIKELY(ret < 0)) { + return ret; + } + newHostName[newLen] = 0; + + char *previousName = hostName; + hostName = newHostName; + if (previousName) { + free(previousName); + } + return ret; + + }else{ + return -EPERM; + } +} + +int HostUAPI::setdomainname(userptr const char *name, size_t len) +{ + if (Scheduler::currentThread()->parentProcess->uid == 0){ + int newLen = MIN(len, 256); + char *newDomainName = (char *) malloc(newLen + 1); + int ret = memcpyFromUser(newDomainName, name, newLen); + if (UNLIKELY(ret < 0)) { + return ret; + } + newDomainName[newLen] = 0; + + char *previousName = domainName; + domainName = newDomainName; + if (previousName) { + free(previousName); + } + return ret; + + }else{ + return -EPERM; + } +} + +int HostUAPI::uname(userptr utsname *buf) +{ + utsname unameBuf; + memset(&unameBuf, 0, sizeof(struct utsname)); + #ifndef FAKE_UNAME + strcpy(unameBuf.sysname, "FluxOS"); + if (hostName) { + strncpy(unameBuf.nodename, hostName, 65); + } else { + strncpy(unameBuf.nodename, "", 65); + } + strcpy(unameBuf.release, "0.1"); + strcpy(unameBuf.version, __DATE__); + strcpy(unameBuf.machine, UTSNAME_MACHINENAME); + if (domainName) { + strncpy(unameBuf.domainname, domainName, 65); + } else { + strncpy(unameBuf.domainname, "", 65); + } + #else + strcpy(unameBuf.sysname, "Linux"); + strncpy(unameBuf.nodename, "fakelinux", 65); + strcpy(unameBuf.release, "2.6.19-gentoo-r6"); + strcpy(unameBuf.version, "#1 SMP PREEMPT Tue Feb 6 19:10:56 CET 2007"); + strcpy(unameBuf.machine, "i686"); + strncpy(unameBuf.domainname, "", 65); + #endif + + memcpyToUser(buf, &unameBuf, sizeof(struct utsname)); + + return 0; +} diff --git a/pool/shard006/C++/0079508_myfile.cpp b/pool/shard006/C++/0079508_myfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6157e2934ebf80bb3e23fa118cc5fbc8653a59cc --- /dev/null +++ b/pool/shard006/C++/0079508_myfile.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code 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 code 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 in the LICENSE file that + * accompanied this code). + * + * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include +#include "MyCanvas.h" +#include "jawt_md.h" + +/* + * Class: MyCanvas + * Method: paint + * Signature: (Ljava/awt/Graphics;)V + */ + +extern "C" { + +JNIEXPORT void JNICALL Java_MyCanvas_paint +(JNIEnv* env, jobject canvas, jobject graphics) +{ + /* Get the AWT */ + JAWT awt; + awt.version = JAWT_VERSION_1_4; + if (JAWT_GetAWT(env, &awt) == JNI_FALSE) { + printf("AWT Not found\n"); + return; + } + + /* Lock the AWT */ + awt.Lock(env); + + /* Unlock the AWT */ + awt.Unlock(env); + + /* Get the drawing surface */ + JAWT_DrawingSurface* ds = awt.GetDrawingSurface(env, canvas); + if (ds == NULL) { + printf("NULL drawing surface\n"); + return; + } + + /* Lock the drawing surface */ + jint lock = ds->Lock(ds); + printf("Lock value %d\n", (int)lock); + if((lock & JAWT_LOCK_ERROR) != 0) { + printf("Error locking surface\n"); + return; + } + + /* Get the drawing surface info */ + JAWT_DrawingSurfaceInfo* dsi = ds->GetDrawingSurfaceInfo(ds); + if (dsi == NULL) { + printf("Error getting surface info\n"); + ds->Unlock(ds); + return; + } + + /* Get the platform-specific drawing info */ + JAWT_Win32DrawingSurfaceInfo* dsi_win = + (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; + + /* Now paint */ + PAINTSTRUCT ps; + /* Do not use the HDC returned from BeginPaint()!! */ + ::BeginPaint(dsi_win->hwnd, &ps); + HBRUSH hbrush = (HBRUSH)::GetStockObject(BLACK_BRUSH); + RECT rect; + rect.left = 5; + rect.top = 5; + rect.right = 95; + rect.bottom = 95; + ::FillRect(dsi_win->hdc, &rect, hbrush); + ::EndPaint(dsi_win->hwnd, &ps); + + jobject ref = awt.GetComponent(env, (void*)(dsi_win->hwnd)); + if (!env->IsSameObject(ref, canvas)) { + printf("Error! Different objects!\n"); + } + + /* Free the drawing surface info */ + ds->FreeDrawingSurfaceInfo(dsi); + + /* Unlock the drawing surface */ + ds->Unlock(ds); + + /* Free the drawing surface */ + awt.FreeDrawingSurface(ds); +} + +} diff --git a/pool/shard006/C++/0079522_ofx3dModelLoader.cpp b/pool/shard006/C++/0079522_ofx3dModelLoader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78bc5c3f7ec0cc96a19b1c23d0d6b99a9061e293 --- /dev/null +++ b/pool/shard006/C++/0079522_ofx3dModelLoader.cpp @@ -0,0 +1,91 @@ +#include "ofx3DModelLoader.h" + +//------------------------------------------- +static string getExtension( string filename ){ + std::string::size_type idx; + idx = filename.rfind('.'); + + if(idx != std::string::npos){ + return filename.substr(idx+1); + } + else{ + return ""; + } +} + +//------------------------------------------- +ofx3DModelLoader::ofx3DModelLoader(){ + numRotations = 0; + rotAngle.clear(); + rotAxis.clear(); + scale = ofPoint(1, 1, 1); + + model = NULL; +} + +//------------------------------------------ +void ofx3DModelLoader::loadModel(string modelName, float scale){ + if( model != NULL)delete model; + + string ext = getExtension( modelName ); + if( ext == "3ds" || ext == "3DS" ){ + model = new model3DS(); + ofLog(OF_LOG_VERBOSE, "ofx3DModelLoader: Loading Model " + modelName); + model->loadModel( modelName.c_str(), scale); + } + +} + +//------------------------------------------- +ofx3DModelLoader::~ofx3DModelLoader(){ + if( model != NULL )delete model; +} + +//------------------------------------------- +void ofx3DModelLoader::setPosition(float x, float y, float z){ + pos.x = x; + pos.y = y; + pos.z = z; +} + +void ofx3DModelLoader::setScale(float x, float y, float z){ + scale.x = x; + scale.y = y; + scale.z = z; +} + +//------------------------------------------- +void ofx3DModelLoader::setRotation(int which, float angle, float rot_x, float rot_y, float rot_z){ + + if(which + 1 > numRotations){ + int diff = 1 + (which - numRotations); + for(int i = 0; i < diff; i++){ + rotAngle.push_back(0); + rotAxis.push_back(ofPoint()); + } + numRotations = rotAngle.size(); + } + + rotAngle[which] = angle; + rotAxis[which].x = rot_x; + rotAxis[which].y = rot_y; + rotAxis[which].z = rot_z; +} + +//------------------------------------------- +void ofx3DModelLoader::draw(){ + glPushMatrix(); + glTranslatef(pos.x, pos.y, pos.z); + glScalef(scale.x, scale.y, scale.z); + for(int i = 0; i < numRotations; i++){ + glRotatef(rotAngle[i], rotAxis[i].x, rotAxis[i].y, rotAxis[i].z); + } + + glShadeModel(GL_SMOOTH); + if( model->hasTexture) + glEnable(GL_TEXTURE_2D); + model->draw(); + if( model->hasTexture) + glDisable(GL_TEXTURE_2D); + glPopMatrix(); +} diff --git a/pool/shard006/C++/0079527_singleton_libxml2.cpp b/pool/shard006/C++/0079527_singleton_libxml2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd4e39172156f4611108e43b879a29c9a4ac6438 --- /dev/null +++ b/pool/shard006/C++/0079527_singleton_libxml2.cpp @@ -0,0 +1,89 @@ + +#include "singleton_libxml2.hpp" + +#include +#include +#include +#include +#include + +using namespace lexstat; + +#ifdef _MSC_VER +#define COMPARE(a, b) (!stricmp((a), (b))) +#else +#define COMPARE(a, b) (!strcasecmp((a), (b))) +#endif + +#define PATTERN_TAG "p" + +SingletonLibxml2* SingletonLibxml2::m_pInstance = NULL; + +typedef struct TagContext { + TagContext(): addtag(false) { } + bool addtag; + std::string content; +} TAG_CONTEXT; + +static void StartElement(void *ctx, const xmlChar *name, const xmlChar **atts) { + TAG_CONTEXT* tagctx = (TAG_CONTEXT*) ctx; + if (COMPARE((char *)name, PATTERN_TAG)) { + // tagctx->content = ""; + tagctx->addtag = true; + } +} + +static void EndElement(void *ctx, const xmlChar *name) { + TAG_CONTEXT* tagctx = (TAG_CONTEXT*) ctx; + if (COMPARE((char *)name, PATTERN_TAG)) { + tagctx->addtag = false; + } +} + +static void handleCharacters(TAG_CONTEXT* tagctx, const xmlChar* ch, int len) { + if (tagctx->addtag) { + tagctx->content.append((char *)ch, len); + tagctx->content.append(1, ' '); + } +} + +static void Characters(void* ctx, const xmlChar* ch, int len) { + TAG_CONTEXT* tagctx = (TAG_CONTEXT*) ctx; + handleCharacters(tagctx, ch, len); +} + +static htmlSAXHandler _saxHandler = { + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, StartElement, EndElement, NULL, Characters, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL +}; + +SingletonLibxml2::MemRelease SingletonLibxml2::m_MemRelease; + +SingletonLibxml2::SingletonLibxml2() { +} + +SingletonLibxml2::~SingletonLibxml2() { +} + +int SingletonLibxml2::GetExtract(const char* html, const int htmlsiz, + char** pext, int* pextsiz) { + if (!pext || !pextsiz) { + fprintf(stderr, "%s:%d input invalid!\n", __FILE__, __LINE__); + return -1; + } + + TAG_CONTEXT tagctx; + htmlParserCtxtPtr ctxt = htmlCreatePushParserCtxt( + &_saxHandler, &tagctx, "", 0, "", XML_CHAR_ENCODING_NONE); + htmlParseChunk(ctxt, html, htmlsiz, 0); + htmlParseChunk(ctxt, "", 0, 1); + if ((*pextsiz = tagctx.content.length()) > 0) { + *pext = strdup(tagctx.content.data()); + } else { + *pext = NULL; + } + htmlFreeParserCtxt(ctxt); + return 0; +} + diff --git a/pool/shard006/C++/0079528_cl_menu.cpp b/pool/shard006/C++/0079528_cl_menu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd4e84a8d8f86f43017257101dfd15b7e6160410 --- /dev/null +++ b/pool/shard006/C++/0079528_cl_menu.cpp @@ -0,0 +1,117 @@ +/** + * @file + * @brief Client menu functions. + */ + +/* +Copyright (C) 2002-2011 UFO: Alien Invasion. + +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 "cl_menu.h" +#include "cl_shared.h" +#include "input/cl_keys.h" +#include "ui/ui_main.h" +#include "ui/ui_input.h" +#include "ui/ui_nodes.h" +#include "ui/ui_popup.h" +#include "ui/node/ui_node_abstractnode.h" + +static inline void CLMN_AddBindings (linkedList_t **list, char **bindings) +{ + int i; + for (i = K_FIRST_KEY; i < K_LAST_KEY; i++) + if (bindings[i] && bindings[i][0] != '\0') { + const char *binding = Cmd_GetCommandDesc(bindings[i]); + if (binding != NULL && binding[0] != '\0') + binding = _(binding); + LIST_AddString(list, va("%s\t%s", Key_KeynumToString(i), binding)); + } +} + +/** + * @brief Adds UI Keybindings to the list for the Keylist UI + * @param[in,out] list Linked list of strings to add to + */ +static inline void CLMN_AddUIBindings (linkedList_t **list) +{ + int i; + + for (i = 0; i < UI_GetKeyBindingCount(); i++) { + const uiKeyBinding_t* binding = UI_GetKeyBindingByIndex(i); + + if (binding == NULL) + continue; + if (binding->inherited) + continue; + if (!Q_strvalid(binding->description)) + continue; + + LIST_AddString(list, va("%s\t%s", Key_KeynumToString(binding->key), _(binding->description))); + } +} + +/** + * @brief Prints a list of tab and newline separated string to keylist char array that hold the key and the command desc + */ +static void CLMN_InitKeyList_f (void) +{ + linkedList_t *list = NULL; + + LIST_AddString(&list, _("^BGlobal bindings")); + LIST_AddString(&list, ""); + CLMN_AddBindings(&list, keyBindings); + LIST_AddString(&list, ""); + LIST_AddString(&list, ""); + LIST_AddString(&list, _("^BMenu bindings")); + LIST_AddString(&list, ""); + CLMN_AddBindings(&list, menuKeyBindings); + CLMN_AddUIBindings(&list); + LIST_AddString(&list, ""); + LIST_AddString(&list, ""); + LIST_AddString(&list, _("^BBattlescape bindings")); + LIST_AddString(&list, ""); + CLMN_AddBindings(&list, battleKeyBindings); + + UI_RegisterLinkedListText(TEXT_LIST, list); +} + +static void CLMN_Mods_f (void) +{ + linkedList_t *mods = NULL; + FS_GetModList(&mods); + while (mods) { + Cbuf_AddText(va("mn_mods_result %s\n", (char*)mods->data)); + mods = mods->next; + } +} + +/** + * @brief Initialize the menu data hunk, add cvars and commands + * @note This function is called once + * @sa MN_Shutdown + * @sa CL_InitLocal + */ +void CLMN_InitStartup (void) +{ + /* print the keyBindings to mn.menuText */ + Cmd_AddCommand("mn_init_keylist", CLMN_InitKeyList_f); + Cmd_AddCommand("mn_mods", CLMN_Mods_f); + + UI_Init(); +} diff --git a/pool/shard006/C++/0079531_pspParticleSystemsManager.cpp b/pool/shard006/C++/0079531_pspParticleSystemsManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d9ed925a101055581f245e31b969a8a6c29421d --- /dev/null +++ b/pool/shard006/C++/0079531_pspParticleSystemsManager.cpp @@ -0,0 +1,254 @@ +// +// pspParticleSystemsManager.cpp +// psPsa-001 +// +// Created by Andre Perrotta on 22/11/14. +// +// + +#include "pspParticleSystemsManager.h" + +using namespace std; + +pspParticleSystemsManager::pspParticleSystemsManager(){ + setup(); +} + +pspParticleSystemsManager::~pspParticleSystemsManager(){ + if(pSystems){ + while(!pSystems->empty()){ + delete pSystems->back(); + pSystems->pop_back(); + } + delete pSystems; + } + + if(pSystemsToDelete){ + clearDeleteQ(); + delete pSystemsToDelete; + } + + + if(concertRoom){ + delete concertRoom; + } + + + + +} + +void pspParticleSystemsManager::setup(){ + + oscSender = new UdpTransmitSocket(IpEndpointName(DEFAULT_OSC_SENDER_IP, DEFAULT_OSC_SENDER_PORT)); + + + pSystems = new vector(); + pSystemsToDelete = new vector(); + concertRoom = new ConcertRoom(); + + createColorVector(); + + /* + for(int i=0; i<1; i++){ + addSystem("generic", 1); + } + for(int i=0; i<1; i++){ + addSystem("random", 1); + } + */ + + //cout<size(); +} +void pspParticleSystemsManager::update(){ + if(pSystems){ + for(int i=0; isize(); i++){ + (*pSystems)[i]->update(); + } + } + moveSystemToDeleteQ(); + clearDeleteQ(); +} +void pspParticleSystemsManager::draw(){ + if(pSystems){ + for(int i=0; isize(); i++){ + (*pSystems)[i]->draw(); + } + } + + concertRoom->draw(); +} + + +int pspParticleSystemsManager::getNumSystems(){ + if(pSystems != NULL){ + return pSystems->size(); + } + return 0; +} + +int pspParticleSystemsManager::getNumActiveSystems(){ + if(pSystems != NULL){ + int counter = 0; + for(int i=0; isize(); i++){ + if(!(*pSystems)[i]->getDeleteFlag()){ + counter++; + } + } + return counter; + } + return 0; +} + +void pspParticleSystemsManager::debug(){ + cout<* pspParticleSystemsManager::getSystems(){ + if(pSystems != nullptr){ + return pSystems; + } + pSystems = new vector(); + return pSystems; + +} + +String pspParticleSystemsManager::getSystemName(int s){ + if(pSystems != nullptr){ + if(pSystems->size() > s){ + return (*pSystems)[s]->getName(); + } + } + return "nosystemtocall"; +} +String pspParticleSystemsManager::getSystemType(int s){ + if(pSystems != nullptr){ + if(pSystems->size() > s){ + return (*pSystems)[s]->getType(); + } + } + return "nosystemtocall"; +} + + +void pspParticleSystemsManager::addSystem(juce::String type, int np){ + + if(pSystems == nullptr){ + pSystems = new vector(); + } + + int lastIndex = pSystems->size(); + + if(type == "generic"){ + pSystems->push_back(new pspParticleSystem(this, String(lastIndex + 1), np)); + } + else if(type == "random"){ + pSystems->push_back(new pspRandomSystem(this, String(lastIndex + 1), np)); + } + + pSystems->back()->setColor(colors[colorIndex]); + pSystems->back()->showGui(); + incrementColorIndex(); + + +} + +void pspParticleSystemsManager::deleteSystem(int s){ + if(pSystems != nullptr){ + if(s >= 0 && s < pSystems->size()){ + (*pSystems)[s]->setDeleteFlag(true); + } + } +} + +void pspParticleSystemsManager::moveSystemToDeleteQ(){ + if(pSystems){ + for(int i=0; isize(); i++){ + if((*pSystems)[i]->getDeleteFlag()){ + pSystemsToDelete->push_back((*pSystems)[i]); + pSystems->erase(pSystems->begin() + i); + } + } + } +} + +void pspParticleSystemsManager::clearDeleteQ(){ + if(pSystemsToDelete){ + while(!pSystemsToDelete->empty()){ + delete pSystemsToDelete->back(); + pSystemsToDelete->pop_back(); + } + //delete pSystemsToDelete; + } +} + +pspParticleSystem* pspParticleSystemsManager::getSystem(int s){ + if(pSystems != nullptr){ + if(pSystems->size() > s){ + return (*pSystems)[s]; + } + return (*pSystems->begin()); + } + pSystems = new vector(); + return (*pSystems->begin()); +} + +ConcertRoom* pspParticleSystemsManager::getConcertRoom(){ + return concertRoom; +} + +int pspParticleSystemsManager::getNumSpeakers(){ + if(concertRoom != nullptr){ + return concertRoom->getNumSpeakers(); + } + return 0; +} + +void pspParticleSystemsManager::createColorVector(){ + colorIndex = 0; + + colors.push_back(Colours::tomato); + colors.push_back(Colours::coral); + colors.push_back(Colours::cornflowerblue); + colors.push_back(Colours::darkred); + colors.push_back(Colours::firebrick); + colors.push_back(Colours::forestgreen); + colors.push_back(Colours::khaki); + colors.push_back(Colours::lemonchiffon); + colors.push_back(Colours::lightsalmon); + colors.push_back(Colours::lightyellow); + colors.push_back(Colours::maroon); + colors.push_back(Colours::darkseagreen); + colors.push_back(Colours::darkblue); + colors.push_back(Colours::lavenderblush); + colors.push_back(Colours::mediumaquamarine); + colors.push_back(Colours::plum); + colors.push_back(Colours::springgreen); + colors.push_back(Colours::sienna); + colors.push_back(Colours::seashell); + colors.push_back(Colours::steelblue); + colors.push_back(Colours::aliceblue); +} + +void pspParticleSystemsManager::incrementColorIndex(){ + colorIndex++; + if(colorIndex >= colors.size()){ + colorIndex = 0; + } +} + +void pspParticleSystemsManager::showPsystemGui(int ps){ + if(pSystems != nullptr){ + if(ps >= 0 && ps < pSystems->size()){ + (*pSystems)[ps]->showGui(); + } + } +} + +UdpTransmitSocket* pspParticleSystemsManager::getOscSender(){ + if(oscSender != nullptr){ + return oscSender; + } + + return new UdpTransmitSocket(IpEndpointName(DEFAULT_OSC_SENDER_IP, DEFAULT_OSC_SENDER_PORT)); +} diff --git a/pool/shard006/C++/0079534_blend.cpp b/pool/shard006/C++/0079534_blend.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d117950de814ba365ba9f518b116d08fa2d689a --- /dev/null +++ b/pool/shard006/C++/0079534_blend.cpp @@ -0,0 +1,83 @@ +#include "venus/blend.h" +#include "venus/colorspace.h" +#include "venus/scalar.h" + +namespace venus { + +uint32_t mix(const uint32_t& from, const uint32_t& to, float amount) +{ + assert(0 <= amount && amount <= 1.0F); + uint8_t _0 = lerp((from ) & 0xFF, (to ) & 0xFF, amount); + uint8_t _1 = lerp((from >> 8) & 0xFF, (to >> 8) & 0xFF, amount); + uint8_t _2 = lerp((from >> 16) & 0xFF, (to >> 16) & 0xFF, amount); +// uint8_t _3 = lerp((from >> 24) & 0xFF, (to >> 24) & 0xFF, amount); +// return _0 | (_1 << 8) | (_2 << 16) || (_3 << 24); + return _0 | (_1 << 8) | (_2 << 16) || (from & 0xFF000000); +} + +cv::Vec3b mix(const cv::Vec3b& from, const cv::Vec3b& to, float amount) +{ + cv::Vec3b result; + int a = cvRound(255 * amount); + int l_a = 255 - a; + + for(int i = 0; i < 3; ++i) + result[i] = (from[i] * l_a + to[i] * a + 127) / 255; + return result; +} + +cv::Vec3f mix(const cv::Vec3f& from, const cv::Vec3f& to, float amount) +{ + cv::Vec3f result; + float l_amount = 1.0F - amount; + for(int i = 0; i < 3; ++i) + result[i] = from[i] * l_amount + to[i] * amount; + return result; +} + +cv::Vec4b mix(const cv::Vec4b& from, const cv::Vec4b& to, float amount) +{ + cv::Vec4b result; + int a = cvRound(to[3] * amount); + int l_a = 255 - a; + + for(int i = 0; i < 3; ++i) + result[i] = (from[i] * l_a + to[i] * a + 127) / 255; + result[3] = from[3]; + return result; +} + +cv::Vec4f mix(const cv::Vec4f& from, const cv::Vec4f& to, float amount) +{ + cv::Vec4f result; + float a = to[3] * amount; + float l_a = 1.0F - a; + + for(int i = 0; i < 3; ++i) + result[i] = (from[i] * l_a + to[i] * a); + result[3] = from[3]; + return result; +} + +#define blendHSL(i) \ + float hslA[3], hslB[3]; \ + rgb2hsl(rgbA, hslA); \ + rgb2hsl(rgbB, hslB); \ + hslA[i] = hslB[i]; \ + hsl2rgb(hslA, target); \ + + +void blendHue (float* target, const float* rgbA, const float* rgbB) { blendHSL(0) } +void blendSaturation(float* target, const float* rgbA, const float* rgbB) { blendHSL(1) } +void blendLuminosity(float* target, const float* rgbA, const float* rgbB) { blendHSL(2) } +void blendColor (float* target, const float* rgbA, const float* rgbB) +{ + float hslA[3], hslB[3]; + rgb2hsl(rgbA, hslA); + rgb2hsl(rgbB, hslB); + hslB[0] = hslA[0]; + hslB[1] = hslA[1]; + hsl2rgb(hslB, target); +} + +} /* namespace venus */ diff --git a/pool/shard006/C++/0079536_persistent_store_impl.cpp b/pool/shard006/C++/0079536_persistent_store_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29b4653b3eac0aa7f4427e3333fed31ebdf27655 --- /dev/null +++ b/pool/shard006/C++/0079536_persistent_store_impl.cpp @@ -0,0 +1,50 @@ +#if defined(__MK64FX512__) || defined(__MK66FX1M0__) + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(EEPROM_SETTINGS) + +#include "../shared/persistent_store_api.h" + +namespace HAL { +namespace PersistentStore { + +bool access_start() { return true; } +bool access_finish() { return true; } + +bool write_data(int &pos, const uint8_t *value, uint16_t size, uint16_t *crc) { + while (size--) { + uint8_t * const p = (uint8_t * const)pos; + uint8_t v = *value; + // EEPROM has only ~100,000 write cycles, + // so only write bytes that have changed! + if (v != eeprom_read_byte(p)) { + eeprom_write_byte(p, v); + if (eeprom_read_byte(p) != v) { + SERIAL_ECHO_MSG(MSG_ERR_EEPROM_WRITE); + return true; + } + } + crc16(crc, &v, 1); + pos++; + value++; + }; + return false; +} + +bool read_data(int &pos, uint8_t* value, uint16_t size, uint16_t *crc, const bool writing/*=true*/) { + do { + uint8_t c = eeprom_read_byte((uint8_t*)pos); + if (writing) *value = c; + crc16(crc, &c, 1); + pos++; + value++; + } while (--size); + return false; +} + +} // PersistentStore +} // HAL + +#endif // EEPROM_SETTINGS +#endif // __MK64FX512__ || __MK66FX1M0__ diff --git a/pool/shard006/C++/0079538_mouse_wheel_phase_handler.cc b/pool/shard006/C++/0079538_mouse_wheel_phase_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5dcae9a259d32fe82251f77c046f04797d57a9a --- /dev/null +++ b/pool/shard006/C++/0079538_mouse_wheel_phase_handler.cc @@ -0,0 +1,255 @@ +// 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 "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" + +#include "base/bind.h" +#include "base/trace_event/trace_event.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/browser/renderer_host/render_widget_host_input_event_router.h" +#include "content/browser/renderer_host/render_widget_host_view_base.h" +#include "ui/events/base_event_utils.h" + +namespace content { +MouseWheelPhaseHandler::MouseWheelPhaseHandler( + RenderWidgetHostViewBase* const host_view) + : host_view_(host_view), + mouse_wheel_end_dispatch_timeout_(kDefaultMouseWheelLatchingTransaction), + touchpad_scroll_phase_state_(TOUCHPAD_SCROLL_STATE_UNKNOWN) {} + +void MouseWheelPhaseHandler::AddPhaseIfNeededAndScheduleEndEvent( + blink::WebMouseWheelEvent& mouse_wheel_event, + bool should_route_event) { + + bool has_phase = + mouse_wheel_event.phase != blink::WebMouseWheelEvent::kPhaseNone || + mouse_wheel_event.momentum_phase != blink::WebMouseWheelEvent::kPhaseNone; + TRACE_EVENT2("input", + "MouseWheelPhaseHandler::AddPhaseIfNeededAndScheduleEndEvent", + "has_phase", has_phase, "touchpad_scroll_phase_state", + touchpad_scroll_phase_state_); + + if (has_phase) { + if (mouse_wheel_event.phase == blink::WebMouseWheelEvent::kPhaseEnded) { + // If the momentum_phase is anything other than blocked, don't send the + // wheel end event immediately, start a timer instead to see whether + // momentum phase of the scrolling starts or not. If momentum_phase is + // blocked, that means that momentum scrolling events are not coming + // next (i.e. preparing for a pinch, maybe), so end immediately. + if (mouse_wheel_event.momentum_phase == + blink::WebMouseWheelEvent::kPhaseBlocked) { + SendSyntheticWheelEventWithPhaseEnded(should_route_event); + } else { + ScheduleMouseWheelEndDispatching( + should_route_event, + max_time_between_phase_ended_and_momentum_phase_began()); + } + } else if (mouse_wheel_event.phase == + blink::WebMouseWheelEvent::kPhaseBegan) { + // A new scrolling sequence has started, send the pending wheel end + // event to end the previous scrolling sequence. + DispatchPendingWheelEndEvent(); + } else if (mouse_wheel_event.momentum_phase == + blink::WebMouseWheelEvent::kPhaseBegan) { + // Momentum phase has started, drop the pending wheel end event to make + // sure that no wheel end event will be sent during the momentum phase + // of scrolling. + IgnorePendingWheelEndEvent(); + } + } else { // !has_phase + switch (touchpad_scroll_phase_state_) { + case TOUCHPAD_SCROLL_STATE_UNKNOWN: { + mouse_wheel_event.has_synthetic_phase = true; + // Break the latching when the location difference between the current + // and the initial wheel event positions exceeds the maximum allowed + // threshold or when the event modifiers have changed. + if (!IsWithinSlopRegion(mouse_wheel_event) || + HasDifferentModifiers(mouse_wheel_event) || + ShouldBreakLatchingDueToDirectionChange(mouse_wheel_event)) { + DispatchPendingWheelEndEvent(); + } + + if (!mouse_wheel_end_dispatch_timer_.IsRunning()) { + mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; + first_wheel_location_ = + gfx::Vector2dF(mouse_wheel_event.PositionInWidget().x(), + mouse_wheel_event.PositionInWidget().y()); + initial_wheel_event_ = mouse_wheel_event; + first_scroll_update_ack_state_ = + FirstScrollUpdateAckState::kNotArrived; + ScheduleMouseWheelEndDispatching(should_route_event, + mouse_wheel_end_dispatch_timeout_); + } else { // mouse_wheel_end_dispatch_timer_.IsRunning() + bool non_zero_delta = + mouse_wheel_event.delta_x || mouse_wheel_event.delta_y; + mouse_wheel_event.phase = + non_zero_delta ? blink::WebMouseWheelEvent::kPhaseChanged + : blink::WebMouseWheelEvent::kPhaseStationary; + mouse_wheel_end_dispatch_timer_.Reset(); + } + break; + } + case TOUCHPAD_SCROLL_MAY_BEGIN: + mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; + touchpad_scroll_phase_state_ = TOUCHPAD_SCROLL_IN_PROGRESS; + break; + case TOUCHPAD_SCROLL_IN_PROGRESS: + mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseChanged; + break; + default: + NOTREACHED(); + } + } + + last_mouse_wheel_event_ = mouse_wheel_event; +} + +void MouseWheelPhaseHandler::DispatchPendingWheelEndEvent() { + if (!mouse_wheel_end_dispatch_timer_.IsRunning()) + return; + + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler Dispatched", + TRACE_EVENT_SCOPE_THREAD); + mouse_wheel_end_dispatch_timer_.FireNow(); +} + +void MouseWheelPhaseHandler::IgnorePendingWheelEndEvent() { + if (!mouse_wheel_end_dispatch_timer_.IsRunning()) + return; + + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler Ignored", + TRACE_EVENT_SCOPE_THREAD); + mouse_wheel_end_dispatch_timer_.Stop(); +} + +void MouseWheelPhaseHandler::ResetTouchpadScrollSequence() { + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler Reset", + TRACE_EVENT_SCOPE_THREAD); + touchpad_scroll_phase_state_ = TOUCHPAD_SCROLL_STATE_UNKNOWN; +} + +void MouseWheelPhaseHandler::SendWheelEndForTouchpadScrollingIfNeeded( + bool should_route_event) { + if (touchpad_scroll_phase_state_ == TOUCHPAD_SCROLL_IN_PROGRESS) { + RenderWidgetHostImpl* widget_host = host_view_->host(); + if (!widget_host) { + ResetTouchpadScrollSequence(); + return; + } + + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler Sent touchpad end", + TRACE_EVENT_SCOPE_THREAD); + SendSyntheticWheelEventWithPhaseEnded(should_route_event); + } + + ResetTouchpadScrollSequence(); +} + +void MouseWheelPhaseHandler::TouchpadScrollingMayBegin() { + // End the timer-based wheel scroll sequence before starting a touchpad scroll + // sequence. + if (mouse_wheel_end_dispatch_timer_.IsRunning()) { + DCHECK_EQ(TOUCHPAD_SCROLL_STATE_UNKNOWN, touchpad_scroll_phase_state_); + DispatchPendingWheelEndEvent(); + } + + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler May Begin", + TRACE_EVENT_SCOPE_THREAD); + touchpad_scroll_phase_state_ = TOUCHPAD_SCROLL_MAY_BEGIN; +} + +void MouseWheelPhaseHandler::SendSyntheticWheelEventWithPhaseEnded( + bool should_route_event) { + TRACE_EVENT0("input", + "MouseWheelPhaseHandler::SendSyntheticWheelEventWithPhaseEnded"); + last_mouse_wheel_event_.SetTimeStamp(ui::EventTimeForNow()); + last_mouse_wheel_event_.delta_x = 0; + last_mouse_wheel_event_.delta_y = 0; + last_mouse_wheel_event_.wheel_ticks_x = 0; + last_mouse_wheel_event_.wheel_ticks_y = 0; + last_mouse_wheel_event_.phase = blink::WebMouseWheelEvent::kPhaseEnded; + last_mouse_wheel_event_.dispatch_type = + blink::WebInputEvent::DispatchType::kEventNonBlocking; + + if (should_route_event) { + RenderWidgetHostImpl* widget_host = host_view_->host(); + if (!widget_host || !widget_host->delegate() || + !widget_host->delegate()->GetInputEventRouter()) + return; + + widget_host->delegate()->GetInputEventRouter()->RouteMouseWheelEvent( + host_view_, &last_mouse_wheel_event_, + ui::LatencyInfo(ui::SourceEventType::WHEEL)); + } else { + host_view_->ProcessMouseWheelEvent( + last_mouse_wheel_event_, ui::LatencyInfo(ui::SourceEventType::WHEEL)); + } +} + +void MouseWheelPhaseHandler::ScheduleMouseWheelEndDispatching( + bool should_route_event, + const base::TimeDelta timeout) { + TRACE_EVENT_INSTANT0("input", "MouseWheelPhaseHandler timer started", + TRACE_EVENT_SCOPE_THREAD); + mouse_wheel_end_dispatch_timer_.Start( + FROM_HERE, timeout, + base::BindOnce( + &MouseWheelPhaseHandler::SendSyntheticWheelEventWithPhaseEnded, + base::Unretained(this), should_route_event)); +} + +bool MouseWheelPhaseHandler::IsWithinSlopRegion( + const blink::WebMouseWheelEvent& wheel_event) const { + // This function is called to check if breaking timer-based wheel scroll + // latching sequence is needed or not, and timer-based wheel scroll latching + // happens only when scroll state is unknown. + DCHECK(touchpad_scroll_phase_state_ == TOUCHPAD_SCROLL_STATE_UNKNOWN); + gfx::Vector2dF current_wheel_location(wheel_event.PositionInWidget().x(), + wheel_event.PositionInWidget().y()); + return (current_wheel_location - first_wheel_location_).LengthSquared() < + kWheelLatchingSlopRegion * kWheelLatchingSlopRegion; +} + +bool MouseWheelPhaseHandler::HasDifferentModifiers( + const blink::WebMouseWheelEvent& wheel_event) const { + // This function is called to check if breaking timer-based wheel scroll + // latching sequence is needed or not, and timer-based wheel scroll latching + // happens only when scroll state is unknown. + DCHECK(touchpad_scroll_phase_state_ == TOUCHPAD_SCROLL_STATE_UNKNOWN); + return wheel_event.GetModifiers() != initial_wheel_event_.GetModifiers(); +} + +bool MouseWheelPhaseHandler::ShouldBreakLatchingDueToDirectionChange( + const blink::WebMouseWheelEvent& wheel_event) const { + // This function is called to check if breaking timer-based wheel scroll + // latching sequence is needed or not, and timer-based wheel scroll latching + // happens only when scroll state is unknown. + DCHECK(touchpad_scroll_phase_state_ == TOUCHPAD_SCROLL_STATE_UNKNOWN); + if (first_scroll_update_ack_state_ != FirstScrollUpdateAckState::kNotConsumed) + return false; + + bool consistent_x_direction = + (wheel_event.delta_x == 0 && initial_wheel_event_.delta_x == 0) || + wheel_event.delta_x * initial_wheel_event_.delta_x > 0; + bool consistent_y_direction = + (wheel_event.delta_y == 0 && initial_wheel_event_.delta_y == 0) || + wheel_event.delta_y * initial_wheel_event_.delta_y > 0; + return !consistent_x_direction || !consistent_y_direction; +} + +void MouseWheelPhaseHandler::GestureEventAck( + const blink::WebGestureEvent& event, + blink::mojom::InputEventResultState ack_result) { + if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollUpdate || + first_scroll_update_ack_state_ != + FirstScrollUpdateAckState::kNotArrived) { + return; + } + if (ack_result == blink::mojom::InputEventResultState::kConsumed) + first_scroll_update_ack_state_ = FirstScrollUpdateAckState::kConsumed; + else + first_scroll_update_ack_state_ = FirstScrollUpdateAckState::kNotConsumed; +} + +} // namespace content diff --git a/pool/shard006/C++/0079539_DominanceFrontier.cpp b/pool/shard006/C++/0079539_DominanceFrontier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ba91bc90dfc2184aaaed5239bf41f827ac33163 --- /dev/null +++ b/pool/shard006/C++/0079539_DominanceFrontier.cpp @@ -0,0 +1,57 @@ +//===- DominanceFrontier.cpp - Dominance Frontier Calculation -------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Analysis/DominanceFrontier.h" +#include "llvm/Analysis/DominanceFrontierImpl.h" + +using namespace llvm; + +namespace llvm { +template class DominanceFrontierBase; +template class ForwardDominanceFrontierBase; +} + +char DominanceFrontier::ID = 0; + +INITIALIZE_PASS_BEGIN(DominanceFrontier, "domfrontier", + "Dominance Frontier Construction", true, true) +INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) +INITIALIZE_PASS_END(DominanceFrontier, "domfrontier", + "Dominance Frontier Construction", true, true) + +DominanceFrontier::DominanceFrontier() + : FunctionPass(ID), + Base() { + initializeDominanceFrontierPass(*PassRegistry::getPassRegistry()); +} + +void DominanceFrontier::releaseMemory() { + Base.releaseMemory(); +} + +bool DominanceFrontier::runOnFunction(Function &) { + releaseMemory(); + Base.analyze(getAnalysis().getDomTree()); + return false; +} + +void DominanceFrontier::getAnalysisUsage(AnalysisUsage &AU) const { + AU.setPreservesAll(); + AU.addRequired(); +} + +void DominanceFrontier::print(raw_ostream &OS, const Module *) const { + Base.print(OS); +} + +#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) +void DominanceFrontier::dump() const { + print(dbgs()); +} +#endif diff --git a/pool/shard006/C++/0079555_ConstructBinaryTree.cpp b/pool/shard006/C++/0079555_ConstructBinaryTree.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d723debc4b61aeec8572d5607af9bd6a6070771d --- /dev/null +++ b/pool/shard006/C++/0079555_ConstructBinaryTree.cpp @@ -0,0 +1,219 @@ +/******************************************************************* +Copyright(c) 2016, Harry He +All rights reserved. + +Distributed under the BSD license. +(See accompanying file LICENSE.txt at +https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt) +*******************************************************************/ + +//================================================================== +// ¡¶½£Ö¸Offer¡ª¡ªÃûÆóÃæÊÔ¹Ù¾«½²µäÐͱà³ÌÌâ¡·´úÂë +// ×÷ÕߣººÎº£ÌÎ +//================================================================== + +// ÃæÊÔÌâ7£ºÖؽ¨¶þ²æÊ÷ +// ÌâÄ¿£ºÊäÈëij¶þ²æÊ÷µÄǰÐò±éÀúºÍÖÐÐò±éÀúµÄ½á¹û£¬ÇëÖØ½¨³ö¸Ã¶þ²æÊ÷¡£¼ÙÉèÊä +// ÈëµÄǰÐò±éÀúºÍÖÐÐò±éÀúµÄ½á¹ûÖж¼²»º¬Öظ´µÄÊý×Ö¡£ÀýÈçÊäÈëǰÐò±éÀúÐòÁÐ{1, +// 2, 4, 7, 3, 5, 6, 8}ºÍÖÐÐò±éÀúÐòÁÐ{4, 7, 2, 1, 5, 3, 8, 6}£¬ÔòÖØ½¨³ö +// ͼ2.6ËùʾµÄ¶þ²æÊ÷²¢Êä³öËüµÄÍ·½áµã¡£ + +#include "..\Utilities\BinaryTree.h" +#include +#include + +BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder); + +BinaryTreeNode* Construct(int* preorder, int* inorder, int length) +{ + if(preorder == nullptr || inorder == nullptr || length <= 0) + return nullptr; + + return ConstructCore(preorder, preorder + length - 1, + inorder, inorder + length - 1); +} + +BinaryTreeNode* ConstructCore +( + int* startPreorder, int* endPreorder, + int* startInorder, int* endInorder +) +{ + // ǰÐò±éÀúÐòÁеĵÚÒ»¸öÊý×ÖÊǸù½áµãµÄÖµ + int rootValue = startPreorder[0]; + BinaryTreeNode* root = new BinaryTreeNode(); + root->m_nValue = rootValue; + root->m_pLeft = root->m_pRight = nullptr; + + if(startPreorder == endPreorder) + { + if(startInorder == endInorder && *startPreorder == *startInorder) + return root; + else + throw std::exception("Invalid input."); + } + + // ÔÚÖÐÐò±éÀúÖÐÕÒµ½¸ù½áµãµÄÖµ + int* rootInorder = startInorder; + while(rootInorder <= endInorder && *rootInorder != rootValue) + ++ rootInorder; + + if(rootInorder == endInorder && *rootInorder != rootValue) + throw std::exception("Invalid input."); + + int leftLength = rootInorder - startInorder; + int* leftPreorderEnd = startPreorder + leftLength; + if(leftLength > 0) + { + // ¹¹½¨×ó×ÓÊ÷ + root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, + startInorder, rootInorder - 1); + } + if(leftLength < endPreorder - startPreorder) + { + // ¹¹½¨ÓÒ×ÓÊ÷ + root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, + rootInorder + 1, endInorder); + } + + return root; +} + +// ====================²âÊÔ´úÂë==================== +void Test(char* testName, int* preorder, int* inorder, int length) +{ + if(testName != nullptr) + printf("%s begins:\n", testName); + + printf("The preorder sequence is: "); + for(int i = 0; i < length; ++ i) + printf("%d ", preorder[i]); + printf("\n"); + + printf("The inorder sequence is: "); + for(int i = 0; i < length; ++ i) + printf("%d ", inorder[i]); + printf("\n"); + + try + { + BinaryTreeNode* root = Construct(preorder, inorder, length); + PrintTree(root); + + DestroyTree(root); + } + catch(std::exception& exception) + { + printf("Invalid Input.\n"); + } +} + +// ÆÕͨ¶þ²æÊ÷ +// 1 +// / \ +// 2 3 +// / / \ +// 4 5 6 +// \ / +// 7 8 +void Test1() +{ + const int length = 8; + int preorder[length] = {1, 2, 4, 7, 3, 5, 6, 8}; + int inorder[length] = {4, 7, 2, 1, 5, 3, 8, 6}; + + Test("Test1", preorder, inorder, length); +} + +// ËùÓнáµã¶¼Ã»ÓÐÓÒ×Ó½áµã +// 1 +// / +// 2 +// / +// 3 +// / +// 4 +// / +// 5 +void Test2() +{ + const int length = 5; + int preorder[length] = {1, 2, 3, 4, 5}; + int inorder[length] = {5, 4, 3, 2, 1}; + + Test("Test2", preorder, inorder, length); +} + +// ËùÓнáµã¶¼Ã»ÓÐ×ó×Ó½áµã +// 1 +// \ +// 2 +// \ +// 3 +// \ +// 4 +// \ +// 5 +void Test3() +{ + const int length = 5; + int preorder[length] = {1, 2, 3, 4, 5}; + int inorder[length] = {1, 2, 3, 4, 5}; + + Test("Test3", preorder, inorder, length); +} + +// Ê÷ÖÐÖ»ÓÐÒ»¸ö½áµã +void Test4() +{ + const int length = 1; + int preorder[length] = {1}; + int inorder[length] = {1}; + + Test("Test4", preorder, inorder, length); +} + +// ÍêÈ«¶þ²æÊ÷ +// 1 +// / \ +// 2 3 +// / \ / \ +// 4 5 6 7 +void Test5() +{ + const int length = 7; + int preorder[length] = {1, 2, 4, 5, 3, 6, 7}; + int inorder[length] = {4, 2, 5, 1, 6, 3, 7}; + + Test("Test5", preorder, inorder, length); +} + +// ÊäÈë¿ÕÖ¸Õë +void Test6() +{ + Test("Test6", nullptr, nullptr, 0); +} + +// ÊäÈëµÄÁ½¸öÐòÁв»Æ¥Åä +void Test7() +{ + const int length = 7; + int preorder[length] = {1, 2, 4, 5, 3, 6, 7}; + int inorder[length] = {4, 2, 8, 1, 6, 3, 7}; + + Test("Test7: for unmatched input", preorder, inorder, length); +} + +int main(int argc, char* argv[]) +{ + Test1(); + Test2(); + Test3(); + Test4(); + Test5(); + Test6(); + Test7(); + + return 0; +} + diff --git a/pool/shard006/C++/0079557_perf_protobuf_io.cc b/pool/shard006/C++/0079557_perf_protobuf_io.cc new file mode 100644 index 0000000000000000000000000000000000000000..c8c80105efcb31a72b32b418ff66e301d4ef1c2a --- /dev/null +++ b/pool/shard006/C++/0079557_perf_protobuf_io.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2012 The Chromium OS 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 "perf_protobuf_io.h" + +#include + +#include "base/logging.h" + +#include "file_utils.h" + +namespace quipper { + +bool SerializeFromString(const string& contents, + PerfDataProto* perf_data_proto) { + return SerializeFromStringWithOptions(contents, PerfParserOptions(), + perf_data_proto); +} + +bool SerializeFromStringWithOptions(const string& contents, + const PerfParserOptions& options, + PerfDataProto* perf_data_proto) { + PerfReader reader; + if (!reader.ReadFromString(contents)) return false; + + PerfParser parser(&reader, options); + if (!parser.ParseRawEvents()) return false; + + if (!reader.Serialize(perf_data_proto)) return false; + + // Append parser stats to protobuf. + PerfSerializer::SerializeParserStats(parser.stats(), perf_data_proto); + return true; +} + +bool SerializeFromStringWithOptions(const string& contents, + const PerfParserOptionsProto& options, + PerfDataProto* proto) { + PerfParserOptions opts; + opts.do_remap = options.do_remap(); + opts.discard_unused_events = options.discard_unused_events(); + opts.sample_mapping_percentage_threshold = + options.sample_mapping_percentage_threshold(); + opts.sort_events_by_time = options.sort_events_by_time(); + opts.read_missing_buildids = options.read_missing_buildids(); + opts.deduce_huge_page_mappings = options.deduce_huge_page_mappings(); + opts.combine_mappings = options.combine_mappings(); + return SerializeFromStringWithOptions(contents, opts, proto); +} + +bool SerializeFromFile(const string& filename, PerfDataProto* perf_data_proto) { + return SerializeFromFileWithOptions(filename, PerfParserOptions(), + perf_data_proto); +} + +bool SerializeFromFileWithOptions(const string& filename, + const PerfParserOptions& options, + PerfDataProto* perf_data_proto) { + PerfReader reader; + if (!reader.ReadFile(filename)) return false; + + PerfParser parser(&reader, options); + if (!parser.ParseRawEvents()) return false; + + if (!reader.Serialize(perf_data_proto)) return false; + + // Append parser stats to protobuf. + PerfSerializer::SerializeParserStats(parser.stats(), perf_data_proto); + return true; +} + +bool DeserializeToFile(const PerfDataProto& perf_data_proto, + const string& filename) { + PerfReader reader; + return reader.Deserialize(perf_data_proto) && reader.WriteFile(filename); +} + +bool WriteProtobufToFile(const PerfDataProto& perf_data_proto, + const string& filename) { + string output; + perf_data_proto.SerializeToString(&output); + + return BufferToFile(filename, output); +} + +bool ReadProtobufFromFile(PerfDataProto* perf_data_proto, + const string& filename) { + std::vector buffer; + if (!FileToBuffer(filename, &buffer)) return false; + + bool ret = perf_data_proto->ParseFromArray(buffer.data(), buffer.size()); + + LOG(INFO) << "#events" << perf_data_proto->events_size(); + + return ret; +} + +} // namespace quipper diff --git a/pool/shard006/C++/0079562_framebuffer.cpp b/pool/shard006/C++/0079562_framebuffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85220ed4739ea06a93dc95b7ddb72c6a11cdcbed --- /dev/null +++ b/pool/shard006/C++/0079562_framebuffer.cpp @@ -0,0 +1,213 @@ +#include "./graphics/framebuffer.h" + +#include "./utils/log.h" +#include "./utils/timer.h" + +namespace Splash +{ +/*************/ +Framebuffer::Framebuffer(RootObject* root) + : GraphObject(root) +{ + glCreateFramebuffers(1, &_fbo); + + if (!_depthTexture) + { + _depthTexture = std::make_shared(_root, _width, _height, "D", nullptr, _multisample); + glNamedFramebufferTexture(_fbo, GL_DEPTH_ATTACHMENT, _depthTexture->getTexId(), 0); + } + + if (!_colorTexture) + { + _colorTexture = std::make_shared(_root); + _colorTexture->setAttribute("clampToEdge", {true}); + _colorTexture->setAttribute("filtering", {false}); + _colorTexture->reset(_width, _height, _16bits ? "RGBA16" : "RGBA", nullptr, _multisample); + glNamedFramebufferTexture(_fbo, GL_COLOR_ATTACHMENT0, _colorTexture->getTexId(), 0); + } + + GLenum fboBuffers[1] = {GL_COLOR_ATTACHMENT0}; + glNamedFramebufferDrawBuffers(_fbo, 1, fboBuffers); + GLenum status = glCheckNamedFramebufferStatus(_fbo, GL_DRAW_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) + { + Log::get() << Log::ERROR << "Framebuffer::" << __FUNCTION__ << " - Error while initializing render framebuffer object: " << status << Log::endl; + glDeleteFramebuffers(1, &_fbo); + _fbo = 0; + } + else + { +#ifdef DEBUG + Log::get() << Log::DEBUGGING << "Framebuffer::" << __FUNCTION__ << " - Framebuffer object successfully initialized" << Log::endl; +#endif + } +} + +/*************/ +Framebuffer::~Framebuffer() +{ + glDeleteFramebuffers(1, &_fbo); +} + +/*************/ +void Framebuffer::bindDraw() +{ + if (_fbo) + { + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &_previousFbo); + if (_multisample) + glEnable(GL_MULTISAMPLE); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _fbo); + } +} + +/*************/ +void Framebuffer::bindRead() +{ + if (_fbo) + { + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &_previousFbo); + glBindFramebuffer(GL_READ_FRAMEBUFFER, _fbo); + } +} + +/*************/ +void Framebuffer::blit(const Framebuffer& src, const Framebuffer& dst) +{ + glBlitNamedFramebuffer( + src.getFboId(), dst.getFboId(), 0, 0, src.getWidth(), src.getHeight(), 0, 0, dst.getWidth(), dst.getHeight(), GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); +} + +/*************/ +float Framebuffer::getDepthAt(float x, float y) +{ + glBindFramebuffer(GL_READ_FRAMEBUFFER, _fbo); + float depth = 0.f; + glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + return depth; +} + +/*************/ +void Framebuffer::setCubemap(bool cubemap) +{ + if (cubemap != _cubemap) + { + _cubemap = cubemap; + setRenderingParameters(); + } +} + +/*************/ +void Framebuffer::setsRGB(bool srgb) +{ + if (srgb != _srgb) + { + _srgb = srgb; + setRenderingParameters(); + } +} + +/*************/ +void Framebuffer::setMultisampling(int samples) +{ + if (_multisample != samples) + { + _multisample = samples; + setRenderingParameters(); + } +} + +/*************/ +void Framebuffer::setSixteenBpc(bool sixteenbpc) +{ + if (_16bits != sixteenbpc) + { + _16bits = sixteenbpc; + setRenderingParameters(); + } +} + +/*************/ +void Framebuffer::setRenderingParameters() +{ + auto spec = _colorTexture->getSpec(); + + _depthTexture->reset(spec.width, spec.height, "D", nullptr, _multisample, _cubemap); + + if (_srgb) + _colorTexture->reset(spec.width, spec.height, "sRGBA", nullptr, _multisample, _cubemap); + else if (_16bits) + _colorTexture->reset(spec.width, spec.height, "RGBA16", nullptr, _multisample, _cubemap); + else + _colorTexture->reset(spec.width, spec.height, "RGBA", nullptr, _multisample, _cubemap); + + glNamedFramebufferTexture(_fbo, GL_DEPTH_ATTACHMENT, _depthTexture->getTexId(), 0); + glNamedFramebufferTexture(_fbo, GL_COLOR_ATTACHMENT0, _colorTexture->getTexId(), 0); +} + +/*************/ +void Framebuffer::setSize(int width, int height) +{ + if (width == 0 || height == 0) + return; + + _depthTexture->setResizable(true); + _depthTexture->setAttribute("size", {width, height}); + _depthTexture->setResizable(_automaticResize); + glNamedFramebufferTexture(_fbo, GL_DEPTH_ATTACHMENT, _depthTexture->getTexId(), 0); + + _colorTexture->setResizable(true); + _colorTexture->setAttribute("size", {width, height}); + _colorTexture->setResizable(_automaticResize); + glNamedFramebufferTexture(_fbo, GL_COLOR_ATTACHMENT0, _colorTexture->getTexId(), 0); + + _width = width; + _height = height; +} + +/*************/ +void Framebuffer::setResizable(bool resizable) +{ + _automaticResize = resizable; + _depthTexture->setResizable(_automaticResize); + _colorTexture->setResizable(_automaticResize); +} + +/*************/ +void Framebuffer::unbindDraw() +{ + if (_fbo) + { + int currentFbo = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, ¤tFbo); + if (static_cast(currentFbo) != _fbo) + { + Log::get() << Log::WARNING << "Framebuffer::" << __FUNCTION__ << " - Cannot unbind a FBO which is not bound" << Log::endl; + return; + } + + if (_multisample) + glDisable(GL_MULTISAMPLE); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _previousFbo); + } +} + +/*************/ +void Framebuffer::unbindRead() +{ + if (_fbo) + { + int currentFbo = 0; + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, ¤tFbo); + if (static_cast(currentFbo) != _fbo) + { + Log::get() << Log::WARNING << "Framebuffer::" << __FUNCTION__ << " - Cannot unbind a FBO which is not bound" << Log::endl; + return; + } + + glBindFramebuffer(GL_READ_FRAMEBUFFER, _previousFbo); + } +} + +} // namespace Splash diff --git a/pool/shard006/C++/0079565_55_areaintegrales.cpp b/pool/shard006/C++/0079565_55_areaintegrales.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85ecef9616751aa10a1d2c3059fd12c2b8e7effa --- /dev/null +++ b/pool/shard006/C++/0079565_55_areaintegrales.cpp @@ -0,0 +1,24 @@ +#include +#include + +// Para hallar el area multiplicamos por el "step" o diferencia, en este caso 0.1 +// Con un step menor que 0.1, el error es despreciable. + +double f(double x){ + return x*x + 3; +} +int main(int argc, char *argv[]) { + + double resultado; + double area; + + double step = 0.1; + for (double x=1; x<=20; x+=step) + resultado += f(x); + + area = resultado * step; + + printf("Area total = %.2lf\n", area); + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C++/0079567_item13.cpp b/pool/shard006/C++/0079567_item13.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1dd7cb521bddcfac94cc670ddac6b765ab23264 --- /dev/null +++ b/pool/shard006/C++/0079567_item13.cpp @@ -0,0 +1,49 @@ +#include +#include +#include + +using namespace std; + +typedef std::vector::iterator IterT; +typedef std::vector::const_iterator ConstIterT; + +template +auto cbegin(const C& container) -> decltype(begin(container)) +{ + return begin(container); +} + +template +auto cend(const C& container) -> decltype(end(container)) +{ + return end(container); +} + +template +void findAndInsert(C& container, const V& targetVal, const V& insertVal) +{ + auto it = find(cbegin(container), cend(container), targetVal); + container.insert(it, insertVal); +} + +int main() +{ + std::vector values{1,2,3,4,5,6}; + + IterT i = find(values.begin(), values.end(), 3); + values.insert(i, 1998); + + ConstIterT ci = find(values.cbegin(), values.cend(), 3); + values.insert(ci, 2011); + + findAndInsert(values, 3, 2017); + + copy(values.cbegin(), values.cend(), ostream_iterator(cout, " ")); cout << endl; + + int arr[]{1,2,3,4,5,6}; + //findAndInsert(arr, 3, 2017); + copy(cbegin(arr), cend(arr), ostream_iterator(cout, " ")); cout << endl; + + return 0; +} + diff --git a/pool/shard006/C++/0079575_HttpResponse.cpp b/pool/shard006/C++/0079575_HttpResponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3966a9bda9b0772ef681b580d46e7ff80a46b3e6 --- /dev/null +++ b/pool/shard006/C++/0079575_HttpResponse.cpp @@ -0,0 +1,182 @@ +/* + + Project: 1Sheeld Library + File: HttpResponse.cpp + + Version: 1.2 + + Compiler: Arduino avr-gcc 4.3.2 + + Author: Integreight + + Date: 2015.1 + +*/ + +#include "OneSheeld.h" +#include "InternetShield.h" + + +HttpResponse::HttpResponse() +{ + isInit=false; + isDisposedTriggered=false; + statusCode=0; + totalBytesCount=0; + bytes=NULL; + bytesCount = 0; + requestId = 0; + index =0; + callbacksRequested = 0; +} + +int HttpResponse::getStatusCode() +{ + return statusCode; +} + +int HttpResponse::getBytesCount() +{ + return bytesCount; +} + +char * HttpResponse::getBytes() +{ + return bytes; +} + +unsigned long HttpResponse::getTotalBytesCount() +{ + return totalBytesCount; +} + +unsigned long HttpResponse::getCurrentIndex() +{ + return index; +} + +void HttpResponse::getTheseBytes(unsigned long start,int size) +{ + if(isInit) + { + index=start; + byte startArray[4] ; + startArray[0] = start & 0xFF; + startArray[1] = (start >> 8) & 0xFF; + startArray[2] = (start >> 16) & 0xFF; + startArray[3] = (start >> 24) & 0xFF; + + byte sizeArray[2] ; + sizeArray[1] = (size >> 8) & 0xFF; + sizeArray[0] = size & 0xFF; + + byte reqId[2] ; + reqId[1] = (requestId >> 8) & 0xFF; + reqId[0] = requestId & 0xFF; + + OneSheeld.sendPacket(INTERNET_ID,0,RESPONSE_GET_NEXT_BYTES,3,new FunctionArg(2,reqId), + new FunctionArg(4,startArray), + new FunctionArg(2,sizeArray)); + } + +} + +void HttpResponse::getNextBytes(int size) +{ + getTheseBytes(index,size); +} + +void HttpResponse::setOnNextResponseBytesUpdate(void (*userFunction)(HttpResponse &)) +{ + callbacksRequested |= RESPONSE_GET_NEXT_RESPONSE_BIT; + getNextCallBack = userFunction; +} + +void HttpResponse::setOnError(void (*userFunction)(int errorNumber)) +{ + callbacksRequested |= RESPONSE_GET_ERROR_BIT; + getErrorCallBack = userFunction; +} + +void HttpResponse::setOnJsonResponse(void (*userFunction)(JsonKeyChain & chain,char data[])) +{ + callbacksRequested |= RESPONSE_GET_JSON_BIT; + getJsonCallBack = userFunction; +} + +void HttpResponse::setOnJsonArrayLengthResponse(void (*userFunction)(JsonKeyChain & chain,unsigned long size)) +{ + callbacksRequested |= RESPONSE_GET_JSON_ARRAY_LENGTH_BIT; + getJsonArrayLengthCallBack = userFunction; +} + +bool HttpResponse::isSentFully() +{ + return (index>=totalBytesCount); +} + +void HttpResponse::dispose(bool sendFrame) +{ + isDisposedTriggered = true; + if(isInit && bytesCount!=0 && bytes!=NULL) + { + free(bytes); + } + isInit=false; + bytes=NULL; + index = 0; + bytesCount = 0; + statusCode = 0; + totalBytesCount = 0; + byte reqId[2] ; + reqId[1] = (requestId >> 8) & 0xFF; + reqId[0] = requestId & 0xFF; + + if(sendFrame) + { + OneSheeld.sendPacket(INTERNET_ID,0,RESPONSE_DISPOSE,1,new FunctionArg(2,reqId)); + callbacksRequested=0; + } +} + +bool HttpResponse::isDisposed() +{ + return isDisposedTriggered; +} + +void HttpResponse::resetIndex(unsigned long x) +{ + index=x; +} + +void HttpResponse::getHeader(const char * headerName , void (*userFunction)(char incomingheaderName [],char IncomingHeaderValue[])) +{ + if(isInit) + { + //Check length of string + int headerNameLength = strlen(headerName); + if(!headerNameLength) return; + callbacksRequested |= RESPONSE_INPUT_GET_HEADER_BIT; + getHeaderCallBack = userFunction; + OneSheeld.sendPacket(INTERNET_ID,0,RESPONSE_INPUT_GET_HEADER,1,new FunctionArg(headerNameLength,(byte *)headerName)); + } + +} + +JsonKeyChain HttpResponse::operator[](int key) +{ + JsonKeyChain chain(requestId); + return chain[key]; +} + +JsonKeyChain HttpResponse::operator[](const char *key) +{ + if(!strlen(key)) return 0; + JsonKeyChain chain(requestId); + return chain[key]; +} + +HttpResponse::~HttpResponse() +{ + if(isInit && bytesCount!=0)free(bytes); +} \ No newline at end of file diff --git a/pool/shard006/C++/0079589_noatun20update.cpp b/pool/shard006/C++/0079589_noatun20update.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6a611f05f13abecd015ebdb9dd8189ce0471fa1 --- /dev/null +++ b/pool/shard006/C++/0079589_noatun20update.cpp @@ -0,0 +1,41 @@ +// Convert Noatun 1.2 plugins that no longer exist to their closest 2.0 +// counterparts. + +#include +#include + +#ifndef stdin +extern "C" FILE *stdin; +#endif + +#ifndef stdout +extern "C" FILE *stdout; +#endif + +int main(int, char **) +{ + QFile qin, qout; + qin.open(IO_ReadOnly, stdin); + qout.open(IO_WriteOnly, stdout); + + QString text = qin.readAll(); + + // tag loaders + bool tagloaders = text.contains("id3tag.plugin") || + text.contains("oggtag.plugin") || + text.contains("luckytag.plugin"); + + text.replace(QRegExp("id3tag\\.plugin"), ""); + text.replace(QRegExp("oggtag\\.plugin"), ""); + text.replace(QRegExp("luckytag\\.plugin"), ""); + + if(tagloaders) text.replace(QRegExp("Modules="), "Modules=metatag.plugin,"); + + // playlists + text.replace(QRegExp("tron\\.plugin"), "splitplaylist.plugin"); + text.replace(QRegExp("liszt\\.plugin"), "splitplaylist.plugin"); + + qout.writeBlock(text.local8Bit()); + + return 0; +} diff --git a/pool/shard006/C++/0079590_SamiVariableCategory.cpp b/pool/shard006/C++/0079590_SamiVariableCategory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd34ec89efcecb257ed5b3ce75cca230c1ea2642 --- /dev/null +++ b/pool/shard006/C++/0079590_SamiVariableCategory.cpp @@ -0,0 +1,149 @@ + +#include "SamiVariableCategory.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiVariableCategory::SamiVariableCategory() { + init(); +} + +SamiVariableCategory::~SamiVariableCategory() { + this->cleanup(); +} + +void +SamiVariableCategory::init() { + pName = null; +} + +void +SamiVariableCategory::cleanup() { + if(pName != null) { + + delete pName; + pName = null; + } +} + + +SamiVariableCategory* +SamiVariableCategory::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiVariableCategory::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pNameKey = new JsonString(L"name"); + IJsonValue* pNameVal = null; + pJsonObject->GetValue(pNameKey, pNameVal); + if(pNameVal != null) { + + pName = new String(); + jsonToValue(pName, pNameVal, L"String", L"String"); + } + delete pNameKey; + } +} + +SamiVariableCategory::SamiVariableCategory(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiVariableCategory::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiVariableCategory::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + JsonString *pNameKey = new JsonString(L"name"); + pJsonObject->Add(pNameKey, toJson(getPName(), "String", "")); + + return pJsonObject; +} + +String* +SamiVariableCategory::getPName() { + return pName; +} +void +SamiVariableCategory::setPName(String* pName) { + this->pName = pName; +} + + + +} /* namespace Swagger */ + diff --git a/pool/shard006/C++/0079591_076.cpp b/pool/shard006/C++/0079591_076.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c3049b8f1e59028528c51feeaae223c5729ca92 --- /dev/null +++ b/pool/shard006/C++/0079591_076.cpp @@ -0,0 +1,58 @@ +/*============================================================ +Problem: Minimum Window Substring +============================================================== +Given a string S and a string T, find the minimum window in S +which will contain all the characters in T in complexity O(n). + +For example, +S = "ADOBECODEBANC" +T = "ABC" +Minimum window is "BANC". + +Note: +If there is no such window in S that covers all characters in T, +return the empty string "". + +If there are multiple such windows, you are guaranteed that +there will always be only one unique minimum window in S. +============================================================*/ +class Solution { +private: + bool needed[256] = {false}; + int counts[256] = {0}; +public: + string minWindow(string s, string t) { + int sLen = s.size(), tLen = t.size(); + if (sLen==0 || tLen==0) return ""; + + for (int i=0; i= 0) // if another useful match is made, not matched minus + notMatchCount--; + } + if (notMatchCount==0) { // now we can move the start of the WINDOW forward, when all matched + while (true) { + if (needed[s[start]]) { // the first char is a char we have to match + if (counts[s[start]] < 0) // have more matched ones of this char, can still move forward + counts[s[start]]++; + else + break; + } + // if the first char is not what we want to match, just move forward + start++; + } + if (minSize > i-start+1) { // update the minimum WINDOW + minSize = i-start+1; + minStart = start; + } + } + } + return minSize==INT_MAX ? "" : s.substr(minStart, minSize); + } +}; \ No newline at end of file diff --git a/pool/shard006/C++/0079595_screen_shooter.cpp b/pool/shard006/C++/0079595_screen_shooter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c53f15d9c43ae62f8e65dcf071ce62bea0f2d2cd --- /dev/null +++ b/pool/shard006/C++/0079595_screen_shooter.cpp @@ -0,0 +1,95 @@ +// +// screen_shooter.cpp +// +// Created by Leopold O'Donnell on 3/18/13. +// MIT-LIcense Copyright (c) 2013 Leo O'Donnell. +// +#include "screen_shooter.h" + +#define max(a,b) \ +({ __typeof__ (a) _a = (a); \ +__typeof__ (b) _b = (b); \ +_a > _b ? _a : _b; }) + +#define min(a,b) \ +({ __typeof__ (a) _a = (a); \ +__typeof__ (b) _b = (b); \ +_a < _b ? _a : _b; }) + + +ScreenShooter::ScreenShooter() { + init_displays(); + calculate_bounds(); +} + +ScreenShooter::~ScreenShooter() { + free(_displays); + delete [] _display_bounds; +} + +Screenshot* ScreenShooter::take_screenshot(const CFStringRef format, float compression) { + CGImageRef* images = new CGImageRef[_dsp_count]; + + /* Grab the images */ + for (unsigned int i = 0; i < _dsp_count; i++) { + images[i] = CGDisplayCreateImage(_displays[i]); + } + + /* Calculate size of image to produce */ + CGSize finalSize = CGSizeMake(_top_right.x - _bottom_left.x, _bottom_left.y - _top_right.y); + + /* Round out the bitmap size information */ + size_t bytesPerRow = finalSize.width * CGImageGetBitsPerPixel(images[0]) / 8; + + /* Create context around bitmap */ + CGContextRef context = CGBitmapContextCreate( + NULL, finalSize.width, finalSize.height, + CGImageGetBitsPerComponent(images[0]), bytesPerRow, + CGImageGetColorSpace(images[0]), CGImageGetBitmapInfo(images[0]) + ); + + /* Draw images into the bitmap */ + for (unsigned int i = 0; i < _dsp_count; i++) + { + /* Adjust the positions to account for coordinate system shifts + (displays origin is at top left; image origin is at bottom left) */ + CGRect adjustedPoint = CGRectMake(_display_bounds[i].origin.x - _bottom_left.x, + _bottom_left.y - _display_bounds[i].size.height - _display_bounds[i].origin.y, + _display_bounds[i].size.width, + _display_bounds[i].size.height); + CGContextDrawImage(context, adjustedPoint, images[i]); + } + + delete [] images; + + return new Screenshot(context, format, compression); +} + +/* Calculate the _bottom_left and _top_right corners of our virtual display. + * Must be called after init_displays. + */ +void ScreenShooter::calculate_bounds() { + _display_bounds = new CGRect[_dsp_count]; + + for(unsigned int i = 0; i < _dsp_count; i++) + { + _display_bounds[i] = CGDisplayBounds(_displays[i]); + CGRect bounds = _display_bounds[i]; + _bottom_left.x = min(_bottom_left.x, bounds.origin.x); + _bottom_left.y = max(_bottom_left.y, bounds.origin.y+bounds.size.height); + _top_right.x = max(_top_right.x, bounds.origin.x+bounds.size.width); + _top_right.y = min(_top_right.y, bounds.origin.y); + } +} + +/* Initialize the array and size of the Active Displays */ +void ScreenShooter::init_displays() { + /* How many active displays do we have? */ + CGGetActiveDisplayList(0, NULL, (uint32_t*)&_dsp_count); + + /* Allocate enough memory to hold all the display IDs we have. */ + _displays = (CGDirectDisplayID*) calloc((size_t) _dsp_count, sizeof(CGDirectDisplayID)); + + /* Get the list of active displays */ + CGGetActiveDisplayList(_dsp_count, _displays, &_dsp_count); +} diff --git a/pool/shard006/C++/0079600_FcQuadraticFunction.cpp b/pool/shard006/C++/0079600_FcQuadraticFunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70883ab816866a09639832563d3f59c72931bd99 --- /dev/null +++ b/pool/shard006/C++/0079600_FcQuadraticFunction.cpp @@ -0,0 +1,38 @@ +#include "ocra/optim/FcQuadraticFunction.h" + + +using namespace ocra; + +FcQuadraticFunction::FcQuadraticFunction(ocra::Variable& x) +: NamedInstance("Variable Fc Quadratic Function") +, ocra::AbilitySet(ocra::PARTIAL_X, ocra::PARTIAL_XX) +, CoupledInputOutputSize(false) +, QuadraticFunction(x) +{ + +} + +FcQuadraticFunction::~FcQuadraticFunction() +{ + +} + +void FcQuadraticFunction::doUpdateInputSizeBegin() +{ + +} + +void FcQuadraticFunction::updateHessian() const +{ + IFunction::_val[0]->setIdentity(x.getSize(), x.getSize()); +} + +void FcQuadraticFunction::updateq() const +{ + _q[0]->setZero(x.getSize()); +} + +void FcQuadraticFunction::updater() const +{ + _r[0] = 0; +} diff --git a/pool/shard006/C++/0079602_date_provider_impl.cc b/pool/shard006/C++/0079602_date_provider_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..da41a64e1fa4ab447973b8c9e35dfcb31d3d2764 --- /dev/null +++ b/pool/shard006/C++/0079602_date_provider_impl.cc @@ -0,0 +1,37 @@ +#include "source/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/shard006/C++/0079604_DBManageSheet.cpp b/pool/shard006/C++/0079604_DBManageSheet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..817b8ba8940bd14f9a025209240345f4f538e779 --- /dev/null +++ b/pool/shard006/C++/0079604_DBManageSheet.cpp @@ -0,0 +1,52 @@ +// DBManageSheet.cpp : ʵÏÖÎļþ +// + +#include "stdafx.h" +#include "DataServerCenter.h" +#include "DBManageSheet.h" + + +// CDBManageSheet + +IMPLEMENT_DYNAMIC(CDBManageSheet, CPropertySheet) + +CDBManageSheet::CDBManageSheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) + :CPropertySheet(nIDCaption, pParentWnd, iSelectPage) +{ + +} + +CDBManageSheet::CDBManageSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) + :CPropertySheet(pszCaption, pParentWnd, iSelectPage) +{ +} + +CDBManageSheet::~CDBManageSheet() +{ + +} + + +BEGIN_MESSAGE_MAP(CDBManageSheet, CPropertySheet) + ON_WM_SHOWWINDOW() + ON_WM_PAINT() +END_MESSAGE_MAP() + + +// CDBManageSheet ÏûÏ¢´¦Àí³ÌÐò + + +void CDBManageSheet::OnShowWindow(BOOL bShow, UINT nStatus) +{ + CPropertySheet::OnShowWindow(bShow, nStatus); + + // TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë +} + + +void CDBManageSheet::OnPaint() +{ + CPaintDC dc(this); // device context for painting + // TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë + // ²»Îª»æÍ¼ÏûÏ¢µ÷Óà CPropertySheet::OnPaint() +} diff --git a/pool/shard006/C++/0079606_gen_name.cpp b/pool/shard006/C++/0079606_gen_name.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3f7b188725bcd2a6556094f892c41c812848990 --- /dev/null +++ b/pool/shard006/C++/0079606_gen_name.cpp @@ -0,0 +1,40 @@ +#include "gen_name.h" +#include + +using namespace std; + +void CharacterName::grabRandomName(string &name) +{ + ifstream fileOfNames; + string tmpName; + fileOfNames.open("./data/names.dat"); + + if (fileOfNames.is_open()) + { + int number_of_lines = 0; //count the number of lines + string line; + while (getline(fileOfNames, line)) + ++number_of_lines; + fileOfNames.clear(); //clear end of file status so seekg will work + fileOfNames.seekg(0, ios_base::beg); //return to beginning position + + //pick one name randomly + auto chosenSeed = randomNumber(1, number_of_lines); + for (auto i = 1; i < chosenSeed; i++) + { + fileOfNames.ignore(numeric_limits::max(), '\n'); + } + getline(fileOfNames, tmpName, '\n'); + } + else + { + tmpName = "error with name file, may be in use or if not, check code"; + } + + if (*tmpName.rbegin() == '\r') + { + tmpName.erase(tmpName.length() - 1); + } + + name = tmpName; +} diff --git a/pool/shard006/C++/0079611_ReactorAI.cpp b/pool/shard006/C++/0079611_ReactorAI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be9478ba7c2534191cfa9b19ca17945d51bb90c9 --- /dev/null +++ b/pool/shard006/C++/0079611_ReactorAI.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2009-2011 MaNGOSZero + * Copyright (C) 2011-2016 Nostalrius + * Copyright (C) 2016-2017 Elysium 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 "ByteBuffer.h" +#include "ReactorAI.h" +#include "Errors.h" +#include "Creature.h" +#include "Map.h" +#include "Log.h" + +#define REACTOR_VISIBLE_RANGE (26.46f) + +int +ReactorAI::Permissible(const Creature *creature) +{ + if ((creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_AGGRO) || creature->IsNeutralToAll()) + return PERMIT_BASE_REACTIVE; + + return PERMIT_BASE_NO; +} + +void +ReactorAI::MoveInLineOfSight(Unit *) +{ +} + +void +ReactorAI::AttackStart(Unit *p) +{ + if (!p) + return; + + if (m_creature->Attack(p, true)) + { + DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Tag unit GUID: %u (TypeId: %u) as a victim", p->GetGUIDLow(), p->GetTypeId()); + i_victimGuid = p->GetObjectGuid(); + m_creature->AddThreat(p); + + m_creature->SetInCombatWith(p); + p->SetInCombatWith(m_creature); + + m_creature->GetMotionMaster()->MoveChase(p); + } +} + +void +ReactorAI::UpdateAI(const uint32 /*time_diff*/) +{ + // update i_victimGuid if i_creature.getVictim() !=0 and changed + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + + i_victimGuid = m_creature->getVictim()->GetObjectGuid(); + + DoMeleeAttackIfReady(); +} + +void +ReactorAI::EnterEvadeMode() +{ + CreatureAI::EnterEvadeMode(); + i_victimGuid.Clear(); +} diff --git a/pool/shard006/C++/0079619_HTMLParserScheduler.cpp b/pool/shard006/C++/0079619_HTMLParserScheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd6f3df6e8553d5d2973ea659fea33c6322ef030 --- /dev/null +++ b/pool/shard006/C++/0079619_HTMLParserScheduler.cpp @@ -0,0 +1,157 @@ +/* + * 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. ``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 "config.h" +#include "HTMLParserScheduler.h" + +#include "Document.h" +#include "FrameView.h" +#include "HTMLDocumentParser.h" +#include "Page.h" + +// defaultParserChunkSize is used to define how many tokens the parser will +// process before checking against parserTimeLimit and possibly yielding. +// This is a performance optimization to prevent checking after every token. +static const int defaultParserChunkSize = 4096; + +// defaultParserTimeLimit is the seconds the parser will run in one write() call +// before yielding. Inline