Pendigard commited on
Commit
3fca285
·
verified ·
1 Parent(s): 233d4a5

Upload folder using huggingface_hub (part 72)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pool/shard006/C++/0078449_pagelocker.cpp +70 -0
  2. pool/shard006/C++/0078462_memory_details_android.cc +142 -0
  3. pool/shard006/C++/0078464_native_test_launcher.cc +153 -0
  4. pool/shard006/C++/0078473_instantiation_test.cpp +81 -0
  5. pool/shard006/C++/0078478_moc_vscvideowall.cpp +216 -0
  6. pool/shard006/C++/0078481_PurchaseHostReservationRequest.cpp +76 -0
  7. pool/shard006/C++/0078487_systemmodel.cpp +186 -0
  8. pool/shard006/C++/0078490_mrlock.cpp +124 -0
  9. pool/shard006/C++/0078491_main.cpp +107 -0
  10. pool/shard006/C++/0078497_multisiginputentry.cpp +174 -0
  11. pool/shard006/C++/0078507_JSCSSValueCustom.cpp +75 -0
  12. pool/shard006/C++/0078514_jdtrans.cpp +125 -0
  13. pool/shard006/C++/0078515_boss_SpoilsOfPandaria.cpp +178 -0
  14. pool/shard006/C++/0078516_RGBLed.cpp +55 -0
  15. pool/shard006/C++/0078519_iniparser.cpp +165 -0
  16. pool/shard006/C++/0078520_06.cpp +31 -0
  17. pool/shard006/C++/0078524_FlightMapSettings.cc +159 -0
  18. pool/shard006/C++/0078526_12665_jokingfermat.cpp +92 -0
  19. pool/shard006/C++/0078527_InputManager.cpp +63 -0
  20. pool/shard006/C++/0078541_BroadcastDiscovery.cpp +151 -0
  21. pool/shard006/C++/0078543_string.cpp +71 -0
  22. pool/shard006/C++/0078550_remove_element.cpp +76 -0
  23. pool/shard006/C++/0078551_5.cpp +108 -0
  24. pool/shard006/C++/0078556_uri.cpp +124 -0
  25. pool/shard006/C++/0078558_partialdate.cpp +217 -0
  26. pool/shard006/C++/0078561_ChShaftsTorqueConverter.cpp +221 -0
  27. pool/shard006/C++/0078564_command_interface.cpp +47 -0
  28. pool/shard006/C++/0078577_Led.cpp +109 -0
  29. pool/shard006/C++/0078596_init_process_reaper.cc +101 -0
  30. pool/shard006/C++/0078598_boss_ambassador_hellmaw.cpp +209 -0
  31. pool/shard006/C++/0078614_parser.cpp +157 -0
  32. pool/shard006/C++/0078616_DrawingElement.cpp +230 -0
  33. pool/shard006/C++/0078617_stackdriver_client_test.cc +215 -0
  34. pool/shard006/C++/0078620_qgsclassificationjenks.cpp +192 -0
  35. pool/shard006/C++/0078623_RPC.cpp +212 -0
  36. pool/shard006/C++/0078634_checkpoints.cpp +146 -0
  37. pool/shard006/C++/0078638_ReactorAI.cpp +135 -0
  38. pool/shard006/C++/0078641_test_metro_viewer_process_host.cc +50 -0
  39. pool/shard006/C++/0078643_Firm.cpp +148 -0
  40. pool/shard006/C++/0078645_max_size.pass.cpp +55 -0
  41. pool/shard006/C++/0078646_gist.cpp +120 -0
  42. pool/shard006/C++/0078662_lock_impl_unittest.cc +199 -0
  43. pool/shard006/C++/0078666_lanRouter.cc +129 -0
  44. pool/shard006/C++/0078667_EventFactory.cpp +54 -0
  45. pool/shard006/C++/0078671_testing_cgebrd.cpp +202 -0
  46. pool/shard006/C++/0078672_GraphNodeView.cpp +228 -0
  47. pool/shard006/C++/0078678_benchmarkudf.cc +140 -0
  48. pool/shard006/C++/0078679_skinned_mesh.cpp +89 -0
  49. pool/shard006/C++/0078685_2.cc +43 -0
  50. pool/shard006/C++/0078686_EvaluationMetrics.cpp +75 -0
