Pendigard commited on
Commit
cde9b8e
·
verified ·
1 Parent(s): 3765ab6

Upload folder using huggingface_hub (part 22)

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/shard001/C++/0017002_rf24-ping.cpp +172 -0
  2. pool/shard001/C++/0017007_namedpipe_thread.cpp +244 -0
  3. pool/shard001/C++/0017013_modality-eval.cpp +46 -0
  4. pool/shard001/C++/0017014_cflow-hand.cc +22 -0
  5. pool/shard001/C++/0017018_gen_random.cc +66 -0
  6. pool/shard001/C++/0017019_op_+.pass.cpp +33 -0
  7. pool/shard001/C++/0017021_qwaylandglcontext.cpp +265 -0
  8. pool/shard001/C++/0017023_pathdat.cpp +78 -0
  9. pool/shard001/C++/0017033_SphericalScanlineTextureMapper.cpp +260 -0
  10. pool/shard001/C++/0017039_ui_resource_layer.cc +167 -0
  11. pool/shard001/C++/0017040_gunsms.cpp +75 -0
  12. pool/shard001/C++/0017050_copy-renderer.cpp +56 -0
  13. pool/shard001/C++/0017065_extension_gallery_install_apitest.cc +85 -0
  14. pool/shard001/C++/0017071_kastentoolviewwidget.cpp +82 -0
  15. pool/shard001/C++/0017072_vme.cc +192 -0
  16. pool/shard001/C++/0017076_jsonfile.cpp +260 -0
  17. pool/shard001/C++/0017084_object_rep.cpp +273 -0
  18. pool/shard001/C++/0017088_trajectory_builder_stub.cc +173 -0
  19. pool/shard001/C++/0017090_unnest-node.cc +173 -0
  20. pool/shard001/C++/0017105_dtb_object.cc +184 -0
  21. pool/shard001/C++/0017113_Claw.cpp +175 -0
  22. pool/shard001/C++/0017115_target_anim_ctrl.cpp +227 -0
  23. pool/shard001/C++/0017116_cellcolors.cpp +122 -0
  24. pool/shard001/C++/0017123_GrProcessor.cpp +143 -0
  25. pool/shard001/C++/0017143_binarycontourimagefilter.cpp +168 -0
  26. pool/shard001/C++/0017150_pow_valarray_value.pass.cpp +55 -0
  27. pool/shard001/C++/0017153_optimized_test.cpp +82 -0
  28. pool/shard001/C++/0017155_ir_function_detect_recursion.cpp +375 -0
  29. pool/shard001/C++/0017157_print_string.cpp +91 -0
  30. pool/shard001/C++/0017164_quic_sent_packet_manager_peer.cc +180 -0
  31. pool/shard001/C++/0017166_profile_window.cc +191 -0
  32. pool/shard001/C++/0017170_S3_wrap.cpp +42 -0
  33. pool/shard001/C++/0017182_shortcutsimpl.cpp +114 -0
  34. pool/shard001/C++/0017189_render_view_context_menu_unittest.cc +239 -0
  35. pool/shard001/C++/0017193_socket_util.cc +47 -0
  36. pool/shard001/C++/0017201_BPFTargetMachine.cpp +131 -0
  37. pool/shard001/C++/0017203_atom_menu_model.cc +65 -0
  38. pool/shard001/C++/0017205_isobarAmplitude_py.cc +118 -0
  39. pool/shard001/C++/0017208_subscriber_test.cc +159 -0
  40. pool/shard001/C++/0017218_vix_iniwriter.cpp +38 -0
  41. pool/shard001/C++/0017221_3.cpp +58 -0
  42. pool/shard001/C++/0017223_scrollbar_theme_overlay_mobile.cc +81 -0
  43. pool/shard001/C++/0017229_boss_shazzrah.cpp +148 -0
  44. pool/shard001/C++/0017230_base_run_loop.cc +81 -0
  45. pool/shard001/C++/0017243_publisherinfoservice.cpp +36 -0
  46. pool/shard001/C++/0017245_StringTokenizer.cpp +154 -0
  47. pool/shard001/C++/0017252_play_game.cpp +55 -0
  48. pool/shard001/C++/0017253_window_demo.cc +144 -0
  49. pool/shard001/C++/0017255_Shader.cpp +228 -0
  50. pool/shard001/C++/0017258_JSONVariantParser.cpp +227 -0