pool/shard006/C++/0078449_pagelocker.cpp ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2009-2015 The Bitcoin Core developers
2
+ // Distributed under the MIT software license, see the accompanying
3
+ // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
+
5
+ #include "support/pagelocker.h"
6
+
7
+ #if defined(HAVE_CONFIG_H)
8
+ #include "config/mxn-config.h"
9
+ #endif
10
+
11
+ #ifdef WIN32
12
+ #ifdef _WIN32_WINNT
13
+ #undef _WIN32_WINNT
14
+ #endif
15
+ #define _WIN32_WINNT 0x0501
16
+ #define WIN32_LEAN_AND_MEAN 1
17
+ #ifndef NOMINMAX
18
+ #define NOMINMAX
19
+ #endif
20
+ #include <windows.h>
21
+ // This is used to attempt to keep keying material out of swap
22
+ // Note that VirtualLock does not provide this as a guarantee on Windows,
23
+ // but, in practice, memory that has been VirtualLock'd almost never gets written to
24
+ // the pagefile except in rare circumstances where memory is extremely low.
25
+ #else
26
+ #include <sys/mman.h>
27
+ #include <limits.h> // for PAGESIZE
28
+ #include <unistd.h> // for sysconf
29
+ #endif
30
+
31
+ LockedPageManager* LockedPageManager::_instance = NULL;
32
+ boost::once_flag LockedPageManager::init_flag = BOOST_ONCE_INIT;
33
+
34
+ /** Determine system page size in bytes */
35
+ static inline size_t GetSystemPageSize()
36
+ {
37
+ size_t page_size;
38
+ #if defined(WIN32)
39
+ SYSTEM_INFO sSysInfo;
40
+ GetSystemInfo(&sSysInfo);
41
+ page_size = sSysInfo.dwPageSize;
42
+ #elif defined(PAGESIZE) // defined in limits.h
43
+ page_size = PAGESIZE;
44
+ #else // assume some POSIX OS
45
+ page_size = sysconf(_SC_PAGESIZE);
46
+ #endif
47
+ return page_size;
48
+ }
49
+
50
+ bool MemoryPageLocker::Lock(const void* addr, size_t len)
51
+ {
52
+ #ifdef WIN32
53
+ return VirtualLock(const_cast<void*>(addr), len) != 0;
54
+ #else
55
+ return mlock(addr, len) == 0;
56
+ #endif
57
+ }
58
+
59
+ bool MemoryPageLocker::Unlock(const void* addr, size_t len)
60
+ {
61
+ #ifdef WIN32
62
+ return VirtualUnlock(const_cast<void*>(addr), len) != 0;
63
+ #else
64
+ return munlock(addr, len) == 0;
65
+ #endif
66
+ }
67
+
68
+ LockedPageManager::LockedPageManager() : LockedPageManagerBase<MemoryPageLocker>(GetSystemPageSize())
69
+ {
70
+ }
pool/shard006/C++/0078462_memory_details_android.cc ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "chrome/browser/memory_details.h"
6
+
7
+ #include <set>
8
+ #include <string>
9
+ #include <vector>
10
+
11
+ #include "base/bind.h"
12
+ #include "base/memory/scoped_ptr.h"
13
+ #include "base/process/process_iterator.h"
14
+ #include "base/strings/utf_string_conversions.h"
15
+ #include "chrome/common/chrome_constants.h"
16
+ #include "chrome/grit/chromium_strings.h"
17
+ #include "content/public/browser/browser_thread.h"
18
+ #include "content/public/common/process_type.h"
19
+ #include "ui/base/l10n/l10n_util.h"
20
+
21
+ using base::ProcessEntry;
22
+ using base::ProcessId;
23
+ using content::BrowserThread;
24
+
25
+ namespace {
26
+
27
+ // A helper for |CollectProcessData()| to include the chrome sandboxed
28
+ // processes in android which are not running as a child of the browser
29
+ // process.
30
+ void AddNonChildChromeProcesses(
31
+ std::vector<ProcessMemoryInformation>* processes) {
32
+ base::ProcessIterator process_iter(NULL);
33
+ while (const ProcessEntry* process_entry = process_iter.NextProcessEntry()) {
34
+ const std::vector<std::string>& cmd_args = process_entry->cmd_line_args();
35
+ if (cmd_args.empty() ||
36
+ cmd_args[0].find(chrome::kHelperProcessExecutableName) ==
37
+ std::string::npos) {
38
+ continue;
39
+ }
40
+ ProcessMemoryInformation info;
41
+ info.pid = process_entry->pid();
42
+ processes->push_back(info);
43
+ }
44
+ }
45
+
46
+ // For each of the pids, collect memory information about that process
47
+ // and append a record to |out|.
48
+ void GetProcessDataMemoryInformation(
49
+ const std::set<ProcessId>& pids, ProcessData* out) {
50
+ for (std::set<ProcessId>::const_iterator i = pids.begin(); i != pids.end();
51
+ ++i) {
52
+ ProcessMemoryInformation pmi;
53
+
54
+ pmi.pid = *i;
55
+ pmi.num_processes = 1;
56
+
57
+ if (pmi.pid == base::GetCurrentProcId())
58
+ pmi.process_type = content::PROCESS_TYPE_BROWSER;
59
+ else
60
+ pmi.process_type = content::PROCESS_TYPE_UNKNOWN;
61
+
62
+ scoped_ptr<base::ProcessMetrics> metrics(
63
+ base::ProcessMetrics::CreateProcessMetrics(*i));
64
+ metrics->GetWorkingSetKBytes(&pmi.working_set);
65
+
66
+ out->processes.push_back(pmi);
67
+ }
68
+ }
69
+
70
+ // Find all children of the given process.
71
+ void GetAllChildren(const std::vector<ProcessEntry>& processes,
72
+ const std::set<ProcessId>& roots,
73
+ std::set<ProcessId>* out) {
74
+ *out = roots;
75
+
76
+ std::set<ProcessId> wavefront;
77
+ for (std::set<ProcessId>::const_iterator i = roots.begin(); i != roots.end();
78
+ ++i) {
79
+ wavefront.insert(*i);
80
+ }
81
+
82
+ while (wavefront.size()) {
83
+ std::set<ProcessId> next_wavefront;
84
+ for (std::vector<ProcessEntry>::const_iterator i = processes.begin();
85
+ i != processes.end(); ++i) {
86
+ if (wavefront.count(i->parent_pid())) {
87
+ out->insert(i->pid());
88
+ next_wavefront.insert(i->pid());
89
+ }
90
+ }
91
+
92
+ wavefront.clear();
93
+ wavefront.swap(next_wavefront);
94
+ }
95
+ }
96
+
97
+ } // namespace
98
+
99
+ MemoryDetails::MemoryDetails()
100
+ : user_metrics_mode_(UPDATE_USER_METRICS),
101
+ memory_growth_tracker_(NULL) {
102
+ }
103
+
104
+ ProcessData* MemoryDetails::ChromeBrowser() {
105
+ return &process_data_[0];
106
+ }
107
+
108
+ void MemoryDetails::CollectProcessData(
109
+ const std::vector<ProcessMemoryInformation>& chrome_processes) {
110
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
111
+
112
+ std::vector<ProcessMemoryInformation> all_processes(chrome_processes);
113
+ AddNonChildChromeProcesses(&all_processes);
114
+
115
+ std::vector<ProcessEntry> processes;
116
+ base::ProcessIterator process_iter(NULL);
117
+ while (const ProcessEntry* process_entry = process_iter.NextProcessEntry()) {
118
+ processes.push_back(*process_entry);
119
+ }
120
+
121
+ std::set<ProcessId> roots;
122
+ roots.insert(base::GetCurrentProcId());
123
+ for (std::vector<ProcessMemoryInformation>::const_iterator
124
+ i = all_processes.begin(); i != all_processes.end(); ++i) {
125
+ roots.insert(i->pid);
126
+ }
127
+
128
+ std::set<ProcessId> current_browser_processes;
129
+ GetAllChildren(processes, roots, &current_browser_processes);
130
+
131
+ ProcessData current_browser;
132
+ GetProcessDataMemoryInformation(current_browser_processes, &current_browser);
133
+ current_browser.name = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
134
+ current_browser.process_name =
135
+ base::ASCIIToUTF16(chrome::kBrowserProcessExecutableName);
136
+ process_data_.push_back(current_browser);
137
+
138
+ // Finally return to the browser thread.
139
+ BrowserThread::PostTask(
140
+ BrowserThread::UI, FROM_HERE,
141
+ base::Bind(&MemoryDetails::CollectChildInfoOnUIThread, this));
142
+ }
pool/shard006/C++/0078464_native_test_launcher.cc ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ // This class sets up the environment for running the native tests inside an
6
+ // android application. It outputs (to a fifo) markers identifying the
7
+ // START/PASSED/CRASH of the test suite, FAILURE/SUCCESS of individual tests,
8
+ // etc.
9
+ // These markers are read by the test runner script to generate test results.
10
+ // It installs signal handlers to detect crashes.
11
+
12
+ #include <android/log.h>
13
+ #include <signal.h>
14
+
15
+ #include "base/android/base_jni_registrar.h"
16
+ #include "base/android/context_utils.h"
17
+ #include "base/android/fifo_utils.h"
18
+ #include "base/android/jni_string.h"
19
+ #include "base/android/scoped_java_ref.h"
20
+ #include "base/at_exit.h"
21
+ #include "base/base_switches.h"
22
+ #include "base/command_line.h"
23
+ #include "base/files/file_path.h"
24
+ #include "base/files/file_util.h"
25
+ #include "base/logging.h"
26
+ #include "base/strings/stringprintf.h"
27
+ #include "gtest/gtest.h"
28
+ #include "jni/NativeTestActivity_jni.h"
29
+ #include "testing/android/native_test/native_test_util.h"
30
+
31
+ // The main function of the program to be wrapped as a test apk.
32
+ extern int main(int argc, char** argv);
33
+
34
+ namespace testing {
35
+ namespace android {
36
+
37
+ namespace {
38
+
39
+ const char kLogTag[] = "chromium";
40
+ const char kCrashedMarker[] = "[ CRASHED ]\n";
41
+
42
+ // The list of signals which are considered to be crashes.
43
+ const int kExceptionSignals[] = {
44
+ SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
45
+ };
46
+
47
+ struct sigaction g_old_sa[NSIG];
48
+
49
+ // This function runs in a compromised context. It should not allocate memory.
50
+ void SignalHandler(int sig, siginfo_t* info, void* reserved) {
51
+ // Output the crash marker.
52
+ write(STDOUT_FILENO, kCrashedMarker, sizeof(kCrashedMarker));
53
+ g_old_sa[sig].sa_sigaction(sig, info, reserved);
54
+ }
55
+
56
+ // Writes printf() style string to Android's logger where |priority| is one of
57
+ // the levels defined in <android/log.h>.
58
+ void AndroidLog(int priority, const char* format, ...) {
59
+ va_list args;
60
+ va_start(args, format);
61
+ __android_log_vprint(priority, kLogTag, format, args);
62
+ va_end(args);
63
+ }
64
+
65
+ } // namespace
66
+
67
+ static void RunTests(JNIEnv* env,
68
+ const JavaParamRef<jobject>& obj,
69
+ const JavaParamRef<jstring>& jcommand_line_flags,
70
+ const JavaParamRef<jstring>& jcommand_line_file_path,
71
+ const JavaParamRef<jstring>& jstdout_file_path,
72
+ jboolean jstdout_fifo,
73
+ const JavaParamRef<jobject>& app_context) {
74
+ // Command line initialized basically, will be fully initialized later.
75
+ static const char* const kInitialArgv[] = { "ChromeTestActivity" };
76
+ base::CommandLine::Init(arraysize(kInitialArgv), kInitialArgv);
77
+
78
+ std::vector<std::string> args;
79
+
80
+ const std::string command_line_file_path(
81
+ base::android::ConvertJavaStringToUTF8(env, jcommand_line_file_path));
82
+ if (command_line_file_path.empty())
83
+ args.push_back("_");
84
+ else
85
+ ParseArgsFromCommandLineFile(command_line_file_path.c_str(), &args);
86
+
87
+ const std::string command_line_flags(
88
+ base::android::ConvertJavaStringToUTF8(env, jcommand_line_flags));
89
+ ParseArgsFromString(command_line_flags, &args);
90
+
91
+ std::vector<char*> argv;
92
+ int argc = ArgsToArgv(args, &argv);
93
+
94
+ // Fully initialize command line with arguments.
95
+ base::CommandLine::ForCurrentProcess()->AppendArguments(
96
+ base::CommandLine(argc, &argv[0]), false);
97
+ const base::CommandLine& command_line =
98
+ *base::CommandLine::ForCurrentProcess();
99
+
100
+ base::FilePath stdout_file_path(
101
+ base::android::ConvertJavaStringToUTF8(env, jstdout_file_path));
102
+
103
+ // A few options, such "--gtest_list_tests", will just use printf directly
104
+ // Always redirect stdout to a known file.
105
+ unlink(stdout_file_path.value().c_str());
106
+ if (jstdout_fifo) {
107
+ if (!base::android::CreateFIFO(stdout_file_path, 0666)) {
108
+ AndroidLog(ANDROID_LOG_ERROR, "Failed to create fifo %s: %s\n",
109
+ stdout_file_path.value().c_str(), strerror(errno));
110
+ exit(EXIT_FAILURE);
111
+ }
112
+ }
113
+ if (!base::android::RedirectStream(stdout, stdout_file_path, "w+")) {
114
+ AndroidLog(ANDROID_LOG_ERROR, "Failed to redirect stream to file: %s: %s\n",
115
+ stdout_file_path.value().c_str(), strerror(errno));
116
+ exit(EXIT_FAILURE);
117
+ }
118
+ dup2(STDOUT_FILENO, STDERR_FILENO);
119
+
120
+ if (command_line.HasSwitch(switches::kWaitForDebugger)) {
121
+ AndroidLog(ANDROID_LOG_VERBOSE,
122
+ "Native test waiting for GDB because flag %s was supplied",
123
+ switches::kWaitForDebugger);
124
+ base::debug::WaitForDebugger(24 * 60 * 60, false);
125
+ }
126
+
127
+ ScopedMainEntryLogger scoped_main_entry_logger;
128
+ main(argc, &argv[0]);
129
+ }
130
+
131
+ bool RegisterNativeTestJNI(JNIEnv* env) {
132
+ if (!base::android::RegisterJni(env)) {
133
+ return false;
134
+ }
135
+ return RegisterNativesImpl(env);
136
+ }
137
+
138
+ // TODO(nileshagrawal): now that we're using FIFO, test scripts can detect EOF.
139
+ // Remove the signal handlers.
140
+ void InstallHandlers() {
141
+ struct sigaction sa;
142
+ memset(&sa, 0, sizeof(sa));
143
+
144
+ sa.sa_sigaction = SignalHandler;
145
+ sa.sa_flags = SA_SIGINFO;
146
+
147
+ for (unsigned int i = 0; kExceptionSignals[i] != -1; ++i) {
148
+ sigaction(kExceptionSignals[i], &sa, &g_old_sa[kExceptionSignals[i]]);
149
+ }
150
+ }
151
+
152
+ } // namespace android
153
+ } // namespace testing
pool/shard006/C++/0078473_instantiation_test.cpp ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include"all_defines.hpp"
2
+ #include"objects.hpp"
3
+ #include"heaps.hpp"
4
+ #include"types.hpp"
5
+
6
+ #include<iostream>
7
+ #include<cassert>
8
+
9
+ class MyHeap : public Heap {
10
+ protected:
11
+ virtual void scan_root_object(GenericTraverser* gt) {
12
+ gt->traverse(r0);
13
+ gt->traverse(r1);
14
+ }
15
+ public:
16
+ Object::ref r0;
17
+ Object::ref r1;
18
+ explicit MyHeap(size_t sz) : Heap(sz) { }
19
+ };
20
+
21
+ class HlError {
22
+ public:
23
+ char const* val;
24
+ explicit HlError(char const* nval) : val(nval) { }
25
+ };
26
+
27
+ void throw_HlError(char const* t) {
28
+ throw HlError(t);
29
+ }
30
+
31
+ class OverBrokenHeart {
32
+ public:
33
+ Generic* cause;
34
+ explicit OverBrokenHeart(Generic* ncause) : cause(ncause) { }
35
+ };
36
+
37
+ void throw_OverBrokenHeart(Generic* cause) {
38
+ throw OverBrokenHeart(cause);
39
+ }
40
+
41
+ struct RangeError {
42
+ };
43
+ struct TypeError {
44
+ };
45
+
46
+ void throw_RangeError(const char*) {
47
+ throw RangeError();
48
+ }
49
+ void throw_TypeError(Object::ref, const char*) {
50
+ throw TypeError();
51
+ }
52
+
53
+ struct DeallocError {
54
+ };
55
+
56
+ void throw_DeallocError(void*) {
57
+ throw DeallocError();
58
+ }
59
+
60
+ int main(void) {
61
+ MyHeap tmp(sizeof(Cons));
62
+
63
+ std::cout << "allocating 1st" << std::endl;
64
+ tmp.r0 = Object::to_ref<Generic*>(tmp.create<Cons>());
65
+ std::cout << "r0 = @" << as_a<Generic*>(tmp.r0) << std::endl;
66
+
67
+ std::cout << "allocating 2nd" << std::endl;
68
+ tmp.r1 = Object::to_ref<Generic*>(tmp.create<Cons>());
69
+ scar(tmp.r1, tmp.r0);
70
+ std::cout << "r0 = @" << as_a<Generic*>(tmp.r0) << std::endl;
71
+ std::cout << "r1 = @" << as_a<Generic*>(tmp.r1) << std::endl;
72
+ assert(car(tmp.r1) == tmp.r0);
73
+
74
+ std::cout << "allocating 3rd" << std::endl;
75
+ tmp.r1 = Object::to_ref<Generic*>(tmp.create<Cons>());
76
+ scdr(tmp.r0, tmp.r1);
77
+ std::cout << "r0 = @" << as_a<Generic*>(tmp.r0) << std::endl;
78
+ std::cout << "r1 = @" << as_a<Generic*>(tmp.r1) << std::endl;
79
+ assert(cdr(tmp.r0) == tmp.r1);
80
+ }
81
+
pool/shard006/C++/0078478_moc_vscvideowall.cpp ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /****************************************************************************
2
+ ** Meta object code from reading C++ file 'vscvideowall.h'
3
+ **
4
+ ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.2)
5
+ **
6
+ ** WARNING! All changes made in this file will be lost!
7
+ *****************************************************************************/
8
+
9
+ #include "../../../vwidget/vscvideowall.h"
10
+ #include <QtCore/qbytearray.h>
11
+ #include <QtCore/qmetatype.h>
12
+ #if !defined(Q_MOC_OUTPUT_REVISION)
13
+ #error "The header file 'vscvideowall.h' doesn't include <QObject>."
14
+ #elif Q_MOC_OUTPUT_REVISION != 67
15
+ #error "This file was generated using the moc from 5.0.2. It"
16
+ #error "cannot be used with the include files from this version of Qt."
17
+ #error "(The moc has changed too much.)"
18
+ #endif
19
+
20
+ QT_BEGIN_MOC_NAMESPACE
21
+ struct qt_meta_stringdata_VSCVideoWall_t {
22
+ QByteArrayData data[15];
23
+ char stringdata[224];
24
+ };
25
+ #define QT_MOC_LITERAL(idx, ofs, len) \
26
+ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
27
+ offsetof(qt_meta_stringdata_VSCVideoWall_t, stringdata) + ofs \
28
+ - idx * sizeof(QByteArrayData) \
29
+ )
30
+ static const qt_meta_stringdata_VSCVideoWall_t qt_meta_stringdata_VSCVideoWall = {
31
+ {
32
+ QT_MOC_LITERAL(0, 0, 12),
33
+ QT_MOC_LITERAL(1, 13, 18),
34
+ QT_MOC_LITERAL(2, 32, 0),
35
+ QT_MOC_LITERAL(3, 33, 3),
36
+ QT_MOC_LITERAL(4, 37, 19),
37
+ QT_MOC_LITERAL(5, 57, 17),
38
+ QT_MOC_LITERAL(6, 75, 16),
39
+ QT_MOC_LITERAL(7, 92, 14),
40
+ QT_MOC_LITERAL(8, 107, 16),
41
+ QT_MOC_LITERAL(9, 124, 16),
42
+ QT_MOC_LITERAL(10, 141, 16),
43
+ QT_MOC_LITERAL(11, 158, 16),
44
+ QT_MOC_LITERAL(12, 175, 14),
45
+ QT_MOC_LITERAL(13, 190, 17),
46
+ QT_MOC_LITERAL(14, 208, 14)
47
+ },
48
+ "VSCVideoWall\0ShowDisplayClicked\0\0nId\0"
49
+ "ShowFloatingClicked\0ShowTabbedClicked\0"
50
+ "ShowFocusClicked\0floatingAction\0"
51
+ "unFloatingAction\0SetLayoutMode4x4\0"
52
+ "SetLayoutMode3x3\0SetLayoutMode2x2\0"
53
+ "SetLayoutMode6\0SetLayoutMode12p1\0"
54
+ "SetLayoutMode1\0"
55
+ };
56
+ #undef QT_MOC_LITERAL
57
+
58
+ static const uint qt_meta_data_VSCVideoWall[] = {
59
+
60
+ // content:
61
+ 7, // revision
62
+ 0, // classname
63
+ 0, 0, // classinfo
64
+ 12, 14, // methods
65
+ 0, 0, // properties
66
+ 0, 0, // enums/sets
67
+ 0, 0, // constructors
68
+ 0, // flags
69
+ 4, // signalCount
70
+
71
+ // signals: name, argc, parameters, tag, flags
72
+ 1, 1, 74, 2, 0x05,
73
+ 4, 0, 77, 2, 0x05,
74
+ 5, 0, 78, 2, 0x05,
75
+ 6, 1, 79, 2, 0x05,
76
+
77
+ // slots: name, argc, parameters, tag, flags
78
+ 7, 0, 82, 2, 0x0a,
79
+ 8, 0, 83, 2, 0x0a,
80
+ 9, 0, 84, 2, 0x0a,
81
+ 10, 0, 85, 2, 0x0a,
82
+ 11, 0, 86, 2, 0x0a,
83
+ 12, 0, 87, 2, 0x0a,
84
+ 13, 0, 88, 2, 0x0a,
85
+ 14, 0, 89, 2, 0x0a,
86
+
87
+ // signals: parameters
88
+ QMetaType::Void, QMetaType::Int, 3,
89
+ QMetaType::Void,
90
+ QMetaType::Void,
91
+ QMetaType::Void, QMetaType::Int, 3,
92
+
93
+ // slots: parameters
94
+ QMetaType::Void,
95
+ QMetaType::Void,
96
+ QMetaType::Void,
97
+ QMetaType::Void,
98
+ QMetaType::Void,
99
+ QMetaType::Void,
100
+ QMetaType::Void,
101
+ QMetaType::Void,
102
+
103
+ 0 // eod
104
+ };
105
+
106
+ void VSCVideoWall::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
107
+ {
108
+ if (_c == QMetaObject::InvokeMetaMethod) {
109
+ VSCVideoWall *_t = static_cast<VSCVideoWall *>(_o);
110
+ switch (_id) {
111
+ case 0: _t->ShowDisplayClicked((*reinterpret_cast< int(*)>(_a[1]))); break;
112
+ case 1: _t->ShowFloatingClicked(); break;
113
+ case 2: _t->ShowTabbedClicked(); break;
114
+ case 3: _t->ShowFocusClicked((*reinterpret_cast< int(*)>(_a[1]))); break;
115
+ case 4: _t->floatingAction(); break;
116
+ case 5: _t->unFloatingAction(); break;
117
+ case 6: _t->SetLayoutMode4x4(); break;
118
+ case 7: _t->SetLayoutMode3x3(); break;
119
+ case 8: _t->SetLayoutMode2x2(); break;
120
+ case 9: _t->SetLayoutMode6(); break;
121
+ case 10: _t->SetLayoutMode12p1(); break;
122
+ case 11: _t->SetLayoutMode1(); break;
123
+ default: ;
124
+ }
125
+ } else if (_c == QMetaObject::IndexOfMethod) {
126
+ int *result = reinterpret_cast<int *>(_a[0]);
127
+ void **func = reinterpret_cast<void **>(_a[1]);
128
+ {
129
+ typedef void (VSCVideoWall::*_t)(int );
130
+ if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowDisplayClicked)) {
131
+ *result = 0;
132
+ }
133
+ }
134
+ {
135
+ typedef void (VSCVideoWall::*_t)();
136
+ if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowFloatingClicked)) {
137
+ *result = 1;
138
+ }
139
+ }
140
+ {
141
+ typedef void (VSCVideoWall::*_t)();
142
+ if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowTabbedClicked)) {
143
+ *result = 2;
144
+ }
145
+ }
146
+ {
147
+ typedef void (VSCVideoWall::*_t)(int );
148
+ if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&VSCVideoWall::ShowFocusClicked)) {
149
+ *result = 3;
150
+ }
151
+ }
152
+ }
153
+ }
154
+
155
+ const QMetaObject VSCVideoWall::staticMetaObject = {
156
+ { &QWidget::staticMetaObject, qt_meta_stringdata_VSCVideoWall.data,
157
+ qt_meta_data_VSCVideoWall, qt_static_metacall, 0, 0}
158
+ };
159
+
160
+
161
+ const QMetaObject *VSCVideoWall::metaObject() const
162
+ {
163
+ return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
164
+ }
165
+
166
+ void *VSCVideoWall::qt_metacast(const char *_clname)
167
+ {
168
+ if (!_clname) return 0;
169
+ if (!strcmp(_clname, qt_meta_stringdata_VSCVideoWall.stringdata))
170
+ return static_cast<void*>(const_cast< VSCVideoWall*>(this));
171
+ return QWidget::qt_metacast(_clname);
172
+ }
173
+
174
+ int VSCVideoWall::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
175
+ {
176
+ _id = QWidget::qt_metacall(_c, _id, _a);
177
+ if (_id < 0)
178
+ return _id;
179
+ if (_c == QMetaObject::InvokeMetaMethod) {
180
+ if (_id < 12)
181
+ qt_static_metacall(this, _c, _id, _a);
182
+ _id -= 12;
183
+ } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
184
+ if (_id < 12)
185
+ *reinterpret_cast<int*>(_a[0]) = -1;
186
+ _id -= 12;
187
+ }
188
+ return _id;
189
+ }
190
+
191
+ // SIGNAL 0
192
+ void VSCVideoWall::ShowDisplayClicked(int _t1)
193
+ {
194
+ void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
195
+ QMetaObject::activate(this, &staticMetaObject, 0, _a);
196
+ }
197
+
198
+ // SIGNAL 1
199
+ void VSCVideoWall::ShowFloatingClicked()
200
+ {
201
+ QMetaObject::activate(this, &staticMetaObject, 1, 0);
202
+ }
203
+
204
+ // SIGNAL 2
205
+ void VSCVideoWall::ShowTabbedClicked()
206
+ {
207
+ QMetaObject::activate(this, &staticMetaObject, 2, 0);
208
+ }
209
+
210
+ // SIGNAL 3
211
+ void VSCVideoWall::ShowFocusClicked(int _t1)
212
+ {
213
+ void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
214
+ QMetaObject::activate(this, &staticMetaObject, 3, _a);
215
+ }
216
+ QT_END_MOC_NAMESPACE
pool/shard006/C++/0078481_PurchaseHostReservationRequest.cpp ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License").
5
+ * You may not use this file except in compliance with the License.
6
+ * A copy of the License is located at
7
+ *
8
+ * http://aws.amazon.com/apache2.0
9
+ *
10
+ * or in the "license" file accompanying this file. This file is distributed
11
+ * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12
+ * express or implied. See the License for the specific language governing
13
+ * permissions and limitations under the License.
14
+ */
15
+
16
+ #include <aws/ec2/model/PurchaseHostReservationRequest.h>
17
+ #include <aws/core/utils/StringUtils.h>
18
+ #include <aws/core/utils/memory/stl/AWSStringStream.h>
19
+
20
+ using namespace Aws::EC2::Model;
21
+ using namespace Aws::Utils;
22
+
23
+ PurchaseHostReservationRequest::PurchaseHostReservationRequest() :
24
+ m_offeringIdHasBeenSet(false),
25
+ m_hostIdSetHasBeenSet(false),
26
+ m_limitPriceHasBeenSet(false),
27
+ m_currencyCode(CurrencyCodeValues::NOT_SET),
28
+ m_currencyCodeHasBeenSet(false),
29
+ m_clientTokenHasBeenSet(false)
30
+ {
31
+ }
32
+
33
+ Aws::String PurchaseHostReservationRequest::SerializePayload() const
34
+ {
35
+ Aws::StringStream ss;
36
+ ss << "Action=PurchaseHostReservation&";
37
+ if(m_offeringIdHasBeenSet)
38
+ {
39
+ ss << "OfferingId=" << StringUtils::URLEncode(m_offeringId.c_str()) << "&";
40
+ }
41
+
42
+ if(m_hostIdSetHasBeenSet)
43
+ {
44
+ unsigned hostIdSetCount = 1;
45
+ for(auto& item : m_hostIdSet)
46
+ {
47
+ ss << "HostIdSet." << hostIdSetCount << "="
48
+ << StringUtils::URLEncode(item.c_str()) << "&";
49
+ hostIdSetCount++;
50
+ }
51
+ }
52
+
53
+ if(m_limitPriceHasBeenSet)
54
+ {
55
+ ss << "LimitPrice=" << StringUtils::URLEncode(m_limitPrice.c_str()) << "&";
56
+ }
57
+
58
+ if(m_currencyCodeHasBeenSet)
59
+ {
60
+ ss << "CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&";
61
+ }
62
+
63
+ if(m_clientTokenHasBeenSet)
64
+ {
65
+ ss << "ClientToken=" << StringUtils::URLEncode(m_clientToken.c_str()) << "&";
66
+ }
67
+
68
+ ss << "Version=2016-11-15";
69
+ return ss.str();
70
+ }
71
+
72
+
73
+ void PurchaseHostReservationRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
74
+ {
75
+ uri.SetQueryString(SerializePayload());
76
+ }
pool/shard006/C++/0078487_systemmodel.cpp ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /***************************************************************************
2
+ * Copyright (C) 2014 by Eike Hein <hein@kde.org> *
3
+ * *
4
+ * This program is free software; you can redistribute it and/or modify *
5
+ * it under the terms of the GNU General Public License as published by *
6
+ * the Free Software Foundation; either version 2 of the License, or *
7
+ * (at your option) any later version. *
8
+ * *
9
+ * This program is distributed in the hope that it will be useful, *
10
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12
+ * GNU General Public License for more details. *
13
+ * *
14
+ * You should have received a copy of the GNU General Public License *
15
+ * along with this program; if not, write to the *
16
+ * Free Software Foundation, Inc., *
17
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
18
+ ***************************************************************************/
19
+
20
+ #include "systemmodel.h"
21
+ #include "actionlist.h"
22
+
23
+ #include <QDBusConnection>
24
+ #include <QDBusInterface>
25
+ #include <QDBusPendingCall>
26
+
27
+ #include <KAuthorized>
28
+ #include <KConfigGroup>
29
+ #include <KLocalizedString>
30
+ #include <KSharedConfig>
31
+ #include <kworkspace.h>
32
+ #include <Solid/PowerManagement>
33
+ #include "ksmserver_interface.h"
34
+
35
+ SystemEntry::SystemEntry(SystemEntry::Action action, const QString &name, const QString &icon)
36
+ {
37
+ m_action = action;
38
+ m_name = name;
39
+ m_icon = QIcon::fromTheme(icon, QIcon::fromTheme("unknown"));
40
+ }
41
+
42
+ SystemModel::SystemModel(QObject *parent) : AbstractModel(parent)
43
+ {
44
+ m_favoriteIds[SystemEntry::LockSession] = "lock-screen";
45
+ m_favoriteIds[SystemEntry::LogoutSession] = "logout";
46
+ m_favoriteIds[SystemEntry::SaveSession] = "save-session";
47
+ m_favoriteIds[SystemEntry::NewSession] = "switch-user";
48
+ m_favoriteIds[SystemEntry::SuspendToRam] = "suspend";
49
+ m_favoriteIds[SystemEntry::SuspendToDisk] = "hibernate";
50
+ m_favoriteIds[SystemEntry::Reboot] = "reboot";
51
+ m_favoriteIds[SystemEntry::Shutdown] = "shutdown";
52
+
53
+ if (KAuthorized::authorizeKAction("lock_screen")) {
54
+ m_entryList << new SystemEntry(SystemEntry::LockSession, i18n("Lock"), "system-lock-screen");
55
+ }
56
+
57
+ if (KAuthorized::authorizeKAction("logout") && KAuthorized::authorize("logout")) {
58
+ m_entryList << new SystemEntry(SystemEntry::LogoutSession, i18n("Logout"), "system-log-out");
59
+
60
+ const KConfigGroup c(KSharedConfig::openConfig("ksmserverrc", KConfig::NoGlobals), "General");
61
+
62
+ if (c.readEntry("loginMode") == "restoreSavedSession") {
63
+ m_entryList << new SystemEntry(SystemEntry::SaveSession, i18n("Save Session"), "system-save-session");
64
+ }
65
+ }
66
+
67
+ if (KAuthorized::authorizeKAction("start_new_session")
68
+ && m_displayManager.isSwitchable()
69
+ && m_displayManager.numReserve() >= 0) {
70
+ m_entryList << new SystemEntry(SystemEntry::NewSession, i18n("New Session"), "system-switch-user");
71
+ }
72
+
73
+ QSet<Solid::PowerManagement::SleepState> sleepStates = Solid::PowerManagement::supportedSleepStates();
74
+
75
+ if (KAuthorized::authorizeKAction("logout") && KAuthorized::authorize("logout")) {
76
+ if (sleepStates.contains(Solid::PowerManagement::SuspendState)) {
77
+ m_entryList << new SystemEntry(SystemEntry::SuspendToRam, i18n("Suspend"), "system-suspend");
78
+ }
79
+
80
+ if (sleepStates.contains(Solid::PowerManagement::HibernateState)) {
81
+ m_entryList << new SystemEntry(SystemEntry::SuspendToDisk, i18n("Hibernate"), "system-suspend-hibernate");
82
+ }
83
+ }
84
+
85
+ m_entryList << new SystemEntry(SystemEntry::Reboot, i18n("Restart"), "system-reboot");
86
+ m_entryList << new SystemEntry(SystemEntry::Shutdown, i18n("Shutdown"), "system-shutdown");
87
+ }
88
+
89
+ SystemModel::~SystemModel()
90
+ {
91
+ qDeleteAll(m_entryList);
92
+ }
93
+
94
+ QVariant SystemModel::data(const QModelIndex &index, int role) const
95
+ {
96
+ if (!index.isValid() || index.row() >= m_entryList.count()) {
97
+ return QVariant();
98
+ }
99
+
100
+ if (role == Qt::DisplayRole) {
101
+ return m_entryList.at(index.row())->name();
102
+ } else if (role == Qt::DecorationRole) {
103
+ return m_entryList.at(index.row())->iconName();
104
+ } else if (role == Kicker::FavoriteIdRole) {
105
+ return QVariant("sys:" + m_favoriteIds[m_entryList.at(index.row())->action()]);
106
+ }
107
+
108
+ return QVariant();
109
+ }
110
+
111
+ int SystemModel::rowCount(const QModelIndex &parent) const
112
+ {
113
+ return parent.isValid() ? 0 : m_entryList.count();
114
+ }
115
+
116
+ bool SystemModel::trigger(int row, const QString &actionId, const QVariant &argument)
117
+ {
118
+ Q_UNUSED(actionId)
119
+ Q_UNUSED(argument)
120
+
121
+ if (row >= 0 && row < m_entryList.count()) {
122
+ SystemEntry::Action action = m_entryList.at(row)->action();
123
+
124
+ switch (action) {
125
+ case SystemEntry::LockSession:
126
+ {
127
+ QDBusConnection bus = QDBusConnection::sessionBus();
128
+ QDBusInterface interface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver", bus);
129
+ interface.asyncCall("Lock");
130
+ break;
131
+ }
132
+ case SystemEntry::LogoutSession:
133
+ KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeNone);
134
+ break;
135
+ case SystemEntry::SaveSession:
136
+ {
137
+ org::kde::KSMServerInterface ksmserver(QStringLiteral("org.kde.ksmserver"),
138
+ QStringLiteral("/KSMServer"), QDBusConnection::sessionBus());
139
+
140
+ if (ksmserver.isValid()) {
141
+ ksmserver.saveCurrentSession();
142
+ }
143
+
144
+ break;
145
+ }
146
+ case SystemEntry::NewSession:
147
+ {
148
+ QDBusConnection bus = QDBusConnection::sessionBus();
149
+ QDBusInterface interface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver", bus);
150
+ interface.asyncCall("Lock");
151
+ m_displayManager.startReserve();
152
+ break;
153
+ };
154
+ case SystemEntry::SuspendToRam:
155
+ Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState, 0, 0);
156
+ break;
157
+ case SystemEntry::SuspendToDisk:
158
+ Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState, 0, 0);
159
+ break;
160
+ case SystemEntry::Shutdown:
161
+ KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeHalt);
162
+ break;
163
+ case SystemEntry::Reboot:
164
+ KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeReboot);
165
+ break;
166
+ }
167
+
168
+ return true;
169
+ }
170
+
171
+ return false;
172
+ }
173
+
174
+ int SystemModel::rowForFavoriteId(const QString& favoriteId)
175
+ {
176
+ const SystemEntry::Action action = m_favoriteIds.key(favoriteId);
177
+
178
+ for (int i = 0; i < m_entryList.count(); ++i) {
179
+ if (action == m_entryList.at(i)->action()) {
180
+ return i;
181
+ }
182
+ }
183
+
184
+ return -1;
185
+ }
186
+
pool/shard006/C++/0078490_mrlock.cpp ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // mrlock.cpp
2
+ // author: Mr-Small
3
+ #include <stdio.h>
4
+ #include "mrlock.h"
5
+
6
+ namespace mrio {
7
+
8
+ // Constructor.
9
+ MrLock::MrLock()
10
+ : lock_(false)
11
+ , lockHandle_(INVALID_HANDLE) {
12
+ createHandle();
13
+ }
14
+
15
+ // Destructor.
16
+ MrLock::~MrLock() {
17
+ deleteHandle();
18
+ }
19
+
20
+ // Create handle for lock.
21
+ void MrLock::createHandle() {
22
+
23
+ #if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
24
+ // Create mutex handle.
25
+ lockHandle_ = CreateMutex(0, TRUE, NULL);
26
+ #elif defined(ANDROID)
27
+ // Create semaphore.
28
+ lockHandle_ = new sem_t;
29
+ sem_init(lockHandle_, 0, 1);
30
+ #else
31
+ // Create semaphore.
32
+ lockHandle_ = semget((key_t)1111, 1, 0666 | IPC_CREAT);
33
+ if (lockHandle_ != INVALID_HANDLE) {
34
+ union semuni semunion;
35
+ semunion.val = 1;
36
+ if (semctl(lockHandle_, 0, SETVAL, semunion) == -1) {
37
+ perror("create handle failed.");
38
+ }
39
+ }
40
+ #endif // WIIN
41
+ }
42
+
43
+ // Delete handle for lock.
44
+ void MrLock::deleteHandle() {
45
+
46
+ unlock();
47
+ if (lockHandle_ != INVALID_HANDLE) {
48
+ #if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
49
+ // Check mutex.
50
+ CloseHandle(lockHandle_);
51
+ #elif defined(ANDROID)
52
+ sem_destroy(lockHandle_);
53
+ #else
54
+ union semuni semunion;
55
+ if (semctl(lockHandle_, 0, IPC_RMID, semunion) == -1) {
56
+ perror("delete handle failed.");
57
+ }
58
+ #endif // WIN
59
+ lockHandle_ = INVALID_HANDLE;
60
+ }
61
+ lock_ = false;
62
+ }
63
+
64
+ // Lock with handle.
65
+ bool MrLock::lock() {
66
+
67
+ if (lock_) {
68
+ return true;
69
+ }
70
+
71
+ if (lockHandle_ == INVALID_HANDLE) {
72
+ perror("lock handle invalid.");
73
+ return false;
74
+ }
75
+
76
+ #if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
77
+
78
+ // Wait for single object.
79
+ if (WaitForSingleObject(lockHandle_, INFINITE) == WAIT_FAILED) {
80
+ perror("waitforsingleobject wait failed.");
81
+ return false;
82
+ }
83
+ #elif defined(ANDROID)
84
+ sem_wait(lockHandle_);
85
+ #else
86
+ // semaphore lock.
87
+ sembuf_.sem_num = 0;
88
+ sembuf_.sem_op = -1;
89
+ sembuf_.sem_flg = SEM_UNDO;
90
+
91
+ if (semop(lockHandle_, &sembuf_, 1) == -1) {
92
+ perror("semop failed.");
93
+ }
94
+ #endif // WIN
95
+
96
+ lock_ = true;
97
+ return true;
98
+ }
99
+
100
+ // Unlock.
101
+ void MrLock::unlock() {
102
+
103
+ if (!lock_) {
104
+ return;
105
+ }
106
+ #if defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
107
+ ReleaseMutex(lockHandle_);
108
+ #elif defined(ANDROID)
109
+ sem_post(lockHandle_);
110
+ #else
111
+ sembuf_.sem_op = 1;
112
+ if (semop(lockHandle_, &sembuf_, 1) == -1) {
113
+ perror("semop failed.");
114
+ }
115
+ #endif // WIN
116
+ lock_ = false;
117
+ }
118
+
119
+ // Check locked.
120
+ bool MrLock::isLocked() {
121
+ return lock_;
122
+ }
123
+
124
+ } // namespace mrio
pool/shard006/C++/0078491_main.cpp ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* This file is part of Music Shelf
2
+ * Copyright (C) 2011 Martin Grimme <martin.grimme _AT_ gmail.com>
3
+ *
4
+ * This program is free software; you can redistribute it and/or modify
5
+ * it under the terms of the GNU General Public License as published by
6
+ * the Free Software Foundation; either version 2 of the License, or
7
+ * (at your option) any later version.
8
+ *
9
+ * This program is distributed in the hope that it will be useful,
10
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ * GNU General Public License for more details.
13
+ *
14
+ * You should have received a copy of the GNU General Public License
15
+ * along with this program; if not, write to the Free Software
16
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
+ */
18
+
19
+
20
+ #include <QGuiApplication>
21
+ #include <QQuickView>
22
+ #include <QtQml>
23
+ #include <QQmlComponent>
24
+ #include <QQmlContext>
25
+ #include <QDir>
26
+ #include <QDesktopServices>
27
+ #include <QDebug>
28
+
29
+ #include "context.h"
30
+ #include "foldermodel.h"
31
+ #include "mobilitybackend.h"
32
+
33
+ #include "mediabox-core/abstractbackend.h"
34
+ #include "mediabox-core/contentmodel.h"
35
+ #include "mediabox-core/contentprovider.h"
36
+ #include "mediabox-core/datadirectory.h"
37
+ #include "mediabox-core/player.h"
38
+ #include "mediabox-core/playqueue.h"
39
+
40
+ #ifdef HAS_BOOSTER
41
+ #include <MDeclarativeCache>
42
+ #endif
43
+
44
+ #ifdef HAS_BOOSTER
45
+ Q_DECL_EXPORT
46
+ #endif
47
+ int main(int argc, char *argv[])
48
+ {
49
+ QGuiApplication* application;
50
+ QQuickView* view;
51
+
52
+ DataDirectory::initialize();
53
+ #ifdef HAS_BOOSTER
54
+ application = MDeclarativeCache::qApplication(argc, argv);
55
+ view = MDeclarativeCache::qQuickView();
56
+ #else
57
+ qWarning() << Q_FUNC_INFO << "Warning! Running without booster. This may be a bit slower.";
58
+ QGuiApplication stackApp(argc, argv);
59
+ QQuickView stackView;
60
+ application = &stackApp;
61
+ view = &stackView;
62
+ #endif
63
+ QGuiApplication::setOrganizationDomain("org.nemomobile");
64
+ QGuiApplication::setOrganizationName("nemomobile");
65
+ application->setApplicationName("Music Player");
66
+ Context context;
67
+
68
+ media::Player player;
69
+ MobilityBackend backend;
70
+ player.registerBackend("mobility", &backend);
71
+ player.selectBackend("mobility");
72
+
73
+ qDebug() << "setting up playing queue";
74
+ media::PlayQueue *playQueue = new media::PlayQueue;
75
+ QGuiApplication::connect(playQueue, SIGNAL(itemChanged(content::File::Ptr)),
76
+ &player, SLOT(load(content::File::Ptr)));
77
+ QGuiApplication::connect(&player, SIGNAL(eofReached()),
78
+ playQueue, SLOT(next()));
79
+
80
+ FolderModel folderModel;
81
+
82
+ // export into QML world
83
+ view->rootContext()->setContextProperty("context", &context);
84
+ view->rootContext()->setContextProperty("folderModel", &folderModel);
85
+ view->rootContext()->setContextProperty("albumModel",
86
+ context.contentProvider()->createModel());
87
+ view->rootContext()->setContextProperty("tracksModel",
88
+ context.contentProvider()->createModel());
89
+ view->rootContext()->setContextProperty("player", &player);
90
+ view->rootContext()->setContextProperty("playQueue", playQueue);
91
+
92
+ view->setSource(QUrl("qrc:/qml/main.qml"));
93
+ view->setResizeMode(QQuickView::SizeRootObjectToView);
94
+
95
+ #if defined(QML_MEDIA_PLAYER_DESKTOP_BUILD)
96
+ QScreen *desktop = QGuiApplication::primaryScreen();
97
+ if (desktop->physicalSize().height() < 1000) {
98
+ win.scale(.8, .8);
99
+ win.resize(win.size() * .8);
100
+ }
101
+ view->show();
102
+ #else
103
+ view->showFullScreen();
104
+ #endif
105
+
106
+ return application->exec();
107
+ }
pool/shard006/C++/0078497_multisiginputentry.cpp ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <QApplication>
2
+ #include <QClipboard>
3
+ #include <string>
4
+ #include <vector>
5
+
6
+ #include "base58.h"
7
+ #include "multisiginputentry.h"
8
+ #include "ui_multisiginputentry.h"
9
+ #include "main.h"
10
+ #include "script.h"
11
+ #include "util.h"
12
+ #include "wallet.h"
13
+ #include "walletmodel.h"
14
+
15
+
16
+ MultisigInputEntry::MultisigInputEntry(QWidget *parent) : QFrame(parent), ui(new Ui::MultisigInputEntry), model(0)
17
+ {
18
+ ui->setupUi(this);
19
+ }
20
+
21
+ MultisigInputEntry::~MultisigInputEntry()
22
+ {
23
+ delete ui;
24
+ }
25
+
26
+ void MultisigInputEntry::setModel(WalletModel *model)
27
+ {
28
+ this->model = model;
29
+ clear();
30
+ }
31
+
32
+ void MultisigInputEntry::clear()
33
+ {
34
+ ui->transactionId->clear();
35
+ ui->transactionOutput->clear();
36
+ ui->redeemScript->clear();
37
+ }
38
+
39
+ bool MultisigInputEntry::validate()
40
+ {
41
+ return (ui->transactionOutput->count() > 0);
42
+ }
43
+
44
+ CTxIn MultisigInputEntry::getInput()
45
+ {
46
+ unsigned int nOutput = ui->transactionOutput->currentIndex();
47
+ CTxIn input(COutPoint(txHash, nOutput));
48
+
49
+ return input;
50
+ }
51
+
52
+ int64_t MultisigInputEntry::getAmount()
53
+ {
54
+ int64_t amount = 0;
55
+ unsigned int nOutput = ui->transactionOutput->currentIndex();
56
+ CTransaction tx;
57
+ uint256 blockHash = 0;
58
+
59
+ if(GetTransaction(txHash, tx, blockHash))
60
+ {
61
+ if(nOutput < tx.vout.size())
62
+ {
63
+ const CTxOut& txOut = tx.vout[nOutput];
64
+ amount = txOut.nValue;
65
+ }
66
+ }
67
+
68
+ return amount;
69
+ }
70
+
71
+ QString MultisigInputEntry::getRedeemScript()
72
+ {
73
+ return ui->redeemScript->text();
74
+ }
75
+
76
+ void MultisigInputEntry::setTransactionId(QString transactionId)
77
+ {
78
+ ui->transactionId->setText(transactionId);
79
+ }
80
+
81
+ void MultisigInputEntry::setTransactionOutputIndex(int index)
82
+ {
83
+ ui->transactionOutput->setCurrentIndex(index);
84
+ }
85
+
86
+ void MultisigInputEntry::setRemoveEnabled(bool enabled)
87
+ {
88
+ ui->deleteButton->setEnabled(enabled);
89
+ }
90
+
91
+ void MultisigInputEntry::on_pasteTransactionIdButton_clicked()
92
+ {
93
+ ui->transactionId->setText(QApplication::clipboard()->text());
94
+ }
95
+
96
+ void MultisigInputEntry::on_deleteButton_clicked()
97
+ {
98
+ emit removeEntry(this);
99
+ }
100
+
101
+ void MultisigInputEntry::on_pasteRedeemScriptButton_clicked()
102
+ {
103
+ ui->redeemScript->setText(QApplication::clipboard()->text());
104
+ }
105
+
106
+ void MultisigInputEntry::on_transactionId_textChanged(const QString &transactionId)
107
+ {
108
+ ui->transactionOutput->clear();
109
+ if(transactionId.isEmpty())
110
+ return;
111
+
112
+ // Make list of transaction outputs
113
+ txHash.SetHex(transactionId.toStdString().c_str());
114
+ CTransaction tx;
115
+ uint256 blockHash = 0;
116
+ if(!GetTransaction(txHash, tx, blockHash))
117
+ return;
118
+ for(unsigned int i = 0; i < tx.vout.size(); i++)
119
+ {
120
+ QString idStr;
121
+ idStr.setNum(i);
122
+ const CTxOut& txOut = tx.vout[i];
123
+ int64_t amount = txOut.nValue;
124
+ QString amountStr;
125
+ amountStr.sprintf("%.6f", (double) amount / COIN);
126
+ CScript script = txOut.scriptPubKey;
127
+ CTxDestination addr;
128
+ if(ExtractDestination(script, addr))
129
+ {
130
+ CBitcoinAddress address(addr);
131
+ QString addressStr(address.ToString().c_str());
132
+ ui->transactionOutput->addItem(idStr + QString(" - ") + addressStr + QString(" - ") + amountStr + QString(" MSCN"));
133
+ }
134
+ else
135
+ ui->transactionOutput->addItem(idStr + QString(" - ") + amountStr + QString(" MSCN"));
136
+ }
137
+ }
138
+
139
+ void MultisigInputEntry::on_transactionOutput_currentIndexChanged(int index)
140
+ {
141
+ if(ui->transactionOutput->itemText(index).isEmpty())
142
+ return;
143
+
144
+ CTransaction tx;
145
+ uint256 blockHash = 0;
146
+ if(!GetTransaction(txHash, tx, blockHash))
147
+ return;
148
+ const CTxOut& txOut = tx.vout[index];
149
+ CScript script = txOut.scriptPubKey;
150
+
151
+ if(script.IsPayToScriptHash())
152
+ {
153
+ ui->redeemScript->setEnabled(true);
154
+
155
+ if(model)
156
+ {
157
+ // Try to find the redeem script
158
+ CTxDestination dest;
159
+ if(ExtractDestination(script, dest))
160
+ {
161
+ CScriptID scriptID = boost::get<CScriptID>(dest);
162
+ CScript redeemScript;
163
+ if(model->getWallet()->GetCScript(scriptID, redeemScript))
164
+ ui->redeemScript->setText(HexStr(redeemScript.begin(), redeemScript.end()).c_str());
165
+ }
166
+ }
167
+ }
168
+ else
169
+ {
170
+ ui->redeemScript->setEnabled(false);
171
+ }
172
+
173
+ emit updateAmount();
174
+ }
pool/shard006/C++/0078507_JSCSSValueCustom.cpp ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions
6
+ * are met:
7
+ * 1. Redistributions of source code must retain the above copyright
8
+ * notice, this list of conditions and the following disclaimer.
9
+ * 2. Redistributions in binary form must reproduce the above copyright
10
+ * notice, this list of conditions and the following disclaimer in the
11
+ * documentation and/or other materials provided with the distribution.
12
+ *
13
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
+ */
25
+
26
+ #include "config.h"
27
+ #include "JSCSSValue.h"
28
+
29
+ #include "CSSPrimitiveValue.h"
30
+ #include "CSSValueList.h"
31
+ #include "JSCSSPrimitiveValue.h"
32
+ #include "JSCSSValueList.h"
33
+ #include "JSWebKitCSSTransformValue.h"
34
+ #include "WebKitCSSTransformValue.h"
35
+
36
+ #if ENABLE(SVG)
37
+ #include "JSSVGColor.h"
38
+ #include "JSSVGPaint.h"
39
+ #include "SVGColor.h"
40
+ #include "SVGPaint.h"
41
+ #endif
42
+
43
+ using namespace JSC;
44
+
45
+ namespace WebCore {
46
+
47
+ JSValue toJS(ExecState* exec, JSDOMGlobalObject* globalObject, CSSValue* value)
48
+ {
49
+ if (!value)
50
+ return jsNull();
51
+
52
+ DOMObject* wrapper = getCachedDOMObjectWrapper(exec, value);
53
+
54
+ if (wrapper)
55
+ return wrapper;
56
+
57
+ if (value->isWebKitCSSTransformValue())
58
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, WebKitCSSTransformValue, value);
59
+ else if (value->isValueList())
60
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSValueList, value);
61
+ #if ENABLE(SVG)
62
+ else if (value->isSVGPaint())
63
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, SVGPaint, value);
64
+ else if (value->isSVGColor())
65
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, SVGColor, value);
66
+ #endif
67
+ else if (value->isPrimitiveValue())
68
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSPrimitiveValue, value);
69
+ else
70
+ wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, globalObject, CSSValue, value);
71
+
72
+ return wrapper;
73
+ }
74
+
75
+ } // namespace WebCore
pool/shard006/C++/0078514_jdtrans.cpp ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * jdtrans.c
3
+ *
4
+ * Copyright (C) 1995, Thomas G. Lane.
5
+ * This file is part of the Independent JPEG Group's software.
6
+ * For conditions of distribution and use, see the accompanying README file.
7
+ *
8
+ * This file contains library routines for transcoding decompression,
9
+ * that is, reading raw DCT coefficient arrays from an input JPEG file.
10
+ * The routines in jdapimin.c will also be needed by a transcoder.
11
+ */
12
+
13
+ #define JPEG_INTERNALS
14
+ #include "jinclude.h"
15
+ #include "jpeglib.h"
16
+
17
+
18
+ /* Forward declarations */
19
+ LOCAL void transdecode_master_selection JPP( (j_decompress_ptr cinfo) );
20
+
21
+
22
+ /*
23
+ * Read the coefficient arrays from a JPEG file.
24
+ * jpeg_read_header must be completed before calling this.
25
+ *
26
+ * The entire image is read into a set of virtual coefficient-block arrays,
27
+ * one per component. The return value is a pointer to the array of
28
+ * virtual-array descriptors. These can be manipulated directly via the
29
+ * JPEG memory manager, or handed off to jpeg_write_coefficients().
30
+ * To release the memory occupied by the virtual arrays, call
31
+ * jpeg_finish_decompress() when done with the data.
32
+ *
33
+ * Returns NULL if suspended. This case need be checked only if
34
+ * a suspending data source is used.
35
+ */
36
+
37
+ GLOBAL jvirt_barray_ptr *
38
+ jpeg_read_coefficients( j_decompress_ptr cinfo ) {
39
+ if ( cinfo->global_state == DSTATE_READY ) {
40
+ /* First call: initialize active modules */
41
+ transdecode_master_selection( cinfo );
42
+ cinfo->global_state = DSTATE_RDCOEFS;
43
+ } else if ( cinfo->global_state != DSTATE_RDCOEFS ) {
44
+ ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state );
45
+ }
46
+ /* Absorb whole file into the coef buffer */
47
+ for (;; ) {
48
+ int retcode;
49
+ /* Call progress monitor hook if present */
50
+ if ( cinfo->progress != NULL ) {
51
+ ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo );
52
+ }
53
+ /* Absorb some more input */
54
+ retcode = ( *cinfo->inputctl->consume_input )( cinfo );
55
+ if ( retcode == JPEG_SUSPENDED ) {
56
+ return NULL;
57
+ }
58
+ if ( retcode == JPEG_REACHED_EOI ) {
59
+ break;
60
+ }
61
+ /* Advance progress counter if appropriate */
62
+ if ( ( cinfo->progress != NULL ) &&
63
+ ( ( retcode == JPEG_ROW_COMPLETED ) || ( retcode == JPEG_REACHED_SOS ) ) ) {
64
+ if ( ++cinfo->progress->pass_counter >= cinfo->progress->pass_limit ) {
65
+ /* startup underestimated number of scans; ratchet up one scan */
66
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
67
+ }
68
+ }
69
+ }
70
+ /* Set state so that jpeg_finish_decompress does the right thing */
71
+ cinfo->global_state = DSTATE_STOPPING;
72
+ return cinfo->coef->coef_arrays;
73
+ }
74
+
75
+
76
+ /*
77
+ * Master selection of decompression modules for transcoding.
78
+ * This substitutes for jdmaster.c's initialization of the full decompressor.
79
+ */
80
+
81
+ LOCAL void
82
+ transdecode_master_selection( j_decompress_ptr cinfo ) {
83
+ /* Entropy decoding: either Huffman or arithmetic coding. */
84
+ if ( cinfo->arith_code ) {
85
+ ERREXIT( cinfo, JERR_ARITH_NOTIMPL );
86
+ } else {
87
+ if ( cinfo->progressive_mode ) {
88
+ #ifdef D_PROGRESSIVE_SUPPORTED
89
+ jinit_phuff_decoder( cinfo );
90
+ #else
91
+ ERREXIT( cinfo, JERR_NOT_COMPILED );
92
+ #endif
93
+ } else {
94
+ jinit_huff_decoder( cinfo );
95
+ }
96
+ }
97
+
98
+ /* Always get a full-image coefficient buffer. */
99
+ jinit_d_coef_controller( cinfo, TRUE );
100
+
101
+ /* We can now tell the memory manager to allocate virtual arrays. */
102
+ ( *cinfo->mem->realize_virt_arrays )( (j_common_ptr) cinfo );
103
+
104
+ /* Initialize input side of decompressor to consume first scan. */
105
+ ( *cinfo->inputctl->start_input_pass )( cinfo );
106
+
107
+ /* Initialize progress monitoring. */
108
+ if ( cinfo->progress != NULL ) {
109
+ int nscans;
110
+ /* Estimate number of scans to set pass_limit. */
111
+ if ( cinfo->progressive_mode ) {
112
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
113
+ nscans = 2 + 3 * cinfo->num_components;
114
+ } else if ( cinfo->inputctl->has_multiple_scans ) {
115
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
116
+ nscans = cinfo->num_components;
117
+ } else {
118
+ nscans = 1;
119
+ }
120
+ cinfo->progress->pass_counter = 0L;
121
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
122
+ cinfo->progress->completed_passes = 0;
123
+ cinfo->progress->total_passes = 1;
124
+ }
125
+ }
pool/shard006/C++/0078515_boss_SpoilsOfPandaria.cpp ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/>
3
+ * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it
6
+ * under the terms of the GNU General Public License as published by the
7
+ * Free Software Foundation; either version 2 of the License, or (at your
8
+ * option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful, but WITHOUT
11
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13
+ * more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License along
16
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "ScriptMgr.h"
20
+ #include "ScriptedCreature.h"
21
+ #include "SiegeOfOrgrimmar.h"
22
+
23
+ enum Texts
24
+ {
25
+ SAY_AGGRO = 0,
26
+ SAY_EARTHQUAKE = 1,
27
+ SAY_OVERRUN = 2,
28
+ SAY_SLAY = 3,
29
+ SAY_DEATH = 4
30
+ };
31
+
32
+ enum Spells
33
+ {
34
+ SPELL_EARTHQUAKE = 153616,
35
+ SPELL_SUNDER_ARMOR = 153726,
36
+ SPELL_CHAIN_LIGHTNING = 153764,
37
+ SPELL_OVERRUN = 154221,
38
+ SPELL_ENRAGE = 157173,
39
+ SPELL_MARK_DEATH = 153234,
40
+ SPELL_AURA_DEATH = 153616
41
+ };
42
+
43
+ enum Events
44
+ {
45
+ EVENT_ENRAGE = 1,
46
+ EVENT_ARMOR = 2,
47
+ EVENT_CHAIN = 3,
48
+ EVENT_QUAKE = 4,
49
+ EVENT_OVERRUN = 5
50
+ };
51
+
52
+ class boss_SpoilsOfPandaria : public CreatureScript
53
+ {
54
+ public:
55
+ boss_SpoilsOfPandaria() : CreatureScript("boss_SpoilsOfPandaria") { }
56
+
57
+ struct boss_SpoilsOfPandariaAI : public ScriptedAI
58
+ {
59
+ boss_SpoilsOfPandariaAI(Creature* creature) : ScriptedAI(creature)
60
+ {
61
+ Initialize();
62
+ }
63
+
64
+ void Initialize()
65
+ {
66
+ _inEnrage = false;
67
+ }
68
+
69
+ void Reset() override
70
+ {
71
+ _events.Reset();
72
+ _events.ScheduleEvent(EVENT_ENRAGE, 0);
73
+ _events.ScheduleEvent(EVENT_ARMOR, urand(5000, 13000));
74
+ _events.ScheduleEvent(EVENT_CHAIN, urand(10000, 30000));
75
+ _events.ScheduleEvent(EVENT_QUAKE, urand(25000, 35000));
76
+ _events.ScheduleEvent(EVENT_OVERRUN, urand(30000, 45000));
77
+ Initialize();
78
+ }
79
+
80
+ void KilledUnit(Unit* victim) override
81
+ {
82
+ victim->CastSpell(victim, SPELL_MARK_DEATH, 0);
83
+
84
+ if (urand(0, 4))
85
+ return;
86
+
87
+ Talk(SAY_SLAY);
88
+ }
89
+
90
+ void JustDied(Unit* /*killer*/) override
91
+ {
92
+ Talk(SAY_DEATH);
93
+ }
94
+
95
+ void EnterCombat(Unit* /*who*/) override
96
+ {
97
+ Talk(SAY_AGGRO);
98
+ }
99
+
100
+ void MoveInLineOfSight(Unit* who) override
101
+
102
+ {
103
+ if (who && who->GetTypeId() == TYPEID_PLAYER && me->IsValidAttackTarget(who))
104
+ if (who->HasAura(SPELL_MARK_DEATH))
105
+ who->CastSpell(who, SPELL_AURA_DEATH, 1);
106
+ }
107
+
108
+ void UpdateAI(uint32 diff) override
109
+ {
110
+ if (!UpdateVictim())
111
+ return;
112
+
113
+ _events.Update(diff);
114
+
115
+ if (me->HasUnitState(UNIT_STATE_CASTING))
116
+ return;
117
+
118
+ while (uint32 eventId = _events.ExecuteEvent())
119
+ {
120
+ switch (eventId)
121
+ {
122
+ case EVENT_ENRAGE:
123
+ if (!HealthAbovePct(20))
124
+ {
125
+ DoCast(me, SPELL_ENRAGE);
126
+ _events.ScheduleEvent(EVENT_ENRAGE, 6000);
127
+ _inEnrage = true;
128
+ }
129
+ break;
130
+ case EVENT_OVERRUN:
131
+ Talk(SAY_OVERRUN);
132
+ DoCastVictim(SPELL_OVERRUN);
133
+ _events.ScheduleEvent(EVENT_OVERRUN, urand(25000, 40000));
134
+ break;
135
+ case EVENT_QUAKE:
136
+ if (urand(0, 1))
137
+ return;
138
+
139
+ Talk(SAY_EARTHQUAKE);
140
+
141
+ //remove enrage before casting earthquake because enrage + earthquake = 16000dmg over 8sec and all dead
142
+ if (_inEnrage)
143
+ me->RemoveAurasDueToSpell(SPELL_ENRAGE);
144
+
145
+ DoCast(me, SPELL_EARTHQUAKE);
146
+ _events.ScheduleEvent(EVENT_QUAKE, urand(30000, 55000));
147
+ break;
148
+ case EVENT_CHAIN:
149
+ if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true))
150
+ DoCast(target, SPELL_CHAIN_LIGHTNING);
151
+ _events.ScheduleEvent(EVENT_CHAIN, urand(7000, 27000));
152
+ break;
153
+ case EVENT_ARMOR:
154
+ DoCastVictim(SPELL_SUNDER_ARMOR);
155
+ _events.ScheduleEvent(EVENT_ARMOR, urand(10000, 25000));
156
+ break;
157
+ default:
158
+ break;
159
+ }
160
+ }
161
+ DoMeleeAttackIfReady();
162
+ }
163
+
164
+ private:
165
+ EventMap _events;
166
+ bool _inEnrage;
167
+ };
168
+
169
+ CreatureAI* GetAI(Creature* creature) const override
170
+ {
171
+ return new boss_SpoilsOfPandariaAI(creature);
172
+ }
173
+ };
174
+
175
+ void AddSC_boss_SpoilsOfPandaria()
176
+ {
177
+ new boss_SpoilsOfPandaria();
178
+ }
pool/shard006/C++/0078516_RGBLed.cpp ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "RGBLed.h"
2
+ /**
3
+ * RGBLed
4
+ * Default constructor, init class value and set com PIN to 8,9,10
5
+ */
6
+
7
+ RGBLed :: RGBLed()
8
+ {
9
+ redPin = 6;
10
+ greenPin = 9;
11
+ bluePin = 8;
12
+
13
+ }
14
+
15
+ /**
16
+ * RGBLed
17
+ * Overrided constructor, init set com PIN with param
18
+ * @param _redPin
19
+ * @param _greenPin
20
+ * @param _bluePin
21
+ */
22
+
23
+ RGBLed :: RGBLed(int _redPin,int _greenPin,int _bluePin)
24
+ {
25
+ redPin = _redPin;
26
+ greenPin = _greenPin;
27
+ bluePin = _bluePin;
28
+ }
29
+
30
+ /**
31
+ * lightOn
32
+ * set color value green, blue, red
33
+ * @param red
34
+ * @param green
35
+ * @param blue
36
+ */
37
+ void RGBLed :: lightOn(int red,int green,int blue)
38
+ {
39
+ analogWrite(redPin, red);
40
+ analogWrite(greenPin, green);
41
+ analogWrite(bluePin, blue);
42
+ }
43
+
44
+ /**
45
+ * lightOff
46
+ * switchOff RGB Led
47
+ */
48
+ void RGBLed :: lightOff()
49
+ {
50
+ analogWrite(redPin, 0);
51
+ analogWrite(greenPin, 0);
52
+ analogWrite(bluePin, 0);
53
+ }
54
+
55
+
pool/shard006/C++/0078519_iniparser.cpp ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * This file is a part of ncxmms2, an XMMS2 Client.
3
+ *
4
+ * Copyright (C) 2011-2015 Pavel Kunavin <tusk.kun@gmail.com>
5
+ *
6
+ * This program is free software; you can redistribute it and/or
7
+ * modify it under the terms of the GNU General Public License
8
+ * as published by the Free Software Foundation; either version 2
9
+ * of the License, or (at your option) any later version.
10
+ *
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ * GNU General Public License for more details.
15
+ */
16
+
17
+ #include <glib.h>
18
+ #include "iniparser.h"
19
+
20
+ namespace ncxmms2 {
21
+
22
+ class IniParserPrivate
23
+ {
24
+ public:
25
+ IniParserPrivate() :
26
+ keyFile(nullptr) {}
27
+
28
+ std::string errorString;
29
+ std::string filePath;
30
+ GKeyFile *keyFile;
31
+
32
+ void closeFile();
33
+ };
34
+ } // ncxmms2
35
+
36
+ using namespace ncxmms2;
37
+
38
+ void IniParserPrivate::closeFile()
39
+ {
40
+ errorString.clear();
41
+ if (keyFile) {
42
+ g_key_file_free(keyFile);
43
+ keyFile = nullptr;
44
+ }
45
+ }
46
+
47
+ IniParser::IniParser() :
48
+ d(new IniParserPrivate())
49
+ {
50
+
51
+ }
52
+
53
+ IniParser::~IniParser()
54
+ {
55
+ sync();
56
+ d->closeFile();
57
+ }
58
+
59
+ void IniParser::setFile(const std::string& file)
60
+ {
61
+ sync();
62
+ d->closeFile();
63
+
64
+ d->filePath = file;
65
+ d->keyFile = g_key_file_new();
66
+ GError *error = nullptr;
67
+ if (!g_key_file_load_from_file(d->keyFile, d->filePath.c_str(),
68
+ G_KEY_FILE_KEEP_COMMENTS, &error)) {
69
+ d->errorString = error->message;
70
+ g_error_free(error);
71
+ }
72
+ }
73
+
74
+ void IniParser::sync()
75
+ {
76
+ if (!d->keyFile)
77
+ return;
78
+
79
+ gsize size;
80
+ gchar *data = g_key_file_to_data(d->keyFile, &size, nullptr);
81
+
82
+ GError *error = nullptr;
83
+ g_file_set_contents(d->filePath.c_str(), data, size, &error);
84
+ if (error) {
85
+ d->errorString = error->message;
86
+ g_error_free(error);
87
+ }
88
+ g_free(data);
89
+ }
90
+
91
+ bool IniParser::isOk() const
92
+ {
93
+ return d->errorString.empty();
94
+ }
95
+
96
+ std::string IniParser::errorString() const
97
+ {
98
+ return d->errorString;
99
+ }
100
+
101
+ void IniParser::setValue(const std::string& group, const std::string& key, int value)
102
+ {
103
+ if (!d->keyFile)
104
+ return;
105
+
106
+ g_key_file_set_integer(d->keyFile, group.c_str(), key.c_str(), value);
107
+ }
108
+
109
+ void IniParser::setValue(const std::string& group, const std::string& key, const std::string& value)
110
+ {
111
+ if (!d->keyFile)
112
+ return;
113
+
114
+ g_key_file_set_string(d->keyFile, group.c_str(), key.c_str(), value.c_str());
115
+ }
116
+
117
+ void IniParser::setValue(const std::string& group, const std::string& key, bool value)
118
+ {
119
+ if (!d->keyFile)
120
+ return;
121
+
122
+ g_key_file_set_boolean(d->keyFile, group.c_str(), key.c_str(), value);
123
+ }
124
+
125
+ void IniParser::getValue(const std::string& group, const std::string& key, int *value) const
126
+ {
127
+ if (!d->keyFile)
128
+ return;
129
+
130
+ GError *error = nullptr;
131
+ int val = g_key_file_get_integer(d->keyFile, group.c_str(), key.c_str(), &error);
132
+ if (error) {
133
+ g_error_free(error);;
134
+ } else {
135
+ *value = val;
136
+ }
137
+ }
138
+
139
+ void IniParser::getValue(const std::string& group, const std::string& key, std::string *value) const
140
+ {
141
+ if (!d->keyFile)
142
+ return;
143
+
144
+ gchar *string = g_key_file_get_string(d->keyFile, group.c_str(), key.c_str(), nullptr);
145
+ if (string) {
146
+ value->assign(string);
147
+ g_free(string);
148
+ }
149
+ }
150
+
151
+ void IniParser::getValue(const std::string& group, const std::string& key, bool *value) const
152
+ {
153
+ if (!d->keyFile)
154
+ return;
155
+
156
+ GError *error = nullptr;
157
+ gboolean val = g_key_file_get_boolean(d->keyFile, group.c_str(), key.c_str(), &error);
158
+ if (error) {
159
+ g_error_free(error);;
160
+ } else {
161
+ *value = val;
162
+ }
163
+ }
164
+
165
+
pool/shard006/C++/0078520_06.cpp ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bm_oopsla.h"
2
+
3
+ int main(int argc, char * argv[]) {
4
+ RECORD(4, w, x, y, z);
5
+
6
+ w = 1;
7
+ z = 0;
8
+ x = 0;
9
+ y = 0;
10
+
11
+ while (unknown1()) {
12
+ PRINT_VARS();
13
+ PRINT_BAR(1);
14
+
15
+ while (unknown2()) {
16
+ PRINT_VARS();
17
+
18
+ if (w % 2 == 1) x++;
19
+ if (z % 2 == 0) y++;
20
+ }
21
+ PRINT_VARS();
22
+ PRINT_BAR(2);
23
+
24
+ z = x + y;
25
+ w = z + 1;
26
+ }
27
+ PRINT_VARS();
28
+ PRINT_BAR(1);
29
+
30
+ assert(x == y);
31
+ }
pool/shard006/C++/0078524_FlightMapSettings.cc ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*=====================================================================
2
+
3
+ QGroundControl Open Source Ground Control Station
4
+
5
+ (c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
6
+
7
+ This file is part of the QGROUNDCONTROL project
8
+
9
+ QGROUNDCONTROL is free software: you can redistribute it and/or modify
10
+ it under the terms of the GNU General Public License as published by
11
+ the Free Software Foundation, either version 3 of the License, or
12
+ (at your option) any later version.
13
+
14
+ QGROUNDCONTROL is distributed in the hope that it will be useful,
15
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ GNU General Public License for more details.
18
+
19
+ You should have received a copy of the GNU General Public License
20
+ along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
21
+
22
+ ======================================================================*/
23
+
24
+ #include "FlightMapSettings.h"
25
+
26
+ #include <QSettings>
27
+ #include <QtQml>
28
+
29
+ const char* FlightMapSettings::_defaultMapProvider = "Bing"; // Bing is default since it support full street/satellite/hybrid set
30
+ const char* FlightMapSettings::_settingsGroup = "FlightMapSettings";
31
+ const char* FlightMapSettings::_mapProviderKey = "MapProvider";
32
+ const char* FlightMapSettings::_mapTypeKey = "MapType";
33
+
34
+ FlightMapSettings::FlightMapSettings(QGCApplication* app)
35
+ : QGCTool(app)
36
+ , _mapProvider(_defaultMapProvider)
37
+ {
38
+ }
39
+
40
+ void FlightMapSettings::setToolbox(QGCToolbox *toolbox)
41
+ {
42
+ QGCTool::setToolbox(toolbox);
43
+
44
+ qmlRegisterUncreatableType<FlightMapSettings> ("QGroundControl", 1, 0, "FlightMapSetting", "Reference only");
45
+
46
+ _supportedMapProviders << "Bing" << "Google"; // << "OpenStreetMap";
47
+
48
+ _loadSettings();
49
+ }
50
+
51
+ void FlightMapSettings::_storeSettings(void)
52
+ {
53
+ QSettings settings;
54
+
55
+ settings.beginGroup(_settingsGroup);
56
+ settings.setValue(_mapProviderKey, _supportedMapProviders.contains(_mapProvider) ? _mapProvider : _defaultMapProvider);
57
+ }
58
+
59
+ void FlightMapSettings::_loadSettings(void)
60
+ {
61
+ QSettings settings;
62
+
63
+ settings.beginGroup(_settingsGroup);
64
+ _mapProvider = settings.value(_mapProviderKey, _defaultMapProvider).toString();
65
+
66
+ if (!_supportedMapProviders.contains(_mapProvider)) {
67
+ _mapProvider = _defaultMapProvider;
68
+ }
69
+
70
+ _setMapTypesForCurrentProvider();
71
+ }
72
+
73
+ QString FlightMapSettings::mapProvider(void)
74
+ {
75
+ return _mapProvider;
76
+ }
77
+
78
+ void FlightMapSettings::setMapProvider(const QString& mapProvider)
79
+ {
80
+ if (_supportedMapProviders.contains(mapProvider)) {
81
+ _mapProvider = mapProvider;
82
+ _storeSettings();
83
+ _setMapTypesForCurrentProvider();
84
+ emit mapProviderChanged(mapProvider);
85
+ }
86
+ }
87
+
88
+ void FlightMapSettings::_setMapTypesForCurrentProvider(void)
89
+ {
90
+ _mapTypes.clear();
91
+
92
+ if (_mapProvider == "Bing") {
93
+ _mapTypes << "Street Map" << "Satellite Map" << "Hybrid Map";
94
+ } else if (_mapProvider == "Google") {
95
+ _mapTypes << "Street Map" << "Satellite Map" << "Terrain Map";
96
+ /*
97
+ } else if (_mapProvider == "OpenStreetMap") {
98
+ _mapTypes << "Street Map";
99
+ */
100
+ }
101
+
102
+ emit mapTypesChanged(_mapTypes);
103
+ }
104
+
105
+ QString FlightMapSettings::mapTypeForMapName(const QString& mapName)
106
+ {
107
+ QSettings settings;
108
+
109
+ settings.beginGroup(_settingsGroup);
110
+ settings.beginGroup(mapName);
111
+ settings.beginGroup(_mapProvider);
112
+ return settings.value(_mapTypeKey, "Satellite Map").toString();
113
+ }
114
+
115
+ void FlightMapSettings::setMapTypeForMapName(const QString& mapName, const QString& mapType)
116
+ {
117
+ QSettings settings;
118
+
119
+ settings.beginGroup(_settingsGroup);
120
+ settings.beginGroup(mapName);
121
+ settings.beginGroup(_mapProvider);
122
+ settings.setValue(_mapTypeKey, mapType);
123
+ }
124
+
125
+ void FlightMapSettings::saveMapSetting (const QString &mapName, const QString& key, const QString& value)
126
+ {
127
+ QSettings settings;
128
+
129
+ settings.beginGroup(_settingsGroup);
130
+ settings.beginGroup(mapName);
131
+ settings.setValue(key, value);
132
+ }
133
+
134
+ QString FlightMapSettings::loadMapSetting (const QString &mapName, const QString& key, const QString& defaultValue)
135
+ {
136
+ QSettings settings;
137
+
138
+ settings.beginGroup(_settingsGroup);
139
+ settings.beginGroup(mapName);
140
+ return settings.value(key, defaultValue).toString();
141
+ }
142
+
143
+ void FlightMapSettings::saveBoolMapSetting (const QString &mapName, const QString& key, bool value)
144
+ {
145
+ QSettings settings;
146
+
147
+ settings.beginGroup(_settingsGroup);
148
+ settings.beginGroup(mapName);
149
+ settings.setValue(key, value);
150
+ }
151
+
152
+ bool FlightMapSettings::loadBoolMapSetting (const QString &mapName, const QString& key, bool defaultValue)
153
+ {
154
+ QSettings settings;
155
+
156
+ settings.beginGroup(_settingsGroup);
157
+ settings.beginGroup(mapName);
158
+ return settings.value(key, defaultValue).toBool();
159
+ }
pool/shard006/C++/0078526_12665_jokingfermat.cpp ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cstdio>
2
+ #include <iostream>
3
+ #include <vector>
4
+ #include <cstring>
5
+ #include <cstdlib>
6
+ #include <cmath>
7
+ #include <algorithm>
8
+
9
+ using namespace std;
10
+
11
+ //#define DEBUG //comment this line to pull out print statements
12
+ #ifdef DEBUG
13
+ #define TAB '\t'
14
+ #define debug(a, end) cout << #a << ": " << a << end
15
+ #define dbg(end) end
16
+ #else
17
+ #define debug(a, end)
18
+ #define dbg(end)
19
+ #endif
20
+
21
+ typedef pair<int, int> point;
22
+ typedef vector<int> vi;
23
+ typedef vector<point> vp;
24
+
25
+ #define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end())
26
+ #define SORT(c) sort((c).begin(),(c).end())
27
+ #define FOR(i,a,b) for (int i=(a); i < (b); i++)
28
+ #define REP(i,n) FOR(i,0,(int)n)
29
+ #define CL(a,b) memset(a,b,sizeof(a))
30
+ #define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y)
31
+
32
+ /*global variables*/
33
+ int cubes[1001];
34
+ int x, y;
35
+ /*global variables*/
36
+
37
+ void dump()
38
+ {
39
+ //dump data
40
+ }
41
+
42
+ bool getInput()
43
+ {
44
+ //get input
45
+ if (feof(stdin)) return false;
46
+ scanf("%d %d ", &x, &y);
47
+ return true;
48
+ }
49
+
50
+ void process()
51
+ {
52
+ //process input
53
+ int n = 0;
54
+ long long c;
55
+ int b, e;
56
+ for (int a = x; a <= y; a++)
57
+ {
58
+ for (b = a+1; b <= 1001; b++)
59
+ {
60
+ c = cubes[a] + cubes[b];
61
+ e = c%10;
62
+ c /= 10;
63
+ if (c > y)
64
+ break;
65
+ if (e == 3)
66
+ n++;
67
+ }
68
+ if (b == (a+1)) break;
69
+ }
70
+ printf("%d\n", n*2);
71
+ }
72
+
73
+ int main()
74
+ {
75
+ FOR(i, 1, 1001)
76
+ {
77
+ cubes[i] = pow(i, 3);
78
+ }
79
+ debug(sizeof(cubes[1000]), endl);
80
+ int pn = 1;
81
+ while (getInput())
82
+ {
83
+ printf("Case %d: ", pn++);
84
+ process();
85
+
86
+ /*CLEAR GLOBAL VARIABLES!*/
87
+
88
+ /*CLEAR GLOBAL VARIABLES!*/
89
+ }
90
+
91
+ return 0;
92
+ }
pool/shard006/C++/0078527_InputManager.cpp ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../include/InputManager.h"
2
+
3
+ namespace FGF
4
+ {
5
+ InputManager::InputManager()
6
+ {
7
+ }
8
+
9
+ InputManager::~InputManager()
10
+ {
11
+ key_press.clear();
12
+ }
13
+
14
+ bool InputManager::getKeyState(SDLKey key)
15
+ {
16
+ return SDL_GetKeyState(NULL)[key];
17
+ }
18
+
19
+ int InputManager::getMouseX()
20
+ {
21
+ int x;
22
+ SDL_GetMouseState(&x,NULL);
23
+ return x;
24
+ }
25
+ int InputManager::getMouseY()
26
+ {
27
+ int y;
28
+ SDL_GetMouseState(NULL,&y);
29
+ return y;
30
+ }
31
+
32
+ int InputManager::getMouseXRel()
33
+ {
34
+ int x;
35
+ SDL_GetRelativeMouseState(&x,NULL);
36
+ return x;
37
+ }
38
+ int InputManager::getMouseYRel()
39
+ {
40
+ int y;
41
+ SDL_GetRelativeMouseState(NULL,&y);
42
+ return y;
43
+ }
44
+
45
+ bool InputManager::getMouseButtonState(int button)
46
+ {
47
+ return (SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(button));
48
+ }
49
+
50
+ void InputManager::setCommand_OnKeyPress(SDLKey key,ICommand* cmd)
51
+ {
52
+ key_press[key] = cmd;
53
+ }
54
+
55
+ void InputManager::Update(float dt)
56
+ {
57
+ for(std::map<SDLKey,ICommand*>::iterator it = key_press.begin();
58
+ it != key_press.end(); it++)
59
+ {
60
+ if(getKeyState(it->first)) it->second->Execute(dt);
61
+ }
62
+ }
63
+ }
pool/shard006/C++/0078541_BroadcastDiscovery.cpp ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "umundo/discovery/BroadcastDiscovery.h"
2
+
3
+ namespace umundo {
4
+
5
+ /**
6
+ * Have a look at https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L81 to
7
+ * see how to setup UDP sockets for broadcast.
8
+ *
9
+ * Receiving Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L700
10
+ * Sending Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L751
11
+ */
12
+
13
+ #if 0
14
+ SOCKET BroadcastDiscovery::udpSocket = 0;
15
+ RMutex BroadcastDiscovery::globalMutex;
16
+
17
+ sockaddr_in BroadcastDiscovery::bCastAddress;
18
+ char BroadcastDiscovery::hostName[NI_MAXHOST];
19
+ #endif
20
+
21
+ BroadcastDiscovery::BroadcastDiscovery() {
22
+ /**
23
+ * This is called twice overall, once for the prototype in the factory and
24
+ * once for the instance that is actually used.
25
+ */
26
+ }
27
+
28
+ BroadcastDiscovery::~BroadcastDiscovery() {
29
+ }
30
+
31
+ #if 0
32
+ void BroadcastDiscovery::setupUDPSocket() {
33
+ RScopeLock(globalMutex);
34
+ if (udpSocket == 0) {
35
+ int enable = 1;
36
+
37
+ udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
38
+ if (udpSocket == INVALID_SOCKET)
39
+ return;
40
+
41
+ if (setsockopt (udpSocket, SOL_SOCKET, SO_BROADCAST, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) {
42
+ //error
43
+ }
44
+ if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) {
45
+ //error
46
+ }
47
+
48
+ #if defined (SO_REUSEPORT)
49
+ if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEPORT, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) {
50
+ //error
51
+ }
52
+ #endif
53
+ in_addr_t bindTo = INADDR_ANY;
54
+ in_addr_t sendTo = INADDR_BROADCAST;
55
+
56
+ bCastAddress.sin_family = AF_INET;
57
+ bCastAddress.sin_port = htons(43005);
58
+ bCastAddress.sin_addr.s_addr = sendTo;
59
+
60
+ sockaddr_in address = bCastAddress;
61
+ address.sin_addr.s_addr = bindTo;
62
+
63
+ #if (defined (__WINDOWS__))
64
+ sockaddr_in sockaddr = address;
65
+ #elif (defined (__APPLE__))
66
+ sockaddr_in sockaddr = bCastAddress;
67
+ sockaddr.sin_addr.s_addr = htons (INADDR_ANY);
68
+ #else
69
+ sockaddr_in sockaddr = bCastAddress;
70
+ #endif
71
+
72
+ if (bind (udpSocket, (struct sockaddr *) &sockaddr, sizeof (sockaddr_in))) {
73
+ // error
74
+ }
75
+
76
+ getnameinfo ((struct sockaddr *) &address, sizeof (sockaddr_in), hostName, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
77
+
78
+ }
79
+ }
80
+ #endif
81
+
82
+ SharedPtr<BroadcastDiscovery> BroadcastDiscovery::getInstance() {
83
+ if (_instance.get() == NULL) {
84
+ // setup UDP socket when th first instance is required
85
+ //setupUDPSocket();
86
+
87
+ _instance = SharedPtr<BroadcastDiscovery>(new BroadcastDiscovery());
88
+ _instance->start();
89
+ }
90
+ return _instance;
91
+ }
92
+ SharedPtr<BroadcastDiscovery> BroadcastDiscovery::_instance;
93
+
94
+ SharedPtr<Implementation> BroadcastDiscovery::create() {
95
+ return getInstance();
96
+ }
97
+
98
+ void BroadcastDiscovery::init(const Options*) {
99
+ /*
100
+ * This is where you can setup the non-prototype instance, i.e. not the one
101
+ * in the factory, but the one created from the prototype.
102
+ *
103
+ * The options object is not used and empty.
104
+ */
105
+ }
106
+
107
+ void BroadcastDiscovery::suspend() {
108
+ }
109
+
110
+ void BroadcastDiscovery::resume() {
111
+ }
112
+
113
+ void BroadcastDiscovery::advertise(const EndPoint& node) {
114
+ /**
115
+ * umundo.core asks you to make the given node discoverable
116
+ */
117
+ }
118
+
119
+ void BroadcastDiscovery::add(Node& node) {
120
+ }
121
+
122
+ void BroadcastDiscovery::unadvertise(const EndPoint& node) {
123
+ /**
124
+ * umundo.core asks you to announce the removal of the given node
125
+ */
126
+ }
127
+
128
+ void BroadcastDiscovery::remove(Node& node) {
129
+ }
130
+
131
+ void BroadcastDiscovery::browse(ResultSet<ENDPOINT_RS_TYPE>* query) {
132
+ /**
133
+ * Another node wants to browse for nodes
134
+ */
135
+ }
136
+
137
+ void BroadcastDiscovery::unbrowse(ResultSet<ENDPOINT_RS_TYPE>* query) {
138
+ /**
139
+ * Another node no longer wants to browse for nodes
140
+ */
141
+ }
142
+
143
+ std::vector<EndPoint> BroadcastDiscovery::list() {
144
+ return std::vector<EndPoint>();
145
+ }
146
+
147
+ void BroadcastDiscovery::run() {
148
+ // your very own thread!
149
+ }
150
+
151
+ }
pool/shard006/C++/0078543_string.cpp ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This file is a part of Luminance HDR package.
3
+ * ----------------------------------------------------------------------
4
+ * Copyright (C) 2013 Davide Anastasia
5
+ *
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; either version 2 of the License, or
9
+ * (at your option) any later version.
10
+ *
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ * GNU General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with this program; if not, write to the Free Software
18
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
+ * ----------------------------------------------------------------------
20
+ */
21
+
22
+ #include <Libpfs/utils/string.h>
23
+
24
+ #include <cmath>
25
+ #include <algorithm>
26
+
27
+ using namespace std;
28
+
29
+ namespace pfs {
30
+ namespace utils {
31
+
32
+ // Utility functions for case insensitive string compare
33
+ static
34
+ int charDiff(char c1, char c2)
35
+ {
36
+ if ( tolower(c1) < tolower(c2) ) return -1;
37
+ if ( tolower(c1) == tolower(c2) ) return 0;
38
+ return 1;
39
+ }
40
+
41
+ static
42
+ int stringCompare(const string& str1, const string& str2)
43
+ {
44
+ int diff = 0;
45
+ size_t size = std::min(str1.size(), str2.size());
46
+ for (size_t idx = 0; idx < size && diff == 0; ++idx)
47
+ {
48
+ diff = charDiff(str1[idx], str2[idx]);
49
+ }
50
+ if ( diff != 0 ) return diff;
51
+
52
+ if ( str2.length() == str1.length() ) return 0;
53
+ if ( str2.length() > str1.length() ) return 1;
54
+ return -1;
55
+ }
56
+
57
+ bool StringUnsensitiveComp::operator()(const std::string& str1, const std::string& str2) const {
58
+ return ( stringCompare(str1, str2) == -1 );
59
+ }
60
+
61
+ string getFormat(const string &filename)
62
+ {
63
+ size_t i = filename.rfind('.', filename.length());
64
+ if ( i != string::npos ) {
65
+ return filename.substr(i+1, filename.length()-i);
66
+ }
67
+ return string();
68
+ }
69
+
70
+ } // utils
71
+ } // pfs
pool/shard006/C++/0078550_remove_element.cpp ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Remove Element
3
+
4
+ Given an array and a value, remove all instances of that value
5
+ in place and return the new length.
6
+
7
+ The order of elements can be changed.
8
+ It doesn't matter what you leave beyond the new length.
9
+
10
+ */
11
+
12
+ #include <iostream>
13
+ #include <vector>
14
+
15
+ using namespace std;
16
+
17
+ class Solution
18
+ {
19
+ public:
20
+ int removeElement(int A[], int n, int elem)
21
+ {
22
+ if (n <= 0)
23
+ return n; //
24
+
25
+ if (n == 1)
26
+ return A[0] == elem ? 0 : 1;
27
+
28
+ int start = 0, end = n - 1;
29
+ while (start < end) {
30
+ if (A[start] != elem) {
31
+ start++;
32
+ } else if (A[end] == elem) {
33
+ end--;
34
+ } else {
35
+ swap(A[start], A[end]);
36
+ start++;
37
+ end--;
38
+ }
39
+ }
40
+ return start + (A[start] == elem ? 0 : 1); //
41
+ }
42
+
43
+ int removeElement2(int A[], int n, int elem)
44
+ {
45
+ int i = 0, j = 0;
46
+ while (j < n) {
47
+ if (A[j] != elem) A[i++] = A[j];
48
+ j++;
49
+ }
50
+ return i;
51
+ }
52
+
53
+ int removeElement3(int A[], int n, int elem)
54
+ {
55
+ int idx = 0;
56
+
57
+ for (int i = 0; i < n; i++) {
58
+ if (A[i] != elem) A[idx++] = A[i];
59
+ }
60
+
61
+ return idx;
62
+ }
63
+ };
64
+
65
+ int main(int argc, char *argv[])
66
+ {
67
+ int a[] = { 3, 3, 5, 4, 5 };
68
+ Solution sol;
69
+
70
+ cout << sol.removeElement(a, sizeof(a) / sizeof(int), 5) << endl;
71
+
72
+ for (auto t : a)
73
+ cout << t << ends;
74
+
75
+ return 0;
76
+ }
pool/shard006/C++/0078551_5.cpp ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class Solution {
3
+ public:
4
+ int findKthLargest(vector<int>& nums, int k) {
5
+ sort(nums.begin(), nums.end());
6
+ return nums[nums.size() - k ];
7
+ }
8
+ };
9
+
10
+
11
+ // n logn
12
+ //
13
+
14
+
15
+ class Solution {
16
+ public:
17
+ int findKthLargest(vector<int>& nums, int k) {
18
+ priority_queue<int> pq(nums.begin(), nums.end());
19
+ for (int i = 0; i < k - 1; i++)
20
+ pq.pop();
21
+ return pq.top();
22
+ }
23
+ };
24
+
25
+ //
26
+ //
27
+ class Solution {
28
+ public:
29
+ inline int left(int idx) {
30
+ return (idx << 1) + 1;
31
+ }
32
+ inline int right(int idx) {
33
+ return (idx << 1) + 2;
34
+ }
35
+ void max_heapify(vector<int>& nums, int idx) {
36
+ int largest = idx;
37
+ int l = left(idx), r = right(idx);
38
+ if (l < heap_size && nums[l] > nums[largest]) largest = l;
39
+ if (r < heap_size && nums[r] > nums[largest]) largest = r;
40
+ if (largest != idx) {
41
+ swap(nums[idx], nums[largest]);
42
+ max_heapify(nums, largest);
43
+ }
44
+ }
45
+ void build_max_heap(vector<int>& nums) {
46
+ heap_size = nums.size();
47
+ for (int i = (heap_size >> 1) - 1; i >= 0; i--)
48
+ max_heapify(nums, i);
49
+ }
50
+ int findKthLargest(vector<int>& nums, int k) {
51
+ build_max_heap(nums);
52
+ for (int i = 0; i < k; i++) {
53
+ swap(nums[0], nums[heap_size - 1]);
54
+ heap_size--;
55
+ max_heapify(nums, 0);
56
+ }
57
+ return nums[heap_size];
58
+ }
59
+ private:
60
+ int heap_size;
61
+ };
62
+
63
+ //
64
+
65
+
66
+ class Solution {
67
+ public:
68
+ inline int swap(vector<int>& nums, int left, int right){
69
+ if (left <0 or right>= nums.size()) return -1;
70
+ int temp = nums[left];
71
+ nums[left] = nums[right];
72
+ nums[right] = temp;
73
+
74
+ return 1;
75
+ }
76
+
77
+ int partition(vector<int>& nums, int left, int right) {
78
+ int pivot = nums[left];
79
+ int l = left + 1, r = right;
80
+ while (l <= r) {
81
+ if (nums[l] < pivot && nums[r] > pivot)
82
+ swap(nums,l++, r--);
83
+
84
+ if (nums[l] >= pivot) l++;
85
+ if (nums[r] <= pivot) r--;
86
+ }
87
+ swap(nums,left, r);
88
+ return r;
89
+ }
90
+
91
+ /*
92
+ * param k : description of k
93
+ * param nums : description of array and index 0 ~ n-1
94
+ * return: description of return
95
+ */
96
+
97
+ int findKthLargest(vector<int>& nums, int k) {
98
+ int left = 0, right = nums.size() - 1;
99
+ while (true) {
100
+ int pos = partition(nums, left, right);
101
+ if (pos == k - 1) return nums[pos];
102
+ if (pos > k - 1) right = pos - 1;
103
+ else left = pos + 1;
104
+ }
105
+
106
+
107
+ }
108
+ };
pool/shard006/C++/0078556_uri.cpp ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright contributors to the gecko project.
3
+
4
+ #include <base/ansi.h>
5
+ #include <base/contract.h>
6
+ #include <base/string_util.h>
7
+ #include <base/unit_test.h>
8
+ #include <base/uri.h>
9
+ #include <iostream>
10
+ #include <sstream>
11
+
12
+ namespace
13
+ {
14
+ void check(
15
+ base::unit_test & ut,
16
+ const std::string &test,
17
+ bool should = true,
18
+ bool except = false )
19
+ {
20
+ try
21
+ {
22
+ base::uri u( test );
23
+ std::string match = base::to_string( u );
24
+
25
+ if ( test == match )
26
+ ut.success( test );
27
+ else if ( !should )
28
+ ut.negative_success( test + " != " + match );
29
+ else
30
+ ut.failure( test + " != " + match );
31
+ }
32
+ catch ( const std::exception &e )
33
+ {
34
+ std::stringstream msg;
35
+ base::print_exception( msg, e );
36
+ if ( except )
37
+ ut.negative_success( test + " -> exception " + msg.str() );
38
+ else
39
+ ut.failure( test + " -> exception " + msg.str() );
40
+ }
41
+ }
42
+
43
+ int safemain( int argc, char *argv[] )
44
+ {
45
+ base::unit_test test( "uri" );
46
+
47
+ base::cmd_line options( argv[0] );
48
+ test.setup( options );
49
+
50
+ try
51
+ {
52
+ options.parse( argc, argv );
53
+ }
54
+ catch ( ... )
55
+ {
56
+ throw_add( "parsing command line arguments" );
57
+ }
58
+
59
+ test["basic_parsing"] = [&]( void ) {
60
+ check( test, "http", false, true );
61
+ check( test, "http:", false, true );
62
+ check( test, "file:/tmp" );
63
+ check( test, "file:///tmp", false );
64
+ check( test, "http://host.com" );
65
+ check( test, "http://user@host.com" );
66
+ check( test, "http://host.com:1234" );
67
+ check( test, "http://user@host.com:1234" );
68
+ check( test, "http://host.com/path1" );
69
+ check( test, "http://host.com/path1/path2" );
70
+ };
71
+
72
+ test["parse_query_frag"] = [&]( void ) {
73
+ check( test, "http://host.com?query" );
74
+ check( test, "http://host.com#frag" );
75
+ check( test, "http://host.com?query#frag" );
76
+ check( test, "http://host.com/path1?query#frag" );
77
+ };
78
+
79
+ test["parse_encoded"] = [&]( void ) {
80
+ check( test, "http://host.com/path1#frag%3Fmorefrag" );
81
+ check( test, "http://host%2ecom", false );
82
+ check( test, "http://host%2Ecom", false );
83
+ check( test, "http://host.com/%2fmore", false );
84
+ check( test, "http://host.com/%2Fmore" );
85
+ check( test, "http://host.com/with%20space", false );
86
+ check( test, "http://host.com/with space", true );
87
+ };
88
+
89
+ test["path_construction"] = [&]( void ) {
90
+ base::uri tf( "file", "" );
91
+ tf /= "file.txt";
92
+ if ( tf.pretty() == "file:///file.txt" )
93
+ test.success( "operator/=" );
94
+ else
95
+ test.failure( "operator/= -> {0}", tf );
96
+
97
+ tf = base::uri( "file", "" ) / "hello" / "world";
98
+ if ( tf.pretty() == "file:///hello/world" )
99
+ test.success( "operator/" );
100
+ else
101
+ test.failure( "operator/ -> {0}", tf );
102
+ };
103
+
104
+ // test.cleanup() = [&]( void ) {};
105
+ test.run( options );
106
+ test.clean();
107
+
108
+ return -static_cast<int>( test.failure_count() );
109
+ }
110
+
111
+ } // namespace
112
+
113
+ int main( int argc, char *argv[] )
114
+ {
115
+ try
116
+ {
117
+ return safemain( argc, argv );
118
+ }
119
+ catch ( const std::exception &e )
120
+ {
121
+ base::print_exception( std::cerr, e );
122
+ }
123
+ return -1;
124
+ }
pool/shard006/C++/0078558_partialdate.cpp ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /***************************************************************************
2
+ * (C) 2005-2009 Michal Rudolf <mrudolf@kdewebdev.org> *
3
+ * *
4
+ * This program is free software; you can redistribute it and/or modify *
5
+ * it under the terms of the GNU General Public License as published by *
6
+ * the Free Software Foundation; either version 2 of the License, or *
7
+ * (at your option) any later version. *
8
+ ***************************************************************************/
9
+
10
+ #include "partialdate.h"
11
+ #include <QRegExp>
12
+
13
+ PartialDate::PartialDate(int y, int m, int d) :
14
+ m_year(y),
15
+ m_month(m),
16
+ m_day(d)
17
+ {
18
+ m_bIsValid = !m_year || asDate().isValid();
19
+ }
20
+
21
+ PartialDate::PartialDate(const QString& s)
22
+ {
23
+ m_year = 0;
24
+ m_month = 0;
25
+ m_day = 0;
26
+ fromString(s);
27
+ }
28
+
29
+ PartialDate::PartialDate(const QDate& d)
30
+ {
31
+ m_bIsValid = true;
32
+ m_year = d.year();
33
+ m_month = d.month();
34
+ m_day = d.day();
35
+ }
36
+
37
+ PartialDate PartialDate::today()
38
+ {
39
+ return PartialDate(QDate::currentDate());
40
+ }
41
+
42
+ int PartialDate::year() const
43
+ {
44
+ return m_year;
45
+ }
46
+
47
+ int PartialDate::month() const
48
+ {
49
+ return m_month;
50
+ }
51
+
52
+ int PartialDate::day() const
53
+ {
54
+ return m_day;
55
+ }
56
+
57
+ PartialDate& PartialDate::fromString(const QString& s)
58
+ {
59
+ QString test = s.trimmed();
60
+ QRegExp regExp("^[\\?0-9]{4}([\\./]([\\?0-9]){1,2}){,2}$");
61
+ if(regExp.exactMatch(test) || test.isEmpty())
62
+ {
63
+ QRegExp sep("[\\./]");
64
+ m_year = test.section(sep, 0, 0).toInt();
65
+ m_month = test.section(sep, 1, 1).toInt();
66
+ m_day = test.section(sep, 2, 2).toInt();
67
+ m_bIsValid = !year() || asDate().isValid();
68
+ }
69
+ else
70
+ {
71
+ QRegExp regExpContinental("^(([\\?0-9]){1,2}\\.){,2}[\\?0-9]{4}$");
72
+ if(regExpContinental.exactMatch(test))
73
+ {
74
+ m_day = test.section('.', 0, 0).toInt();
75
+ m_month = test.section('.', 1, 1).toInt();
76
+ m_year = test.section('.', 2, 2).toInt();
77
+ m_bIsValid = !year() || asDate().isValid();
78
+ }
79
+ else
80
+ {
81
+ QRegExp regExpAmerican("^(([\\?0-9]){1,2}/){,2}[\\?0-9]{4}$");
82
+ if(regExpAmerican.exactMatch(test))
83
+ {
84
+ m_month = test.section('/', 0, 0).toInt();
85
+ m_day = test.section('/', 1, 1).toInt();
86
+ m_year = test.section('/', 2, 2).toInt();
87
+ m_bIsValid = !year() || asDate().isValid();
88
+ }
89
+ }
90
+ }
91
+ return *this;
92
+ }
93
+
94
+
95
+ QDate PartialDate::asDate() const
96
+ {
97
+ return QDate(m_year, m_month ? m_month : 1, m_day ? m_day : 1);
98
+ }
99
+
100
+ bool PartialDate::isValid() const
101
+ {
102
+ return m_bIsValid;
103
+ }
104
+
105
+ QString PartialDate::asString() const
106
+ {
107
+ if(!m_year)
108
+ {
109
+ return "????.??.??";
110
+ }
111
+ QString s = QString("%1.%2.%3")
112
+ .arg(m_year, 4)
113
+ .arg(numberToString(m_month))
114
+ .arg(numberToString(m_day));
115
+ return s;
116
+ }
117
+
118
+ QString PartialDate::asShortString(int part) const
119
+ {
120
+ if(!m_year)
121
+ {
122
+ return QString();
123
+ }
124
+ QString s;
125
+ if(part & Year)
126
+ {
127
+ s = numberToString(m_year);
128
+ }
129
+ if(!m_month)
130
+ {
131
+ return s;
132
+ }
133
+ if(part & Month)
134
+ {
135
+ if(!s.isEmpty())
136
+ {
137
+ s += '.';
138
+ }
139
+ s += numberToString(m_month);
140
+ }
141
+ if(!m_day)
142
+ {
143
+ return s;
144
+ }
145
+ if(part & Day)
146
+ {
147
+ if(!s.isEmpty())
148
+ {
149
+ s += '.';
150
+ }
151
+ s += numberToString(m_day);
152
+ }
153
+ return s;
154
+ }
155
+
156
+ QString PartialDate::numberToString(int d, QChar fill) const
157
+ {
158
+ if(!d)
159
+ {
160
+ return "??";
161
+ }
162
+ return d < 10 ? QString(fill) + QString::number(d) : QString::number(d);
163
+ }
164
+
165
+ bool operator==(const PartialDate& d1, const PartialDate& d2)
166
+ {
167
+ return d1.year() == d2.year() && d1.month() == d2.month() && d1.day() == d2.day();
168
+ }
169
+
170
+ bool operator<(const PartialDate& d1, const PartialDate& d2)
171
+ {
172
+ return d2.year() > d1.year() ||
173
+ ((d2.year() == d1.year()) &&
174
+ (d2.month() > d1.month() || (d2.month() == d1.month() && d2.day() > d1.day())));
175
+ }
176
+
177
+ bool operator>(const PartialDate& d1, const PartialDate& d2)
178
+ {
179
+ return d1.year() > d2.year() ||
180
+ ((d1.year() == d2.year()) &&
181
+ (d1.month() > d2.month() || (d1.month() == d2.month() && d1.day() > d2.day())));
182
+ }
183
+
184
+ bool operator>=(const PartialDate& d1, const PartialDate& d2)
185
+ {
186
+ return d2 < d1 || d2 == d1;
187
+ }
188
+
189
+ bool operator<=(const PartialDate& d1, const PartialDate& d2)
190
+ {
191
+ return d2 > d1 || d2 == d1;
192
+ }
193
+
194
+ bool operator!=(const PartialDate& d1, const PartialDate& d2)
195
+ {
196
+ return d1.year() != d2.year() || d1.month() != d2.month() || d1.day() != d2.day();
197
+ }
198
+
199
+ QString PartialDate::range(const PartialDate& d) const
200
+ {
201
+ if(year() != d.year())
202
+ {
203
+ return asShortString() + "-" + d.asShortString();
204
+ }
205
+ QString result = numberToString(year());
206
+ if(month() != d.month())
207
+ return QString("%1.%2-%3").arg(year()).arg(asShortString(Month | Day))
208
+ .arg(d.asShortString(Month | Day));
209
+ else if(day() != d.day())
210
+ return QString("%1.%2.%3-%4").arg(year()).arg(month())
211
+ .arg(asShortString(Day)).arg(d.asShortString(Day));
212
+ else
213
+ {
214
+ return asShortString();
215
+ }
216
+ }
217
+
pool/shard006/C++/0078561_ChShaftsTorqueConverter.cpp ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // PROJECT CHRONO - http://projectchrono.org
3
+ //
4
+ // Copyright (c) 2010, 2012 Alessandro Tasora
5
+ // Copyright (c) 2013 Project Chrono
6
+ // All rights reserved.
7
+ //
8
+ // Use of this source code is governed by a BSD-style license that can be
9
+ // found in the LICENSE file at the top level of the distribution
10
+ // and at http://projectchrono.org/license-chrono.txt.
11
+ //
12
+
13
+
14
+ #include "physics/ChShaftsTorqueConverter.h"
15
+ #include "physics/ChSystem.h"
16
+ #include "physics/ChShaft.h"
17
+
18
+ #include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only.
19
+
20
+ namespace chrono
21
+ {
22
+
23
+
24
+ // Register into the object factory, to enable run-time
25
+ // dynamic creation and persistence
26
+ ChClassRegister<ChShaftsTorqueConverter> a_registration_ChShaftsTorqueConverter;
27
+
28
+
29
+
30
+ //////////////////////////////////////
31
+ //////////////////////////////////////
32
+
33
+
34
+ ChShaftsTorqueConverter::ChShaftsTorqueConverter ()
35
+ {
36
+ this->shaft1 = 0;
37
+ this->shaft2 = 0;
38
+ this->shaft_stator = 0;
39
+ this->torque_in= 0;
40
+ this->torque_out= 0;
41
+ this->K = ChSharedPtr<ChFunction> (new ChFunction_Const(0.9));
42
+ this->T = ChSharedPtr<ChFunction> (new ChFunction_Const(0.9));
43
+ this->state_warning_reverseflow = false;
44
+ this->state_warning_wrongimpellerdirection = false;
45
+
46
+ SetIdentifier(GetUniqueIntID()); // mark with unique ID
47
+ }
48
+
49
+
50
+ ChShaftsTorqueConverter::~ChShaftsTorqueConverter ()
51
+ {
52
+
53
+ }
54
+
55
+ void ChShaftsTorqueConverter::Copy(ChShaftsTorqueConverter* source)
56
+ {
57
+ // copy the parent class data...
58
+ ChPhysicsItem::Copy(source);
59
+
60
+ // copy class data
61
+ shaft1 = 0;
62
+ shaft2 = 0;
63
+ shaft_stator = 0;
64
+
65
+ torque_in = source->torque_in;
66
+ torque_out = source->torque_out;
67
+
68
+ state_warning_reverseflow = source->state_warning_reverseflow;
69
+ state_warning_wrongimpellerdirection = source->state_warning_wrongimpellerdirection;
70
+
71
+ this->K = ChSharedPtr<ChFunction>(K->new_Duplicate()); // deep copy
72
+ this->T = ChSharedPtr<ChFunction>(T->new_Duplicate()); // deep copy
73
+ }
74
+
75
+
76
+ int ChShaftsTorqueConverter::Initialize(ChSharedPtr<ChShaft> mshaft1, ChSharedPtr<ChShaft> mshaft2, ChSharedPtr<ChShaft> mshaft_stator)
77
+ {
78
+ ChShaft* mm1 = mshaft1.get_ptr();
79
+ ChShaft* mm2 = mshaft2.get_ptr();
80
+ ChShaft* mm_stator = mshaft_stator.get_ptr();
81
+ assert(mm1 && mm2 && mm_stator);
82
+ assert((mm1 != mm2) && (mm1 != mm_stator));
83
+ assert((mm1->GetSystem() == mm2->GetSystem()) && (mm1->GetSystem() == mm_stator->GetSystem()));
84
+
85
+ this->shaft1 = mm1;
86
+ this->shaft2 = mm2;
87
+ this->shaft_stator = mm_stator;
88
+
89
+ this->SetSystem(this->shaft1->GetSystem());
90
+
91
+ return true;
92
+ }
93
+
94
+
95
+ double ChShaftsTorqueConverter::GetSpeedRatio() const
96
+ {
97
+ double wrel1 = this->shaft1->GetPos_dt() - this->shaft_stator->GetPos_dt();
98
+ double wrel2 = this->shaft2->GetPos_dt() - this->shaft_stator->GetPos_dt();
99
+
100
+ if ((fabs(wrel1) < 10e-9) || (fabs(wrel2) < 10e-9))
101
+ return 0;
102
+
103
+ return wrel2/wrel1;
104
+ }
105
+
106
+
107
+ void ChShaftsTorqueConverter::Update (double mytime)
108
+ {
109
+ // Inherit time changes of parent class
110
+ ChPhysicsItem::Update(mytime);
111
+
112
+ // update class data
113
+
114
+ state_warning_wrongimpellerdirection= false;
115
+ state_warning_reverseflow = false;
116
+
117
+ // Compute actual speed ratio
118
+ double mR = this->GetSpeedRatio();
119
+
120
+ // The speed ratio must always be in the [0...1] range,
121
+ // anyway let's correct singular cases:
122
+
123
+ // - it should be inusual that speed ratio >1, say if the impeller
124
+ // outruns turbine (if there's a clutch lock-in, this should happen).
125
+ // If so, assume a reflection of T curve and a polar reflection of K curve, after 1.
126
+ if (mR > 1)
127
+ {
128
+ mR = 1-(mR-1);
129
+ state_warning_reverseflow = true;
130
+ }
131
+
132
+ // - if the output shaft is spinning a bit backward, when
133
+ // close to stall, maybe win/wout < 0. If so, set as stall anyway:
134
+ if (mR < 0)
135
+ mR = 0;
136
+
137
+ // - if input impeller shaft is spinning in negative direction,
138
+ // this is assumed as an error: set all torques to zero and bail out:
139
+ if (this->shaft1->GetPos_dt() - this->shaft_stator->GetPos_dt() < 0)
140
+ {
141
+ state_warning_wrongimpellerdirection = true;
142
+ this->torque_in = 0;
143
+ this->torque_out = 0;
144
+ return;
145
+ }
146
+
147
+ // Compute actual capacity factor
148
+ double mK = K->Get_y(mR);
149
+
150
+ // Compute actual torque factor
151
+ double mT = T->Get_y(mR);
152
+
153
+ // compute input torque (with minus sign because applied TO input thaft)
154
+ this->torque_in = - pow(( this->shaft1->GetPos_dt() / mK ),2);
155
+
156
+ if (state_warning_reverseflow)
157
+ this->torque_in = -this->torque_in;
158
+
159
+ // compute output torque (with opposite sign because
160
+ // applied to output shaft, with same direction of input shaft)
161
+ this->torque_out = - mT * this->torque_in;
162
+ }
163
+
164
+
165
+
166
+
167
+ ////////// LCP INTERFACES ////
168
+
169
+
170
+
171
+ void ChShaftsTorqueConverter::VariablesFbLoadForces(double factor)
172
+ {
173
+ // Apply torques to the three connected 1D variables:
174
+ shaft1->Variables().Get_fb().ElementN(0) += torque_in*factor;
175
+ shaft2->Variables().Get_fb().ElementN(0) += torque_out*factor;
176
+ shaft_stator->Variables().Get_fb().ElementN(0) += GetTorqueReactionOnStator()*factor;
177
+ }
178
+
179
+
180
+
181
+ //////// FILE I/O
182
+
183
+ void ChShaftsTorqueConverter::StreamOUT(ChStreamOutBinary& mstream)
184
+ {
185
+ // class version number
186
+ mstream.VersionWrite(1);
187
+
188
+ // serialize parent class too
189
+ ChPhysicsItem::StreamOUT(mstream);
190
+
191
+ // stream out all member data
192
+ mstream.AbstractWrite(this->K.get_ptr()); //***TODO*** proper serialize for ChSharedPtr
193
+ mstream.AbstractWrite(this->T.get_ptr()); //***TODO*** proper serialize for ChSharedPtr
194
+ }
195
+
196
+ void ChShaftsTorqueConverter::StreamIN(ChStreamInBinary& mstream)
197
+ {
198
+ // class version number
199
+ int version = mstream.VersionRead();
200
+
201
+ // deserialize parent class too
202
+ ChPhysicsItem::StreamIN(mstream);
203
+
204
+ // deserialize class
205
+ ChFunction* newfun;
206
+ mstream.AbstractReadCreate(&newfun); //***TODO*** proper deserialize for ChSharedPtr
207
+ this->K = ChSharedPtr<ChFunction>(newfun);
208
+ mstream.AbstractReadCreate(&newfun); //***TODO*** proper deserialize for ChSharedPtr
209
+ this->T = ChSharedPtr<ChFunction>(newfun);;
210
+
211
+ }
212
+
213
+
214
+
215
+
216
+
217
+
218
+ } // END_OF_NAMESPACE____
219
+
220
+
221
+ /////////////////////
pool/shard006/C++/0078564_command_interface.cpp ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "command_interface.h"
2
+
3
+ #include <vector>
4
+
5
+ #include "abort/abort.h"
6
+ #include "util/str_util.h"
7
+
8
+ namespace Chess
9
+ {
10
+ CommandInterface::CommandInterface()
11
+ : _cmd_map()
12
+ {
13
+ }
14
+
15
+ bool CommandInterface::install(const std::string& name,
16
+ handler_t handler)
17
+ {
18
+ const std::string cmdName = Util::trim(Util::to_lower(name));
19
+ AbortIf(cmdName.empty(), false);
20
+
21
+ _cmd_map[cmdName] = handler;
22
+ return true;
23
+ }
24
+
25
+ bool CommandInterface::process(const std::string& data)
26
+ {
27
+ const std::string input = Util::trim(data);
28
+ AbortIf(input.empty(), false);
29
+
30
+ std::vector<std::string> tokens; Util::split(input, tokens);
31
+ AbortIf(tokens.empty(), false);
32
+
33
+ const std::string cmd = Util::to_lower( tokens[0] );
34
+ auto iter = _cmd_map.find(cmd);
35
+
36
+ AbortIf(iter == _cmd_map.end(), false);
37
+
38
+ tokens.erase(tokens.begin());
39
+
40
+ const std::string args = Util::build_string(tokens, " ");
41
+
42
+ // Invoke the handler for this command
43
+
44
+ iter->second(args);
45
+ return true;
46
+ }
47
+ }
pool/shard006/C++/0078577_Led.cpp ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ To change this license header, choose License Headers in Project Properties.
3
+ To change this template file, choose Tools | Templates
4
+ and open the template in the editor.
5
+ */
6
+
7
+ /*
8
+ File: Led.cpp
9
+ Author: Mathilde
10
+
11
+ Created on 25 octobre 2016, 16:29
12
+ */
13
+
14
+ #include "Led.h"
15
+
16
+
17
+ Led::Led(int newPin, int newNumber) {
18
+ this->pin = newPin;
19
+ this->number = newNumber;
20
+ this->state = false;
21
+ this->blink = false;
22
+ this->color = {0, 0, 0};
23
+ }
24
+
25
+ bool Led::init() {
26
+
27
+ this->strip = Adafruit_NeoPixel(this->number, this->pin, NEO_GRB + NEO_KHZ800);
28
+ this->strip.begin();// Initialise toute les led à 'off'
29
+ setColorAll(255, 255, 255);
30
+ }
31
+
32
+ std::vector<int> Led::getColor() {
33
+ return this->color;
34
+ }
35
+
36
+ void Led::show(int ledNbr, int newR, int newV, int newB) {
37
+ this->color = { newR, newV, newB };
38
+ this->strip.setPixelColor(ledNbr, newR, newV, newB);
39
+ this->strip.show();
40
+ }
41
+
42
+ void Led::setColorAll(int newR, int newV, int newB) {
43
+ this->color = {newR, newV, newB};
44
+
45
+ int cpt;
46
+ for (cpt = 0; cpt < this->number; cpt++) {
47
+ this->strip.setPixelColor(cpt, newR, newV, newB);
48
+ if (this->pin == 44) {
49
+ this->strip.setPixelColor(0, 0, 0, 0);
50
+ }
51
+ }
52
+ this->strip.show();
53
+ delay(100);
54
+ }
55
+
56
+ void Led::setColorUnit(int ledNbr, int newR, int newV, int newB) {
57
+ ledNbr = abs(ledNbr);
58
+ if (ledNbr > this->number) show(this->number, 0, 0, 0);
59
+ else show(ledNbr - 1, newR, newV, newB);
60
+ }
61
+
62
+ /* Code de Quentin */
63
+ void Led::setColor(int couleur) {
64
+ /*this->r = this->tabColor[couleur][0];
65
+ this->v = this->tabColor[couleur][1];
66
+ this->b = this->tabColor[couleur][2];*/
67
+ switch (couleur) {
68
+ case 0: setColorAll(10, 10, 10); //blanc
69
+ break;
70
+ case 1: setColorAll(100, 0, 0); //rouge
71
+ break;
72
+ case 2: setColorAll(0, 100, 0); //bleu
73
+ break;
74
+ case 3: setColorAll(0, 0, 100); //vert
75
+ break;
76
+ case 4: setColorAll(100, 255, 255); //turquoise
77
+ break;
78
+ case 5: setColorAll(255, 0, 50); //orange
79
+ break;
80
+ case 6: setColorAll(160, 160, 160); //gris
81
+ break;
82
+ case 7: setColorAll(153, 0, 153); //jaune
83
+ break;
84
+ case 8: setColorAll(255, 255, 51); //magenta
85
+ break;
86
+ case 9: setColorAll(120, 120, 0); //violet
87
+ break;
88
+ default:
89
+ break;
90
+ }
91
+ }
92
+
93
+
94
+ void Led::ledOnOff(bool state) {
95
+ if (state == 1) {
96
+ int cpt;
97
+ for (cpt = 0; cpt < this->number; cpt++) {
98
+ this->strip.setPixelColor(cpt, 255, 255, 255);
99
+ }
100
+ this->strip.show();
101
+ }
102
+ else if (state == 0) {
103
+ int cpt;
104
+ for (cpt = 0; cpt < this->number; cpt++) {
105
+ this->strip.setPixelColor(cpt, 0, 0, 0);
106
+ }
107
+ this->strip.show();
108
+ }
109
+ }
pool/shard006/C++/0078596_init_process_reaper.cc ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "sandbox/linux/services/init_process_reaper.h"
6
+
7
+ #include <signal.h>
8
+ #include <string.h>
9
+ #include <sys/socket.h>
10
+ #include <sys/types.h>
11
+ #include <sys/wait.h>
12
+ #include <unistd.h>
13
+
14
+ #include "base/callback.h"
15
+ #include "base/logging.h"
16
+ #include "base/posix/eintr_wrapper.h"
17
+
18
+ namespace sandbox {
19
+
20
+ namespace {
21
+
22
+ void DoNothingSignalHandler(int signal) {}
23
+
24
+ } // namespace
25
+
26
+ bool CreateInitProcessReaper(base::Closure* post_fork_parent_callback) {
27
+ int sync_fds[2];
28
+ // We want to use send, so we can't use a pipe
29
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)) {
30
+ PLOG(ERROR) << "Failed to create socketpair";
31
+ return false;
32
+ }
33
+ pid_t child_pid = fork();
34
+ if (child_pid == -1) {
35
+ int close_ret;
36
+ close_ret = IGNORE_EINTR(close(sync_fds[0]));
37
+ DPCHECK(!close_ret);
38
+ close_ret = IGNORE_EINTR(close(sync_fds[1]));
39
+ DPCHECK(!close_ret);
40
+ return false;
41
+ }
42
+ if (child_pid) {
43
+ // In the parent, assuming the role of an init process.
44
+ // The disposition for SIGCHLD cannot be SIG_IGN or wait() will only return
45
+ // once all of our childs are dead. Since we're init we need to reap childs
46
+ // as they come.
47
+ struct sigaction action;
48
+ memset(&action, 0, sizeof(action));
49
+ action.sa_handler = &DoNothingSignalHandler;
50
+ CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
51
+
52
+ int close_ret;
53
+ close_ret = IGNORE_EINTR(close(sync_fds[0]));
54
+ DPCHECK(!close_ret);
55
+ close_ret = shutdown(sync_fds[1], SHUT_RD);
56
+ DPCHECK(!close_ret);
57
+ if (post_fork_parent_callback)
58
+ post_fork_parent_callback->Run();
59
+ // Tell the child to continue
60
+ CHECK(HANDLE_EINTR(send(sync_fds[1], "C", 1, MSG_NOSIGNAL)) == 1);
61
+ close_ret = IGNORE_EINTR(close(sync_fds[1]));
62
+ DPCHECK(!close_ret);
63
+
64
+ for (;;) {
65
+ // Loop until we have reaped our one natural child
66
+ siginfo_t reaped_child_info;
67
+ int wait_ret =
68
+ HANDLE_EINTR(waitid(P_ALL, 0, &reaped_child_info, WEXITED));
69
+ if (wait_ret)
70
+ _exit(1);
71
+ if (reaped_child_info.si_pid == child_pid) {
72
+ int exit_code = 0;
73
+ // We're done waiting
74
+ if (reaped_child_info.si_code == CLD_EXITED) {
75
+ exit_code = reaped_child_info.si_status;
76
+ }
77
+ // Exit with the same exit code as our parent. Exit with 0 if we got
78
+ // signaled.
79
+ _exit(exit_code);
80
+ }
81
+ }
82
+ } else {
83
+ // The child needs to wait for the parent to run the callback to avoid a
84
+ // race condition.
85
+ int close_ret;
86
+ close_ret = IGNORE_EINTR(close(sync_fds[1]));
87
+ DPCHECK(!close_ret);
88
+ close_ret = shutdown(sync_fds[0], SHUT_WR);
89
+ DPCHECK(!close_ret);
90
+ char should_continue;
91
+ int read_ret = HANDLE_EINTR(read(sync_fds[0], &should_continue, 1));
92
+ close_ret = IGNORE_EINTR(close(sync_fds[0]));
93
+ DPCHECK(!close_ret);
94
+ if (read_ret == 1)
95
+ return true;
96
+ else
97
+ return false;
98
+ }
99
+ }
100
+
101
+ } // namespace sandbox.
pool/shard006/C++/0078598_boss_ambassador_hellmaw.cpp ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
3
+ * Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it
6
+ * under the terms of the GNU General Public License as published by the
7
+ * Free Software Foundation; either version 2 of the License, or (at your
8
+ * option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful, but WITHOUT
11
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13
+ * more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License along
16
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ /* ScriptData
20
+ SDName: Boss_Ambassador_Hellmaw
21
+ SD%Complete: 80
22
+ SDComment: Enrage spell missing/not known
23
+ SDCategory: Auchindoun, Shadow Labyrinth
24
+ EndScriptData */
25
+
26
+ #include "ScriptPCH.h"
27
+ #include "ScriptedEscortAI.h"
28
+ #include "shadow_labyrinth.h"
29
+
30
+ enum eEnums
31
+ {
32
+ SAY_INTRO = -1555000,
33
+ SAY_AGGRO1 = -1555001,
34
+ SAY_AGGRO2 = -1555002,
35
+ SAY_AGGRO3 = -1555003,
36
+ SAY_HELP = -1555004,
37
+ SAY_SLAY1 = -1555005,
38
+ SAY_SLAY2 = -1555006,
39
+ SAY_DEATH = -1555007,
40
+
41
+ SPELL_BANISH = 30231,
42
+ SPELL_CORROSIVE_ACID = 33551,
43
+ SPELL_FEAR = 33547,
44
+ SPELL_ENRAGE = 34970
45
+ };
46
+
47
+ class boss_ambassador_hellmaw : public CreatureScript
48
+ {
49
+ public:
50
+ boss_ambassador_hellmaw() : CreatureScript("boss_ambassador_hellmaw") { }
51
+
52
+ CreatureAI* GetAI(Creature* creature) const
53
+ {
54
+ return new boss_ambassador_hellmawAI(creature);
55
+ }
56
+
57
+ struct boss_ambassador_hellmawAI : public npc_escortAI
58
+ {
59
+ boss_ambassador_hellmawAI(Creature* creature) : npc_escortAI(creature)
60
+ {
61
+ m_pInstance = creature->GetInstanceScript();
62
+ }
63
+
64
+ InstanceScript* m_pInstance;
65
+
66
+ uint32 EventCheck_Timer;
67
+ uint32 CorrosiveAcid_Timer;
68
+ uint32 Fear_Timer;
69
+ uint32 Enrage_Timer;
70
+ bool Intro;
71
+ bool IsBanished;
72
+ bool Enraged;
73
+
74
+ void Reset()
75
+ {
76
+ EventCheck_Timer = 5000;
77
+ CorrosiveAcid_Timer = urand(5000, 10000);
78
+ Fear_Timer = urand(25000, 30000);
79
+ Enrage_Timer = 180000;
80
+ Intro = false;
81
+ IsBanished = true;
82
+ Enraged = false;
83
+
84
+ if (m_pInstance && me->isAlive())
85
+ {
86
+ if (m_pInstance->GetData(TYPE_OVERSEER) != DONE)
87
+ DoCast(me, SPELL_BANISH, true);
88
+ }
89
+ }
90
+
91
+ void JustReachedHome()
92
+ {
93
+ if (m_pInstance)
94
+ m_pInstance->SetData(TYPE_HELLMAW, FAIL);
95
+ }
96
+
97
+ void MoveInLineOfSight(Unit* who)
98
+ {
99
+ if (me->HasAura(SPELL_BANISH))
100
+ return;
101
+
102
+ npc_escortAI::MoveInLineOfSight(who);
103
+ }
104
+
105
+ void WaypointReached(uint32 /*i*/)
106
+ {
107
+ }
108
+
109
+ void DoIntro()
110
+ {
111
+ if (me->HasAura(SPELL_BANISH))
112
+ me->RemoveAurasDueToSpell(SPELL_BANISH);
113
+
114
+ IsBanished = false;
115
+ Intro = true;
116
+
117
+ if (m_pInstance)
118
+ {
119
+ if (m_pInstance->GetData(TYPE_HELLMAW) != FAIL)
120
+ {
121
+ DoScriptText(SAY_INTRO, me);
122
+ Start(true, false, 0, NULL, false, true);
123
+ }
124
+
125
+ m_pInstance->SetData(TYPE_HELLMAW, IN_PROGRESS);
126
+ }
127
+ }
128
+
129
+ void EnterCombat(Unit* /*who*/)
130
+ {
131
+ DoScriptText(RAND(SAY_AGGRO1, SAY_AGGRO2, SAY_AGGRO3), me);
132
+ }
133
+
134
+ void KilledUnit(Unit* /*victim*/)
135
+ {
136
+ DoScriptText(RAND(SAY_SLAY1, SAY_SLAY2), me);
137
+ }
138
+
139
+ void JustDied(Unit* /*victim*/)
140
+ {
141
+ DoScriptText(SAY_DEATH, me);
142
+
143
+ if (m_pInstance)
144
+ m_pInstance->SetData(TYPE_HELLMAW, DONE);
145
+ }
146
+
147
+ void UpdateAI(const uint32 diff)
148
+ {
149
+ if (!Intro && !HasEscortState(STATE_ESCORT_ESCORTING))
150
+ {
151
+ if (EventCheck_Timer <= diff)
152
+ {
153
+ if (m_pInstance)
154
+ {
155
+ if (m_pInstance->GetData(TYPE_OVERSEER) == DONE)
156
+ {
157
+ DoIntro();
158
+ return;
159
+ }
160
+ }
161
+ EventCheck_Timer = 5000;
162
+ return;
163
+ }
164
+ else
165
+ {
166
+ EventCheck_Timer -= diff;
167
+ return;
168
+ }
169
+ }
170
+
171
+ npc_escortAI::UpdateAI(diff);
172
+
173
+ if (!UpdateVictim())
174
+ return;
175
+
176
+ if (me->HasAura(SPELL_BANISH, 0))
177
+ {
178
+ EnterEvadeMode();
179
+ return;
180
+ }
181
+
182
+ if (CorrosiveAcid_Timer <= diff)
183
+ {
184
+ DoCast(me->getVictim(), SPELL_CORROSIVE_ACID);
185
+ CorrosiveAcid_Timer = urand(15000, 25000);
186
+ } else CorrosiveAcid_Timer -= diff;
187
+
188
+ if (Fear_Timer <= diff)
189
+ {
190
+ DoCast(me, SPELL_FEAR);
191
+ Fear_Timer = urand(20000, 35000);
192
+ } else Fear_Timer -= diff;
193
+
194
+ if (IsHeroic())
195
+ {
196
+ if (!Enraged && Enrage_Timer <= diff)
197
+ {
198
+ DoCast(me, SPELL_ENRAGE);
199
+ Enraged = true;
200
+ } else Enrage_Timer -= diff;
201
+ }
202
+ }
203
+ };
204
+ };
205
+
206
+ void AddSC_boss_ambassador_hellmaw()
207
+ {
208
+ new boss_ambassador_hellmaw();
209
+ }
pool/shard006/C++/0078614_parser.cpp ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Uses Jsoncpp, reference here:
2
+ * http://open-source-parsers.github.io/jsoncpp-docs/
3
+ */
4
+ #include "parser.h"
5
+ #include <iostream>
6
+
7
+
8
+ Parser::Parser(std::string filename)
9
+ {
10
+ init();
11
+
12
+ std::ifstream contents(filename, std::ifstream::binary);
13
+
14
+ /* root is the top-level handle on the json object we parse */
15
+ Json::Reader reader;
16
+ if (reader.parse(contents, root, false) == false) {
17
+ std::cerr << "Error parsing scene" << std::endl;
18
+ }
19
+ }
20
+
21
+ Parser::Parser(Json::Value root) : root(root)
22
+ {
23
+ init();
24
+ }
25
+
26
+ void Parser::init()
27
+ {
28
+ /* We map object types to their JSON converters. */
29
+ converters.insert(
30
+ std::make_pair("sphere", (json_converter)&Parser::json_to_sphere)
31
+ );
32
+ converters.insert(
33
+ std::make_pair("box", (json_converter)&Parser::json_to_box)
34
+ );
35
+ converters.insert(
36
+ std::make_pair("point_light",
37
+ (json_converter)&Parser::json_to_point_light)
38
+ );
39
+ }
40
+
41
+ bool Parser::valid_object_type(std::string type)
42
+ {
43
+ /* Is the type in the map? */
44
+ return converters.find(type) != converters.end();
45
+ }
46
+
47
+ vector3_t Parser::json_to_vector3(Json::Value json_vector)
48
+ {
49
+ return vector3_t(
50
+ json_vector["x"].asDouble(),
51
+ json_vector["y"].asDouble(),
52
+ json_vector["z"].asDouble()
53
+ );
54
+ }
55
+
56
+ color_t Parser::json_to_color(Json::Value json_color)
57
+ {
58
+ return color_t(
59
+ json_color["r"].asDouble(),
60
+ json_color["g"].asDouble(),
61
+ json_color["b"].asDouble(),
62
+ json_color["a"].asDouble()
63
+ );
64
+ }
65
+
66
+ material_t Parser::json_to_material(Json::Value json_material)
67
+ {
68
+ material_t mat = material_t(
69
+ json_to_color(json_material["ambient"]),
70
+ json_to_color(json_material["diffuse"]),
71
+ json_to_color(json_material["specular"]),
72
+ json_to_color(json_material["emission"]),
73
+ json_material["reflection"].asDouble()
74
+ );
75
+
76
+ /* Pptionally set refraction amount, and index of refraction.
77
+ If unspecified default to 0 and 1 respectively. */
78
+ mat.refraction =
79
+ json_material.get("refraction", Json::Value(0.0)).asDouble();
80
+ mat.refraction_index =
81
+ json_material.get("refraction_index", Json::Value(1)).asDouble();
82
+ mat.texture = json_material.get("texture", Json::Value(false)).asBool();
83
+
84
+
85
+ return mat;
86
+ }
87
+
88
+ Sphere *Parser::json_to_sphere(Json::Value json_sphere)
89
+ {
90
+ return new Sphere(
91
+ json_to_vector3(json_sphere["loc"]),
92
+ json_to_material(json_sphere["material"]),
93
+ json_sphere["radius"].asDouble()
94
+ );
95
+ }
96
+
97
+ Box *Parser::json_to_box(Json::Value json_box)
98
+ {
99
+ return new Box(
100
+ json_to_vector3(json_box["min"]),
101
+ json_to_vector3(json_box["max"]),
102
+ json_to_material(json_box["material"])
103
+ );
104
+ }
105
+
106
+ PointLight *Parser::json_to_point_light(Json::Value json_point_light) {
107
+
108
+ return new PointLight(
109
+ json_to_vector3(json_point_light["loc"]),
110
+ json_to_color(json_point_light["intensity"]));
111
+ }
112
+
113
+ scene_t Parser::parse()
114
+ {
115
+ scene_t scene;
116
+
117
+ /* The list of scene objects is referenced by key:
118
+ * "scene_objects"
119
+ */
120
+ Json::Value scene_objs_json = root["scene_objects"];
121
+ /* Create scene_obj from each item in JSON "scene_objects"[]
122
+ * based on object_type; append object into scene_objs vector
123
+ */
124
+ for (Json::ValueIterator itr = scene_objs_json.begin();
125
+ itr != scene_objs_json.end(); itr++) {
126
+
127
+ /* We branch based on the type of object we encounter
128
+ * in the scene file.
129
+ */
130
+ std::string type = (*itr)["object_type"].asString();
131
+ if (valid_object_type(type)) {
132
+ json_converter c = converters[type];
133
+ scene.objects.push_back((this->*c)(*itr));
134
+ }
135
+ else {
136
+ std::cerr << "UNKNOWN TYPE " << type << std::endl;
137
+ }
138
+ }
139
+ Json::Value scene_lights_json = root["scene_lights"];
140
+ for (Json::ValueIterator itr = scene_lights_json.begin();
141
+ itr != scene_lights_json.end(); itr++) {
142
+
143
+ /* We branch based on the type of object we encounter
144
+ * in the scene file.
145
+ */
146
+ std::string type = (*itr)["object_type"].asString();
147
+ if (valid_object_type(type)) {
148
+ json_converter c = converters[type];
149
+ scene.lights.push_back((this->*c)(*itr));
150
+ }
151
+ else {
152
+ std::cerr << "UNKNOWN TYPE " << type << std::endl;
153
+ }
154
+ }
155
+
156
+ return scene;
157
+ }
pool/shard006/C++/0078616_DrawingElement.cpp ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // DrawingElement.cpp
3
+ //
4
+ // Sketchup C++ Wrapper for C API
5
+ // MIT License
6
+ //
7
+ // Copyright (c) 2017 Tom Kaneko
8
+ //
9
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ // of this software and associated documentation files (the "Software"), to deal
11
+ // in the Software without restriction, including without limitation the rights
12
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ // copies of the Software, and to permit persons to whom the Software is
14
+ // furnished to do so, subject to the following conditions:
15
+
16
+ // The above copyright notice and this permission notice shall be included in all
17
+ // copies or substantial portions of the Software.
18
+
19
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ // SOFTWARE.
26
+ //
27
+
28
+ // Macro for getting rid of unused variables commonly for assert checking
29
+ #define _unused(x) ((void)(x))
30
+
31
+ #include "SUAPI-CppWrapper/model/DrawingElement.hpp"
32
+
33
+ #include <cassert>
34
+ #include <stdexcept>
35
+
36
+ #include "SUAPI-CppWrapper/model/Layer.hpp"
37
+ #include "SUAPI-CppWrapper/model/Material.hpp"
38
+ #include "SUAPI-CppWrapper/Geometry.hpp"
39
+
40
+
41
+ namespace CW {
42
+
43
+ DrawingElement::DrawingElement(SUDrawingElementRef drawing_element, bool attached):
44
+ Entity(SUDrawingElementToEntity(drawing_element), attached)
45
+ {}
46
+
47
+
48
+ DrawingElement::DrawingElement(const DrawingElement& other, SUDrawingElementRef element_ref):
49
+ Entity(other, SUDrawingElementToEntity(element_ref))
50
+ {}
51
+
52
+ DrawingElement::DrawingElement():
53
+ Entity()
54
+ {}
55
+
56
+
57
+ /** Copy assignment operator */
58
+ DrawingElement& DrawingElement::operator=(const DrawingElement& other) {
59
+ if (!other.m_attached && SUIsValid(other.m_entity)) {
60
+ this->copy_properties_from(other);
61
+ }
62
+ Entity::operator=(other);
63
+ return (*this);
64
+ }
65
+
66
+
67
+ SUDrawingElementRef DrawingElement::ref() const {
68
+ return SUDrawingElementFromEntity(m_entity);
69
+ }
70
+
71
+
72
+ DrawingElement::operator SUDrawingElementRef() const {
73
+ return this->ref();
74
+ }
75
+
76
+
77
+ BoundingBox3D DrawingElement::bounds() {
78
+ if (SUIsInvalid(m_entity)) {
79
+ throw std::logic_error("CW::DrawingElement::bounds(): DrawingElement is null");
80
+ }
81
+ SUBoundingBox3D box;
82
+ SUResult res = SUDrawingElementGetBoundingBox(this->ref(), &box);
83
+ assert(res == SU_ERROR_NONE); _unused(res);
84
+ return BoundingBox3D(box);
85
+ }
86
+
87
+
88
+ bool DrawingElement::copy_properties_from(const DrawingElement& element) {
89
+ bool success = this->casts_shadows(element.casts_shadows());
90
+ if (!success)
91
+ return false;
92
+ success = this->hidden(element.hidden());
93
+ if (!success)
94
+ return false;
95
+ success = this->receive_shadows(element.receive_shadows());
96
+ if (!success)
97
+ return false;
98
+ Layer elem_layer = element.layer();
99
+ success = this->layer(elem_layer);
100
+ if (!success)
101
+ return false;
102
+ success = this->material(element.material());
103
+ if (!success)
104
+ return false;
105
+
106
+ return true;
107
+ }
108
+
109
+
110
+ bool DrawingElement::casts_shadows() const {
111
+ if (SUIsInvalid(m_entity)) {
112
+ throw std::logic_error("CW::DrawingElement::casts_shadows(): DrawingElement is null");
113
+ }
114
+ bool cast_shadows_flag;
115
+ SUResult res = SUDrawingElementGetCastsShadows(this->ref(), &cast_shadows_flag);
116
+ assert(res == SU_ERROR_NONE); _unused(res);
117
+ return cast_shadows_flag;
118
+ }
119
+
120
+
121
+ bool DrawingElement::casts_shadows(bool casts_shadows) {
122
+ if (SUIsInvalid(m_entity)) {
123
+ throw std::logic_error("CW::DrawingElement::casts_shadows(): DrawingElement is null");
124
+ }
125
+ SUResult res = SUDrawingElementSetCastsShadows(this->ref(), casts_shadows);
126
+ if (res == SU_ERROR_NONE) {
127
+ return true;
128
+ }
129
+ return false;
130
+ }
131
+
132
+
133
+ bool DrawingElement::hidden() const {
134
+ if (SUIsInvalid(m_entity)) {
135
+ throw std::logic_error("CW::DrawingElement::hidden(): DrawingElement is null");
136
+ }
137
+ bool hide_flag;
138
+ SUDrawingElementGetHidden(this->ref(), &hide_flag);
139
+ return hide_flag;
140
+ }
141
+
142
+
143
+ bool DrawingElement::hidden(bool hidden) {
144
+ if (SUIsInvalid(m_entity)) {
145
+ throw std::logic_error("CW::DrawingElement::hidden(): DrawingElement is null");
146
+ }
147
+ SUResult res = SUDrawingElementSetHidden(this->ref(), hidden);
148
+ if (res == SU_ERROR_NONE) {
149
+ return true;
150
+ }
151
+ return false;
152
+ }
153
+
154
+
155
+ Layer DrawingElement::layer() const {
156
+ if (SUIsInvalid(m_entity)) {
157
+ throw std::logic_error("CW::DrawingElement::layer(): DrawingElement is null");
158
+ }
159
+ SULayerRef layer_ref = SU_INVALID;
160
+ SUResult res = SUDrawingElementGetLayer(this->ref(), &layer_ref);
161
+ if (res == SU_ERROR_NULL_POINTER_OUTPUT || res == SU_ERROR_NO_DATA) {
162
+ return Layer();
163
+ }
164
+ assert(res == SU_ERROR_NONE); _unused(res);
165
+ return Layer(layer_ref, true);
166
+ }
167
+
168
+
169
+ bool DrawingElement::layer(Layer& layer){
170
+ if (SUIsInvalid(m_entity)) {
171
+ throw std::logic_error("CW::DrawingElement::layer(): DrawingElement is null");
172
+ }
173
+ SUResult res = SUDrawingElementSetLayer(this->ref(), layer);
174
+ if (res == SU_ERROR_NONE) {
175
+ layer.attached(true);
176
+ return true;
177
+ }
178
+ return false;
179
+ }
180
+
181
+
182
+ Material DrawingElement::material() const {
183
+ if (SUIsInvalid(m_entity)) {
184
+ throw std::logic_error("CW::DrawingElement::material(): DrawingElement is null");
185
+ }
186
+ SUMaterialRef material_ref = SU_INVALID;
187
+ SUResult res = SUDrawingElementGetMaterial(this->ref(), &material_ref);
188
+ if (res == SU_ERROR_NO_DATA || res == SU_ERROR_NULL_POINTER_OUTPUT) {
189
+ return Material();
190
+ }
191
+ assert(res == SU_ERROR_NONE); _unused(res);
192
+ return Material(material_ref, true);
193
+ }
194
+
195
+
196
+ bool DrawingElement::material(const Material& material) {
197
+ if (SUIsInvalid(m_entity)) {
198
+ throw std::logic_error("CW::DrawingElement::material(): DrawingElement is null");
199
+ }
200
+ SUResult res = SUDrawingElementSetMaterial(this->ref(), material);
201
+ if (res == SU_ERROR_NONE) {
202
+ return true;
203
+ }
204
+ return false;
205
+ }
206
+
207
+
208
+ bool DrawingElement::receive_shadows() const {
209
+ if (SUIsInvalid(m_entity)) {
210
+ throw std::logic_error("CW::DrawingElement::receive_shadows(): DrawingElement is null");
211
+ }
212
+ bool receives_shadows_flag;
213
+ SUResult res = SUDrawingElementGetReceivesShadows(this->ref(), &receives_shadows_flag);
214
+ assert (res == SU_ERROR_NONE); _unused(res);
215
+ return receives_shadows_flag;
216
+ }
217
+
218
+
219
+ bool DrawingElement::receive_shadows(bool receives_shadows_flag) {
220
+ if (SUIsInvalid(m_entity)) {
221
+ throw std::logic_error("CW::DrawingElement::receive_shadows(): DrawingElement is null");
222
+ }
223
+ SUResult res = SUDrawingElementSetReceivesShadows(this->ref(), receives_shadows_flag);
224
+ if (res == SU_ERROR_NONE) {
225
+ return true;
226
+ }
227
+ return false;
228
+ }
229
+
230
+ } /* namespace CW */
pool/shard006/C++/0078617_stackdriver_client_test.cc ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 Google LLC
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ ==============================================================================*/
15
+
16
+ #include "monitoring/stackdriver_client.h"
17
+
18
+ #include <gmock/gmock.h>
19
+ #include <gtest/gtest.h>
20
+
21
+ #include <list>
22
+
23
+ #include "google/monitoring/v3/metric_service_mock.grpc.pb.h"
24
+ #include "google/protobuf/util/json_util.h"
25
+
26
+ namespace tensorflow {
27
+ namespace monitoring {
28
+
29
+ using ::testing::_;
30
+ using ::testing::Return;
31
+
32
+ namespace {
33
+ inline void SetPointValue(int64 value, Point* point) {
34
+ point->value_type = ValueType::kInt64;
35
+ point->int64_value = value;
36
+ }
37
+
38
+ inline void SetPointValue(std::list<double> value, Point* point) {
39
+ point->value_type = ValueType::kHistogram;
40
+ HistogramProto& histogram = point->histogram_value;
41
+
42
+ // 2 buckets: (-oo, 0] and (0, +oo)
43
+ histogram.add_bucket_limit(0.0);
44
+ histogram.add_bucket(0.0);
45
+ histogram.add_bucket_limit(DBL_MAX);
46
+ histogram.add_bucket(0.0);
47
+
48
+ if (value.empty()) {
49
+ return;
50
+ }
51
+
52
+ histogram.set_min(value.front());
53
+ histogram.set_max(value.front());
54
+ histogram.set_num(value.size());
55
+ for (double sample : value) {
56
+ histogram.set_min(std::min(histogram.min(), sample));
57
+ histogram.set_max(std::max(histogram.max(), sample));
58
+ histogram.set_sum(histogram.sum() + sample);
59
+ histogram.set_sum_squares(histogram.sum_squares() + sample * sample);
60
+ size_t bucket_id = (sample < 0.0) ? 0 : 1;
61
+ histogram.set_bucket(bucket_id, histogram.bucket(bucket_id) + 1);
62
+ }
63
+ }
64
+
65
+ template <typename T>
66
+ std::unique_ptr<PointSet> MakePointSet(std::string name, int64 time_millis,
67
+ std::initializer_list<T> values) {
68
+ auto point_set = std::make_unique<PointSet>();
69
+ point_set->metric_name = std::move(name);
70
+ for (auto& value : values) {
71
+ auto point = std::make_unique<Point>();
72
+ SetPointValue(std::move(value), point.get());
73
+ point->end_timestamp_millis = time_millis;
74
+ point_set->points.emplace_back(std::move(point));
75
+ }
76
+ return point_set;
77
+ }
78
+
79
+ MATCHER_P(EqualsRequest, expected, "The expected request does not match") {
80
+ *result_listener << "as the expected is " << expected.DebugString();
81
+ return expected.SerializeAsString() == arg.SerializeAsString();
82
+ }
83
+
84
+ } // namespace
85
+
86
+ TEST(StackdriverClientTest, CreateTimeSeries) {
87
+ std::map<string, std::unique_ptr<PointSet>> point_set_map;
88
+ point_set_map["/metric_1"] = MakePointSet(
89
+ "/metric_1", // metric type is "custom.googleapis.com/metric_1"
90
+ 12345, // timestamp is 12 seconds and 345,000,000 nanoseconds
91
+ {33, 44}); // the first number 33 is exported as int64_value
92
+ point_set_map["/metric_2"] = MakePointSet(
93
+ "/metric_2", // metric type is "custom.googleapis.com/metric_2"
94
+ 12345, // timestamp is 12 seconds and 345,000,000 nanoseconds
95
+ {std::list<double>{-1.0, 1.0}}); // one histogram containing {-1.0, 1.0}
96
+
97
+ const std::string expected_request_json = R"(
98
+ {
99
+ "name": "projects/test_project",
100
+ "time_series": [
101
+ {
102
+ "metric": {
103
+ "type": "custom.googleapis.com/metric_1",
104
+ },
105
+ "resource": {
106
+ "type": "global"
107
+ },
108
+ "points": {
109
+ "interval": {
110
+ "end_time": {
111
+ "seconds": 12,
112
+ "nanos": 345000000,
113
+ },
114
+ },
115
+ "value": {
116
+ "int64_value": 33,
117
+ },
118
+ },
119
+ },
120
+ {
121
+ "metric": {
122
+ "type": "custom.googleapis.com/metric_2",
123
+ },
124
+ "resource": {
125
+ "type": "global"
126
+ },
127
+ "points": {
128
+ "interval": {
129
+ "end_time": {
130
+ "seconds": 12,
131
+ "nanos": 345000000,
132
+ },
133
+ },
134
+ "value": {
135
+ "distribution_value": {
136
+ "count": 2,
137
+ "mean": 0.0,
138
+ "sum_of_squared_deviation": 2.0,
139
+ "bucket_options": {
140
+ "explicit_buckets": {
141
+ "bounds": [
142
+ 0.0,
143
+ ],
144
+ },
145
+ },
146
+ "bucket_counts": [
147
+ 1,
148
+ 1,
149
+ ],
150
+ }
151
+ },
152
+ },
153
+ },
154
+ ],
155
+ }
156
+ )";
157
+ google::monitoring::v3::CreateTimeSeriesRequest expected_request;
158
+ auto status = google::protobuf::util::JsonStringToMessage(
159
+ expected_request_json, &expected_request);
160
+ ASSERT_TRUE(status.ok()) << status.error_message();
161
+
162
+ auto mock_metric_service =
163
+ std::make_unique<google::monitoring::v3::grpc::MockMetricServiceStub>();
164
+ EXPECT_CALL(*mock_metric_service,
165
+ CreateTimeSeries(_, EqualsRequest(expected_request), _))
166
+ .WillOnce(Return(::grpc::Status::OK));
167
+ StackdriverClient client({"test_project"}, std::move(mock_metric_service));
168
+ EXPECT_OK(client.CreateTimeSeries(point_set_map));
169
+ }
170
+
171
+ TEST(StackdriverClientTest, CreateMetricDescriptor) {
172
+ MetricDescriptor metric_descriptor{
173
+ .name = "metric_1",
174
+ .description = "desc",
175
+ .label_names = {"a", "b"},
176
+ .metric_kind = MetricKind::kCumulative,
177
+ .value_type = ValueType::kInt64,
178
+ };
179
+
180
+ const std::string expected_request_json = R"(
181
+ {
182
+ name: "projects/test_project",
183
+ metric_descriptor: {
184
+ name: "metric_1",
185
+ type: "custom.googleapis.commetric_1",
186
+ description: "desc",
187
+ labels: [
188
+ {
189
+ key: "a"
190
+ },
191
+ {
192
+ key: "b"
193
+ }
194
+ ],
195
+ metric_kind: 3,
196
+ value_type: 2,
197
+ },
198
+ }
199
+ )";
200
+ google::monitoring::v3::CreateMetricDescriptorRequest expected_request;
201
+ auto status = google::protobuf::util::JsonStringToMessage(
202
+ expected_request_json, &expected_request);
203
+ ASSERT_TRUE(status.ok()) << status.error_message();
204
+
205
+ auto mock_metric_service =
206
+ std::make_unique<google::monitoring::v3::grpc::MockMetricServiceStub>();
207
+ EXPECT_CALL(*mock_metric_service,
208
+ CreateMetricDescriptor(_, EqualsRequest(expected_request), _))
209
+ .WillOnce(Return(::grpc::Status::OK));
210
+ StackdriverClient client({"test_project"}, std::move(mock_metric_service));
211
+ EXPECT_OK(client.CreateMetricDescriptor(metric_descriptor));
212
+ }
213
+
214
+ } // namespace monitoring
215
+ } // namespace tensorflow
pool/shard006/C++/0078620_qgsclassificationjenks.cpp ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /***************************************************************************
2
+ qgsclassificationjenks.h
3
+ ---------------------
4
+ begin : September 2019
5
+ copyright : (C) 2019 by Denis Rouzaud
6
+ email : denis@opengis.ch
7
+ ***************************************************************************
8
+ * *
9
+ * This program is free software; you can redistribute it and/or modify *
10
+ * it under the terms of the GNU General Public License as published by *
11
+ * the Free Software Foundation; either version 2 of the License, or *
12
+ * (at your option) any later version. *
13
+ * *
14
+ ***************************************************************************/
15
+
16
+ #include <limits>
17
+ #include "qgsclassificationjenks.h"
18
+ #include "qgsapplication.h"
19
+
20
+ #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
21
+ #include <QRandomGenerator>
22
+ #endif
23
+
24
+ QgsClassificationJenks::QgsClassificationJenks()
25
+ : QgsClassificationMethod()
26
+ {
27
+
28
+ }
29
+
30
+ QString QgsClassificationJenks::name() const
31
+ {
32
+ return QObject::tr( "Natural Breaks (Jenks)" );
33
+ }
34
+
35
+ QString QgsClassificationJenks::id() const
36
+ {
37
+ return QStringLiteral( "Jenks" );
38
+ }
39
+
40
+ QgsClassificationMethod *QgsClassificationJenks::clone() const
41
+ {
42
+ QgsClassificationJenks *c = new QgsClassificationJenks();
43
+ copyBase( c );
44
+ return c;
45
+ }
46
+
47
+ QIcon QgsClassificationJenks::icon() const
48
+ {
49
+ return QgsApplication::getThemeIcon( "classification_methods/mClassificationNaturalBreak.svg" );
50
+ }
51
+
52
+
53
+ QList<double> QgsClassificationJenks::calculateBreaks( double &minimum, double &maximum,
54
+ const QList<double> &values, int nclasses )
55
+ {
56
+ // Jenks Optimal (Natural Breaks) algorithm
57
+ // Based on the Jenks algorithm from the 'classInt' package available for
58
+ // the R statistical prgramming language, and from Python code from here:
59
+ // http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
60
+ // and is based on a JAVA and Fortran code available here:
61
+ // https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html
62
+
63
+ // Returns class breaks such that classes are internally homogeneous while
64
+ // assuring heterogeneity among classes.
65
+
66
+ if ( values.isEmpty() )
67
+ return QList<double>();
68
+
69
+ if ( nclasses <= 1 )
70
+ {
71
+ return QList<double>() << maximum;
72
+ }
73
+
74
+ if ( nclasses >= values.size() )
75
+ {
76
+ return values;
77
+ }
78
+
79
+ QVector<double> sample;
80
+ QVector<double> sorted;
81
+
82
+ // if we have lots of values, we need to take a random sample
83
+ if ( values.size() > mMaximumSize )
84
+ {
85
+ // for now, sample at least maximumSize values or a 10% sample, whichever
86
+ // is larger. This will produce a more representative sample for very large
87
+ // layers, but could end up being computationally intensive...
88
+
89
+ sample.resize( std::max( mMaximumSize, static_cast<int>( values.size() ) / 10 ) );
90
+
91
+ QgsDebugMsgLevel( QStringLiteral( "natural breaks (jenks) sample size: %1" ).arg( sample.size() ), 2 );
92
+ QgsDebugMsgLevel( QStringLiteral( "values:%1" ).arg( values.size() ), 2 );
93
+
94
+ sample[ 0 ] = minimum;
95
+ sample[ 1 ] = maximum;
96
+
97
+ sorted = values.toVector();
98
+ std::sort( sorted.begin(), sorted.end() );
99
+
100
+ int j = -1;
101
+
102
+ // loop through all values in initial array
103
+ // skip the first value as it is a minimum one
104
+ // skip the last value as that one is a maximum one
105
+ // and those are already in the sample as items 0 and 1
106
+ for ( int i = 1; i < sorted.size() - 2; i++ )
107
+ {
108
+ if ( ( i * ( mMaximumSize - 2 ) / ( sorted.size() - 2 ) ) > j )
109
+ {
110
+ j++;
111
+ sample[ j + 2 ] = sorted[ i ];
112
+ }
113
+ }
114
+ }
115
+ else
116
+ {
117
+ sample = values.toVector();
118
+ }
119
+
120
+ const int n = sample.size();
121
+
122
+ // sort the sample values
123
+ std::sort( sample.begin(), sample.end() );
124
+
125
+ QVector< QVector<int> > matrixOne( n + 1 );
126
+ QVector< QVector<double> > matrixTwo( n + 1 );
127
+
128
+ for ( int i = 0; i <= n; i++ )
129
+ {
130
+ matrixOne[i].resize( nclasses + 1 );
131
+ matrixTwo[i].resize( nclasses + 1 );
132
+ }
133
+
134
+ for ( int i = 1; i <= nclasses; i++ )
135
+ {
136
+ matrixOne[0][i] = 1;
137
+ matrixOne[1][i] = 1;
138
+ matrixTwo[0][i] = 0.0;
139
+ for ( int j = 2; j <= n; j++ )
140
+ {
141
+ matrixTwo[j][i] = std::numeric_limits<double>::max();
142
+ }
143
+ }
144
+
145
+ for ( int l = 2; l <= n; l++ )
146
+ {
147
+ double s1 = 0.0;
148
+ double s2 = 0.0;
149
+ int w = 0;
150
+
151
+ double v = 0.0;
152
+
153
+ for ( int m = 1; m <= l; m++ )
154
+ {
155
+ const int i3 = l - m + 1;
156
+
157
+ const double val = sample[ i3 - 1 ];
158
+
159
+ s2 += val * val;
160
+ s1 += val;
161
+ w++;
162
+
163
+ v = s2 - ( s1 * s1 ) / static_cast< double >( w );
164
+ const int i4 = i3 - 1;
165
+ if ( i4 != 0 )
166
+ {
167
+ for ( int j = 2; j <= nclasses; j++ )
168
+ {
169
+ if ( matrixTwo[l][j] >= v + matrixTwo[i4][j - 1] )
170
+ {
171
+ matrixOne[l][j] = i4;
172
+ matrixTwo[l][j] = v + matrixTwo[i4][j - 1];
173
+ }
174
+ }
175
+ }
176
+ }
177
+ matrixOne[l][1] = 1;
178
+ matrixTwo[l][1] = v;
179
+ }
180
+
181
+ QVector<double> breaks( nclasses );
182
+ breaks[nclasses - 1] = sample[n - 1];
183
+
184
+ for ( int j = nclasses, k = n; j >= 2; j-- )
185
+ {
186
+ const int id = matrixOne[k][j] - 1;
187
+ breaks[j - 2] = sample[id];
188
+ k = matrixOne[k][j] - 1;
189
+ }
190
+
191
+ return breaks.toList();
192
+ }
pool/shard006/C++/0078623_RPC.cpp ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "RPC.h"
2
+ #include "../../../General/Driver/Network/LibEvent/ZNetworkLibEvent.h"
3
+ #include "../../../Core/Driver/Thread/Pthread/ZThreadPthread.h"
4
+ #include "../../../General/Misc/RemoteProxy.h"
5
+
6
+ using namespace PaintsNow;
7
+
8
+ class Foo : public TReflected<Foo, IScript::Library> {
9
+ public:
10
+ Foo() {}
11
+
12
+ virtual TObject<IReflect>& operator () (IReflect& reflect) {
13
+ BaseClass::operator () (reflect);
14
+ if (reflect.IsReflectMethod()) {
15
+ ReflectMethod(RequestNewFoo)[ScriptMethod = "NewFoo"];
16
+ }
17
+
18
+ return *this;
19
+ }
20
+
21
+ void RequestNewFoo(IScript::Request& request, int a, const String& str) {
22
+
23
+ }
24
+ };
25
+
26
+ class PrefabFactory : public TWrapper<IScript::Object*, const String&> {
27
+ public:
28
+ PrefabFactory(IThread& threadApi) : TWrapper<IScript::Object*, const String&>(Wrap(this, &PrefabFactory::CreateObject)), thread(threadApi) {}
29
+ class Prefab : public TReflected<Prefab, IScript::Object> {
30
+ public:
31
+ virtual TObject<IReflect>& operator () (IReflect& reflect) {
32
+ BaseClass::operator () (reflect);
33
+ if (reflect.IsReflectMethod()) {
34
+ ReflectMethod(Test)[ScriptMethod];
35
+ ReflectMethod(Complete)[ScriptMethod];
36
+ }
37
+
38
+ return *this;
39
+ }
40
+
41
+ void Test(IScript::Request& request, uint32_t p, const String& message, int value) {
42
+ printf("Message: %s : %d, %d\n", message.c_str(), p, value);
43
+ }
44
+
45
+ void Complete(IScript::Request& request, const String& message) {
46
+ printf("Complete: %s\n", message.c_str());
47
+ }
48
+
49
+ virtual void ScriptUninitialize(IScript::Request& request) {}
50
+ };
51
+
52
+ IScript::Object* CreateObject(const String& entry) const {
53
+ printf("Hello %s \n", entry.c_str());
54
+ return new Prefab();
55
+ }
56
+
57
+ IThread& thread;
58
+ };
59
+
60
+ void Then(IScript::Request& request) {
61
+ IScript::Request::ArrayStart ns;
62
+ request >> ns;
63
+ for (size_t i = 0; i < ns.count; i++) {
64
+ String name;
65
+ request >> begintable;
66
+ request << key("Name") >> name;
67
+ printf("Name: %s\n", name.c_str());
68
+ IScript::Request::ArrayStart ts;
69
+ request << key("Arguments") >> ts;
70
+ for (size_t j = 0; j < ts.count; j++) {
71
+ request >> name;
72
+ printf("\tArg[%d]: %s\n", (int)j, name.c_str());
73
+ }
74
+ request << endarray;
75
+ request << endtable;
76
+ }
77
+ request << endarray;
78
+ }
79
+
80
+ void After(IScript::Request& request, IScript::Request::Ref prefab) {
81
+ request.DoLock();
82
+ request.Push();
83
+ request.Call(prefab, 0, String("abcasdfwhaodkjfo;asld;asdgihaosdfi"));
84
+ request.Pop();
85
+ request.UnLock();
86
+ }
87
+
88
+ class MyPrefab : public TReflected<MyPrefab, IReflectObjectComplex> {
89
+ public:
90
+ virtual TObject<IReflect>& operator () (IReflect& reflect) {
91
+ BaseClass::operator () (reflect);
92
+ if (reflect.IsReflectProperty()) {
93
+ ReflectProperty(Test)[ScriptRemoteMethod(&PrefabFactory::Prefab::Test)];
94
+ ReflectProperty(Complete)[ScriptRemoteMethod(&PrefabFactory::Prefab::Complete)];
95
+ }
96
+ return *this;
97
+ }
98
+ TWrapper<void, const IScript::Request::AutoWrapperBase&, IScript::Request&, uint32_t, const String&, int> Test;
99
+ TWrapper<void, const IScript::Request::AutoWrapperBase&, IScript::Request&, const String&> Complete;
100
+ } myPrefab;
101
+
102
+ void OnFinish(IScript::Request& request) {
103
+ printf("FINISH!\n");
104
+ }
105
+
106
+ void OnQueryPrefab(IScript::Request& request, IReflectObject& inter, const IScript::Request::Ref& ref) {
107
+ assert(&myPrefab == &inter);
108
+ String s = "Hello, World";
109
+
110
+ request.DoLock();
111
+ request.Push();
112
+ myPrefab.Test(request.Adapt(Wrap(OnFinish)), request, 666, s, 1234);
113
+ request.Pop();
114
+ request.Push();
115
+ myPrefab.Complete(request.Adapt(Wrap(OnFinish)), request, s);
116
+ request.Pop();
117
+ request.UnLock();
118
+
119
+ /*
120
+ request.DoLock();
121
+ request.Push();
122
+ request.Call(ref, 0, "abcasdfwhaodkjfo;asld;asdgihaosdfi");
123
+ request.Pop();
124
+ request.UnLock();*/
125
+ }
126
+
127
+ void OnQuery(IScript::Request& request, IReflectObject& inter, const IScript::Request::Ref& ref) {
128
+ RemoteFactory& testInterface = static_cast<RemoteFactory&>(inter);
129
+ IScript::Request::Ref prefab;
130
+ request.DoLock();
131
+ request.Push();
132
+
133
+ // You can choose either sync or async call.
134
+ testInterface.NewObject(IScript::Request::Sync(), request, "Prefab");
135
+ request >> prefab;
136
+
137
+ request.QueryInterface(Wrap(OnQueryPrefab), myPrefab, prefab);
138
+ request.Pop();
139
+ request.UnLock();
140
+
141
+ /*
142
+ if (prefab) {
143
+ request.Push();
144
+ request.Call(prefab, 0, "abcasdfwhaodkjfo;asld;asdgihaosdfi");
145
+ request.Pop();
146
+ }*/
147
+ }
148
+
149
+ void OnConnect(IScript::Request& request, bool isServer, RemoteProxy::STATUS status, const String& info) {
150
+ // sync call
151
+ printf("Connecting ... %d, %d\n", isServer, status);
152
+ }
153
+
154
+ void TestRPC() {
155
+ }
156
+
157
+ bool RPC::Initialize() {
158
+ return true;
159
+ }
160
+
161
+ bool RPC::Run(int randomSeed, int length) {
162
+ ZThreadPthread uniqueThreadApi;
163
+ Foo foo;
164
+ IScript::Library* module = foo.QueryInterface(UniqueType<IScript::Library>());
165
+ IScript::Object* object = foo.QueryInterface(UniqueType<IScript::Object>());
166
+
167
+ ZNetworkLibEvent network(uniqueThreadApi);
168
+ ITunnel& tunnel = network;
169
+
170
+ const PrefabFactory factory(uniqueThreadApi);
171
+
172
+ RemoteProxy serverProxy(uniqueThreadApi, tunnel, factory, "127.0.0.1:16384", Wrap(OnConnect));
173
+ serverProxy.Run();
174
+
175
+ for (int i = 0; i < length; i++) {
176
+ RemoteProxy clientProxy(uniqueThreadApi, tunnel, factory, "127.0.0.1:16385");
177
+ clientProxy.Run();
178
+ // async create request
179
+ IScript::Request* r = clientProxy.NewRequest("127.0.0.1:16384");
180
+ if (r == nullptr) {
181
+ printf("Unable to connect RPC server. Stop.\n");
182
+ break;
183
+ }
184
+
185
+ r->Destroy();
186
+ r = clientProxy.NewRequest("127.0.0.1:16384");
187
+
188
+ IScript::Request& request = *r;
189
+ request.DoLock();
190
+ request.Push();
191
+ IScript::Request::Ref global = request.Load("Global", "Initialize");
192
+ RemoteFactory testInterface;
193
+ request.QueryInterface(Wrap(OnQuery), testInterface, global);
194
+ // parse result
195
+ request.Pop();
196
+ request.UnLock();
197
+ getchar();
198
+
199
+ // Close connection
200
+ r->Destroy();
201
+ }
202
+
203
+ return true;
204
+ }
205
+
206
+ void RPC::Summary() {}
207
+
208
+ TObject<IReflect>& RPC::operator () (IReflect& reflect) {
209
+ BaseClass::operator () (reflect);
210
+
211
+ return *this;
212
+ }
pool/shard006/C++/0078634_checkpoints.cpp ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2009-2012 The GulfCoin developers
2
+ // Distributed under the MIT/X11 software license, see the accompanying
3
+ // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
+
5
+ #include <boost/assign/list_of.hpp> // for 'map_list_of()'
6
+ #include <boost/foreach.hpp>
7
+
8
+ #include "checkpoints.h"
9
+
10
+ #include "main.h"
11
+ #include "uint256.h"
12
+
13
+ namespace Checkpoints
14
+ {
15
+ typedef std::map<int, uint256> MapCheckpoints;
16
+
17
+ // How many times we expect transactions after the last checkpoint to
18
+ // be slower. This number is a compromise, as it can't be accurate for
19
+ // every system. When reindexing from a fast disk with a slow CPU, it
20
+ // can be up to 20, while when downloading from a slow network with a
21
+ // fast multicore CPU, it won't be much higher than 1.
22
+ static const double fSigcheckVerificationFactor = 5.0;
23
+
24
+ struct CCheckpointData {
25
+ const MapCheckpoints *mapCheckpoints;
26
+ int64 nTimeLastCheckpoint;
27
+ int64 nTransactionsLastCheckpoint;
28
+ double fTransactionsPerDay;
29
+ };
30
+
31
+ bool fEnabled = true;
32
+
33
+ // What makes a good checkpoint block?
34
+ // + Is surrounded by blocks with reasonable timestamps
35
+ // (no blocks before with a timestamp after, none after with
36
+ // timestamp before)
37
+ // + Contains no strange transactions
38
+ static MapCheckpoints mapCheckpoints =
39
+ boost::assign::map_list_of
40
+ ( 0, uint256("0x00000000b37e82110be5b83b20707ddbb60ac0eb3e7d6f65cf29661a55128ed3"))
41
+ ( 6870, uint256("0x0000000000013e4806cf9d4c107afe309c750e346b4be4c10ce78a5f8eb4dbd3"))
42
+ ;
43
+ static const CCheckpointData data = {
44
+ &mapCheckpoints,
45
+ 1492065540, // * UNIX timestamp of last checkpoint block
46
+ 6900, // * total number of transactions between genesis and last checkpoint
47
+ };
48
+
49
+ static MapCheckpoints mapCheckpointsTestnet =
50
+ boost::assign::map_list_of
51
+ ( 0, uint256("00000000b37e82110be5b83b20707ddbb60ac0eb3e7d6f65cf29661a55128ed3"))
52
+ ;
53
+ static const CCheckpointData dataTestnet = {
54
+ &mapCheckpointsTestnet,
55
+ };
56
+
57
+ static MapCheckpoints mapCheckpointsRegtest =
58
+ boost::assign::map_list_of
59
+ ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
60
+ ;
61
+ static const CCheckpointData dataRegtest = {
62
+ &mapCheckpointsRegtest,
63
+ 0,
64
+ 0,
65
+ 0
66
+ };
67
+
68
+ const CCheckpointData &Checkpoints() {
69
+ if (Params().NetworkID() == CChainParams::TESTNET)
70
+ return dataTestnet;
71
+ else if (Params().NetworkID() == CChainParams::MAIN)
72
+ return data;
73
+ else
74
+ return dataRegtest;
75
+ }
76
+
77
+ bool CheckBlock(int nHeight, const uint256& hash)
78
+ {
79
+ if (!fEnabled)
80
+ return true;
81
+
82
+ const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
83
+
84
+ MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
85
+ if (i == checkpoints.end()) return true;
86
+ return hash == i->second;
87
+ }
88
+
89
+ // Guess how far we are in the verification process at the given block index
90
+ double GuessVerificationProgress(CBlockIndex *pindex) {
91
+ if (pindex==NULL)
92
+ return 0.0;
93
+
94
+ int64 nNow = time(NULL);
95
+
96
+ double fWorkBefore = 0.0; // Amount of work done before pindex
97
+ double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
98
+ // Work is defined as: 1.0 per transaction before the last checkoint, and
99
+ // fSigcheckVerificationFactor per transaction after.
100
+
101
+ const CCheckpointData &data = Checkpoints();
102
+
103
+ if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
104
+ double nCheapBefore = pindex->nChainTx;
105
+ double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
106
+ double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
107
+ fWorkBefore = nCheapBefore;
108
+ fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
109
+ } else {
110
+ double nCheapBefore = data.nTransactionsLastCheckpoint;
111
+ double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
112
+ double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
113
+ fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
114
+ fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
115
+ }
116
+
117
+ return fWorkBefore / (fWorkBefore + fWorkAfter);
118
+ }
119
+
120
+ int GetTotalBlocksEstimate()
121
+ {
122
+ if (!fEnabled)
123
+ return 0;
124
+
125
+ const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
126
+
127
+ return checkpoints.rbegin()->first;
128
+ }
129
+
130
+ CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
131
+ {
132
+ if (!fEnabled)
133
+ return NULL;
134
+
135
+ const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
136
+
137
+ BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
138
+ {
139
+ const uint256& hash = i.second;
140
+ std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
141
+ if (t != mapBlockIndex.end())
142
+ return t->second;
143
+ }
144
+ return NULL;
145
+ }
146
+ }
pool/shard006/C++/0078638_ReactorAI.cpp ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * MaNGOS is a full featured server for World of Warcraft, supporting
3
+ * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
4
+ *
5
+ * Copyright (C) 2005-2022 MaNGOS <https://getmangos.eu>
6
+ *
7
+ * This program is free software; you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation; either version 2 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program; if not, write to the Free Software
19
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
+ *
21
+ * World of Warcraft, and all World of Warcraft or Warcraft art, images,
22
+ * and lore are copyrighted by Blizzard Entertainment, Inc.
23
+ */
24
+
25
+ #include "ByteBuffer.h"
26
+ #include "ReactorAI.h"
27
+ #include "Errors.h"
28
+ #include "Creature.h"
29
+ #include "Map.h"
30
+ #include "Log.h"
31
+
32
+ #define REACTOR_VISIBLE_RANGE (26.46f)
33
+
34
+ int
35
+ ReactorAI::Permissible(const Creature* creature)
36
+ {
37
+ if (creature->IsCivilian() || creature->IsNeutralToAll())
38
+ {
39
+ return PERMIT_BASE_REACTIVE;
40
+ }
41
+
42
+ return PERMIT_BASE_NO;
43
+ }
44
+
45
+ void
46
+ ReactorAI::MoveInLineOfSight(Unit*)
47
+ {
48
+ }
49
+
50
+ void
51
+ ReactorAI::AttackStart(Unit* p)
52
+ {
53
+ if (!p || !m_creature->CanInitiateAttack())
54
+ {
55
+ return;
56
+ }
57
+
58
+ if (m_creature->Attack(p, true))
59
+ {
60
+ DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Tag unit GUID: %u (TypeId: %u) as a victim", p->GetGUIDLow(), p->GetTypeId());
61
+ i_victimGuid = p->GetObjectGuid();
62
+ m_creature->AddThreat(p);
63
+
64
+ m_creature->SetInCombatWith(p);
65
+ p->SetInCombatWith(m_creature);
66
+
67
+ HandleMovementOnAttackStart(p);
68
+ }
69
+ }
70
+
71
+ bool
72
+ ReactorAI::IsVisible(Unit*) const
73
+ {
74
+ return false;
75
+ }
76
+
77
+ void
78
+ ReactorAI::UpdateAI(const uint32 /*time_diff*/)
79
+ {
80
+ // update i_victimGuid if i_creature.getVictim() !=0 and changed
81
+ if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
82
+ {
83
+ return;
84
+ }
85
+
86
+ i_victimGuid = m_creature->getVictim()->GetObjectGuid();
87
+
88
+ DoMeleeAttackIfReady();
89
+ }
90
+
91
+ void
92
+ ReactorAI::EnterEvadeMode()
93
+ {
94
+ if (!m_creature->IsAlive())
95
+ {
96
+ DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, he is dead [guid=%u]", m_creature->GetGUIDLow());
97
+ m_creature->GetMotionMaster()->MovementExpired();
98
+ m_creature->GetMotionMaster()->MoveIdle();
99
+ i_victimGuid.Clear();
100
+ m_creature->CombatStop(true);
101
+ m_creature->DeleteThreatList();
102
+ return;
103
+ }
104
+
105
+ Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid);
106
+
107
+ if (!victim)
108
+ {
109
+ DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, no victim [guid=%u]", m_creature->GetGUIDLow());
110
+ }
111
+ else if (victim->HasStealthAura())
112
+ {
113
+ DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in stealth [guid=%u]", m_creature->GetGUIDLow());
114
+ }
115
+ else if (victim->IsTaxiFlying())
116
+ {
117
+ DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in flight [guid=%u]", m_creature->GetGUIDLow());
118
+ }
119
+ else
120
+ {
121
+ 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());
122
+ }
123
+
124
+ m_creature->RemoveAllAurasOnEvade();
125
+ m_creature->DeleteThreatList();
126
+ i_victimGuid.Clear();
127
+ m_creature->CombatStop(true);
128
+ m_creature->SetLootRecipient(NULL);
129
+
130
+ // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead
131
+ if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE)
132
+ {
133
+ m_creature->GetMotionMaster()->MoveTargetedHome();
134
+ }
135
+ }
pool/shard006/C++/0078641_test_metro_viewer_process_host.cc ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "ash/test/test_metro_viewer_process_host.h"
6
+
7
+ #include <windef.h>
8
+
9
+ #include "base/logging.h"
10
+ #include "ui/aura/remote_root_window_host_win.h"
11
+ #include "ui/surface/accelerated_surface_win.h"
12
+
13
+ namespace ash {
14
+ namespace test {
15
+
16
+ TestMetroViewerProcessHost::TestMetroViewerProcessHost(
17
+ base::SingleThreadTaskRunner* ipc_task_runner)
18
+ : MetroViewerProcessHost(ipc_task_runner), closed_unexpectedly_(false) {
19
+ }
20
+
21
+ TestMetroViewerProcessHost::~TestMetroViewerProcessHost() {
22
+ }
23
+
24
+ void TestMetroViewerProcessHost::OnChannelError() {
25
+ closed_unexpectedly_ = true;
26
+ aura::RemoteRootWindowHostWin::Instance()->Disconnected();
27
+ }
28
+
29
+ void TestMetroViewerProcessHost::OnSetTargetSurface(
30
+ gfx::NativeViewId target_surface) {
31
+ DLOG(INFO) << __FUNCTION__ << ", target_surface = " << target_surface;
32
+ HWND hwnd = reinterpret_cast<HWND>(target_surface);
33
+ aura::RemoteRootWindowHostWin::Instance()->Connected(this, hwnd);
34
+
35
+ backing_surface_.reset(new AcceleratedSurface(hwnd));
36
+ }
37
+
38
+ void TestMetroViewerProcessHost::OnOpenURL(const string16& url) {
39
+ }
40
+
41
+ void TestMetroViewerProcessHost::OnHandleSearchRequest(
42
+ const string16& search_string) {
43
+ }
44
+
45
+ void TestMetroViewerProcessHost::OnWindowSizeChanged(uint32 width,
46
+ uint32 height) {
47
+ }
48
+
49
+ } // namespace test
50
+ } // namespace ash
pool/shard006/C++/0078643_Firm.cpp ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (C) 2014-2020 Sven Willner <sven.willner@pik-potsdam.de>
3
+ Christian Otto <christian.otto@pik-potsdam.de>
4
+
5
+ This file is part of Acclimate.
6
+
7
+ Acclimate is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU Affero General Public License as
9
+ published by the Free Software Foundation, either version 3 of
10
+ the License, or (at your option) any later version.
11
+
12
+ Acclimate is distributed in the hope that it will be useful,
13
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ GNU Affero General Public License for more details.
16
+
17
+ You should have received a copy of the GNU Affero General Public License
18
+ along with Acclimate. If not, see <http://www.gnu.org/licenses/>.
19
+ */
20
+
21
+ #include "model/Firm.h"
22
+
23
+ #include <algorithm>
24
+ #include <utility>
25
+
26
+ #include "acclimate.h"
27
+ #include "model/CapacityManager.h"
28
+ #include "model/EconomicAgent.h"
29
+ #include "model/PurchasingManager.h"
30
+ #include "model/SalesManager.h"
31
+ #include "model/Sector.h"
32
+ #include "model/Storage.h"
33
+
34
+ namespace acclimate {
35
+
36
+ Firm::Firm(id_t id_p, Sector* sector_p, Region* region_p, const Ratio& possible_overcapacity_ratio_beta_p)
37
+ : EconomicAgent(std::move(id_p), region_p, EconomicAgent::type_t::FIRM),
38
+ sector(sector_p),
39
+ capacity_manager(new CapacityManager(this, possible_overcapacity_ratio_beta_p)),
40
+ sales_manager(new SalesManager(this)) {}
41
+
42
+ void Firm::produce_X() {
43
+ debug::assertstep(this, IterationStep::CONSUMPTION_AND_PRODUCTION);
44
+ production_X_ = capacity_manager->calc_production_X();
45
+ assert(production_X_.get_quantity() >= 0.0);
46
+ sector->add_production_X(production_X_);
47
+ }
48
+
49
+ void Firm::iterate_consumption_and_production() {
50
+ debug::assertstep(this, IterationStep::CONSUMPTION_AND_PRODUCTION);
51
+ produce_X();
52
+ for (const auto& is : input_storages) {
53
+ Flow used_flow_U_current = round(production_X_ * is->get_technology_coefficient_a());
54
+ if (production_X_.get_quantity() > 0.0) {
55
+ used_flow_U_current.set_price(is->get_possible_use_U_hat().get_price());
56
+ }
57
+ is->use_content_S(used_flow_U_current);
58
+ is->iterate_consumption_and_production();
59
+ }
60
+ sales_manager->distribute();
61
+ }
62
+
63
+ void Firm::iterate_expectation() {
64
+ debug::assertstep(this, IterationStep::EXPECTATION);
65
+ sales_manager->iterate_expectation();
66
+ for (const auto& is : input_storages) {
67
+ const FlowQuantity& desired_production =
68
+ std::max(sales_manager->communicated_parameters().expected_production_X.get_quantity(), sales_manager->sum_demand_requests_D().get_quantity());
69
+ is->set_desired_used_flow_U_tilde(round(desired_production * is->get_technology_coefficient_a()));
70
+ }
71
+ }
72
+
73
+ void Firm::add_initial_production_X_star(const Flow& initial_production_flow_X_star) {
74
+ debug::assertstep(this, IterationStep::INITIALIZATION);
75
+ initial_production_X_star_ += initial_production_flow_X_star;
76
+ production_X_ += initial_production_flow_X_star;
77
+ sales_manager->add_initial_demand_request_D_star(initial_production_flow_X_star);
78
+ sector->add_initial_production_X(initial_production_flow_X_star);
79
+ }
80
+
81
+ void Firm::subtract_initial_production_X_star(const Flow& initial_production_flow_X_star) {
82
+ debug::assertstep(this, IterationStep::INITIALIZATION);
83
+ initial_production_X_star_ -= initial_production_flow_X_star;
84
+ production_X_ -= initial_production_flow_X_star;
85
+ sales_manager->subtract_initial_demand_request_D_star(initial_production_flow_X_star);
86
+ sector->subtract_initial_production_X(initial_production_flow_X_star);
87
+ }
88
+
89
+ void Firm::add_initial_total_use_U_star(const Flow& initial_use_flow_U_star) {
90
+ debug::assertstep(this, IterationStep::INITIALIZATION);
91
+ initial_total_use_U_star_ += initial_use_flow_U_star;
92
+ }
93
+
94
+ void Firm::subtract_initial_total_use_U_star(const Flow& initial_use_flow_U_star) {
95
+ debug::assertstep(this, IterationStep::INITIALIZATION);
96
+ if (initial_total_use_U_star_.get_quantity() > initial_use_flow_U_star.get_quantity()) {
97
+ initial_total_use_U_star_ -= initial_use_flow_U_star;
98
+ } else {
99
+ initial_total_use_U_star_ = Flow(0.0);
100
+ }
101
+ }
102
+
103
+ void Firm::iterate_purchase() {
104
+ debug::assertstep(this, IterationStep::PURCHASE);
105
+ for (const auto& is : input_storages) {
106
+ is->purchasing_manager->iterate_purchase();
107
+ }
108
+ }
109
+
110
+ void Firm::iterate_investment() {
111
+ // debug::assertstep(this, IterationStep::INVESTMENT);
112
+ // for (const auto& is : input_storages) {
113
+ // is->purchasing_manager->iterate_investment();
114
+ // }
115
+ }
116
+
117
+ Flow Firm::maximal_production_beta_X_star() const { return round(initial_production_X_star_ * capacity_manager->possible_overcapacity_ratio_beta); }
118
+
119
+ FlowQuantity Firm::forced_maximal_production_quantity_lambda_beta_X_star() const {
120
+ return round(initial_production_X_star_.get_quantity() * (capacity_manager->possible_overcapacity_ratio_beta * forcing_m));
121
+ }
122
+
123
+ const BusinessConnection* Firm::self_supply_connection() const {
124
+ debug::assertstepnot(this, IterationStep::CONSUMPTION_AND_PRODUCTION);
125
+ return self_supply_connection_.get();
126
+ }
127
+
128
+ void Firm::self_supply_connection(std::shared_ptr<BusinessConnection> self_supply_connection_p) {
129
+ debug::assertstep(this, IterationStep::INITIALIZATION);
130
+ self_supply_connection_ = std::move(self_supply_connection_p);
131
+ }
132
+
133
+ const Flow& Firm::production_X() const {
134
+ debug::assertstepnot(this, IterationStep::CONSUMPTION_AND_PRODUCTION);
135
+ return production_X_;
136
+ }
137
+
138
+ void Firm::debug_print_details() const {
139
+ if constexpr (options::DEBUGGING) {
140
+ log::info(this, "X_star= ", initial_production_X_star_.get_quantity(), ":");
141
+ for (const auto& input_storage : input_storages) {
142
+ input_storage->purchasing_manager->debug_print_details();
143
+ }
144
+ sales_manager->debug_print_details();
145
+ }
146
+ }
147
+
148
+ } // namespace acclimate
pool/shard006/C++/0078645_max_size.pass.cpp ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // The LLVM Compiler Infrastructure
4
+ //
5
+ // This file is dual licensed under the MIT and the University of Illinois Open
6
+ // Source Licenses. See LICENSE.TXT for details.
7
+ //
8
+ //===----------------------------------------------------------------------===//
9
+
10
+ // <unordered_map>
11
+
12
+ // class unordered_multimap
13
+
14
+ // size_type max_size() const;
15
+
16
+ #include <cassert>
17
+ #include <limits>
18
+ #include <type_traits>
19
+ #include <unordered_map>
20
+
21
+ #include "test_allocator.h"
22
+ #include "test_macros.h"
23
+
24
+ int main()
25
+ {
26
+ typedef std::pair<const int, int> KV;
27
+ {
28
+ typedef limited_allocator<KV, 10> A;
29
+ typedef std::unordered_multimap<int, int, std::hash<int>,
30
+ std::equal_to<int>, A>
31
+ C;
32
+ C c;
33
+ assert(c.max_size() <= 10);
34
+ LIBCPP_ASSERT(c.max_size() == 10);
35
+ }
36
+ {
37
+ typedef limited_allocator<KV, (size_t)-1> A;
38
+ typedef std::unordered_multimap<int, int, std::hash<int>,
39
+ std::equal_to<int>, A>
40
+ C;
41
+ const C::difference_type max_dist =
42
+ std::numeric_limits<C::difference_type>::max();
43
+ C c;
44
+ assert(c.max_size() <= max_dist);
45
+ LIBCPP_ASSERT(c.max_size() == max_dist);
46
+ }
47
+ {
48
+ typedef std::unordered_multimap<char, int> C;
49
+ const C::difference_type max_dist =
50
+ std::numeric_limits<C::difference_type>::max();
51
+ C c;
52
+ assert(c.max_size() <= max_dist);
53
+ assert(c.max_size() <= alloc_max_size(c.get_allocator()));
54
+ }
55
+ }
pool/shard006/C++/0078646_gist.cpp ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2
+ /*
3
+ * Main authors:
4
+ * Guido Tack <tack@gecode.org>
5
+ *
6
+ * Copyright:
7
+ * Guido Tack, 2006
8
+ *
9
+ * Last modified:
10
+ * $Date: 2011-08-25 10:43:31 +0200 (to, 25 aug 2011) $ by $Author: tack $
11
+ * $Revision: 12352 $
12
+ *
13
+ * This file is part of Gecode, the generic constraint
14
+ * development environment:
15
+ * http://www.gecode.org
16
+ *
17
+ * Permission is hereby granted, free of charge, to any person obtaining
18
+ * a copy of this software and associated documentation files (the
19
+ * "Software"), to deal in the Software without restriction, including
20
+ * without limitation the rights to use, copy, modify, merge, publish,
21
+ * distribute, sublicense, and/or sell copies of the Software, and to
22
+ * permit persons to whom the Software is furnished to do so, subject to
23
+ * the following conditions:
24
+ *
25
+ * The above copyright notice and this permission notice shall be
26
+ * included in all copies or substantial portions of the Software.
27
+ *
28
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
+ *
36
+ */
37
+
38
+ #include <QtGui>
39
+
40
+ #include <gecode/gist.hh>
41
+ #include <gecode/gist/textoutput.hh>
42
+ #include <gecode/gist/mainwindow.hh>
43
+ #include <gecode/gist/stopbrancher.hh>
44
+
45
+ namespace Gecode { namespace Gist {
46
+
47
+ std::string
48
+ Inspector::name(void) { return "Inspector"; }
49
+
50
+ void
51
+ Inspector::finalize(void) {}
52
+
53
+ Inspector::~Inspector(void) {}
54
+
55
+ std::string
56
+ Comparator::name(void) { return "Comparator"; }
57
+
58
+ void
59
+ Comparator::finalize(void) {}
60
+
61
+ Comparator::~Comparator(void) {}
62
+
63
+ TextOutput::TextOutput(const std::string& name)
64
+ : t(NULL), n(name) {}
65
+
66
+ void
67
+ TextOutput::finalize(void) {
68
+ delete t;
69
+ t = NULL;
70
+ }
71
+
72
+ TextOutput::~TextOutput(void) {
73
+ delete t;
74
+ }
75
+
76
+ std::string
77
+ TextOutput::name(void) { return n; }
78
+
79
+ void
80
+ TextOutput::init(void) {
81
+ if (t == NULL) {
82
+ t = new TextOutputI(n);
83
+ }
84
+ t->setVisible(true);
85
+ }
86
+
87
+ std::ostream&
88
+ TextOutput::getStream(void) {
89
+ return t->getStream();
90
+ }
91
+
92
+ void
93
+ TextOutput::flush(void) {
94
+ t->flush();
95
+ }
96
+
97
+ void
98
+ TextOutput::addHtml(const char* s) {
99
+ t->insertHtml(s);
100
+ }
101
+
102
+ const Options Options::def;
103
+
104
+ int
105
+ explore(Space* root, bool bab, const Options& opt) {
106
+ char argv0='\0'; char* argv1=&argv0;
107
+ int argc=0;
108
+ QApplication app(argc, &argv1);
109
+ GistMainWindow mw(root, bab, opt);
110
+ return app.exec();
111
+ }
112
+
113
+ void
114
+ stopBranch(Space& home) {
115
+ StopBrancher::post(home);
116
+ }
117
+
118
+ }}
119
+
120
+ // STATISTICS: gist-any
pool/shard006/C++/0078662_lock_impl_unittest.cc ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2018 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "chromeos/components/nearby/lock_impl.h"
6
+
7
+ #include <memory>
8
+
9
+ #include "base/bind.h"
10
+ #include "base/containers/flat_set.h"
11
+ #include "base/single_thread_task_runner.h"
12
+ #include "base/stl_util.h"
13
+ #include "base/task/post_task.h"
14
+ #include "base/task/thread_pool.h"
15
+ #include "base/test/gtest_util.h"
16
+ #include "base/test/task_environment.h"
17
+ #include "base/test/test_timeouts.h"
18
+ #include "base/threading/platform_thread.h"
19
+ #include "base/unguessable_token.h"
20
+ #include "testing/gtest/include/gtest/gtest.h"
21
+
22
+ namespace chromeos {
23
+
24
+ namespace nearby {
25
+
26
+ class LockImplTest : public testing::Test {
27
+ protected:
28
+ LockImplTest()
29
+ : lock_(std::make_unique<LockImpl>()),
30
+ different_thread_task_runner_(
31
+ base::ThreadPool::CreateSingleThreadTaskRunner(
32
+ {base::MayBlock()})) {}
33
+
34
+ // testing::Test
35
+ void SetUp() override {
36
+ // |different_thread_task_runner_| is expected to run on a different thread
37
+ // than the main test thread.
38
+ EXPECT_FALSE(different_thread_task_runner_->BelongsToCurrentThread());
39
+ }
40
+
41
+ void TearDown() override {
42
+ // Releases the test thread's ownership of |lock_|.
43
+ int times_to_unlock;
44
+ {
45
+ base::AutoLock al(lock_->bookkeeping_lock_);
46
+ times_to_unlock = lock_->num_acquisitions_;
47
+ }
48
+ for (int i = 0; i < times_to_unlock; ++i)
49
+ lock_->unlock();
50
+
51
+ // Makes sure that outstanding LockAndUnlockFromDifferentThread() tasks in
52
+ // |different_thread_task_runner_| finish running after the test thread
53
+ // relinquishes its ownership of |lock_|.
54
+ task_environment_.RunUntilIdle();
55
+
56
+ base::AutoLock al(lock_->bookkeeping_lock_);
57
+ EXPECT_EQ(0u, lock_->num_acquisitions_);
58
+ EXPECT_EQ(base::kInvalidThreadId, lock_->owning_thread_id_);
59
+ }
60
+
61
+ void PostLockAndUnlockFromDifferentThread(
62
+ const base::UnguessableToken& attempt_id) {
63
+ different_thread_task_runner_->PostTask(
64
+ FROM_HERE,
65
+ base::BindOnce(&LockImplTest::LockAndUnlockFromDifferentThread,
66
+ base::Unretained(this), attempt_id));
67
+ }
68
+
69
+ // Invoked whenever attempting to verify that a parallel task has indeed
70
+ // blocked, since there's no way to deterministically find out if that task
71
+ // will ever unblock.
72
+ void TinyTimeout() {
73
+ base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
74
+ }
75
+
76
+ bool HasSuccessfullyLockedWithAttemptId(
77
+ const base::UnguessableToken& attempt_id) {
78
+ lock_->lock();
79
+ bool contains_key = base::Contains(successful_lock_attempts_, attempt_id);
80
+ lock_->unlock();
81
+ return contains_key;
82
+ }
83
+
84
+ location::nearby::Lock* lock() { return lock_.get(); }
85
+
86
+ base::test::TaskEnvironment task_environment_;
87
+
88
+ private:
89
+ // Only meant to be posted via PostLockAndUnlockFromDifferentThread() on
90
+ // |different_thread_task_runner_|.
91
+ //
92
+ // This method will only insert |attempt_id| into |successful_lock_attempts_|
93
+ // if it succeeds in acquiring |lock_|. It will also immediately unlock()
94
+ // after doing so because unlock() may only be called from the same thread
95
+ // that originally called lock().
96
+ void LockAndUnlockFromDifferentThread(
97
+ const base::UnguessableToken& attempt_id) {
98
+ lock_->lock();
99
+ successful_lock_attempts_.insert(attempt_id);
100
+ lock_->unlock();
101
+ }
102
+
103
+ std::unique_ptr<LockImpl> lock_;
104
+ scoped_refptr<base::SingleThreadTaskRunner> different_thread_task_runner_;
105
+ base::flat_set<base::UnguessableToken> successful_lock_attempts_;
106
+
107
+ DISALLOW_COPY_AND_ASSIGN(LockImplTest);
108
+ };
109
+
110
+ TEST_F(LockImplTest, LockOnce_UnlockOnce) {
111
+ lock()->lock();
112
+ lock()->unlock();
113
+ }
114
+
115
+ TEST_F(LockImplTest, LockThrice_UnlockThrice) {
116
+ lock()->lock();
117
+ lock()->lock();
118
+ lock()->lock();
119
+ lock()->unlock();
120
+ lock()->unlock();
121
+ lock()->unlock();
122
+ }
123
+
124
+ TEST_F(LockImplTest,
125
+ LockOnce_DisallowRelockingFromDifferentThreadUntilCurrentThreadUnlocks) {
126
+ // Lock on current thread.
127
+ lock()->lock();
128
+
129
+ // Try to lock again, but on different thread.
130
+ base::UnguessableToken attempt_id = base::UnguessableToken::Create();
131
+ PostLockAndUnlockFromDifferentThread(attempt_id);
132
+
133
+ // Wait for a little, then check to see if the lock attempt failed.
134
+ TinyTimeout();
135
+ EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id));
136
+
137
+ // Outstanding lock attempt succeed after unlocking from current thread.
138
+ lock()->unlock();
139
+ task_environment_.RunUntilIdle();
140
+ EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id));
141
+ }
142
+
143
+ TEST_F(
144
+ LockImplTest,
145
+ LockThrice_DisallowRelockingFromDifferentThreadUntilCurrentThreadUnlocks) {
146
+ // Lock on current thread.
147
+ lock()->lock();
148
+ lock()->lock();
149
+ lock()->lock();
150
+
151
+ // Try to lock again, but on different thread.
152
+ base::UnguessableToken attempt_id = base::UnguessableToken::Create();
153
+ PostLockAndUnlockFromDifferentThread(attempt_id);
154
+
155
+ // Wait for a little, then check to see if the lock attempt failed.
156
+ TinyTimeout();
157
+ EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id));
158
+
159
+ // Outstanding lock attempt succeed after unlocking from current thread.
160
+ lock()->unlock();
161
+ lock()->unlock();
162
+ lock()->unlock();
163
+ task_environment_.RunUntilIdle();
164
+ EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id));
165
+ }
166
+
167
+ TEST_F(LockImplTest, InterweavedLocking) {
168
+ base::UnguessableToken attempt_id1 = base::UnguessableToken::Create();
169
+ base::UnguessableToken attempt_id2 = base::UnguessableToken::Create();
170
+ base::UnguessableToken attempt_id3 = base::UnguessableToken::Create();
171
+
172
+ lock()->lock();
173
+ PostLockAndUnlockFromDifferentThread(attempt_id1);
174
+ lock()->lock();
175
+ PostLockAndUnlockFromDifferentThread(attempt_id2);
176
+ lock()->lock();
177
+ PostLockAndUnlockFromDifferentThread(attempt_id3);
178
+
179
+ TinyTimeout();
180
+ EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id1));
181
+ EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id2));
182
+ EXPECT_FALSE(HasSuccessfullyLockedWithAttemptId(attempt_id3));
183
+
184
+ lock()->unlock();
185
+ lock()->unlock();
186
+ lock()->unlock();
187
+ task_environment_.RunUntilIdle();
188
+ EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id1));
189
+ EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id2));
190
+ EXPECT_TRUE(HasSuccessfullyLockedWithAttemptId(attempt_id3));
191
+ }
192
+
193
+ TEST_F(LockImplTest, CannotUnlockBeforeAnyLocks) {
194
+ EXPECT_DCHECK_DEATH(lock()->unlock());
195
+ }
196
+
197
+ } // namespace nearby
198
+
199
+ } // namespace chromeos
pool/shard006/C++/0078666_lanRouter.cc ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */
2
+
3
+ /*
4
+ * Copyright (C) 1998 by the University of Southern California
5
+ * $Id: lanRouter.cc,v 1.10 2005/08/25 18:58:07 johnh Exp $
6
+ *
7
+ * This program is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU General Public License,
9
+ * version 2, as published by the Free Software Foundation.
10
+ *
11
+ * This program is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ * GNU General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU General Public License along
17
+ * with this program; if not, write to the Free Software Foundation, Inc.,
18
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19
+ *
20
+ *
21
+ * The copyright of this module includes the following
22
+ * linking-with-specific-other-licenses addition:
23
+ *
24
+ * In addition, as a special exception, the copyright holders of
25
+ * this module give you permission to combine (via static or
26
+ * dynamic linking) this module with free software programs or
27
+ * libraries that are released under the GNU LGPL and with code
28
+ * included in the standard release of ns-2 under the Apache 2.0
29
+ * license or under otherwise-compatible licenses with advertising
30
+ * requirements (or modified versions of such code, with unchanged
31
+ * license). You may copy and distribute such a system following the
32
+ * terms of the GNU GPL for this module and the licenses of the
33
+ * other code concerned, provided that you include the source code of
34
+ * that other code when and as the GNU GPL requires distribution of
35
+ * source code.
36
+ *
37
+ * Note that people who make modified versions of this module
38
+ * are not obligated to grant this special exception for their
39
+ * modified versions; it is their choice whether to do so. The GNU
40
+ * General Public License gives permission to release a modified
41
+ * version without this exception; this exception also makes it
42
+ * possible to release a modified version which carries forward this
43
+ * exception.
44
+ *
45
+ */
46
+
47
+ #ifndef lint
48
+ static const char rcsid[] =
49
+ "@(#) $Header: /usr/src/mash/repository/vint/ns-2/lanRouter.cc";
50
+ #endif
51
+
52
+ #include <tcl.h>
53
+ #include "lanRouter.h"
54
+ #include "address.h"
55
+ #include "ip.h"
56
+
57
+ static class LanRouterClass : public TclClass {
58
+ public:
59
+ LanRouterClass() : TclClass("LanRouter") {}
60
+ TclObject* create(int, const char*const*) {
61
+ return (new LanRouter());
62
+ }
63
+ } class_mac;
64
+
65
+ int LanRouter::next_hop(Packet *p) {
66
+ if (switch_ && switch_->classify(p)==1) {
67
+ return -1;
68
+ }
69
+ if (!routelogic_) return -1;
70
+
71
+ hdr_ip* iph= hdr_ip::access(p);
72
+ char* adst= Address::instance().print_nodeaddr(iph->daddr());
73
+ int next_hopIP;
74
+
75
+ if (enableHrouting_) {
76
+ char* bdst;
77
+
78
+ routelogic_->lookup_hier(lanaddr_, adst, next_hopIP);
79
+ // hacking: get rid of the last "."
80
+ bdst = Address::instance().print_nodeaddr(next_hopIP);
81
+ // bdst[strlen(bdst)-1] = '\0';
82
+ Tcl &tcl = Tcl::instance();
83
+ tcl.evalf("[Simulator instance] get-node-id-by-addr %s", bdst);
84
+ sscanf(tcl.result(), "%d", &next_hopIP);
85
+ delete [] bdst;
86
+ } else {
87
+ routelogic_->lookup_flat(lanaddr_, adst, next_hopIP);
88
+ }
89
+ delete [] adst;
90
+
91
+ return next_hopIP;
92
+ }
93
+ int LanRouter::command(int argc, const char*const* argv)
94
+ {
95
+ // Tcl& tcl = Tcl::instance();
96
+ if (argc == 3) {
97
+ // cmd lanaddr <addr>
98
+ if (strcmp(argv[1], "lanaddr") == 0) {
99
+ strcpy(lanaddr_, argv[2]);
100
+ return (TCL_OK);
101
+ }
102
+ // cmd routing hier|flat
103
+ if (strcmp(argv[1], "routing") == 0) {
104
+ if (strcmp(argv[2], "hier")==0)
105
+ enableHrouting_= true;
106
+ else if (strcmp(argv[2], "flat")==0)
107
+ enableHrouting_= false;
108
+ else return (TCL_ERROR);
109
+ return (TCL_OK);
110
+ }
111
+ // cmd switch <switch>
112
+ if (strcmp(argv[1], "switch") == 0) {
113
+ switch_ = (Classifier*) TclObject::lookup(argv[2]);
114
+ return (TCL_OK);
115
+ }
116
+ // cmd routelogic <routelogic>
117
+ if (strcmp(argv[1], "routelogic") == 0) {
118
+ routelogic_ = (RouteLogic*) TclObject::lookup(argv[2]);
119
+ return (TCL_OK);
120
+ }
121
+ }
122
+ return NsObject::command(argc, argv);
123
+ }
124
+
125
+
126
+
127
+
128
+
129
+
pool/shard006/C++/0078667_EventFactory.cpp ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Siconos is a program dedicated to modeling, simulation and control
2
+ * of non smooth dynamical systems.
3
+ *
4
+ * Copyright 2020 INRIA.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ #include "EventFactory.hpp"
20
+ #include "SiconosException.hpp"
21
+ #include <iostream>
22
+
23
+
24
+
25
+ namespace EventFactory
26
+ {
27
+
28
+ Registry& Registry::get()
29
+ {
30
+ static Registry instance;
31
+ return instance;
32
+ }
33
+
34
+ void Registry::add(int type, object_creator creator)
35
+ {
36
+ factory_map[type] = creator;
37
+ }
38
+
39
+ SP::Event Registry::instantiate(double time, int type)
40
+ {
41
+ MapFactoryIt it = factory_map.find(type) ;
42
+
43
+ if(it == factory_map.end())
44
+ THROW_EXCEPTION("Registry::instantiate (EventFactory) failed, no class with id: " + std::to_string(type));
45
+
46
+ return (it->second)(time, type) ; // run our factory
47
+ }
48
+
49
+ Registration::Registration(int type, object_creator creator)
50
+ {
51
+ Registry::get().add(type, creator) ;
52
+ }
53
+
54
+ }
pool/shard006/C++/0078671_testing_cgebrd.cpp ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ -- MAGMA (version 1.5.0-beta3) --
3
+ Univ. of Tennessee, Knoxville
4
+ Univ. of California, Berkeley
5
+ Univ. of Colorado, Denver
6
+ @date July 2014
7
+
8
+ @generated from testing_zgebrd.cpp normal z -> c, Fri Jul 18 17:34:25 2014
9
+
10
+ */
11
+
12
+ // includes, system
13
+ #include <stdlib.h>
14
+ #include <stdio.h>
15
+ #include <string.h>
16
+ #include <math.h>
17
+ #include <cuda_runtime_api.h>
18
+ #include <cublas.h>
19
+
20
+ // includes, project
21
+ #include "flops.h"
22
+ #include "magma.h"
23
+ #include "magma_lapack.h"
24
+ #include "testings.h"
25
+
26
+ #define PRECISION_c
27
+
28
+ /* ////////////////////////////////////////////////////////////////////////////
29
+ -- Testing cgebrd
30
+ */
31
+ int main( int argc, char** argv)
32
+ {
33
+ TESTING_INIT();
34
+
35
+ real_Double_t gflops, gpu_perf, gpu_time, cpu_perf, cpu_time;
36
+ magmaFloatComplex *h_A, *h_Q, *h_PT, *h_work;
37
+ magmaFloatComplex *taup, *tauq;
38
+ float *diag, *offdiag;
39
+ float eps, result[3] = {0., 0., 0.};
40
+ magma_int_t M, N, n2, lda, lhwork, info, minmn, nb;
41
+ magma_int_t ione = 1;
42
+ magma_int_t ISEED[4] = {0,0,0,1};
43
+
44
+ eps = lapackf77_slamch( "E" );
45
+ magma_int_t status = 0;
46
+
47
+ magma_opts opts;
48
+ parse_opts( argc, argv, &opts );
49
+
50
+ float tol = opts.tolerance * lapackf77_slamch("E");
51
+
52
+ printf(" M N CPU GFlop/s (sec) GPU GFlop/s (sec) |A-QBP'|/N|A| |I-QQ'|/N |I-PP'|/N\n");
53
+ printf("=========================================================================================\n");
54
+ for( int itest = 0; itest < opts.ntest; ++itest ) {
55
+ for( int iter = 0; iter < opts.niter; ++iter ) {
56
+ M = opts.msize[itest];
57
+ N = opts.nsize[itest];
58
+ minmn = min(M, N);
59
+ nb = magma_get_cgebrd_nb(N);
60
+ lda = M;
61
+ n2 = lda*N;
62
+ lhwork = (M + N)*nb;
63
+ gflops = FLOPS_CGEBRD( M, N ) / 1e9;
64
+
65
+ TESTING_MALLOC_CPU( h_A, magmaFloatComplex, lda*N );
66
+ TESTING_MALLOC_CPU( tauq, magmaFloatComplex, minmn );
67
+ TESTING_MALLOC_CPU( taup, magmaFloatComplex, minmn );
68
+ TESTING_MALLOC_CPU( diag, float, minmn );
69
+ TESTING_MALLOC_CPU( offdiag, float, minmn-1 );
70
+
71
+ TESTING_MALLOC_PIN( h_Q, magmaFloatComplex, lda*N );
72
+ TESTING_MALLOC_PIN( h_work, magmaFloatComplex, lhwork );
73
+
74
+ /* Initialize the matrices */
75
+ lapackf77_clarnv( &ione, ISEED, &n2, h_A );
76
+ lapackf77_clacpy( MagmaUpperLowerStr, &M, &N, h_A, &lda, h_Q, &lda );
77
+
78
+ /* ====================================================================
79
+ Performs operation using MAGMA
80
+ =================================================================== */
81
+ gpu_time = magma_wtime();
82
+ magma_cgebrd( M, N, h_Q, lda,
83
+ diag, offdiag, tauq, taup,
84
+ h_work, lhwork, &info);
85
+ gpu_time = magma_wtime() - gpu_time;
86
+ gpu_perf = gflops / gpu_time;
87
+ if (info != 0)
88
+ printf("magma_cgebrd returned error %d: %s.\n",
89
+ (int) info, magma_strerror( info ));
90
+
91
+ /* =====================================================================
92
+ Check the factorization
93
+ =================================================================== */
94
+ if ( opts.check ) {
95
+ // cungbr prefers minmn*NB
96
+ // cbdt01 needs M+N
97
+ // cunt01 prefers minmn*(minmn+1) to check Q and P
98
+ magma_int_t lwork_err;
99
+ magmaFloatComplex *h_work_err;
100
+ lwork_err = max( minmn * nb, M+N );
101
+ lwork_err = max( lwork_err, minmn*(minmn+1) );
102
+ TESTING_MALLOC_CPU( h_PT, magmaFloatComplex, lda*N );
103
+ TESTING_MALLOC_CPU( h_work_err, magmaFloatComplex, lwork_err );
104
+
105
+ // cbdt01 needs M
106
+ // cunt01 needs minmn
107
+ #if defined(PRECISION_z) || defined(PRECISION_c)
108
+ float *rwork_err;
109
+ TESTING_MALLOC_CPU( rwork_err, float, M );
110
+ #endif
111
+
112
+ lapackf77_clacpy(MagmaUpperLowerStr, &M, &N, h_Q, &lda, h_PT, &lda);
113
+
114
+ // generate Q & P'
115
+ lapackf77_cungbr("Q", &M, &minmn, &N, h_Q, &lda, tauq, h_work_err, &lwork_err, &info);
116
+ if (info != 0)
117
+ printf("lapackf77_cungbr #1 returned error %d: %s.\n",
118
+ (int) info, magma_strerror( info ));
119
+ lapackf77_cungbr("P", &minmn, &N, &M, h_PT, &lda, taup, h_work_err, &lwork_err, &info);
120
+ if (info != 0)
121
+ printf("lapackf77_cungbr #2 returned error %d: %s.\n",
122
+ (int) info, magma_strerror( info ));
123
+
124
+ // Test 1: Check the decomposition A := Q * B * PT
125
+ // 2: Check the orthogonality of Q
126
+ // 3: Check the orthogonality of PT
127
+ #if defined(PRECISION_z) || defined(PRECISION_c)
128
+ lapackf77_cbdt01(&M, &N, &ione,
129
+ h_A, &lda, h_Q, &lda,
130
+ diag, offdiag, h_PT, &lda,
131
+ h_work_err, rwork_err, &result[0]);
132
+ lapackf77_cunt01("Columns", &M, &minmn, h_Q, &lda, h_work_err, &lwork_err, rwork_err, &result[1]);
133
+ lapackf77_cunt01("Rows", &minmn, &N, h_PT, &lda, h_work_err, &lwork_err, rwork_err, &result[2]);
134
+ #else
135
+ lapackf77_cbdt01(&M, &N, &ione,
136
+ h_A, &lda, h_Q, &lda,
137
+ diag, offdiag, h_PT, &lda,
138
+ h_work_err, &result[0]);
139
+ lapackf77_cunt01("Columns", &M, &minmn, h_Q, &lda, h_work_err, &lwork_err, &result[1]);
140
+ lapackf77_cunt01("Rows", &minmn, &N, h_PT, &lda, h_work_err, &lwork_err, &result[2]);
141
+ #endif
142
+
143
+ TESTING_FREE_CPU( h_PT );
144
+ TESTING_FREE_CPU( h_work_err );
145
+ #if defined(PRECISION_z) || defined(PRECISION_c)
146
+ TESTING_FREE_CPU( rwork_err );
147
+ #endif
148
+ }
149
+
150
+ /* =====================================================================
151
+ Performs operation using LAPACK
152
+ =================================================================== */
153
+ if ( opts.lapack ) {
154
+ cpu_time = magma_wtime();
155
+ lapackf77_cgebrd(&M, &N, h_A, &lda,
156
+ diag, offdiag, tauq, taup,
157
+ h_work, &lhwork, &info);
158
+ cpu_time = magma_wtime() - cpu_time;
159
+ cpu_perf = gflops / cpu_time;
160
+ if (info != 0)
161
+ printf("lapackf77_cgebrd returned error %d: %s.\n",
162
+ (int) info, magma_strerror( info ));
163
+ }
164
+
165
+ /* =====================================================================
166
+ Print performance and error.
167
+ =================================================================== */
168
+ if ( opts.lapack ) {
169
+ printf("%5d %5d %7.2f (%7.2f) %7.2f (%7.2f)",
170
+ (int) M, (int) N, cpu_perf, cpu_time, gpu_perf, gpu_time );
171
+ }
172
+ else {
173
+ printf("%5d %5d --- ( --- ) %7.2f (%7.2f)",
174
+ (int) M, (int) N, gpu_perf, gpu_time );
175
+ }
176
+ if ( opts.check ) {
177
+ printf(" %8.2e %8.2e %8.2e %s\n",
178
+ result[0]*eps, result[1]*eps, result[2]*eps,
179
+ (result[0]*eps < tol && result[1]*eps < tol && result[2]*eps < tol ? "ok" : "failed") );
180
+ status += ! (result[0]*eps < tol && result[1]*eps < tol && result[2]*eps < tol);
181
+ } else {
182
+ printf(" --- --- \n");
183
+ }
184
+
185
+ TESTING_FREE_CPU( h_A );
186
+ TESTING_FREE_CPU( tauq );
187
+ TESTING_FREE_CPU( taup );
188
+ TESTING_FREE_CPU( diag );
189
+ TESTING_FREE_CPU( offdiag );
190
+
191
+ TESTING_FREE_PIN( h_Q );
192
+ TESTING_FREE_PIN( h_work );
193
+ fflush( stdout );
194
+ }
195
+ if ( opts.niter > 1 ) {
196
+ printf( "\n" );
197
+ }
198
+ }
199
+
200
+ TESTING_FINALIZE();
201
+ return status;
202
+ }
pool/shard006/C++/0078672_GraphNodeView.cpp ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "stdafx.h"
2
+
3
+ #ifndef GRAPHNODEVIEW_H
4
+ #include "GraphNodeView.h"
5
+ #endif
6
+ #ifndef GRAPHEDGEVIEW_H
7
+ #include "stdafx.h"
8
+ #include "GraphEdgeView.h"
9
+ #endif
10
+ #ifndef PLANSTEPEX_H
11
+ #include "PlanStepEx.h"
12
+ #endif
13
+ #include "OlcbpPlanNodeData.h"
14
+
15
+ using namespace IStrategizer;
16
+ using namespace std;
17
+
18
+ GraphNodeView::GraphNodeView(PlanStepEx* pPlanStep, ConstOlcbpPlanNodeDataPtr pNodeData, QMenu *pContextMeun, QGraphicsItem *pParent /* = 0 */) :
19
+ QGraphicsRectItem(pParent),
20
+ m_modelId(pPlanStep->Id()),
21
+ m_isActive(false),
22
+ m_isOpen(false),
23
+ m_pNodeModel(pPlanStep),
24
+ m_pContextMenu(pContextMeun),
25
+ m_pNodeData(pNodeData),
26
+ m_SatisfyingGoalId(IOlcbpPlan::NullNodeID)
27
+ {
28
+ _ASSERTE(m_pNodeModel);
29
+
30
+ m_nodeTxt = QString::fromStdString(pPlanStep->ToString(true));
31
+ m_tooltipTxt[0] = 0,
32
+
33
+ m_style = GetStyle();
34
+
35
+ setBrush(m_style.BackgroundBrush);
36
+ setPen(m_style.BorderPen);
37
+
38
+ // Measure text width and set the node width accordingly with small padding
39
+ QFontMetrics fontMetric(m_style.TxtFont);
40
+
41
+ m_nodeHeight = fontMetric.height() + 40;
42
+ m_nodeWidth = fontMetric.width(m_nodeTxt) + 20;
43
+
44
+ setFlag(QGraphicsItem::ItemIsSelectable);
45
+ setFlag(QGraphicsItem::ItemIsMovable);
46
+ setFlag(QGraphicsItem::ItemSendsGeometryChanges);
47
+
48
+ m_nodeToString = m_pNodeModel->ToString().c_str();
49
+ m_isGoal = BELONG(GoalType, m_pNodeModel->StepTypeId());
50
+
51
+ if (m_pNodeData != nullptr)
52
+ m_SatisfyingGoalId = m_pNodeData->SatisfyingGoal;
53
+
54
+ if (m_pNodeData == nullptr)
55
+ setToolTip(QString::fromLocal8Bit(m_pNodeModel->ToString().c_str()));
56
+ }
57
+ //----------------------------------------------------------------------------------------------
58
+ void GraphNodeView::AddEdge(GraphEdgeView* p_edge)
59
+ {
60
+ m_edges.append(p_edge);
61
+ }
62
+ //----------------------------------------------------------------------------------------------
63
+ void GraphNodeView::RemoveEdge(GraphEdgeView* p_edge)
64
+ {
65
+ QList<GraphEdgeView*>::iterator where = find(m_edges.begin(), m_edges.end(), p_edge);
66
+
67
+ if (where != m_edges.end())
68
+ m_edges.erase(where);
69
+ }
70
+ //----------------------------------------------------------------------------------------------
71
+ QList<GraphEdgeView*> GraphNodeView::Disconnect()
72
+ {
73
+ GraphNodeView *other = NULL;
74
+ QList<GraphEdgeView*> edges(m_edges);
75
+
76
+ foreach(GraphEdgeView* edge, edges)
77
+ {
78
+ if (edge->StartNode() != this)
79
+ other = edge->StartNode();
80
+ else
81
+ other = edge->EndNode();
82
+
83
+ other->RemoveEdge(edge);
84
+ this->RemoveEdge(edge);
85
+ }
86
+
87
+ return edges;
88
+ }
89
+ //----------------------------------------------------------------------------------------------
90
+ QVariant GraphNodeView::itemChange(GraphicsItemChange change,
91
+ const QVariant &value)
92
+ {
93
+ if (change == QGraphicsItem::ItemPositionChange)
94
+ {
95
+ foreach(GraphEdgeView *edge, m_edges)
96
+ {
97
+ edge->UpdatePosition();
98
+ }
99
+ }
100
+
101
+ return value;
102
+ }
103
+ //----------------------------------------------------------------------------------------------
104
+ void GraphNodeView::paint(QPainter *p_painter, const QStyleOptionGraphicsItem *p_option, QWidget *p_widget)
105
+ {
106
+ QGraphicsRectItem::paint(p_painter, p_option, p_widget);
107
+
108
+ m_style = GetStyle();
109
+
110
+ setBrush(m_style.BackgroundBrush);
111
+ setPen(m_style.BorderPen);
112
+
113
+ QTextOption textOption;
114
+ textOption.setAlignment(Qt::AlignCenter);
115
+
116
+ p_painter->setFont(m_style.TxtFont);
117
+ p_painter->setPen(m_style.TxtPen);
118
+
119
+ // Measure text width and set the node width accordingly with small padding
120
+ QFontMetrics fontMetric(m_style.TxtFont);
121
+
122
+ m_nodeHeight = fontMetric.height() + 20;
123
+ m_nodeWidth = fontMetric.width(m_nodeTxt) + 20;
124
+
125
+ // Call setRect ONLY in case the node dimensions changed, if it is called each paint
126
+ // it will cause infinite loop (and lead to stack overflow) because setRect always
127
+ // case the node to repaint
128
+ if (rect().width() != m_nodeWidth || rect().height() != m_nodeHeight)
129
+ setRect(0, 0, m_nodeWidth, m_nodeHeight);
130
+
131
+ setToolTip(QString::fromLocal8Bit(m_tooltipTxt));
132
+
133
+ p_painter->drawText(this->rect(), m_nodeTxt, textOption);
134
+ }
135
+ //----------------------------------------------------------------------------------------------
136
+ void GraphNodeView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
137
+ {
138
+ event->accept();
139
+ scene()->clearSelection();
140
+ setSelected(true);
141
+ if (m_pContextMenu != NULL)
142
+ m_pContextMenu->exec(event->screenPos());
143
+ }
144
+ //////////////////////////////////////////////////////////////////////////
145
+ GraphNodeView::NodeStyle GraphNodeView::GetStyle()
146
+ {
147
+ NodeStyle style;
148
+
149
+ Qt::GlobalColor bgBrushColor = Qt::white;
150
+ Qt::GlobalColor txtPenColor = Qt::black;
151
+ Qt::GlobalColor borderColor = Qt::black;
152
+ auto fillPattern = Qt::SolidPattern;
153
+
154
+ switch (m_state)
155
+ {
156
+ case ESTATE_Failed:
157
+ bgBrushColor = Qt::red;
158
+ break;
159
+ case ESTATE_Succeeded:
160
+ bgBrushColor = Qt::green;
161
+ break;
162
+ case ESTATE_NotPrepared:
163
+ if (m_isGoal)
164
+ {
165
+ if (!m_isOpen)
166
+ {
167
+ bgBrushColor = Qt::blue;
168
+ txtPenColor = Qt::white;
169
+ }
170
+ else
171
+ bgBrushColor = Qt::lightGray;
172
+ }
173
+ else
174
+ bgBrushColor = Qt::lightGray;
175
+ break;
176
+ case ESTATE_Pending:
177
+ bgBrushColor = Qt::yellow;
178
+ break;
179
+ case ESTATE_Executing:
180
+ bgBrushColor = Qt::blue;
181
+ txtPenColor = Qt::white;
182
+ break;
183
+ default:
184
+ bgBrushColor = Qt::white;
185
+ break;
186
+ }
187
+
188
+ style.BackgroundBrush = QBrush(bgBrushColor, fillPattern);
189
+ style.BorderPen = QPen(QColor(borderColor));
190
+ style.TxtPen = QPen(QColor(txtPenColor));
191
+
192
+ if (m_isGoal)
193
+ {
194
+ style.TxtFont.setBold(true);
195
+ style.TxtFont.setPixelSize(26);
196
+ style.BorderPen.setWidth(2);
197
+
198
+ if (m_isActive)
199
+ {
200
+ style.TxtFont.setItalic(true);
201
+ style.TxtFont.setUnderline(true);
202
+ }
203
+ }
204
+ else
205
+ {
206
+ style.TxtFont.setPixelSize(22);
207
+ style.BorderPen.setWidth(1);
208
+ }
209
+
210
+ return style;
211
+ }
212
+ //////////////////////////////////////////////////////////////////////////
213
+ void GraphNodeView::OnUpdate()
214
+ {
215
+ m_state = m_pNodeModel->GetState();
216
+
217
+ if (m_pNodeData != nullptr)
218
+ {
219
+ m_isOpen = m_pNodeData->IsOpen;
220
+
221
+ sprintf_s(m_tooltipTxt, "%s: O?%d, SG:%d, PC:%d, CC:%d",
222
+ m_nodeToString.c_str(),
223
+ m_pNodeData->IsOpen,
224
+ m_pNodeData->SatisfyingGoal,
225
+ m_pNodeData->WaitOnParentsCount,
226
+ m_pNodeData->WaitOnChildrenCount);
227
+ }
228
+ }
pool/shard006/C++/0078678_benchmarkudf.cc ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
+ * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
+ *
4
+ * Copyright (C) 2008 MySQL AB
5
+ *
6
+ * This program is free software; you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation; version 2 of the License.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+ #include <config.h>
21
+ #include <drizzled/error.h>
22
+ #include <drizzled/internal/m_string.h>
23
+ #include <drizzled/plugin/function.h>
24
+ #include <drizzled/session.h>
25
+
26
+ using namespace std;
27
+ using namespace drizzled;
28
+
29
+ class BenchmarkFunction :public Item_int_func
30
+ {
31
+ public:
32
+ BenchmarkFunction() :Item_int_func() {}
33
+ int64_t val_int();
34
+ virtual void print(String *str);
35
+
36
+ const char *func_name() const
37
+ {
38
+ return "benchmark";
39
+ }
40
+
41
+ void fix_length_and_dec()
42
+ {
43
+ max_length= 1;
44
+ maybe_null= false;
45
+ }
46
+
47
+ bool check_argument_count(int n)
48
+ {
49
+ return (n == 2);
50
+ }
51
+ };
52
+
53
+
54
+ /* This function is just used to test speed of different functions */
55
+ int64_t BenchmarkFunction::val_int()
56
+ {
57
+ assert(fixed == true);
58
+
59
+ char buff[MAX_FIELD_WIDTH];
60
+ String tmp(buff,sizeof(buff), &my_charset_bin);
61
+ type::Decimal tmp_decimal;
62
+ uint64_t loop_count;
63
+
64
+ loop_count= (uint64_t) args[0]->val_int();
65
+
66
+ if (args[0]->null_value ||
67
+ (args[0]->unsigned_flag == false && (((int64_t) loop_count) < 0)))
68
+ {
69
+ if (args[0]->null_value == false)
70
+ {
71
+ internal::int64_t10_to_str((int64_t)loop_count, buff, -10);
72
+ push_warning_printf(&getSession(), DRIZZLE_ERROR::WARN_LEVEL_ERROR,
73
+ ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
74
+ "count", buff, "benchmark");
75
+ }
76
+
77
+ null_value= true;
78
+ return 0;
79
+ }
80
+
81
+ null_value= false;
82
+
83
+ uint64_t loop;
84
+ for (loop= 0 ; loop < loop_count && not getSession().getKilled(); loop++)
85
+ {
86
+ switch (args[1]->result_type())
87
+ {
88
+ case REAL_RESULT:
89
+ (void) args[1]->val_real();
90
+ break;
91
+ case INT_RESULT:
92
+ (void) args[1]->val_int();
93
+ break;
94
+ case STRING_RESULT:
95
+ (void) args[1]->val_str(&tmp);
96
+ break;
97
+ case DECIMAL_RESULT:
98
+ (void) args[1]->val_decimal(&tmp_decimal);
99
+ break;
100
+ case ROW_RESULT:
101
+ default:
102
+ // This case should never be chosen
103
+ assert(0);
104
+ return 0;
105
+ }
106
+ }
107
+ return 0;
108
+ }
109
+
110
+ void BenchmarkFunction::print(String *str)
111
+ {
112
+ str->append(STRING_WITH_LEN("benchmark("));
113
+ args[0]->print(str);
114
+ str->append(',');
115
+ args[1]->print(str);
116
+ str->append(')');
117
+ }
118
+
119
+ plugin::Create_function<BenchmarkFunction> *benchmarkudf= NULL;
120
+
121
+ static int initialize(module::Context &context)
122
+ {
123
+ benchmarkudf= new plugin::Create_function<BenchmarkFunction>("benchmark");
124
+ context.add(benchmarkudf);
125
+ return 0;
126
+ }
127
+
128
+ DRIZZLE_DECLARE_PLUGIN
129
+ {
130
+ DRIZZLE_VERSION_ID,
131
+ "benchmark",
132
+ "1.0",
133
+ "Devananda van der Veen",
134
+ "Measure time for repeated calls to a function.",
135
+ PLUGIN_LICENSE_GPL,
136
+ initialize, /* Plugin Init */
137
+ NULL, /* depends */
138
+ NULL /* config options */
139
+ }
140
+ DRIZZLE_DECLARE_PLUGIN_END;
pool/shard006/C++/0078679_skinned_mesh.cpp ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <mesh_converter/mesh_converter.hpp>
2
+
3
+ #include <zombye/rendering/rendering_system.hpp>
4
+ #include <zombye/rendering/skinned_mesh.hpp>
5
+ #include <zombye/utils/logger.hpp>
6
+
7
+ #include <glm/gtx/string_cast.hpp>
8
+
9
+ namespace zombye {
10
+ skinned_mesh::skinned_mesh(rendering_system& rendering_system, const std::vector<char>& source, const std::string& file_name) noexcept
11
+ : vbo_{0, GL_STATIC_DRAW}, ibo_{0, GL_STATIC_DRAW}, parallax_mapping_{false} {
12
+ auto data_ptr = source.data();
13
+
14
+ auto head = *reinterpret_cast<const header*>(data_ptr);
15
+ if (head.magic != 0x31424D5A) {
16
+ throw std::runtime_error(file_name + " is not an zombye mesh file");
17
+ }
18
+
19
+ parallax_mapping_ = head.parallax_mapping;
20
+
21
+ auto vertex_size = head.vertex_count * sizeof(skinned_vertex);
22
+ auto index_size = head.index_count * sizeof(uint32_t);
23
+ auto size = sizeof(header)
24
+ + vertex_size
25
+ + index_size
26
+ + head.submesh_count * sizeof(devtools::submesh);
27
+
28
+ if (size != source.size()) {
29
+ throw std::runtime_error(file_name + " has not the apropriate size. expected size: "
30
+ + std::to_string(source.size()) + " calculated size: " + std::to_string(size));
31
+ }
32
+ data_ptr += sizeof(header);
33
+
34
+ vbo_.data(vertex_size, data_ptr);
35
+ data_ptr += vertex_size;
36
+
37
+ ibo_.data(index_size, data_ptr);
38
+ data_ptr += index_size;
39
+
40
+ for (auto i = 0; i < head.submesh_count; ++i) {
41
+ submesh s;
42
+
43
+ s.index_count = *reinterpret_cast<const uint64_t*>(data_ptr);
44
+ data_ptr += sizeof(uint64_t);
45
+ s.offset = *reinterpret_cast<const uint64_t*>(data_ptr);
46
+ data_ptr += sizeof(uint64_t);
47
+
48
+ auto texture_id = *reinterpret_cast<const uint64_t*>(data_ptr);
49
+ auto texture_name = std::to_string(texture_id) + ".dds";
50
+ s.diffuse = rendering_system.texture_manager().load("texture/" + texture_name);
51
+ if (!s.diffuse) {
52
+ throw std::runtime_error("could not load texure " + texture_name);
53
+ }
54
+ data_ptr += sizeof(uint64_t);
55
+
56
+ texture_id = *reinterpret_cast<const uint64_t*>(data_ptr);
57
+ texture_name = std::to_string(texture_id) + ".dds";
58
+ s.normal = rendering_system.texture_manager().load("texture/" + texture_name);
59
+ if (!s.normal) {
60
+ throw std::runtime_error("could not load texure " + texture_name);
61
+ }
62
+ data_ptr += sizeof(uint64_t);
63
+
64
+ texture_id = *reinterpret_cast<const uint64_t*>(data_ptr);
65
+ texture_name = std::to_string(texture_id) + ".dds";
66
+ s.material = rendering_system.texture_manager().load("texture/" + texture_name);
67
+ if (!s.material) {
68
+ throw std::runtime_error("could not load texure " + texture_name);
69
+ }
70
+ data_ptr += sizeof(uint64_t);
71
+
72
+ submeshes_.emplace_back(s);
73
+ }
74
+
75
+ vao_.bind_index_buffer(ibo_);
76
+ rendering_system.skinnedmesh_layout().setup_layout(vao_, &vbo_);
77
+ }
78
+
79
+ void skinned_mesh::draw() const noexcept {
80
+ vao_.bind();
81
+ for (auto& sub : submeshes_) {
82
+ sub.diffuse->bind(0);
83
+ sub.material->bind(1);
84
+ sub.normal->bind(2);
85
+ glDrawElements(GL_TRIANGLES, sub.index_count, GL_UNSIGNED_INT,
86
+ reinterpret_cast<void*>(sub.offset * sizeof(unsigned int)));
87
+ }
88
+ }
89
+ }
pool/shard006/C++/0078685_2.cc ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // 1999-05-11 bkoz
2
+
3
+ // Copyright (C) 1999, 2002, 2003 Free Software Foundation, Inc.
4
+ //
5
+ // This file is part of the GNU ISO C++ Library. This library is free
6
+ // software; you can redistribute it and/or modify it under the
7
+ // terms of the GNU General Public License as published by the
8
+ // Free Software Foundation; either version 2, or (at your option)
9
+ // any later version.
10
+
11
+ // This library is distributed in the hope that it will be useful,
12
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ // GNU General Public License for more details.
15
+
16
+ // You should have received a copy of the GNU General Public License along
17
+ // with this library; see the file COPYING. If not, write to the Free
18
+ // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19
+ // USA.
20
+
21
+ // 21.3.3 string capacity
22
+
23
+ #include <string>
24
+ #include <testsuite_hooks.h>
25
+
26
+ // libstdc++/4548
27
+ // http://gcc.gnu.org/ml/libstdc++/2001-11/msg00150.html
28
+ void test02()
29
+ {
30
+ bool test __attribute__((unused)) = true;
31
+
32
+ std::string str01 = "twelve chars";
33
+ // str01 becomes shared
34
+ std::string str02 = str01;
35
+ str01.reserve(1);
36
+ VERIFY( str01.capacity() == 12 );
37
+ }
38
+
39
+ int main()
40
+ {
41
+ test02();
42
+ return 0;
43
+ }
pool/shard006/C++/0078686_EvaluationMetrics.cpp ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0.
4
+ */
5
+
6
+ #include <aws/glue/model/EvaluationMetrics.h>
7
+ #include <aws/core/utils/json/JsonSerializer.h>
8
+
9
+ #include <utility>
10
+
11
+ using namespace Aws::Utils::Json;
12
+ using namespace Aws::Utils;
13
+
14
+ namespace Aws
15
+ {
16
+ namespace Glue
17
+ {
18
+ namespace Model
19
+ {
20
+
21
+ EvaluationMetrics::EvaluationMetrics() :
22
+ m_transformType(TransformType::NOT_SET),
23
+ m_transformTypeHasBeenSet(false),
24
+ m_findMatchesMetricsHasBeenSet(false)
25
+ {
26
+ }
27
+
28
+ EvaluationMetrics::EvaluationMetrics(JsonView jsonValue) :
29
+ m_transformType(TransformType::NOT_SET),
30
+ m_transformTypeHasBeenSet(false),
31
+ m_findMatchesMetricsHasBeenSet(false)
32
+ {
33
+ *this = jsonValue;
34
+ }
35
+
36
+ EvaluationMetrics& EvaluationMetrics::operator =(JsonView jsonValue)
37
+ {
38
+ if(jsonValue.ValueExists("TransformType"))
39
+ {
40
+ m_transformType = TransformTypeMapper::GetTransformTypeForName(jsonValue.GetString("TransformType"));
41
+
42
+ m_transformTypeHasBeenSet = true;
43
+ }
44
+
45
+ if(jsonValue.ValueExists("FindMatchesMetrics"))
46
+ {
47
+ m_findMatchesMetrics = jsonValue.GetObject("FindMatchesMetrics");
48
+
49
+ m_findMatchesMetricsHasBeenSet = true;
50
+ }
51
+
52
+ return *this;
53
+ }
54
+
55
+ JsonValue EvaluationMetrics::Jsonize() const
56
+ {
57
+ JsonValue payload;
58
+
59
+ if(m_transformTypeHasBeenSet)
60
+ {
61
+ payload.WithString("TransformType", TransformTypeMapper::GetNameForTransformType(m_transformType));
62
+ }
63
+
64
+ if(m_findMatchesMetricsHasBeenSet)
65
+ {
66
+ payload.WithObject("FindMatchesMetrics", m_findMatchesMetrics.Jsonize());
67
+
68
+ }
69
+
70
+ return payload;
71
+ }
72
+
73
+ } // namespace Model
74
+ } // namespace Glue
75
+ } // namespace Aws