pool/shard001/C++/0017002_rf24-ping.cpp ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The MIT License (MIT)
2
+ *
3
+ * Copyright (c) 2016 Jean Gressmann <jean@0x42.de>
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in
13
+ * all copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ * THE SOFTWARE.
22
+ */
23
+
24
+ #include <sys/types.h>
25
+ #include <sys/stat.h>
26
+ #include <sys/socket.h>
27
+ #include <sys/un.h>
28
+ #include <unistd.h>
29
+ #include <errno.h>
30
+ #include <time.h>
31
+ #include <inttypes.h>
32
+ #include <assert.h>
33
+ #include <stdlib.h>
34
+ #include <errno.h>
35
+ #include <string.h>
36
+ #include <stdint.h>
37
+ #include <signal.h>
38
+ #include <toe/cmdlopt.h>
39
+ #include <linuxapi/linuxapi.h>
40
+
41
+ #include "Globals.h"
42
+
43
+ #define APPNAME "rf24-ping"
44
+
45
+ #define ERROR(...) fprintf(stderr, "ERROR: " __VA_ARGS__)
46
+ #define LOG(...) fprintf(stdout, __VA_ARGS__)
47
+
48
+ #if 0
49
+ # define DEBUG(...) fprintf(stderr, __VA_ARGS__)
50
+ #else
51
+ # define DEBUG(...)
52
+ #endif
53
+
54
+ template<typename T>
55
+ static
56
+ int
57
+ UnsignedParser(const char* arg, T& value) {
58
+ char* end = NULL;
59
+ value = (T)strtoul(arg, &end, 10);
60
+ if (!end || end == arg) {
61
+ ERROR("Argument '%s' could not be converted to unsigned int\n", arg);
62
+ return -1;
63
+ }
64
+
65
+ return 0;
66
+ }
67
+
68
+ static const cmdlopt_arg s_Dummy_Arg[] = {
69
+ CMDLOPT_ARGUMENT_TERMINATOR
70
+ };
71
+
72
+ static const char* s_RF24PacketRouterSocketPath = RF24_PACKET_ROUTER_SOCKET_PATH;
73
+ static
74
+ int
75
+ RF24PacketRouterSocketPath_Parser(void*, char* arg) {
76
+ s_RF24PacketRouterSocketPath = arg;
77
+ return 0;
78
+ }
79
+
80
+
81
+ static unsigned s_MillisecondsToSleep = 1000;
82
+ static
83
+ int
84
+ Sleep_Parser(void*, char* arg) {
85
+ return UnsignedParser(arg, s_MillisecondsToSleep);
86
+ }
87
+
88
+ static const cmdlopt_opt s_Options[] = {
89
+ { "rf24-packet-router-socket-path", "Path to UNIX socket. Defaults to " RF24_PACKET_ROUTER_SOCKET_PATH, 0, 0x100, s_Dummy_Arg, RF24PacketRouterSocketPath_Parser},
90
+ { "sleep", "Milliseconds to sleep between pings. Defaults to 1000", 's', 0x101, s_Dummy_Arg, Sleep_Parser},
91
+ CMDLOPT_COMMON_OPTIONS,
92
+ CMDLOPT_OPTION_TERMINATOR
93
+ };
94
+
95
+ int
96
+ main(int argc, char** argv) {
97
+ int socketFd = -1;
98
+ sockaddr_un sa;
99
+ char buffer[32];
100
+ uint32_t counter = 0;
101
+
102
+ cmdlopt_set_app_name(APPNAME);
103
+ cmdlopt_set_app_version("1.0\nCopyright (c) 2016 Jean Gressmann <jean@0x42.de>");
104
+ cmdlopt_set_options(s_Options);
105
+ int error = cmdlopt_parse_cmdl(argc, argv, NULL);
106
+
107
+ switch (error) {
108
+ case CMDLOPT_E_NONE:
109
+ break;
110
+ case CMDLOPT_E_HELP_REQUESTED:
111
+ case CMDLOPT_E_VERSION_REQUESTED:
112
+ error = 0;
113
+ goto Exit;
114
+ case CMDLOPT_E_UNKNOWN_OPTION:
115
+ cmdlopt_fprint_help(stderr);
116
+ goto Exit;
117
+ case CMDLOPT_E_ERRNO:
118
+ error = errno;
119
+ goto Exit;
120
+ case CMDLOPT_E_INVALID_PARAM:
121
+ fprintf(stderr, "Internal program error %d\n", error);
122
+ goto Exit;
123
+ default:
124
+ goto Exit;
125
+ }
126
+
127
+ if (!s_RF24PacketRouterSocketPath || !*s_RF24PacketRouterSocketPath) {
128
+ fprintf(stderr, "Empty Rf24 packet router UNIX socket path.\n");
129
+ error = -1;
130
+ goto Exit;
131
+ }
132
+
133
+ memset(&sa, 0, sizeof(sa));
134
+
135
+
136
+ socketFd = socket(AF_UNIX, SOCK_STREAM, 0);
137
+ if (socketFd == -1) {
138
+ ERROR("Failed to create socket\n");
139
+ error = errno;
140
+ goto Exit;
141
+ }
142
+
143
+ sa.sun_family = AF_UNIX;
144
+ strncpy(sa.sun_path, s_RF24PacketRouterSocketPath, sizeof(sa.sun_path) - 1);
145
+ if (connect(socketFd, (sockaddr*)&sa, sizeof(sa)) < 0) {
146
+ ERROR("Failed to connect to AF_UNIX socket %s\n", s_RF24PacketRouterSocketPath);
147
+ error = errno;
148
+ goto Exit;
149
+ }
150
+
151
+ error = 0;
152
+
153
+
154
+ while (1) {
155
+ snprintf(buffer, sizeof(buffer), "ping %u\n", counter++);
156
+ LOG(buffer);
157
+ write(socketFd, buffer, sizeof(buffer));
158
+ usleep(s_MillisecondsToSleep * 1000);
159
+ }
160
+
161
+ Exit:
162
+ if (socketFd >= 0) {
163
+ safe_close(socketFd);
164
+ }
165
+
166
+ if (error > 0) {
167
+ fprintf(stderr, "%s (%d)\n", strerror(error), error);
168
+ }
169
+ return error;
170
+ }
171
+
172
+
pool/shard001/C++/0017007_namedpipe_thread.cpp ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <Windows.h>
2
+ #include "namedpipe_thread.h"
3
+ #include "namedpipe.h"
4
+
5
+ //
6
+ // 数据包 定义
7
+ //
8
+ struct NamedPipe_Package : public package {
9
+ public:
10
+ bool head_readed;
11
+ DWORD byte_written;
12
+ };
13
+
14
+ NamedPipe_PackageHandler::NamedPipe_PackageHandler(NamedPipe* pipe)
15
+ : m_pipe(pipe) {
16
+ }
17
+
18
+ void NamedPipe_PackageHandler::set_namedpipe(NamedPipe* pipe) {
19
+ m_pipe = pipe;
20
+ }
21
+
22
+ NamedPipe* NamedPipe_PackageHandler::get_namedpipe() {
23
+ return m_pipe;
24
+ }
25
+
26
+ // 返回 -1:错误,返回0:成功发送,返回1:发送过程中
27
+ int NamedPipe_PackageHandler::read_package(package* pkg) {
28
+ assert(NULL != m_pipe);
29
+ if(NULL == pkg || NULL == m_pipe) {
30
+ return -1;
31
+ }
32
+
33
+ NamedPipe_Package* pThePkg = (NamedPipe_Package*)pkg;
34
+
35
+ // 读包头
36
+ if(!pThePkg->head_readed) {
37
+ DWORD dwBytes = 0;
38
+ if(!::PeekNamedPipe(m_pipe->handle(), NULL, 0, NULL, &dwBytes, NULL)) {
39
+ return -1;
40
+ }
41
+ if(sizeof(DWORD) * 3 > dwBytes) {
42
+ return 1;
43
+ }
44
+
45
+ m_pipe->read(&(pThePkg->cmd), sizeof(pThePkg->cmd));
46
+ m_pipe->read(&(pThePkg->flag), sizeof(pThePkg->flag));
47
+ m_pipe->read(&(pThePkg->size), sizeof(pThePkg->size));
48
+
49
+ delete pThePkg->data;
50
+ pThePkg->data = new char[(pThePkg->size / 16 + 1) * 16];
51
+
52
+ pThePkg->head_readed = true;
53
+ }
54
+
55
+ // 读包体
56
+ if(pThePkg->size > 0) {
57
+ DWORD dwBytes = 0;
58
+ if(!::PeekNamedPipe(m_pipe->handle(), NULL, 0, NULL, &dwBytes, NULL)) {
59
+ return -1;
60
+ }
61
+
62
+ if(dwBytes < pThePkg->size) {
63
+ return 1;
64
+ }
65
+
66
+ // 获取数据包体
67
+ if(pThePkg->size != m_pipe->read(pThePkg->data, DWORD(pThePkg->size))) {
68
+ return -1;
69
+ }
70
+ }
71
+
72
+ return 0;
73
+ }
74
+
75
+ int NamedPipe_PackageHandler::write_package(package* pkg) {
76
+ assert(NULL != m_pipe);
77
+ if(NULL == pkg || NULL == m_pipe) {
78
+ return -1;
79
+ }
80
+
81
+ NamedPipe_Package* pThePkg = (NamedPipe_Package*)pkg;
82
+
83
+ DWORD dwBuffer[3];
84
+ dwBuffer[0] = pThePkg->cmd;
85
+ dwBuffer[1] = pThePkg->flag;
86
+ dwBuffer[2] = DWORD(pThePkg->size);
87
+ if(sizeof(dwBuffer) != m_pipe->write(dwBuffer, sizeof(dwBuffer))) {
88
+ return -1;
89
+ }
90
+
91
+ if(pThePkg->size > 0) {
92
+ int nByteWritten = m_pipe->write((char*)(pThePkg->data) + pThePkg->byte_written, DWORD(pThePkg->size) - pThePkg->byte_written);
93
+ if(nByteWritten < 0) {
94
+ return -1;
95
+ }
96
+
97
+ pThePkg->byte_written += nByteWritten;
98
+ }
99
+
100
+ return (pThePkg->byte_written == pThePkg->size)?0:1;
101
+ }
102
+
103
+ package* NamedPipe_PackageHandler::create_package(int32_t cmd, const void* data, size_t size, uint32_t flag) {
104
+ NamedPipe_Package* pkg = new NamedPipe_Package;
105
+
106
+ pkg->cmd = cmd;
107
+ pkg->flag = flag;
108
+
109
+ pkg->byte_written = 0;
110
+ pkg->head_readed = false;
111
+
112
+ if(NULL != data && size > 0) {
113
+ pkg->data = new char[(size/16 + 1) * 16];
114
+ pkg->size = size;
115
+
116
+ memcpy(pkg->data, data, size);
117
+ } else {
118
+ pkg->data = NULL;
119
+ pkg->size = 0;
120
+ }
121
+
122
+ return pkg;
123
+ }
124
+
125
+ void NamedPipe_PackageHandler::destroy_package(package* pkg) {
126
+ if(NULL != pkg) {
127
+ delete pkg->data;
128
+ delete (NamedPipe_Package*)pkg;
129
+ }
130
+ }
131
+
132
+ // server reader impl.
133
+ class NamedPipe_ServerReader : public IO_ThreadReader {
134
+ public:
135
+ NamedPipe_ServerReader(NamedPipe_Server* server)
136
+ : m_client_connected(false)
137
+ , m_server(server) {
138
+ }
139
+
140
+ protected:
141
+ virtual void do_run() {
142
+ m_client_connected = false;
143
+ if(m_server->connect()) {
144
+ m_client_connected = true;
145
+
146
+ {
147
+ __super::do_run();
148
+ }
149
+
150
+ m_server->disconnect();
151
+ m_client_connected = false;
152
+ }
153
+ }
154
+
155
+ virtual bool do_stop(bool bKillOnTimeout, UINT uTimeout) {
156
+ if(is_running() && !m_client_connected) {
157
+ NamedPipe_Client client;
158
+ client.open(m_server->pipename());
159
+ client.close();
160
+ }
161
+
162
+ return IO_ThreadReader::do_stop(bKillOnTimeout, uTimeout);
163
+ }
164
+
165
+ private:
166
+ NamedPipe_Server* m_server;
167
+ volatile bool m_client_connected;
168
+ };
169
+
170
+ // server writer impl.
171
+ class NamedPipe_ServerWriter : public IO_ThreadWriter {
172
+ };
173
+
174
+ // client reader impl.
175
+ class NamedPipe_ClientReader : public IO_ThreadReader {
176
+ };
177
+
178
+ // client writer impl.
179
+ class NamedPipe_ClientWriter : public IO_ThreadWriter {
180
+ };
181
+
182
+ NamedPipe_ThreadServer::NamedPipe_ThreadServer() {
183
+ m_pkg_handler.set_namedpipe(&m_pipe);
184
+ this->set_reader(new NamedPipe_ServerReader(&m_pipe));
185
+ this->set_writer(new NamedPipe_ServerWriter());
186
+ this->set_package_handler(&m_pkg_handler);
187
+ }
188
+
189
+ bool NamedPipe_ThreadServer::start(const char* pipename, DWORD dwInBuffer, DWORD dwOutBuffer, SECURITY_ATTRIBUTES* pSecAttrs, DWORD* pErrCode) {
190
+ if(!m_pipe.open(pipename, dwInBuffer, dwOutBuffer, pSecAttrs, pErrCode)) {
191
+ return false;
192
+ }
193
+
194
+ return IO_ThreadWorker::start();
195
+ }
196
+
197
+ bool NamedPipe_ThreadServer::do_start() {
198
+ if(NULL == m_pipe.handle()) {
199
+ return false;
200
+ }
201
+
202
+ return IO_ThreadWorker::do_start();
203
+ }
204
+
205
+ bool NamedPipe_ThreadServer::do_stop(bool bKillOnTimeout, UINT uTimeout) {
206
+ bool ret = IO_ThreadWorker::do_stop(bKillOnTimeout, uTimeout);
207
+ m_pipe.close();
208
+ return ret;
209
+ }
210
+
211
+ NamedPipe_ThreadServer::~NamedPipe_ThreadServer() {
212
+ }
213
+
214
+ NamedPipe_ThreadClient::NamedPipe_ThreadClient() {
215
+ m_pkg_handler.set_namedpipe(&m_pipe);
216
+ this->set_reader(new NamedPipe_ClientReader());
217
+ this->set_writer(new NamedPipe_ClientWriter());
218
+ this->set_package_handler(&m_pkg_handler);
219
+ }
220
+
221
+ bool NamedPipe_ThreadClient::start(const char* pipename) {
222
+ if(!m_pipe.open(pipename)) {
223
+ return false;
224
+ }
225
+
226
+ return IO_ThreadWorker::start();
227
+ }
228
+
229
+ bool NamedPipe_ThreadClient::do_start() {
230
+ if(NULL == m_pipe.handle()) {
231
+ return false;
232
+ }
233
+
234
+ return IO_ThreadWorker::do_start();
235
+ }
236
+
237
+ bool NamedPipe_ThreadClient::do_stop(bool bKillOnTimeout, UINT uTimeout) {
238
+ bool ret = IO_ThreadWorker::do_stop(bKillOnTimeout, uTimeout);
239
+ m_pipe.close();
240
+ return ret;
241
+ }
242
+
243
+ NamedPipe_ThreadClient::~NamedPipe_ThreadClient() {
244
+ }
pool/shard001/C++/0017013_modality-eval.cpp ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <boost/program_options.hpp>
3
+ #include <boost/algorithm/string.hpp>
4
+ #include "eval.hpp"
5
+
6
+
7
+ int main(int argc, char *argv[]) {
8
+ boost::program_options::options_description opt("Usage");
9
+ opt.add_options()
10
+ ("help,h", "Show help messages")
11
+ ("version,v", "Show version informaion");
12
+
13
+ boost::program_options::variables_map argmap;
14
+ boost::program_options::store(parse_command_line(argc, argv, opt), argmap);
15
+ boost::program_options::notify(argmap);
16
+
17
+ evaluator _evaluator;
18
+
19
+ std::string buf;
20
+ while( getline(std::cin, buf) ) {
21
+ std::vector<std::string> l;
22
+ boost::algorithm::split(l, buf, boost::algorithm::is_any_of(","));
23
+
24
+ if (l.size() == 3) {
25
+ _evaluator.add( l[0], l[1], l[2] );
26
+ }
27
+ else {
28
+ std::cerr << "WARN: invalid format " << buf << std::endl;
29
+ }
30
+ }
31
+
32
+ _evaluator.eval();
33
+
34
+ std::cout << "* confusion matrix" << std::endl;
35
+ _evaluator.print_confusion_matrix();
36
+
37
+ std::cout << "* Precision and Recall" << std::endl;
38
+ _evaluator.print_prec_rec();
39
+
40
+ double acc = _evaluator.accuracy();
41
+ std::cout << "* Accuracy" << std::endl;
42
+ std::cout << acc << std::endl;
43
+
44
+ return true;
45
+ }
46
+
pool/shard001/C++/0017014_cflow-hand.cc ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (C) 2012 Gustav Munkby, Hamburg University of Technology (TUHH)
2
+ #define likely(x) __builtin_expect((x),1)
3
+ #define unlikely(x) __builtin_expect((x),0)
4
+ #include "handler.hh"
5
+ #include "protected_clone.hh"
6
+
7
+ int basic(int input)
8
+ {
9
+ static unsigned int block = 0;
10
+ int x = input;
11
+ if (likely(x <= 2))
12
+ {
13
+ if (unlikely(sihft::protected_clone(block) != 0))
14
+ sihft::fault_detected();
15
+ block = 1;
16
+ x += 1;
17
+ }
18
+ if (unlikely(sihft::protected_clone(block) > 1))
19
+ sihft::fault_detected();
20
+ block = 0;
21
+ return x;
22
+ }
pool/shard001/C++/0017018_gen_random.cc ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * This program generates random graphs for use by book-embedder.
3
+ *
4
+ * Program for minimizing the number of crossings in a book embedding of a given
5
+ * graph to a given number of pages.
6
+ *
7
+ * Author: Josef Cibulka
8
+ * License: see the file LICENSE
9
+ */
10
+
11
+ #include <ctime>
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+ #include <string>
15
+
16
+ #define MAXP 1000000
17
+ #define MAXN 1000000
18
+
19
+ const std::string usage =
20
+ "Exactly three arguments are required -- the number of the pages provided for the drawing, "
21
+ "the number of vertices of the graph and the probability, in percents, of each edge. "
22
+ "The edges are created independently.\n"
23
+ "E.g. a graph with 10 vertices and edge probability 20% (will have 9 vertices on average) "
24
+ "to be drawn in a book with 3 pages: \"gen_random 3 10 20\".\n";
25
+
26
+ void print_usage_and_exit()
27
+ {
28
+ fprintf(stderr, usage.c_str());
29
+ exit(0);
30
+ }
31
+
32
+ int main(int argc, char *argv[])
33
+ {
34
+ if (argc != 4)
35
+ print_usage_and_exit();
36
+
37
+ int p = -1;
38
+ p = atoi(argv[1]);
39
+ if (p <= 0 || p > MAXP)
40
+ print_usage_and_exit();
41
+
42
+ int n = -1;
43
+ n = atoi(argv[2]);
44
+ if (n <= 0 || n > MAXN)
45
+ print_usage_and_exit();
46
+
47
+ double prob = -1;
48
+ prob = atof(argv[3]);
49
+ if (prob <= 0.0 || prob > 100.0)
50
+ print_usage_and_exit();
51
+
52
+ printf("%d\n", n);
53
+ printf("%d\n", p);
54
+
55
+ int thr = prob * RAND_MAX / 100.0;
56
+
57
+ srand(time(nullptr));
58
+ for (int i = 0; i < n; i++)
59
+ printf("%d\n", i);
60
+
61
+ for (int i = 0; i < n; i++)
62
+ for (int j = i + 1; j < n; j++)
63
+ if (rand() < thr)
64
+ printf("%d %d [0]\n", i, j);
65
+ return 0;
66
+ }
pool/shard001/C++/0017019_op_+.pass.cpp ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // <chrono>
11
+
12
+ // duration
13
+
14
+ // duration operator+() const;
15
+
16
+ #include <chrono>
17
+ #include <cassert>
18
+
19
+ int main()
20
+ {
21
+ {
22
+ const std::chrono::minutes m(3);
23
+ std::chrono::minutes m2 = +m;
24
+ assert(m.count() == m2.count());
25
+ }
26
+ #ifndef _LIBCPP_HAS_NO_CONSTEXPR
27
+ {
28
+ constexpr std::chrono::minutes m(3);
29
+ constexpr std::chrono::minutes m2 = +m;
30
+ static_assert(m.count() == m2.count(), "");
31
+ }
32
+ #endif
33
+ }
pool/shard001/C++/0017021_qwaylandglcontext.cpp ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /****************************************************************************
2
+ **
3
+ ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4
+ ** Contact: http://www.qt-project.org/legal
5
+ **
6
+ ** This file is part of the plugins of the Qt Toolkit.
7
+ **
8
+ ** $QT_BEGIN_LICENSE:LGPL$
9
+ ** Commercial License Usage
10
+ ** Licensees holding valid commercial Qt licenses may use this file in
11
+ ** accordance with the commercial license agreement provided with the
12
+ ** Software or, alternatively, in accordance with the terms contained in
13
+ ** a written agreement between you and Digia. For licensing terms and
14
+ ** conditions see http://qt.digia.com/licensing. For further information
15
+ ** use the contact form at http://qt.digia.com/contact-us.
16
+ **
17
+ ** GNU Lesser General Public License Usage
18
+ ** Alternatively, this file may be used under the terms of the GNU Lesser
19
+ ** General Public License version 2.1 as published by the Free Software
20
+ ** Foundation and appearing in the file LICENSE.LGPL included in the
21
+ ** packaging of this file. Please review the following information to
22
+ ** ensure the GNU Lesser General Public License version 2.1 requirements
23
+ ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
+ **
25
+ ** In addition, as a special exception, Digia gives you certain additional
26
+ ** rights. These rights are described in the Digia Qt LGPL Exception
27
+ ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28
+ **
29
+ ** GNU General Public License Usage
30
+ ** Alternatively, this file may be used under the terms of the GNU
31
+ ** General Public License version 3.0 as published by the Free Software
32
+ ** Foundation and appearing in the file LICENSE.GPL included in the
33
+ ** packaging of this file. Please review the following information to
34
+ ** ensure the GNU General Public License version 3.0 requirements will be
35
+ ** met: http://www.gnu.org/copyleft/gpl.html.
36
+ **
37
+ **
38
+ ** $QT_END_LICENSE$
39
+ **
40
+ ****************************************************************************/
41
+
42
+ #include "qwaylandglcontext.h"
43
+
44
+ #include <QtWaylandClient/private/qwaylanddisplay_p.h>
45
+ #include <QtWaylandClient/private/qwaylandwindow_p.h>
46
+ #include <QtWaylandClient/private/qwaylanddecoration_p.h>
47
+ #include "qwaylandeglwindow.h"
48
+
49
+ #include <QDebug>
50
+ #include <QtPlatformSupport/private/qeglconvenience_p.h>
51
+ #include <QtGui/private/qopenglcontext_p.h>
52
+ #include <QtGui/private/qopengltexturecache_p.h>
53
+
54
+ #include <qpa/qplatformopenglcontext.h>
55
+ #include <QtGui/QSurfaceFormat>
56
+ #include <QtGui/QOpenGLShaderProgram>
57
+
58
+ QT_BEGIN_NAMESPACE
59
+
60
+ QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share)
61
+ : QPlatformOpenGLContext()
62
+ , m_eglDisplay(eglDisplay)
63
+ , m_config(q_configFromGLFormat(m_eglDisplay, format, true))
64
+ , m_format(q_glFormatFromConfig(m_eglDisplay, m_config))
65
+ , m_blitProgram(0)
66
+ , m_textureCache(0)
67
+ , mUseNativeDefaultFbo(false)
68
+ {
69
+ m_shareEGLContext = share ? static_cast<QWaylandGLContext *>(share)->eglContext() : EGL_NO_CONTEXT;
70
+
71
+ switch (m_format.renderableType()) {
72
+ case QSurfaceFormat::OpenVG:
73
+ eglBindAPI(EGL_OPENVG_API);
74
+ break;
75
+ #ifdef EGL_VERSION_1_4
76
+ # if !defined(QT_OPENGL_ES_2)
77
+ case QSurfaceFormat::DefaultRenderableType:
78
+ # endif
79
+ case QSurfaceFormat::OpenGL:
80
+ eglBindAPI(EGL_OPENGL_API);
81
+ break;
82
+ #endif
83
+ case QSurfaceFormat::OpenGLES:
84
+ default:
85
+ eglBindAPI(EGL_OPENGL_ES_API);
86
+ break;
87
+ }
88
+
89
+ QVector<EGLint> eglContextAttrs;
90
+ eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION);
91
+ eglContextAttrs.append(format.majorVersion() == 1 ? 1 : 2);
92
+ eglContextAttrs.append(EGL_NONE);
93
+
94
+ m_context = eglCreateContext(m_eglDisplay, m_config, m_shareEGLContext, eglContextAttrs.constData());
95
+
96
+ if (m_context == EGL_NO_CONTEXT) {
97
+ m_context = eglCreateContext(m_eglDisplay, m_config, EGL_NO_CONTEXT, eglContextAttrs.constData());
98
+ m_shareEGLContext = EGL_NO_CONTEXT;
99
+ }
100
+ }
101
+
102
+ QWaylandGLContext::~QWaylandGLContext()
103
+ {
104
+ delete m_blitProgram;
105
+ delete m_textureCache;
106
+ eglDestroyContext(m_eglDisplay, m_context);
107
+ }
108
+
109
+ bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface)
110
+ {
111
+ QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface);
112
+
113
+ window->setCanResize(false);
114
+
115
+ EGLSurface eglSurface = window->eglSurface();
116
+ if (!eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context)) {
117
+ qWarning("QEGLPlatformContext::makeCurrent: eglError: %x, this: %p \n", eglGetError(), this);
118
+ return false;
119
+ }
120
+
121
+ window->bindContentFBO();
122
+
123
+ return true;
124
+ }
125
+
126
+ void QWaylandGLContext::doneCurrent()
127
+ {
128
+ eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
129
+ }
130
+
131
+ void QWaylandGLContext::swapBuffers(QPlatformSurface *surface)
132
+ {
133
+ QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface);
134
+
135
+ EGLSurface eglSurface = window->eglSurface();
136
+
137
+ if (window->decoration()) {
138
+ makeCurrent(surface);
139
+ if (!m_blitProgram) {
140
+ initializeOpenGLFunctions();
141
+ m_blitProgram = new QOpenGLShaderProgram();
142
+ m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute vec4 position;\n\
143
+ attribute vec4 texCoords;\n\
144
+ varying vec2 outTexCoords;\n\
145
+ void main()\n\
146
+ {\n\
147
+ gl_Position = position;\n\
148
+ outTexCoords = texCoords.xy;\n\
149
+ }");
150
+ m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, "varying highp vec2 outTexCoords;\n\
151
+ uniform sampler2D texture;\n\
152
+ void main()\n\
153
+ {\n\
154
+ gl_FragColor = texture2D(texture, outTexCoords);\n\
155
+ }");
156
+
157
+ if (!m_blitProgram->link()) {
158
+ qDebug() << "Shader Program link failed.";
159
+ qDebug() << m_blitProgram->log();
160
+ }
161
+ }
162
+
163
+ if (!m_textureCache) {
164
+ m_textureCache = new QOpenGLTextureCache(this->context());
165
+ }
166
+
167
+ QRect windowRect = window->window()->frameGeometry();
168
+ glViewport(0, 0, windowRect.width(), windowRect.height());
169
+
170
+ glDisable(GL_DEPTH_TEST);
171
+ glDisable(GL_BLEND);
172
+ mUseNativeDefaultFbo = true;
173
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
174
+ mUseNativeDefaultFbo = false;
175
+
176
+ static const GLfloat squareVertices[] = {
177
+ -1.f, -1.f,
178
+ 1.0f, -1.f,
179
+ -1.f, 1.0f,
180
+ 1.0f, 1.0f
181
+ };
182
+
183
+ static const GLfloat inverseSquareVertices[] = {
184
+ -1.f, 1.f,
185
+ 1.f, 1.f,
186
+ -1.f, -1.f,
187
+ 1.f, -1.f
188
+ };
189
+
190
+ static const GLfloat textureVertices[] = {
191
+ 0.0f, 0.0f,
192
+ 1.0f, 0.0f,
193
+ 0.0f, 1.0f,
194
+ 1.0f, 1.0f,
195
+ };
196
+
197
+ m_blitProgram->bind();
198
+
199
+ m_blitProgram->setUniformValue("texture", 0);
200
+
201
+ m_blitProgram->enableAttributeArray("position");
202
+ m_blitProgram->enableAttributeArray("texCoords");
203
+ m_blitProgram->setAttributeArray("texCoords", textureVertices, 2);
204
+
205
+ glActiveTexture(GL_TEXTURE0);
206
+
207
+ //Draw Decoration
208
+ m_blitProgram->setAttributeArray("position", inverseSquareVertices, 2);
209
+ QImage decorationImage = window->decoration()->contentImage();
210
+ m_textureCache->bindTexture(context(), decorationImage);
211
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
212
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
213
+ if (!context()->functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat)) {
214
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
215
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
216
+ }
217
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
218
+
219
+ //Draw Content
220
+ m_blitProgram->setAttributeArray("position", squareVertices, 2);
221
+ glBindTexture(GL_TEXTURE_2D, window->contentTexture());
222
+ QRect r = window->contentsRect();
223
+ glViewport(r.x(), r.y(), r.width(), r.height());
224
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
225
+
226
+ //Cleanup
227
+ m_blitProgram->disableAttributeArray("position");
228
+ m_blitProgram->disableAttributeArray("texCoords");
229
+ m_blitProgram->release();
230
+ }
231
+
232
+ eglSwapBuffers(m_eglDisplay, eglSurface);
233
+
234
+ window->setCanResize(true);
235
+ }
236
+
237
+ GLuint QWaylandGLContext::defaultFramebufferObject(QPlatformSurface *surface) const
238
+ {
239
+ if (mUseNativeDefaultFbo)
240
+ return 0;
241
+
242
+ return static_cast<QWaylandEglWindow *>(surface)->contentFBO();
243
+ }
244
+
245
+ bool QWaylandGLContext::isSharing() const
246
+ {
247
+ return m_shareEGLContext != EGL_NO_CONTEXT;
248
+ }
249
+
250
+ bool QWaylandGLContext::isValid() const
251
+ {
252
+ return m_context != EGL_NO_CONTEXT;
253
+ }
254
+
255
+ void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) ()
256
+ {
257
+ return eglGetProcAddress(procName.constData());
258
+ }
259
+
260
+ EGLConfig QWaylandGLContext::eglConfig() const
261
+ {
262
+ return m_config;
263
+ }
264
+
265
+ QT_END_NAMESPACE
pool/shard001/C++/0017023_pathdat.cpp ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ctdl.h"
2
+ #pragma hdrstop
3
+
4
+ #include "auxtab.h"
5
+ #include "pathdat.h"
6
+ #include "msg.h"
7
+ #include "extmsg.h"
8
+
9
+ void CreatePathDat(void)
10
+ {
11
+ #ifndef WINCIT
12
+ #ifndef AUXMEM
13
+ #ifndef REGULAR
14
+ Message *Msg = new Message;
15
+
16
+ if (Msg)
17
+ {
18
+ FILE *fl;
19
+
20
+ mPrintfCR(getsysmsg(266));
21
+
22
+ char fullPathToPathDat[128];
23
+ sprintf(fullPathToPathDat, sbs, cfg.homepath, getsysmsg(8));
24
+
25
+ if ((fl = fopen(fullPathToPathDat, FO_W)) != NULL)
26
+ {
27
+ for (m_index mcnt = cfg.OldestMsgTab; mcnt <= cfg.NewestMsg; mcnt++)
28
+ {
29
+ long loc = MsgTab.GetLocation(mcnt);
30
+ int i, j;
31
+ label lastlocID;
32
+
33
+ Msg->ReadHeader(RMC_NORMAL, NULL, loc, NULL);
34
+
35
+ if (*Msg->GetFromPath())
36
+ {
37
+ fprintf(fl, pcts, Msg->GetFromPath());
38
+
39
+ // Get last locID, this stuff probably not necessary
40
+ for (i = strlen(Msg->GetFromPath()); i && Msg->GetFromPath()[i] != '.'; i--);
41
+
42
+ for (j = 0, i++; Msg->GetFromPath()[i] && Msg->GetFromPath()[i] != '!' && j < 4; i++, j++)
43
+ {
44
+ lastlocID[j] = Msg->GetFromPath()[i];
45
+ }
46
+ lastlocID[j] = 0;
47
+
48
+ /* if last locID was same as current locID just use alias */
49
+ if (SameString(lastlocID, cfg.locID))
50
+ {
51
+ fprintf(fl, getmsg(2), cfg.alias);
52
+ }
53
+ else
54
+ {
55
+ fprintf(fl, getmsg(2), cfg.Address);
56
+ }
57
+
58
+ fprintf(fl, bn);
59
+ }
60
+ }
61
+
62
+ fclose(fl);
63
+ }
64
+ else
65
+ {
66
+ mPrintf(getmsg(78), fullPathToPathDat);
67
+ }
68
+
69
+ delete Msg;
70
+ }
71
+ else
72
+ {
73
+ OutOfMemory(90);
74
+ }
75
+ #endif
76
+ #endif
77
+ #endif
78
+ }
pool/shard001/C++/0017033_SphericalScanlineTextureMapper.cpp ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // This file is part of the Marble Virtual Globe.
3
+ //
4
+ // This program is free software licensed under the GNU LGPL. You can
5
+ // find a copy of this license in LICENSE.txt in the top directory of
6
+ // the source code.
7
+ //
8
+ // Copyright 2007 Torsten Rahn <tackat@kde.org>
9
+ // Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
10
+ //
11
+
12
+
13
+ #include "SphericalScanlineTextureMapper.h"
14
+
15
+ #include <cmath>
16
+
17
+ #include <QtCore/QRunnable>
18
+
19
+ #include "MarbleGlobal.h"
20
+ #include "GeoPainter.h"
21
+ #include "GeoDataPolygon.h"
22
+ #include "GeoDataDocument.h"
23
+ #include "MarbleDebug.h"
24
+ #include "Quaternion.h"
25
+ #include "ScanlineTextureMapperContext.h"
26
+ #include "StackedTileLoader.h"
27
+ #include "StackedTile.h"
28
+ #include "TextureColorizer.h"
29
+ #include "ViewportParams.h"
30
+ #include "MathHelper.h"
31
+
32
+
33
+ using namespace Marble;
34
+
35
+ class SphericalScanlineTextureMapper::RenderJob : public QRunnable
36
+ {
37
+ public:
38
+ RenderJob( StackedTileLoader *tileLoader, int tileLevel, QImage *canvasImage, const ViewportParams *viewport, MapQuality mapQuality, int yTop, int yBottom );
39
+
40
+ virtual void run();
41
+
42
+ private:
43
+ StackedTileLoader *const m_tileLoader;
44
+ const int m_tileLevel;
45
+ QImage *const m_canvasImage;
46
+ const ViewportParams *const m_viewport;
47
+ const MapQuality m_mapQuality;
48
+ int const m_yTop;
49
+ int const m_yBottom;
50
+ };
51
+
52
+ SphericalScanlineTextureMapper::RenderJob::RenderJob( StackedTileLoader *tileLoader, int tileLevel, QImage *canvasImage, const ViewportParams *viewport, MapQuality mapQuality, int yTop, int yBottom )
53
+ : m_tileLoader( tileLoader ),
54
+ m_tileLevel( tileLevel ),
55
+ m_canvasImage( canvasImage ),
56
+ m_viewport( viewport ),
57
+ m_mapQuality( mapQuality ),
58
+ m_yTop( yTop ),
59
+ m_yBottom( yBottom )
60
+ {
61
+ }
62
+
63
+ QRect SphericalScanlineTextureMapper::rect( const ViewportParams *viewport ) const
64
+ {
65
+ const int radius = viewport->radius();
66
+
67
+ return QRect( viewport->width() / 2 - radius, viewport->height() / 2 - radius,
68
+ 2 * radius, 2 * radius);
69
+ }
70
+
71
+ void SphericalScanlineTextureMapper::mapTexture( QImage *canvasImage, StackedTileLoader *tileLoader, const ViewportParams *viewport, int tileZoomLevel, MapQuality mapQuality )
72
+ {
73
+ // Reset backend
74
+ tileLoader->resetTilehash();
75
+
76
+ // Initialize needed constants:
77
+
78
+ const int imageHeight = canvasImage->height();
79
+ const qint64 radius = viewport->radius();
80
+
81
+ // Calculate the actual y-range of the map on the screen
82
+ const int skip = ( mapQuality == LowQuality ) ? 1
83
+ : 0;
84
+ const int yTop = ( imageHeight / 2 - radius >= 0 ) ? imageHeight / 2 - radius
85
+ : 0;
86
+ const int yBottom = ( yTop == 0 ) ? imageHeight - skip
87
+ : yTop + radius + radius - skip;
88
+
89
+ const int numThreads = m_threadPool.maxThreadCount();
90
+ const int yStep = ( yBottom - yTop ) / numThreads;
91
+ for ( int i = 0; i < numThreads; ++i ) {
92
+ const int yStart = yTop + i * yStep;
93
+ const int yEnd = yTop + (i + 1) * yStep;
94
+ QRunnable *const job = new RenderJob( tileLoader, tileZoomLevel, canvasImage, viewport, mapQuality, yStart, yEnd );
95
+ m_threadPool.start( job );
96
+ }
97
+
98
+ m_threadPool.waitForDone();
99
+
100
+ tileLoader->cleanupTilehash();
101
+ }
102
+
103
+ void SphericalScanlineTextureMapper::RenderJob::run()
104
+ {
105
+ const int imageHeight = m_canvasImage->height();
106
+ const int imageWidth = m_canvasImage->width();
107
+ const qint64 radius = m_viewport->radius();
108
+ const qreal inverseRadius = 1.0 / (qreal)(radius);
109
+
110
+ const bool interlaced = ( m_mapQuality == LowQuality );
111
+ const bool highQuality = ( m_mapQuality == HighQuality
112
+ || m_mapQuality == PrintQuality );
113
+ const bool printQuality = ( m_mapQuality == PrintQuality );
114
+
115
+ // Evaluate the degree of interpolation
116
+ const int n = ScanlineTextureMapperContext::interpolationStep( m_viewport, m_mapQuality );
117
+
118
+ // Calculate north pole position to decrease pole distortion later on
119
+ Quaternion northPole = Quaternion::fromSpherical( 0.0, M_PI * 0.5 );
120
+ northPole.rotateAroundAxis( m_viewport->planetAxis().inverse() );
121
+ const int northPoleX = imageWidth / 2 + (int)( radius * northPole.v[Q_X] );
122
+ const int northPoleY = imageHeight / 2 - (int)( radius * northPole.v[Q_Y] );
123
+
124
+ // Calculate axis matrix to represent the planet's rotation.
125
+ matrix planetAxisMatrix;
126
+ m_viewport->planetAxis().toMatrix( planetAxisMatrix );
127
+
128
+ // initialize needed variables that are modified during texture mapping:
129
+
130
+ ScanlineTextureMapperContext context( m_tileLoader, m_tileLevel );
131
+ qreal lon = 0.0;
132
+ qreal lat = 0.0;
133
+
134
+ // Scanline based algorithm to texture map a sphere
135
+ for ( int y = m_yTop; y < m_yBottom ; ++y ) {
136
+
137
+ // Evaluate coordinates for the 3D position vector of the current pixel
138
+ const qreal qy = inverseRadius * (qreal)( imageHeight / 2 - y );
139
+ const qreal qr = 1.0 - qy * qy;
140
+
141
+ // rx is the radius component in x direction
142
+ const int rx = (int)sqrt( (qreal)( radius * radius
143
+ - ( ( y - imageHeight / 2 )
144
+ * ( y - imageHeight / 2 ) ) ) );
145
+
146
+ // Calculate the actual x-range of the map within the current scanline.
147
+ //
148
+ // If the circular border of the earth disk is still visible then xLeft
149
+ // equals the scanline position of the most left pixel that gets covered
150
+ // by the earth disk. In terms of math this equals the half image width minus
151
+ // the radius component on the current scanline in x direction ("rx").
152
+ //
153
+ // If the zoom factor is high enough then the whole screen gets covered
154
+ // by the earth and the border of the earth disk isn't visible anymore.
155
+ // In that situation xLeft equals zero.
156
+ // For xRight the situation is similar.
157
+
158
+ const int xLeft = ( imageWidth / 2 - rx > 0 ) ? imageWidth / 2 - rx
159
+ : 0;
160
+ const int xRight = ( imageWidth / 2 - rx > 0 ) ? xLeft + rx + rx
161
+ : imageWidth;
162
+
163
+ QRgb * scanLine = (QRgb*)( m_canvasImage->scanLine( y ) ) + xLeft;
164
+
165
+ const int xIpLeft = ( imageWidth / 2 - rx > 0 ) ? n * (int)( xLeft / n + 1 )
166
+ : 1;
167
+ const int xIpRight = ( imageWidth / 2 - rx > 0 ) ? n * (int)( xRight / n - 1 )
168
+ : n * (int)( xRight / n - 1 ) + 1;
169
+
170
+ // Decrease pole distortion due to linear approximation ( y-axis )
171
+ bool crossingPoleArea = false;
172
+ if ( northPole.v[Q_Z] > 0
173
+ && northPoleY - ( n * 0.75 ) <= y
174
+ && northPoleY + ( n * 0.75 ) >= y )
175
+ {
176
+ crossingPoleArea = true;
177
+ }
178
+
179
+ int ncount = 0;
180
+
181
+ for ( int x = xLeft; x < xRight; ++x ) {
182
+ // Prepare for interpolation
183
+
184
+ const int leftInterval = xIpLeft + ncount * n;
185
+
186
+ bool interpolate = false;
187
+ if ( x >= xIpLeft && x <= xIpRight ) {
188
+
189
+ // Decrease pole distortion due to linear approximation ( x-axis )
190
+ // mDebug() << QString("NorthPole X: %1, LeftInterval: %2").arg( northPoleX ).arg( leftInterval );
191
+ if ( crossingPoleArea
192
+ && northPoleX >= leftInterval + n
193
+ && northPoleX < leftInterval + 2 * n
194
+ && x < leftInterval + 3 * n )
195
+ {
196
+ interpolate = false;
197
+ }
198
+ else {
199
+ x += n - 1;
200
+ interpolate = !printQuality;
201
+ ++ncount;
202
+ }
203
+ }
204
+ else
205
+ interpolate = false;
206
+
207
+ // Evaluate more coordinates for the 3D position vector of
208
+ // the current pixel.
209
+ const qreal qx = (qreal)( x - imageWidth / 2 ) * inverseRadius;
210
+ const qreal qr2z = qr - qx * qx;
211
+ const qreal qz = ( qr2z > 0.0 ) ? sqrt( qr2z ) : 0.0;
212
+
213
+ // Create Quaternion from vector coordinates and rotate it
214
+ // around globe axis
215
+ Quaternion qpos( 0.0, qx, qy, qz );
216
+ qpos.rotateAroundAxis( planetAxisMatrix );
217
+
218
+ qpos.getSpherical( lon, lat );
219
+ // mDebug() << QString("lon: %1 lat: %2").arg(lon).arg(lat);
220
+ // Approx for n-1 out of n pixels within the boundary of
221
+ // xIpLeft to xIpRight
222
+
223
+ if ( interpolate ) {
224
+ if (highQuality)
225
+ context.pixelValueApproxF( lon, lat, scanLine, n );
226
+ else
227
+ context.pixelValueApprox( lon, lat, scanLine, n );
228
+
229
+ scanLine += ( n - 1 );
230
+ }
231
+
232
+ // Comment out the pixelValue line and run Marble if you want
233
+ // to understand the interpolation:
234
+
235
+ // Uncomment the crossingPoleArea line to check precise
236
+ // rendering around north pole:
237
+
238
+ // if ( !crossingPoleArea )
239
+ if ( x < imageWidth ) {
240
+ if ( highQuality )
241
+ context.pixelValueF( lon, lat, scanLine );
242
+ else
243
+ context.pixelValue( lon, lat, scanLine );
244
+ }
245
+
246
+ ++scanLine;
247
+ }
248
+
249
+ // copy scanline to improve performance
250
+ if ( interlaced && y + 1 < m_yBottom ) {
251
+
252
+ const int pixelByteSize = m_canvasImage->bytesPerLine() / imageWidth;
253
+
254
+ memcpy( m_canvasImage->scanLine( y + 1 ) + xLeft * pixelByteSize,
255
+ m_canvasImage->scanLine( y ) + xLeft * pixelByteSize,
256
+ ( xRight - xLeft ) * pixelByteSize );
257
+ ++y;
258
+ }
259
+ }
260
+ }
pool/shard001/C++/0017039_ui_resource_layer.cc ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 "cc/layers/ui_resource_layer.h"
6
+
7
+ #include "cc/layers/ui_resource_layer_impl.h"
8
+ #include "cc/resources/prioritized_resource.h"
9
+ #include "cc/resources/resource_update.h"
10
+ #include "cc/resources/resource_update_queue.h"
11
+ #include "cc/resources/scoped_ui_resource.h"
12
+ #include "cc/resources/ui_resource_bitmap.h"
13
+ #include "cc/trees/layer_tree_host.h"
14
+
15
+ namespace cc {
16
+
17
+
18
+ namespace {
19
+
20
+ class ScopedUIResourceHolder : public UIResourceLayer::UIResourceHolder {
21
+ public:
22
+ static scoped_ptr<ScopedUIResourceHolder> Create(LayerTreeHost* host,
23
+ const SkBitmap& skbitmap) {
24
+ return make_scoped_ptr(new ScopedUIResourceHolder(host, skbitmap));
25
+ }
26
+ virtual UIResourceId id() OVERRIDE { return resource_->id(); }
27
+
28
+ private:
29
+ ScopedUIResourceHolder(LayerTreeHost* host, const SkBitmap& skbitmap) {
30
+ resource_ = ScopedUIResource::Create(host, UIResourceBitmap(skbitmap));
31
+ }
32
+
33
+ scoped_ptr<ScopedUIResource> resource_;
34
+ };
35
+
36
+ class SharedUIResourceHolder : public UIResourceLayer::UIResourceHolder {
37
+ public:
38
+ static scoped_ptr<SharedUIResourceHolder> Create(UIResourceId id) {
39
+ return make_scoped_ptr(new SharedUIResourceHolder(id));
40
+ }
41
+
42
+ virtual UIResourceId id() OVERRIDE { return id_; }
43
+
44
+ private:
45
+ explicit SharedUIResourceHolder(UIResourceId id) : id_(id) {}
46
+
47
+ UIResourceId id_;
48
+ };
49
+
50
+ } // anonymous namespace
51
+
52
+ UIResourceLayer::UIResourceHolder::~UIResourceHolder() {}
53
+
54
+ scoped_refptr<UIResourceLayer> UIResourceLayer::Create() {
55
+ return make_scoped_refptr(new UIResourceLayer());
56
+ }
57
+
58
+ UIResourceLayer::UIResourceLayer()
59
+ : Layer(),
60
+ uv_top_left_(0.f, 0.f),
61
+ uv_bottom_right_(1.f, 1.f) {
62
+ vertex_opacity_[0] = 1.0f;
63
+ vertex_opacity_[1] = 1.0f;
64
+ vertex_opacity_[2] = 1.0f;
65
+ vertex_opacity_[3] = 1.0f;
66
+ }
67
+
68
+ UIResourceLayer::~UIResourceLayer() {}
69
+
70
+ scoped_ptr<LayerImpl> UIResourceLayer::CreateLayerImpl(
71
+ LayerTreeImpl* tree_impl) {
72
+ return UIResourceLayerImpl::Create(tree_impl, id()).PassAs<LayerImpl>();
73
+ }
74
+
75
+ void UIResourceLayer::SetUV(const gfx::PointF& top_left,
76
+ const gfx::PointF& bottom_right) {
77
+ if (uv_top_left_ == top_left && uv_bottom_right_ == bottom_right)
78
+ return;
79
+ uv_top_left_ = top_left;
80
+ uv_bottom_right_ = bottom_right;
81
+ SetNeedsCommit();
82
+ }
83
+
84
+ void UIResourceLayer::SetVertexOpacity(float bottom_left,
85
+ float top_left,
86
+ float top_right,
87
+ float bottom_right) {
88
+ // Indexing according to the quad vertex generation:
89
+ // 1--2
90
+ // | |
91
+ // 0--3
92
+ if (vertex_opacity_[0] == bottom_left &&
93
+ vertex_opacity_[1] == top_left &&
94
+ vertex_opacity_[2] == top_right &&
95
+ vertex_opacity_[3] == bottom_right)
96
+ return;
97
+ vertex_opacity_[0] = bottom_left;
98
+ vertex_opacity_[1] = top_left;
99
+ vertex_opacity_[2] = top_right;
100
+ vertex_opacity_[3] = bottom_right;
101
+ SetNeedsCommit();
102
+ }
103
+
104
+ void UIResourceLayer::SetLayerTreeHost(LayerTreeHost* host) {
105
+ if (host == layer_tree_host())
106
+ return;
107
+
108
+ Layer::SetLayerTreeHost(host);
109
+
110
+ // Recreate the resource hold against the new LTH.
111
+ RecreateUIResourceHolder();
112
+ }
113
+
114
+ void UIResourceLayer::RecreateUIResourceHolder() {
115
+ ui_resource_holder_.reset();
116
+ if (layer_tree_host() && !bitmap_.empty()) {
117
+ ui_resource_holder_ =
118
+ ScopedUIResourceHolder::Create(layer_tree_host(), bitmap_);
119
+ }
120
+ UpdateDrawsContent(HasDrawableContent());
121
+ }
122
+
123
+ void UIResourceLayer::SetBitmap(const SkBitmap& skbitmap) {
124
+ bitmap_ = skbitmap;
125
+
126
+ RecreateUIResourceHolder();
127
+ SetNeedsCommit();
128
+ }
129
+
130
+ void UIResourceLayer::SetUIResourceId(UIResourceId resource_id) {
131
+ if (ui_resource_holder_ && ui_resource_holder_->id() == resource_id)
132
+ return;
133
+
134
+ if (resource_id) {
135
+ ui_resource_holder_ = SharedUIResourceHolder::Create(resource_id);
136
+ } else {
137
+ ui_resource_holder_.reset();
138
+ }
139
+
140
+ UpdateDrawsContent(HasDrawableContent());
141
+ SetNeedsCommit();
142
+ }
143
+
144
+ bool UIResourceLayer::HasDrawableContent() const {
145
+ return ui_resource_holder_ && ui_resource_holder_->id() &&
146
+ Layer::HasDrawableContent();
147
+ }
148
+
149
+ void UIResourceLayer::PushPropertiesTo(LayerImpl* layer) {
150
+ Layer::PushPropertiesTo(layer);
151
+ UIResourceLayerImpl* layer_impl = static_cast<UIResourceLayerImpl*>(layer);
152
+
153
+ if (!ui_resource_holder_) {
154
+ layer_impl->SetUIResourceId(0);
155
+ } else {
156
+ DCHECK(layer_tree_host());
157
+
158
+ gfx::Size image_size =
159
+ layer_tree_host()->GetUIResourceSize(ui_resource_holder_->id());
160
+ layer_impl->SetUIResourceId(ui_resource_holder_->id());
161
+ layer_impl->SetImageBounds(image_size);
162
+ layer_impl->SetUV(uv_top_left_, uv_bottom_right_);
163
+ layer_impl->SetVertexOpacity(vertex_opacity_);
164
+ }
165
+ }
166
+
167
+ } // namespace cc
pool/shard001/C++/0017040_gunsms.cpp ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "stdhdr.h"
2
+ #include "SmsDraw.h"
3
+ #include "fcc.h"
4
+ #include "guns.h"
5
+ #include "Graphics\Include\display.h"
6
+ #include "hardpnt.h"
7
+ #include "simveh.h"
8
+ #include "Sms.h"
9
+ #include "aircrft.h"
10
+ #include "simdrive.h"
11
+
12
+ void SmsDrawable::GunDisplay (void)
13
+ {
14
+ char tmpStr[12];
15
+ int station, numRounds;
16
+ FireControlComputer *FCC = Sms->ownship->GetFCC();
17
+
18
+ // JPO - moved a lot of it into these two routines.
19
+ TopRow(0);
20
+ BottomRow();
21
+
22
+ //MI
23
+ if(g_bRealisticAvionics && FCC && FCC->GetSubMode() ==
24
+ FireControlComputer::EEGS)
25
+ {
26
+ char tempstr[4] = "";
27
+ sprintf(tempstr,"%s", Sms->FEDS == TRUE ? "ON" : "OFF");
28
+ LabelButton (19, "SCOR", tempstr);
29
+ }
30
+ else if(g_bRealisticAvionics)
31
+ LabelButton(19,"");
32
+ else
33
+ LabelButton (19, "SCOR", "OFF");
34
+
35
+ if (Sms->ownship)
36
+ {
37
+ if (FCC->GetMasterMode() == FireControlComputer::Dogfight)
38
+ station = 0;
39
+ else
40
+ station = Sms->curHardpoint;
41
+
42
+ GunClass *gun = Sms->GetGun(station);
43
+ if (gun)
44
+ numRounds = gun->numRoundsRemaining / 10;
45
+ else
46
+ numRounds = 0;
47
+ }
48
+ else
49
+ numRounds = 0;
50
+
51
+ //MI I think this should only show RDY when we are in ARM, like all the other weapons
52
+ if (numRounds)
53
+ {
54
+ if(!g_bRealisticAvionics)
55
+ {
56
+
57
+ sprintf (tmpStr, "%02dGUN", numRounds);
58
+ display->TextCenter (0.3F, 0.6F, "RDY");
59
+ }
60
+ else
61
+ {
62
+ float x,y = 0;
63
+ GetButtonPos(5, &x, &y); //button for Gun
64
+ sprintf (tmpStr, "%02dGUN", numRounds);
65
+ if(Sms->MasterArm() == SMSBaseClass::Arm)
66
+ display->TextCenter (0.3F, y, "RDY");
67
+ else if(Sms->MasterArm() == SMSBaseClass::Sim)
68
+ display->TextCenter (0.3F, y, "SIM");
69
+ }
70
+ }
71
+ else
72
+ sprintf (tmpStr, "00GUN");
73
+
74
+ LabelButton (5, tmpStr);
75
+ }
pool/shard001/C++/0017050_copy-renderer.cpp ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright © 2012 Linaro Limited
3
+ *
4
+ * This file is part of the glmark2 OpenGL (ES) 2.0 benchmark.
5
+ *
6
+ * glmark2 is free software: you can redistribute it and/or modify it under the
7
+ * terms of the GNU General Public License as published by the Free Software
8
+ * Foundation, either version 3 of the License, or (at your option) any later
9
+ * version.
10
+ *
11
+ * glmark2 is distributed in the hope that it will be useful, but WITHOUT ANY
12
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
+ * details.
15
+ *
16
+ * You should have received a copy of the GNU General Public License along with
17
+ * glmark2. If not, see <http://www.gnu.org/licenses/>.
18
+ *
19
+ * Authors:
20
+ * Alexandros Frantzis
21
+ */
22
+ #include "options.h"
23
+ #include "scene.h"
24
+ #include "renderer.h"
25
+ #include "shader-source.h"
26
+
27
+ CopyRenderer::CopyRenderer(const LibMatrix::vec2 &size) :
28
+ TextureRenderer(size, *copy_program(true))
29
+ {
30
+ copy_program_ = copy_program(false);
31
+ }
32
+
33
+ Program *
34
+ CopyRenderer::copy_program(bool create_new)
35
+ {
36
+ static Program *copy_program(0);
37
+ if (create_new)
38
+ copy_program = 0;
39
+
40
+ if (!copy_program) {
41
+ copy_program = new Program();
42
+ ShaderSource vtx_shader(Options::data_path + "/shaders/terrain-texture.vert");
43
+ ShaderSource frg_shader(Options::data_path + "/shaders/terrain-overlay.frag");
44
+
45
+ Scene::load_shaders_from_strings(*copy_program, vtx_shader.str(), frg_shader.str());
46
+
47
+ copy_program->start();
48
+ (*copy_program)["tDiffuse"] = 0;
49
+ (*copy_program)["opacity"] = 1.0f;
50
+ (*copy_program)["uvOffset"] = LibMatrix::vec2(0.0f, 0.0f);
51
+ (*copy_program)["uvScale"] = LibMatrix::vec2(1.0f, 1.0f);
52
+ copy_program->stop();
53
+ }
54
+
55
+ return copy_program;
56
+ }
pool/shard001/C++/0017065_extension_gallery_install_apitest.cc ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2011 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 "base/stringprintf.h"
6
+ #if defined (OS_WIN)
7
+ #include "base/win/windows_version.h"
8
+ #endif // defined (OS_WIN)
9
+
10
+ #include "chrome/browser/extensions/extension_apitest.h"
11
+ #include "chrome/browser/extensions/extension_webstore_private_api.h"
12
+ #include "chrome/common/chrome_switches.h"
13
+ #include "chrome/test/ui_test_utils.h"
14
+ #include "net/base/mock_host_resolver.h"
15
+
16
+ class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
17
+ public:
18
+ void SetUpCommandLine(CommandLine* command_line) {
19
+ ExtensionApiTest::SetUpCommandLine(command_line);
20
+ command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
21
+ "http://www.example.com");
22
+ }
23
+
24
+ bool RunInstallTest(const std::string& page) {
25
+ std::string base_url = base::StringPrintf(
26
+ "http://www.example.com:%u/files/extensions/",
27
+ test_server()->host_port_pair().port());
28
+
29
+ std::string testing_install_base_url = base_url;
30
+ testing_install_base_url += "good.crx";
31
+
32
+ CommandLine::ForCurrentProcess()->AppendSwitchASCII(
33
+ switches::kAppsGalleryUpdateURL, testing_install_base_url);
34
+
35
+ std::string page_url = base_url;
36
+ page_url += "api_test/extension_gallery_install/" + page;
37
+
38
+ return RunPageTest(page_url.c_str());
39
+ }
40
+ };
41
+
42
+ namespace {
43
+
44
+ bool RunningOnXP() {
45
+ #if defined (OS_WIN)
46
+ return GetVersion() < base::win::VERSION_VISTA;
47
+ #else
48
+ return false;
49
+ #endif // defined (OS_WIN)
50
+ }
51
+
52
+ } // namespace
53
+
54
+ // TODO(asargent) - for some reason this test occasionally fails on XP,
55
+ // but not other versions of windows. http://crbug.com/55642
56
+ #if defined (OS_WIN)
57
+ #define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall
58
+ #else
59
+ #define MAYBE_InstallAndUninstall InstallAndUninstall
60
+ #endif
61
+ IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
62
+ MAYBE_InstallAndUninstall) {
63
+ if (RunningOnXP()) {
64
+ LOG(INFO) << "Adding host resolver rule";
65
+ }
66
+ host_resolver()->AddRule("www.example.com", "127.0.0.1");
67
+ if (RunningOnXP()) {
68
+ LOG(INFO) << "Starting test server";
69
+ }
70
+ ASSERT_TRUE(test_server()->Start());
71
+
72
+ if (RunningOnXP()) {
73
+ LOG(INFO) << "Starting tests without user gesture checking";
74
+ }
75
+ BeginInstallFunction::SetIgnoreUserGestureForTests(true);
76
+ ASSERT_TRUE(RunInstallTest("test.html"));
77
+ ASSERT_TRUE(RunInstallTest("complete_without_begin.html"));
78
+ ASSERT_TRUE(RunInstallTest("invalid_begin.html"));
79
+
80
+ if (RunningOnXP()) {
81
+ LOG(INFO) << "Starting tests with user gesture checking";
82
+ }
83
+ BeginInstallFunction::SetIgnoreUserGestureForTests(false);
84
+ ASSERT_TRUE(RunInstallTest("no_user_gesture.html"));
85
+ }
pool/shard001/C++/0017071_kastentoolviewwidget.cpp ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file is part of the KDevelop Okteta module, part of the KDE project.
3
+
4
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
5
+
6
+ This library is free software; you can redistribute it and/or
7
+ modify it under the terms of the GNU Lesser General Public
8
+ License as published by the Free Software Foundation; either
9
+ version 2.1 of the License, or (at your option) version 3, or any
10
+ later version accepted by the membership of KDE e.V. (or its
11
+ successor approved by the membership of KDE e.V.), which shall
12
+ act as a proxy defined in Section 6 of version 3 of the license.
13
+
14
+ This library 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 GNU
17
+ Lesser General Public License for more details.
18
+
19
+ You should have received a copy of the GNU Lesser General Public
20
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
21
+ */
22
+
23
+ #include "kastentoolviewwidget.h"
24
+
25
+ // plugin
26
+ #include "oktetaview.h"
27
+ // Okteta Kasten
28
+ #include "kasten/okteta/bytearrayview.h"
29
+ // Kasten
30
+ #include <Kasten/AbstractToolView>
31
+ #include <Kasten/AbstractTool>
32
+ // KDev
33
+ #include <interfaces/icore.h>
34
+ #include <interfaces/iuicontroller.h>
35
+ #include <sublime/mainwindow.h>
36
+ #include <sublime/controller.h>
37
+ // Qt
38
+ #include <QVBoxLayout>
39
+
40
+ namespace KDevelop
41
+ {
42
+
43
+ // TODO: find if hiddden, than unset target model
44
+ KastenToolViewWidget::KastenToolViewWidget( Kasten::AbstractToolView* toolView, QWidget* parent )
45
+ : QWidget( parent ),
46
+ mToolView( toolView )
47
+ {
48
+ Sublime::Controller* controller = ICore::self()->uiController()->controller();
49
+ connect( controller, &Sublime::Controller::mainWindowAdded,
50
+ this, &KastenToolViewWidget::onMainWindowAdded );
51
+ const QList<Sublime::MainWindow*>& mainWindows = controller->mainWindows();
52
+ foreach( Sublime::MainWindow* mainWindow, mainWindows )
53
+ onMainWindowAdded( mainWindow );
54
+
55
+ QVBoxLayout* layout = new QVBoxLayout( this );
56
+ layout->setMargin( 0 );
57
+ layout->addWidget( mToolView->widget() );
58
+ }
59
+
60
+ void KastenToolViewWidget::onMainWindowAdded( Sublime::MainWindow* mainWindow )
61
+ {
62
+ connect( mainWindow, &Sublime::MainWindow::activeViewChanged,
63
+ this, &KastenToolViewWidget::onActiveViewChanged );
64
+ onActiveViewChanged( mainWindow->activeView() );
65
+ }
66
+
67
+ void KastenToolViewWidget::onActiveViewChanged( Sublime::View* view )
68
+ {
69
+ // TODO: check if own mainWindow
70
+ OktetaView* oktetaView = qobject_cast<OktetaView*>( view );
71
+ Kasten::ByteArrayView* byteArrayView = oktetaView ? oktetaView->byteArrayView() : 0;
72
+ mToolView->tool()->setTargetModel( byteArrayView );
73
+ }
74
+
75
+ KastenToolViewWidget::~KastenToolViewWidget()
76
+ {
77
+ Kasten::AbstractTool* tool = mToolView->tool();
78
+ delete mToolView;
79
+ delete tool;
80
+ }
81
+
82
+ }
pool/shard001/C++/0017072_vme.cc ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "equipmentList_common.hh"
2
+ #include "globals.h"
3
+ #include "vme.h"
4
+ #include "maroc.h"
5
+
6
+ extern int32_t BHandle;
7
+ extern int addr_conn_out;
8
+
9
+ void InitVme()
10
+ {
11
+ fprintf(stdout,"\n-----------------\nInit VME\n---\n");
12
+ std::cout << "addr_conn_out: " << addr_conn_out << std::endl;
13
+ CVBoardTypes VMEBoard;
14
+ short Link;
15
+ short Device;
16
+
17
+ // Initialize the Board
18
+ VMEBoard = cvV2718;
19
+ Link = 0;
20
+ Device = 0;
21
+ if( CAENVME_Init(VMEBoard, Link, Device, &BHandle) != cvSuccess ) {
22
+ printf("\n\n Error opening the device\n");
23
+ exit(1); }
24
+ else fprintf(stdout,"---\nVME initialised\n-----------------\n");
25
+ }
26
+
27
+ /* Routine to read from VME bus (24 bit addr and 16 bit data) */
28
+ unsigned short read_vme(int *data, int address)
29
+ {
30
+ /*
31
+ unsigned short value_16;
32
+ int read_size;
33
+ if (lseek(ifile_map,(off_t)address,SEEK_SET)==-1) {
34
+ perror("read_vme lseek(): ");
35
+ exit(EXIT_FAILURE);
36
+ }
37
+ if ((read_size=read(ifile_map,(void*)(&value_16),2))==-1) {
38
+ perror("read_vme read(): ");
39
+ exit(EXIT_FAILURE);
40
+ }
41
+ *data_ptr = value_16;
42
+ */
43
+ CVErrorCodes ret;
44
+ ret = CAENVME_ReadCycle(BHandle,(uint32_t)address,data,cvA24_U_DATA,cvD16);
45
+ if (ret==cvSuccess) ;//printf(" Cycle(s) completed normally\n");
46
+ else if (ret==cvBusError){ printf(" Bus Error !!!"); return(1);}
47
+ else if (ret==cvCommError){ printf(" Communication Error !!!"); return(1);}
48
+ else{ printf(" Unknown Error !!!"); return(1);}
49
+ return(0);
50
+ }
51
+
52
+ /* Routine to write on VME bus (24 bit addr and 16 bit data) */
53
+ unsigned short write_vme(int data, int address)
54
+ {
55
+ /*
56
+ unsigned short value_16=data;
57
+ int written_size;
58
+ if (lseek(ifile_map,(off_t)address,SEEK_SET)==-1) {
59
+ perror("write_vme lseek(): ");
60
+ exit(EXIT_FAILURE);
61
+ }
62
+ if ((written_size=write(ifile_map,&value_16,2))==-1) {
63
+ perror("write_vme write(): ");
64
+ exit(EXIT_FAILURE);
65
+ }
66
+ */
67
+ CVErrorCodes ret;
68
+ ret = CAENVME_WriteCycle(BHandle,(uint32_t)address,&data,cvA24_U_DATA,cvD16);
69
+ if (ret==cvSuccess) ;//printf(" Cycle(s) completed normally\n");
70
+ else if (ret==cvBusError){ printf(" Bus Error !!!"); return(1);}
71
+ else if (ret==cvCommError){ printf(" Communication Error !!!"); return(1);}
72
+ else{ printf(" Unknown Error !!!"); return(1);}
73
+ return(0);
74
+ }
75
+
76
+ /* Clear one bit */
77
+ void clear_bit(int *dataptr, int mode_bit)
78
+ {
79
+ *dataptr = *dataptr & (~(1<<mode_bit));
80
+ }
81
+
82
+ /* Set one bit */
83
+ void set_bit(int *dataptr, int mode_bit)
84
+ {
85
+ *dataptr = *dataptr | (1<<mode_bit);
86
+ }
87
+
88
+ void clock_bus_pulse()
89
+ {
90
+ int local_reg;
91
+ read_vme(&local_reg,addr_conn_out);
92
+ clear_bit(&local_reg,0);
93
+ write_vme(local_reg,addr_conn_out);
94
+ set_bit(&local_reg,0);
95
+ write_vme(local_reg,addr_conn_out);
96
+ clear_bit(&local_reg,0);
97
+ write_vme(local_reg,addr_conn_out);
98
+ }
99
+
100
+ void regin_up()
101
+ {
102
+ unsigned short mask;
103
+ int bit_reg;
104
+ int outreg_data;
105
+ bit_reg = 5;
106
+ read_vme(&outreg_data,addr_conn_out);
107
+ mask = 0x1 << bit_reg;
108
+ outreg_data = outreg_data | mask;
109
+ write_vme(outreg_data,addr_conn_out);
110
+ write_vme(outreg_data,addr_conn_out);
111
+ write_vme(outreg_data,addr_conn_out);
112
+ }
113
+
114
+ void regin_down()
115
+ {
116
+ unsigned short mask;
117
+ int bit_reg;
118
+ int outreg_data;
119
+ bit_reg = 5;
120
+ read_vme(&outreg_data,addr_conn_out);
121
+ mask = ~(0x1 << bit_reg);
122
+ outreg_data = outreg_data & mask;
123
+ write_vme(outreg_data,addr_conn_out);
124
+ write_vme(outreg_data,addr_conn_out);
125
+ write_vme(outreg_data,addr_conn_out);
126
+ }
127
+
128
+ void clkreg_clk()
129
+ {
130
+ unsigned short mask;
131
+ int bit_reg;
132
+ int outreg_data;
133
+ bit_reg = 4;
134
+ read_vme(&outreg_data,addr_conn_out);
135
+ mask = 0x1 << bit_reg;
136
+ outreg_data = outreg_data | mask;
137
+ write_vme(outreg_data,addr_conn_out);
138
+ write_vme(outreg_data,addr_conn_out);
139
+ write_vme(outreg_data,addr_conn_out);
140
+ mask = ~(0x1 << bit_reg);
141
+ outreg_data = outreg_data & mask;
142
+ write_vme(outreg_data,addr_conn_out);
143
+ write_vme(outreg_data,addr_conn_out);
144
+ write_vme(outreg_data,addr_conn_out);
145
+ }
146
+
147
+ void send_on_bus_mus(int febid, int address, int data)
148
+ {
149
+ int local_reg;
150
+ int ibit;
151
+ int xbit;
152
+ int local_addr;
153
+
154
+ local_addr = address | ((febid & 0xf) << 8);
155
+
156
+ read_vme(&local_reg,addr_conn_out);
157
+ clear_bit(&local_reg,1);
158
+ write_vme(local_reg,addr_conn_out);
159
+ set_bit(&local_reg,1);
160
+ write_vme(local_reg,addr_conn_out);
161
+ set_bit(&local_reg,2);
162
+ write_vme(local_reg,addr_conn_out);
163
+ clock_bus_pulse();
164
+ clock_bus_pulse();
165
+ for (ibit=0; ibit<16; ibit++) {
166
+ xbit = (local_addr >> (15-ibit)) & 0x1;
167
+ if (xbit==1) {
168
+ set_bit(&local_reg,2);
169
+ write_vme(local_reg,addr_conn_out);
170
+ } else {
171
+ clear_bit(&local_reg,2);
172
+ write_vme(local_reg,addr_conn_out);
173
+ }
174
+ clock_bus_pulse();
175
+ }
176
+ for (ibit=0; ibit<16; ibit++) {
177
+ xbit = (data >> (15-ibit)) & 0x1;
178
+ if (xbit==1) {
179
+ set_bit(&local_reg,2);
180
+ write_vme(local_reg,addr_conn_out);
181
+ } else {
182
+ clear_bit(&local_reg,2);
183
+ write_vme(local_reg,addr_conn_out);
184
+ }
185
+ clock_bus_pulse();
186
+ }
187
+ clear_bit(&local_reg,1);
188
+ write_vme(local_reg,addr_conn_out);
189
+ clock_bus_pulse();
190
+ }
191
+
192
+
pool/shard001/C++/0017076_jsonfile.cpp ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file is part of WebTooth-Extractor and for personal use the
3
+ GPL3 license applies. For any kind of commercial usage, you have to
4
+ acquire a commercial license before use. The copyright of the WebTooth
5
+ application and source code remains with Patrick Scheller and any
6
+ contributor to the project agrees with his commits to renounce to the
7
+ copyright of his parts completely.
8
+
9
+ WebTooth-Extractor 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.
12
+
13
+ WebTooth-Extractor is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with WebTooth-Extractor. If not, see http://www.gnu.org/licenses/ .
20
+ */
21
+
22
+ #include <QJsonObject>
23
+ #include <QJsonArray>
24
+ #include <QJsonDocument>
25
+ #include <QJsonParseError>
26
+ #include <QtDebug>
27
+ #include <QDir>
28
+ #include <QListWidgetItem>
29
+ #include <QDateTime>
30
+
31
+ #include <qtpropertymanager.h>
32
+ #include <qttreepropertybrowser.h>
33
+
34
+
35
+ #include "jsonfile.h"
36
+
37
+ JSONFile::JSONFile(QObject *parent) : QObject(parent)
38
+ {
39
+
40
+ }
41
+
42
+ JSONFile::~JSONFile()
43
+ {
44
+
45
+ }
46
+
47
+ bool JSONFile::readJsonFile(t_filterdata& filterlist, QHash<QString, QString>& projectdata, const QString &prjfilepath)
48
+ {
49
+ bool bRes = false;
50
+
51
+ QJsonParseError jerror;
52
+ QFile projFile(prjfilepath);
53
+ if (!projFile.exists())
54
+ {
55
+ qDebug() << "Error: File" << prjfilepath << "does not exist!";
56
+ return(bRes);
57
+ }
58
+ else
59
+ {
60
+ //qDebug() << "File" << prjfilepath << "exists";
61
+ }
62
+ QJsonDocument jdoc;
63
+ if (projFile.open(QIODevice::ReadOnly | QIODevice::Text))
64
+ {
65
+ //qDebug() << "JSON-File could be opened";
66
+ jdoc = QJsonDocument::fromJson(projFile.readAll(),&jerror);
67
+ if(jerror.error != QJsonParseError::NoError)
68
+ {
69
+ qDebug() << "ERROR-JSON-Read:" << jerror.errorString() << "at position:" << jerror.offset;
70
+ projFile.close();
71
+ return (bRes);
72
+ }
73
+ else
74
+ {
75
+ //qDebug() << "QJsonDocument::fromJson() succeeded";
76
+ }
77
+ }
78
+ else
79
+ {
80
+ qDebug() << "ERROR-JSON: File could not be opened";
81
+ projFile.close();
82
+ return(bRes);
83
+ }
84
+ QJsonObject rootObj = jdoc.object();
85
+ projFile.close();
86
+
87
+ //QHashIterator<QString, QString> itPrjData(projectdata);
88
+ projectdata.insert("projectapp", "WebTooth-Extractor");
89
+ projectdata.insert("projectname", rootObj["projectname"].toString());
90
+ projectdata.insert("projectauthor", rootObj["projectauthor"].toString());
91
+ projectdata.insert("projectmodified", rootObj["projectmodified"].toString());
92
+ projectdata.insert("cropthumb", rootObj["cropthumb"].toString());
93
+ projectdata.insert("projecnotes", rootObj["projecnotes"].toString());
94
+ projectdata.insert("projecturl", rootObj["projecturl"].toString());
95
+ projectdata.insert("thumbheight", rootObj["thumbheight"].toString());
96
+ projectdata.insert("thumbwidth", rootObj["thumbwidth"].toString());
97
+
98
+ // typedef QHash<QString, QVector<QString>*> t_filterdata;
99
+ QJsonArray filters = rootObj["projectdata"].toArray();
100
+ qDebug() << "No. of filters found in the project file:" << filters.size();
101
+ int ideb = 0; // For Debug purpose
102
+ for(auto&& filterItem: filters)
103
+ {
104
+ //qDebug() << "XXX - filterItem";
105
+ const QJsonObject& filter = filterItem.toObject();
106
+ //filterlist.insert("filtername", new QVector<QString>(){filter["filtername"].toString()} );
107
+ //filterlist.insert("filtertype", new QVector<QString>(){filter["filtertype"].toString()} );
108
+
109
+ QJsonArray arrProperties = filter["filterdata"].toArray();
110
+ QVector<QString>* vattrlist= new QVector<QString>();
111
+ for (auto&& item: arrProperties)
112
+ {
113
+ const QJsonObject& attrProp = item.toObject();
114
+ if (filter["filtertype"].toString() == "tag")
115
+ {
116
+ //qDebug() << "Filtertype:" << filter["filtertype"].toString();
117
+ // qDebug() << " > Filter-Sizes:" << attrProp["H Tag Name"].toString().size() << "," << attrProp["H ID Name"].toString().size() << "," << attrProp["H Class Name"].toString().size()
118
+ // << "," << attrProp["P Tag Name"].toString().size() << "," << attrProp["P Attribute Name"].toString().size() << "," << attrProp["P ID Name"].toString().size()
119
+ // << "," << attrProp["P Class Name"].toString().size();
120
+ vattrlist->push_back(filter["filtertype"].toString());
121
+ vattrlist->push_back(attrProp["H Tag Name"].toString());
122
+ vattrlist->push_back(attrProp["H Attribute Name"].toString());
123
+ vattrlist->push_back(attrProp["H ID Name"].toString());
124
+ vattrlist->push_back(attrProp["H Class Name"].toString());
125
+ vattrlist->push_back(attrProp["P Tag Name"].toString());
126
+ vattrlist->push_back(attrProp["P Attribute Name"].toString());
127
+ vattrlist->push_back(attrProp["P ID Name"].toString());
128
+ vattrlist->push_back(attrProp["P Class Name"].toString());
129
+ vattrlist->push_back(attrProp["Occurrence Amount"].toString());
130
+ vattrlist->push_back(attrProp["Occurrence Function"].toString());
131
+ }
132
+ else if (filter["filtertype"].toString() == "reg")
133
+ {
134
+ //qDebug() << "XXX - RegExpr";
135
+ vattrlist->push_back(filter["filtertype"].toString());
136
+ vattrlist->push_back(attrProp["Regular Expression"].toString());
137
+ }
138
+ }
139
+ qDebug() << "vattrList contains no. of elements:" << vattrlist->size();
140
+ filterlist.insert(filter["filtername"].toString(), vattrlist);
141
+ //qDebug() << "YYY - End of JSON-Read";
142
+ bRes = true;
143
+ ideb++;
144
+ }
145
+ qDebug() << "iDeb count of loops:" << ideb;
146
+ qDebug() << "No. of elements in Filterlist:" << filterlist.size();
147
+ return(bRes);
148
+ }
149
+
150
+ bool JSONFile::writeJsonFile(const t_filterdata& filterlist, const QHash<QString, QString>& projectdata, const QString &prjfilepath)
151
+ {
152
+ qDebug() << "Entering writeJsonFile";
153
+ bool bRes = false;
154
+ QDir dir;
155
+ qDebug() << "Current Path: " << dir.currentPath() << flush;
156
+ //QFileInfo myfileInfo;
157
+ QFile projFile(prjfilepath);
158
+ if (!projFile.open(QIODevice::WriteOnly | QIODevice::Text))
159
+ {
160
+ qWarning("Couldn't open the project file.");
161
+ return(bRes);
162
+ }
163
+
164
+ // *******************************
165
+ QJsonObject rootObj;//root object
166
+ QHashIterator<QString, QString> itPrjData(projectdata);
167
+ while (itPrjData.hasNext())
168
+ {
169
+ itPrjData.next();
170
+ // if (itPrjData.key() == "projectauthor")
171
+ // qDebug() << "ProjectAuthor will be written to JSON:" << itPrjData.value();
172
+ rootObj[itPrjData.key()] = itPrjData.value();
173
+ }
174
+ //rootObj["projectapp"] = "WebTooth-Extractor";
175
+ //rootObj["projectname"] = "usertest";
176
+ //rootObj["projectauthor"] = "Lunix Sdlavrot";
177
+ //QDateTime now = QDateTime::currentDateTime();
178
+ //rootObj["projectmodified"] = now.toString(Qt::ISODate);
179
+
180
+ QJsonArray filters;
181
+ auto itFList = filterlist.constBegin();
182
+ while (itFList != filterlist.constEnd())
183
+ {
184
+ QJsonObject filter;
185
+ filter["filtername"] = itFList.key();
186
+ auto myvec = itFList.value();
187
+ filter["filtertype"] = myvec->at(0);
188
+
189
+ QJsonArray arrProperties;
190
+ QJsonObject objProperties;
191
+ if (myvec->at(0) == "tag")
192
+ {
193
+ objProperties["H Tag Name"] = myvec->at(1);
194
+ objProperties["H Attribute Name"] = myvec->at(2);
195
+ objProperties["H ID Name"] = myvec->at(3);
196
+ objProperties["H Class Name"] = myvec->at(4);
197
+
198
+ objProperties["P Tag Name"] = myvec->at(5);
199
+ objProperties["P Attribute Name"] = myvec->at(6);
200
+ objProperties["P ID Name"] = myvec->at(7);
201
+ objProperties["P Class Name"] = myvec->at(8);
202
+
203
+ objProperties["Occurrence Amount"] = myvec->at(9);
204
+ objProperties["Occurrence Function"] = myvec->at(10);
205
+ }
206
+ else if (myvec->at(0) == "reg")
207
+ {
208
+ objProperties["Regular Expression"] = myvec->at(1);
209
+ }
210
+ arrProperties.append(objProperties);
211
+ filter["filterdata"] = arrProperties;
212
+
213
+ filters.append(filter);
214
+ itFList++;
215
+
216
+ }
217
+ rootObj["projectdata"] = filters;
218
+
219
+ //qDebug() << "writeJsonFile: Before write to file.";
220
+ qint64 byteswritten = projFile.write( QJsonDocument(rootObj).toJson(/*QJsonDocument::Compact*/) );
221
+ //qDebug() << "writeJsonFile: After write to file.";
222
+ projFile.close();
223
+
224
+ if (byteswritten == -1)
225
+ {
226
+ qDebug() << "No Bytes written to the JsonFile :(";
227
+ qWarning("Error: Could not write to the project file.");
228
+ }
229
+ else
230
+ {
231
+ qDebug() << byteswritten << "Bytes have been written to the file";
232
+ bRes = true;
233
+ }
234
+
235
+ return(bRes);
236
+ }
237
+
238
+ bool JSONFile::openJsonFile()
239
+ {
240
+ bool bRes = false;
241
+ return(bRes);
242
+ }
243
+
244
+ QString JSONFile::getJsonFilePath(void)
245
+ {
246
+ QString sRes = "";
247
+ return(sRes);
248
+ }
249
+
250
+ qint64 JSONFile::getJsonFileSize(void)
251
+ {
252
+ qint64 iRes = 0;
253
+ return(iRes);
254
+ }
255
+
256
+ bool JSONFile::checkJsonFile()
257
+ {
258
+ bool bRes = false;
259
+ return(bRes);
260
+ }
pool/shard001/C++/0017084_object_rep.cpp ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2003 Daniel Wallin and Arvid Norberg
2
+
3
+ // Permission is hereby granted, free of charge, to any person obtaining a
4
+ // copy of this software and associated documentation files (the "Software"),
5
+ // to deal in the Software without restriction, including without limitation
6
+ // the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ // and/or sell copies of the Software, and to permit persons to whom the
8
+ // Software is furnished to do so, subject to the following conditions:
9
+
10
+ // The above copyright notice and this permission notice shall be included
11
+ // in all copies or substantial portions of the Software.
12
+
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
14
+ // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
15
+ // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
16
+ // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17
+ // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
18
+ // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19
+ // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
21
+ // OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ #define LUABIND_BUILDING
24
+
25
+ #include <luabind/detail/object_rep.hpp>
26
+ #include <luabind/detail/class_rep.hpp>
27
+ #include <luabind/lua502.hpp>
28
+
29
+ namespace luabind { namespace detail
30
+ {
31
+
32
+ // dest is a function that is called to delete the c++ object this struct holds
33
+ object_rep::object_rep(instance_holder* instance, class_rep* crep)
34
+ : m_instance(instance)
35
+ , m_classrep(crep)
36
+ , m_dependency_cnt(0)
37
+ {}
38
+
39
+ object_rep::~object_rep()
40
+ {
41
+ if (!m_instance)
42
+ return;
43
+ m_instance->~instance_holder();
44
+ deallocate(m_instance);
45
+ }
46
+
47
+ void object_rep::add_dependency(lua_State* L, int index)
48
+ {
49
+ assert(m_dependency_cnt < sizeof(object_rep));
50
+
51
+ void* key = (char*)this + m_dependency_cnt;
52
+
53
+ lua_pushlightuserdata(L, key);
54
+ lua_pushvalue(L, index);
55
+ lua_rawset(L, LUA_REGISTRYINDEX);
56
+
57
+ ++m_dependency_cnt;
58
+ }
59
+
60
+ void object_rep::release_dependency_refs(lua_State* L)
61
+ {
62
+ for (std::size_t i = 0; i < m_dependency_cnt; ++i)
63
+ {
64
+ void* key = (char*)this + i;
65
+ lua_pushlightuserdata(L, key);
66
+ lua_pushnil(L);
67
+ lua_rawset(L, LUA_REGISTRYINDEX);
68
+ }
69
+ }
70
+
71
+ int destroy_instance(lua_State* L)
72
+ {
73
+ object_rep* instance = static_cast<object_rep*>(lua_touserdata(L, 1));
74
+
75
+ lua_pushstring(L, "__finalize");
76
+ lua_gettable(L, 1);
77
+
78
+ if (lua_isnil(L, -1))
79
+ {
80
+ lua_pop(L, 1);
81
+ }
82
+ else
83
+ {
84
+ lua_pushvalue(L, 1);
85
+ lua_call(L, 1, 0);
86
+ }
87
+
88
+ instance->release_dependency_refs(L);
89
+ instance->~object_rep();
90
+ return 0;
91
+ }
92
+
93
+ namespace
94
+ {
95
+
96
+ int set_instance_value(lua_State* L)
97
+ {
98
+ lua_getfenv(L, 1);
99
+ lua_pushvalue(L, 2);
100
+ lua_rawget(L, -2);
101
+
102
+ if (lua_isnil(L, -1) && lua_getmetatable(L, -2))
103
+ {
104
+ lua_pushvalue(L, 2);
105
+ lua_rawget(L, -2);
106
+ lua_replace(L, -3);
107
+ lua_pop(L, 1);
108
+ }
109
+
110
+ if (lua_tocfunction(L, -1) == &property_tag)
111
+ {
112
+ // this member is a property, extract the "set" function and call it.
113
+ lua_getupvalue(L, -1, 2);
114
+
115
+ if (lua_isnil(L, -1))
116
+ {
117
+ lua_pushfstring(L, "property '%s' is read only", lua_tostring(L, 2));
118
+ lua_error(L);
119
+ }
120
+
121
+ lua_pushvalue(L, 1);
122
+ lua_pushvalue(L, 3);
123
+ lua_call(L, 2, 0);
124
+ return 0;
125
+ }
126
+
127
+ lua_pop(L, 1);
128
+
129
+ if (!lua_getmetatable(L, 4))
130
+ {
131
+ lua_newtable(L);
132
+ lua_pushvalue(L, -1);
133
+ lua_setfenv(L, 1);
134
+ lua_pushvalue(L, 4);
135
+ lua_setmetatable(L, -2);
136
+ }
137
+ else
138
+ {
139
+ lua_pop(L, 1);
140
+ }
141
+
142
+ lua_pushvalue(L, 2);
143
+ lua_pushvalue(L, 3);
144
+ lua_rawset(L, -3);
145
+
146
+ return 0;
147
+ }
148
+
149
+ int get_instance_value(lua_State* L)
150
+ {
151
+ lua_getfenv(L, 1);
152
+ lua_pushvalue(L, 2);
153
+ lua_rawget(L, -2);
154
+
155
+ if (lua_isnil(L, -1) && lua_getmetatable(L, -2))
156
+ {
157
+ lua_pushvalue(L, 2);
158
+ lua_rawget(L, -2);
159
+ }
160
+
161
+ if (lua_tocfunction(L, -1) == &property_tag)
162
+ {
163
+ // this member is a property, extract the "get" function and call it.
164
+ lua_getupvalue(L, -1, 1);
165
+ lua_pushvalue(L, 1);
166
+ lua_call(L, 1, 1);
167
+ }
168
+
169
+ return 1;
170
+ }
171
+
172
+ int dispatch_operator(lua_State* L)
173
+ {
174
+ for (int i = 0; i < 2; ++i)
175
+ {
176
+ if (get_instance(L, 1 + i))
177
+ {
178
+ int nargs = lua_gettop(L);
179
+
180
+ lua_pushvalue(L, lua_upvalueindex(1));
181
+ lua_gettable(L, 1 + i);
182
+
183
+ if (lua_isnil(L, -1))
184
+ {
185
+ lua_pop(L, 1);
186
+ continue;
187
+ }
188
+
189
+ lua_insert(L, 1); // move the function to the bottom
190
+
191
+ nargs = lua_toboolean(L, lua_upvalueindex(2)) ? 1 : nargs;
192
+
193
+ if (lua_toboolean(L, lua_upvalueindex(2))) // remove trailing nil
194
+ lua_remove(L, 3);
195
+
196
+ lua_call(L, nargs, 1);
197
+ return 1;
198
+ }
199
+ }
200
+
201
+ lua_pop(L, lua_gettop(L));
202
+ lua_pushstring(L, "No such operator defined");
203
+ lua_error(L);
204
+
205
+ return 0;
206
+ }
207
+
208
+ } // namespace unnamed
209
+
210
+ LUABIND_API void push_instance_metatable(lua_State* L)
211
+ {
212
+ lua_newtable(L);
213
+
214
+ // just indicate that this really is a class and not just
215
+ // any user data
216
+ lua_pushboolean(L, 1);
217
+ lua_setfield(L, -2, "__luabind_class");
218
+
219
+ // This is used as a tag to determine if a userdata is a luabind
220
+ // instance. We use a numeric key and a cclosure for fast comparision.
221
+ lua_pushnumber(L, 1);
222
+ lua_pushcclosure(L, get_instance_value, 0);
223
+ lua_rawset(L, -3);
224
+
225
+ lua_pushcclosure(L, destroy_instance, 0);
226
+ lua_setfield(L, -2, "__gc");
227
+
228
+ lua_pushcclosure(L, get_instance_value, 0);
229
+ lua_setfield(L, -2, "__index");
230
+
231
+ lua_pushcclosure(L, set_instance_value, 0);
232
+ lua_setfield(L, -2, "__newindex");
233
+
234
+ for (int op = 0; op < number_of_operators; ++op)
235
+ {
236
+ lua_pushstring(L, get_operator_name(op));
237
+ lua_pushvalue(L, -1);
238
+ lua_pushboolean(L, op == op_unm || op == op_len);
239
+ lua_pushcclosure(L, &dispatch_operator, 2);
240
+ lua_settable(L, -3);
241
+ }
242
+ }
243
+
244
+ LUABIND_API object_rep* get_instance(lua_State* L, int index)
245
+ {
246
+ object_rep* result = static_cast<object_rep*>(lua_touserdata(L, index));
247
+
248
+ if (!result || !lua_getmetatable(L, index))
249
+ return 0;
250
+
251
+ lua_rawgeti(L, -1, 1);
252
+
253
+ if (lua_tocfunction(L, -1) != &get_instance_value)
254
+ result = 0;
255
+
256
+ lua_pop(L, 2);
257
+
258
+ return result;
259
+ }
260
+
261
+ LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls)
262
+ {
263
+ void* storage = lua_newuserdata(L, sizeof(object_rep));
264
+ object_rep* result = new (storage) object_rep(0, cls);
265
+ cls->get_table(L);
266
+ lua_setfenv(L, -2);
267
+ lua_rawgeti(L, LUA_REGISTRYINDEX, cls->metatable_ref());
268
+ lua_setmetatable(L, -2);
269
+ return result;
270
+ }
271
+
272
+ }}
273
+
pool/shard001/C++/0017088_trajectory_builder_stub.cc ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017 The Cartographer Authors
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
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ #include "cartographer/cloud/internal/client/trajectory_builder_stub.h"
18
+
19
+ #include "cartographer/cloud/internal/sensor/serialization.h"
20
+ #include "cartographer/cloud/proto/map_builder_service.pb.h"
21
+ #include "cartographer/mapping/internal/local_slam_result_data.h"
22
+ #include "cartographer/transform/transform.h"
23
+ #include "glog/logging.h"
24
+
25
+ namespace cartographer {
26
+ namespace cloud {
27
+
28
+ TrajectoryBuilderStub::TrajectoryBuilderStub(
29
+ std::shared_ptr<::grpc::Channel> client_channel, const int trajectory_id,
30
+ const std::string& client_id,
31
+ LocalSlamResultCallback local_slam_result_callback)
32
+ : client_channel_(client_channel),
33
+ trajectory_id_(trajectory_id),
34
+ client_id_(client_id),
35
+ receive_local_slam_results_client_(client_channel_) {
36
+ if (local_slam_result_callback) {
37
+ proto::ReceiveLocalSlamResultsRequest request;
38
+ request.set_trajectory_id(trajectory_id);
39
+ receive_local_slam_results_client_.Write(request);
40
+ auto* receive_local_slam_results_client_ptr =
41
+ &receive_local_slam_results_client_;
42
+ receive_local_slam_results_thread_ = absl::make_unique<std::thread>(
43
+ [receive_local_slam_results_client_ptr, local_slam_result_callback]() {
44
+ RunLocalSlamResultsReader(receive_local_slam_results_client_ptr,
45
+ local_slam_result_callback);
46
+ });
47
+ }
48
+ }
49
+
50
+ TrajectoryBuilderStub::~TrajectoryBuilderStub() {
51
+ if (receive_local_slam_results_thread_) {
52
+ receive_local_slam_results_thread_->join();
53
+ }
54
+ if (add_rangefinder_client_) {
55
+ CHECK(add_rangefinder_client_->StreamWritesDone());
56
+ CHECK(add_rangefinder_client_->StreamFinish().ok());
57
+ }
58
+ if (add_imu_client_) {
59
+ CHECK(add_imu_client_->StreamWritesDone());
60
+ CHECK(add_imu_client_->StreamFinish().ok());
61
+ }
62
+ if (add_odometry_client_) {
63
+ CHECK(add_odometry_client_->StreamWritesDone());
64
+ CHECK(add_odometry_client_->StreamFinish().ok());
65
+ }
66
+ if (add_landmark_client_) {
67
+ CHECK(add_landmark_client_->StreamWritesDone());
68
+ CHECK(add_landmark_client_->StreamFinish().ok());
69
+ }
70
+ if (add_fixed_frame_pose_client_) {
71
+ CHECK(add_fixed_frame_pose_client_->StreamWritesDone());
72
+ CHECK(add_fixed_frame_pose_client_->StreamFinish().ok());
73
+ }
74
+ }
75
+
76
+ void TrajectoryBuilderStub::AddSensorData(
77
+ const std::string& sensor_id,
78
+ const sensor::TimedPointCloudData& timed_point_cloud_data) {
79
+ if (!add_rangefinder_client_) {
80
+ add_rangefinder_client_ = absl::make_unique<
81
+ async_grpc::Client<handlers::AddRangefinderDataSignature>>(
82
+ client_channel_);
83
+ }
84
+ proto::AddRangefinderDataRequest request;
85
+ CreateAddRangeFinderDataRequest(sensor_id, trajectory_id_, client_id_,
86
+ sensor::ToProto(timed_point_cloud_data),
87
+ &request);
88
+ add_rangefinder_client_->Write(request);
89
+ }
90
+
91
+ void TrajectoryBuilderStub::AddSensorData(const std::string& sensor_id,
92
+ const sensor::ImuData& imu_data) {
93
+ if (!add_imu_client_) {
94
+ add_imu_client_ =
95
+ absl::make_unique<async_grpc::Client<handlers::AddImuDataSignature>>(
96
+ client_channel_);
97
+ }
98
+ proto::AddImuDataRequest request;
99
+ CreateAddImuDataRequest(sensor_id, trajectory_id_, client_id_,
100
+ sensor::ToProto(imu_data), &request);
101
+ add_imu_client_->Write(request);
102
+ }
103
+
104
+ void TrajectoryBuilderStub::AddSensorData(
105
+ const std::string& sensor_id, const sensor::OdometryData& odometry_data) {
106
+ if (!add_odometry_client_) {
107
+ add_odometry_client_ = absl::make_unique<
108
+ async_grpc::Client<handlers::AddOdometryDataSignature>>(
109
+ client_channel_);
110
+ }
111
+ proto::AddOdometryDataRequest request;
112
+ CreateAddOdometryDataRequest(sensor_id, trajectory_id_, client_id_,
113
+ sensor::ToProto(odometry_data), &request);
114
+ add_odometry_client_->Write(request);
115
+ }
116
+
117
+ void TrajectoryBuilderStub::AddSensorData(
118
+ const std::string& sensor_id,
119
+ const sensor::FixedFramePoseData& fixed_frame_pose) {
120
+ if (!add_fixed_frame_pose_client_) {
121
+ add_fixed_frame_pose_client_ = absl::make_unique<
122
+ async_grpc::Client<handlers::AddFixedFramePoseDataSignature>>(
123
+ client_channel_);
124
+ }
125
+ proto::AddFixedFramePoseDataRequest request;
126
+ CreateAddFixedFramePoseDataRequest(sensor_id, trajectory_id_, client_id_,
127
+ sensor::ToProto(fixed_frame_pose),
128
+ &request);
129
+ add_fixed_frame_pose_client_->Write(request);
130
+ }
131
+
132
+ void TrajectoryBuilderStub::AddSensorData(
133
+ const std::string& sensor_id, const sensor::LandmarkData& landmark_data) {
134
+ if (!add_landmark_client_) {
135
+ add_landmark_client_ = absl::make_unique<
136
+ async_grpc::Client<handlers::AddLandmarkDataSignature>>(
137
+ client_channel_);
138
+ }
139
+ proto::AddLandmarkDataRequest request;
140
+ CreateAddLandmarkDataRequest(sensor_id, trajectory_id_, client_id_,
141
+ sensor::ToProto(landmark_data), &request);
142
+ add_landmark_client_->Write(request);
143
+ }
144
+
145
+ void TrajectoryBuilderStub::AddLocalSlamResultData(
146
+ std::unique_ptr<mapping::LocalSlamResultData> local_slam_result_data) {
147
+ LOG(FATAL) << "Not implemented";
148
+ }
149
+
150
+ void TrajectoryBuilderStub::RunLocalSlamResultsReader(
151
+ async_grpc::Client<handlers::ReceiveLocalSlamResultsSignature>* client,
152
+ LocalSlamResultCallback local_slam_result_callback) {
153
+ proto::ReceiveLocalSlamResultsResponse response;
154
+ while (client->StreamRead(&response)) {
155
+ int trajectory_id = response.trajectory_id();
156
+ common::Time time = common::FromUniversal(response.timestamp());
157
+ transform::Rigid3d local_pose = transform::ToRigid3(response.local_pose());
158
+ sensor::RangeData range_data = sensor::FromProto(response.range_data());
159
+ auto insertion_result =
160
+ response.has_insertion_result()
161
+ ? absl::make_unique<InsertionResult>(
162
+ InsertionResult{mapping::NodeId{
163
+ response.insertion_result().node_id().trajectory_id(),
164
+ response.insertion_result().node_id().node_index()}})
165
+ : nullptr;
166
+ local_slam_result_callback(trajectory_id, time, local_pose, range_data,
167
+ std::move(insertion_result));
168
+ }
169
+ client->StreamFinish();
170
+ }
171
+
172
+ } // namespace cloud
173
+ } // namespace cartographer
pool/shard001/C++/0017090_unnest-node.cc ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 Cloudera Inc.
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
+ #include "common/status.h"
16
+ #include "exec/unnest-node.h"
17
+ #include "exec/subplan-node.h"
18
+ #include "exprs/expr-context.h"
19
+ #include "exprs/slot-ref.h"
20
+ #include "runtime/runtime-state.h"
21
+ #include "util/runtime-profile.h"
22
+
23
+ namespace impala {
24
+
25
+ const ArrayValue UnnestNode::EMPTY_ARRAY_VALUE;
26
+
27
+ UnnestNode::UnnestNode(ObjectPool* pool, const TPlanNode& tnode,
28
+ const DescriptorTbl& descs)
29
+ : ExecNode(pool, tnode, descs),
30
+ item_byte_size_(0),
31
+ array_expr_ctx_(NULL),
32
+ array_slot_desc_(NULL),
33
+ array_tuple_idx_(-1),
34
+ array_value_(NULL),
35
+ item_idx_(0),
36
+ num_collections_(0),
37
+ total_collection_size_(0),
38
+ max_collection_size_(-1),
39
+ min_collection_size_(-1),
40
+ avg_collection_size_counter_(NULL),
41
+ max_collection_size_counter_(NULL),
42
+ min_collection_size_counter_(NULL),
43
+ num_collections_counter_(NULL) {
44
+ }
45
+
46
+ Status UnnestNode::Init(const TPlanNode& tnode) {
47
+ RETURN_IF_ERROR(ExecNode::Init(tnode));
48
+ DCHECK(tnode.__isset.unnest_node);
49
+ Expr::CreateExprTree(pool_, tnode.unnest_node.collection_expr, &array_expr_ctx_);
50
+ return Status::OK();
51
+ }
52
+
53
+ Status UnnestNode::Prepare(RuntimeState* state) {
54
+ SCOPED_TIMER(runtime_profile_->total_time_counter());
55
+ DCHECK(containing_subplan_ != NULL) << "set_containing_subplan() must be called";
56
+ RETURN_IF_ERROR(ExecNode::Prepare(state));
57
+
58
+ avg_collection_size_counter_ =
59
+ ADD_COUNTER(runtime_profile_, "AvgCollectionSize", TUnit::DOUBLE_VALUE);
60
+ max_collection_size_counter_ =
61
+ ADD_COUNTER(runtime_profile_, "MaxCollectionSize", TUnit::UNIT);
62
+ min_collection_size_counter_ =
63
+ ADD_COUNTER(runtime_profile_, "MinCollectionSize", TUnit::UNIT);
64
+ num_collections_counter_ =
65
+ ADD_COUNTER(runtime_profile_, "NumCollections", TUnit::UNIT);
66
+
67
+ DCHECK_EQ(1, row_desc().tuple_descriptors().size());
68
+ const TupleDescriptor* item_tuple_desc = row_desc().tuple_descriptors()[0];
69
+ DCHECK(item_tuple_desc != NULL);
70
+ item_byte_size_ = item_tuple_desc->byte_size();
71
+ RETURN_IF_ERROR(array_expr_ctx_->Prepare(
72
+ state, containing_subplan_->child(0)->row_desc(), expr_mem_tracker()));
73
+
74
+ // Set the array_slot_desc_ and the corresponding tuple index used for manually
75
+ // evaluating the array SlotRef and for projection.
76
+ DCHECK(array_expr_ctx_->root()->is_slotref());
77
+ const SlotRef* slot_ref = static_cast<SlotRef*>(array_expr_ctx_->root());
78
+ array_slot_desc_ = state->desc_tbl().GetSlotDescriptor(slot_ref->slot_id());
79
+ DCHECK(array_slot_desc_ != NULL);
80
+ const RowDescriptor& row_desc = containing_subplan_->child(0)->row_desc();
81
+ array_tuple_idx_ = row_desc.GetTupleIdx(array_slot_desc_->parent()->id());
82
+
83
+ return Status::OK();
84
+ }
85
+
86
+ Status UnnestNode::Open(RuntimeState* state) {
87
+ SCOPED_TIMER(runtime_profile_->total_time_counter());
88
+ RETURN_IF_ERROR(ExecNode::Open(state));
89
+ RETURN_IF_ERROR(array_expr_ctx_->Open(state));
90
+
91
+ DCHECK(containing_subplan_->current_row() != NULL);
92
+ Tuple* tuple = containing_subplan_->current_input_row_->GetTuple(array_tuple_idx_);
93
+ if (tuple != NULL) {
94
+ // Retrieve the array value to be unnested directly from the tuple. We purposely
95
+ // ignore the null bit of the slot because we may have set it in a previous Open()
96
+ // of this same unnest node for projection.
97
+ array_value_ = reinterpret_cast<const ArrayValue*>(
98
+ tuple->GetSlot(array_slot_desc_->tuple_offset()));
99
+ // Projection: Set the slot containing the array value to NULL.
100
+ tuple->SetNull(array_slot_desc_->null_indicator_offset());
101
+ } else {
102
+ array_value_ = &EMPTY_ARRAY_VALUE;
103
+ DCHECK_EQ(array_value_->num_tuples, 0);
104
+ }
105
+
106
+ ++num_collections_;
107
+ COUNTER_SET(num_collections_counter_, num_collections_);
108
+ total_collection_size_ += array_value_->num_tuples;
109
+ COUNTER_SET(avg_collection_size_counter_,
110
+ static_cast<double>(total_collection_size_) / num_collections_);
111
+ if (max_collection_size_ == -1 || array_value_->num_tuples > max_collection_size_) {
112
+ max_collection_size_ = array_value_->num_tuples;
113
+ COUNTER_SET(max_collection_size_counter_, max_collection_size_);
114
+ }
115
+ if (min_collection_size_ == -1 || array_value_->num_tuples < min_collection_size_) {
116
+ min_collection_size_ = array_value_->num_tuples;
117
+ COUNTER_SET(min_collection_size_counter_, min_collection_size_);
118
+ }
119
+ return Status::OK();
120
+ }
121
+
122
+ Status UnnestNode::GetNext(RuntimeState* state, RowBatch* row_batch, bool* eos) {
123
+ SCOPED_TIMER(runtime_profile_->total_time_counter());
124
+ // Avoid expensive query maintenance overhead for small arrays.
125
+ if (item_idx_ > 0) {
126
+ RETURN_IF_CANCELLED(state);
127
+ RETURN_IF_ERROR(QueryMaintenance(state));
128
+ }
129
+ *eos = false;
130
+
131
+ // Populate the output row_batch with tuples from the array.
132
+ DCHECK(array_value_ != NULL);
133
+ while (item_idx_ < array_value_->num_tuples) {
134
+ Tuple* item =
135
+ reinterpret_cast<Tuple*>(array_value_->ptr + item_idx_ * item_byte_size_);
136
+ ++item_idx_;
137
+ int row_idx = row_batch->AddRow();
138
+ TupleRow* row = row_batch->GetRow(row_idx);
139
+ row->SetTuple(0, item);
140
+ // TODO: Ideally these should be evaluated by the parent scan node.
141
+ if (EvalConjuncts(&conjunct_ctxs_[0], conjunct_ctxs_.size(), row)) {
142
+ row_batch->CommitLastRow();
143
+ // The limit is handled outside of this loop.
144
+ if (row_batch->AtCapacity()) break;
145
+ }
146
+ }
147
+ num_rows_returned_ += row_batch->num_rows();
148
+
149
+ // Checking the limit here is simpler/cheaper than doing it in the loop above.
150
+ if (ReachedLimit()) {
151
+ *eos = true;
152
+ row_batch->set_num_rows(row_batch->num_rows() - (num_rows_returned_ - limit_));
153
+ num_rows_returned_ = limit_;
154
+ } else if (item_idx_ == array_value_->num_tuples) {
155
+ *eos = true;
156
+ }
157
+ COUNTER_SET(rows_returned_counter_, num_rows_returned_);
158
+ return Status::OK();
159
+ }
160
+
161
+ Status UnnestNode::Reset(RuntimeState* state) {
162
+ item_idx_ = 0;
163
+ return ExecNode::Reset(state);
164
+ }
165
+
166
+ void UnnestNode::Close(RuntimeState* state) {
167
+ if (is_closed()) return;
168
+ DCHECK(array_expr_ctx_ != NULL);
169
+ array_expr_ctx_->Close(state);
170
+ ExecNode::Close(state);
171
+ }
172
+
173
+ }
pool/shard001/C++/0017105_dtb_object.cc ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2013 The Regents of The University of Michigan
3
+ * All rights reserved.
4
+ *
5
+ * Redistribution and use in source and binary forms, with or without
6
+ * modification, are permitted provided that the following conditions are
7
+ * met: redistributions of source code must retain the above copyright
8
+ * notice, this list of conditions and the following disclaimer;
9
+ * 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
+ * neither the name of the copyright holders nor the names of its
13
+ * contributors may be used to endorse or promote products derived from
14
+ * this software without specific prior written permission.
15
+ *
16
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+ *
28
+ * Authors: Anthony Gutierrez
29
+ */
30
+
31
+ #include <sys/mman.h>
32
+ #include <err.h>
33
+ #include <unistd.h>
34
+
35
+ #include <cassert>
36
+
37
+ #include "base/loader/dtb_object.hh"
38
+ #include "sim/byteswap.hh"
39
+ #include "fdt.h"
40
+ #include "libfdt.h"
41
+
42
+ ObjectFile *
43
+ DtbObject::tryFile(const std::string &fname, size_t len, uint8_t *data)
44
+ {
45
+ // Check if this is a FDT file by looking for magic number
46
+ if (fdt_magic((void*)data) == FDT_MAGIC) {
47
+ return new DtbObject(fname, len, data,
48
+ ObjectFile::UnknownArch, ObjectFile::UnknownOpSys);
49
+ } else {
50
+ return NULL;
51
+ }
52
+ }
53
+
54
+ DtbObject::DtbObject(const std::string &_filename, size_t _len, uint8_t *_data,
55
+ Arch _arch, OpSys _opSys)
56
+ : ObjectFile(_filename, _len, _data, _arch, _opSys)
57
+ {
58
+ text.baseAddr = 0;
59
+ text.size = len;
60
+ text.fileImage = fileData;
61
+
62
+ data.baseAddr = 0;
63
+ data.size = 0;
64
+ data.fileImage = NULL;
65
+
66
+ bss.baseAddr = 0;
67
+ bss.size = 0;
68
+ bss.fileImage = NULL;
69
+
70
+ fileDataMmapped = true;
71
+ }
72
+
73
+ DtbObject::~DtbObject()
74
+ {
75
+ // Make sure to clean up memory properly depending
76
+ // on how buffer was allocated.
77
+ if (fileData && !fileDataMmapped) {
78
+ delete [] fileData;
79
+ fileData = NULL;
80
+ } else if (fileData) {
81
+ munmap(fileData, len);
82
+ fileData = NULL;
83
+ }
84
+ }
85
+
86
+ bool
87
+ DtbObject::addBootCmdLine(const char* _args, size_t len)
88
+ {
89
+ const char* root_path = "/";
90
+ const char* node_name = "chosen";
91
+ const char* full_path_node_name = "/chosen";
92
+ const char* property_name = "bootargs";
93
+
94
+ // Make a new buffer that has extra space to add nodes/properties
95
+ int newLen = 2*this->len;
96
+ uint8_t* fdt_buf_w_space = new uint8_t[newLen];
97
+ // Copy and unpack flattened device tree into new buffer
98
+ int ret = fdt_open_into((void*)fileData, (void*)fdt_buf_w_space, (newLen));
99
+ if (ret < 0) {
100
+ warn("Error resizing buffer of flattened device tree, "
101
+ "errno: %d\n", ret);
102
+ delete [] fdt_buf_w_space;
103
+ return false;
104
+ }
105
+
106
+ // First try finding the /chosen node in the dtb
107
+ int offset = fdt_path_offset((void*)fdt_buf_w_space, full_path_node_name);
108
+ if (offset < 0) {
109
+ // try adding the node by walking dtb tree to proper insertion point
110
+ offset = fdt_path_offset((void*)fdt_buf_w_space, root_path);
111
+ offset = fdt_add_subnode((void*)fdt_buf_w_space, offset, node_name);
112
+ offset = fdt_path_offset((void*)fdt_buf_w_space, full_path_node_name);
113
+ if (offset < 0) {
114
+ warn("Error finding or adding \"chosen\" subnode to flattened "
115
+ "device tree, errno: %d\n", offset);
116
+ delete [] fdt_buf_w_space;
117
+ return false;
118
+ }
119
+ }
120
+
121
+ // Set the bootargs property in the /chosen node
122
+ ret = fdt_setprop((void*)fdt_buf_w_space, offset, property_name,
123
+ (const void*)_args, len+1);
124
+ if (ret < 0) {
125
+ warn("Error setting \"bootargs\" property to flattened device tree, "
126
+ "errno: %d\n", ret);
127
+ delete [] fdt_buf_w_space;
128
+ return false;
129
+ }
130
+
131
+ // Repack the dtb for kernel use
132
+ ret = fdt_pack((void*)fdt_buf_w_space);
133
+ if (ret < 0) {
134
+ warn("Error re-packing flattened device tree structure, "
135
+ "errno: %d\n", ret);
136
+ delete [] fdt_buf_w_space;
137
+ return false;
138
+ }
139
+
140
+ text.size = newLen;
141
+ text.fileImage = fdt_buf_w_space;
142
+
143
+ // clean up old buffer and set to new fdt blob
144
+ munmap(fileData, this->len);
145
+ fileData = fdt_buf_w_space;
146
+ fileDataMmapped = false;
147
+ this->len = newLen;
148
+
149
+ return true;
150
+ }
151
+
152
+ Addr
153
+ DtbObject::findReleaseAddr()
154
+ {
155
+ void *fd = (void*)fileData;
156
+
157
+ int offset = fdt_path_offset(fd, "/cpus/cpu@0");
158
+ int len;
159
+
160
+ const void* temp = fdt_getprop(fd, offset, "cpu-release-addr", &len);
161
+ Addr rel_addr = 0;
162
+
163
+ if (len > 3)
164
+ rel_addr = betoh(*static_cast<const uint32_t*>(temp));
165
+ if (len == 8)
166
+ rel_addr = (rel_addr << 32) | betoh(*(static_cast<const uint32_t*>(temp)+1));
167
+
168
+ return rel_addr;
169
+ }
170
+
171
+
172
+ bool
173
+ DtbObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
174
+ {
175
+ // nothing to do here
176
+ return false;
177
+ }
178
+
179
+ bool
180
+ DtbObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
181
+ {
182
+ // nothing to do here
183
+ return false;
184
+ }
pool/shard001/C++/0017113_Claw.cpp ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2014-2021 FRC Team 3512. All Rights Reserved.
2
+
3
+ #include "subsystems/Claw.hpp"
4
+
5
+ #include <frc/DriverStation.h>
6
+ #include <frc/Joystick.h>
7
+ #include <wpi/math>
8
+
9
+ Claw::Claw() {
10
+ // Sets degrees rotated per pulse of encoder
11
+ m_angleEncoder.SetDistancePerPulse((1.0 / 71.0) * 14.0 / 44.0);
12
+
13
+ m_ballShooter.emplace_back(8);
14
+ m_ballShooter.emplace_back(2);
15
+ m_ballShooter.emplace_back(3);
16
+ m_ballShooter.emplace_back(6);
17
+ }
18
+
19
+ void Claw::SetAngleReference(units::degree_t shooterAngle) {
20
+ m_controller.SetSetpoint(shooterAngle.to<double>());
21
+ }
22
+
23
+ units::degree_t Claw::GetAngleReference() const {
24
+ return units::degree_t{m_controller.GetSetpoint()};
25
+ }
26
+
27
+ void Claw::SetWheel(double speed) { m_intakeWheel.Set(speed); }
28
+
29
+ void Claw::Shoot() {
30
+ if (m_shooterState == ShooterState::kIdle) {
31
+ m_collectorArm.Set(true);
32
+ m_shooterState = ShooterState::kArmIsLifting;
33
+ m_shootTimer.Start();
34
+ m_shootTimer.Reset();
35
+ }
36
+ }
37
+
38
+ bool Claw::IsShooting() const { return m_shooterState != ShooterState::kIdle; }
39
+
40
+ void Claw::RobotPeriodic() {
41
+ static frc::Joystick driveStick2{2};
42
+ static frc::Joystick shootStick{3};
43
+
44
+ if (driveStick2.GetRawButtonPressed(7)) {
45
+ SetAngleReference(190_deg);
46
+ }
47
+
48
+ if (driveStick2.GetRawButtonPressed(9)) {
49
+ SetAngleReference(106_deg);
50
+ }
51
+
52
+ if (driveStick2.GetRawButtonPressed(8)) {
53
+ SetAngleReference(57_deg);
54
+ }
55
+
56
+ if (driveStick2.GetRawButtonPressed(11)) {
57
+ // Collector should always be retracted when resetting encoder
58
+ m_collectorArm.Set(false);
59
+ SetAngleReference(0_deg);
60
+ }
61
+
62
+ if (driveStick2.GetRawButtonPressed(10)) {
63
+ SetAngleReference(GetAngleReference() + 3_deg);
64
+ }
65
+
66
+ if (driveStick2.GetRawButtonPressed(12)) {
67
+ SetAngleReference(GetAngleReference() - 3_deg);
68
+ }
69
+
70
+ // Engage collector
71
+ if (driveStick2.GetRawButtonPressed(2)) {
72
+ m_collectorArm.Set(!m_collectorArm.Get());
73
+ }
74
+
75
+ // Shoots a ball
76
+ if ((shootStick.GetRawButtonPressed(1) ||
77
+ driveStick2.GetRawButtonPressed(1)) &&
78
+ !IsShooting()) {
79
+ Shoot();
80
+ }
81
+
82
+ if (shootStick.GetRawButtonPressed(3)) {
83
+ SetWheel(-1.0);
84
+ } else if (shootStick.GetRawButtonPressed(4)) {
85
+ SetWheel(1.0);
86
+ } else {
87
+ SetWheel(0.0);
88
+ }
89
+
90
+ double ff = 0.0;
91
+ if (m_controller.GetSetpoint() > 0.0) {
92
+ ff = kK *
93
+ std::cos((m_angleEncoder.GetDistance() + kL) * wpi::math::pi /
94
+ 180.0) /
95
+ m_controller.GetSetpoint();
96
+ }
97
+ double fb = m_controller.Calculate(m_angleEncoder.GetDistance());
98
+
99
+ m_clawRotator.Set(ff + fb);
100
+
101
+ if (m_shooterState == ShooterState::kArmIsLifting &&
102
+ m_shootTimer.HasPeriodPassed(0.5_s)) {
103
+ for (auto& solenoid : m_ballShooter) {
104
+ solenoid.Set(true);
105
+ }
106
+ m_shootTimer.Reset();
107
+ m_shooterState = ShooterState::kShooting;
108
+ }
109
+ if (m_shooterState == ShooterState::kShooting &&
110
+ m_shootTimer.HasPeriodPassed(2.0_s)) {
111
+ for (auto& solenoid : m_ballShooter) {
112
+ solenoid.Set(false);
113
+ }
114
+ m_vacuum.Set(frc::Relay::kOn);
115
+ m_shootTimer.Reset();
116
+ m_shooterState = ShooterState::kVacuuming;
117
+ }
118
+ if (m_shooterState == ShooterState::kVacuuming &&
119
+ m_shootTimer.HasPeriodPassed(3.0_s)) {
120
+ m_vacuum.Set(frc::Relay::kOff);
121
+ m_collectorArm.Set(false);
122
+
123
+ m_shootTimer.Reset();
124
+ m_shooterState = ShooterState::kIdle;
125
+ }
126
+
127
+ // Spins intake wheel to keep ball in while rotating claw at high speeds
128
+ if (std::abs(m_angleEncoder.GetRate()) > 35.0) {
129
+ SetWheel(-1.0);
130
+ }
131
+
132
+ /* Fixes arm, when at reset angle, not touching zeroSwitch due to gradual
133
+ * encoder error. If limit switch isn't pressed but arm is supposedly at
134
+ * zeroing point or farther:
135
+ */
136
+ if (m_zeroSwitch.Get() && GetAngleReference() <= 1_deg) {
137
+ SetAngleReference(GetAngleReference() - 5_deg);
138
+ }
139
+
140
+ // If wasn't pressed last time and is now
141
+ if (!m_zeroSwitch.Get() && GetAngleReference() <= 0_deg) {
142
+ SetAngleReference(0_deg);
143
+ m_controller.Reset();
144
+ m_angleEncoder.Reset();
145
+ }
146
+
147
+ // Close claw if zero switch is pressed
148
+ if (m_zeroSwitch.Get() && !IsShooting()) {
149
+ m_collectorArm.Set(false);
150
+ }
151
+
152
+ m_lastZeroSwitch = m_zeroSwitch.Get();
153
+ }
154
+
155
+ void Claw::TestClaw() {
156
+ auto& ds = frc::DriverStation::GetInstance();
157
+
158
+ for (auto& solenoid : m_ballShooter) {
159
+ solenoid.Set(true);
160
+ frc2::Wait(1.5_s);
161
+
162
+ solenoid.Set(false);
163
+ frc2::Wait(1.5_s);
164
+
165
+ m_vacuum.Set(frc::Relay::kOn);
166
+ frc2::Wait(1.5_s);
167
+
168
+ m_vacuum.Set(frc::Relay::kOff);
169
+ frc2::Wait(1.5_s);
170
+
171
+ if (ds.IsDisabled()) {
172
+ return;
173
+ }
174
+ }
175
+ }
pool/shard001/C++/0017115_target_anim_ctrl.cpp ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
2
+ // Copyright (C) 2010 Winch Gate Property Limited
3
+ //
4
+ // This program is free software: you can redistribute it and/or modify
5
+ // it under the terms of the GNU Affero General Public License as
6
+ // published by the Free Software Foundation, either version 3 of the
7
+ // License, or (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 Affero General Public License for more details.
13
+ //
14
+ // You should have received a copy of the GNU Affero General Public License
15
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+
17
+ #include "std3d.h"
18
+ #include "nel/misc/common.h"
19
+ #include "nel/3d/target_anim_ctrl.h"
20
+ #include "nel/3d/bone.h"
21
+ #include "nel/3d/skeleton_model.h"
22
+ #include "nel/3d/scene.h"
23
+
24
+ using namespace std;
25
+ using namespace NLMISC;
26
+
27
+ namespace NL3D {
28
+
29
+
30
+ // ***************************************************************************
31
+ CTargetAnimCtrl::CTargetAnimCtrl()
32
+ {
33
+ Mode= DirectionMode;
34
+ WorldTarget= CVector::Null;
35
+ EyePos= CVector::Null;
36
+ // Default Direction to "LookBack".
37
+ DefaultWorldDirection.set(0,0,1,0);
38
+ MaxAngle= (float)Pi/3;
39
+ MaxAngularVelocity= (float)(2*Pi);
40
+ Enabled= true;
41
+ _EnableToDisableTransition= false;
42
+ _LastEnabled= true;
43
+ }
44
+
45
+
46
+ // ***************************************************************************
47
+ CTargetAnimCtrl::~CTargetAnimCtrl()
48
+ {
49
+ }
50
+
51
+
52
+ // ***************************************************************************
53
+ void CTargetAnimCtrl::execute(CSkeletonModel *model, CBone *bone)
54
+ {
55
+ // no op if req not met
56
+ if(!bone || !model || bone->getTransformMode()!=ITransformable::RotQuat)
57
+ return;
58
+
59
+ // If the user changed the Enabled state, must do a transition.
60
+ if(_LastEnabled!=Enabled)
61
+ {
62
+ _LastEnabled= Enabled;
63
+ // if re-enable the control while completely disabled before
64
+ if(Enabled && !_EnableToDisableTransition)
65
+ {
66
+ // set the LastLSRotation so that it match the current anim ones.
67
+ _LastLSRotation= getCurrentLSRotationFromBone(model, bone);
68
+ }
69
+ // if disable the ctrl, then do a transition first
70
+ if(!Enabled)
71
+ {
72
+ _EnableToDisableTransition= true;
73
+ }
74
+ }
75
+
76
+ // If not enabled, and not in transition, no op.
77
+ if( !Enabled && !_EnableToDisableTransition)
78
+ return;
79
+
80
+ // If Target mode, compute CurrentWorldDirection
81
+ // ***********
82
+ // NB: does need to compute direction if disabled (even if in transition)
83
+ if(Mode==TargetMode && Enabled)
84
+ {
85
+ // get the eye pos in world.
86
+ CVector worldEye= bone->getWorldMatrix()*EyePos;
87
+ // get the world dir
88
+ CVector worldDir= (WorldTarget - worldEye).normed();
89
+ // get the associated quat
90
+ CMatrix mat;
91
+ mat.setRot(CVector::I, worldDir, CVector::K);
92
+ mat.normalize(CMatrix::YZX);
93
+ CurrentWorldDirection= mat.getRot();
94
+ }
95
+
96
+
97
+ // compute rotation to apply In LocalSkeleton Space
98
+ // ***********
99
+ CQuat currentLSRotation;
100
+
101
+ /* Get the Skeleton default WorldMatrix (bind pos). used later
102
+ TRICK: to get the default Skeleton WorldMatrix, get it from Bone[0] (ie "Bip01")
103
+ We cannot use the Default Pos/Rot of the skeleton model because of export bug (not exported...)
104
+ So, since Bip01 as no Local Rot (yes, its true, exporter report all Bip01 rots on Skeleton),
105
+ we are sure that Bip01 BindPos is the default Skeleton World Matrix.
106
+ */
107
+ CQuat rootInvBP= model->Bones[0].getBoneBase().InvBindPos.getRot();
108
+
109
+ // If ctrl not enabled, take the LSRotation from the animation
110
+ if(!Enabled)
111
+ {
112
+ currentLSRotation= getCurrentLSRotationFromBone(model, bone);
113
+ }
114
+ else
115
+ {
116
+ // Get the wanted direction in LocalSkeleton Space.
117
+ CQuat currentLSDirection;
118
+
119
+ // Get the current wanted WorldDirection into LocalSkeleton space (hence using current skeleton WorldMatrix).
120
+ CMatrix toLSSpace= model->getWorldMatrix();
121
+ currentLSDirection= toLSSpace.getRot().conjugate() * CurrentWorldDirection;
122
+
123
+ // Get the default WorldDirection into LocalSkeleton space (hence using default skeleton WorldMatrix).
124
+ CQuat defaultLSDirection= rootInvBP * DefaultWorldDirection;
125
+
126
+ /* get the rotation to apply to the bone when it is in bind Pos. If this quat is identity,
127
+ then the bone will be in default (or bind) pos.
128
+ It is in essence the "rotation to apply to defaultDirection in LS space, in order to get
129
+ the wanted current direction in LS space".
130
+ The makeClosest() is here just to ensure that the resulting angle<Pi (for clamp direction later)
131
+ */
132
+ currentLSDirection.makeClosest(defaultLSDirection);
133
+ currentLSRotation= currentLSDirection * defaultLSDirection.conjugate();
134
+ }
135
+
136
+
137
+ // Clamp direction, and smooth direction changes.
138
+ // ***********
139
+ // if not enabled, then LSRotation comes from the animation => do not clamp
140
+ if(Enabled)
141
+ {
142
+ // to AngleAxis.
143
+ CAngleAxis angleAxis= currentLSRotation.getAngleAxis();
144
+ // Clamp the angle
145
+ clamp(angleAxis.Angle, -MaxAngle, MaxAngle);
146
+ // back To Quat.
147
+ currentLSRotation.setAngleAxis(angleAxis);
148
+ }
149
+
150
+ // get the dt of the scene.
151
+ CScene *scene= model->getOwnerScene();
152
+ float sceneDt= scene->getEllapsedTime();
153
+ float maxDeltaAngle= MaxAngularVelocity*sceneDt;
154
+ // get the quat that change from LastRotation to CurrentRotation
155
+ CQuat rotMod= _LastLSRotation.conjugate() * currentLSRotation;
156
+ // compute how many rotation we are allowed to do.
157
+ float rotModAngle= (float)fabs(rotMod.getAngle());
158
+ bool rotSpeedClamped= false;
159
+ if(rotModAngle)
160
+ {
161
+ float factor= (float)fabs(maxDeltaAngle) / rotModAngle;
162
+ // If cannot do all the rotation this frame
163
+ if(factor<1)
164
+ {
165
+ // then slerp between last and current rotation
166
+ currentLSRotation.makeClosest(_LastLSRotation);
167
+ currentLSRotation= CQuat::slerp(_LastLSRotation, currentLSRotation, factor);
168
+ rotSpeedClamped= true;
169
+ }
170
+ }
171
+
172
+ // if the rotation has not been clamped for speed consideration, and if !Enabed, it's mean we have ended
173
+ // the transition => no more compute next time
174
+ if(!Enabled && !rotSpeedClamped)
175
+ _EnableToDisableTransition= false;
176
+
177
+ // bkup last rotation
178
+ _LastLSRotation= currentLSRotation;
179
+
180
+ // Apply the weighted Rotation to the bone
181
+ // ***********
182
+ // Get the bone Bind Pos in LocalSkeleton space (hence using Default Skeleton WorldMatrix)
183
+ CQuat boneBindPosInWorld= bone->getBoneBase().InvBindPos.getRot().conjugate();
184
+ CQuat boneBindPosInLS= rootInvBP * boneBindPosInWorld;
185
+ // rotate it to match our wanted direction.
186
+ boneBindPosInLS= currentLSRotation * boneBindPosInLS;
187
+
188
+ // get it in bone local space.
189
+ // get the Bone Parent LocalSkeletonMatrix
190
+ CBone *boneParent= bone->getFatherId()==-1? NULL : &model->Bones[bone->getFatherId()];
191
+ CQuat currentLocalQuat;
192
+ if(!boneParent)
193
+ currentLocalQuat= boneBindPosInLS;
194
+ else
195
+ {
196
+ // compute the rotation to apply, in local space
197
+ CQuat qp= boneParent->getLocalSkeletonMatrix().getRot();
198
+ currentLocalQuat= qp.conjugate() * boneBindPosInLS;
199
+ }
200
+
201
+ // set the new LocalRotQuat
202
+ bone->setRotQuat(currentLocalQuat);
203
+ // and recompute the bone (but without AnimCtrl of course :) )
204
+ bone->compute(boneParent, model->getWorldMatrix(), NULL);
205
+
206
+ }
207
+
208
+
209
+ // ***************************************************************************
210
+ CQuat CTargetAnimCtrl::getCurrentLSRotationFromBone(CSkeletonModel *model, CBone *bone)
211
+ {
212
+ // get the current rotation matrix (qmat) of this bone, in LS space
213
+ CQuat currentLSRot= bone->getLocalSkeletonMatrix().getRot();
214
+
215
+ // get the default bindPos (qb) rotation of this bone, in LS space.
216
+ CQuat boneBindPosInWorld= bone->getBoneBase().InvBindPos.getRot().conjugate();
217
+ CQuat rootInvBP= model->Bones[0].getBoneBase().InvBindPos.getRot();
218
+ CQuat boneBindPosInLS= rootInvBP * boneBindPosInWorld;
219
+
220
+ // The rotation (qrot) is computed such that qmat= qrot * qb
221
+ currentLSRot.makeClosest(boneBindPosInLS);
222
+ return currentLSRot * boneBindPosInLS.conjugate();
223
+ }
224
+
225
+
226
+
227
+ } // NL3D
pool/shard001/C++/0017116_cellcolors.cpp ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Dwarf Therapist
3
+ Copyright (c) 2009 Trey Stout (chmod)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
22
+ */
23
+ #include "cellcolors.h"
24
+ #include "viewcolumn.h"
25
+ #include "dwarftherapist.h"
26
+ #include "cellcolordef.h"
27
+
28
+ CellColors::CellColors(QObject *parent)
29
+ : QObject(parent)
30
+ , m_override_cell_colors(false)
31
+ {
32
+ }
33
+
34
+ CellColors::CellColors(const CellColors &cc)
35
+ : QObject(cc.parent())
36
+ {
37
+ m_color_defs = cc.m_color_defs;
38
+ m_override_cell_colors = cc.m_override_cell_colors;
39
+ }
40
+
41
+ CellColors::~CellColors(){
42
+ m_color_defs.clear();
43
+ }
44
+
45
+ void CellColors::load_settings(QSettings &s){
46
+ m_override_cell_colors = s.value("overrides_cell_colors",false).toBool();
47
+ if(m_override_cell_colors){
48
+ set_color(0,s.value("active_labor").value<QColor>());
49
+ set_color(1,s.value("pending_color").value<QColor>());
50
+ set_color(2,s.value("disabled_color").value<QColor>());
51
+ }
52
+ }
53
+
54
+ void CellColors::inherit_colors(const CellColors &cc){
55
+ int idx = 0;
56
+ foreach(QSharedPointer<CellColorDef> c, cc.m_color_defs){
57
+ //if we're not overridding or this specific color isn't overridden, then inherit
58
+ if(!m_override_cell_colors || !c->is_overridden()){
59
+ m_color_defs[idx].swap(c);
60
+ }
61
+ idx++;
62
+ }
63
+ }
64
+
65
+ void CellColors::use_defaults(){
66
+ //by default use the global color scheme
67
+ m_color_defs.clear();
68
+ m_color_defs.append(DT->get_global_color(GCOL_ACTIVE));
69
+ m_color_defs.append(DT->get_global_color(GCOL_PENDING));
70
+ m_color_defs.append(DT->get_global_color(GCOL_DISABLED));
71
+ }
72
+
73
+ QColor CellColors::get_default_color(int idx) const{
74
+ return DT->get_global_color(static_cast<GLOBAL_COLOR_TYPES>(idx))->color();
75
+ }
76
+
77
+ QSharedPointer<CellColorDef> CellColors::get_default_color_def(int idx){
78
+ return DT->get_global_color(static_cast<GLOBAL_COLOR_TYPES>(idx));
79
+ }
80
+
81
+ void CellColors::write_to_ini(QSettings &s){
82
+ //only write values if they've overridden the defaults
83
+ if(m_override_cell_colors){
84
+ s.setValue("overrides_cell_colors",m_override_cell_colors);
85
+ foreach(QSharedPointer<CellColorDef> c, m_color_defs){
86
+ s.setValue(c->key(),c->color());
87
+ }
88
+ }
89
+ }
90
+
91
+ QColor CellColors::get_color(int idx) const {
92
+ return m_color_defs.at(idx)->color();
93
+ }
94
+
95
+ QVector<QSharedPointer<CellColorDef> > CellColors::get_color_defs(){
96
+ return m_color_defs;
97
+ }
98
+
99
+ void CellColors::set_color(int idx, QColor c){
100
+ if(c.isValid()){
101
+ if(c != get_default_color(idx)){
102
+ //new color is valid and not the default color
103
+ if(m_color_defs.at(idx)->is_overridden()){
104
+ //current color def is already custom, update the color def's color
105
+ m_color_defs.at(idx)->set_color(c);
106
+ }else{
107
+ //current color def is not custom, so it's the default. create a new def by copying the existing one
108
+ QSharedPointer<CellColorDef> cpy = QSharedPointer<CellColorDef>(new CellColorDef(*m_color_defs.at(idx)));
109
+ cpy->set_color(c);
110
+ cpy->set_overridden(true);
111
+ m_color_defs[idx].swap(cpy);
112
+ }
113
+ }else{
114
+ //new color is the default color
115
+ if(m_color_defs.at(idx)->is_overridden()){
116
+ //current color def is custom, replace it with the default color def
117
+ QSharedPointer<CellColorDef> def = get_default_color_def(idx);
118
+ m_color_defs[idx].swap(def);
119
+ }
120
+ }
121
+ }
122
+ }
pool/shard001/C++/0017123_GrProcessor.cpp ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2012 Google Inc.
3
+ *
4
+ * Use of this source code is governed by a BSD-style license that can be
5
+ * found in the LICENSE file.
6
+ */
7
+
8
+ #include "GrProcessor.h"
9
+ #include "GrContext.h"
10
+ #include "GrGeometryProcessor.h"
11
+ #include "GrInvariantOutput.h"
12
+ #include "GrMemoryPool.h"
13
+ #include "GrXferProcessor.h"
14
+ #include "SkSpinlock.h"
15
+
16
+ #if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
17
+
18
+ class GrFragmentProcessor;
19
+ class GrGeometryProcessor;
20
+
21
+ /*
22
+ * Originally these were both in the processor unit test header, but then it seemed to cause linker
23
+ * problems on android.
24
+ */
25
+ template<>
26
+ SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true>*
27
+ GrProcessorTestFactory<GrFragmentProcessor>::GetFactories() {
28
+ static SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true> gFactories;
29
+ return &gFactories;
30
+ }
31
+
32
+ template<>
33
+ SkTArray<GrProcessorTestFactory<GrXPFactory>*, true>*
34
+ GrProcessorTestFactory<GrXPFactory>::GetFactories() {
35
+ static SkTArray<GrProcessorTestFactory<GrXPFactory>*, true> gFactories;
36
+ return &gFactories;
37
+ }
38
+
39
+ template<>
40
+ SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true>*
41
+ GrProcessorTestFactory<GrGeometryProcessor>::GetFactories() {
42
+ static SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true> gFactories;
43
+ return &gFactories;
44
+ }
45
+
46
+ /*
47
+ * To ensure we always have successful static initialization, before creating from the factories
48
+ * we verify the count is as expected. If a new factory is added, then these numbers must be
49
+ * manually adjusted.
50
+ */
51
+ static const int kFPFactoryCount = 40;
52
+ static const int kGPFactoryCount = 14;
53
+ static const int kXPFactoryCount = 6;
54
+
55
+ template<>
56
+ void GrProcessorTestFactory<GrFragmentProcessor>::VerifyFactoryCount() {
57
+ if (kFPFactoryCount != GetFactories()->count()) {
58
+ SkFAIL("Wrong number of fragment processor factories!");
59
+ }
60
+ }
61
+
62
+ template<>
63
+ void GrProcessorTestFactory<GrGeometryProcessor>::VerifyFactoryCount() {
64
+ if (kGPFactoryCount != GetFactories()->count()) {
65
+ SkFAIL("Wrong number of geometry processor factories!");
66
+ }
67
+ }
68
+
69
+ template<>
70
+ void GrProcessorTestFactory<GrXPFactory>::VerifyFactoryCount() {
71
+ if (kXPFactoryCount != GetFactories()->count()) {
72
+ SkFAIL("Wrong number of xp factory factories!");
73
+ }
74
+ }
75
+
76
+ #endif
77
+
78
+
79
+ // We use a global pool protected by a mutex(spinlock). Chrome may use the same GrContext on
80
+ // different threads. The GrContext is not used concurrently on different threads and there is a
81
+ // memory barrier between accesses of a context on different threads. Also, there may be multiple
82
+ // GrContexts and those contexts may be in use concurrently on different threads.
83
+ namespace {
84
+ static SkSpinlock gProcessorSpinlock;
85
+ class MemoryPoolAccessor {
86
+ public:
87
+ MemoryPoolAccessor() { gProcessorSpinlock.acquire(); }
88
+
89
+ ~MemoryPoolAccessor() { gProcessorSpinlock.release(); }
90
+
91
+ GrMemoryPool* pool() const {
92
+ static GrMemoryPool gPool(4096, 4096);
93
+ return &gPool;
94
+ }
95
+ };
96
+ }
97
+
98
+ int32_t GrProcessor::gCurrProcessorClassID = GrProcessor::kIllegalProcessorClassID;
99
+
100
+ ///////////////////////////////////////////////////////////////////////////////
101
+
102
+ GrProcessor::~GrProcessor() {}
103
+
104
+ void GrProcessor::addTextureAccess(const GrTextureAccess* access) {
105
+ fTextureAccesses.push_back(access);
106
+ this->addGpuResource(access->getProgramTexture());
107
+ }
108
+
109
+ void GrProcessor::addBufferAccess(const GrBufferAccess* access) {
110
+ fBufferAccesses.push_back(access);
111
+ this->addGpuResource(access->getProgramBuffer());
112
+ }
113
+
114
+ void* GrProcessor::operator new(size_t size) {
115
+ return MemoryPoolAccessor().pool()->allocate(size);
116
+ }
117
+
118
+ void GrProcessor::operator delete(void* target) {
119
+ return MemoryPoolAccessor().pool()->release(target);
120
+ }
121
+
122
+ bool GrProcessor::hasSameSamplers(const GrProcessor& that) const {
123
+ if (this->numTextures() != that.numTextures() || this->numBuffers() != that.numBuffers()) {
124
+ return false;
125
+ }
126
+ for (int i = 0; i < this->numTextures(); ++i) {
127
+ if (this->textureAccess(i) != that.textureAccess(i)) {
128
+ return false;
129
+ }
130
+ }
131
+ for (int i = 0; i < this->numBuffers(); ++i) {
132
+ if (this->bufferAccess(i) != that.bufferAccess(i)) {
133
+ return false;
134
+ }
135
+ }
136
+ return true;
137
+ }
138
+
139
+ ///////////////////////////////////////////////////////////////////////////////////////////////////
140
+
141
+ // Initial static variable from GrXPFactory
142
+ int32_t GrXPFactory::gCurrXPFClassID =
143
+ GrXPFactory::kIllegalXPFClassID;
pool/shard001/C++/0017143_binarycontourimagefilter.cpp ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /***********************************************************************************
2
+ * *
3
+ * Voreen - The Volume Rendering Engine *
4
+ * *
5
+ * Copyright (C) 2005-2013 University of Muenster, Germany. *
6
+ * Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
7
+ * For a list of authors please refer to the file "CREDITS.txt". *
8
+ * *
9
+ * This file is part of the Voreen software package. Voreen is free software: *
10
+ * you can redistribute it and/or modify it under the terms of the GNU General *
11
+ * Public License version 2 as published by the Free Software Foundation. *
12
+ * *
13
+ * Voreen is distributed in the hope that it will be useful, but WITHOUT ANY *
14
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR *
15
+ * A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
16
+ * *
17
+ * You should have received a copy of the GNU General Public License in the file *
18
+ * "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
19
+ * *
20
+ * For non-commercial academic use see the license exception specified in the file *
21
+ * "LICENSE-academic.txt". To get information about commercial licensing please *
22
+ * contact the authors. *
23
+ * *
24
+ ***********************************************************************************/
25
+
26
+ #include "binarycontourimagefilter.h"
27
+ #include "voreen/core/datastructures/volume/volumeram.h"
28
+ #include "voreen/core/datastructures/volume/volume.h"
29
+ #include "voreen/core/datastructures/volume/volumeatomic.h"
30
+ #include "voreen/core/ports/conditions/portconditionvolumetype.h"
31
+ #include "modules/itk/utils/itkwrapper.h"
32
+ #include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h"
33
+ #include "itkImage.h"
34
+
35
+ #include "itkBinaryContourImageFilter.h"
36
+
37
+ #include <iostream>
38
+
39
+ namespace voreen {
40
+
41
+ const std::string BinaryContourImageFilterITK::loggerCat_("voreen.BinaryContourImageFilterITK");
42
+
43
+ BinaryContourImageFilterITK::BinaryContourImageFilterITK()
44
+ : ITKProcessor(),
45
+ inport1_(Port::INPORT, "InputImage"),
46
+ outport1_(Port::OUTPORT, "OutputImage"),
47
+ enableProcessing_("enabled", "Enable", false),
48
+ fullyConnected_("fullyConnected", "FullyConnected", false),
49
+ backgroundValue_("backgroundValue", "BackgroundValue"),
50
+ foregroundValue_("foregroundValue", "ForegroundValue")
51
+ {
52
+ addPort(inport1_);
53
+ PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr();
54
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8());
55
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8());
56
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16());
57
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16());
58
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32());
59
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32());
60
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat());
61
+ orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble());
62
+ inport1_.addCondition(orCondition1);
63
+ addPort(outport1_);
64
+
65
+ addProperty(enableProcessing_);
66
+ addProperty(fullyConnected_);
67
+ addProperty(backgroundValue_);
68
+ addProperty(foregroundValue_);
69
+
70
+ }
71
+
72
+ Processor* BinaryContourImageFilterITK::create() const {
73
+ return new BinaryContourImageFilterITK();
74
+ }
75
+
76
+ template<class T>
77
+ void BinaryContourImageFilterITK::binaryContourImageFilterITK() {
78
+ backgroundValue_.setVolume(inport1_.getData());
79
+ foregroundValue_.setVolume(inport1_.getData());
80
+
81
+ if (!enableProcessing_.get()) {
82
+ outport1_.setData(inport1_.getData(), false);
83
+ return;
84
+ }
85
+
86
+ typedef itk::Image<T, 3> InputImageType1;
87
+ typedef itk::Image<T, 3> OutputImageType1;
88
+
89
+ typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData());
90
+
91
+
92
+ //Filter define
93
+ typedef itk::BinaryContourImageFilter<InputImageType1, OutputImageType1> FilterType;
94
+ typename FilterType::Pointer filter = FilterType::New();
95
+
96
+ filter->SetInput(p1);
97
+
98
+ filter->SetFullyConnected(fullyConnected_.get());
99
+ filter->SetBackgroundValue(backgroundValue_.getValue<T>());
100
+ filter->SetForegroundValue(foregroundValue_.getValue<T>());
101
+
102
+
103
+ observe(filter.GetPointer());
104
+
105
+ try
106
+ {
107
+ filter->Update();
108
+
109
+ }
110
+ catch (itk::ExceptionObject &e)
111
+ {
112
+ LERROR(e);
113
+ }
114
+
115
+
116
+ Volume* outputVolume1 = 0;
117
+ outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput());
118
+
119
+ if (outputVolume1) {
120
+ transferRWM(inport1_.getData(), outputVolume1);
121
+ transferTransformation(inport1_.getData(), outputVolume1);
122
+ outport1_.setData(outputVolume1);
123
+ } else
124
+ outport1_.setData(0);
125
+
126
+
127
+
128
+ }
129
+
130
+
131
+
132
+
133
+ void BinaryContourImageFilterITK::process() {
134
+ const VolumeBase* inputHandle1 = inport1_.getData();
135
+ const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>();
136
+
137
+ if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) {
138
+ binaryContourImageFilterITK<uint8_t>();
139
+ }
140
+ else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) {
141
+ binaryContourImageFilterITK<int8_t>();
142
+ }
143
+ else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) {
144
+ binaryContourImageFilterITK<uint16_t>();
145
+ }
146
+ else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) {
147
+ binaryContourImageFilterITK<int16_t>();
148
+ }
149
+ else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) {
150
+ binaryContourImageFilterITK<uint32_t>();
151
+ }
152
+ else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) {
153
+ binaryContourImageFilterITK<int32_t>();
154
+ }
155
+ else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) {
156
+ binaryContourImageFilterITK<float>();
157
+ }
158
+ else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) {
159
+ binaryContourImageFilterITK<double>();
160
+ }
161
+ else {
162
+ LERROR("Inputformat of Volume 1 is not supported!");
163
+ }
164
+
165
+ }
166
+
167
+
168
+ } // namespace
pool/shard001/C++/0017150_pow_valarray_value.pass.cpp ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ // <valarray>
10
+
11
+ // template<class T> class valarray;
12
+
13
+ // template<class T>
14
+ // valarray<T>
15
+ // pow(const valarray<T>& x, const T& y);
16
+
17
+ #include <valarray>
18
+ #include <cassert>
19
+ #include <sstream>
20
+ #include <cstddef>
21
+
22
+ #include "test_macros.h"
23
+
24
+ bool is_about(double x, double y, int p)
25
+ {
26
+ std::ostringstream o;
27
+ o.precision(p);
28
+ scientific(o);
29
+ o << x;
30
+ std::string a = o.str();
31
+ o.str("");
32
+ o << y;
33
+ return a == o.str();
34
+ }
35
+
36
+ int main(int, char**)
37
+ {
38
+ {
39
+ typedef double T;
40
+ T a1[] = {.9, .5, 0., .5, .75};
41
+ T a3[] = {8.1000000000000005e-01,
42
+ 2.5000000000000000e-01,
43
+ 0.0000000000000000e+00,
44
+ 2.5000000000000000e-01,
45
+ 5.6250000000000000e-01};
46
+ const unsigned N = sizeof(a1)/sizeof(a1[0]);
47
+ std::valarray<T> v1(a1, N);
48
+ std::valarray<T> v3 = pow(v1, 2.0);
49
+ assert(v3.size() == v1.size());
50
+ for (std::size_t i = 0; i < v3.size(); ++i)
51
+ assert(is_about(v3[i], a3[i], 10));
52
+ }
53
+
54
+ return 0;
55
+ }
pool/shard001/C++/0017153_optimized_test.cpp ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
2
+
3
+ #include <vespa/vespalib/testkit/testapp.h>
4
+ #include <vespa/vespalib/util/optimized.h>
5
+
6
+ using namespace vespalib;
7
+
8
+ class Test : public vespalib::TestApp
9
+ {
10
+ private:
11
+ template<typename T>
12
+ void testMsbIdx();
13
+ template<typename T>
14
+ void testLsbIdx();
15
+ template<typename T>
16
+ void testPopCount();
17
+ public:
18
+ int Main() override;
19
+ };
20
+
21
+ template<typename T>
22
+ void Test::testMsbIdx()
23
+ {
24
+ EXPECT_EQUAL(Optimized::msbIdx(T(0)), 0);
25
+ EXPECT_EQUAL(Optimized::msbIdx(T(1)), 0);
26
+ EXPECT_EQUAL(Optimized::msbIdx(T(-1)), int(sizeof(T)*8 - 1));
27
+ T v(static_cast<T>(-1));
28
+ for (size_t i(0); i < sizeof(T); i++) {
29
+ for (size_t j(0); j < 8; j++) {
30
+ EXPECT_EQUAL(Optimized::msbIdx(v), int(sizeof(T)*8 - (i*8+j) - 1));
31
+ v = v >> 1;
32
+ }
33
+ }
34
+ }
35
+
36
+ template<typename T>
37
+ void Test::testLsbIdx()
38
+ {
39
+ EXPECT_EQUAL(Optimized::lsbIdx(T(0)), 0);
40
+ EXPECT_EQUAL(Optimized::lsbIdx(T(1)), 0);
41
+ EXPECT_EQUAL(Optimized::lsbIdx(T(T(1)<<(sizeof(T)*8 - 1))), int(sizeof(T)*8 - 1));
42
+ EXPECT_EQUAL(Optimized::lsbIdx(T(-1)), 0);
43
+ T v(static_cast<T>(-1));
44
+ for (size_t i(0); i < sizeof(T); i++) {
45
+ for (size_t j(0); j < 8; j++) {
46
+ EXPECT_EQUAL(Optimized::lsbIdx(v), int(i*8+j));
47
+ v = v << 1;
48
+ }
49
+ }
50
+ }
51
+
52
+ template<typename T>
53
+ void Test::testPopCount()
54
+ {
55
+ EXPECT_EQUAL(0, Optimized::popCount(T(0)));
56
+ EXPECT_EQUAL(1, Optimized::popCount(T(1)));
57
+ EXPECT_EQUAL(int(8 * sizeof(T)), Optimized::popCount(T(-1)));
58
+ }
59
+
60
+ int Test::Main()
61
+ {
62
+ TEST_INIT("optimized_test");
63
+
64
+ testMsbIdx<unsigned int>();
65
+ testMsbIdx<unsigned long>();
66
+ testMsbIdx<unsigned long long>();
67
+
68
+ TEST_FLUSH();
69
+ testLsbIdx<unsigned int>();
70
+ testLsbIdx<unsigned long>();
71
+ testLsbIdx<unsigned long long>();
72
+
73
+ TEST_FLUSH();
74
+ testPopCount<unsigned int>();
75
+ testPopCount<unsigned long>();
76
+ testPopCount<unsigned long long>();
77
+
78
+ TEST_FLUSH();
79
+ TEST_DONE();
80
+ }
81
+
82
+ TEST_APPHOOK(Test)
pool/shard001/C++/0017155_ir_function_detect_recursion.cpp ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright © 2011 Intel Corporation
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a
5
+ * copy of this software and associated documentation files (the "Software"),
6
+ * to deal in the Software without restriction, including without limitation
7
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8
+ * and/or sell copies of the Software, and to permit persons to whom the
9
+ * Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice (including the next
12
+ * paragraph) shall be included in all copies or substantial portions of the
13
+ * Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
+ * DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ /**
25
+ * \file ir_function_detect_recursion.cpp
26
+ * Determine whether a shader contains static recursion.
27
+ *
28
+ * Consider the (possibly disjoint) graph of function calls in a shader. If a
29
+ * program contains recursion, this graph will contain a cycle. If a function
30
+ * is part of a cycle, it will have a caller and it will have a callee (it
31
+ * calls another function).
32
+ *
33
+ * To detect recursion, the function call graph is constructed. The graph is
34
+ * repeatedly reduced by removing any function that either has no callees
35
+ * (leaf functions) or has no caller. Eventually the only functions that
36
+ * remain will be the functions in the cycles.
37
+ *
38
+ * The GLSL spec is a bit wishy-washy about recursion.
39
+ *
40
+ * From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:
41
+ *
42
+ * "Behavior is undefined if recursion is used. Recursion means having any
43
+ * function appearing more than once at any one time in the run-time stack
44
+ * of function calls. That is, a function may not call itself either
45
+ * directly or indirectly. Compilers may give diagnostic messages when
46
+ * this is detectable at compile time, but not all such cases can be
47
+ * detected at compile time."
48
+ *
49
+ * From page 79 (page 85 of the PDF):
50
+ *
51
+ * "22) Should recursion be supported?
52
+ *
53
+ * DISCUSSION: Probably not necessary, but another example of limiting
54
+ * the language based on how it would directly map to hardware. One
55
+ * thought is that recursion would benefit ray tracing shaders. On the
56
+ * other hand, many recursion operations can also be implemented with the
57
+ * user managing the recursion through arrays. RenderMan doesn't support
58
+ * recursion. This could be added at a later date, if it proved to be
59
+ * necessary.
60
+ *
61
+ * RESOLVED on September 10, 2002: Implementations are not required to
62
+ * support recursion.
63
+ *
64
+ * CLOSED on September 10, 2002."
65
+ *
66
+ * From page 79 (page 85 of the PDF):
67
+ *
68
+ * "56) Is it an error for an implementation to support recursion if the
69
+ * specification says recursion is not supported?
70
+ *
71
+ * ADDED on September 10, 2002.
72
+ *
73
+ * DISCUSSION: This issues is related to Issue (22). If we say that
74
+ * recursion (or some other piece of functionality) is not supported, is
75
+ * it an error for an implementation to support it? Perhaps the
76
+ * specification should remain silent on these kind of things so that they
77
+ * could be gracefully added later as an extension or as part of the
78
+ * standard.
79
+ *
80
+ * RESOLUTION: Languages, in general, have programs that are not
81
+ * well-formed in ways a compiler cannot detect. Portability is only
82
+ * ensured for well-formed programs. Detecting recursion is an example of
83
+ * this. The language will say a well-formed program may not recurse, but
84
+ * compilers are not forced to detect that recursion may happen.
85
+ *
86
+ * CLOSED: November 29, 2002."
87
+ *
88
+ * In GLSL 1.10 the behavior of recursion is undefined. Compilers don't have
89
+ * to reject shaders (at compile-time or link-time) that contain recursion.
90
+ * Instead they could work, or crash, or kill a kitten.
91
+ *
92
+ * From page 44 (page 50 of the PDF) of the GLSL 1.20 spec:
93
+ *
94
+ * "Recursion is not allowed, not even statically. Static recursion is
95
+ * present if the static function call graph of the program contains
96
+ * cycles."
97
+ *
98
+ * This langauge clears things up a bit, but it still leaves a lot of
99
+ * questions unanswered.
100
+ *
101
+ * - Is the error generated at compile-time or link-time?
102
+ *
103
+ * - Is it an error to have a recursive function that is never statically
104
+ * called by main or any function called directly or indirectly by main?
105
+ * Technically speaking, such a function is not in the "static function
106
+ * call graph of the program" at all.
107
+ *
108
+ * \bug
109
+ * If a shader has multiple cycles, this algorithm may erroneously complain
110
+ * about functions that aren't in any cycle, but are in the part of the call
111
+ * tree that connects them. For example, if the call graph consists of a
112
+ * cycle between A and B, and a cycle between D and E, and B also calls C
113
+ * which calls D, then this algorithm will report C as a function which "has
114
+ * static recursion" even though it is not part of any cycle.
115
+ *
116
+ * A better algorithm for cycle detection that doesn't have this drawback can
117
+ * be found here:
118
+ *
119
+ * http://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm
120
+ *
121
+ * \author Ian Romanick <ian.d.romanick@intel.com>
122
+ */
123
+ #include "main/core.h"
124
+ #include "ir.h"
125
+ #include "glsl_parser_extras.h"
126
+ #include "linker.h"
127
+ #include "program/hash_table.h"
128
+ #include "program.h"
129
+
130
+ struct call_node : public exec_node {
131
+ class function *func;
132
+ };
133
+
134
+ class function {
135
+ public:
136
+ function(ir_function_signature *sig)
137
+ : sig(sig)
138
+ {
139
+ /* empty */
140
+ }
141
+
142
+
143
+ /* Callers of this ralloc-based new need not call delete. It's
144
+ * easier to just ralloc_free 'ctx' (or any of its ancestors). */
145
+ static void* operator new(size_t size, void *ctx)
146
+ {
147
+ void *node;
148
+
149
+ node = ralloc_size(ctx, size);
150
+ assert(node != NULL);
151
+
152
+ return node;
153
+ }
154
+
155
+ /* If the user *does* call delete, that's OK, we will just
156
+ * ralloc_free in that case. */
157
+ static void operator delete(void *node)
158
+ {
159
+ ralloc_free(node);
160
+ }
161
+
162
+ ir_function_signature *sig;
163
+
164
+ /** List of functions called by this function. */
165
+ exec_list callees;
166
+
167
+ /** List of functions that call this function. */
168
+ exec_list callers;
169
+ };
170
+
171
+ class has_recursion_visitor : public ir_hierarchical_visitor {
172
+ public:
173
+ has_recursion_visitor()
174
+ : current(NULL)
175
+ {
176
+ progress = false;
177
+ this->mem_ctx = ralloc_context(NULL);
178
+ this->function_hash = hash_table_ctor(0, hash_table_pointer_hash,
179
+ hash_table_pointer_compare);
180
+ }
181
+
182
+ ~has_recursion_visitor()
183
+ {
184
+ hash_table_dtor(this->function_hash);
185
+ ralloc_free(this->mem_ctx);
186
+ }
187
+
188
+ function *get_function(ir_function_signature *sig)
189
+ {
190
+ function *f = (function *) hash_table_find(this->function_hash, sig);
191
+ if (f == NULL) {
192
+ f = new(mem_ctx) function(sig);
193
+ hash_table_insert(this->function_hash, f, sig);
194
+ }
195
+
196
+ return f;
197
+ }
198
+
199
+ virtual ir_visitor_status visit_enter(ir_function_signature *sig)
200
+ {
201
+ this->current = this->get_function(sig);
202
+ return visit_continue;
203
+ }
204
+
205
+ virtual ir_visitor_status visit_leave(ir_function_signature *sig)
206
+ {
207
+ (void) sig;
208
+ this->current = NULL;
209
+ return visit_continue;
210
+ }
211
+
212
+ virtual ir_visitor_status visit_enter(ir_call *call)
213
+ {
214
+ /* At global scope this->current will be NULL. Since there is no way to
215
+ * call global scope, it can never be part of a cycle. Don't bother
216
+ * adding calls from global scope to the graph.
217
+ */
218
+ if (this->current == NULL)
219
+ return visit_continue;
220
+
221
+ function *const target = this->get_function(call->callee);
222
+
223
+ /* Create a link from the caller to the callee.
224
+ */
225
+ call_node *node = new(mem_ctx) call_node;
226
+ node->func = target;
227
+ this->current->callees.push_tail(node);
228
+
229
+ /* Create a link from the callee to the caller.
230
+ */
231
+ node = new(mem_ctx) call_node;
232
+ node->func = this->current;
233
+ target->callers.push_tail(node);
234
+ return visit_continue;
235
+ }
236
+
237
+ function *current;
238
+ struct hash_table *function_hash;
239
+ void *mem_ctx;
240
+ bool progress;
241
+ };
242
+
243
+ static void
244
+ destroy_links(exec_list *list, function *f)
245
+ {
246
+ foreach_list_safe(node, list) {
247
+ struct call_node *n = (struct call_node *) node;
248
+
249
+ /* If this is the right function, remove it. Note that the loop cannot
250
+ * terminate now. There can be multiple links to a function if it is
251
+ * either called multiple times or calls multiple times.
252
+ */
253
+ if (n->func == f)
254
+ n->remove();
255
+ }
256
+ }
257
+
258
+
259
+ /**
260
+ * Remove a function if it has either no in or no out links
261
+ */
262
+ static void
263
+ remove_unlinked_functions(const void *key, void *data, void *closure)
264
+ {
265
+ has_recursion_visitor *visitor = (has_recursion_visitor *) closure;
266
+ function *f = (function *) data;
267
+
268
+ if (f->callers.is_empty() || f->callees.is_empty()) {
269
+ while (!f->callers.is_empty()) {
270
+ struct call_node *n = (struct call_node *) f->callers.pop_head();
271
+ destroy_links(& n->func->callees, f);
272
+ }
273
+
274
+ while (!f->callees.is_empty()) {
275
+ struct call_node *n = (struct call_node *) f->callees.pop_head();
276
+ destroy_links(& n->func->callers, f);
277
+ }
278
+
279
+ hash_table_remove(visitor->function_hash, key);
280
+ visitor->progress = true;
281
+ }
282
+ }
283
+
284
+
285
+ static void
286
+ emit_errors_unlinked(const void *key, void *data, void *closure)
287
+ {
288
+ struct _mesa_glsl_parse_state *state =
289
+ (struct _mesa_glsl_parse_state *) closure;
290
+ function *f = (function *) data;
291
+ YYLTYPE loc;
292
+
293
+ (void) key;
294
+
295
+ char *proto = prototype_string(f->sig->return_type,
296
+ f->sig->function_name(),
297
+ &f->sig->parameters);
298
+
299
+ memset(&loc, 0, sizeof(loc));
300
+ _mesa_glsl_error(&loc, state,
301
+ "function `%s' has static recursion.",
302
+ proto);
303
+ ralloc_free(proto);
304
+ }
305
+
306
+
307
+ static void
308
+ emit_errors_linked(const void *key, void *data, void *closure)
309
+ {
310
+ struct gl_shader_program *prog =
311
+ (struct gl_shader_program *) closure;
312
+ function *f = (function *) data;
313
+
314
+ (void) key;
315
+
316
+ char *proto = prototype_string(f->sig->return_type,
317
+ f->sig->function_name(),
318
+ &f->sig->parameters);
319
+
320
+ linker_error(prog, "function `%s' has static recursion.\n", proto);
321
+ ralloc_free(proto);
322
+ prog->LinkStatus = false;
323
+ }
324
+
325
+
326
+ void
327
+ detect_recursion_unlinked(struct _mesa_glsl_parse_state *state,
328
+ exec_list *instructions)
329
+ {
330
+ has_recursion_visitor v;
331
+
332
+ /* Collect all of the information about which functions call which other
333
+ * functions.
334
+ */
335
+ v.run(instructions);
336
+
337
+ /* Remove from the set all of the functions that either have no caller or
338
+ * call no other functions. Repeat until no functions are removed.
339
+ */
340
+ do {
341
+ v.progress = false;
342
+ hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);
343
+ } while (v.progress);
344
+
345
+
346
+ /* At this point any functions still in the hash must be part of a cycle.
347
+ */
348
+ hash_table_call_foreach(v.function_hash, emit_errors_unlinked, state);
349
+ }
350
+
351
+
352
+ void
353
+ detect_recursion_linked(struct gl_shader_program *prog,
354
+ exec_list *instructions)
355
+ {
356
+ has_recursion_visitor v;
357
+
358
+ /* Collect all of the information about which functions call which other
359
+ * functions.
360
+ */
361
+ v.run(instructions);
362
+
363
+ /* Remove from the set all of the functions that either have no caller or
364
+ * call no other functions. Repeat until no functions are removed.
365
+ */
366
+ do {
367
+ v.progress = false;
368
+ hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);
369
+ } while (v.progress);
370
+
371
+
372
+ /* At this point any functions still in the hash must be part of a cycle.
373
+ */
374
+ hash_table_call_foreach(v.function_hash, emit_errors_linked, prog);
375
+ }
pool/shard001/C++/0017157_print_string.cpp ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*************************************************************************/
2
+ /* print_string.cpp */
3
+ /*************************************************************************/
4
+ /* This file is part of: */
5
+ /* GODOT ENGINE */
6
+ /* http://www.godotengine.org */
7
+ /*************************************************************************/
8
+ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
9
+ /* */
10
+ /* Permission is hereby granted, free of charge, to any person obtaining */
11
+ /* a copy of this software and associated documentation files (the */
12
+ /* "Software"), to deal in the Software without restriction, including */
13
+ /* without limitation the rights to use, copy, modify, merge, publish, */
14
+ /* distribute, sublicense, and/or sell copies of the Software, and to */
15
+ /* permit persons to whom the Software is furnished to do so, subject to */
16
+ /* the following conditions: */
17
+ /* */
18
+ /* The above copyright notice and this permission notice shall be */
19
+ /* included in all copies or substantial portions of the Software. */
20
+ /* */
21
+ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
22
+ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
23
+ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
24
+ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
25
+ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
26
+ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
27
+ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
28
+ /*************************************************************************/
29
+ #include "print_string.h"
30
+ #include "os/os.h"
31
+ #include <stdio.h>
32
+
33
+ static PrintHandlerList *print_handler_list=NULL;
34
+ bool _print_line_enabled=true;
35
+ bool _print_error_enabled = true;
36
+
37
+ void add_print_handler(PrintHandlerList *p_handler) {
38
+
39
+ _global_lock();
40
+ p_handler->next=print_handler_list;
41
+ print_handler_list=p_handler;
42
+ _global_unlock();
43
+ }
44
+
45
+ void remove_print_handler(PrintHandlerList *p_handler) {
46
+
47
+ _global_lock();
48
+
49
+ PrintHandlerList *prev = NULL;
50
+ PrintHandlerList *l = print_handler_list;
51
+
52
+ while(l) {
53
+
54
+ if (l==p_handler) {
55
+
56
+ if (prev)
57
+ prev->next=l->next;
58
+ else
59
+ print_handler_list=l->next;
60
+ break;
61
+ }
62
+ prev=l;
63
+ l=l->next;
64
+
65
+ }
66
+ //OS::get_singleton()->print("print handler list is %p\n",print_handler_list);
67
+
68
+ ERR_FAIL_COND(l==NULL);
69
+ _global_unlock();
70
+
71
+ }
72
+
73
+
74
+ void print_line(String p_string) {
75
+
76
+ if (!_print_line_enabled)
77
+ return;
78
+
79
+ OS::get_singleton()->print("%s\n",p_string.utf8().get_data());
80
+
81
+ _global_lock();
82
+ PrintHandlerList *l = print_handler_list;
83
+ while(l) {
84
+
85
+ l->printfunc(l->userdata,p_string);
86
+ l=l->next;
87
+ }
88
+
89
+ _global_unlock();
90
+
91
+ }
pool/shard001/C++/0017164_quic_sent_packet_manager_peer.cc ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 "net/quic/test_tools/quic_sent_packet_manager_peer.h"
6
+
7
+ #include "base/stl_util.h"
8
+ #include "net/quic/congestion_control/loss_detection_interface.h"
9
+ #include "net/quic/congestion_control/send_algorithm_interface.h"
10
+ #include "net/quic/quic_flags.h"
11
+ #include "net/quic/quic_protocol.h"
12
+ #include "net/quic/quic_sent_packet_manager.h"
13
+
14
+ namespace net {
15
+ namespace test {
16
+
17
+ // static
18
+ size_t QuicSentPacketManagerPeer::GetMaxTailLossProbes(
19
+ QuicSentPacketManager* sent_packet_manager) {
20
+ return sent_packet_manager->max_tail_loss_probes_;
21
+ }
22
+
23
+ // static
24
+ void QuicSentPacketManagerPeer::SetMaxTailLossProbes(
25
+ QuicSentPacketManager* sent_packet_manager,
26
+ size_t max_tail_loss_probes) {
27
+ sent_packet_manager->max_tail_loss_probes_ = max_tail_loss_probes;
28
+ }
29
+
30
+ // static
31
+ bool QuicSentPacketManagerPeer::GetEnableHalfRttTailLossProbe(
32
+ QuicSentPacketManager* sent_packet_manager) {
33
+ return sent_packet_manager->enable_half_rtt_tail_loss_probe_;
34
+ }
35
+
36
+ // static
37
+ bool QuicSentPacketManagerPeer::GetUseNewRto(
38
+ QuicSentPacketManager* sent_packet_manager) {
39
+ return sent_packet_manager->use_new_rto_;
40
+ }
41
+
42
+ // static
43
+ QuicByteCount QuicSentPacketManagerPeer::GetReceiveWindow(
44
+ QuicSentPacketManager* sent_packet_manager) {
45
+ return sent_packet_manager->receive_buffer_bytes_;
46
+ }
47
+
48
+ // static
49
+ void QuicSentPacketManagerPeer::SetPerspective(
50
+ QuicSentPacketManager* sent_packet_manager,
51
+ Perspective perspective) {
52
+ sent_packet_manager->perspective_ = perspective;
53
+ }
54
+
55
+ // static
56
+ const SendAlgorithmInterface* QuicSentPacketManagerPeer::GetSendAlgorithm(
57
+ const QuicSentPacketManager& sent_packet_manager) {
58
+ return sent_packet_manager.send_algorithm_.get();
59
+ }
60
+
61
+ // static
62
+ void QuicSentPacketManagerPeer::SetSendAlgorithm(
63
+ QuicSentPacketManager* sent_packet_manager,
64
+ SendAlgorithmInterface* send_algorithm) {
65
+ sent_packet_manager->send_algorithm_.reset(send_algorithm);
66
+ }
67
+
68
+ // static
69
+ const LossDetectionInterface* QuicSentPacketManagerPeer::GetLossAlgorithm(
70
+ QuicSentPacketManager* sent_packet_manager) {
71
+ return sent_packet_manager->loss_algorithm_.get();
72
+ }
73
+
74
+ // static
75
+ void QuicSentPacketManagerPeer::SetLossAlgorithm(
76
+ QuicSentPacketManager* sent_packet_manager,
77
+ LossDetectionInterface* loss_detector) {
78
+ sent_packet_manager->loss_algorithm_.reset(loss_detector);
79
+ }
80
+
81
+ // static
82
+ RttStats* QuicSentPacketManagerPeer::GetRttStats(
83
+ QuicSentPacketManager* sent_packet_manager) {
84
+ return &sent_packet_manager->rtt_stats_;
85
+ }
86
+
87
+ // static
88
+ bool QuicSentPacketManagerPeer::HasPendingPackets(
89
+ const QuicSentPacketManager* sent_packet_manager) {
90
+ return sent_packet_manager->unacked_packets_.HasInFlightPackets();
91
+ }
92
+
93
+ // static
94
+ QuicTime QuicSentPacketManagerPeer::GetSentTime(
95
+ const QuicSentPacketManager* sent_packet_manager,
96
+ QuicPacketNumber packet_number) {
97
+ DCHECK(sent_packet_manager->unacked_packets_.IsUnacked(packet_number));
98
+
99
+ return sent_packet_manager->unacked_packets_.GetTransmissionInfo(
100
+ packet_number)
101
+ .sent_time;
102
+ }
103
+
104
+ // static
105
+ bool QuicSentPacketManagerPeer::IsRetransmission(
106
+ QuicSentPacketManager* sent_packet_manager,
107
+ QuicPacketNumber packet_number) {
108
+ DCHECK(sent_packet_manager->HasRetransmittableFrames(packet_number));
109
+ if (FLAGS_quic_track_single_retransmission) {
110
+ if (!sent_packet_manager->HasRetransmittableFrames(packet_number)) {
111
+ return false;
112
+ }
113
+ for (auto transmission_info : sent_packet_manager->unacked_packets_) {
114
+ if (transmission_info.retransmission == packet_number) {
115
+ return true;
116
+ }
117
+ }
118
+ return false;
119
+ }
120
+ return sent_packet_manager->HasRetransmittableFrames(packet_number) &&
121
+ sent_packet_manager->unacked_packets_.GetTransmissionInfo(
122
+ packet_number)
123
+ .all_transmissions != nullptr;
124
+ }
125
+
126
+ // static
127
+ void QuicSentPacketManagerPeer::MarkForRetransmission(
128
+ QuicSentPacketManager* sent_packet_manager,
129
+ QuicPacketNumber packet_number,
130
+ TransmissionType transmission_type) {
131
+ sent_packet_manager->MarkForRetransmission(packet_number, transmission_type);
132
+ }
133
+
134
+ // static
135
+ QuicTime::Delta QuicSentPacketManagerPeer::GetRetransmissionDelay(
136
+ const QuicSentPacketManager* sent_packet_manager) {
137
+ return sent_packet_manager->GetRetransmissionDelay();
138
+ }
139
+
140
+ // static
141
+ bool QuicSentPacketManagerPeer::HasUnackedCryptoPackets(
142
+ const QuicSentPacketManager* sent_packet_manager) {
143
+ return sent_packet_manager->unacked_packets_.HasPendingCryptoPackets();
144
+ }
145
+
146
+ // static
147
+ size_t QuicSentPacketManagerPeer::GetNumRetransmittablePackets(
148
+ const QuicSentPacketManager* sent_packet_manager) {
149
+ size_t num_unacked_packets = 0;
150
+ for (QuicUnackedPacketMap::const_iterator it =
151
+ sent_packet_manager->unacked_packets_.begin();
152
+ it != sent_packet_manager->unacked_packets_.end(); ++it) {
153
+ if (it->retransmittable_frames != nullptr) {
154
+ ++num_unacked_packets;
155
+ }
156
+ }
157
+ return num_unacked_packets;
158
+ }
159
+
160
+ // static
161
+ QuicByteCount QuicSentPacketManagerPeer::GetBytesInFlight(
162
+ const QuicSentPacketManager* sent_packet_manager) {
163
+ return sent_packet_manager->unacked_packets_.bytes_in_flight();
164
+ }
165
+
166
+ // static
167
+ QuicSentPacketManager::NetworkChangeVisitor*
168
+ QuicSentPacketManagerPeer::GetNetworkChangeVisitor(
169
+ const QuicSentPacketManager* sent_packet_manager) {
170
+ return sent_packet_manager->network_change_visitor_;
171
+ }
172
+
173
+ // static
174
+ QuicSustainedBandwidthRecorder& QuicSentPacketManagerPeer::GetBandwidthRecorder(
175
+ QuicSentPacketManager* sent_packet_manager) {
176
+ return sent_packet_manager->sustained_bandwidth_recorder_;
177
+ }
178
+
179
+ } // namespace test
180
+ } // namespace net
pool/shard001/C++/0017166_profile_window.cc ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 "chrome/browser/profiles/profile_window.h"
6
+
7
+ #include "base/command_line.h"
8
+ #include "base/files/file_path.h"
9
+ #include "chrome/browser/browser_process.h"
10
+ #include "chrome/browser/profiles/profile.h"
11
+ #include "chrome/browser/profiles/profile_manager.h"
12
+ #include "chrome/browser/ui/browser.h"
13
+ #include "chrome/browser/ui/browser_dialogs.h"
14
+ #include "content/public/browser/browser_thread.h"
15
+ #include "content/public/browser/user_metrics.h"
16
+
17
+ #if !defined(OS_IOS)
18
+ #include "chrome/browser/ui/browser_finder.h"
19
+ #include "chrome/browser/ui/browser_list.h"
20
+ #include "chrome/browser/ui/browser_list_observer.h"
21
+ #include "chrome/browser/ui/browser_window.h"
22
+ #include "chrome/browser/ui/startup/startup_browser_creator.h"
23
+ #endif // !defined (OS_IOS)
24
+
25
+ using content::BrowserThread;
26
+ using content::UserMetricsAction;
27
+
28
+ namespace {
29
+
30
+ // Handles running a callback when a new Browser has been completely created.
31
+ class BrowserAddedObserver : public chrome::BrowserListObserver {
32
+ public:
33
+ explicit BrowserAddedObserver(
34
+ profiles::ProfileSwitchingDoneCallback callback) : callback_(callback) {
35
+ BrowserList::AddObserver(this);
36
+ }
37
+ virtual ~BrowserAddedObserver() {
38
+ BrowserList::RemoveObserver(this);
39
+ }
40
+
41
+ private:
42
+ // Overridden from BrowserListObserver:
43
+ virtual void OnBrowserAdded(Browser* browser) OVERRIDE {
44
+ DCHECK(!callback_.is_null());
45
+ callback_.Run();
46
+ }
47
+
48
+ profiles::ProfileSwitchingDoneCallback callback_;
49
+
50
+ DISALLOW_COPY_AND_ASSIGN(BrowserAddedObserver);
51
+ };
52
+
53
+ void OpenBrowserWindowForProfile(
54
+ profiles::ProfileSwitchingDoneCallback callback,
55
+ bool always_create,
56
+ bool is_new_profile,
57
+ chrome::HostDesktopType desktop_type,
58
+ Profile* profile,
59
+ Profile::CreateStatus status) {
60
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
61
+
62
+ if (status != Profile::CREATE_STATUS_INITIALIZED)
63
+ return;
64
+
65
+ chrome::startup::IsProcessStartup is_process_startup =
66
+ chrome::startup::IS_NOT_PROCESS_STARTUP;
67
+ chrome::startup::IsFirstRun is_first_run = chrome::startup::IS_NOT_FIRST_RUN;
68
+
69
+ // If this is a brand new profile, then start a first run window.
70
+ if (is_new_profile) {
71
+ is_process_startup = chrome::startup::IS_PROCESS_STARTUP;
72
+ is_first_run = chrome::startup::IS_FIRST_RUN;
73
+ }
74
+
75
+ // If we are not showing any browsers windows (we could be showing the
76
+ // desktop User Manager, for example), then this is a process startup browser.
77
+ if (BrowserList::GetInstance(desktop_type)->size() == 0)
78
+ is_process_startup = chrome::startup::IS_PROCESS_STARTUP;
79
+
80
+ // If there is a callback, create an observer to make sure it is only
81
+ // run when the browser has been completely created.
82
+ scoped_ptr<BrowserAddedObserver> browser_added_observer;
83
+ if (!callback.is_null())
84
+ browser_added_observer.reset(new BrowserAddedObserver(callback));
85
+
86
+ profiles::FindOrCreateNewWindowForProfile(
87
+ profile,
88
+ is_process_startup,
89
+ is_first_run,
90
+ desktop_type,
91
+ always_create);
92
+ }
93
+
94
+ } // namespace
95
+
96
+ namespace profiles {
97
+
98
+ void FindOrCreateNewWindowForProfile(
99
+ Profile* profile,
100
+ chrome::startup::IsProcessStartup process_startup,
101
+ chrome::startup::IsFirstRun is_first_run,
102
+ chrome::HostDesktopType desktop_type,
103
+ bool always_create) {
104
+ #if defined(OS_IOS)
105
+ NOTREACHED();
106
+ #else
107
+ DCHECK(profile);
108
+
109
+ if (!always_create) {
110
+ Browser* browser = chrome::FindTabbedBrowser(profile, false, desktop_type);
111
+ if (browser) {
112
+ browser->window()->Activate();
113
+ return;
114
+ }
115
+ }
116
+
117
+ content::RecordAction(UserMetricsAction("NewWindow"));
118
+ CommandLine command_line(CommandLine::NO_PROGRAM);
119
+ int return_code;
120
+ StartupBrowserCreator browser_creator;
121
+ browser_creator.LaunchBrowser(command_line, profile, base::FilePath(),
122
+ process_startup, is_first_run, &return_code);
123
+ #endif // defined(OS_IOS)
124
+ }
125
+
126
+ void SwitchToProfile(
127
+ const base::FilePath& path,
128
+ chrome::HostDesktopType desktop_type,
129
+ bool always_create,
130
+ ProfileSwitchingDoneCallback callback) {
131
+ g_browser_process->profile_manager()->CreateProfileAsync(
132
+ path,
133
+ base::Bind(&OpenBrowserWindowForProfile,
134
+ callback,
135
+ always_create,
136
+ false,
137
+ desktop_type),
138
+ base::string16(),
139
+ base::string16(),
140
+ std::string());
141
+ }
142
+
143
+ void SwitchToGuestProfile(chrome::HostDesktopType desktop_type,
144
+ ProfileSwitchingDoneCallback callback) {
145
+ g_browser_process->profile_manager()->CreateProfileAsync(
146
+ ProfileManager::GetGuestProfilePath(),
147
+ base::Bind(&OpenBrowserWindowForProfile,
148
+ callback,
149
+ false,
150
+ false,
151
+ desktop_type),
152
+ base::string16(),
153
+ base::string16(),
154
+ std::string());
155
+ }
156
+
157
+ void CreateAndSwitchToNewProfile(chrome::HostDesktopType desktop_type,
158
+ ProfileSwitchingDoneCallback callback) {
159
+ ProfileManager::CreateMultiProfileAsync(
160
+ base::string16(),
161
+ base::string16(),
162
+ base::Bind(&OpenBrowserWindowForProfile,
163
+ callback,
164
+ true,
165
+ true,
166
+ desktop_type),
167
+ std::string());
168
+ }
169
+
170
+ void CloseGuestProfileWindows() {
171
+ ProfileManager* profile_manager = g_browser_process->profile_manager();
172
+ Profile* profile = profile_manager->GetProfileByPath(
173
+ ProfileManager::GetGuestProfilePath());
174
+
175
+ if (profile) {
176
+ BrowserList::CloseAllBrowsersWithProfile(profile);
177
+ }
178
+ }
179
+
180
+ void LockProfile(Profile* profile) {
181
+ DCHECK(profile);
182
+ ProfileInfoCache& cache =
183
+ g_browser_process->profile_manager()->GetProfileInfoCache();
184
+
185
+ size_t index = cache.GetIndexOfProfileWithPath(profile->GetPath());
186
+ cache.SetProfileSigninRequiredAtIndex(index, true);
187
+ chrome::ShowUserManager(profile->GetPath());
188
+ BrowserList::CloseAllBrowsersWithProfile(profile);
189
+ }
190
+
191
+ } // namespace profiles
pool/shard001/C++/0017170_S3_wrap.cpp ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "S3_wrap.h"
2
+ #include "S3.h"
3
+
4
+ #ifdef __cplusplus
5
+ extern "C" {
6
+ #endif
7
+
8
+ void init_pd_client(struct PDClient * client, char* name_bucket) {
9
+ S3 s3;
10
+ client->s3 = (void *)(&s3);
11
+ client->name_bucket = name_bucket;
12
+ }
13
+
14
+ void get(struct PDClient *client, char *output) {
15
+ std::string str_output = ((S3*)(client->s3))->getObjects(client->name_bucket);
16
+ output = const_cast<char*>(str_output.c_str());
17
+
18
+ }
19
+ void put(struct PDClient *client, const char* directory_to_upload_char) {
20
+ std::string directory_to_upload(directory_to_upload_char);
21
+ std::vector<std::string> storage;
22
+ Helper::getFilesInDirectory(storage, directory_to_upload);
23
+ for (auto string_to_upload: storage) {
24
+ ((S3*)(client->s3))->putObject(string_to_upload, (*client).name_bucket);
25
+ }
26
+
27
+ }
28
+
29
+ void hello_world() {
30
+ std::cout << "hello world\n";
31
+ }
32
+
33
+ void hello(const char *example_text) {
34
+ std::string tex(example_text);
35
+ std::cout << "Hello "<<tex << "\n";
36
+ }
37
+
38
+
39
+ #ifdef __cplusplus
40
+ }
41
+ #endif
42
+
pool/shard001/C++/0017182_shortcutsimpl.cpp ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This file is part of QDevelop, an open-source cross-platform IDE
3
+ * Copyright (C) 2006 - 2010 Jean-Luc Biord
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation; either version 2 of the License, or
8
+ * (at your option) any later version.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
+ *
19
+ * Contact e-mail: Jean-Luc Biord <jlbiord@gmail.com>
20
+ * Program URL : http://biord-software.org/qdevelop/
21
+ *
22
+ */
23
+ #include <QHeaderView>
24
+ #include "shortcutsimpl.h"
25
+ #include "ui_main.h"
26
+ #include "mainimpl.h"
27
+ #include "misc.h"
28
+
29
+ //
30
+ ShortcutsImpl::ShortcutsImpl(QWidget * parent)
31
+ : QDialog(parent), m_mainImpl((MainImpl *)parent)
32
+ {
33
+ setupUi(this);
34
+ initTable( m_mainImpl );
35
+ connect(okButton, SIGNAL(clicked()), this, SLOT(slotAccept()) );
36
+ connect(defaultButton, SIGNAL(clicked()), this, SLOT(slotDefault()) );
37
+ }
38
+
39
+ //
40
+ void ShortcutsImpl::initTable(MainImpl *main)
41
+ {
42
+ QList<QObject*> childrens = main->children();
43
+ QListIterator<QObject*> iterator(childrens);
44
+ int row = 0;
45
+
46
+ while( iterator.hasNext() )
47
+ {
48
+ QObject *object = iterator.next();
49
+ QAction *action = qobject_cast<QAction*>(object);
50
+
51
+ if (action)
52
+ {
53
+ QString text = action->text().remove("&");
54
+
55
+ if ( !text.isEmpty() && !(action->data().toString().contains("Recent|")) )
56
+ {
57
+ QString shortcut = action->shortcut();
58
+ QTableWidgetItem *newItem = new QTableWidgetItem(text);
59
+
60
+ newItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
61
+ newItem->setData(Qt::UserRole, addressToVariant(object));
62
+ newItem->setIcon(action->icon());
63
+ table->setRowCount(row+1);
64
+ table->setItem(row, 0, newItem);
65
+ table->setItem(row++, 1, new QTableWidgetItem(shortcut));
66
+ }
67
+ }
68
+ table->sortItems( 0 );
69
+ }
70
+
71
+ QHeaderView *header = table->horizontalHeader();
72
+ header->resizeSection( 0, 230 );
73
+ table->verticalHeader()->hide();
74
+ }
75
+
76
+ //
77
+ void ShortcutsImpl::slotAccept()
78
+ {
79
+ for(int row=0; row<table->rowCount(); row++ )
80
+ {
81
+ QTableWidgetItem *item = table->item(row, 0);
82
+ QAction *action = (QAction *)variantToAction( item->data(Qt::UserRole) );
83
+ QString shortcut = table->item(row, 1)->text();
84
+ action->setShortcut( shortcut );
85
+ }
86
+ }
87
+
88
+ //
89
+ void ShortcutsImpl::slotDefault()
90
+ {
91
+ QMainWindow *dial = new QMainWindow;
92
+ Ui::Main ui;
93
+ ui.setupUi(dial);
94
+
95
+ QList<QObject*> childrens = dial->children();
96
+ QListIterator<QObject*> iterator(childrens);
97
+
98
+ while( iterator.hasNext() )
99
+ {
100
+ QObject *object = iterator.next();
101
+ QAction *action = qobject_cast<QAction*>(object);
102
+
103
+ if (action)
104
+ {
105
+ QString text = action->text().remove("&");
106
+ QString shortcut = action->shortcut();
107
+ QList<QTableWidgetItem *> listFind = table->findItems(text , Qt::MatchExactly);
108
+ if( listFind.count() )
109
+ table->item(table->row(listFind.first()), 1)->setText(shortcut);
110
+ }
111
+ }
112
+
113
+ delete dial;
114
+ }
pool/shard001/C++/0017189_render_view_context_menu_unittest.cc ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2011 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 <string>
6
+
7
+ #include "chrome/browser/tab_contents/render_view_context_menu.h"
8
+
9
+ #include "chrome/browser/extensions/extension_prefs.h"
10
+ #include "chrome/common/extensions/url_pattern.h"
11
+ #include "googleurl/src/gurl.h"
12
+ #include "testing/gtest/include/gtest/gtest.h"
13
+ #include "webkit/glue/context_menu.h"
14
+
15
+ #include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
16
+
17
+ class RenderViewContextMenuTest : public testing::Test {
18
+ public:
19
+ RenderViewContextMenuTest() { }
20
+
21
+ protected:
22
+ // Proxy defined here to minimize friend classes in RenderViewContextMenu
23
+ static bool ExtensionContextAndPatternMatch(
24
+ const ContextMenuParams& params,
25
+ ExtensionMenuItem::ContextList contexts,
26
+ const URLPatternSet& patterns) {
27
+ return RenderViewContextMenu::ExtensionContextAndPatternMatch(params,
28
+ contexts, patterns);
29
+ }
30
+
31
+ private:
32
+ DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuTest);
33
+ };
34
+
35
+ // Generates a ContextMenuParams that matches the specified contexts.
36
+ static ContextMenuParams CreateParams(int contexts) {
37
+ ContextMenuParams rv;
38
+ rv.is_editable = false;
39
+ rv.media_type = WebKit::WebContextMenuData::MediaTypeNone;
40
+ rv.page_url = GURL("http://test.page/");
41
+
42
+ static const char16 selected_text[] = { 's', 'e', 'l', 0 };
43
+ if (contexts & ExtensionMenuItem::SELECTION)
44
+ rv.selection_text = selected_text;
45
+
46
+ if (contexts & ExtensionMenuItem::LINK)
47
+ rv.link_url = GURL("http://test.link/");
48
+
49
+ if (contexts & ExtensionMenuItem::EDITABLE)
50
+ rv.is_editable = true;
51
+
52
+ if (contexts & ExtensionMenuItem::IMAGE) {
53
+ rv.src_url = GURL("http://test.image/");
54
+ rv.media_type = WebKit::WebContextMenuData::MediaTypeImage;
55
+ }
56
+
57
+ if (contexts & ExtensionMenuItem::VIDEO) {
58
+ rv.src_url = GURL("http://test.video/");
59
+ rv.media_type = WebKit::WebContextMenuData::MediaTypeVideo;
60
+ }
61
+
62
+ if (contexts & ExtensionMenuItem::AUDIO) {
63
+ rv.src_url = GURL("http://test.audio/");
64
+ rv.media_type = WebKit::WebContextMenuData::MediaTypeAudio;
65
+ }
66
+
67
+ if (contexts & ExtensionMenuItem::FRAME)
68
+ rv.frame_url = GURL("http://test.frame/");
69
+
70
+ return rv;
71
+ }
72
+
73
+ // Generates a URLPatternSet with a single pattern
74
+ static URLPatternSet CreatePatternSet(const std::string& pattern) {
75
+ URLPattern target(URLPattern::SCHEME_HTTP);
76
+ target.Parse(pattern);
77
+
78
+ URLPatternSet rv;
79
+ rv.AddPattern(target);
80
+
81
+ return rv;
82
+ }
83
+
84
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForPage) {
85
+ ContextMenuParams params = CreateParams(0);
86
+
87
+ ExtensionMenuItem::ContextList contexts;
88
+ contexts.Add(ExtensionMenuItem::PAGE);
89
+
90
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
91
+
92
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
93
+ }
94
+
95
+ TEST_F(RenderViewContextMenuTest, TargetCheckedForLink) {
96
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::LINK);
97
+
98
+ ExtensionMenuItem::ContextList contexts;
99
+ contexts.Add(ExtensionMenuItem::PAGE);
100
+ contexts.Add(ExtensionMenuItem::LINK);
101
+
102
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
103
+
104
+ EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns));
105
+ }
106
+
107
+ TEST_F(RenderViewContextMenuTest, TargetCheckedForImage) {
108
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE);
109
+
110
+ ExtensionMenuItem::ContextList contexts;
111
+ contexts.Add(ExtensionMenuItem::PAGE);
112
+ contexts.Add(ExtensionMenuItem::IMAGE);
113
+
114
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
115
+
116
+ EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns));
117
+ }
118
+
119
+ TEST_F(RenderViewContextMenuTest, TargetCheckedForVideo) {
120
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::VIDEO);
121
+
122
+ ExtensionMenuItem::ContextList contexts;
123
+ contexts.Add(ExtensionMenuItem::PAGE);
124
+ contexts.Add(ExtensionMenuItem::VIDEO);
125
+
126
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
127
+
128
+ EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns));
129
+ }
130
+
131
+ TEST_F(RenderViewContextMenuTest, TargetCheckedForAudio) {
132
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::AUDIO);
133
+
134
+ ExtensionMenuItem::ContextList contexts;
135
+ contexts.Add(ExtensionMenuItem::PAGE);
136
+ contexts.Add(ExtensionMenuItem::AUDIO);
137
+
138
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
139
+
140
+ EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns));
141
+ }
142
+
143
+ TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesTarget) {
144
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE |
145
+ ExtensionMenuItem::LINK);
146
+
147
+ ExtensionMenuItem::ContextList contexts;
148
+ contexts.Add(ExtensionMenuItem::LINK);
149
+ contexts.Add(ExtensionMenuItem::IMAGE);
150
+
151
+ URLPatternSet patterns = CreatePatternSet("*://test.link/*");
152
+
153
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
154
+ }
155
+
156
+ TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesSource) {
157
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE |
158
+ ExtensionMenuItem::LINK);
159
+
160
+ ExtensionMenuItem::ContextList contexts;
161
+ contexts.Add(ExtensionMenuItem::LINK);
162
+ contexts.Add(ExtensionMenuItem::IMAGE);
163
+
164
+ URLPatternSet patterns = CreatePatternSet("*://test.image/*");
165
+
166
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
167
+ }
168
+
169
+ TEST_F(RenderViewContextMenuTest, NoMatchWhenLinkedImageMatchesNeither) {
170
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::IMAGE |
171
+ ExtensionMenuItem::LINK);
172
+
173
+ ExtensionMenuItem::ContextList contexts;
174
+ contexts.Add(ExtensionMenuItem::LINK);
175
+ contexts.Add(ExtensionMenuItem::IMAGE);
176
+
177
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
178
+
179
+ EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns));
180
+ }
181
+
182
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForFrame) {
183
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::FRAME);
184
+
185
+ ExtensionMenuItem::ContextList contexts;
186
+ contexts.Add(ExtensionMenuItem::FRAME);
187
+
188
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
189
+
190
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
191
+ }
192
+
193
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForEditable) {
194
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::EDITABLE);
195
+
196
+ ExtensionMenuItem::ContextList contexts;
197
+ contexts.Add(ExtensionMenuItem::EDITABLE);
198
+
199
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
200
+
201
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
202
+ }
203
+
204
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelection) {
205
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION);
206
+
207
+ ExtensionMenuItem::ContextList contexts;
208
+ contexts.Add(ExtensionMenuItem::SELECTION);
209
+
210
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
211
+
212
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
213
+ }
214
+
215
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnLink) {
216
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION |
217
+ ExtensionMenuItem::LINK);
218
+
219
+ ExtensionMenuItem::ContextList contexts;
220
+ contexts.Add(ExtensionMenuItem::SELECTION);
221
+ contexts.Add(ExtensionMenuItem::LINK);
222
+
223
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
224
+
225
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
226
+ }
227
+
228
+ TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnImage) {
229
+ ContextMenuParams params = CreateParams(ExtensionMenuItem::SELECTION |
230
+ ExtensionMenuItem::IMAGE);
231
+
232
+ ExtensionMenuItem::ContextList contexts;
233
+ contexts.Add(ExtensionMenuItem::SELECTION);
234
+ contexts.Add(ExtensionMenuItem::IMAGE);
235
+
236
+ URLPatternSet patterns = CreatePatternSet("*://test.none/*");
237
+
238
+ EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns));
239
+ }
pool/shard001/C++/0017193_socket_util.cc ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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 "chromecast/net/socket_util.h"
6
+
7
+ #include <sys/socket.h>
8
+
9
+ #include <utility>
10
+
11
+ #include "base/logging.h"
12
+ #include "net/base/net_errors.h"
13
+ #include "net/base/sockaddr_storage.h"
14
+ #include "net/socket/socket_posix.h"
15
+ #include "net/socket/stream_socket.h"
16
+ #include "net/socket/unix_domain_client_socket_posix.h"
17
+
18
+ namespace chromecast {
19
+
20
+ bool CreateUnnamedSocketPair(base::ScopedFD* fd1, base::ScopedFD* fd2) {
21
+ int raw_socks[2];
22
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_socks) == -1) {
23
+ return false;
24
+ }
25
+ fd1->reset(raw_socks[0]);
26
+ fd2->reset(raw_socks[1]);
27
+ return true;
28
+ }
29
+
30
+ std::unique_ptr<net::StreamSocket> AdoptUnnamedSocketHandle(
31
+ base::ScopedFD socket_fd) {
32
+ if (!socket_fd.is_valid()) {
33
+ LOG(ERROR) << "Received invalid socket descriptor: " << socket_fd.get();
34
+ return nullptr;
35
+ }
36
+
37
+ net::SockaddrStorage address;
38
+ auto socket_posix = std::make_unique<net::SocketPosix>();
39
+ if (socket_posix->AdoptConnectedSocket(socket_fd.release(), address) !=
40
+ net::OK) {
41
+ LOG(ERROR) << "Cannot adopt connected socket.";
42
+ return nullptr;
43
+ }
44
+ return std::make_unique<net::UnixDomainClientSocket>(std::move(socket_posix));
45
+ }
46
+
47
+ } // namespace chromecast
pool/shard001/C++/0017201_BPFTargetMachine.cpp ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- BPFTargetMachine.cpp - Define TargetMachine for BPF ---------------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // Implements the info about BPF target spec.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #include "BPFTargetMachine.h"
14
+ #include "BPF.h"
15
+ #include "MCTargetDesc/BPFMCAsmInfo.h"
16
+ #include "TargetInfo/BPFTargetInfo.h"
17
+ #include "llvm/CodeGen/Passes.h"
18
+ #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
19
+ #include "llvm/CodeGen/TargetPassConfig.h"
20
+ #include "llvm/IR/LegacyPassManager.h"
21
+ #include "llvm/Support/FormattedStream.h"
22
+ #include "llvm/Support/TargetRegistry.h"
23
+ #include "llvm/Target/TargetOptions.h"
24
+ using namespace llvm;
25
+
26
+ static cl::
27
+ opt<bool> DisableMIPeephole("disable-bpf-peephole", cl::Hidden,
28
+ cl::desc("Disable machine peepholes for BPF"));
29
+
30
+ extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeBPFTarget() {
31
+ // Register the target.
32
+ RegisterTargetMachine<BPFTargetMachine> X(getTheBPFleTarget());
33
+ RegisterTargetMachine<BPFTargetMachine> Y(getTheBPFbeTarget());
34
+ RegisterTargetMachine<BPFTargetMachine> Z(getTheBPFTarget());
35
+
36
+ PassRegistry &PR = *PassRegistry::getPassRegistry();
37
+ initializeBPFAbstractMemberAccessPass(PR);
38
+ initializeBPFMIPeepholePass(PR);
39
+ initializeBPFMIPeepholeTruncElimPass(PR);
40
+ }
41
+
42
+ // DataLayout: little or big endian
43
+ static std::string computeDataLayout(const Triple &TT) {
44
+ if (TT.getArch() == Triple::bpfeb)
45
+ return "E-m:e-p:64:64-i64:64-i128:128-n32:64-S128";
46
+ else
47
+ return "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128";
48
+ }
49
+
50
+ static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
51
+ if (!RM.hasValue())
52
+ return Reloc::PIC_;
53
+ return *RM;
54
+ }
55
+
56
+ BPFTargetMachine::BPFTargetMachine(const Target &T, const Triple &TT,
57
+ StringRef CPU, StringRef FS,
58
+ const TargetOptions &Options,
59
+ Optional<Reloc::Model> RM,
60
+ Optional<CodeModel::Model> CM,
61
+ CodeGenOpt::Level OL, bool JIT)
62
+ : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
63
+ getEffectiveRelocModel(RM),
64
+ getEffectiveCodeModel(CM, CodeModel::Small), OL),
65
+ TLOF(std::make_unique<TargetLoweringObjectFileELF>()),
66
+ Subtarget(TT, std::string(CPU), std::string(FS), *this) {
67
+ initAsmInfo();
68
+
69
+ BPFMCAsmInfo *MAI =
70
+ static_cast<BPFMCAsmInfo *>(const_cast<MCAsmInfo *>(AsmInfo.get()));
71
+ MAI->setDwarfUsesRelocationsAcrossSections(!Subtarget.getUseDwarfRIS());
72
+ }
73
+
74
+ namespace {
75
+ // BPF Code Generator Pass Configuration Options.
76
+ class BPFPassConfig : public TargetPassConfig {
77
+ public:
78
+ BPFPassConfig(BPFTargetMachine &TM, PassManagerBase &PM)
79
+ : TargetPassConfig(TM, PM) {}
80
+
81
+ BPFTargetMachine &getBPFTargetMachine() const {
82
+ return getTM<BPFTargetMachine>();
83
+ }
84
+
85
+ void addIRPasses() override;
86
+ bool addInstSelector() override;
87
+ void addMachineSSAOptimization() override;
88
+ void addPreEmitPass() override;
89
+ };
90
+ }
91
+
92
+ TargetPassConfig *BPFTargetMachine::createPassConfig(PassManagerBase &PM) {
93
+ return new BPFPassConfig(*this, PM);
94
+ }
95
+
96
+ void BPFPassConfig::addIRPasses() {
97
+
98
+ addPass(createBPFAbstractMemberAccess(&getBPFTargetMachine()));
99
+
100
+ TargetPassConfig::addIRPasses();
101
+ }
102
+
103
+ // Install an instruction selector pass using
104
+ // the ISelDag to gen BPF code.
105
+ bool BPFPassConfig::addInstSelector() {
106
+ addPass(createBPFISelDag(getBPFTargetMachine()));
107
+
108
+ return false;
109
+ }
110
+
111
+ void BPFPassConfig::addMachineSSAOptimization() {
112
+ addPass(createBPFMISimplifyPatchablePass());
113
+
114
+ // The default implementation must be called first as we want eBPF
115
+ // Peephole ran at last.
116
+ TargetPassConfig::addMachineSSAOptimization();
117
+
118
+ const BPFSubtarget *Subtarget = getBPFTargetMachine().getSubtargetImpl();
119
+ if (!DisableMIPeephole) {
120
+ if (Subtarget->getHasAlu32())
121
+ addPass(createBPFMIPeepholePass());
122
+ addPass(createBPFMIPeepholeTruncElimPass());
123
+ }
124
+ }
125
+
126
+ void BPFPassConfig::addPreEmitPass() {
127
+ addPass(createBPFMIPreEmitCheckingPass());
128
+ if (getOptLevel() != CodeGenOpt::None)
129
+ if (!DisableMIPeephole)
130
+ addPass(createBPFMIPreEmitPeepholePass());
131
+ }
pool/shard001/C++/0017203_atom_menu_model.cc ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2015 GitHub, Inc.
2
+ // Use of this source code is governed by the MIT license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "atom/browser/ui/atom_menu_model.h"
6
+
7
+ #include "base/stl_util.h"
8
+
9
+ namespace atom {
10
+
11
+ bool AtomMenuModel::Delegate::GetAcceleratorForCommandId(int command_id,
12
+ ui::Accelerator* accelerator) const {
13
+ return GetAcceleratorForCommandIdWithParams(
14
+ command_id, false, accelerator);
15
+ }
16
+
17
+ AtomMenuModel::AtomMenuModel(Delegate* delegate)
18
+ : ui::SimpleMenuModel(delegate), delegate_(delegate) {}
19
+
20
+ AtomMenuModel::~AtomMenuModel() {}
21
+
22
+ void AtomMenuModel::SetRole(int index, const base::string16& role) {
23
+ int command_id = GetCommandIdAt(index);
24
+ roles_[command_id] = role;
25
+ }
26
+
27
+ base::string16 AtomMenuModel::GetRoleAt(int index) {
28
+ int command_id = GetCommandIdAt(index);
29
+ if (base::ContainsKey(roles_, command_id))
30
+ return roles_[command_id];
31
+ else
32
+ return base::string16();
33
+ }
34
+
35
+ bool AtomMenuModel::GetAcceleratorAtWithParams(
36
+ int index,
37
+ bool use_default_accelerator,
38
+ ui::Accelerator* accelerator) const {
39
+ if (delegate_) {
40
+ return delegate_->GetAcceleratorForCommandIdWithParams(
41
+ GetCommandIdAt(index), use_default_accelerator, accelerator);
42
+ }
43
+ return false;
44
+ }
45
+
46
+ void AtomMenuModel::MenuWillClose() {
47
+ ui::SimpleMenuModel::MenuWillClose();
48
+ for (Observer& observer : observers_) {
49
+ observer.OnMenuWillClose();
50
+ }
51
+ }
52
+
53
+ void AtomMenuModel::MenuWillShow() {
54
+ ui::SimpleMenuModel::MenuWillShow();
55
+ for (Observer& observer : observers_) {
56
+ observer.OnMenuWillShow();
57
+ }
58
+ }
59
+
60
+ AtomMenuModel* AtomMenuModel::GetSubmenuModelAt(int index) {
61
+ return static_cast<AtomMenuModel*>(
62
+ ui::SimpleMenuModel::GetSubmenuModelAt(index));
63
+ }
64
+
65
+ } // namespace atom
pool/shard001/C++/0017205_isobarAmplitude_py.cc ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "isobarAmplitude_py.h"
2
+
3
+ #include <boost/python.hpp>
4
+
5
+ #include "isobarAmplitude.h"
6
+ #include "rootConverters_py.h"
7
+
8
+ namespace bp = boost::python;
9
+
10
+
11
+ namespace {
12
+
13
+ struct isobarAmplitudeWrapper : public rpwa::isobarAmplitude,
14
+ bp::wrapper<rpwa::isobarAmplitude>
15
+ {
16
+
17
+ void init() {
18
+ if(bp::override init = this->get_override("init")) {
19
+ init();
20
+ }
21
+ rpwa::isobarAmplitude::init();
22
+ }
23
+
24
+ void default_init() {
25
+ rpwa::isobarAmplitude::init();
26
+ }
27
+
28
+ std::string name() const {
29
+ if(bp::override name = this->get_override("name")) {
30
+ return name();
31
+ }
32
+ return rpwa::isobarAmplitude::name();
33
+ }
34
+
35
+ std::string default_name() const {
36
+ return rpwa::isobarAmplitude::name();
37
+ }
38
+
39
+ std::string printParameters__() const {
40
+ std::stringstream sstr;
41
+ if(bp::override printParameters = this->get_override("printParameters")) {
42
+ printParameters(sstr);
43
+ } else {
44
+ rpwa::isobarAmplitude::printParameters(sstr);
45
+ }
46
+ return sstr.str();
47
+ }
48
+
49
+ std::string default_printParameters__() const {
50
+ std::stringstream sstr;
51
+ rpwa::isobarAmplitude::printParameters(sstr);
52
+ return sstr.str();
53
+ }
54
+
55
+ };
56
+
57
+ rpwa::isobarDecayTopology& isobarAmplitude_decayTopology(const rpwa::isobarAmplitude& self) {
58
+ return *(self.decayTopology());
59
+ }
60
+
61
+ PyObject* isobarAmplitude_gjTransform(PyObject* pyBeamLv, PyObject* pyXLv) {
62
+ TLorentzVector* beamLv = rpwa::py::convertFromPy<TLorentzVector*>(pyBeamLv);
63
+ TLorentzVector* XLv = rpwa::py::convertFromPy<TLorentzVector*>(pyXLv);
64
+ if((beamLv == NULL) || (XLv == NULL)) {
65
+ printErr<<"Got invalid input when executing rpwa::isobarAmplitude::gjTransform()."<<std::endl;
66
+ return bp::object().ptr();
67
+ }
68
+ return rpwa::py::convertToPy<TLorentzRotation>(rpwa::isobarAmplitude::gjTransform(*beamLv, *XLv));
69
+ }
70
+
71
+ std::string isobarAmplitude_printParameters(const rpwa::isobarAmplitude& self) {
72
+ std::stringstream sstr;
73
+ self.printParameters(sstr);
74
+ return sstr.str();
75
+ }
76
+
77
+ }
78
+
79
+ void rpwa::py::exportIsobarAmplitude() {
80
+
81
+ bp::class_<isobarAmplitudeWrapper, boost::noncopyable>("isobarAmplitude", bp::no_init)
82
+
83
+ .def(bp::self_ns::str(bp::self))
84
+
85
+ .def(
86
+ "decayTopology"
87
+ , &isobarAmplitude_decayTopology
88
+ , bp::return_internal_reference<>()
89
+ )
90
+
91
+ .def("setDecayTopology", &rpwa::isobarAmplitude::setDecayTopology)
92
+
93
+ .def("init", &isobarAmplitudeWrapper::init, &isobarAmplitudeWrapper::default_init)
94
+ .def("init", &rpwa::isobarAmplitude::init)
95
+
96
+ .add_property("reflectivityBasis", &rpwa::isobarAmplitude::reflectivityBasis, &rpwa::isobarAmplitude::enableReflectivityBasis)
97
+ .add_property("boseSymmetrization", &rpwa::isobarAmplitude::boseSymmetrization, &rpwa::isobarAmplitude::enableBoseSymmetrization)
98
+ .add_property("isospinSymmetrization", &rpwa::isobarAmplitude::isospinSymmetrization, &rpwa::isobarAmplitude::enableIsospinSymmetrization)
99
+ .add_property("doSpaceInversion", &rpwa::isobarAmplitude::doSpaceInversion, &rpwa::isobarAmplitude::enableSpaceInversion)
100
+ .add_property("doReflection", &rpwa::isobarAmplitude::doReflection, &rpwa::isobarAmplitude::enableReflection)
101
+
102
+ .def("gjTransform", &isobarAmplitude_gjTransform)
103
+ .staticmethod("gjTransform")
104
+
105
+ .def("amplitude", &rpwa::isobarAmplitude::amplitude)
106
+
107
+ .def("__call__", &rpwa::isobarAmplitude::operator())
108
+
109
+ .def("name", &isobarAmplitudeWrapper::name, &isobarAmplitudeWrapper::default_name)
110
+ .def("name", &isobarAmplitude::name)
111
+ .def("printParameters", &isobarAmplitudeWrapper::printParameters__, &isobarAmplitudeWrapper::default_printParameters__)
112
+ .def("printParameters", &isobarAmplitude_printParameters)
113
+
114
+ .add_static_property("debugIsobarAmplitude", &rpwa::isobarAmplitude::debug, &rpwa::isobarAmplitude::setDebug);
115
+
116
+ bp::register_ptr_to_python<rpwa::isobarAmplitudePtr>();
117
+
118
+ }
pool/shard001/C++/0017208_subscriber_test.cc ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * Copyright 2015, Google Inc.
4
+ * All rights reserved.
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are
8
+ * met:
9
+ *
10
+ * * Redistributions of source code must retain the above copyright
11
+ * notice, this list of conditions and the following disclaimer.
12
+ * * Redistributions in binary form must reproduce the above
13
+ * copyright notice, this list of conditions and the following disclaimer
14
+ * in the documentation and/or other materials provided with the
15
+ * distribution.
16
+ * * Neither the name of Google Inc. nor the names of its
17
+ * contributors may be used to endorse or promote products derived from
18
+ * this software without specific prior written permission.
19
+ *
20
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+ *
32
+ */
33
+
34
+ #include <google/protobuf/stubs/common.h>
35
+
36
+ #include <grpc++/channel_arguments.h>
37
+ #include <grpc++/channel_interface.h>
38
+ #include <grpc++/client_context.h>
39
+ #include <grpc++/create_channel.h>
40
+ #include <grpc++/server.h>
41
+ #include <grpc++/server_builder.h>
42
+ #include <grpc++/server_context.h>
43
+ #include <grpc++/server_credentials.h>
44
+ #include <grpc++/status.h>
45
+ #include <gtest/gtest.h>
46
+
47
+ #include "examples/pubsub/subscriber.h"
48
+ #include "test/core/util/port.h"
49
+ #include "test/core/util/test_config.h"
50
+
51
+ namespace grpc {
52
+ namespace testing {
53
+ namespace {
54
+
55
+ const char kTopic[] = "test topic";
56
+ const char kSubscriptionName[] = "subscription name";
57
+ const char kData[] = "Message data";
58
+
59
+ class SubscriberServiceImpl : public tech::pubsub::SubscriberService::Service {
60
+ public:
61
+ Status CreateSubscription(
62
+ ServerContext* context, const tech::pubsub::Subscription* request,
63
+ tech::pubsub::Subscription* response) GRPC_OVERRIDE {
64
+ EXPECT_EQ(request->topic(), kTopic);
65
+ EXPECT_EQ(request->name(), kSubscriptionName);
66
+ return Status::OK;
67
+ }
68
+
69
+ Status GetSubscription(ServerContext* context,
70
+ const tech::pubsub::GetSubscriptionRequest* request,
71
+ tech::pubsub::Subscription* response) GRPC_OVERRIDE {
72
+ EXPECT_EQ(request->subscription(), kSubscriptionName);
73
+ response->set_topic(kTopic);
74
+ return Status::OK;
75
+ }
76
+
77
+ Status DeleteSubscription(
78
+ ServerContext* context,
79
+ const tech::pubsub::DeleteSubscriptionRequest* request,
80
+ proto2::Empty* response) GRPC_OVERRIDE {
81
+ EXPECT_EQ(request->subscription(), kSubscriptionName);
82
+ return Status::OK;
83
+ }
84
+
85
+ Status Pull(ServerContext* context, const tech::pubsub::PullRequest* request,
86
+ tech::pubsub::PullResponse* response) GRPC_OVERRIDE {
87
+ EXPECT_EQ(request->subscription(), kSubscriptionName);
88
+ response->set_ack_id("1");
89
+ response->mutable_pubsub_event()->mutable_message()->set_data(kData);
90
+ return Status::OK;
91
+ }
92
+
93
+ Status Acknowledge(ServerContext* context,
94
+ const tech::pubsub::AcknowledgeRequest* request,
95
+ proto2::Empty* response) GRPC_OVERRIDE {
96
+ return Status::OK;
97
+ }
98
+
99
+ };
100
+
101
+ class SubscriberTest : public ::testing::Test {
102
+ protected:
103
+ // Setup a server and a client for SubscriberService.
104
+ void SetUp() GRPC_OVERRIDE {
105
+ int port = grpc_pick_unused_port_or_die();
106
+ server_address_ << "localhost:" << port;
107
+ ServerBuilder builder;
108
+ builder.AddListeningPort(server_address_.str(), grpc::InsecureServerCredentials());
109
+ builder.RegisterService(&service_);
110
+ server_ = builder.BuildAndStart();
111
+
112
+ channel_ = CreateChannel(server_address_.str(), grpc::InsecureCredentials(), ChannelArguments());
113
+
114
+ subscriber_.reset(new grpc::examples::pubsub::Subscriber(channel_));
115
+ }
116
+
117
+ void TearDown() GRPC_OVERRIDE {
118
+ server_->Shutdown();
119
+ subscriber_->Shutdown();
120
+ }
121
+
122
+ std::ostringstream server_address_;
123
+ std::unique_ptr<Server> server_;
124
+ SubscriberServiceImpl service_;
125
+
126
+ std::shared_ptr<ChannelInterface> channel_;
127
+
128
+ std::unique_ptr<grpc::examples::pubsub::Subscriber> subscriber_;
129
+ };
130
+
131
+ TEST_F(SubscriberTest, TestSubscriber) {
132
+ EXPECT_TRUE(subscriber_->CreateSubscription(kTopic,
133
+ kSubscriptionName).IsOk());
134
+
135
+ grpc::string topic;
136
+ EXPECT_TRUE(subscriber_->GetSubscription(kSubscriptionName,
137
+ &topic).IsOk());
138
+ EXPECT_EQ(topic, kTopic);
139
+
140
+ grpc::string data;
141
+ EXPECT_TRUE(subscriber_->Pull(kSubscriptionName,
142
+ &data).IsOk());
143
+
144
+ EXPECT_TRUE(subscriber_->DeleteSubscription(kSubscriptionName).IsOk());
145
+ }
146
+
147
+ } // namespace
148
+ } // namespace testing
149
+ } // namespace grpc
150
+
151
+ int main(int argc, char** argv) {
152
+ grpc_test_init(argc, argv);
153
+ grpc_init();
154
+ ::testing::InitGoogleTest(&argc, argv);
155
+ gpr_log(GPR_INFO, "Start test ...");
156
+ int result = RUN_ALL_TESTS();
157
+ grpc_shutdown();
158
+ return result;
159
+ }
pool/shard001/C++/0017218_vix_iniwriter.cpp ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <vix_iniwriter.h>
2
+ #include <vix_filemanager.h>
3
+
4
+ namespace Vixen {
5
+
6
+ INIWriter::INIWriter()
7
+ {
8
+ _values["TEST_SECTION"].push_back("bFixed");
9
+ _values["TEST_SECTION"].push_back("iWidth");
10
+ _values["TEST_SECTION"].push_back("iHeight");
11
+ _values["TEST_SECTION"].push_back("fScale");
12
+ _values["TEST_SECTION"].push_back("fDepth");
13
+ }
14
+
15
+ void INIWriter::Write(std::string outname)
16
+ {
17
+ File* file = FileManager::OpenFile(UStringFromCharArray(outname.c_str()), Vixen::FileMode::WriteBinary);
18
+ if(file)
19
+ {
20
+ for(auto& key : _values)
21
+ {
22
+ //Write section
23
+ std::string section = "[" + key.first + "]\n";
24
+
25
+ file->Write((BYTE*)section.c_str(), section.size());
26
+
27
+ std::vector<std::string> _map = key.second;
28
+ for(int i = 0; i < _map.size(); i++)
29
+ {
30
+ std::string name = _map[i];
31
+ name += "\n";
32
+ file->Write((BYTE*)name.c_str(), name.size());
33
+ }
34
+ }
35
+ }
36
+ }
37
+
38
+ }
pool/shard001/C++/0017221_3.cpp ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <iostream>
3
+ #include <string.h>
4
+ #include <string>
5
+ #include <sstream>
6
+
7
+ using namespace std;
8
+
9
+ int main(){
10
+ int n;
11
+ char c[101];
12
+ scanf("%d", &n);
13
+ for(int i=0;i<n;i++){
14
+ bool result = true;
15
+ int count1 = 0, count2 = 0, count3 = 0;
16
+ int countP = 0, countT = 0;
17
+ scanf("%s", c);
18
+ for(int j=0;j<strlen(c);j++){
19
+ if(c[j] != 'P' && c[j] != 'A' && c[j] != 'T'){
20
+ result = false;
21
+ break;
22
+ }
23
+ if(c[j] == 'P'){
24
+ countP ++;
25
+ if(countP == 2){
26
+ result = false;
27
+ break;
28
+ }
29
+ }
30
+ if(c[j] == 'T'){
31
+ countT ++;
32
+ if(countT == 2){
33
+ result = false;
34
+ break;
35
+ }
36
+ }
37
+ }
38
+ if(result){
39
+ string s = c;
40
+ count1 =s.find("P");
41
+ count2 = s.find("A");
42
+ count3 = s.find("T");
43
+ if(count1 == -1 || count2 == -1 || count3 == -1){
44
+ result = false;
45
+ }
46
+ else{
47
+ result = ((count1 * (count3 - count1 - 1)) == (strlen(c) - count3 - 1)) ? true : false;
48
+ }
49
+ }
50
+ if(result){
51
+ printf("YES\n");
52
+ }
53
+ else{
54
+ printf("NO\n");
55
+ }
56
+ }
57
+ return 0;
58
+ }
pool/shard001/C++/0017223_scrollbar_theme_overlay_mobile.cc ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2019 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 "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.h"
6
+
7
+ #include "third_party/blink/public/platform/platform.h"
8
+ #include "third_party/blink/public/platform/web_theme_engine.h"
9
+ #include "third_party/blink/renderer/core/layout/layout_box.h"
10
+ #include "third_party/blink/renderer/core/paint/paint_auto_dark_mode.h"
11
+ #include "third_party/blink/renderer/core/scroll/scrollable_area.h"
12
+ #include "third_party/blink/renderer/core/scroll/scrollbar.h"
13
+ #include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h"
14
+ #include "third_party/blink/renderer/platform/graphics/graphics_context.h"
15
+ #include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
16
+
17
+ namespace blink {
18
+
19
+ static const WebThemeEngine::ScrollbarStyle& ScrollbarStyle() {
20
+ static bool initialized = false;
21
+ DEFINE_STATIC_LOCAL(WebThemeEngine::ScrollbarStyle, style,
22
+ (WebThemeEngine::ScrollbarStyle{3, 4, 3, 4, 0x80808080}));
23
+ if (!initialized) {
24
+ // During device emulation, the chrome WebThemeEngine implementation may not
25
+ // be the mobile theme which can provide the overlay scrollbar styles.
26
+ // In the case the following call will do nothing and we'll use the default
27
+ // styles specified above.
28
+ Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style);
29
+ DCHECK(style.thumb_thickness);
30
+ initialized = true;
31
+ }
32
+ return style;
33
+ }
34
+
35
+ ScrollbarThemeOverlayMobile& ScrollbarThemeOverlayMobile::GetInstance() {
36
+ // For unit tests which don't have Platform::Current()->ThemeEngine().
37
+ if (MockScrollbarsEnabled()) {
38
+ DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, theme, ());
39
+ return theme;
40
+ }
41
+
42
+ DEFINE_STATIC_LOCAL(
43
+ ScrollbarThemeOverlayMobile, theme,
44
+ (ScrollbarStyle().thumb_thickness, ScrollbarStyle().scrollbar_margin,
45
+ ScrollbarStyle().thumb_thickness_thin,
46
+ ScrollbarStyle().scrollbar_margin_thin, ScrollbarStyle().color));
47
+ return theme;
48
+ }
49
+
50
+ ScrollbarThemeOverlayMobile::ScrollbarThemeOverlayMobile(
51
+ int thumb_thickness_default,
52
+ int scrollbar_margin_default,
53
+ int thumb_thickness_thin,
54
+ int scrollbar_margin_thin,
55
+ Color color)
56
+ : ScrollbarThemeOverlay(thumb_thickness_default,
57
+ scrollbar_margin_default,
58
+ thumb_thickness_thin,
59
+ scrollbar_margin_thin),
60
+ color_(color) {}
61
+
62
+ void ScrollbarThemeOverlayMobile::PaintThumb(GraphicsContext& context,
63
+ const Scrollbar& scrollbar,
64
+ const IntRect& rect) {
65
+ if (!scrollbar.Enabled())
66
+ return;
67
+
68
+ if (DrawingRecorder::UseCachedDrawingIfPossible(context, scrollbar,
69
+ DisplayItem::kScrollbarThumb))
70
+ return;
71
+
72
+ DrawingRecorder recorder(context, scrollbar, DisplayItem::kScrollbarThumb,
73
+ ToGfxRect(rect));
74
+
75
+ const auto* box = scrollbar.GetScrollableArea()->GetLayoutBox();
76
+ AutoDarkMode auto_dark_mode(PaintAutoDarkMode(
77
+ box->StyleRef(), DarkModeFilter::ElementRole::kBackground));
78
+ context.FillRect(rect, color_, auto_dark_mode);
79
+ }
80
+
81
+ } // namespace blink
pool/shard001/C++/0017229_boss_shazzrah.cpp ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
2
+ * This program is free software; you can redistribute it and/or modify
3
+ * it under the terms of the GNU General Public License as published by
4
+ * the Free Software Foundation; either version 2 of the License, or
5
+ * (at your option) any later version.
6
+ *
7
+ * This program is distributed in the hope that it will be useful,
8
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
+ * GNU General Public License for more details.
11
+ *
12
+ * You should have received a copy of the GNU General Public License
13
+ * along with this program; if not, write to the Free Software
14
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
+ */
16
+
17
+ /* ScriptData
18
+ SDName: Boss_Shazzrah
19
+ SD%Complete: 75
20
+ SDComment: Teleport NYI
21
+ SDCategory: Molten Core
22
+ EndScriptData */
23
+
24
+ #include "scriptPCH.h"
25
+ #include "molten_core.h"
26
+
27
+ enum
28
+ {
29
+ SPELL_ARCANEEXPLOSION = 19712,
30
+ SPELL_SHAZZRAHCURSE = 19713,
31
+ SPELL_DEADENMAGIC = 19714,
32
+ SPELL_COUNTERSPELL = 19715,
33
+ SPELL_GATE_DUMMY = 23138 // effect spell: 23139
34
+ };
35
+
36
+ struct boss_shazzrahAI : public ScriptedAI
37
+ {
38
+ boss_shazzrahAI(Creature* pCreature) : ScriptedAI(pCreature)
39
+ {
40
+ m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
41
+ Reset();
42
+ }
43
+
44
+ uint32 ArcaneExplosion_Timer;
45
+ uint32 ShazzrahCurse_Timer;
46
+ uint32 DeadenMagic_Timer;
47
+ uint32 Countspell_Timer;
48
+ uint32 Blink_Timer;
49
+
50
+ ScriptedInstance* m_pInstance;
51
+
52
+ void Reset()
53
+ {
54
+ ArcaneExplosion_Timer = 2000;
55
+ ShazzrahCurse_Timer = 10000;
56
+ DeadenMagic_Timer = 5000;
57
+ Countspell_Timer = 15000;
58
+ Blink_Timer = urand(25000, 30000);
59
+
60
+ if (m_pInstance && m_creature->isAlive())
61
+ m_pInstance->SetData(TYPE_SHAZZRAH, NOT_STARTED);
62
+ }
63
+
64
+ void Aggro(Unit* pWho)
65
+ {
66
+ if (m_pInstance)
67
+ m_pInstance->SetData(TYPE_SHAZZRAH, IN_PROGRESS);
68
+ }
69
+
70
+ void JustDied(Unit* pKiller)
71
+ {
72
+ if (m_pInstance)
73
+ m_pInstance->SetData(TYPE_SHAZZRAH, DONE);
74
+ }
75
+
76
+ void UpdateAI(const uint32 diff)
77
+ {
78
+ if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
79
+ return;
80
+
81
+ //ArcaneExplosion_Timer
82
+ if (ArcaneExplosion_Timer < diff)
83
+ {
84
+ if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ARCANEEXPLOSION) == CAST_OK)
85
+ ArcaneExplosion_Timer = urand(3000, 5000);
86
+ }
87
+ else ArcaneExplosion_Timer -= diff;
88
+
89
+ //ShazzrahCurse_Timer
90
+ if (ShazzrahCurse_Timer < diff)
91
+ {
92
+ if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SHAZZRAHCURSE, CAST_AURA_NOT_PRESENT) == CAST_OK)
93
+ ShazzrahCurse_Timer = 20000;
94
+ }
95
+ else ShazzrahCurse_Timer -= diff;
96
+
97
+ //DeadenMagic_Timer
98
+ if (DeadenMagic_Timer < diff)
99
+ {
100
+ if (DoCastSpellIfCan(m_creature, SPELL_DEADENMAGIC) == CAST_OK)
101
+ DeadenMagic_Timer = urand(7000, 14000);
102
+ }
103
+ else DeadenMagic_Timer -= diff;
104
+
105
+ //Countspell_Timer
106
+ if (Countspell_Timer < diff)
107
+ {
108
+ if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_COUNTERSPELL) == CAST_OK)
109
+ Countspell_Timer = urand(16000, 18000);
110
+ }
111
+ else Countspell_Timer -= diff;
112
+
113
+ //Blink_Timer
114
+ if (Blink_Timer < diff)
115
+ {
116
+ // Teleporting him to a random gamer and casting Arcane Explosion after that.
117
+ if (DoCastSpellIfCan(m_creature, SPELL_GATE_DUMMY, CAST_TRIGGERED) == CAST_OK)
118
+ {
119
+ // manual, until added effect of dummy properly
120
+ if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER))
121
+ {
122
+ DoResetThreat();
123
+ //if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1))
124
+ m_creature->NearTeleportTo(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), m_creature->GetOrientation());
125
+ m_creature->Attack(pTarget, true);
126
+ }
127
+
128
+ Blink_Timer = urand(25000, 35000);
129
+ }
130
+ }
131
+ else Blink_Timer -= diff;
132
+
133
+ DoMeleeAttackIfReady();
134
+ }
135
+ };
136
+ CreatureAI* GetAI_boss_shazzrah(Creature* pCreature)
137
+ {
138
+ return new boss_shazzrahAI(pCreature);
139
+ }
140
+
141
+ void AddSC_boss_shazzrah()
142
+ {
143
+ Script *newscript;
144
+ newscript = new Script;
145
+ newscript->Name = "boss_shazzrah";
146
+ newscript->GetAI = &GetAI_boss_shazzrah;
147
+ newscript->RegisterSelf();
148
+ }
pool/shard001/C++/0017230_base_run_loop.cc ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 "mojo/android/system/base_run_loop.h"
6
+
7
+ #include <jni.h>
8
+
9
+ #include "base/android/base_jni_registrar.h"
10
+ #include "base/android/jni_android.h"
11
+ #include "base/android/jni_registrar.h"
12
+ #include "base/bind.h"
13
+ #include "base/message_loop/message_loop.h"
14
+ #include "jni/BaseRunLoop_jni.h"
15
+ #include "mojo/message_pump/message_pump_mojo.h"
16
+
17
+ namespace mojo {
18
+ namespace android {
19
+
20
+ static jlong CreateBaseRunLoop(JNIEnv* env,
21
+ const JavaParamRef<jobject>& jcaller) {
22
+ base::MessageLoop* message_loop =
23
+ new base::MessageLoop(common::MessagePumpMojo::Create());
24
+ return reinterpret_cast<uintptr_t>(message_loop);
25
+ }
26
+
27
+ static void Run(JNIEnv* env,
28
+ const JavaParamRef<jobject>& jcaller,
29
+ jlong runLoopID) {
30
+ reinterpret_cast<base::MessageLoop*>(runLoopID)->Run();
31
+ }
32
+
33
+ static void RunUntilIdle(JNIEnv* env,
34
+ const JavaParamRef<jobject>& jcaller,
35
+ jlong runLoopID) {
36
+ reinterpret_cast<base::MessageLoop*>(runLoopID)->RunUntilIdle();
37
+ }
38
+
39
+ static void Quit(JNIEnv* env,
40
+ const JavaParamRef<jobject>& jcaller,
41
+ jlong runLoopID) {
42
+ reinterpret_cast<base::MessageLoop*>(runLoopID)->Quit();
43
+ }
44
+
45
+ static void RunJavaRunnable(
46
+ const base::android::ScopedJavaGlobalRef<jobject>& runnable_ref) {
47
+ Java_BaseRunLoop_runRunnable(base::android::AttachCurrentThread(),
48
+ runnable_ref.obj());
49
+ }
50
+
51
+ static void PostDelayedTask(JNIEnv* env,
52
+ const JavaParamRef<jobject>& jcaller,
53
+ jlong runLoopID,
54
+ const JavaParamRef<jobject>& runnable,
55
+ jlong delay) {
56
+ base::android::ScopedJavaGlobalRef<jobject> runnable_ref;
57
+ // ScopedJavaGlobalRef do not hold onto the env reference, so it is safe to
58
+ // use it across threads. |RunJavaRunnable| will acquire a new JNIEnv before
59
+ // running the Runnable.
60
+ runnable_ref.Reset(env, runnable);
61
+ reinterpret_cast<base::MessageLoop*>(runLoopID)->PostDelayedTask(
62
+ FROM_HERE, base::Bind(&RunJavaRunnable, runnable_ref),
63
+ base::TimeDelta::FromMicroseconds(delay));
64
+ }
65
+
66
+ static void DeleteMessageLoop(JNIEnv* env,
67
+ const JavaParamRef<jobject>& jcaller,
68
+ jlong runLoopID) {
69
+ base::MessageLoop* message_loop =
70
+ reinterpret_cast<base::MessageLoop*>(runLoopID);
71
+ delete message_loop;
72
+ }
73
+
74
+ bool RegisterBaseRunLoop(JNIEnv* env) {
75
+ return RegisterNativesImpl(env);
76
+ }
77
+
78
+ } // namespace android
79
+ } // namespace mojo
80
+
81
+
pool/shard001/C++/0017243_publisherinfoservice.cpp ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "publisherinfoservice.h"
2
+
3
+ PublisherInfoService::PublisherInfoService(QSqlDatabase *db, QObject *parent):DataServiceBase(db, parent)
4
+ {
5
+
6
+ }
7
+
8
+ QStringList PublisherInfoService::getAllPublisherNames()
9
+ {
10
+ QString queryString = "SELECT publisher_name FROM publisher_info ORDER BY publisher_name ASC";
11
+ return this->getStringListFromDatabase(queryString);
12
+ }
13
+
14
+ int PublisherInfoService::getPublisherCount()
15
+ {
16
+ QString queryString = "SELECT COUNT(*) FROM publisher_info";
17
+ return this->getCountFromDatabase(queryString);
18
+ }
19
+
20
+ QString PublisherInfoService::getPublisherCountry(QString publisher)
21
+ {
22
+ QString queryString = "SELECT publisher_country FROM publisher_info WHERE publisher_name = ?";
23
+ return this->getStringFromDatabase(queryString, publisher);
24
+ }
25
+
26
+ QString PublisherInfoService::getPublisherWebsite(QString publisher)
27
+ {
28
+ QString queryString = "SELECT publisher_website FROM publisher_info WHERE publisher_name = ?";
29
+ return this->getStringFromDatabase(queryString, publisher);
30
+ }
31
+
32
+ QString PublisherInfoService::getPublisherNote(QString publisher)
33
+ {
34
+ QString queryString = "SELECT publisher_note FROM publisher_info WHERE publisher_name = ?";
35
+ return this->getStringFromDatabase(queryString, publisher);
36
+ }
pool/shard001/C++/0017245_StringTokenizer.cpp ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**********************************************************************
2
+ *
3
+ * GEOS - Geometry Engine Open Source
4
+ * http://geos.osgeo.org
5
+ *
6
+ * Copyright (C) 2005-2006 Refractions Research Inc.
7
+ * Copyright (C) 2001-2002 Vivid Solutions Inc.
8
+ *
9
+ * This is free software; you can redistribute and/or modify it under
10
+ * the terms of the GNU Lesser General Public Licence as published
11
+ * by the Free Software Foundation.
12
+ * See the COPYING file for more information.
13
+ *
14
+ **********************************************************************
15
+ *
16
+ * Last port: ORIGINAL WORK
17
+ *
18
+ **********************************************************************/
19
+
20
+ #include <geos/io/StringTokenizer.h>
21
+
22
+ #include <string>
23
+ #include <cstdlib>
24
+
25
+ using namespace std;
26
+
27
+ namespace geos {
28
+ namespace io { // geos.io
29
+
30
+ /*public*/
31
+ StringTokenizer::StringTokenizer(const string &txt)
32
+ :
33
+ str(txt)
34
+ {
35
+ stok="";
36
+ ntok=0.0;
37
+ iter=str.begin();
38
+ }
39
+
40
+ /*public*/
41
+ int
42
+ StringTokenizer::nextToken()
43
+ {
44
+ string tok="";
45
+ if (iter==str.end())
46
+ return StringTokenizer::TT_EOF;
47
+ switch(*iter) {
48
+ case '(':
49
+ case ')':
50
+ case ',':
51
+ return *iter++;
52
+ case '\n':
53
+ case '\r':
54
+ case '\t':
55
+ case ' ':
56
+ string::size_type pos=str.find_first_not_of(" \n\r\t",
57
+ iter-str.begin());
58
+ if (pos==string::npos) {
59
+ return StringTokenizer::TT_EOF;
60
+ } else {
61
+ iter=str.begin()+pos;
62
+ return nextToken();
63
+ }
64
+ }
65
+ string::size_type pos=str.find_first_of("\n\r\t() ,",
66
+ iter-str.begin());
67
+ if (pos==string::npos) {
68
+ if (iter!=str.end()) {
69
+ tok.assign(iter,str.end());
70
+ iter=str.end();
71
+ } else {
72
+ return StringTokenizer::TT_EOF;
73
+ }
74
+ } else {
75
+ tok.assign(iter, str.begin()+pos);
76
+ iter=str.begin()+pos;
77
+ }
78
+ char *stopstring;
79
+ double dbl=strtod(tok.c_str(),&stopstring);
80
+ if (*stopstring=='\0') {
81
+ ntok=dbl;
82
+ stok="";
83
+ return StringTokenizer::TT_NUMBER;
84
+ } else {
85
+ ntok=0.0;
86
+ stok=tok;
87
+ return StringTokenizer::TT_WORD;
88
+ }
89
+ }
90
+
91
+ /*public*/
92
+ int
93
+ StringTokenizer::peekNextToken()
94
+ {
95
+
96
+ string::size_type pos;
97
+ string tok="";
98
+ if (iter==str.end())
99
+ return StringTokenizer::TT_EOF;
100
+
101
+ pos=str.find_first_not_of(" \r\n\t", iter-str.begin());
102
+
103
+ if (pos==string::npos) return StringTokenizer::TT_EOF;
104
+ switch(str[pos]) {
105
+ case '(':
106
+ case ')':
107
+ case ',':
108
+ return str[pos];
109
+ }
110
+
111
+ // It's either a Number or a Word, let's
112
+ // see when it ends
113
+
114
+ pos=str.find_first_of("\n\r\t() ,", iter-str.begin());
115
+
116
+ if (pos==string::npos) {
117
+ if (iter!=str.end()) {
118
+ tok.assign(iter,str.end());
119
+ } else {
120
+ return StringTokenizer::TT_EOF;
121
+ }
122
+ } else {
123
+ tok.assign(iter, str.begin()+pos); //str.end());
124
+ }
125
+
126
+ char *stopstring;
127
+ double dbl=strtod(tok.c_str(),&stopstring);
128
+ if (*stopstring=='\0') {
129
+ ntok=dbl;
130
+ stok="";
131
+ return StringTokenizer::TT_NUMBER;
132
+ } else {
133
+ ntok=0.0;
134
+ stok=tok;
135
+ return StringTokenizer::TT_WORD;
136
+ }
137
+ }
138
+
139
+ /*public*/
140
+ double
141
+ StringTokenizer::getNVal()
142
+ {
143
+ return ntok;
144
+ }
145
+
146
+ /*public*/
147
+ string
148
+ StringTokenizer::getSVal()
149
+ {
150
+ return stok;
151
+ }
152
+
153
+ } // namespace geos.io
154
+ } // namespace geos
pool/shard001/C++/0017252_play_game.cpp ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <konig/play_game.hpp>
2
+
3
+ #include <boost/tuple/tuple.hpp>
4
+
5
+ #include <konig/biddingsequence.hpp>
6
+ #include <konig/players.hpp>
7
+ #include <konig/contract.hpp>
8
+
9
+ namespace konig {
10
+
11
+ PlayResult play_game(
12
+ const Ruleset& rules,
13
+ const Players& players,
14
+ Deal deal,
15
+ std::ostream* debug_stream
16
+ )
17
+ {
18
+ std::array<Cards, 4> hands;
19
+ std::array<Cards, 2> talon;
20
+ deal.copy_hands(hands.begin());
21
+ deal.copy_talon(talon.begin());
22
+
23
+ for (PlayPosition i=position_forehand; i<position_max; ++i) {
24
+ players[i].start_game(rules, i, hands[i]);
25
+ }
26
+ BiddingSequence bids(rules.contracts());
27
+ auto const r = bids.get_bids(players);
28
+ Contract const& contract = boost::tuples::get<0>(r);
29
+ PlayPosition declarer = boost::tuples::get<1>(r);
30
+ assert(declarer < 4);
31
+
32
+ if (debug_stream) {
33
+ *debug_stream << "contract is " << contract.name() <<
34
+ " by " << declarer << std::endl;
35
+ }
36
+
37
+ return contract.play(hands, talon, players, declarer, debug_stream);
38
+ }
39
+
40
+ PlayResult play_game(
41
+ const Ruleset& rules,
42
+ Oracle& oracle
43
+ )
44
+ {
45
+ BiddingSequence bids(rules.contracts());
46
+ auto const r = bids.get_bids(oracle);
47
+ Contract const& contract = boost::tuples::get<0>(r);
48
+ PlayPosition declarer = boost::tuples::get<1>(r);
49
+ assert(declarer < 4);
50
+
51
+ return contract.play(oracle, declarer);
52
+ }
53
+
54
+ }
55
+
pool/shard001/C++/0017253_window_demo.cc ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 Google Inc.
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
+ #include "xrtl/testing/demo_main.h"
16
+
17
+ #include "xrtl/base/logging.h"
18
+ #include "xrtl/base/threading/event.h"
19
+ #include "xrtl/base/threading/thread.h"
20
+ #include "xrtl/ui/window.h"
21
+
22
+ namespace xrtl {
23
+ namespace ui {
24
+ namespace {
25
+
26
+ class WindowDemo : private Control::Listener, private Control::InputListener {
27
+ public:
28
+ WindowDemo() {
29
+ message_loop_ = MessageLoop::Create();
30
+ done_event_ = Event::CreateFence();
31
+ }
32
+
33
+ ~WindowDemo() { Thread::Wait(message_loop_->Exit()); }
34
+
35
+ ref_ptr<WaitHandle> Run() {
36
+ window_ = Window::Create(message_loop_);
37
+ window_->set_title("Window Demo");
38
+
39
+ auto control = window_->root_control();
40
+ control->set_listener(this);
41
+ control->set_input_listener(this);
42
+ control->set_size({640, 480});
43
+ control->set_background_color({255, 0, 0, 255});
44
+
45
+ Thread::Wait(window_->Open());
46
+
47
+ return done_event_;
48
+ }
49
+
50
+ private:
51
+ void OnError(ref_ptr<Control> target) override {
52
+ LOG(INFO) << "OnError";
53
+ done_event_->Set();
54
+ }
55
+
56
+ void OnCreating(ref_ptr<Control> target) override {
57
+ LOG(INFO) << "OnCreating";
58
+ }
59
+
60
+ void OnCreated(ref_ptr<Control> target) override { LOG(INFO) << "OnCreated"; }
61
+
62
+ void OnDestroying(ref_ptr<Control> target) override {
63
+ LOG(INFO) << "OnDestroying";
64
+ }
65
+
66
+ void OnDestroyed(ref_ptr<Control> target) override {
67
+ LOG(INFO) << "OnDestroyed";
68
+ done_event_->Set();
69
+ }
70
+
71
+ void OnSystemThemeChanged(ref_ptr<Control> target) override {
72
+ LOG(INFO) << "OnSystemThemeChanged";
73
+ }
74
+
75
+ void OnSuspendChanged(ref_ptr<Control> target, bool is_suspended) override {
76
+ LOG(INFO) << "OnSuspendChanged: " << is_suspended;
77
+ }
78
+
79
+ void OnFocusChanged(ref_ptr<Control> target, bool is_focused) override {
80
+ LOG(INFO) << "OnFocusChanged: " << is_focused;
81
+ }
82
+
83
+ void OnResized(ref_ptr<Control> target, Rect2D bounds) override {
84
+ LOG(INFO) << "OnResized: " << bounds.origin.x << "," << bounds.origin.y
85
+ << " " << bounds.size.width << "x" << bounds.size.height;
86
+ }
87
+
88
+ void OnKeyDown(ref_ptr<Control> target, const KeyboardEvent& ev) override {
89
+ LOG(INFO) << "OnKeyDown: " << ev.key_code();
90
+ }
91
+
92
+ void OnKeyUp(ref_ptr<Control> target, const KeyboardEvent& ev) override {
93
+ LOG(INFO) << "OnKeyUp: " << ev.key_code();
94
+ }
95
+
96
+ void OnKeyPress(ref_ptr<Control> target, const KeyboardEvent& ev) override {
97
+ LOG(INFO) << "OnKeyPress: " << ev.key_code();
98
+ }
99
+
100
+ void OnMouseDown(ref_ptr<Control> target, const MouseEvent& ev) override {
101
+ LOG(INFO) << "OnMouseDown: " << ev.control_offset_px().x << ","
102
+ << ev.control_offset_px().y << " b"
103
+ << static_cast<int>(ev.action_button());
104
+ }
105
+
106
+ void OnMouseUp(ref_ptr<Control> target, const MouseEvent& ev) override {
107
+ LOG(INFO) << "OnMouseUp: " << ev.control_offset_px().x << ","
108
+ << ev.control_offset_px().y << " b"
109
+ << static_cast<int>(ev.action_button());
110
+ }
111
+
112
+ void OnMouseOut(ref_ptr<Control> target, const MouseEvent& ev) override {
113
+ LOG(INFO) << "OnMouseOut: " << ev.control_offset_px().x << ","
114
+ << ev.control_offset_px().y;
115
+ }
116
+
117
+ void OnMouseMove(ref_ptr<Control> target, const MouseEvent& ev) override {
118
+ LOG(INFO) << "OnMouseMove: " << ev.control_offset_px().x << ","
119
+ << ev.control_offset_px().y;
120
+ }
121
+
122
+ void OnMouseWheel(ref_ptr<Control> target, const MouseEvent& ev) override {
123
+ LOG(INFO) << "OnMouseWheel: " << ev.control_offset_px().x << ","
124
+ << ev.control_offset_px().y << " d" << ev.wheel_delta();
125
+ }
126
+
127
+ ref_ptr<MessageLoop> message_loop_;
128
+ ref_ptr<Window> window_;
129
+ ref_ptr<Event> done_event_;
130
+ };
131
+
132
+ int MyEntry(int argc, char** argv) {
133
+ auto demo = absl::make_unique<WindowDemo>();
134
+ Thread::Wait(demo->Run());
135
+ demo.reset();
136
+ LOG(INFO) << "Clean exit!";
137
+ return 0;
138
+ }
139
+
140
+ } // namespace
141
+ } // namespace ui
142
+ } // namespace xrtl
143
+
144
+ DECLARE_ENTRY_POINT(xrtl::ui::MyEntry);
pool/shard001/C++/0017255_Shader.cpp ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Shader.hpp"
2
+
3
+ #include <cassert>
4
+ #include <fstream>
5
+ #include <iostream>
6
+
7
+ static std::string
8
+ getStringFromFile(const std::string &filename)
9
+ {
10
+ std::string s;
11
+
12
+ if (filename == "") {
13
+ //no shader specified
14
+ return "";
15
+ }
16
+
17
+ std::ifstream in(filename.c_str());
18
+ if (!in) {
19
+ std::cerr << "ERROR: unable to read filename: " << filename << "\n";
20
+ return s;
21
+ }
22
+
23
+ std::string line;
24
+ while (std::getline(in, line)) {
25
+ s += line + "\n";
26
+ }
27
+
28
+ return s;
29
+ }
30
+
31
+ static void
32
+ printInfoLog(GLuint object, const std::string &msg)
33
+ {
34
+ GLint logLength = 0;
35
+ if (glIsShader(object) != 0u) {
36
+ glGetShaderiv(object, GL_INFO_LOG_LENGTH, &logLength);
37
+ }
38
+ else if (glIsProgram(object) != 0u) {
39
+ glGetProgramiv(object, GL_INFO_LOG_LENGTH, &logLength);
40
+ }
41
+ else {
42
+ std::cerr << "Error: Not a shader or a program\n";
43
+ return;
44
+ }
45
+
46
+ if (logLength > 0) {
47
+
48
+ auto log = new GLchar[logLength];
49
+ if (glIsShader(object) != 0u) {
50
+ glGetShaderInfoLog(object, logLength, nullptr, log);
51
+ }
52
+ else if (glIsProgram(object) != 0u) {
53
+ glGetProgramInfoLog(object, logLength, nullptr, log);
54
+ }
55
+
56
+ std::cerr << msg << " info: \n" << log << "\n";
57
+
58
+ delete[] log;
59
+ }
60
+ }
61
+
62
+ static GLuint
63
+ createShader(const std::string &src, GLenum type, const std::string &msg)
64
+ {
65
+ GLuint res = glCreateShader(type);
66
+
67
+ const GLchar *s_src = src.c_str();
68
+
69
+ //B : take GL_ES into account ?
70
+ /*
71
+
72
+ const GLchar* sources[] = {
73
+ // Define GLSL version
74
+ #ifdef GL_ES_VERSION_2_0
75
+ "#version 100\n"
76
+ #else
77
+ "#version 120\n"
78
+ #endif
79
+ ,
80
+ // GLES2 precision specifiers
81
+ #ifdef GL_ES_VERSION_2_0
82
+ // Define default float precision for fragment shaders:
83
+ (type == GL_FRAGMENT_SHADER) ?
84
+ "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
85
+ "precision highp float; \n"
86
+ "#else \n"
87
+ "precision mediump float; \n"
88
+ "#endif \n"
89
+ : ""
90
+ // Note: OpenGL ES automatically defines this:
91
+ // #define GL_ES
92
+ #else
93
+ // Ignore GLES 2 precision specifiers:
94
+ "#define lowp \n"
95
+ "#define mediump\n"
96
+ "#define highp \n"
97
+ #endif
98
+ ,
99
+ source };
100
+
101
+ glShaderSource(res, 3, sources, NULL);
102
+
103
+ */
104
+
105
+ GL_CHECK_ERROR_ALWAYS();
106
+
107
+ glShaderSource(res, 1, static_cast<const GLchar **>(&s_src), nullptr);
108
+
109
+ GL_CHECK_ERROR_ALWAYS();
110
+
111
+ glCompileShader(res);
112
+
113
+ GL_CHECK_ERROR_ALWAYS();
114
+
115
+ GLint compile_ok = GL_FALSE;
116
+ glGetShaderiv(res, GL_COMPILE_STATUS, &compile_ok);
117
+ if (compile_ok == GL_FALSE) {
118
+ std::cerr << "Error in " << msg << " shader\n";
119
+ printInfoLog(res, msg);
120
+ glDeleteShader(res);
121
+ return 0;
122
+ }
123
+
124
+ return res;
125
+ }
126
+
127
+ bool
128
+ Shader::loadFromFiles(const std::string &vertexFilename,
129
+ const std::string &fragmentFilename)
130
+ {
131
+ const std::string v = getStringFromFile(vertexFilename);
132
+ const std::string s = getStringFromFile(fragmentFilename);
133
+
134
+ return loadFromStrings(v, s);
135
+ }
136
+
137
+ bool
138
+ Shader::loadFromStrings(const std::string &vertexString,
139
+ const std::string &fragmentString)
140
+ {
141
+
142
+ GLuint program = glCreateProgram();
143
+
144
+ if (vertexString != "") {
145
+ GLuint shader = createShader(vertexString, GL_VERTEX_SHADER, "vertex");
146
+ if (shader == 0u) {
147
+ return false;
148
+ }
149
+ glAttachShader(program, shader);
150
+ //std::cerr << "attach vertex shader " << shader << "\n";
151
+ }
152
+
153
+ if (fragmentString != "") {
154
+ GLuint shader =
155
+ createShader(fragmentString, GL_FRAGMENT_SHADER, "fragment");
156
+ if (shader == 0u) {
157
+ return false;
158
+ }
159
+ glAttachShader(program, shader);
160
+ //std::cerr << "attach fragment shader " << shader << "\n";
161
+ }
162
+
163
+ glLinkProgram(program);
164
+ GLint link_ok = GL_FALSE;
165
+ glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
166
+ if (link_ok == 0) {
167
+ std::cerr << "ERROR: unable to link program\n";
168
+ printInfoLog(program, "program");
169
+ glDeleteProgram(program);
170
+ return false;
171
+ }
172
+
173
+ m_programId = program;
174
+
175
+ m_isValid = true;
176
+
177
+ return true;
178
+ }
179
+
180
+ void
181
+ Shader::activate() const
182
+ {
183
+ assert(m_isValid);
184
+
185
+ glUseProgram(m_programId);
186
+ }
187
+
188
+ GLint
189
+ Shader::getUniformLocation(const char *name) const
190
+ {
191
+ assert(m_isValid);
192
+
193
+ return glGetUniformLocation(m_programId, name);
194
+ }
195
+
196
+ GLint
197
+ Shader::getAttribLocation(const char *name) const
198
+ {
199
+ assert(m_isValid);
200
+
201
+ return glGetAttribLocation(m_programId, name);
202
+ }
203
+
204
+ void
205
+ Shader::setSamplerUnit(const char *sampler, int unit) const
206
+ {
207
+ assert(m_isValid);
208
+
209
+ glUniform1i(getUniformLocation(sampler), unit);
210
+ }
211
+
212
+ void
213
+ Shader::dumpInfos() const
214
+ {
215
+ GLint nbAttrs;
216
+ glGetProgramiv(m_programId, GL_ACTIVE_ATTRIBUTES, &nbAttrs);
217
+
218
+ const size_t SIZE = 1024;
219
+ GLchar name[SIZE];
220
+
221
+ GLint size;
222
+ GLenum type;
223
+ for (GLint i = 0; i < nbAttrs; ++i) {
224
+ glGetActiveAttrib(m_programId, i, SIZE, nullptr, &size, &type, name);
225
+ std::cerr << "Attrib " << glGetAttribLocation(m_programId, name) << ": "
226
+ << name << ", " << size << ", " << type << "\n";
227
+ }
228
+ }
pool/shard001/C++/0017258_JSONVariantParser.cpp ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2005-2015 Team Kodi
3
+ * http://kodi.tv
4
+ *
5
+ * This Program is free software; you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation; either version 2, or (at your option)
8
+ * any later version.
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 Kodi; see the file COPYING. If not, see
17
+ * <http://www.gnu.org/licenses/>.
18
+ *
19
+ */
20
+
21
+ #include "JSONVariantParser.h"
22
+
23
+ #include <rapidjson/reader.h>
24
+
25
+ class CJSONVariantParserHandler
26
+ {
27
+ public:
28
+ CJSONVariantParserHandler(CVariant& parsedObject);
29
+
30
+ bool Null();
31
+ bool Bool(bool b);
32
+ bool Int(int i);
33
+ bool Uint(unsigned u);
34
+ bool Int64(int64_t i);
35
+ bool Uint64(uint64_t u);
36
+ bool Double(double d);
37
+ bool RawNumber(const char* str, rapidjson::SizeType length, bool copy);
38
+ bool String(const char* str, rapidjson::SizeType length, bool copy);
39
+ bool StartObject();
40
+ bool Key(const char* str, rapidjson::SizeType length, bool copy);
41
+ bool EndObject(rapidjson::SizeType memberCount);
42
+ bool StartArray();
43
+ bool EndArray(rapidjson::SizeType elementCount);
44
+
45
+ private:
46
+ template <typename... TArgs>
47
+ bool Primitive(TArgs... args)
48
+ {
49
+ PushObject(CVariant(std::forward<TArgs>(args)...));
50
+ PopObject();
51
+
52
+ return true;
53
+ }
54
+
55
+ void PushObject(CVariant variant);
56
+ void PopObject();
57
+
58
+ CVariant& m_parsedObject;
59
+ std::vector<CVariant *> m_parse;
60
+ std::string m_key;
61
+
62
+ enum class PARSE_STATUS
63
+ {
64
+ Variable,
65
+ Array,
66
+ Object
67
+ };
68
+ PARSE_STATUS m_status;
69
+ };
70
+
71
+ CJSONVariantParserHandler::CJSONVariantParserHandler(CVariant& parsedObject)
72
+ : m_parsedObject(parsedObject),
73
+ m_parse(),
74
+ m_key(),
75
+ m_status(PARSE_STATUS::Variable)
76
+ { }
77
+
78
+ bool CJSONVariantParserHandler::Null()
79
+ {
80
+ PushObject(CVariant::ConstNullVariant);
81
+ PopObject();
82
+
83
+ return true;
84
+ }
85
+
86
+ bool CJSONVariantParserHandler::Bool(bool b)
87
+ {
88
+ return Primitive(b);
89
+ }
90
+
91
+ bool CJSONVariantParserHandler::Int(int i)
92
+ {
93
+ return Primitive(i);
94
+ }
95
+
96
+ bool CJSONVariantParserHandler::Uint(unsigned u)
97
+ {
98
+ return Primitive(u);
99
+ }
100
+
101
+ bool CJSONVariantParserHandler::Int64(int64_t i)
102
+ {
103
+ return Primitive(i);
104
+ }
105
+
106
+ bool CJSONVariantParserHandler::Uint64(uint64_t u)
107
+ {
108
+ return Primitive(u);
109
+ }
110
+
111
+ bool CJSONVariantParserHandler::Double(double d)
112
+ {
113
+ return Primitive(d);
114
+ }
115
+
116
+ bool CJSONVariantParserHandler::RawNumber(const char* str, rapidjson::SizeType length, bool copy)
117
+ {
118
+ return Primitive(str, length);
119
+ }
120
+
121
+ bool CJSONVariantParserHandler::String(const char* str, rapidjson::SizeType length, bool copy)
122
+ {
123
+ return Primitive(str, length);
124
+ }
125
+
126
+ bool CJSONVariantParserHandler::StartObject()
127
+ {
128
+ PushObject(CVariant::VariantTypeObject);
129
+
130
+ return true;
131
+ }
132
+
133
+ bool CJSONVariantParserHandler::Key(const char* str, rapidjson::SizeType length, bool copy)
134
+ {
135
+ m_key = std::string(str, 0, length);
136
+
137
+ return true;
138
+ }
139
+
140
+ bool CJSONVariantParserHandler::EndObject(rapidjson::SizeType memberCount)
141
+ {
142
+ PopObject();
143
+
144
+ return true;
145
+ }
146
+
147
+ bool CJSONVariantParserHandler::StartArray()
148
+ {
149
+ PushObject(CVariant::VariantTypeArray);
150
+
151
+ return true;
152
+ }
153
+
154
+ bool CJSONVariantParserHandler::EndArray(rapidjson::SizeType elementCount)
155
+ {
156
+ PopObject();
157
+
158
+ return true;
159
+ }
160
+
161
+ void CJSONVariantParserHandler::PushObject(CVariant variant)
162
+ {
163
+ if (m_status == PARSE_STATUS::Object)
164
+ {
165
+ (*m_parse[m_parse.size() - 1])[m_key] = variant;
166
+ m_parse.push_back(&(*m_parse[m_parse.size() - 1])[m_key]);
167
+ }
168
+ else if (m_status == PARSE_STATUS::Array)
169
+ {
170
+ CVariant *temp = m_parse[m_parse.size() - 1];
171
+ temp->push_back(variant);
172
+ m_parse.push_back(&(*temp)[temp->size() - 1]);
173
+ }
174
+ else if (m_parse.empty())
175
+ m_parse.push_back(new CVariant(variant));
176
+
177
+ if (variant.isObject())
178
+ m_status = PARSE_STATUS::Object;
179
+ else if (variant.isArray())
180
+ m_status = PARSE_STATUS::Array;
181
+ else
182
+ m_status = PARSE_STATUS::Variable;
183
+ }
184
+
185
+ void CJSONVariantParserHandler::PopObject()
186
+ {
187
+ CVariant *variant = m_parse[m_parse.size() - 1];
188
+ m_parse.pop_back();
189
+
190
+ if (!m_parse.empty())
191
+ {
192
+ variant = m_parse[m_parse.size() - 1];
193
+ if (variant->isObject())
194
+ m_status = PARSE_STATUS::Object;
195
+ else if (variant->isArray())
196
+ m_status = PARSE_STATUS::Array;
197
+ else
198
+ m_status = PARSE_STATUS::Variable;
199
+ }
200
+ else
201
+ {
202
+ m_parsedObject = *variant;
203
+ delete variant;
204
+
205
+ m_status = PARSE_STATUS::Variable;
206
+ }
207
+ }
208
+
209
+ bool CJSONVariantParser::Parse(const char* json, CVariant& data)
210
+ {
211
+ if (json == nullptr)
212
+ return false;
213
+
214
+ rapidjson::Reader reader;
215
+ rapidjson::StringStream stringStream(json);
216
+
217
+ CJSONVariantParserHandler handler(data);
218
+ if (reader.Parse(stringStream, handler))
219
+ return true;
220
+
221
+ return false;
222
+ }
223
+
224
+ bool CJSONVariantParser::Parse(const std::string& json, CVariant& data)
225
+ {
226
+ return Parse(json.c_str(), data);
227
+ }