Pendigard commited on
Commit
2fcec7b
·
verified ·
1 Parent(s): 3fca285

Upload folder using huggingface_hub (part 73)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pool/shard006/C++/0083647_UIPathSelector.cpp +74 -0
  2. pool/shard006/C++/0083648_current.cpp +47 -0
  3. pool/shard006/C++/0083654_82A.cpp +34 -0
  4. pool/shard006/C++/0083657_main.cpp +211 -0
  5. pool/shard006/C++/0083662_user_script_slave.cc +180 -0
  6. pool/shard006/C++/0083663_MPHasher.cpp +78 -0
  7. pool/shard006/C++/0083666_clientsideeffects_test.cpp +302 -0
  8. pool/shard006/C++/0083671_test_context_provider_factory.cc +46 -0
  9. pool/shard006/C++/0083679_rtcp_format_remb_unittest.cc +136 -0
  10. pool/shard006/C++/0083681_viewbasis_funcs.cpp +112 -0
  11. pool/shard006/C++/0083683_osc_route_observer.cc +107 -0
  12. pool/shard006/C++/0083689_mode_fbwa.cpp +37 -0
  13. pool/shard006/C++/0083690_DigitalGlitchFilterJNI.cpp +68 -0
  14. pool/shard006/C++/0083691_uncle.cpp +417 -0
  15. pool/shard006/C++/0083703_reportescuotas.cpp +114 -0
  16. pool/shard006/C++/0083704_Resource.cpp +131 -0
  17. pool/shard006/C++/0083713_CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp +119 -0
  18. pool/shard006/C++/0083722_InstanceFleetTimeline.cpp +96 -0
  19. pool/shard006/C++/0083726_centered_continued_fraction.cpp +51 -0
  20. pool/shard006/C++/0083728_main.cpp +81 -0
  21. pool/shard006/C++/0083732_bonus.cpp +56 -0
  22. pool/shard006/C++/0083736_CEGUIOgreResourceProvider.cpp +115 -0
  23. pool/shard006/C++/0083740_AssemblyContext.cpp +88 -0
  24. pool/shard006/C++/0083742_action_handler.cc +85 -0
  25. pool/shard006/C++/0083750_KernelRidgeRegression.cpp +79 -0
  26. pool/shard006/C++/0083752_boss_ambassador_hellmaw.cpp +193 -0
  27. pool/shard006/C++/0083759_PersistentParserState.cpp +88 -0
  28. pool/shard006/C++/0083769_mysql_remap.cc +251 -0
  29. pool/shard006/C++/0083771_DumpMassCharge.cpp +203 -0
  30. pool/shard006/C++/0083773_desktop_screen_position_client.cc +65 -0
  31. pool/shard006/C++/0083780_a.cc +67 -0
  32. pool/shard006/C++/0083783_AudioManager.cpp +54 -0
  33. pool/shard006/C++/0083789_GrGLShaderStringBuilder.cpp +105 -0
  34. pool/shard006/C++/0083795_utest_gen_sentence.cpp +123 -0
  35. pool/shard006/C++/0083801_EPattern.cpp +249 -0
  36. pool/shard006/C++/0083803_settlement_evaluator.cc +89 -0
  37. pool/shard006/C++/0083809_hud_ammo.cpp +300 -0
  38. pool/shard006/C++/0083818_DecoderPD.cpp +140 -0
  39. pool/shard006/C++/0083820_test_polyhedron_io.cpp +138 -0
  40. pool/shard006/C++/0083822_PlatformCanvas.cpp +111 -0
  41. pool/shard006/C++/0083825_MapWindowTraffic.cpp +134 -0
  42. pool/shard006/C++/0083827_FontGenerator.cpp +112 -0
  43. pool/shard006/C++/0083833_shape.cc +177 -0
  44. pool/shard006/C++/0083835_mat_mul.cpp +104 -0
  45. pool/shard006/C++/0083836_core_types.cpp +73 -0
  46. pool/shard006/C++/0083838_QQSound.cpp +22 -0
  47. pool/shard006/C++/0083843_getcomputername.cpp +45 -0
  48. pool/shard006/C++/0083849_SdFatUtil.cpp +74 -0
  49. pool/shard006/C++/0083856_service_manager.cc +123 -0
  50. pool/shard006/C++/0083858_Pawn.cpp +163 -0
pool/shard006/C++/0083647_UIPathSelector.cpp ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This file is part of AlgAudio.
3
+
4
+ AlgAudio, Copyright (C) 2015 CeTA - Audiovisual Technology Center
5
+
6
+ AlgAudio is free software: you can redistribute it and/or modify
7
+ it under the terms of the GNU Lesser General Public License as
8
+ published by the Free Software Foundation, either version 3 of the
9
+ License, or (at your option) any later version.
10
+
11
+ AlgAudio is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU Lesser General Public License for more details.
15
+
16
+ You should have received a copy of the GNU Lesser General Public License
17
+ along with AlgAudio. If not, see <http://www.gnu.org/licenses/>.
18
+ */
19
+ #include "nfd.h"
20
+ #include "UI/UIPathSelector.hpp"
21
+ #include "UI/UIBox.hpp"
22
+ #include "UI/UITextEntry.hpp"
23
+ #include "UI/UIButton.hpp"
24
+
25
+ namespace AlgAudio{
26
+
27
+ UIPathSelector::UIPathSelector(std::weak_ptr<Window> parent_window, std::string p)
28
+ : UIHBox(parent_window), path(p)
29
+ {
30
+
31
+ }
32
+
33
+ std::shared_ptr<UIPathSelector> UIPathSelector::Create(std::weak_ptr<Window> w, std::string text)
34
+ {
35
+ std::shared_ptr<UIPathSelector> res(new UIPathSelector(w,text));
36
+ res->Init();
37
+ return res;
38
+ }
39
+
40
+ void UIPathSelector::Init()
41
+ {
42
+ child_button = UIButton::Create(window,"...");
43
+ child_entry = UITextEntry::Create(window,path);
44
+ Insert(child_entry, UIBox::PackMode::WIDE);
45
+ Insert(child_button, UIBox::PackMode::TIGHT);
46
+
47
+ child_button->SetBorder(false);
48
+ child_button->SetCustomSize(Size2D(16,16));
49
+ child_button->SetInnerMargin(0);
50
+
51
+ subscriptions += child_button->on_clicked.Subscribe([this](){
52
+ OpenDialog();
53
+ });
54
+ subscriptions += child_entry->on_edited.Subscribe([this](){
55
+ path = child_entry->GetText();
56
+ });
57
+ }
58
+
59
+ void UIPathSelector::OpenDialog(){
60
+ nfdchar_t *outPath = nullptr;
61
+ nfdresult_t result = NFD_OpenDialog( NULL, (path=="") ? NULL : path.c_str() , &outPath );
62
+ if(result == NFD_OKAY){
63
+ path = outPath;
64
+ on_selected.Happen(path);
65
+ child_entry->SetText(path);
66
+ free(outPath);
67
+ }
68
+ }
69
+
70
+ void UIPathSelector::SetName(std::string t){
71
+ child_entry->SetDefaultText(t);
72
+ }
73
+
74
+ } // namespace AlgAudio
pool/shard006/C++/0083648_current.cpp ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ScummVM - Graphic Adventure Engine
2
+ *
3
+ * ScummVM is the legal property of its developers, whose names
4
+ * are too numerous to list here. Please refer to the COPYRIGHT
5
+ * file distributed with this source distribution.
6
+ *
7
+ * This program is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU General Public License
9
+ * as published by the Free Software Foundation; either version 2
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
+ *
21
+ */
22
+
23
+ #include "glk/alan3/current.h"
24
+
25
+ namespace Glk {
26
+ namespace Alan3 {
27
+
28
+ /* PUBLIC DATA */
29
+ CurVars current;
30
+ bool gameStateChanged = FALSE;
31
+
32
+ void CurVars::synchronize(Common::Serializer &s) {
33
+ s.syncAsSint32LE(syntax);
34
+ s.syncAsSint32LE(verb);
35
+ s.syncAsSint32LE(location);
36
+ s.syncAsSint32LE(actor);
37
+ s.syncAsSint32LE(instance);
38
+ s.syncAsSint32LE(tick);
39
+ s.syncAsSint32LE(score);
40
+ s.syncAsSint32LE(visits);
41
+ s.syncAsSint32LE(sourceLine);
42
+ s.syncAsSint32LE(sourceFile);
43
+ s.syncAsUint32LE(meta);
44
+ }
45
+
46
+ } // End of namespace Alan3
47
+ } // End of namespace Glk
pool/shard006/C++/0083654_82A.cpp ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cstdio>
2
+ #include <algorithm>
3
+ #include <string.h>
4
+ #include <cmath>
5
+
6
+ int main() {
7
+ int n;
8
+ scanf("%d", &n);
9
+ int rd = 0;
10
+ while (pow(2, rd)*5 < n) {
11
+ n -= pow(2, rd)*5;
12
+ rd++;
13
+ }
14
+ //printf("n = %d, rd = %d\n", n, rd);
15
+ int take = pow(2, rd);
16
+ switch (n%take==0?(n/take)-1:n/take) {
17
+ case 0:
18
+ printf("Sheldon\n");
19
+ break;
20
+ case 1:
21
+ printf("Leonard\n");
22
+ break;
23
+ case 2:
24
+ printf("Penny\n");
25
+ break;
26
+ case 3:
27
+ printf("Rajesh\n");
28
+ break;
29
+ default:
30
+ printf("Howard\n");
31
+ break;
32
+ }
33
+ return 0;
34
+ }
pool/shard006/C++/0083657_main.cpp ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <fstream>
3
+ #include <sstream>
4
+ #include <algorithm>
5
+ #include <vector>
6
+ #include <string>
7
+
8
+ #include "cat.h"
9
+
10
+ float average(std::string s);
11
+ void readin(std::ifstream &in, std::vector<Cat> &cats);
12
+ void print(std::ofstream &out, std::vector<Cat> &cats);
13
+ void print_extraLines(std::ofstream &out, std::vector<Cat> &cats);
14
+ void print_extraSpaces(std::ofstream &out, std::vector<Cat> &cats);
15
+ void print_lineOrder(std::ofstream &out, const std::vector<Cat> &cats);
16
+ void print_frontSpacing(std::ofstream &out, std::vector<Cat> &cats);
17
+ void print_columnSpacing(std::ofstream &out, std::vector<Cat> &cats);
18
+
19
+ //========================================================================================================
20
+
21
+ int main(int argc, char* argv[])
22
+ {
23
+ //check command line arguments
24
+ if(argc != 3)
25
+ {
26
+ std::cerr << "Wrong number of command line arguments" << std::endl;
27
+ exit(1);
28
+ }
29
+
30
+ //open input stream
31
+ std::ifstream in(argv[1]);
32
+ if(!in.good())
33
+ {
34
+ std::cerr << "Error opening input file" << std::endl;
35
+ exit(1);
36
+ }
37
+
38
+ //open output stream
39
+ std::ofstream out(argv[2]);
40
+ if(!out.good())
41
+ {
42
+ std::cerr << "Error opening output file" << std::endl;
43
+ }
44
+
45
+ std::vector<Cat> cats;
46
+
47
+ readin(in, cats);
48
+
49
+ //call a print function
50
+
51
+ //print(out, cats);
52
+ //print_extraLines(out, cats);
53
+ //print_extraSpaces(out, cats);
54
+ //print_lineOrder(out, cats);
55
+ //print_frontSpacing(out, cats);
56
+ print_columnSpacing(out, cats);
57
+
58
+ return 0;
59
+ }
60
+
61
+ //============================================================================================================
62
+
63
+ //extracts the lower and upper of the range in the string and averages them
64
+ float average(std::string s)
65
+ {
66
+ //get lower value of the range
67
+ std::size_t dash = s.find('-');
68
+ std::size_t start = 0;
69
+ std::string lowerValue = s.substr(start, dash);
70
+
71
+ //get upper value of the range
72
+ start = dash+1;
73
+ std::string upperValue = s.substr(start);
74
+
75
+ //convert strings to ints
76
+ int lower;
77
+ int upper;
78
+ std::istringstream(lowerValue) >> lower;
79
+ std::istringstream(upperValue) >> upper;
80
+
81
+ return (float)(upper + lower) / 2;
82
+ }
83
+
84
+ //read in from the input file
85
+ void readin(std::ifstream &in, std::vector<Cat> &cats)
86
+ {
87
+ std::string breed, lifeSpan, weight;
88
+ std::string interesting = "";
89
+ std::string s;
90
+ std::string classifier;
91
+ std::string unit;
92
+
93
+ in >> classifier;
94
+
95
+ while(!in.eof())
96
+ {
97
+ //take in the breed, life span as a string, weight as a string
98
+ in >> breed;
99
+ in >> classifier >> lifeSpan >> unit;
100
+ in >> classifier >> weight >> unit;
101
+ in >> classifier >> s;
102
+
103
+ //take in the interesting fact about the cat breed
104
+ while(!in.eof() && s != "BREED:")
105
+ {
106
+ interesting += s + " ";
107
+ in >> s;
108
+ }
109
+
110
+ //get the average from the range of values
111
+ float weightAverage = average(weight);
112
+ float lifeSpanAverage = average(lifeSpan);
113
+
114
+ cats.push_back(Cat(breed, lifeSpanAverage, weightAverage, interesting));
115
+
116
+ interesting = "";
117
+ }
118
+ }
119
+
120
+ //---------------------------------------------------------------------------------------------------------------------------
121
+ //functions to print
122
+
123
+ //print the output as expected
124
+ void print(std::ofstream &out, std::vector<Cat> &cats)
125
+ {
126
+ std::sort(cats.begin(), cats.end(), sortCats);
127
+ std::string spacing = " ";
128
+ for(unsigned int i = 0; i < cats.size(); i++)
129
+ {
130
+ out << cats[i].getBreed() << std::endl;
131
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl;
132
+ out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl;
133
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl;
134
+ }
135
+ }
136
+
137
+ //print the output with extra newlines at the end of every line
138
+ void print_extraLines(std::ofstream &out, std::vector<Cat> &cats)
139
+ {
140
+ std::sort(cats.begin(), cats.end(), sortCats);
141
+ std::string spacing = " ";
142
+ for(unsigned int i = 0; i < cats.size(); i++)
143
+ {
144
+ out << cats[i].getBreed() << std::endl << std::endl;
145
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan()
146
+ << std::endl << std::endl;
147
+ out << spacing << "Average Weight: " << cats[i].getAverageSize()
148
+ << std::endl << std::endl;
149
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact()
150
+ << std::endl << std::endl;
151
+ }
152
+ }
153
+
154
+ //print the output with extra spaces at the end of every line
155
+ void print_extraSpaces(std::ofstream &out, std::vector<Cat> &cats)
156
+ {
157
+ std::sort(cats.begin(), cats.end(), sortCats);
158
+ std::string spacing = " ";
159
+ for(unsigned int i = 0; i < cats.size(); i++)
160
+ {
161
+ out << cats[i].getBreed() << " " << std::endl;
162
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan()
163
+ << " " << std::endl;
164
+ out << spacing << "Average Weight: " << cats[i].getAverageSize()
165
+ << " " << std::endl;
166
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact()
167
+ << " " << std::endl;
168
+ }
169
+ }
170
+
171
+ //print the output with the lines in the wrong order
172
+ void print_lineOrder(std::ofstream &out, const std::vector<Cat> &cats)
173
+ {
174
+ std::string spacing = " ";
175
+ for(unsigned int i = 0; i < cats.size(); i++)
176
+ {
177
+ out << cats[i].getBreed() << std::endl;
178
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl;
179
+ out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl;
180
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl;
181
+ }
182
+ }
183
+
184
+ //print the output with the spacing in front off (expected: 5 spaces)
185
+ void print_frontSpacing(std::ofstream &out, std::vector<Cat> &cats)
186
+ {
187
+ std::sort(cats.begin(), cats.end(), sortCats);
188
+ std::string spacing = " ";
189
+ for(unsigned int i = 0; i < cats.size(); i++)
190
+ {
191
+ out << cats[i].getBreed() << std::endl;
192
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl;
193
+ out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl;
194
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl;
195
+ }
196
+ }
197
+
198
+ //print the output with the column spacing off
199
+ //(expected: 1 space between 1st column and 2nd, 1st column the length of the longest attribute)
200
+ void print_columnSpacing(std::ofstream &out, std::vector<Cat> &cats)
201
+ {
202
+ std::sort(cats.begin(), cats.end(), sortCats);
203
+ std::string spacing = " ";
204
+ for(unsigned int i = 0; i < cats.size(); i++)
205
+ {
206
+ out << cats[i].getBreed() << std::endl;
207
+ out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl;
208
+ out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl;
209
+ out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl;
210
+ }
211
+ }
pool/shard006/C++/0083662_user_script_slave.cc ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2009 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/renderer/user_script_slave.h"
6
+
7
+ #include "app/resource_bundle.h"
8
+ #include "base/histogram.h"
9
+ #include "base/logging.h"
10
+ #include "base/perftimer.h"
11
+ #include "base/pickle.h"
12
+ #include "base/shared_memory.h"
13
+ #include "base/string_util.h"
14
+ #include "googleurl/src/gurl.h"
15
+ #include "webkit/api/public/WebScriptSource.h"
16
+ #include "webkit/glue/webframe.h"
17
+
18
+ #include "grit/renderer_resources.h"
19
+
20
+ using WebKit::WebScriptSource;
21
+ using WebKit::WebString;
22
+
23
+ // These two strings are injected before and after the Greasemonkey API and
24
+ // user script to wrap it in an anonymous scope.
25
+ static const char kUserScriptHead[] = "(function (unsafeWindow) {\n";
26
+ static const char kUserScriptTail[] = "\n})(window);";
27
+
28
+ // Creates a convenient reference to a content script's parent extension.
29
+ // TODO(mpcomplete): self.onConnect is deprecated. Remove it at 1.0.
30
+ // http://code.google.com/p/chromium/issues/detail?id=16356
31
+ static const char kInitExtension[] =
32
+ "chrome.extension = new chrome.Extension('%s');"
33
+ "chrome.self.onConnect = chrome.extension.onConnect;";
34
+
35
+ UserScriptSlave::UserScriptSlave()
36
+ : shared_memory_(NULL),
37
+ script_deleter_(&scripts_),
38
+ user_script_start_line_(0) {
39
+ // TODO: Only windows supports resources and only windows supports user
40
+ // scrips, so only load the Greasemonkey API on windows. Fix this when
41
+ // better cross platofrm support is available.
42
+ #if defined(OS_WIN)
43
+ api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource(
44
+ IDR_GREASEMONKEY_API_JS);
45
+ #endif
46
+
47
+ // Count the number of lines that will be injected before the user script.
48
+ StringPiece::size_type pos = 0;
49
+ while ((pos = api_js_.find('\n', pos)) != StringPiece::npos) {
50
+ user_script_start_line_++;
51
+ pos++;
52
+ }
53
+
54
+ // NOTE: There is actually one extra line in the injected script because the
55
+ // function header includes a newline as well. But WebKit expects the
56
+ // numbering to be one-based, not zero-based, so actually *not* accounting for
57
+ // this extra line ends us up with the right offset.
58
+ }
59
+
60
+ bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) {
61
+ scripts_.clear();
62
+
63
+ // Create the shared memory object (read only).
64
+ shared_memory_.reset(new base::SharedMemory(shared_memory, true));
65
+ if (!shared_memory_.get())
66
+ return false;
67
+
68
+ // First get the size of the memory block.
69
+ if (!shared_memory_->Map(sizeof(Pickle::Header)))
70
+ return false;
71
+ Pickle::Header* pickle_header =
72
+ reinterpret_cast<Pickle::Header*>(shared_memory_->memory());
73
+
74
+ // Now map in the rest of the block.
75
+ int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size;
76
+ shared_memory_->Unmap();
77
+ if (!shared_memory_->Map(pickle_size))
78
+ return false;
79
+
80
+ // Unpickle scripts.
81
+ void* iter = NULL;
82
+ size_t num_scripts = 0;
83
+ Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()),
84
+ pickle_size);
85
+ pickle.ReadSize(&iter, &num_scripts);
86
+
87
+ scripts_.reserve(num_scripts);
88
+ for (size_t i = 0; i < num_scripts; ++i) {
89
+ scripts_.push_back(new UserScript());
90
+ UserScript* script = scripts_.back();
91
+ script->Unpickle(pickle, &iter);
92
+
93
+ // Note that this is a pointer into shared memory. We don't own it. It gets
94
+ // cleared up when the last renderer or browser process drops their
95
+ // reference to the shared memory.
96
+ for (size_t j = 0; j < script->js_scripts().size(); ++j) {
97
+ const char* body = NULL;
98
+ int body_length = 0;
99
+ CHECK(pickle.ReadData(&iter, &body, &body_length));
100
+ script->js_scripts()[j].set_external_content(
101
+ StringPiece(body, body_length));
102
+ }
103
+ for (size_t j = 0; j < script->css_scripts().size(); ++j) {
104
+ const char* body = NULL;
105
+ int body_length = 0;
106
+ CHECK(pickle.ReadData(&iter, &body, &body_length));
107
+ script->css_scripts()[j].set_external_content(
108
+ StringPiece(body, body_length));
109
+ }
110
+ }
111
+
112
+ return true;
113
+ }
114
+
115
+ bool UserScriptSlave::InjectScripts(WebFrame* frame,
116
+ UserScript::RunLocation location) {
117
+ PerfTimer timer;
118
+ int num_matched = 0;
119
+
120
+ for (size_t i = 0; i < scripts_.size(); ++i) {
121
+ std::vector<WebScriptSource> sources;
122
+ UserScript* script = scripts_[i];
123
+ if (!script->MatchesUrl(frame->GetURL()))
124
+ continue; // This frame doesn't match the script url pattern, skip it.
125
+
126
+ ++num_matched;
127
+ // CSS files are always injected on document start before js scripts.
128
+ if (location == UserScript::DOCUMENT_START) {
129
+ for (size_t j = 0; j < script->css_scripts().size(); ++j) {
130
+ UserScript::File& file = script->css_scripts()[j];
131
+ frame->InsertCSSStyles(file.GetContent().as_string());
132
+ }
133
+ }
134
+ if (script->run_location() == location) {
135
+ for (size_t j = 0; j < script->js_scripts().size(); ++j) {
136
+ UserScript::File &file = script->js_scripts()[j];
137
+ std::string content = file.GetContent().as_string();
138
+
139
+ // We add this dumb function wrapper for standalone user script to
140
+ // emulate what Greasemonkey does.
141
+ if (script->is_standalone()) {
142
+ content.insert(0, kUserScriptHead);
143
+ content += kUserScriptTail;
144
+ }
145
+ sources.push_back(WebScriptSource(
146
+ WebString::fromUTF8(content.c_str(), content.length()),
147
+ file.url()));
148
+ }
149
+ }
150
+
151
+ if (!sources.empty()) {
152
+ if (script->is_standalone()) {
153
+ // For standalone scripts, we try to emulate the Greasemonkey API.
154
+ sources.insert(sources.begin(),
155
+ WebScriptSource(WebString::fromUTF8(api_js_.as_string())));
156
+ } else {
157
+ // Setup chrome.self to contain an Extension object with the correct
158
+ // ID.
159
+ sources.insert(sources.begin(),
160
+ WebScriptSource(WebString::fromUTF8(
161
+ StringPrintf(kInitExtension, script->extension_id().c_str()))));
162
+ }
163
+
164
+ frame->ExecuteScriptInNewContext(&sources.front(), sources.size());
165
+ }
166
+ }
167
+
168
+ // Log debug info.
169
+ if (location == UserScript::DOCUMENT_START) {
170
+ HISTOGRAM_COUNTS_100("UserScripts:DocStart:Count", num_matched);
171
+ HISTOGRAM_TIMES("UserScripts:DocStart:Time", timer.Elapsed());
172
+ } else {
173
+ HISTOGRAM_COUNTS_100("UserScripts:DocEnd:Count", num_matched);
174
+ HISTOGRAM_TIMES("UserScripts:DocEnd:Time", timer.Elapsed());
175
+ }
176
+
177
+ LOG(INFO) << "Injected " << num_matched << " user scripts into " <<
178
+ frame->GetURL().spec();
179
+ return true;
180
+ }
pool/shard006/C++/0083663_MPHasher.cpp ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "MPHasher.h"
2
+ #include "EventTypeName.h"
3
+ #include <algorithm>
4
+
5
+ namespace mParticle {
6
+ __attribute__((no_sanitize("integer")))
7
+ int Hasher::hashFromString(const string &stringToHash) {
8
+ if (stringToHash.empty()) {
9
+ return 0;
10
+ }
11
+
12
+ string lowerCaseStringToHash = stringToHash;
13
+ transform(lowerCaseStringToHash.begin(), lowerCaseStringToHash.end(), lowerCaseStringToHash.begin(), ::tolower);
14
+
15
+ int hash = 0;
16
+ for (auto &character : lowerCaseStringToHash) {
17
+ hash = ((hash << 5) - hash) + character;
18
+ }
19
+
20
+ return hash;
21
+ }
22
+
23
+ string Hasher::hashString(string stringToHash) {
24
+ if (stringToHash.empty()) {
25
+ return "";
26
+ }
27
+
28
+ auto hash = Hasher::hashFromString(stringToHash);
29
+
30
+ auto hashString = to_string(hash);
31
+ return hashString;
32
+ }
33
+
34
+ vector<string> Hasher::hashedEventTypes(const vector<int> &eventTypes) {
35
+ vector<string> hashedTypes;
36
+
37
+ if (eventTypes.empty()) {
38
+ return hashedTypes;
39
+ }
40
+
41
+ for (auto &eventType : eventTypes) {
42
+ auto eventTypeString = to_string(eventType);
43
+ auto hashedEventType = Hasher::hashString(eventTypeString);
44
+ hashedTypes.push_back(hashedEventType);
45
+ }
46
+
47
+ return hashedTypes;
48
+ }
49
+
50
+ vector<string> Hasher::hashedAllEventTypes() {
51
+ vector<int> eventTypes(EventTypeName::count);
52
+
53
+ int i = 0;
54
+ for_each(eventTypes.begin(), eventTypes.end(), [&i](int &eventType) {eventType = i++;});
55
+
56
+ vector<string> hashes = Hasher::hashedEventTypes(eventTypes);
57
+ return hashes;
58
+ }
59
+
60
+ string Hasher::hashEvent(string eventName, string eventType) {
61
+ eventName.append(eventType);
62
+ return Hasher::hashString(eventName);
63
+ }
64
+
65
+ __attribute__((no_sanitize("integer")))
66
+ int64_t Hasher::hashFNV1a(const char *bytes, int length) {
67
+ // FNV-1a hashing
68
+ int64_t rampHash = 0xcbf29ce484222325;
69
+
70
+ int i = 0;
71
+ while (i < length) {
72
+ rampHash = (rampHash ^ bytes[i]) * 0x100000001B3;
73
+ i += 1;
74
+ }
75
+
76
+ return rampHash;
77
+ }
78
+ }
pool/shard006/C++/0083666_clientsideeffects_test.cpp ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ========
2
+ //
3
+ // The copyright to the contents herein is the property of Valve, L.L.C.
4
+ // The contents may be used and/or copied only with the written permission of
5
+ // Valve, L.L.C., or in accordance with the terms and conditions stipulated in
6
+ // the agreement/contract under which the contents have been supplied.
7
+ //
8
+ // Purpose:
9
+ //
10
+ // $Workfile: $
11
+ // $NoKeywords: $
12
+ //=============================================================================
13
+ #include "cbase.h"
14
+ #include "engine/IEngineSound.h"
15
+ #include "view.h"
16
+
17
+ #include "fx_line.h"
18
+ #include "fx_discreetline.h"
19
+ #include "fx_quad.h"
20
+ #include "clientsideeffects.h"
21
+
22
+ #include "SoundEmitterSystemBase.h"
23
+ #include "tier0/vprof.h"
24
+
25
+ //FIXME: All these functions will be moved out to FX_Main.CPP or a individual folder
26
+
27
+ /*
28
+ ==================================================
29
+ FX_AddStaticLine
30
+ ==================================================
31
+ */
32
+
33
+ void FX_AddStaticLine( const Vector& start, const Vector& end, float scale, float life, const char *materialName, unsigned char flags )
34
+ {
35
+ CFXStaticLine *t = new CFXStaticLine( "StaticLine", start, end, scale, life, materialName, flags );
36
+ assert( t );
37
+
38
+ //Throw it into the list
39
+ clienteffects->AddEffect( t );
40
+ }
41
+
42
+ /*
43
+ ==================================================
44
+ FX_AddDiscreetLine
45
+ ==================================================
46
+ */
47
+
48
+ void FX_AddDiscreetLine( const Vector& start, const Vector& direction, float velocity, float length, float clipLength, float scale, float life, const char *shader )
49
+ {
50
+ CFXDiscreetLine *t = new CFXDiscreetLine( "Line", start, direction, velocity, length, clipLength, scale, life, shader );
51
+ assert( t );
52
+
53
+ //Throw it into the list
54
+ clienteffects->AddEffect( t );
55
+ }
56
+
57
+ //-----------------------------------------------------------------------------
58
+ // Purpose:
59
+ //-----------------------------------------------------------------------------
60
+ void FX_AddQuad( const FXQuadData_t &data )
61
+ {
62
+ CFXQuad *quad = new CFXQuad( data );
63
+
64
+ Assert( quad != NULL );
65
+
66
+ clienteffects->AddEffect( quad );
67
+ }
68
+ //-----------------------------------------------------------------------------
69
+ // Purpose: Parameter heavy version
70
+ //-----------------------------------------------------------------------------
71
+ void FX_AddQuad( const Vector &origin,
72
+ const Vector &normal,
73
+ float startSize,
74
+ float endSize,
75
+ float sizeBias,
76
+ float startAlpha,
77
+ float endAlpha,
78
+ float alphaBias,
79
+ float yaw,
80
+ float deltaYaw,
81
+ const Vector &color,
82
+ float lifeTime,
83
+ const char *shader,
84
+ unsigned int flags )
85
+ {
86
+ FXQuadData_t data;
87
+
88
+ //Setup the data
89
+ data.SetAlpha( startAlpha, endAlpha );
90
+ data.SetScale( startSize, endSize );
91
+ data.SetFlags( flags );
92
+ data.SetMaterial( shader );
93
+ data.SetNormal( normal );
94
+ data.SetOrigin( origin );
95
+ data.SetLifeTime( lifeTime );
96
+ data.SetColor( color[0], color[1], color[2] );
97
+ data.SetScaleBias( sizeBias );
98
+ data.SetAlphaBias( alphaBias );
99
+ data.SetYaw( yaw, deltaYaw );
100
+
101
+ //Output it
102
+ FX_AddQuad( data );
103
+ }
104
+
105
+ //-----------------------------------------------------------------------------
106
+ // Purpose: Creates a test effect
107
+ //-----------------------------------------------------------------------------
108
+ void CreateTestEffect( void )
109
+ {
110
+ //NOTENOTE: Add any test effects here
111
+ //FX_BulletPass( NULL, NULL );
112
+ }
113
+
114
+ /*
115
+ ==================================================
116
+ UTIL_NearestPointOnLine
117
+ ==================================================
118
+ */
119
+
120
+ float UTIL_NearestPointOnLine( const Vector& start, const Vector& end, const Vector& target, Vector& out )
121
+ {
122
+ Vector lineDir, targetDir;
123
+ float dot;
124
+
125
+ //Find the direction of the line
126
+ VectorSubtract( end, start, lineDir );
127
+ VectorNormalize( lineDir );
128
+
129
+ //Find the direction of the target to the line's path
130
+ VectorSubtract( target, start, targetDir );
131
+
132
+ //Find the nearest point to the target on that line
133
+ dot = DotProduct( targetDir, lineDir );
134
+ VectorScale( lineDir, dot, out );
135
+ VectorAdd( start, out, out );
136
+
137
+ //Find the distance to the nearest point
138
+ VectorSubtract( out, target, targetDir );
139
+
140
+ return VectorLength( targetDir );
141
+ }
142
+
143
+ /*
144
+ ==================================================
145
+ FX_PlayerTracer
146
+ ==================================================
147
+ */
148
+
149
+ #define TRACER_BASE_OFFSET 8
150
+
151
+ void FX_PlayerTracer( Vector& start, Vector& end )
152
+ {
153
+ VPROF_BUDGET( "FX_PlayerTracer", VPROF_BUDGETGROUP_PARTICLE_RENDERING );
154
+ Vector shotDir, dStart, dEnd;
155
+ float length;
156
+
157
+ //Find the direction of the tracer
158
+ VectorSubtract( end, start, shotDir );
159
+ length = VectorNormalize( shotDir );
160
+
161
+ //We don't want to draw them if they're too close to us
162
+ if ( length < 256 )
163
+ return;
164
+
165
+ //Randomly place the tracer along this line, with a random length
166
+ VectorMA( start, TRACER_BASE_OFFSET + random->RandomFloat( -24.0f, 64.0f ), shotDir, dStart );
167
+ VectorMA( dStart, ( length * random->RandomFloat( 0.1f, 0.6f ) ), shotDir, dEnd );
168
+
169
+ //Create the line
170
+ CFXStaticLine *t;
171
+ const char *materialName;
172
+
173
+ //materialName = ( random->RandomInt( 0, 1 ) ) ? "effects/tracer_middle" : "effects/tracer_middle2";
174
+ materialName = "effects/spark";
175
+
176
+ t = new CFXStaticLine( "Tracer", dStart, dEnd, random->RandomFloat( 0.5f, 0.75f ), 0.01f, materialName, 0 );
177
+ assert( t );
178
+
179
+ //Throw it into the list
180
+ clienteffects->AddEffect( t );
181
+ }
182
+
183
+ /*
184
+ ==================================================
185
+ FX_Tracer
186
+ ==================================================
187
+ */
188
+ // Tracer must be this close to be considered for hearing
189
+ #define TRACER_MAX_HEAR_DIST (6*12)
190
+ #define TRACER_SOUND_TIME_MIN 0.10f
191
+ #define TRACER_SOUND_TIME_MAX 0.10f
192
+
193
+
194
+ class CBulletWhizTimer : public CAutoGameSystem
195
+ {
196
+ public:
197
+ void LevelInitPreEntity()
198
+ {
199
+ m_nextWhizTime = 0;
200
+ }
201
+
202
+ float m_nextWhizTime;
203
+ };
204
+
205
+ // Client-side tracking for whiz noises
206
+ CBulletWhizTimer g_BulletWhiz;
207
+
208
+ //-----------------------------------------------------------------------------
209
+ // Purpose:
210
+ // Input : &vecStart -
211
+ // &vecDir -
212
+ // iTracerType -
213
+ //-----------------------------------------------------------------------------
214
+ void FX_TracerSound( const Vector &start, const Vector &end, int iTracerType )
215
+ {
216
+ const char *pszSoundName = NULL;
217
+
218
+ switch( iTracerType )
219
+ {
220
+ case TRACER_TYPE_DEFAULT:
221
+ pszSoundName = "Bullets.DefaultNearmiss";
222
+ break;
223
+
224
+ case TRACER_TYPE_GUNSHIP:
225
+ pszSoundName = "Bullets.GunshipNearmiss";
226
+ break;
227
+
228
+ case TRACER_TYPE_STRIDER:
229
+ pszSoundName = "Bullets.StriderNearmiss";
230
+ break;
231
+
232
+ default:
233
+ return;
234
+ break;
235
+ }
236
+
237
+ if( pszSoundName )
238
+ {
239
+ //Get out shot direction and length
240
+ float totalDist;
241
+ Vector shotDir;
242
+
243
+ VectorSubtract( end, start, shotDir );
244
+ totalDist = VectorNormalize( shotDir );
245
+
246
+ float dt = g_BulletWhiz.m_nextWhizTime - gpGlobals->curtime;
247
+
248
+ //If needed, make a bullet whiz noise
249
+ if ( dt <= 0 )
250
+ {
251
+ Vector vNear, dStart, dEnd;
252
+
253
+ //Find the nearest point to our view on the bullet's path
254
+ float vDist = UTIL_NearestPointOnLine( start, end, MainViewOrigin(), vNear );
255
+
256
+ //See if we should play a bullet whizz
257
+ if ( vDist <= TRACER_MAX_HEAR_DIST )
258
+ {
259
+ CLocalPlayerFilter filter;
260
+ CSoundParameters params;
261
+
262
+ if( C_BaseEntity::GetParametersForSound( pszSoundName, params ) )
263
+ {
264
+ enginesound->EmitSound( filter, SOUND_FROM_WORLD, CHAN_STATIC, params.soundname, params.volume, SNDLVL_TO_ATTN(params.soundlevel), 0, params.pitch, &start, &shotDir, false);
265
+ }
266
+
267
+ //Don't play another bullet whiz for this client until this time has run out
268
+ g_BulletWhiz.m_nextWhizTime = gpGlobals->curtime + random->RandomFloat( TRACER_SOUND_TIME_MIN, TRACER_SOUND_TIME_MAX );
269
+
270
+ }
271
+ }
272
+ }
273
+ }
274
+
275
+
276
+ void FX_Tracer( Vector& start, Vector& end, int velocity, bool makeWhiz )
277
+ {
278
+ VPROF_BUDGET( "FX_Tracer", VPROF_BUDGETGROUP_PARTICLE_RENDERING );
279
+ //Don't make small tracers
280
+ float dist;
281
+ Vector dir;
282
+
283
+ VectorSubtract( end, start, dir );
284
+ dist = VectorNormalize( dir );
285
+
286
+ // Don't make short tracers.
287
+ if ( dist < 256 )
288
+ {
289
+ return;
290
+ }
291
+
292
+ float length = random->RandomFloat( 64.0f, 128.0f );
293
+ float life = ( dist + length ) / velocity; //NOTENOTE: We want the tail to finish its run as well
294
+
295
+ //Add it
296
+ FX_AddDiscreetLine( start, dir, velocity, length, dist, random->RandomFloat( 0.75f, 0.9f ), life, "effects/spark" );
297
+
298
+ if( makeWhiz )
299
+ {
300
+ FX_TracerSound( start, end, TRACER_TYPE_DEFAULT );
301
+ }
302
+ }
pool/shard006/C++/0083671_test_context_provider_factory.cc ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "webkit/gpu/test_context_provider_factory.h"
6
+
7
+ #include "base/logging.h"
8
+ #include "cc/output/context_provider.h"
9
+ #include "webkit/gpu/context_provider_in_process.h"
10
+
11
+ namespace webkit {
12
+ namespace gpu {
13
+
14
+ static TestContextProviderFactory* context_provider_instance = NULL;
15
+
16
+ // static
17
+ TestContextProviderFactory* TestContextProviderFactory::GetInstance() {
18
+ if (!context_provider_instance)
19
+ context_provider_instance = new TestContextProviderFactory();
20
+ return context_provider_instance;
21
+ }
22
+
23
+ TestContextProviderFactory::TestContextProviderFactory() {}
24
+
25
+ TestContextProviderFactory::~TestContextProviderFactory() {}
26
+
27
+ scoped_refptr<cc::ContextProvider> TestContextProviderFactory::
28
+ OffscreenContextProviderForMainThread() {
29
+ if (!main_thread_ || main_thread_->DestroyedOnMainThread()) {
30
+ main_thread_ = ContextProviderInProcess::Create();
31
+ if (main_thread_ && !main_thread_->BindToCurrentThread())
32
+ main_thread_ = NULL;
33
+ }
34
+ return main_thread_;
35
+ }
36
+
37
+ scoped_refptr<cc::ContextProvider> TestContextProviderFactory::
38
+ OffscreenContextProviderForCompositorThread() {
39
+ if (!compositor_thread_ ||
40
+ compositor_thread_->DestroyedOnMainThread())
41
+ compositor_thread_ = ContextProviderInProcess::Create();
42
+ return compositor_thread_;
43
+ }
44
+
45
+ } // namespace gpu
46
+ } // namespace webkit
pool/shard006/C++/0083679_rtcp_format_remb_unittest.cc ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3
+ *
4
+ * Use of this source code is governed by a BSD-style license
5
+ * that can be found in the LICENSE file in the root of the source
6
+ * tree. An additional intellectual property rights grant can be found
7
+ * in the file PATENTS. All contributing project authors may
8
+ * be found in the AUTHORS file in the root of the source tree.
9
+ */
10
+
11
+ #include "testing/gtest/include/gtest/gtest.h"
12
+
13
+ #include "webrtc/common_types.h"
14
+ #include "webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h"
15
+ #include "webrtc/modules/remote_bitrate_estimator/include/mock/mock_remote_bitrate_observer.h"
16
+ #include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h"
17
+ #include "webrtc/modules/rtp_rtcp/source/rtcp_sender.h"
18
+ #include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_impl.h"
19
+ #include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
20
+ #include "webrtc/typedefs.h"
21
+
22
+ namespace {
23
+
24
+ using namespace webrtc;
25
+
26
+
27
+ class TestTransport : public Transport {
28
+ public:
29
+ TestTransport(RTCPReceiver* rtcp_receiver) :
30
+ rtcp_receiver_(rtcp_receiver) {
31
+ }
32
+
33
+ virtual int SendPacket(int /*channel*/, const void* /*data*/, int /*len*/) {
34
+ return -1;
35
+ }
36
+ virtual int SendRTCPPacket(int /*channel*/,
37
+ const void *packet,
38
+ int packetLength) {
39
+ RTCPUtility::RTCPParserV2 rtcpParser((uint8_t*)packet,
40
+ (int32_t)packetLength,
41
+ true); // Allow non-compound RTCP
42
+
43
+ EXPECT_TRUE(rtcpParser.IsValid());
44
+ RTCPHelp::RTCPPacketInformation rtcpPacketInformation;
45
+ EXPECT_EQ(0, rtcp_receiver_->IncomingRTCPPacket(rtcpPacketInformation,
46
+ &rtcpParser));
47
+
48
+ EXPECT_EQ((uint32_t)kRtcpRemb,
49
+ rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRemb);
50
+ EXPECT_EQ((uint32_t)1234,
51
+ rtcpPacketInformation.receiverEstimatedMaxBitrate);
52
+ return packetLength;
53
+ }
54
+ private:
55
+ RTCPReceiver* rtcp_receiver_;
56
+ };
57
+
58
+
59
+ class RtcpFormatRembTest : public ::testing::Test {
60
+ protected:
61
+ static const uint32_t kRemoteBitrateEstimatorMinBitrateBps = 30000;
62
+
63
+ RtcpFormatRembTest()
64
+ : over_use_detector_options_(),
65
+ system_clock_(Clock::GetRealTimeClock()),
66
+ receive_statistics_(ReceiveStatistics::Create(system_clock_)),
67
+ remote_bitrate_observer_(),
68
+ remote_bitrate_estimator_(
69
+ RemoteBitrateEstimatorFactory().Create(
70
+ &remote_bitrate_observer_,
71
+ system_clock_,
72
+ kMimdControl,
73
+ kRemoteBitrateEstimatorMinBitrateBps)) {}
74
+ virtual void SetUp();
75
+ virtual void TearDown();
76
+
77
+ OverUseDetectorOptions over_use_detector_options_;
78
+ Clock* system_clock_;
79
+ ModuleRtpRtcpImpl* dummy_rtp_rtcp_impl_;
80
+ scoped_ptr<ReceiveStatistics> receive_statistics_;
81
+ RTCPSender* rtcp_sender_;
82
+ RTCPReceiver* rtcp_receiver_;
83
+ TestTransport* test_transport_;
84
+ MockRemoteBitrateObserver remote_bitrate_observer_;
85
+ scoped_ptr<RemoteBitrateEstimator> remote_bitrate_estimator_;
86
+ };
87
+
88
+ void RtcpFormatRembTest::SetUp() {
89
+ RtpRtcp::Configuration configuration;
90
+ configuration.id = 0;
91
+ configuration.audio = false;
92
+ configuration.clock = system_clock_;
93
+ configuration.remote_bitrate_estimator = remote_bitrate_estimator_.get();
94
+ dummy_rtp_rtcp_impl_ = new ModuleRtpRtcpImpl(configuration);
95
+ rtcp_sender_ =
96
+ new RTCPSender(0, false, system_clock_, receive_statistics_.get());
97
+ rtcp_receiver_ = new RTCPReceiver(0, system_clock_, dummy_rtp_rtcp_impl_);
98
+ test_transport_ = new TestTransport(rtcp_receiver_);
99
+
100
+ EXPECT_EQ(0, rtcp_sender_->Init());
101
+ EXPECT_EQ(0, rtcp_sender_->RegisterSendTransport(test_transport_));
102
+ }
103
+
104
+ void RtcpFormatRembTest::TearDown() {
105
+ delete rtcp_sender_;
106
+ delete rtcp_receiver_;
107
+ delete dummy_rtp_rtcp_impl_;
108
+ delete test_transport_;
109
+ }
110
+
111
+ TEST_F(RtcpFormatRembTest, TestBasicAPI) {
112
+ EXPECT_FALSE(rtcp_sender_->REMB());
113
+ EXPECT_EQ(0, rtcp_sender_->SetREMBStatus(true));
114
+ EXPECT_TRUE(rtcp_sender_->REMB());
115
+ EXPECT_EQ(0, rtcp_sender_->SetREMBStatus(false));
116
+ EXPECT_FALSE(rtcp_sender_->REMB());
117
+
118
+ EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 0, NULL));
119
+ }
120
+
121
+ TEST_F(RtcpFormatRembTest, TestNonCompund) {
122
+ uint32_t SSRC = 456789;
123
+ EXPECT_EQ(0, rtcp_sender_->SetRTCPStatus(kRtcpNonCompound));
124
+ EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 1, &SSRC));
125
+ RTCPSender::FeedbackState feedback_state(dummy_rtp_rtcp_impl_);
126
+ EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpRemb));
127
+ }
128
+
129
+ TEST_F(RtcpFormatRembTest, TestCompund) {
130
+ uint32_t SSRCs[2] = {456789, 98765};
131
+ EXPECT_EQ(0, rtcp_sender_->SetRTCPStatus(kRtcpCompound));
132
+ EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 2, SSRCs));
133
+ RTCPSender::FeedbackState feedback_state(dummy_rtp_rtcp_impl_);
134
+ EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpRemb));
135
+ }
136
+ } // namespace
pool/shard006/C++/0083681_viewbasis_funcs.cpp ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *** Qt GUI: View Basis dialog functions
3
+ *** src/gui/viewbasis_funcs.cpp
4
+ Copyright T. Youngs 2007-2015
5
+
6
+ This file is part of Aten.
7
+
8
+ Aten is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ Aten 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 Aten. If not, see <http://www.gnu.org/licenses/>.
20
+ */
21
+
22
+ #include "main/aten.h"
23
+ #include "gui/viewbasis.h"
24
+ #include "gui/mainwindow.h"
25
+ #include "base/messenger.h"
26
+ #include "base/sysfunc.h"
27
+ #include "model/model.h"
28
+
29
+ // Constructor
30
+ AtenViewBasis::AtenViewBasis(QWidget* parent, Qt::WindowFlags flags) : QDialog(parent,flags)
31
+ {
32
+ // Private variables
33
+ target_ = NULL;
34
+
35
+ ui.setupUi(this);
36
+ }
37
+
38
+ void AtenViewBasis::showWindow(Model* m)
39
+ {
40
+ // Clear old contents
41
+ ui.BasisTable->clear();
42
+ ui.BasisTable->setColumnCount(10);
43
+ ui.BasisTable->setHorizontalHeaderLabels(QStringList() << "Atom" << "Shell" << "Type" << "Exponent" << "Coefficients" << " " << " " << " " << " " << " " );
44
+ // Check model pointer
45
+ if (m == NULL) return;
46
+ // If no basis definition exists in the supplied model, try to look at the trajectory parent
47
+ target_ = m;
48
+ if ((target_->basisShells() == NULL) && (target_->parent() != NULL))
49
+ {
50
+ target_ = target_->parent();
51
+ Messenger::print("No basis definition found in trajectory frame - looking in parent model...");
52
+ }
53
+ // Determine total row count
54
+ BasisShell *bas;
55
+ BasisPrimitive* prim;
56
+ int row = 0, shell, lastid = -1, n, ncartesians = 0;
57
+ Dnchar text;
58
+ for (bas = target_->basisShells(); bas != NULL; bas = bas->next) row += bas->nPrimitives();
59
+ ui.BasisTable->setRowCount(row);
60
+ ui.BasisShellsLabel->setText(itoa(target_->nBasisShells()));
61
+ // Populate table
62
+ QTableWidgetItem *tabitem;
63
+ row = 0;
64
+ shell = 0;
65
+ for (bas = target_->basisShells(); bas != NULL; bas = bas->next)
66
+ {
67
+ ++shell;
68
+ ncartesians += BasisShell::nCartesianFunctions(bas->type());
69
+ // Create atom id item?
70
+ if (lastid != bas->atomId())
71
+ {
72
+ lastid = bas->atomId();
73
+ tabitem = new QTableWidgetItem();
74
+ text.sprintf("%i (%s)\n", lastid+1, m->atom(lastid) != NULL ? Elements().symbol(m->atom(lastid)) : "NULL");
75
+ tabitem->setText(text.get());
76
+ ui.BasisTable->setItem(row, AtenViewBasis::AtomIdColumn, tabitem);
77
+ }
78
+ // Add in shell data
79
+ tabitem = new QTableWidgetItem();
80
+ tabitem->setText(itoa(shell));
81
+ ui.BasisTable->setItem(row, AtenViewBasis::ShellColumn, tabitem);
82
+ tabitem = new QTableWidgetItem();
83
+ tabitem->setText(BasisShell::basisShellType(bas->type()));
84
+ ui.BasisTable->setItem(row, AtenViewBasis::TypeColumn, tabitem);
85
+
86
+ // Cycle over primitives
87
+ n = 0;
88
+ for (prim = bas->primitives(); prim != NULL; prim = prim->next)
89
+ {
90
+ tabitem = new QTableWidgetItem();
91
+ tabitem->setText(ftoa(prim->exponent()));
92
+ ui.BasisTable->setItem(row, AtenViewBasis::ExponentColumn, tabitem);
93
+ for (n = 0; n < prim->nCoefficients(); ++n)
94
+ {
95
+ tabitem = new QTableWidgetItem();
96
+ tabitem->setText(ftoa(prim->coefficient(n)));
97
+ ui.BasisTable->setItem(row, AtenViewBasis::CoefficientColumn+n, tabitem);
98
+ }
99
+ row++;
100
+ }
101
+ }
102
+ ui.BasisCartesiansLabel->setText(itoa(ncartesians));
103
+ // Resize columns
104
+ for (n=0; n<AtenViewBasis::nColumns; ++n) ui.BasisTable->resizeColumnToContents(n);
105
+ show();
106
+ }
107
+
108
+ void AtenViewBasis::dialogFinished(int result)
109
+ {
110
+ accept();
111
+ }
112
+
pool/shard006/C++/0083683_osc_route_observer.cc ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (C) 2009 Paul Davis
3
+
4
+ This program is free software; you can redistribute it and/or modify
5
+ it under the terms of the GNU General Public License as published by
6
+ the Free Software Foundation; either version 2 of the License, or
7
+ (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU General Public License for more details.
13
+
14
+ You should have received a copy of the GNU General Public License
15
+ along with this program; if not, write to the Free Software
16
+ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
+
18
+ */
19
+
20
+ #include "boost/lambda/lambda.hpp"
21
+
22
+ #include "ardour/route.h"
23
+ #include "ardour/audio_track.h"
24
+ #include "ardour/midi_track.h"
25
+
26
+ #include "osc.h"
27
+ #include "osc_route_observer.h"
28
+
29
+ #include "i18n.h"
30
+
31
+ using namespace std;
32
+ using namespace sigc;
33
+ using namespace PBD;
34
+ using namespace ARDOUR;
35
+ using namespace boost;
36
+
37
+ OSCRouteObserver::OSCRouteObserver (boost::shared_ptr<Route> r, lo_address a)
38
+ : _route (r)
39
+ {
40
+ addr = lo_address_new (lo_address_get_hostname(a) , lo_address_get_port(a));
41
+
42
+ _route->PropertyChanged.connect (name_changed_connection, MISSING_INVALIDATOR, boost::bind (&OSCRouteObserver::name_changed, this, boost::lambda::_1), OSC::instance());
43
+
44
+ if (dynamic_pointer_cast<AudioTrack>(_route) || dynamic_pointer_cast<MidiTrack>(_route)) {
45
+
46
+ boost::shared_ptr<Track> track = dynamic_pointer_cast<Track>(r);
47
+ boost::shared_ptr<Controllable> rec_controllable = dynamic_pointer_cast<Controllable>(track->rec_enable_control());
48
+
49
+ rec_controllable->Changed.connect (rec_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/rec"), track->rec_enable_control()), OSC::instance());
50
+ }
51
+
52
+ boost::shared_ptr<Controllable> mute_controllable = dynamic_pointer_cast<Controllable>(_route->mute_control());
53
+ mute_controllable->Changed.connect (mute_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/mute"), _route->mute_control()), OSC::instance());
54
+
55
+ boost::shared_ptr<Controllable> solo_controllable = dynamic_pointer_cast<Controllable>(_route->solo_control());
56
+ solo_controllable->Changed.connect (solo_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/solo"), _route->solo_control()), OSC::instance());
57
+
58
+ boost::shared_ptr<Controllable> gain_controllable = dynamic_pointer_cast<Controllable>(_route->gain_control());
59
+ gain_controllable->Changed.connect (gain_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/gain"), _route->gain_control()), OSC::instance());
60
+ }
61
+
62
+ OSCRouteObserver::~OSCRouteObserver ()
63
+ {
64
+ name_changed_connection.disconnect();
65
+ rec_changed_connection.disconnect();
66
+ mute_changed_connection.disconnect();
67
+ solo_changed_connection.disconnect();
68
+ gain_changed_connection.disconnect();
69
+
70
+ lo_address_free (addr);
71
+ }
72
+
73
+ void
74
+ OSCRouteObserver::name_changed (const PBD::PropertyChange& what_changed)
75
+ {
76
+ if (!what_changed.contains (ARDOUR::Properties::name)) {
77
+ return;
78
+ }
79
+
80
+ if (!_route) {
81
+ return;
82
+ }
83
+
84
+ lo_message msg = lo_message_new ();
85
+
86
+ lo_message_add_int32 (msg, _route->remote_control_id());
87
+ lo_message_add_string (msg, _route->name().c_str());
88
+
89
+ lo_send_message (addr, "/route/name", msg);
90
+ lo_message_free (msg);
91
+ }
92
+
93
+ void
94
+ OSCRouteObserver::send_change_message (string path, boost::shared_ptr<Controllable> controllable)
95
+ {
96
+ lo_message msg = lo_message_new ();
97
+
98
+ lo_message_add_int32 (msg, _route->remote_control_id());
99
+ lo_message_add_float (msg, (float) controllable->get_value());
100
+
101
+ /* XXX thread issues */
102
+
103
+ //std::cerr << "ORC: send " << path << " = " << controllable->get_value() << std::endl;
104
+
105
+ lo_send_message (addr, path.c_str(), msg);
106
+ lo_message_free (msg);
107
+ }
pool/shard006/C++/0083689_mode_fbwa.cpp ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "mode.h"
2
+ #include "Plane.h"
3
+
4
+ void ModeFBWA::update()
5
+ {
6
+ // set nav_roll and nav_pitch using sticks
7
+ plane.nav_roll_cd = plane.channel_roll->norm_input() * plane.roll_limit_cd;
8
+ plane.update_load_factor();
9
+ float pitch_input = plane.channel_pitch->norm_input();
10
+ if (pitch_input > 0) {
11
+ plane.nav_pitch_cd = pitch_input * plane.aparm.pitch_limit_max_cd;
12
+ } else {
13
+ plane.nav_pitch_cd = -(pitch_input * plane.pitch_limit_min_cd);
14
+ }
15
+ plane.adjust_nav_pitch_throttle();
16
+ plane.nav_pitch_cd = constrain_int32(plane.nav_pitch_cd, plane.pitch_limit_min_cd, plane.aparm.pitch_limit_max_cd.get());
17
+ if (plane.fly_inverted()) {
18
+ plane.nav_pitch_cd = -plane.nav_pitch_cd;
19
+ }
20
+ if (plane.failsafe.rc_failsafe && plane.g.fs_action_short == FS_ACTION_SHORT_FBWA) {
21
+ // FBWA failsafe glide
22
+ plane.nav_roll_cd = 0;
23
+ plane.nav_pitch_cd = 0;
24
+ SRV_Channels::set_output_limit(SRV_Channel::k_throttle, SRV_Channel::Limit::MIN);
25
+ }
26
+ RC_Channel *chan = rc().find_channel_for_option(RC_Channel::AUX_FUNC::FBWA_TAILDRAGGER);
27
+ if (chan != nullptr) {
28
+ // check for the user enabling FBWA taildrag takeoff mode
29
+ bool tdrag_mode = chan->get_aux_switch_pos() == RC_Channel::AuxSwitchPos::HIGH;
30
+ if (tdrag_mode && !plane.auto_state.fbwa_tdrag_takeoff_mode) {
31
+ if (plane.auto_state.highest_airspeed < plane.g.takeoff_tdrag_speed1) {
32
+ plane.auto_state.fbwa_tdrag_takeoff_mode = true;
33
+ plane.gcs().send_text(MAV_SEVERITY_WARNING, "FBWA tdrag mode");
34
+ }
35
+ }
36
+ }
37
+ }
pool/shard006/C++/0083690_DigitalGlitchFilterJNI.cpp ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*----------------------------------------------------------------------------*/
2
+ /* Copyright (c) FIRST 2016. All Rights Reserved. */
3
+ /* Open Source Software - may be modified and shared by FRC teams. The code */
4
+ /* must be accompanied by the FIRST BSD license file in the root directory of */
5
+ /* the project. */
6
+ /*----------------------------------------------------------------------------*/
7
+
8
+ #include <jni.h>
9
+ #include "HAL/HAL.hpp"
10
+ #include "HALUtil.h"
11
+
12
+ #include "edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI.h"
13
+
14
+ /*
15
+ * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
16
+ * Method: setFilterSelect
17
+ */
18
+ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterSelect
19
+ (JNIEnv* env, jclass, jlong port_pointer, jint filter_index)
20
+ {
21
+ int32_t status = 0;
22
+ void* digital_port_pointer = reinterpret_cast<void*>(port_pointer);
23
+
24
+ setFilterSelect(digital_port_pointer, filter_index, &status);
25
+ CheckStatus(env, status);
26
+ }
27
+
28
+ /*
29
+ * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
30
+ * Method: getFilterSelect
31
+ */
32
+ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterSelect
33
+ (JNIEnv *env, jclass, jlong port_pointer)
34
+ {
35
+ int32_t status = 0;
36
+ void* digital_port_pointer = reinterpret_cast<void*>(port_pointer);
37
+
38
+ jint result = getFilterSelect(digital_port_pointer, &status);
39
+ CheckStatus(env, status);
40
+ return result;
41
+ }
42
+
43
+ /*
44
+ * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
45
+ * Method: setFilterPeriod
46
+ */
47
+ JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterPeriod
48
+ (JNIEnv *env, jclass, jint filter_index, jint fpga_cycles)
49
+ {
50
+ int32_t status = 0;
51
+
52
+ setFilterPeriod(filter_index, fpga_cycles, &status);
53
+ CheckStatus(env, status);
54
+ }
55
+
56
+ /*
57
+ * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI
58
+ * Method: getFilterPeriod
59
+ */
60
+ JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterPeriod
61
+ (JNIEnv *env, jclass, jint filter_index)
62
+ {
63
+ int32_t status = 0;
64
+
65
+ jint result = getFilterPeriod(filter_index, &status);
66
+ CheckStatus(env, status);
67
+ return result;
68
+ }
pool/shard006/C++/0083691_uncle.cpp ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @file uncle.cpp
3
+ * @brief Purpose: Contains uncle's methods.
4
+ *
5
+ * MIT License
6
+ * Copyright (c) 2017 MindScape
7
+ *
8
+ * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
9
+ */
10
+
11
+ #include "uncle.hpp"
12
+ #include "platform.hpp"
13
+ #include "little_girl.hpp"
14
+ #include "log.hpp"
15
+ #include <stdlib.h>
16
+
17
+ using namespace mindscape;
18
+
19
+ /**
20
+ * @brief Initializes Uncle enemy.
21
+ *
22
+ * Constructor responsible to initialize Uncle in game.
23
+ *
24
+ * @param name Object's name.
25
+ * @param position X and Y axis positions.
26
+ * @param priority Rendering priority object.
27
+ */
28
+
29
+ Uncle::Uncle(
30
+ std::string name,
31
+ std::pair<int, int> position,
32
+ int priority
33
+ ):Enemy(
34
+ name,
35
+ position,
36
+ priority,
37
+ 100
38
+ ){
39
+ /* Initialize all the characterists of the Uncle's boss. */
40
+ initialize_state_map();
41
+ initialize_hitboxes();
42
+ initialize_animations();
43
+ initialize_audio_effects();
44
+ };
45
+
46
+ /**
47
+ * @brief Creates Uncle's animation.
48
+ *
49
+ * Creates an animation to Uncle enemy.
50
+ *
51
+ * @param path Path to the image which contains the sprite sheet.
52
+ * @param sprite_lines Number of the lines on the sprite sheet.
53
+ * @param sprite_colums Number of colums on the sprite sheet.
54
+ * @param duration Time duration of animation.
55
+ * @param direction Direction of animation.
56
+ * @return This method returns Uncle's animation.
57
+ */
58
+
59
+ engine::Animation* Uncle::create_animation(
60
+ std::string path,
61
+ int sprite_lines,
62
+ int sprite_columns,
63
+ double duration,
64
+ std::string direction) {
65
+ DEBUG("Creating animations.");
66
+
67
+ engine::Game& game = engine::Game::get_instance(); /**< Game.
68
+ Gets an instance of a game just initializated. */
69
+
70
+ engine::Animation* animation = nullptr; /**< Animation.
71
+ Can represents all functions about uncle's animation. */
72
+
73
+ /* Initializes uncle's animation object. */
74
+ animation = new engine::Animation(
75
+ game.get_renderer(),
76
+ path,
77
+ false,
78
+ std::make_pair(0, 0),
79
+ 1,
80
+ sprite_lines,
81
+ sprite_columns,
82
+ duration,
83
+ true,
84
+ direction
85
+ );
86
+
87
+ /* Sets values to init a initial position of animation on the screen.*/
88
+ animation->set_values(
89
+ std::make_pair(320, 320),
90
+ std::make_pair(320, 320),
91
+ std::make_pair(0, 0)
92
+ );
93
+
94
+ DEBUG("Animations created.");
95
+ return animation;
96
+ }
97
+
98
+ /**
99
+ * @brief Initialize Uncle's animations.
100
+ *
101
+ * Define Uncle's movement and attack animation.
102
+ *
103
+ * @return void.
104
+ */
105
+
106
+ void Uncle::initialize_animations() {
107
+ /* Starts debugger to accompany the method's development. */
108
+ DEBUG("Initializing animations.");
109
+
110
+ engine::Animation* idle_animation = nullptr; /**< Animation.
111
+ Animation that represents uncle's in a idle state.s */
112
+
113
+ /* Creates uncle's idle animation. */
114
+ idle_animation = create_animation(
115
+ "../assets/images/sprites/enemies/uncle/uncle_idle.png",
116
+ 1, 4, 3.0, "LEFT"
117
+ );
118
+
119
+ /* Sets uncle's idle animation to define when its stopped. */
120
+ idle_animation->set_values(
121
+ std::make_pair(665, 484),
122
+ std::make_pair(665, 484),
123
+ std::make_pair(0, 0)
124
+ );
125
+
126
+ add_animation("idle_animation",idle_animation);
127
+
128
+ idle_animation->activate();
129
+ set_actual_animation(idle_animation);
130
+
131
+ engine::Animation* attacking_animation = nullptr; /**< Animation.
132
+ Animation that represents uncle's attacking. */
133
+
134
+ /* Creates uncle's attack animation. */
135
+ attacking_animation = create_animation(
136
+ "../assets/images/sprites/enemies/uncle/uncle_attacking.png",
137
+ 1, 1, 3.0, "LEFT"
138
+ );
139
+
140
+ /* Sets uncle's attacking animation to define when its attacking. */
141
+ attacking_animation->set_values(
142
+ std::make_pair(719, 523),
143
+ std::make_pair(719, 523),
144
+ std::make_pair(0, 0)
145
+ );
146
+
147
+ attacking_animation->in_loop = false;
148
+
149
+ add_animation("attacking_animation",attacking_animation);
150
+
151
+ /* Ends debugger that represents the end of the method. */
152
+ DEBUG("Animations initializated.");
153
+ }
154
+
155
+ /**
156
+ * @brief Initialize Uncle's hitboxes.
157
+ *
158
+ * Initializes Uncle instance hitboxes.
159
+ *
160
+ * @return void.
161
+ */
162
+
163
+ void Uncle::initialize_hitboxes() {
164
+ /* Starts debugger to accompany the method's development. */
165
+ DEBUG("Initializing uncle's hitbox.");
166
+
167
+ engine::Game& game = engine::Game::get_instance(); /**< Game.
168
+ Gets an instance of a game just initializated. */
169
+
170
+ engine::Hitbox* head_hitbox = nullptr; /**< Hitbox.
171
+ Initialize uncle's head hitbox. */
172
+
173
+ head_hitbox = new engine::Hitbox(
174
+ "head_hitbox",
175
+ this->get_position(),
176
+ std::make_pair(160, 380),
177
+ std::make_pair(180,20),
178
+ game.get_renderer()
179
+ );
180
+
181
+ /* Add hitbox component into the game object. */
182
+ add_component(head_hitbox);
183
+
184
+ /* Ends debugger that represents the end of the method. */
185
+ DEBUG("Uncle's hitbox initialized");
186
+ }
187
+
188
+ /**
189
+ * @brief Initialize Uncle's state map.
190
+ *
191
+ * Initialize all possibles states for the Uncle.
192
+ *
193
+ * @return void.
194
+ */
195
+
196
+ void Uncle::initialize_state_map() {
197
+ /* Starts debugger to accompany the method's development. */
198
+ DEBUG("Initializing uncle's state.");
199
+ states.set_state("ACTION_STATE","NORMAL");
200
+ /* Ends debugger that represents the end of the method. */
201
+ DEBUG("Uncle's state initialized.");
202
+ }
203
+
204
+ /**
205
+ * @brief Initialize uncle's audio effects.
206
+ *
207
+ * Not implemented.
208
+ *
209
+ * @return void.
210
+ */
211
+
212
+ void Uncle::initialize_audio_effects() {
213
+ }
214
+
215
+ /**
216
+ * @brief Register game events.
217
+ *
218
+ * Register an event to Uncle.
219
+ *
220
+ * @param game_event Triggering in-game events.
221
+ * @return void.
222
+ */
223
+
224
+ void Uncle::on_event(GameEvent game_event) {
225
+ std::string event_name = ""; /**< String.
226
+ Gets an event catched by the Uncle. */
227
+
228
+ /* Gets event related with the Uncle. */
229
+ event_name = game_event.game_event_name;
230
+
231
+ /* Check if the Uncle gets an event to move to the left direction. */
232
+ if (event_name == "MOVE_LEFT"
233
+ && !engine::GameObject::on_limit_of_level) {
234
+
235
+ /* The Uncle increments its actual position. */
236
+ set_position_x(get_position_x() + 10);
237
+ }
238
+ /* Check if the Uncle gets an event to move to the right direction. */
239
+ else if (event_name == "MOVE_RIGHT"
240
+ && !engine::GameObject::on_limit_of_level) {
241
+
242
+ /* The Uncle decrements its actual position. */
243
+ set_position_x(get_position_x() - 10);
244
+ }
245
+ else {
246
+ /* Event name is not found. */
247
+ }
248
+ }
249
+
250
+ /**
251
+ * @brief Notify if the object is in the range.
252
+ *
253
+ * Notify if there is an object in the Uncle's range.
254
+ *
255
+ * @param game_object The game object passed in notification, in this case,
256
+ * the girl.
257
+ * @return void.
258
+ */
259
+
260
+ void Uncle::notify(engine::Observable *game_object) {
261
+ LittleGirl* little_girl = nullptr; /**< LittleGirl.
262
+ Gets as observable that tells when little_girl is next. */
263
+
264
+ little_girl = dynamic_cast<LittleGirl *>(game_object);
265
+
266
+ /* Notify if little_girl exists, moving to her direction. */
267
+ if (little_girl) {
268
+ /* The Uncle moves in direction of the girl. */
269
+ attack(little_girl);
270
+ }
271
+ else {
272
+ /* The Uncle don't attack. */
273
+ }
274
+ }
275
+
276
+ /**
277
+ * @brief Event for the collision.
278
+ *
279
+ * Method called everytime when two game objects collides.
280
+ *
281
+ * @param other Other game object that collides.
282
+ * @param p_my_hitbox Hitbox that receives the collision.
283
+ * @param p_other_hitbox Hitbox that collided.
284
+ * @return void.
285
+ */
286
+
287
+ void Uncle::on_collision(
288
+ engine::GameObject* other,
289
+ engine::Hitbox* p_my_hitbox,
290
+ engine::Hitbox* p_other_hitbox) {
291
+ LittleGirl* little_girl = nullptr; /**< LittleGirl.
292
+ References to LittleGirl object. */
293
+ little_girl = dynamic_cast<LittleGirl *>(other);
294
+
295
+ engine::Hitbox* my_hitbox = nullptr; /**< Hitbox.
296
+ References to Uncle's hitbox. */
297
+ my_hitbox = dynamic_cast<engine::Hitbox *>(p_my_hitbox);
298
+
299
+ engine::Hitbox* other_hitbox = nullptr; /**< Hitbox.
300
+ References to girl's hitbox. */
301
+ other_hitbox = dynamic_cast<engine::Hitbox *>(p_other_hitbox);
302
+
303
+ /* Check if the girl is attacking the Uncle. */
304
+ if (little_girl
305
+ && little_girl->get_state("ACTION_STATE") == "ATTACKING"
306
+ && my_hitbox->get_name() == "head_hitbox"
307
+ && little_girl->get_actual_animation()->actual_column == 2
308
+ && get_state("X_STATE") != little_girl->get_state("X_STATE")) {
309
+
310
+ /* Check if the Uncle is under attack. */
311
+ if(get_state("ACTION_STATE") == "ON_ATTACK") {
312
+ return;
313
+ }
314
+ else {
315
+ on_attack(other);
316
+ }
317
+ }
318
+ else {
319
+ /* The girl is not attacking the Uncle. */
320
+ }
321
+ }
322
+
323
+ /**
324
+ * @brief Define a basic attack.
325
+ *
326
+ * Method not implemented.
327
+ *
328
+ * @return void.
329
+ */
330
+
331
+ void Uncle::basic_attack(){
332
+ }
333
+
334
+ /**
335
+ * @brief Uncle's attack.
336
+ *
337
+ * This method define Uncle's state while is attacking, is on attack or
338
+ * while is dying.
339
+ *
340
+ * @param little_girl Object to be attacked.
341
+ * @return void.
342
+ */
343
+
344
+ void Uncle::attack(engine::GameObject* little_girl) {
345
+ DEBUG("The uncle is attacking.");
346
+
347
+ std::string actual_action_state = ""; /**< String.
348
+ Gets the actual state of the uncle. */
349
+ actual_action_state = get_state("ACTION_STATE");
350
+
351
+ if (actual_action_state == "DYING") {
352
+ INFO("The Uncle is dying.");
353
+ return;
354
+ }
355
+ else {
356
+ /* The Uncle stills alive. */
357
+ }
358
+
359
+ if (actual_action_state == "ON_ATTACK"
360
+ || actual_action_state == "ATTACKING") {
361
+
362
+ if (get_actual_animation()->is_finished) {
363
+ states.set_state("ACTION_STATE","NORMAL");
364
+ set_actual_animation(animations["idle_animation"]);
365
+ }
366
+ else {
367
+ return;
368
+ }
369
+ }
370
+ else {
371
+ /* The Uncle is in a idle state. */
372
+ }
373
+ }
374
+
375
+ /**
376
+ * @brief Define action when is on attack.
377
+ *
378
+ * Event called when Uncle is attacking.
379
+ *
380
+ * @param game_object Object to be attacked.
381
+ * @return void.
382
+ */
383
+
384
+ void Uncle::on_attack(engine::GameObject *game_object) {
385
+ states.set_state("ACTION_STATE","ON_ATTACK");
386
+
387
+ hit(game_object, 1);
388
+ if (is_alive()) {
389
+ set_actual_animation(animations["on_attack_animation"]);
390
+ //play_song("hit_me");
391
+ }
392
+ else {
393
+ /* The Uncle is dead. */
394
+ }
395
+ }
396
+
397
+ /**
398
+ * @brief Death method.
399
+ *
400
+ * This method define an animation when Uncle is dead.
401
+ *
402
+ * @param game_object Uncle.
403
+ * @return void.
404
+ */
405
+
406
+ void Uncle::die(engine::GameObject *game_object) {
407
+ DEBUG("The uncle is dying.");
408
+ std::string actual_x_state = ""; /**< String.
409
+ Gets the actual state of the uncle. */
410
+ actual_x_state = get_state("X_STATE");
411
+ /* Sets a state that represents when uncle is dead. */
412
+ states.set_state("ACTION_STATE", "DYING");
413
+ /* Initiates the animation that show the uncle dying.*/
414
+ set_actual_animation(animations["dying_animation"]);
415
+ //play_song("hit_me");
416
+ DEBUG("The uncle died.");
417
+ }
pool/shard006/C++/0083703_reportescuotas.cpp ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "reportescuotas.h"
2
+ #include "EReporte.h"
3
+ #include "mclientes.h"
4
+
5
+ #include <QDate>
6
+ #include <QMessageBox>
7
+ #include <QInputDialog>
8
+
9
+
10
+ /*!
11
+ * \brief ReportesCuotas::version
12
+ * \return
13
+ */
14
+ double ReportesCuotas::version() const
15
+ { return 0.1; }
16
+
17
+ /*!
18
+ * \brief ReportesCuotas::nombre
19
+ * \return
20
+ */
21
+ QString ReportesCuotas::nombre() const
22
+ { return "ReportesCuotas"; }
23
+
24
+ /*!
25
+ * \brief ReportesCuotas::inicializar
26
+ * \return
27
+ */
28
+ bool ReportesCuotas::inicializar()
29
+ {
30
+ ActResumenCuotasDeudaHistorica = new QAction( this );
31
+ ActResumenCuotasDeudaHistorica->setText( "Deuda historica" );
32
+ ActResumenCuotasDeudaHistorica->setStatusTip( "Muestra un resumen de los estados de todas las cuotas" );
33
+ ActResumenCuotasDeudaHistorica->setIcon( QIcon( ":/imagenes/resumen_cuotas.png" ) );
34
+ connect( ActResumenCuotasDeudaHistorica, SIGNAL( triggered() ), this, SLOT( resumenCuotasDeudaHistorica() ) );
35
+
36
+ ActResumenCuotasMes = new QAction( this );
37
+ ActResumenCuotasMes->setText( "Deuda en mes" );
38
+ ActResumenCuotasMes->setStatusTip( "Muestra el resumen de las cuotas del mes" );
39
+ connect( ActResumenCuotasMes, SIGNAL( triggered() ), this, SLOT( resumenCuotasMes() ) );
40
+
41
+ ActResumenCuotasCliente = new QAction( this );
42
+ ActResumenCuotasCliente->setText( "Deuda por cliente" );
43
+ ActResumenCuotasCliente->setStatusTip( "Muestra las deudas de un cliente especifico" );
44
+ connect( ActResumenCuotasCliente, SIGNAL( triggered() ), this, SLOT( resumenCuotasCliente() ) );
45
+
46
+ return true;
47
+ }
48
+
49
+ /*!
50
+ * \brief ReportesCuotas::hacerMenu
51
+ * \param m
52
+ */
53
+ void ReportesCuotas::hacerMenu( QMenu *m )
54
+ {
55
+ QMenu *menu = m->addMenu( "Cuotas" );
56
+ menu->addAction( ActResumenCuotasDeudaHistorica );
57
+ menu->addAction( ActResumenCuotasMes );
58
+ menu->addAction( ActResumenCuotasCliente );
59
+ }
60
+
61
+ /*!
62
+ * \brief ReportesCuotas::resumenCuotasDeudaHistorica
63
+ */
64
+ void ReportesCuotas::resumenCuotasDeudaHistorica()
65
+ {
66
+ EReporte *rep = new EReporte( 0 );
67
+ rep->especial( "CuotasHistoricas", ParameterList() );
68
+ rep->hacerPDF( ParameterList(), QString( "Deudas Cuotas al %1" ).arg( QDate::currentDate().toString( "dd-MM-yyyy" ) ) );
69
+ delete rep;
70
+ }
71
+
72
+ /*!
73
+ * \brief ReportesCuotas::resumenCuotasMes
74
+ */
75
+ void ReportesCuotas::resumenCuotasMes()
76
+ {
77
+ QMessageBox::information( 0, "Error", "No implementado" );
78
+ return;
79
+ bool ok = false;
80
+ QStringList meses;
81
+ meses << "Enero" << "Febrero" << "Marzo" << "Abril" << "Mayo" << "Junio" << "Julio" << "Agosto" << "Septiembre" << "Octubre" << "Noviembre" << "Diciembre";
82
+ QString mes = QInputDialog::getItem( 0, "Elija el mes", "Elija el mes:", meses, QDate::currentDate().month(), false, &ok );
83
+ if( ok ) {
84
+ EReporte *rep = new EReporte( 0 );
85
+ ParameterList lista;
86
+ lista.append( Parameter( "mes", meses.indexOf( mes ) ) );
87
+ rep->especial( "DeudaCuotasMes", lista );
88
+ rep->hacerPDF( ParameterList(), QString( "Deudas Cuotas del mes %1-%2" ).arg( mes ).arg( QDate::currentDate().toString( "yyyy" ) ) );
89
+ delete rep;
90
+ }
91
+ }
92
+
93
+ /*!
94
+ * \brief ReportesCuotas::resumenCuotasCliente
95
+ * Muestra el resumen de cuotas de un cliente específico
96
+ */
97
+ void ReportesCuotas::resumenCuotasCliente()
98
+ {
99
+ QMessageBox::information( 0, "Error", "No implementado" );
100
+ return;
101
+ /// @TODO: Implementar reporte de deuda segun cliente
102
+ EReporte *rep = new EReporte( 0 );
103
+ int id_cliente = 1;
104
+ ParameterList lista;
105
+ lista.append( "id_cliente", id_cliente );
106
+ rep->especial( "deudascuotascliente", lista );
107
+ rep->hacerPDF( ParameterList(),
108
+ QString( "Deudas de Cuotas de %2 Al %1" )
109
+ .arg( QDate::currentDate().toString( Qt::LocaleDate ) )
110
+ .arg( MClientes::getRazonSocial( id_cliente ) ) );
111
+ delete rep;
112
+ }
113
+
114
+ Q_EXPORT_PLUGIN2( reportescuotas, ReportesCuotas )
pool/shard006/C++/0083704_Resource.cpp ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // Copyright (c) 2008-2016 the Urho3D project.
3
+ //
4
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ // of this software and associated documentation files (the "Software"), to deal
6
+ // in the Software without restriction, including without limitation the rights
7
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ // copies of the Software, and to permit persons to whom the Software is
9
+ // furnished to do so, subject to the following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included in
12
+ // all copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+ // THE SOFTWARE.
21
+ //
22
+
23
+ #include "../Precompiled.h"
24
+
25
+ #include "../Core/Profiler.h"
26
+ #include "../IO/File.h"
27
+ #include "../IO/Log.h"
28
+ #include "../Resource/Resource.h"
29
+
30
+ namespace Urho3D
31
+ {
32
+
33
+ Resource::Resource(Context* context) :
34
+ Object(context),
35
+ memoryUse_(0),
36
+ asyncLoadState_(ASYNC_DONE)
37
+ {
38
+ }
39
+
40
+ bool Resource::Load(Deserializer& source)
41
+ {
42
+ // Because BeginLoad() / EndLoad() can be called from worker threads, where profiling would be a no-op,
43
+ // create a type name -based profile block here
44
+ #ifdef URHO3D_PROFILING
45
+ String profileBlockName("Load" + GetTypeName());
46
+
47
+ Profiler* profiler = GetSubsystem<Profiler>();
48
+ if (profiler)
49
+ profiler->BeginBlock(profileBlockName.CString());
50
+ #endif
51
+
52
+ // If we are loading synchronously in a non-main thread, behave as if async loading (for example use
53
+ // GetTempResource() instead of GetResource() to load resource dependencies)
54
+ SetAsyncLoadState(Thread::IsMainThread() ? ASYNC_DONE : ASYNC_LOADING);
55
+ bool success = BeginLoad(source);
56
+ if (success)
57
+ success &= EndLoad();
58
+ SetAsyncLoadState(ASYNC_DONE);
59
+
60
+ #ifdef URHO3D_PROFILING
61
+ if (profiler)
62
+ profiler->EndBlock();
63
+ #endif
64
+
65
+ return success;
66
+ }
67
+
68
+ bool Resource::BeginLoad(Deserializer& source)
69
+ {
70
+ // This always needs to be overridden by subclasses
71
+ return false;
72
+ }
73
+
74
+ bool Resource::EndLoad()
75
+ {
76
+ // If no GPU upload step is necessary, no override is necessary
77
+ return true;
78
+ }
79
+
80
+ bool Resource::Save(Serializer& dest) const
81
+ {
82
+ URHO3D_LOGERROR("Save not supported for " + GetTypeName());
83
+ return false;
84
+ }
85
+
86
+ bool Resource::Load(const String& fileName)
87
+ {
88
+ File file(context_);
89
+ return file.Open(fileName, FILE_READ) && Load(file);
90
+ }
91
+
92
+ bool Resource::Save(const String& fileName) const
93
+ {
94
+ File file(context_);
95
+ return file.Open(fileName, FILE_WRITE) && Save(file);
96
+ }
97
+
98
+ void Resource::SetName(const String& name)
99
+ {
100
+ name_ = name;
101
+ nameHash_ = name;
102
+ }
103
+
104
+ void Resource::SetMemoryUse(unsigned size)
105
+ {
106
+ memoryUse_ = size;
107
+ }
108
+
109
+ void Resource::ResetUseTimer()
110
+ {
111
+ useTimer_.Reset();
112
+ }
113
+
114
+ void Resource::SetAsyncLoadState(AsyncLoadState newState)
115
+ {
116
+ asyncLoadState_ = newState;
117
+ }
118
+
119
+ unsigned Resource::GetUseTimer()
120
+ {
121
+ // If more references than the resource cache, return always 0 & reset the timer
122
+ if (Refs() > 1)
123
+ {
124
+ useTimer_.Reset();
125
+ return 0;
126
+ }
127
+ else
128
+ return useTimer_.GetMSec(false);
129
+ }
130
+
131
+ }
pool/shard006/C++/0083713_CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* TEMPLATE GENERATED TESTCASE FILE
2
+ Filename: CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp
3
+ Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
4
+ Template File: sources-sink-62a.tmpl.cpp
5
+ */
6
+ /*
7
+ * @description
8
+ * CWE: 78 OS Command Injection
9
+ * BadSource: console Read input from the console
10
+ * GoodSource: Fixed string
11
+ * Sinks: w32_spawnvp
12
+ * BadSink : execute command with spawnvp
13
+ * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
14
+ *
15
+ * */
16
+
17
+ #include "std_testcase.h"
18
+
19
+ #include <wchar.h>
20
+
21
+ #ifdef _WIN32
22
+ #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
23
+ #define COMMAND_INT "cmd.exe"
24
+ #define COMMAND_ARG1 "/c"
25
+ #define COMMAND_ARG2 "dir"
26
+ #define COMMAND_ARG3 data
27
+ #else /* NOT _WIN32 */
28
+ #include <unistd.h>
29
+ #define COMMAND_INT_PATH "/bin/sh"
30
+ #define COMMAND_INT "sh"
31
+ #define COMMAND_ARG1 "ls"
32
+ #define COMMAND_ARG2 "-la"
33
+ #define COMMAND_ARG3 data
34
+ #endif
35
+
36
+ #include <process.h>
37
+
38
+ namespace CWE78_OS_Command_Injection__char_console_w32_spawnvp_62
39
+ {
40
+
41
+ #ifndef OMITBAD
42
+
43
+ /* bad function declaration */
44
+ void badSource(char * &data);
45
+
46
+ void bad()
47
+ {
48
+ char * data;
49
+ char dataBuffer[100] = "";
50
+ data = dataBuffer;
51
+ badSource(data);
52
+ {
53
+ char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
54
+ /* spawnvp - searches for the location of the command among
55
+ * the directories specified by the PATH environment variable */
56
+ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
57
+ _spawnvp(_P_WAIT, COMMAND_INT, args);
58
+ }
59
+ }
60
+
61
+ #endif /* OMITBAD */
62
+
63
+ #ifndef OMITGOOD
64
+
65
+ /* goodG2B uses the GoodSource with the BadSink */
66
+ void goodG2BSource(char * &data);
67
+
68
+ static void goodG2B()
69
+ {
70
+ char * data;
71
+ char dataBuffer[100] = "";
72
+ data = dataBuffer;
73
+ goodG2BSource(data);
74
+ {
75
+ char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
76
+ /* spawnvp - searches for the location of the command among
77
+ * the directories specified by the PATH environment variable */
78
+ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
79
+ _spawnvp(_P_WAIT, COMMAND_INT, args);
80
+ }
81
+ }
82
+
83
+ void good()
84
+ {
85
+ goodG2B();
86
+ }
87
+
88
+ #endif /* OMITGOOD */
89
+
90
+ } /* close namespace */
91
+
92
+ /* Below is the main(). It is only used when building this testcase on
93
+ * its own for testing or for building a binary to use in testing binary
94
+ * analysis tools. It is not used when compiling all the testcases as one
95
+ * application, which is how source code analysis tools are tested.
96
+ */
97
+
98
+ #ifdef INCLUDEMAIN
99
+
100
+ using namespace CWE78_OS_Command_Injection__char_console_w32_spawnvp_62; /* so that we can use good and bad easily */
101
+
102
+ int main(int argc, char * argv[])
103
+ {
104
+ /* seed randomness */
105
+ srand( (unsigned)time(NULL) );
106
+ #ifndef OMITGOOD
107
+ printLine("Calling good()...");
108
+ good();
109
+ printLine("Finished good()");
110
+ #endif /* OMITGOOD */
111
+ #ifndef OMITBAD
112
+ printLine("Calling bad()...");
113
+ bad();
114
+ printLine("Finished bad()");
115
+ #endif /* OMITBAD */
116
+ return 0;
117
+ }
118
+
119
+ #endif
pool/shard006/C++/0083722_InstanceFleetTimeline.cpp ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License").
5
+ * You may not use this file except in compliance with the License.
6
+ * A copy of the License is located at
7
+ *
8
+ * http://aws.amazon.com/apache2.0
9
+ *
10
+ * or in the "license" file accompanying this file. This file is distributed
11
+ * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12
+ * express or implied. See the License for the specific language governing
13
+ * permissions and limitations under the License.
14
+ */
15
+
16
+ #include <aws/elasticmapreduce/model/InstanceFleetTimeline.h>
17
+ #include <aws/core/utils/json/JsonSerializer.h>
18
+
19
+ #include <utility>
20
+
21
+ using namespace Aws::Utils::Json;
22
+ using namespace Aws::Utils;
23
+
24
+ namespace Aws
25
+ {
26
+ namespace EMR
27
+ {
28
+ namespace Model
29
+ {
30
+
31
+ InstanceFleetTimeline::InstanceFleetTimeline() :
32
+ m_creationDateTimeHasBeenSet(false),
33
+ m_readyDateTimeHasBeenSet(false),
34
+ m_endDateTimeHasBeenSet(false)
35
+ {
36
+ }
37
+
38
+ InstanceFleetTimeline::InstanceFleetTimeline(JsonView jsonValue) :
39
+ m_creationDateTimeHasBeenSet(false),
40
+ m_readyDateTimeHasBeenSet(false),
41
+ m_endDateTimeHasBeenSet(false)
42
+ {
43
+ *this = jsonValue;
44
+ }
45
+
46
+ InstanceFleetTimeline& InstanceFleetTimeline::operator =(JsonView jsonValue)
47
+ {
48
+ if(jsonValue.ValueExists("CreationDateTime"))
49
+ {
50
+ m_creationDateTime = jsonValue.GetDouble("CreationDateTime");
51
+
52
+ m_creationDateTimeHasBeenSet = true;
53
+ }
54
+
55
+ if(jsonValue.ValueExists("ReadyDateTime"))
56
+ {
57
+ m_readyDateTime = jsonValue.GetDouble("ReadyDateTime");
58
+
59
+ m_readyDateTimeHasBeenSet = true;
60
+ }
61
+
62
+ if(jsonValue.ValueExists("EndDateTime"))
63
+ {
64
+ m_endDateTime = jsonValue.GetDouble("EndDateTime");
65
+
66
+ m_endDateTimeHasBeenSet = true;
67
+ }
68
+
69
+ return *this;
70
+ }
71
+
72
+ JsonValue InstanceFleetTimeline::Jsonize() const
73
+ {
74
+ JsonValue payload;
75
+
76
+ if(m_creationDateTimeHasBeenSet)
77
+ {
78
+ payload.WithDouble("CreationDateTime", m_creationDateTime.SecondsWithMSPrecision());
79
+ }
80
+
81
+ if(m_readyDateTimeHasBeenSet)
82
+ {
83
+ payload.WithDouble("ReadyDateTime", m_readyDateTime.SecondsWithMSPrecision());
84
+ }
85
+
86
+ if(m_endDateTimeHasBeenSet)
87
+ {
88
+ payload.WithDouble("EndDateTime", m_endDateTime.SecondsWithMSPrecision());
89
+ }
90
+
91
+ return payload;
92
+ }
93
+
94
+ } // namespace Model
95
+ } // namespace EMR
96
+ } // namespace Aws
pool/shard006/C++/0083726_centered_continued_fraction.cpp ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // (C) Copyright Nick Thompson 2020.
2
+ // Use, modification and distribution are subject to the
3
+ // Boost Software License, Version 1.0. (See accompanying file
4
+ // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5
+ //
6
+ // Deliberately contains some unicode characters:
7
+ //
8
+ // boost-no-inspect
9
+ //
10
+ #include <iostream>
11
+ #include <boost/math/constants/constants.hpp>
12
+ #include <boost/math/tools/centered_continued_fraction.hpp>
13
+ #include <boost/multiprecision/mpfr.hpp>
14
+
15
+ using boost::math::constants::root_two;
16
+ using boost::math::constants::phi;
17
+ using boost::math::constants::pi;
18
+ using boost::math::constants::e;
19
+ using boost::math::constants::zeta_three;
20
+ using boost::math::tools::centered_continued_fraction;
21
+ using boost::multiprecision::mpfr_float;
22
+
23
+ int main()
24
+ {
25
+ using Real = mpfr_float;
26
+ int p = 10000;
27
+ mpfr_float::default_precision(p);
28
+ auto phi_cfrac = centered_continued_fraction(phi<Real>());
29
+ std::cout << "φ ≈ " << phi_cfrac << "\n";
30
+ std::cout << "Khinchin mean: " << std::setprecision(10) << phi_cfrac.khinchin_geometric_mean() << "\n\n\n";
31
+
32
+ auto pi_cfrac = centered_continued_fraction(pi<Real>());
33
+ std::cout << "π ≈ " << pi_cfrac << "\n";
34
+ std::cout << "Khinchin mean: " << std::setprecision(10) << pi_cfrac.khinchin_geometric_mean() << "\n\n\n";
35
+
36
+ auto rt_cfrac = centered_continued_fraction(root_two<Real>());
37
+ std::cout << "√2 ≈ " << rt_cfrac << "\n";
38
+ std::cout << "Khinchin mean: " << std::setprecision(10) << rt_cfrac.khinchin_geometric_mean() << "\n\n\n";
39
+
40
+ auto e_cfrac = centered_continued_fraction(e<Real>());
41
+ std::cout << "e ≈ " << e_cfrac << "\n";
42
+ std::cout << "Khinchin mean: " << std::setprecision(10) << e_cfrac.khinchin_geometric_mean() << "\n\n\n";
43
+
44
+ auto z_cfrac = centered_continued_fraction(zeta_three<Real>());
45
+ std::cout << "ζ(3) ≈ " << z_cfrac << "\n";
46
+ std::cout << "Khinchin mean: " << std::setprecision(10) << z_cfrac.khinchin_geometric_mean() << "\n\n\n";
47
+
48
+
49
+ // http://jeremiebourdon.free.fr/data/Khintchine.pdf
50
+ std::cout << "The expected Khinchin mean for a random centered continued fraction is 5.45451724454\n";
51
+ }
pool/shard006/C++/0083728_main.cpp ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @file main.cpp
3
+ * @brief Main file.
4
+ * @author Michal Policht
5
+ */
6
+
7
+ #include <QCoreApplication>
8
+ #include <QString>
9
+ #include <QTextStream>
10
+ #include <QThread>
11
+ #include <qextserialport.h>
12
+ #include "PortListener.h"
13
+
14
+ class SerialThread: public QThread
15
+ {
16
+ QextSerialPort * port;
17
+
18
+ protected:
19
+ virtual void run()
20
+ {
21
+ QString inStr;
22
+ QTextStream in(stdin);
23
+ QTextStream out(stdout);
24
+
25
+ out << "Special commands: open close bye" << endl << endl;
26
+ while(inStr.compare("bye") != 0) {
27
+ in >> inStr;
28
+ if (inStr.compare("close") == 0) {
29
+ out << "requesting close... " << endl;
30
+ port->close();
31
+ }
32
+ else if (inStr.compare("open") == 0) {
33
+ out << "opening port... ";
34
+ out << port->open(QIODevice::ReadWrite);
35
+ out << endl;
36
+ } else if (inStr.compare("bye") != 0)
37
+ port->write(inStr.toAscii().constData(), inStr.length());
38
+ }
39
+ port->close();
40
+ }
41
+
42
+ public:
43
+ SerialThread(QextSerialPort * port, QObject * parent = 0):
44
+ QThread(parent)
45
+ {
46
+ this->port = port;
47
+ }
48
+ };
49
+
50
+ int main(int argc, char *argv[])
51
+ {
52
+ QTextStream out(stdout);
53
+ QCoreApplication app(argc, argv);
54
+
55
+ QextSerialPort * port = new QextSerialPort("COM1", QextSerialPort::EventDriven);
56
+ port->setBaudRate(BAUD56000);
57
+ port->setFlowControl(FLOW_OFF);
58
+ port->setParity(PAR_NONE);
59
+ port->setDataBits(DATA_8);
60
+ port->setStopBits(STOP_2);
61
+ port->open(QIODevice::ReadWrite);
62
+ if (!(port->lineStatus() & LS_DSR)) {
63
+ out << "warning: device is not turned on" << endl;
64
+ }
65
+
66
+ PortListener * listener = new PortListener(port);
67
+ //Because port and listener are working in different threads
68
+ //Qt will choose queued connection. This may produce clusters of
69
+ //signals waiting in the queue.
70
+ listener->connect(port, SIGNAL(readyRead()), listener, SLOT(receive()));
71
+ listener->connect(port, SIGNAL(bytesWritten(qint64)), listener, SLOT(reportWritten(qint64)));
72
+ listener->connect(port, SIGNAL(aboutToClose()), listener, SLOT(reportClose()));
73
+ listener->connect(port, SIGNAL(dsrChanged(bool)), listener, SLOT(reportDsr(bool)));
74
+
75
+ SerialThread * thread = new SerialThread(port);
76
+ app.connect(thread, SIGNAL(finished()), & app, SLOT(quit()));
77
+ thread->start();
78
+
79
+ //event loop is required to utilize signals and slots mechanism
80
+ return app.exec();
81
+ }
pool/shard006/C++/0083732_bonus.cpp ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bonus.h"
2
+
3
+ /*!
4
+ * Instanciates a bonus depending its type
5
+ * @param type Type of bonus
6
+ */
7
+ Bonus::Bonus(int type)
8
+ {
9
+ setRect(10, 10, 5, 5);
10
+ m_type = type;
11
+ for (int i = 0; i < 4; i++) {
12
+ m_attributes.append(0);
13
+ }
14
+
15
+ switch(m_type) {
16
+ case BOMB_RANGE_UP:
17
+ if (qrand() % 2 == 1) {
18
+ setBrush(QColor::fromRgb (255, 150, 0));
19
+ m_attributes.insert(BOMB_RANGE_UP, -1);
20
+ } else {
21
+ setBrush(Qt::red);
22
+ m_attributes.insert(BOMB_RANGE_UP, 1);
23
+ }
24
+ break;
25
+ case BOMB_CAPACITY_UP:
26
+ if (qrand() % 2 == 1) {
27
+ setBrush(Qt::cyan);
28
+ m_attributes.insert(BOMB_CAPACITY_UP, -1);
29
+ } else {
30
+ setBrush(Qt::blue);
31
+ m_attributes.insert(BOMB_CAPACITY_UP, 1);
32
+ }
33
+ break;
34
+
35
+ case KICK_ACTIVATOR:
36
+ setBrush(Qt::darkMagenta);
37
+ m_attributes.insert(KICK_ACTIVATOR, 1);
38
+ break;
39
+ case LIFE_UP:
40
+ setBrush(Qt::green);
41
+ m_attributes.insert(LIFE_UP, 1);
42
+ break;
43
+ }
44
+ }
45
+
46
+ Bonus::~Bonus() {
47
+ }
48
+
49
+ int Bonus::type() {
50
+ return m_type;
51
+ }
52
+
53
+ QList<int> Bonus::attributes() {
54
+ return m_attributes;
55
+ }
56
+
pool/shard006/C++/0083736_CEGUIOgreResourceProvider.cpp ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /************************************************************************
2
+ filename: CEGUIOgreResourceProvider.cpp
3
+ created: 8/7/2004
4
+ author: James '_mental_' O'Sullivan
5
+
6
+ purpose: Implements Ogre specific ResourceProvider
7
+ *************************************************************************/
8
+ /***************************************************************************
9
+ * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
10
+ *
11
+ * Permission is hereby granted, free of charge, to any person obtaining
12
+ * a copy of this software and associated documentation files (the
13
+ * "Software"), to deal in the Software without restriction, including
14
+ * without limitation the rights to use, copy, modify, merge, publish,
15
+ * distribute, sublicense, and/or sell copies of the Software, and to
16
+ * permit persons to whom the Software is furnished to do so, subject to
17
+ * the following conditions:
18
+ *
19
+ * The above copyright notice and this permission notice shall be
20
+ * included in all copies or substantial portions of the Software.
21
+ *
22
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
25
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
26
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
27
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
28
+ * OTHER DEALINGS IN THE SOFTWARE.
29
+ ***************************************************************************/
30
+ #include "CEGUIOgreResourceProvider.h"
31
+ #include "CEGUIExceptions.h"
32
+
33
+ #include <OgreArchiveManager.h>
34
+
35
+ // Start of CEGUI namespace section
36
+ namespace CEGUI
37
+ {
38
+ //----------------------------------------------------------------------------//
39
+ OgreResourceProvider::OgreResourceProvider()
40
+ {
41
+ // set deafult resource group for Ogre
42
+ d_defaultResourceGroup =
43
+ Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str();
44
+ }
45
+
46
+ //----------------------------------------------------------------------------//
47
+ void OgreResourceProvider::loadRawDataContainer(const String& filename,
48
+ RawDataContainer& output,
49
+ const String& resourceGroup)
50
+ {
51
+ String orpGroup;
52
+ if (resourceGroup.empty())
53
+ orpGroup = d_defaultResourceGroup.empty() ?
54
+ Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str() :
55
+ d_defaultResourceGroup;
56
+ else
57
+ orpGroup = resourceGroup;
58
+
59
+ Ogre::DataStreamPtr input = Ogre::ResourceGroupManager::getSingleton().
60
+ openResource(filename.c_str(), orpGroup.c_str());
61
+
62
+ if (input.isNull())
63
+ CEGUI_THROW(InvalidRequestException(
64
+ "OgreCEGUIResourceProvider::loadRawDataContainer: Unable to open "
65
+ "resource file '" + filename + "' in resource group '" + orpGroup +
66
+ "'."));
67
+
68
+ Ogre::String buf = input->getAsString();
69
+ const size_t memBuffSize = buf.length();
70
+
71
+ unsigned char* mem = new unsigned char[memBuffSize];
72
+ memcpy(mem, buf.c_str(), memBuffSize);
73
+
74
+ output.setData(mem);
75
+ output.setSize(memBuffSize);
76
+ }
77
+
78
+ //----------------------------------------------------------------------------//
79
+ void OgreResourceProvider::unloadRawDataContainer(RawDataContainer& data)
80
+ {
81
+ if (data.getDataPtr())
82
+ {
83
+ delete[] data.getDataPtr();
84
+ data.setData(0);
85
+ data.setSize(0);
86
+ }
87
+ }
88
+
89
+ //----------------------------------------------------------------------------//
90
+ size_t OgreResourceProvider::getResourceGroupFileNames(
91
+ std::vector<String>& out_vec, const String& file_pattern,
92
+ const String& resource_group)
93
+ {
94
+ // get list of files in the group that match the pattern.
95
+ Ogre::StringVectorPtr vp =
96
+ Ogre::ResourceGroupManager::getSingleton().findResourceNames(
97
+ (resource_group.empty() ?
98
+ d_defaultResourceGroup.c_str() :
99
+ resource_group.c_str()),
100
+ file_pattern.c_str());
101
+
102
+ size_t entries = 0;
103
+ Ogre::StringVector::iterator i = vp->begin();
104
+ for (; i != vp->end(); ++i)
105
+ {
106
+ out_vec.push_back(*i);
107
+ ++entries;
108
+ }
109
+
110
+ return entries;
111
+ }
112
+
113
+ //----------------------------------------------------------------------------//
114
+
115
+ } // End of CEGUI namespace section
pool/shard006/C++/0083740_AssemblyContext.cpp ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2015-2016 The Khronos Group Inc.
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a
4
+ // copy of this software and/or associated documentation files (the
5
+ // "Materials"), to deal in the Materials without restriction, including
6
+ // without limitation the rights to use, copy, modify, merge, publish,
7
+ // distribute, sublicense, and/or sell copies of the Materials, and to
8
+ // permit persons to whom the Materials are furnished to do so, subject to
9
+ // the following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included
12
+ // in all copies or substantial portions of the Materials.
13
+ //
14
+ // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
15
+ // KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
16
+ // SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
17
+ // https://www.khronos.org/registry/
18
+ //
19
+ // THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
+ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22
+ // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23
+ // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24
+ // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25
+ // MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
26
+
27
+ #include "UnitSPIRV.h"
28
+
29
+ #include <vector>
30
+ #include <gmock/gmock.h>
31
+
32
+ #include "source/instruction.h"
33
+
34
+ using libspirv::AssemblyContext;
35
+ using spvtest::AutoText;
36
+ using spvtest::Concatenate;
37
+ using ::testing::Eq;
38
+
39
+ namespace {
40
+
41
+ struct EncodeStringCase {
42
+ std::string str;
43
+ std::vector<uint32_t> initial_contents;
44
+ };
45
+
46
+ using EncodeStringTest = ::testing::TestWithParam<EncodeStringCase>;
47
+
48
+ TEST_P(EncodeStringTest, Sample) {
49
+ AssemblyContext context(AutoText(""), nullptr);
50
+ spv_instruction_t inst;
51
+ inst.words = GetParam().initial_contents;
52
+ ASSERT_EQ(SPV_SUCCESS,
53
+ context.binaryEncodeString(GetParam().str.c_str(), &inst));
54
+ // We already trust MakeVector
55
+ EXPECT_THAT(inst.words,
56
+ Eq(Concatenate({GetParam().initial_contents,
57
+ spvtest::MakeVector(GetParam().str)})));
58
+ }
59
+
60
+ // clang-format off
61
+ INSTANTIATE_TEST_CASE_P(
62
+ BinaryEncodeString, EncodeStringTest,
63
+ ::testing::ValuesIn(std::vector<EncodeStringCase>{
64
+ // Use cases that exercise at least one to two words,
65
+ // and both empty and non-empty initial contents.
66
+ {"", {}},
67
+ {"", {1,2,3}},
68
+ {"a", {}},
69
+ {"a", {4}},
70
+ {"ab", {4}},
71
+ {"abc", {}},
72
+ {"abc", {18}},
73
+ {"abcd", {}},
74
+ {"abcd", {22}},
75
+ {"abcde", {4}},
76
+ {"abcdef", {}},
77
+ {"abcdef", {99,42}},
78
+ {"abcdefg", {}},
79
+ {"abcdefg", {101}},
80
+ {"abcdefgh", {}},
81
+ {"abcdefgh", {102, 103, 104}},
82
+ // A very long string, encoded after an initial word.
83
+ // SPIR-V limits strings to 65535 characters.
84
+ {std::string(65535, 'a'), {1}},
85
+ }),);
86
+ // clang-format on
87
+
88
+ } // anonymous namespace
pool/shard006/C++/0083742_action_handler.cc ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 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 <string>
6
+ #include <utility>
7
+
8
+ #include "base/bind.h"
9
+ #include "base/callback.h"
10
+ #include "base/command_line.h"
11
+ #include "base/files/file_path.h"
12
+ #include "base/files/file_util.h"
13
+ #include "base/logging.h"
14
+ #include "base/memory/ref_counted.h"
15
+ #include "base/process/launch.h"
16
+ #include "base/process/process.h"
17
+ #include "base/task/post_task.h"
18
+ #include "base/task/thread_pool.h"
19
+ #include "base/threading/sequenced_task_runner_handle.h"
20
+ #include "base/time/time.h"
21
+ #include "chrome/updater/action_handler.h"
22
+ #include "components/update_client/update_client.h"
23
+
24
+ namespace updater {
25
+
26
+ class ActionHandler : public update_client::ActionHandler {
27
+ public:
28
+ ActionHandler() = default;
29
+
30
+ private:
31
+ using Result =
32
+ std::tuple<bool /*succeeded*/, int /*error_code*/, int /*extra_code*/>;
33
+ ~ActionHandler() override = default;
34
+
35
+ // Overrides for update_client::ActionHandler.
36
+ void Handle(const base::FilePath& action,
37
+ const std::string& session_id,
38
+ Callback callback) override;
39
+
40
+ // For Windows, the action is a path to an EXE file.
41
+ static Result RunCommand(const base::FilePath& exe_path);
42
+
43
+ ActionHandler(const ActionHandler&) = delete;
44
+ ActionHandler& operator=(const ActionHandler&) = delete;
45
+ };
46
+
47
+ void ActionHandler::Handle(const base::FilePath& action,
48
+ const std::string&,
49
+ Callback callback) {
50
+ DCHECK(!action.empty());
51
+ base::ThreadPool::PostTaskAndReplyWithResult(
52
+ FROM_HERE,
53
+ {base::MayBlock(), base::WithBaseSyncPrimitives(),
54
+ base::TaskPriority::BEST_EFFORT,
55
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
56
+ base::BindOnce(&ActionHandler::RunCommand, action),
57
+ base::BindOnce(
58
+ [](Callback callback, const Result& result) {
59
+ auto [succeeded, error_code, extra_code] = result;
60
+ base::SequencedTaskRunnerHandle::Get()->PostTask(
61
+ FROM_HERE, base::BindOnce(std::move(callback), succeeded,
62
+ error_code, extra_code));
63
+ },
64
+ std::move(callback)));
65
+ }
66
+
67
+ ActionHandler::Result ActionHandler::RunCommand(
68
+ const base::FilePath& exe_path) {
69
+ base::CommandLine command_line(exe_path);
70
+ VLOG(1) << "run command: " << command_line.GetCommandLineString();
71
+ base::LaunchOptions options;
72
+ options.start_hidden = true;
73
+ base::Process process = base::LaunchProcess(command_line, options);
74
+ int exit_code = 0;
75
+ const base::TimeDelta kMaxWaitTime = base::Seconds(600);
76
+ const bool succeeded =
77
+ process.WaitForExitWithTimeout(kMaxWaitTime, &exit_code);
78
+ return Result{succeeded, exit_code, 0};
79
+ }
80
+
81
+ scoped_refptr<update_client::ActionHandler> MakeActionHandler() {
82
+ return base::MakeRefCounted<ActionHandler>();
83
+ }
84
+
85
+ } // namespace updater
pool/shard006/C++/0083750_KernelRidgeRegression.cpp ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @file
3
+ * @copyright This code is licensed under the 3-clause BSD license.\n
4
+ * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
5
+ * See LICENSE.txt for details.
6
+ */
7
+
8
+ #include "KernelRidgeRegression.h"
9
+
10
+ namespace Scine {
11
+ namespace Utils {
12
+ namespace MachineLearning {
13
+
14
+ void KernelRidgeRegression::trainModel(const Eigen::MatrixXd& featureValues, const Eigen::MatrixXd& targetValues) {
15
+ if (targetValues.rows() != featureValues.rows())
16
+ throw std::runtime_error("The number of data points do not match between the feature and target matrices.");
17
+
18
+ // Transpose the feature and target matrices since they are column-major.
19
+ targetValues_ = targetValues.transpose();
20
+ featureValues_ = featureValues.transpose();
21
+ numDataPoints_ = static_cast<int>(targetValues_.cols());
22
+
23
+ // Construct the kernel matrix
24
+ Eigen::MatrixXd kernelMatrix(numDataPoints_, numDataPoints_);
25
+ #pragma omp parallel for schedule(dynamic)
26
+ for (int i = 0; i < numDataPoints_; ++i) {
27
+ for (int j = i; j < numDataPoints_; ++j) {
28
+ double value = kernel_(featureValues_.col(i), featureValues_.col(j), hyperparameters_);
29
+ kernelMatrix(i, j) = value;
30
+ }
31
+ }
32
+
33
+ kernelMatrix = kernelMatrix.selfadjointView<Eigen::Upper>();
34
+
35
+ // Inversion of the regularized kernel matrix
36
+ Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(kernelMatrix.rows(), kernelMatrix.cols());
37
+ Eigen::MatrixXd regularizedKernelMatrix = kernelMatrix + regularizationFactor_ * identity;
38
+ invertedRegularizedKernelMatrix_ = regularizedKernelMatrix.inverse();
39
+ }
40
+
41
+ Eigen::VectorXd KernelRidgeRegression::predict(const Eigen::VectorXd& data) const {
42
+ if (invertedRegularizedKernelMatrix_.size() == 0)
43
+ throw std::runtime_error("The model has not been trained yet!");
44
+
45
+ // Calculate kernel vector
46
+ Eigen::VectorXd kernelVector(numDataPoints_);
47
+ #pragma omp parallel for schedule(dynamic)
48
+ for (int i = 0; i < numDataPoints_; ++i) {
49
+ kernelVector(i) = kernel_(featureValues_.col(i), data, hyperparameters_);
50
+ }
51
+
52
+ // Calculate and return prediction
53
+ Eigen::MatrixXd kernelProduct = invertedRegularizedKernelMatrix_ * kernelVector;
54
+ Eigen::VectorXd prediction = targetValues_ * kernelProduct;
55
+
56
+ for (int k = 0; k < prediction.size(); ++k) {
57
+ if (std::isnan(prediction(k)))
58
+ throw std::runtime_error(
59
+ "One of the predicted results could not be obtained. The reason is probably that the regularization factor "
60
+ "is too small and therefore causes problems during the inversion of the kernel matrix.");
61
+ }
62
+
63
+ return prediction;
64
+ }
65
+
66
+ void KernelRidgeRegression::setRegularizationFactor(double factor) {
67
+ regularizationFactor_ = factor;
68
+ }
69
+
70
+ void KernelRidgeRegression::setKernel(
71
+ std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&, const std::vector<double>&)> kernel,
72
+ std::vector<double> hyperparameters) {
73
+ kernel_ = std::move(kernel);
74
+ hyperparameters_ = hyperparameters;
75
+ }
76
+
77
+ } // namespace MachineLearning
78
+ } // namespace Utils
79
+ } // namespace Scine
pool/shard006/C++/0083752_boss_ambassador_hellmaw.cpp ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/>
3
+ * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it
6
+ * under the terms of the GNU General Public License as published by the
7
+ * Free Software Foundation; either version 2 of the License, or (at your
8
+ * option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful, but WITHOUT
11
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13
+ * more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License along
16
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ /* ScriptData
20
+ SDName: Boss_Ambassador_Hellmaw
21
+ SD%Complete: 80
22
+ SDComment: Enrage spell missing/not known
23
+ SDCategory: Auchindoun, Shadow Labyrinth
24
+ EndScriptData */
25
+
26
+ #include "ScriptMgr.h"
27
+ #include "InstanceScript.h"
28
+ #include "ScriptedEscortAI.h"
29
+ #include "shadow_labyrinth.h"
30
+
31
+ enum Yells
32
+ {
33
+ SAY_INTRO = 0,
34
+ SAY_AGGRO = 1,
35
+ SAY_HELP = 2,
36
+ SAY_SLAY = 3,
37
+ SAY_DEATH = 4
38
+ };
39
+
40
+ enum Spells
41
+ {
42
+ SPELL_BANISH = 30231,
43
+ SPELL_CORROSIVE_ACID = 33551,
44
+ SPELL_FEAR = 33547,
45
+ SPELL_ENRAGE = 34970
46
+ };
47
+
48
+ enum Events
49
+ {
50
+ EVENT_CORROSIVE_ACID = 1,
51
+ EVENT_FEAR,
52
+ EVENT_BERSERK
53
+ };
54
+
55
+ class boss_ambassador_hellmaw : public CreatureScript
56
+ {
57
+ public:
58
+ boss_ambassador_hellmaw() : CreatureScript("boss_ambassador_hellmaw") { }
59
+
60
+ struct boss_ambassador_hellmawAI : public npc_escortAI
61
+ {
62
+ boss_ambassador_hellmawAI(Creature* creature) : npc_escortAI(creature)
63
+ {
64
+ _instance = creature->GetInstanceScript();
65
+ _intro = false;
66
+ }
67
+
68
+ void Reset() override
69
+ {
70
+ if (!me->IsAlive())
71
+ return;
72
+
73
+ _events.Reset();
74
+ _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, NOT_STARTED);
75
+
76
+ _events.ScheduleEvent(EVENT_CORROSIVE_ACID, urand(5000, 10000));
77
+ _events.ScheduleEvent(EVENT_FEAR, urand(25000, 30000));
78
+ if (IsHeroic())
79
+ _events.ScheduleEvent(EVENT_BERSERK, 180000);
80
+
81
+ DoAction(ACTION_AMBASSADOR_HELLMAW_BANISH);
82
+ }
83
+
84
+ void MoveInLineOfSight(Unit* who) override
85
+ {
86
+ if (me->HasAura(SPELL_BANISH))
87
+ return;
88
+
89
+ npc_escortAI::MoveInLineOfSight(who);
90
+ }
91
+
92
+ void WaypointReached(uint32 /*waypointId*/) override
93
+ {
94
+ }
95
+
96
+ void DoAction(int32 actionId) override
97
+ {
98
+ if (actionId == ACTION_AMBASSADOR_HELLMAW_INTRO)
99
+ DoIntro();
100
+ else if (actionId == ACTION_AMBASSADOR_HELLMAW_BANISH)
101
+ {
102
+ if (_instance->GetData(DATA_FEL_OVERSEER) && me->HasAura(SPELL_BANISH))
103
+ DoCast(me, SPELL_BANISH, true); // this will not work, because he is immune to banish
104
+ }
105
+ }
106
+
107
+ void DoIntro()
108
+ {
109
+ if (_intro)
110
+ return;
111
+
112
+ _intro = true;
113
+
114
+ if (me->HasAura(SPELL_BANISH))
115
+ me->RemoveAurasDueToSpell(SPELL_BANISH);
116
+
117
+ Talk(SAY_INTRO);
118
+ Start(true, false, ObjectGuid::Empty, NULL, false, true);
119
+ }
120
+
121
+ void EnterCombat(Unit* /*who*/) override
122
+ {
123
+ _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, IN_PROGRESS);
124
+ Talk(SAY_AGGRO);
125
+ }
126
+
127
+ void KilledUnit(Unit* who) override
128
+ {
129
+ if (who->GetTypeId() == TYPEID_PLAYER)
130
+ Talk(SAY_SLAY);
131
+ }
132
+
133
+ void JustDied(Unit* /*killer*/) override
134
+ {
135
+ _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, DONE);
136
+ Talk(SAY_DEATH);
137
+ }
138
+
139
+ void UpdateEscortAI(uint32 diff) override
140
+ {
141
+ if (!UpdateVictim())
142
+ return;
143
+
144
+ if (me->HasAura(SPELL_BANISH))
145
+ {
146
+ EnterEvadeMode(EVADE_REASON_OTHER);
147
+ return;
148
+ }
149
+
150
+ _events.Update(diff);
151
+
152
+ if (me->HasUnitState(UNIT_STATE_CASTING))
153
+ return;
154
+
155
+ while (uint32 eventId = _events.ExecuteEvent())
156
+ {
157
+ switch (eventId)
158
+ {
159
+ case EVENT_CORROSIVE_ACID:
160
+ DoCastVictim(SPELL_CORROSIVE_ACID);
161
+ _events.ScheduleEvent(EVENT_CORROSIVE_ACID, urand(15000, 25000));
162
+ break;
163
+ case EVENT_FEAR:
164
+ DoCastAOE(SPELL_FEAR);
165
+ _events.ScheduleEvent(EVENT_FEAR, urand(20000, 35000));
166
+ break;
167
+ case EVENT_BERSERK:
168
+ DoCast(me, SPELL_ENRAGE, true);
169
+ break;
170
+ default:
171
+ break;
172
+ }
173
+ }
174
+
175
+ DoMeleeAttackIfReady();
176
+ }
177
+
178
+ private:
179
+ InstanceScript* _instance;
180
+ EventMap _events;
181
+ bool _intro;
182
+ };
183
+
184
+ CreatureAI* GetAI(Creature* creature) const override
185
+ {
186
+ return GetShadowLabyrinthAI<boss_ambassador_hellmawAI>(creature);
187
+ }
188
+ };
189
+
190
+ void AddSC_boss_ambassador_hellmaw()
191
+ {
192
+ new boss_ambassador_hellmaw();
193
+ }
pool/shard006/C++/0083759_PersistentParserState.cpp ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===--- PersistentParserState.cpp - Parser State Implementation ----------===//
2
+ //
3
+ // This source file is part of the Swift.org open source project
4
+ //
5
+ // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6
+ // Licensed under Apache License v2.0 with Runtime Library Exception
7
+ //
8
+ // See https://swift.org/LICENSE.txt for license information
9
+ // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+ //
13
+ // This file implements parser state persistent across multiple parses.
14
+ //
15
+ //===----------------------------------------------------------------------===//
16
+
17
+ #include "swift/AST/Decl.h"
18
+ #include "swift/AST/Expr.h"
19
+ #include "swift/Parse/PersistentParserState.h"
20
+
21
+ using namespace swift;
22
+
23
+ void PersistentParserState::delayFunctionBodyParsing(AbstractFunctionDecl *AFD,
24
+ SourceRange BodyRange,
25
+ SourceLoc PreviousLoc) {
26
+ std::unique_ptr<FunctionBodyState> State;
27
+ State.reset(new FunctionBodyState(BodyRange, PreviousLoc,
28
+ ScopeInfo.saveCurrentScope()));
29
+ assert(DelayedFunctionBodies.find(AFD) == DelayedFunctionBodies.end() &&
30
+ "Already recorded state for this body");
31
+ DelayedFunctionBodies[AFD] = std::move(State);
32
+ }
33
+
34
+ std::unique_ptr<PersistentParserState::FunctionBodyState>
35
+ PersistentParserState::takeFunctionBodyState(AbstractFunctionDecl *AFD) {
36
+ assert(AFD->getBodyKind() == AbstractFunctionDecl::BodyKind::Unparsed);
37
+ DelayedFunctionBodiesTy::iterator I = DelayedFunctionBodies.find(AFD);
38
+ assert(I != DelayedFunctionBodies.end() && "State should be saved");
39
+ std::unique_ptr<FunctionBodyState> State = std::move(I->second);
40
+ DelayedFunctionBodies.erase(I);
41
+ return State;
42
+ }
43
+
44
+ bool PersistentParserState::hasFunctionBodyState(AbstractFunctionDecl *AFD) {
45
+ return DelayedFunctionBodies.find(AFD) != DelayedFunctionBodies.end();
46
+ }
47
+
48
+ void PersistentParserState::delayAccessorBodyParsing(AbstractFunctionDecl *AFD,
49
+ SourceRange BodyRange,
50
+ SourceLoc PreviousLoc,
51
+ SourceLoc LBLoc) {
52
+ std::unique_ptr<AccessorBodyState> State;
53
+ State.reset(new AccessorBodyState(BodyRange, PreviousLoc,
54
+ ScopeInfo.saveCurrentScope(), LBLoc));
55
+ assert(DelayedAccessorBodies.find(AFD) == DelayedAccessorBodies.end() &&
56
+ "Already recorded state for this body");
57
+ DelayedAccessorBodies[AFD] = std::move(State);
58
+ }
59
+
60
+ std::unique_ptr<PersistentParserState::AccessorBodyState>
61
+ PersistentParserState::takeAccessorBodyState(AbstractFunctionDecl *AFD) {
62
+ assert(AFD->getBodyKind() == AbstractFunctionDecl::BodyKind::Unparsed);
63
+ DelayedAccessorBodiesTy::iterator I = DelayedAccessorBodies.find(AFD);
64
+ assert(I != DelayedAccessorBodies.end() && "State should be saved");
65
+ std::unique_ptr<AccessorBodyState> State = std::move(I->second);
66
+ DelayedAccessorBodies.erase(I);
67
+ return State;
68
+ }
69
+
70
+ void PersistentParserState::delayDecl(DelayedDeclKind Kind,
71
+ unsigned Flags,
72
+ DeclContext *ParentContext,
73
+ SourceRange BodyRange,
74
+ SourceLoc PreviousLoc) {
75
+ assert(!CodeCompletionDelayedDeclState.get() &&
76
+ "only one decl can be delayed for code completion");
77
+ CodeCompletionDelayedDeclState.reset(new DelayedDeclState(
78
+ Kind, Flags, ParentContext, BodyRange, PreviousLoc,
79
+ ScopeInfo.saveCurrentScope()));
80
+ }
81
+
82
+ void PersistentParserState::delayTopLevel(TopLevelCodeDecl *TLCD,
83
+ SourceRange BodyRange,
84
+ SourceLoc PreviousLoc) {
85
+ delayDecl(DelayedDeclKind::TopLevelCodeDecl, 0U, TLCD, BodyRange,
86
+ PreviousLoc);
87
+ }
88
+
pool/shard006/C++/0083769_mysql_remap.cc ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements. See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership. The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License. You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
17
+ */
18
+
19
+ #include <ts/ts.h>
20
+ #include <ts/remap.h>
21
+ #include <cstdio>
22
+ #include <unistd.h>
23
+
24
+ #include <mysql/mysql.h>
25
+
26
+ #include "lib/iniparser.h"
27
+ #include "default.h"
28
+
29
+ MYSQL mysql;
30
+
31
+ typedef struct {
32
+ char *query;
33
+ } my_data;
34
+
35
+ bool
36
+ do_mysql_remap(TSCont contp, TSHttpTxn txnp)
37
+ {
38
+ TSMBuffer reqp;
39
+ TSMLoc hdr_loc, url_loc, field_loc;
40
+ bool ret_val = false;
41
+
42
+ const char *request_host;
43
+ int request_host_length = 0;
44
+ const char *request_scheme;
45
+ int request_scheme_length = 0;
46
+ int request_port = 80;
47
+ char *query;
48
+
49
+ MYSQL_ROW row;
50
+ MYSQL_RES *res;
51
+
52
+ my_data *data = static_cast<my_data *>(TSContDataGet(contp));
53
+ query = data->query;
54
+
55
+ if (TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc) != TS_SUCCESS) {
56
+ TSDebug(PLUGIN_NAME, "could not get request data");
57
+ return false;
58
+ }
59
+
60
+ TSHttpHdrUrlGet(reqp, hdr_loc, &url_loc);
61
+
62
+ if (!url_loc) {
63
+ TSDebug(PLUGIN_NAME, "couldn't retrieve request url");
64
+ goto release_hdr;
65
+ }
66
+
67
+ field_loc = TSMimeHdrFieldFind(reqp, hdr_loc, TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST);
68
+
69
+ if (!field_loc) {
70
+ TSDebug(PLUGIN_NAME, "couldn't retrieve request HOST header");
71
+ goto release_url;
72
+ }
73
+
74
+ request_host = TSMimeHdrFieldValueStringGet(reqp, hdr_loc, field_loc, -1, &request_host_length);
75
+ if (!request_host_length) {
76
+ TSDebug(PLUGIN_NAME, "couldn't find request HOST header");
77
+ goto release_field;
78
+ }
79
+
80
+ request_scheme = TSUrlSchemeGet(reqp, url_loc, &request_scheme_length);
81
+ request_port = TSUrlPortGet(reqp, url_loc);
82
+
83
+ TSDebug(PLUGIN_NAME, " +++++MYSQL REMAP+++++ ");
84
+
85
+ TSDebug(PLUGIN_NAME, "\nINCOMING REQUEST ->\n ::: from_scheme_desc: %.*s\n ::: from_hostname: %.*s\n ::: from_port: %d",
86
+ request_scheme_length, request_scheme, request_host_length, request_host, request_port);
87
+
88
+ snprintf(query, QSIZE, " \
89
+ SELECT \
90
+ t_scheme.scheme_desc, \
91
+ t_host.hostname, \
92
+ to_port \
93
+ FROM map \
94
+ INNER JOIN scheme as t_scheme ON (map.to_scheme_id = t_scheme.id) \
95
+ INNER JOIN scheme as f_scheme ON (map.from_scheme_id = f_scheme.id) \
96
+ INNER JOIN hostname as t_host ON (map.to_hostname_id = t_host.id) \
97
+ INNER JOIN hostname as f_host ON (map.from_hostname_id = f_host.id) \
98
+ WHERE \
99
+ is_enabled=1 \
100
+ AND f_host.hostname = '%.*s' \
101
+ AND f_scheme.id = %d \
102
+ AND from_port = %d \
103
+ LIMIT 1",
104
+ request_host_length, request_host, (strcmp(request_scheme, "https") == 0) ? 2 : 1, request_port);
105
+
106
+ mysql_real_query(&mysql, query, (unsigned int)strlen(query));
107
+ res = mysql_use_result(&mysql);
108
+
109
+ if (!res)
110
+ goto not_found; // TODO: define a fallback
111
+
112
+ do {
113
+ row = mysql_fetch_row(res);
114
+ if (!row)
115
+ goto not_found;
116
+ TSDebug(PLUGIN_NAME, "\nOUTGOING REQUEST ->\n ::: to_scheme_desc: %s\n ::: to_hostname: %s\n ::: to_port: %s", row[0], row[1],
117
+ row[2]);
118
+ TSMimeHdrFieldValueStringSet(reqp, hdr_loc, field_loc, 0, row[1], -1);
119
+ TSUrlHostSet(reqp, url_loc, row[1], -1);
120
+ TSUrlSchemeSet(reqp, url_loc, row[0], -1);
121
+ TSUrlPortSet(reqp, url_loc, atoi(row[2]));
122
+ } while (false);
123
+
124
+ ret_val = true;
125
+
126
+ not_found:
127
+ if (!ret_val) {
128
+ // lets build up a nice 404 message for someone
129
+ TSHttpHdrStatusSet(reqp, hdr_loc, TS_HTTP_STATUS_NOT_FOUND);
130
+ TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_NOT_FOUND);
131
+ }
132
+ if (res)
133
+ mysql_free_result(res);
134
+ #if (TS_VERSION_NUMBER < 2001005)
135
+ if (request_host)
136
+ TSHandleStringRelease(reqp, hdr_loc, request_host);
137
+ if (request_scheme)
138
+ TSHandleStringRelease(reqp, hdr_loc, request_scheme);
139
+ #endif
140
+ release_field:
141
+ if (field_loc) {
142
+ TSHandleMLocRelease(reqp, hdr_loc, field_loc);
143
+ }
144
+ release_url:
145
+ if (url_loc) {
146
+ TSHandleMLocRelease(reqp, hdr_loc, url_loc);
147
+ }
148
+ release_hdr:
149
+ if (hdr_loc) {
150
+ TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc);
151
+ }
152
+
153
+ return ret_val;
154
+ }
155
+
156
+ static int
157
+ mysql_remap(TSCont contp, TSEvent event, void *edata)
158
+ {
159
+ TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
160
+ TSEvent reenable = TS_EVENT_HTTP_CONTINUE;
161
+
162
+ switch (event) {
163
+ case TS_EVENT_HTTP_READ_REQUEST_HDR:
164
+ TSDebug(PLUGIN_NAME, "Reading Request");
165
+ TSSkipRemappingSet(txnp, 1);
166
+ if (!do_mysql_remap(contp, txnp)) {
167
+ reenable = TS_EVENT_HTTP_ERROR;
168
+ }
169
+ break;
170
+ default:
171
+ break;
172
+ }
173
+
174
+ TSHttpTxnReenable(txnp, reenable);
175
+ return 1;
176
+ }
177
+
178
+ void
179
+ TSPluginInit(int argc, const char *argv[])
180
+ {
181
+ dictionary *ini;
182
+ const char *host;
183
+ int port;
184
+ const char *username;
185
+ const char *password;
186
+ const char *db;
187
+
188
+ my_data *data = static_cast<my_data *>(malloc(1 * sizeof(my_data)));
189
+
190
+ TSPluginRegistrationInfo info;
191
+ bool reconnect = true;
192
+
193
+ info.plugin_name = const_cast<char *>(PLUGIN_NAME);
194
+ info.vendor_name = const_cast<char *>("Apache Software Foundation");
195
+ info.support_email = const_cast<char *>("dev@trafficserver.apache.org");
196
+
197
+ if (TSPluginRegister(&info) != TS_SUCCESS) {
198
+ TSError("[mysql_remap] Plugin registration failed");
199
+ }
200
+
201
+ if (argc != 2) {
202
+ TSError("[mysql_remap] Usage: %s /path/to/sample.ini", argv[0]);
203
+ return;
204
+ }
205
+
206
+ ini = iniparser_load(argv[1]);
207
+ if (!ini) {
208
+ TSError("[mysql_remap] Error with ini file (1)");
209
+ TSDebug(PLUGIN_NAME, "Error parsing ini file(1)");
210
+ return;
211
+ }
212
+
213
+ host = iniparser_getstring(ini, "mysql_remap:mysql_host", (char *)"localhost");
214
+ port = iniparser_getint(ini, "mysql_remap:mysql_port", 3306);
215
+ username = iniparser_getstring(ini, "mysql_remap:mysql_username", nullptr);
216
+ password = iniparser_getstring(ini, "mysql_remap:mysql_password", nullptr);
217
+ db = iniparser_getstring(ini, "mysql_remap:mysql_database", (char *)"mysql_remap");
218
+
219
+ if (mysql_library_init(0, NULL, NULL)) {
220
+ TSError("[mysql_remap] Error initializing mysql client library");
221
+ TSDebug(PLUGIN_NAME, "Error initializing mysql client library");
222
+ return;
223
+ }
224
+
225
+ if (!mysql_init(&mysql)) {
226
+ TSError("[mysql_remap] Could not initialize MySQL");
227
+ TSDebug(PLUGIN_NAME, "Could not initialize MySQL");
228
+ return;
229
+ }
230
+
231
+ mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
232
+
233
+ if (!mysql_real_connect(&mysql, host, username, password, db, port, NULL, 0)) {
234
+ TSError("[mysql_remap] Could not connect to mysql");
235
+ TSDebug(PLUGIN_NAME, "Could not connect to mysql: %s", mysql_error(&mysql));
236
+ return;
237
+ }
238
+
239
+ data->query = static_cast<char *>(TSmalloc(QSIZE * sizeof(char))); // TODO: malloc smarter sizes
240
+
241
+ TSDebug(PLUGIN_NAME, "h: %s; u: %s; p: %s; p:%d; d:%s", host, username, password, port, db);
242
+ TSCont cont = TSContCreate(mysql_remap, TSMutexCreate());
243
+
244
+ TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, cont);
245
+
246
+ TSContDataSet(cont, (void *)data);
247
+
248
+ TSDebug(PLUGIN_NAME, "plugin is successfully initialized [plugin mode]");
249
+ iniparser_freedict(ini);
250
+ return;
251
+ }
pool/shard006/C++/0083771_DumpMassCharge.cpp ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
+ Copyright (c) 2015-2020 The plumed team
3
+ (see the PEOPLE file at the root of the distribution for a list of names)
4
+
5
+ See http://www.plumed.org for more information.
6
+
7
+ This file is part of plumed, version 2.
8
+
9
+ plumed is free software: you can redistribute it and/or modify
10
+ it under the terms of the GNU Lesser General Public License as published by
11
+ the Free Software Foundation, either version 3 of the License, or
12
+ (at your option) any later version.
13
+
14
+ plumed is distributed in the hope that it will be useful,
15
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ GNU Lesser General Public License for more details.
18
+
19
+ You should have received a copy of the GNU Lesser General Public License
20
+ along with plumed. If not, see <http://www.gnu.org/licenses/>.
21
+ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
22
+ #include "core/ActionAtomistic.h"
23
+ #include "core/ActionPilot.h"
24
+ #include "core/ActionRegister.h"
25
+ #include "tools/File.h"
26
+ #include "core/PlumedMain.h"
27
+ #include "core/Atoms.h"
28
+
29
+ using namespace std;
30
+
31
+ namespace PLMD
32
+ {
33
+ namespace generic {
34
+
35
+ //+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE
36
+ /*
37
+ Dump masses and charges on a selected file.
38
+
39
+ This command dumps a file containing charges and masses.
40
+ It does so only once in the simulation (at first step).
41
+ File can be recycled in the \ref driver tool.
42
+
43
+ Notice that masses and charges are only written once at the beginning
44
+ of the simulation. In case no atom list is provided, charges and
45
+ masses for all atoms are written.
46
+
47
+ \par Examples
48
+
49
+ You can add the DUMPMASSCHARGE action at the end of the plumed.dat
50
+ file that you use during an MD simulations:
51
+
52
+ \plumedfile
53
+ c1: COM ATOMS=1-10
54
+ c2: COM ATOMS=11-20
55
+ DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100
56
+
57
+ DUMPMASSCHARGE FILE=mcfile
58
+ \endplumedfile
59
+
60
+ In this way, you will be able to use the same masses while processing
61
+ a trajectory from the \ref driver . To do so, you need to
62
+ add the --mc flag on the driver command line, e.g.
63
+ \verbatim
64
+ plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz
65
+ \endverbatim
66
+
67
+ With the following input you can dump only the charges for a specific
68
+ group.
69
+ \plumedfile
70
+ solute_ions: GROUP ATOMS=1-121,200-2012
71
+ DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100
72
+ DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions
73
+ \endplumedfile
74
+ Notice however that if you want to process the charges
75
+ with the driver (e.g. reading traj.gro) you have to fix atom
76
+ numbers first, e.g. with the script
77
+ \verbatim
78
+ awk 'BEGIN{c=0}{
79
+ if(match($0,"#")) print ; else {print c,$2,$3; c++}
80
+ }' < mc > newmc
81
+ }'
82
+ \endverbatim
83
+ then
84
+ \verbatim
85
+ plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro
86
+ \endverbatim
87
+
88
+
89
+ */
90
+ //+ENDPLUMEDOC
91
+
92
+ class DumpMassCharge:
93
+ public ActionAtomistic,
94
+ public ActionPilot
95
+ {
96
+ string file;
97
+ bool first;
98
+ bool second;
99
+ bool print_masses;
100
+ bool print_charges;
101
+ public:
102
+ explicit DumpMassCharge(const ActionOptions&);
103
+ ~DumpMassCharge();
104
+ static void registerKeywords( Keywords& keys );
105
+ void prepare() override;
106
+ void calculate() override {}
107
+ void apply() override {}
108
+ void update() override;
109
+ };
110
+
111
+ PLUMED_REGISTER_ACTION(DumpMassCharge,"DUMPMASSCHARGE")
112
+
113
+ void DumpMassCharge::registerKeywords( Keywords& keys ) {
114
+ Action::registerKeywords( keys );
115
+ ActionPilot::registerKeywords( keys );
116
+ ActionAtomistic::registerKeywords( keys );
117
+ keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output");
118
+ keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out");
119
+ keys.add("compulsory", "FILE", "file on which to output charges and masses.");
120
+ keys.addFlag("ONLY_MASSES",false,"Only output masses to file");
121
+ keys.addFlag("ONLY_CHARGES",false,"Only output charges to file");
122
+ }
123
+
124
+ DumpMassCharge::DumpMassCharge(const ActionOptions&ao):
125
+ Action(ao),
126
+ ActionAtomistic(ao),
127
+ ActionPilot(ao),
128
+ first(true),
129
+ second(true),
130
+ print_masses(true),
131
+ print_charges(true)
132
+ {
133
+ vector<AtomNumber> atoms;
134
+ parse("FILE",file);
135
+ if(file.length()==0) error("name of output file was not specified");
136
+ log.printf(" output written to file %s\n",file.c_str());
137
+
138
+ parseAtomList("ATOMS",atoms);
139
+
140
+ if(atoms.size()==0) {
141
+ for(int i=0; i<plumed.getAtoms().getNatoms(); i++) {
142
+ atoms.push_back(AtomNumber::index(i));
143
+ }
144
+ }
145
+
146
+ bool only_masses = false;
147
+ parseFlag("ONLY_MASSES",only_masses);
148
+ if(only_masses) {
149
+ print_charges = false;
150
+ log.printf(" only masses will be written to file\n");
151
+ }
152
+
153
+ bool only_charges = false;
154
+ parseFlag("ONLY_CHARGES",only_charges);
155
+ if(only_charges) {
156
+ print_masses = false;
157
+ log.printf(" only charges will be written to file\n");
158
+ }
159
+
160
+
161
+ checkRead();
162
+
163
+ log.printf(" printing the following atoms:" );
164
+ for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() );
165
+ log.printf("\n");
166
+ requestAtoms(atoms);
167
+
168
+ if(only_masses && only_charges) {
169
+ plumed_merror("using both ONLY_MASSES and ONLY_CHARGES doesn't make sense");
170
+ }
171
+
172
+ }
173
+
174
+ void DumpMassCharge::prepare() {
175
+ if(!first && second) {
176
+ requestAtoms(vector<AtomNumber>());
177
+ second=false;
178
+ }
179
+ }
180
+
181
+ void DumpMassCharge::update() {
182
+ if(!first) return;
183
+ first=false;
184
+
185
+ OFile of;
186
+ of.link(*this);
187
+ of.open(file);
188
+
189
+ for(unsigned i=0; i<getNumberOfAtoms(); i++) {
190
+ int ii=getAbsoluteIndex(i).index();
191
+ of.printField("index",ii);
192
+ if(print_masses) {of.printField("mass",getMass(i));}
193
+ if(print_charges) {of.printField("charge",getCharge(i));}
194
+ of.printField();
195
+ }
196
+ }
197
+
198
+ DumpMassCharge::~DumpMassCharge() {
199
+ }
200
+
201
+
202
+ }
203
+ }
pool/shard006/C++/0083773_desktop_screen_position_client.cc ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "ui/views/widget/desktop_aura/desktop_screen_position_client.h"
6
+
7
+ #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
8
+
9
+ namespace views {
10
+
11
+ namespace {
12
+
13
+ // Returns true if bounds passed to window in SetBounds should be treated as
14
+ // though they are in screen coordinates.
15
+ bool PositionWindowInScreenCoordinates(aura::Window* window) {
16
+ if (window->type() == ui::wm::WINDOW_TYPE_POPUP)
17
+ return true;
18
+
19
+ Widget* widget = Widget::GetWidgetForNativeView(window);
20
+ return widget && widget->is_top_level();
21
+ }
22
+
23
+ } // namespace
24
+
25
+ DesktopScreenPositionClient::DesktopScreenPositionClient(
26
+ aura::Window* root_window)
27
+ : wm::DefaultScreenPositionClient(), root_window_(root_window) {
28
+ aura::client::SetScreenPositionClient(root_window_, this);
29
+ }
30
+
31
+ DesktopScreenPositionClient::~DesktopScreenPositionClient() {
32
+ aura::client::SetScreenPositionClient(root_window_, NULL);
33
+ }
34
+
35
+ void DesktopScreenPositionClient::SetBounds(aura::Window* window,
36
+ const gfx::Rect& bounds,
37
+ const gfx::Display& display) {
38
+ // TODO(jam): Use the 3rd parameter, |display|.
39
+ aura::Window* root = window->GetRootWindow();
40
+
41
+ // This method assumes that |window| does not have an associated
42
+ // DesktopNativeWidgetAura.
43
+ internal::NativeWidgetPrivate* desktop_native_widget =
44
+ DesktopNativeWidgetAura::ForWindow(root);
45
+ DCHECK(!desktop_native_widget ||
46
+ desktop_native_widget->GetNativeView() != window);
47
+
48
+ if (PositionWindowInScreenCoordinates(window)) {
49
+ // The caller expects windows we consider "embedded" to be placed in the
50
+ // screen coordinate system. So we need to offset the root window's
51
+ // position (which is in screen coordinates) from these bounds.
52
+
53
+ gfx::Point origin = bounds.origin();
54
+ aura::Window::ConvertPointToTarget(window->parent(), root, &origin);
55
+
56
+ gfx::Point host_origin = GetOriginInScreen(root);
57
+ origin.Offset(-host_origin.x(), -host_origin.y());
58
+ window->SetBounds(gfx::Rect(origin, bounds.size()));
59
+ return;
60
+ }
61
+
62
+ window->SetBounds(bounds);
63
+ }
64
+
65
+ } // namespace views
pool/shard006/C++/0083780_a.cc ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <string>
3
+
4
+ using namespace std;
5
+
6
+ class MyClass {
7
+
8
+ private:
9
+ string name;
10
+
11
+ public:
12
+ MyClass (string s) :name(s) {}
13
+ ~MyClass() {
14
+ cout << "Destroying " << name << endl;
15
+ }
16
+ };
17
+
18
+ void fa();
19
+ void fb();
20
+ void fc();
21
+ void fd();
22
+
23
+ int main() {
24
+
25
+ try {
26
+
27
+ MyClass mainObj("M");
28
+ fa();
29
+ cout << "Mission accomplished!\n";
30
+
31
+ } catch (const char *e) {
32
+
33
+ cout << "exception: " << e << endl;
34
+ cout << "Mission impossible!\n";
35
+ }
36
+
37
+ return 0;
38
+ }
39
+
40
+ void fa() {
41
+ MyClass a("A");
42
+ fb();
43
+ cout << "return from fa()\n";
44
+ return;
45
+ }
46
+
47
+ void fb() {
48
+ MyClass b("B");
49
+ fc();
50
+ cout << "return from fb()\n";
51
+ return;
52
+ }
53
+
54
+ void fc() {
55
+ MyClass c("C");
56
+ fd();
57
+ cout << "return from fc()\n";
58
+ return;
59
+ }
60
+
61
+ void fd() {
62
+ MyClass d("D");
63
+ throw "in fd(), something weird happened.";
64
+ cout << "return from fd()\n";
65
+ return;
66
+ }
67
+
pool/shard006/C++/0083783_AudioManager.cpp ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "AudioManager.h"
2
+
3
+ AudioManager& AudioManager::getInstance()
4
+ {
5
+ static AudioManager s;
6
+ return s;
7
+ }
8
+
9
+ void AudioManager::playBackgroundAudio()
10
+ {
11
+ if (_playing == true)
12
+ stopBackgroundAudio(); //only one sound thread can be played at the same time
13
+ background_audioID = AudioEngine::play2d(BACKGROUND_SOUND, true, 1.0f);
14
+ _playing = true;
15
+ }
16
+
17
+ void AudioManager::stopBackgroundAudio()
18
+ {
19
+ AudioEngine::stop(background_audioID);
20
+ _playing = false;
21
+ }
22
+
23
+ void AudioManager::pauseBackgroundAudio()
24
+ {
25
+ AudioEngine::pause(background_audioID);
26
+ _playing = false;
27
+ }
28
+
29
+ void AudioManager::resumeBackgroundAudio()
30
+ {
31
+ AudioEngine::resume(background_audioID);
32
+ _playing = true;
33
+ }
34
+
35
+ void AudioManager::setBackgroundAudioVolume(float value)
36
+ {
37
+ AudioEngine::setVolume(background_audioID, value);
38
+ }
39
+
40
+ float AudioManager::getBackgroundAudioVolume()
41
+ {
42
+ return AudioEngine::getVolume(background_audioID);
43
+ }
44
+
45
+ void AudioManager::endAudio()
46
+ {
47
+ _playing = false;
48
+ AudioEngine::end();
49
+ }
50
+
51
+ bool AudioManager::isBackgroundMusicPlaying()
52
+ {
53
+ return _playing;
54
+ }
pool/shard006/C++/0083789_GrGLShaderStringBuilder.cpp ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2014 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 "GrGLShaderStringBuilder.h"
9
+ #include "gl/GrGLGpu.h"
10
+ #include "gl/GrGLSLPrettyPrint.h"
11
+ #include "SkTraceEvent.h"
12
+
13
+ #define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X)
14
+ #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X)
15
+
16
+ // Print the source code for all shaders generated.
17
+ static const bool c_PrintShaders{false};
18
+
19
+ static void print_shader_source(const char** strings, int* lengths, int count);
20
+
21
+ GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx,
22
+ GrGLuint programId,
23
+ GrGLenum type,
24
+ const char** strings,
25
+ int* lengths,
26
+ int count,
27
+ GrGpu::Stats* stats) {
28
+ const GrGLInterface* gli = glCtx.interface();
29
+
30
+ GrGLuint shaderId;
31
+ GR_GL_CALL_RET(gli, shaderId, CreateShader(type));
32
+ if (0 == shaderId) {
33
+ return 0;
34
+ }
35
+
36
+ #ifdef SK_DEBUG
37
+ SkString prettySource = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, false);
38
+ const GrGLchar* sourceStr = prettySource.c_str();
39
+ GrGLint sourceLength = static_cast<GrGLint>(prettySource.size());
40
+ GR_GL_CALL(gli, ShaderSource(shaderId, 1, &sourceStr, &sourceLength));
41
+ #else
42
+ GR_GL_CALL(gli, ShaderSource(shaderId, count, strings, lengths));
43
+ #endif
44
+
45
+ // If tracing is enabled in chrome then we pretty print
46
+ bool traceShader;
47
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), &traceShader);
48
+ if (traceShader) {
49
+ SkString shader = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, false);
50
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader",
51
+ TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shader.c_str()));
52
+ }
53
+
54
+ stats->incShaderCompilations();
55
+ GR_GL_CALL(gli, CompileShader(shaderId));
56
+
57
+ // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds.
58
+ bool checkCompiled = kChromium_GrGLDriver != glCtx.driver();
59
+ #ifdef SK_DEBUG
60
+ checkCompiled = true;
61
+ #endif
62
+ if (checkCompiled) {
63
+ GrGLint compiled = GR_GL_INIT_ZERO;
64
+ GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled));
65
+
66
+ if (!compiled) {
67
+ GrGLint infoLen = GR_GL_INIT_ZERO;
68
+ GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen));
69
+ SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
70
+ if (infoLen > 0) {
71
+ // retrieve length even though we don't need it to workaround bug in Chromium cmd
72
+ // buffer param validation.
73
+ GrGLsizei length = GR_GL_INIT_ZERO;
74
+ GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get()));
75
+ print_shader_source(strings, lengths, count);
76
+ SkDebugf("\n%s", (const char*)log.get());
77
+ }
78
+ SkDEBUGFAIL("Shader compilation failed!");
79
+ GR_GL_CALL(gli, DeleteShader(shaderId));
80
+ return 0;
81
+ }
82
+ }
83
+
84
+ if (c_PrintShaders) {
85
+ print_shader_source(strings, lengths, count);
86
+ }
87
+
88
+ // Attach the shader, but defer deletion until after we have linked the program.
89
+ // This works around a bug in the Android emulator's GLES2 wrapper which
90
+ // will immediately delete the shader object and free its memory even though it's
91
+ // attached to a program, which then causes glLinkProgram to fail.
92
+ GR_GL_CALL(gli, AttachShader(programId, shaderId));
93
+
94
+ return shaderId;
95
+ }
96
+
97
+ static void print_shader_source(const char** strings, int* lengths, int count) {
98
+ const SkString& pretty = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, true);
99
+ SkTArray<SkString> lines;
100
+ SkStrSplit(pretty.c_str(), "\n", &lines);
101
+ for (const SkString& line : lines) {
102
+ // Print the shader one line at the time so it doesn't get truncated by the adb log.
103
+ SkDebugf("%s\n", line.c_str());
104
+ }
105
+ }
pool/shard006/C++/0083795_utest_gen_sentence.cpp ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <vector>
3
+ #include <string>
4
+ #include <stdexcept>
5
+ #include "cppunit/ui/text/TestRunner.h"
6
+ #include "cppunit/TestCaller.h"
7
+ #include "cppunit/extensions/HelperMacros.h"
8
+ #include "gen_sentence.h"
9
+
10
+ using std::vector;
11
+ using std::string;
12
+ using std::logic_error;
13
+
14
+
15
+
16
+ class GenAuxTest : public CppUnit::TestFixture {
17
+
18
+ private:
19
+
20
+ Grammar *grammar;
21
+ vector<string> *recipe, *actualize, *location;
22
+
23
+ public:
24
+
25
+ void setUp() {
26
+
27
+ grammar = new Grammar;
28
+ recipe = new vector<string>;
29
+ actualize = new vector<string>;
30
+ location = new vector<string>;
31
+
32
+ location->push_back("wherever");
33
+ location->push_back("it");
34
+ location->push_back("wants");
35
+ (*grammar)["<location>"].push_back(*location);
36
+
37
+ recipe->push_back("<ending>");
38
+
39
+ actualize->push_back("the");
40
+ actualize->push_back("dog");
41
+ actualize->push_back("sits");
42
+ }
43
+
44
+
45
+ void tearDown() {
46
+ delete grammar;
47
+ delete recipe;
48
+ delete actualize;
49
+ }
50
+
51
+
52
+ // check behavior for a literal (i.e. not a bracketed rule) word
53
+ void test_word_literal() {
54
+
55
+ Grammar grammar_before = *grammar;
56
+ vector<string> recipe_before = *recipe;
57
+ vector<string> actualize_before = *actualize;
58
+ string word_literal = "yayaya!";
59
+
60
+ gen_aux(*grammar, word_literal, *recipe, *actualize);
61
+
62
+ // these should remain unchanged
63
+ CPPUNIT_ASSERT(*grammar == grammar_before);
64
+ CPPUNIT_ASSERT(*recipe == recipe_before);
65
+
66
+ // should simply append `word_literal' to `*actualize'
67
+ CPPUNIT_ASSERT(actualize->size() == 4);
68
+ CPPUNIT_ASSERT((*actualize)[0] == actualize_before[0]);
69
+ CPPUNIT_ASSERT((*actualize)[1] == actualize_before[1]);
70
+ CPPUNIT_ASSERT((*actualize)[2] == actualize_before[2]);
71
+ CPPUNIT_ASSERT((*actualize)[3] == word_literal);
72
+ }
73
+
74
+
75
+ // check behavior for a rule word
76
+ void test_word_rule() {
77
+
78
+ Grammar grammar_before = *grammar;
79
+ vector<string> recipe_before = *recipe;
80
+ vector<string> actualize_before = *actualize;
81
+ string word_rule = "<location>";
82
+
83
+ gen_aux(*grammar, word_rule, *recipe, *actualize);
84
+
85
+ // these should location vector is reverse order
86
+ CPPUNIT_ASSERT(*grammar == grammar_before);
87
+ CPPUNIT_ASSERT(*actualize == actualize_before);
88
+
89
+ // should append words from (*grammar)["<location>"][0] to *recipe, in
90
+ // reverse
91
+ CPPUNIT_ASSERT(recipe->size() == 4);
92
+ CPPUNIT_ASSERT((*recipe)[0] == recipe_before[0]);
93
+ CPPUNIT_ASSERT((*recipe)[1] == (*location)[2]);
94
+ CPPUNIT_ASSERT((*recipe)[2] == (*location)[1]);
95
+ CPPUNIT_ASSERT((*recipe)[3] == (*location)[0]);
96
+ }
97
+
98
+
99
+ // check that providing a `word' not defined in `grammer' throws an
100
+ // exception
101
+ void test_illegal_word() {
102
+ CPPUNIT_ASSERT_THROW(gen_aux(*grammar, "<no_rule>", *recipe, *actualize),
103
+ logic_error);
104
+ }
105
+
106
+
107
+ CPPUNIT_TEST_SUITE(GenAuxTest);
108
+ CPPUNIT_TEST(test_word_literal);
109
+ CPPUNIT_TEST(test_word_rule);
110
+ CPPUNIT_TEST(test_illegal_word);
111
+ CPPUNIT_TEST_SUITE_END();
112
+ };
113
+
114
+
115
+
116
+
117
+ int main() {
118
+
119
+ CppUnit::TextUi::TestRunner runner;
120
+ runner.addTest(GenAuxTest::suite());
121
+
122
+ return runner.run() ? 0 : 1;
123
+ }
pool/shard006/C++/0083801_EPattern.cpp ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * EPattern.cpp
3
+ *
4
+ * Created on: 2013-3-25
5
+ * Author: cxxjava@163.com
6
+ */
7
+
8
+ #include "EPattern.hh"
9
+ #include "EPatternSyntaxException.hh"
10
+ #include "EMatcher.hh"
11
+
12
+ namespace efc {
13
+
14
+ EPattern::~EPattern()
15
+ {
16
+ eso_pcre_free(&_pcre);
17
+ }
18
+
19
+ EPattern::EPattern(const char* regex, int opetion) THROWS(EPatternSyntaxException)
20
+ {
21
+ _pattern = regex;
22
+
23
+ int v;
24
+ _pcre = eso_pcre_make(regex, opetion, &v);
25
+ if (!_pcre) {
26
+ throw EPatternSyntaxException(__FILE__, __LINE__);
27
+ }
28
+ }
29
+
30
+ EString EPattern::pattern()
31
+ {
32
+ return _pattern;
33
+ }
34
+
35
+ EString EPattern::toString()
36
+ {
37
+ return _pattern;
38
+ }
39
+
40
+ es_pcre_t* EPattern::c_pcre()
41
+ {
42
+ return _pcre;
43
+ }
44
+
45
+ EMatcher* EPattern::newMatcher(const char* input)
46
+ {
47
+ return new EMatcher(this, input);
48
+ }
49
+
50
+ EArray<EString*> EPattern::split(const char* input, int limit)
51
+ {
52
+ const char *regex = _pattern.c_str();
53
+ EArray<EString*> res;
54
+ EString *s;
55
+
56
+ if (!input || !*input) {
57
+ return res;
58
+ }
59
+
60
+ if (!regex || !*regex) {
61
+ s = new EString(input);
62
+ res.add(s);
63
+ return res;
64
+ }
65
+
66
+ int v, count, length;
67
+ int ovector[3];
68
+ char *psrc = (char*)input;
69
+
70
+ count = length = 0;
71
+ while (*psrc && ((limit == 0) || (count < limit))) {
72
+ v = eso_pcre_exec(_pcre, psrc, -1, 0, 0, ovector, 3);
73
+ if (v >= 0) {
74
+ res.add(new EString(psrc, 0, ovector[0]));
75
+ psrc += ovector[1];
76
+ count++;
77
+
78
+ continue;
79
+ }
80
+ else if (v == -1) {
81
+ res.add(new EString(psrc));
82
+ break;
83
+ }
84
+ else if (v < -1) {
85
+ throw EPatternSyntaxException(__FILE__, __LINE__);
86
+ }
87
+ }
88
+
89
+ return res;
90
+ }
91
+
92
+ EArray<EString*> EPattern::split(const char* regex, const char* input,
93
+ int limit) THROWS(EPatternSyntaxException)
94
+ {
95
+ EArray<EString*> res;
96
+ EString *s;
97
+
98
+ if (!input) {
99
+ return res;
100
+ }
101
+
102
+ if (!regex || !*regex) {
103
+ s = new EString(input);
104
+ res.add(s);
105
+ return res;
106
+ }
107
+
108
+ //@see: openjdk-8/src/share/classes/java/lang/String.java#L2316
109
+
110
+ /* fastpath if the regex is a
111
+ (1)one-char String and this character is not one of the
112
+ RegEx's meta characters ".$|()[{^?*+\\", or
113
+ (2)two-char String and the first char is the backslash and
114
+ the second is not the ascii digit or ascii letter.
115
+ */
116
+ char ch = 0;
117
+ if (((eso_strlen(regex) == 1 &&
118
+ eso_strchr(".$|()[{^?*+\\", (ch = regex[0])) == NULL) ||
119
+ (eso_strlen(regex) == 2 &&
120
+ regex[0] == '\\' &&
121
+ (((ch = regex[1])-'0')|('9'-ch)) < 0 &&
122
+ ((ch-'a')|('z'-ch)) < 0 &&
123
+ ((ch-'A')|('Z'-ch)) < 0)))
124
+ {
125
+ EString s(input);
126
+ int off = 0;
127
+ int next = 0;
128
+ boolean limited = limit > 0;
129
+ while ((next = s.indexOf(ch, off)) != -1) {
130
+ if (!limited || res.size() < limit - 1) {
131
+ res.add(new EString(s.substring(off, next)));
132
+ off = next + 1;
133
+ } else { // last one
134
+ //assert (res.size() == limit - 1);
135
+ res.add(new EString(s.substring(off, s.length())));
136
+ off = s.length();
137
+ break;
138
+ }
139
+ }
140
+ // If no match was found, return this
141
+ if (off == 0) {
142
+ res.add(new EString(input));
143
+ return res;
144
+ }
145
+
146
+ // Add remaining segment
147
+ if (!limited || res.size() < limit)
148
+ res.add(new EString(s.substring(off, s.length())));
149
+
150
+ /* @see:
151
+ // Construct result
152
+ int resultSize = list.size();
153
+ if (limit == 0) {
154
+ while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
155
+ resultSize--;
156
+ }
157
+ }
158
+ String[] result = new String[resultSize];
159
+ return list.subList(0, resultSize).toArray(result);
160
+ */
161
+ int resultSize = res.size();
162
+ for (int i=resultSize-1; i>=0; i--) {
163
+ if (res[i]->length() == 0) {
164
+ res.removeAt(i);
165
+ } else {
166
+ break;
167
+ }
168
+ }
169
+
170
+ return res;
171
+ }
172
+
173
+ //=================================================
174
+
175
+ es_pcre_t *pcre;
176
+ int v, count, length;
177
+ int ovector[3];
178
+ char *psrc = (char*)input;
179
+
180
+ pcre = eso_pcre_make(regex, 0, &v);
181
+ if (!pcre) {
182
+ throw EPatternSyntaxException(__FILE__, __LINE__);
183
+ }
184
+
185
+ count = length = 0;
186
+ while (*psrc && ((limit == 0) || (count < limit))) {
187
+ v = eso_pcre_exec(pcre, psrc, -1, 0, 0, ovector, 3);
188
+ if (v >= 0) {
189
+ res.add(new EString(psrc, 0, ovector[0]));
190
+ psrc += ovector[1];
191
+ count++;
192
+
193
+ continue;
194
+ }
195
+ else if (v == -1) {
196
+ res.add(new EString(psrc));
197
+ break;
198
+ }
199
+ else if (v < -1) {
200
+ eso_pcre_free(&pcre);
201
+ throw EPatternSyntaxException(__FILE__, __LINE__);
202
+ }
203
+ }
204
+
205
+ eso_pcre_free(&pcre);
206
+
207
+ return res;
208
+ }
209
+
210
+ boolean EPattern::matches(const char* regex, const char* input) THROWS(EPatternSyntaxException)
211
+ {
212
+ if ((!input || !*input) && (!regex || !*regex)) {
213
+ return true;
214
+ }
215
+
216
+ if (!input || !*input) {
217
+ return false;
218
+ }
219
+
220
+ if (!regex || !*regex) {
221
+ return false;
222
+ }
223
+
224
+ es_pcre_t *pcre;
225
+ int v;
226
+ int ovector[3];
227
+ boolean ret;
228
+
229
+ pcre = eso_pcre_make(regex, 0, &v);
230
+ if (!pcre) {
231
+ throw EPatternSyntaxException(__FILE__, __LINE__);
232
+ }
233
+
234
+ v = eso_pcre_exec(pcre, input, -1, 0, 0, ovector, 3);
235
+ if (v >= 0) {
236
+ ret = true;
237
+ } else if (v == -1) {
238
+ ret = false;
239
+ } else if (v < -1) {
240
+ eso_pcre_free(&pcre);
241
+ throw EPatternSyntaxException(__FILE__, __LINE__);
242
+ }
243
+
244
+ eso_pcre_free(&pcre);
245
+
246
+ return ret;
247
+ }
248
+
249
+ } /* namespace efc */
pool/shard006/C++/0083803_settlement_evaluator.cc ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- mode: c++; indent-tabs-mode: nil -*- */
2
+
3
+ /*
4
+ Determining the molar fraction of a gas component within a gas mixture.
5
+
6
+ License: BSD
7
+ Authors:
8
+ */
9
+
10
+ #include "settlement_evaluator.hh"
11
+ #include "boost/math/constants/constants.hpp"
12
+
13
+ namespace Amanzi {
14
+
15
+ SettlementRateEvaluator :: SettlementRateEvaluator(Teuchos::ParameterList& plist) :
16
+ SecondaryVariableFieldEvaluator(plist) {
17
+
18
+ Key domain_name = "surface";
19
+
20
+ velocity_key_ = plist_.get<std::string>("velocity key",
21
+ Keys::getKey(domain_name,"velocity"));
22
+
23
+ sediment_key_ = plist_.get<std::string>("sediment key",
24
+ Keys::getKey(domain_name,"sediment"));
25
+
26
+ tau_d_ = plist_.get<double>("critical shear stress");
27
+ ws_ = plist_.get<double>("settling velocity");
28
+ gamma_ = plist_.get<double>("specific weight of water");
29
+ sediment_density_ = plist_.get<double>("sediment density [kg m^-3]");
30
+
31
+
32
+ umax_ = plist_.get<double>("max current");
33
+ xi_ = plist_.get<double>("Chezy parameter");
34
+
35
+ double pi = boost::math::constants::pi<double>();
36
+
37
+ lambda_ = 8./(3*pi) * (umax_/(xi_*xi_));
38
+
39
+ dependencies_.insert("surface-pressure");
40
+ dependencies_.insert(sediment_key_);
41
+
42
+ }
43
+
44
+
45
+ SettlementRateEvaluator ::SettlementRateEvaluator (const SettlementRateEvaluator & other) :
46
+ SecondaryVariableFieldEvaluator(other),
47
+ velocity_key_(other.velocity_key_), sediment_key_(other.sediment_key_) {
48
+
49
+ tau_d_ = other.tau_d_;
50
+ ws_ = other.ws_;
51
+ gamma_ = other.gamma_;
52
+ lambda_ = other.lambda_;
53
+ sediment_density_ = other.sediment_density_;
54
+ }
55
+
56
+
57
+ Teuchos::RCP<FieldEvaluator> SettlementRateEvaluator ::Clone() const {
58
+ return Teuchos::rcp(new SettlementRateEvaluator (*this));
59
+ }
60
+
61
+
62
+ void SettlementRateEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
63
+ const Teuchos::Ptr<CompositeVector>& result) {
64
+
65
+ const Epetra_MultiVector& vel = *S->GetFieldData(velocity_key_)->ViewComponent("cell");
66
+ const Epetra_MultiVector& tcc = *S->GetFieldData(sediment_key_)->ViewComponent("cell");
67
+ Epetra_MultiVector& result_c = *result->ViewComponent("cell");
68
+
69
+ for (int c=0; c<result_c.MyLength(); c++){
70
+ double tau_0 = gamma_ * lambda_ * (sqrt(vel[0][c] * vel[0][c] + vel[1][c] * vel[1][c]));
71
+
72
+ if (tau_0 < tau_d_){
73
+ result_c[0][c] = sediment_density_ * ws_ * std::min(tcc[0][c], 0.5) * (1 - tau_0 / tau_d_);
74
+ }else{
75
+ result_c[0][c] = 0.;
76
+ }
77
+
78
+ }
79
+
80
+ }
81
+
82
+ void SettlementRateEvaluator::EvaluateFieldPartialDerivative_ (const Teuchos::Ptr<State>& S,
83
+ Key wrt_key,
84
+ const Teuchos::Ptr<CompositeVector>& result) {
85
+ AMANZI_ASSERT(0);
86
+ }
87
+
88
+
89
+ } // namespace
pool/shard006/C++/0083809_hud_ammo.cpp ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //========= Copyright © 1996-2003, Valve LLC, All rights reserved. ============
2
+ //
3
+ // Purpose:
4
+ //
5
+ //=============================================================================
6
+
7
+ #include "cbase.h"
8
+ #include "hud.h"
9
+ #include "hudelement.h"
10
+ #include "hud_macros.h"
11
+ #include "parsemsg.h"
12
+ #include "hud_numericdisplay.h"
13
+ #include "iclientmode.h"
14
+
15
+ #include <vgui_controls/AnimationController.h>
16
+
17
+ //-----------------------------------------------------------------------------
18
+ // Purpose: Displays current ammunition level
19
+ //-----------------------------------------------------------------------------
20
+ class CHudAmmo : public CHudNumericDisplay, public CHudElement
21
+ {
22
+ DECLARE_CLASS_SIMPLE( CHudAmmo, CHudNumericDisplay );
23
+
24
+ public:
25
+ CHudAmmo( const char *pElementName );
26
+ void Init( void );
27
+ void VidInit( void );
28
+
29
+ void SetAmmo(int ammo, bool playAnimation);
30
+ void SetAmmo2(int ammo2, bool playAnimation);
31
+
32
+ protected:
33
+ virtual void OnThink();
34
+
35
+ private:
36
+ CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon;
37
+ int m_iAmmo;
38
+ int m_iAmmo2;
39
+ };
40
+
41
+ DECLARE_HUDELEMENT( CHudAmmo );
42
+
43
+ //-----------------------------------------------------------------------------
44
+ // Purpose: Constructor
45
+ //-----------------------------------------------------------------------------
46
+ CHudAmmo::CHudAmmo( const char *pElementName ) : BaseClass(NULL, "HudAmmo"), CHudElement( pElementName )
47
+ {
48
+ }
49
+
50
+ //-----------------------------------------------------------------------------
51
+ // Purpose:
52
+ //-----------------------------------------------------------------------------
53
+ void CHudAmmo::Init( void )
54
+ {
55
+ m_iAmmo = -1;
56
+ m_iAmmo2 = -1;
57
+
58
+ SetLabelText(L"AMMO");
59
+ }
60
+
61
+ //-----------------------------------------------------------------------------
62
+ // Purpose:
63
+ //-----------------------------------------------------------------------------
64
+ void CHudAmmo::VidInit( void )
65
+ {
66
+ }
67
+
68
+ //-----------------------------------------------------------------------------
69
+ // Purpose: called every frame to get ammo info from the weapon
70
+ //-----------------------------------------------------------------------------
71
+ void CHudAmmo::OnThink()
72
+ {
73
+ C_BaseCombatWeapon *wpn = GetActiveWeapon();
74
+ C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
75
+ if (!wpn || !player || !wpn->UsesPrimaryAmmo())
76
+ {
77
+ SetPaintEnabled(false);
78
+ SetPaintBackgroundEnabled(false);
79
+ return;
80
+ }
81
+ else
82
+ {
83
+ SetPaintEnabled(true);
84
+ SetPaintBackgroundEnabled(true);
85
+ }
86
+
87
+ // get the ammo in our clip
88
+ int ammo1 = wpn->Clip1();
89
+ int ammo2;
90
+ if (ammo1 < 0)
91
+ {
92
+ // we don't use clip ammo, just use the total ammo count
93
+ ammo1 = player->GetAmmoCount(wpn->GetPrimaryAmmoType());
94
+ ammo2 = 0;
95
+ }
96
+ else
97
+ {
98
+ // we use clip ammo, so the second ammo is the total ammo
99
+ ammo2 = player->GetAmmoCount(wpn->GetPrimaryAmmoType());
100
+ }
101
+
102
+ if (wpn == m_hCurrentActiveWeapon)
103
+ {
104
+ // same weapon, just update counts
105
+ SetAmmo(ammo1, true);
106
+ SetAmmo2(ammo2, true);
107
+ }
108
+ else
109
+ {
110
+ // diferent weapon, change without triggering
111
+ SetAmmo(ammo1, false);
112
+ SetAmmo2(ammo2, false);
113
+
114
+ // update whether or not we show the total ammo display
115
+ if (wpn->UsesClipsForAmmo1())
116
+ {
117
+ SetShouldDisplaySecondaryValue(true);
118
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponUsesClips");
119
+
120
+ }
121
+ else
122
+ {
123
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponDoesNotUseClips");
124
+ SetShouldDisplaySecondaryValue(false);
125
+ }
126
+
127
+ if ( GetGameRestored() )
128
+ {
129
+ SetGameRestored( false );
130
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChangedRestore");
131
+ }
132
+ else
133
+ {
134
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChanged");
135
+ }
136
+ m_hCurrentActiveWeapon = wpn;
137
+ }
138
+ }
139
+
140
+ //-----------------------------------------------------------------------------
141
+ // Purpose: Updates ammo display
142
+ //-----------------------------------------------------------------------------
143
+ void CHudAmmo::SetAmmo(int ammo, bool playAnimation)
144
+ {
145
+ if (ammo != m_iAmmo)
146
+ {
147
+ if (ammo == 0)
148
+ {
149
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoEmpty");
150
+ }
151
+ else if (ammo < m_iAmmo)
152
+ {
153
+ // ammo has decreased
154
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoDecreased");
155
+ }
156
+ else
157
+ {
158
+ // ammunition has increased
159
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoIncreased");
160
+ }
161
+
162
+ m_iAmmo = ammo;
163
+ }
164
+
165
+ SetDisplayValue(ammo);
166
+ }
167
+
168
+ //-----------------------------------------------------------------------------
169
+ // Purpose: Updates 2nd ammo display
170
+ //-----------------------------------------------------------------------------
171
+ void CHudAmmo::SetAmmo2(int ammo2, bool playAnimation)
172
+ {
173
+ if (ammo2 != m_iAmmo2)
174
+ {
175
+ if (ammo2 == 0)
176
+ {
177
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Empty");
178
+ }
179
+ else if (ammo2 < m_iAmmo2)
180
+ {
181
+ // ammo has decreased
182
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Decreased");
183
+ }
184
+ else
185
+ {
186
+ // ammunition has increased
187
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Increased");
188
+ }
189
+
190
+ m_iAmmo2 = ammo2;
191
+ }
192
+
193
+ SetSecondaryValue(ammo2);
194
+ }
195
+
196
+ //-----------------------------------------------------------------------------
197
+ // Purpose: Displays the secondary ammunition level
198
+ //-----------------------------------------------------------------------------
199
+ class CHudSecondaryAmmo : public CHudNumericDisplay, public CHudElement
200
+ {
201
+ DECLARE_CLASS_SIMPLE( CHudSecondaryAmmo, CHudNumericDisplay );
202
+
203
+ public:
204
+ CHudSecondaryAmmo( const char *pElementName ) : BaseClass( NULL, "HudAmmoSecondary" ), CHudElement( pElementName )
205
+ {
206
+ m_iAmmo = -1;
207
+ }
208
+
209
+ void Init( void )
210
+ {
211
+ }
212
+
213
+ void VidInit( void )
214
+ {
215
+ }
216
+
217
+ void SetAmmo( int ammo )
218
+ {
219
+ if (ammo != m_iAmmo)
220
+ {
221
+ if (ammo == 0)
222
+ {
223
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryEmpty");
224
+ }
225
+ else if (ammo < m_iAmmo)
226
+ {
227
+ // ammo has decreased
228
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryDecreased");
229
+ }
230
+ else
231
+ {
232
+ // ammunition has increased
233
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryIncreased");
234
+ }
235
+
236
+ m_iAmmo = ammo;
237
+ }
238
+ SetDisplayValue( ammo );
239
+ }
240
+
241
+ protected:
242
+ virtual void OnThink( void )
243
+ {
244
+ // set whether or not the panel draws based on if we have a weapon that supports secondary ammo
245
+ C_BaseCombatWeapon *wpn = GetActiveWeapon();
246
+ C_BasePlayer *player = C_BasePlayer::GetLocalPlayer();
247
+ if (!wpn || !player)
248
+ {
249
+ m_hCurrentActiveWeapon = NULL;
250
+ SetPaintEnabled(false);
251
+ SetPaintBackgroundEnabled(false);
252
+ return;
253
+ }
254
+ else
255
+ {
256
+ SetPaintEnabled(true);
257
+ SetPaintBackgroundEnabled(true);
258
+ }
259
+
260
+ if (wpn->UsesSecondaryAmmo())
261
+ {
262
+ SetAmmo(player->GetAmmoCount(wpn->GetSecondaryAmmoType()));
263
+ }
264
+
265
+ if ( m_hCurrentActiveWeapon != wpn )
266
+ {
267
+ bool restored = false;
268
+ if ( GetGameRestored() )
269
+ {
270
+ SetGameRestored( false );
271
+ restored = true;
272
+ }
273
+
274
+ if ( wpn->UsesSecondaryAmmo() )
275
+ {
276
+ // we've changed to a weapon that uses secondary ammo
277
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence(
278
+ restored ?
279
+ "WeaponUsesSecondaryAmmoRestore" :
280
+ "WeaponUsesSecondaryAmmo");
281
+ }
282
+ else
283
+ {
284
+ // we've changed away from a weapon that uses secondary ammo
285
+ g_pClientMode->GetViewportAnimationController()->StartAnimationSequence(
286
+ restored ?
287
+ "WeaponDoesNotUseSecondaryAmmoRestore" :
288
+ "WeaponDoesNotUseSecondaryAmmo" );
289
+ }
290
+ m_hCurrentActiveWeapon = wpn;
291
+ }
292
+ }
293
+
294
+ private:
295
+ CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon;
296
+ int m_iAmmo;
297
+ };
298
+
299
+ DECLARE_HUDELEMENT( CHudSecondaryAmmo );
300
+
pool/shard006/C++/0083818_DecoderPD.cpp ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * DecoderPD.cpp
3
+ * zxing
4
+ *
5
+ * Created by Hartmut Neubauer (hfn), 2012-05-25 (translated from Java source)
6
+ * Copyright 2010,2012 ZXing authors All rights reserved.
7
+ *
8
+ * Licensed under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License.
10
+ * You may obtain a copy of the License at
11
+ *
12
+ * http://www.apache.org/licenses/LICENSE-2.0
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ *
20
+ * 2012-06-27 hfn: PDF417 Reed-Solomon error correction, using following Java
21
+ * source code:
22
+ * http://code.google.com/p/zxing/issues/attachmentText?id=817&aid=8170033000&name=pdf417-java-reed-solomon-error-correction-2.patch&token=0819f5d7446ae2814fd91385eeec6a11
23
+ */
24
+
25
+ #include <zxing/pdf417/decoder/Decoder.h>
26
+ #include <zxing/pdf417/decoder/BitMatrixParser.h>
27
+ #include <zxing/pdf417/decoder/DecodedBitStreamParser.h>
28
+ #include <zxing/pdf417/decoder/PDF417RSDecoder.h>
29
+ #include <zxing/ReaderException.h>
30
+ #include <zxing/common/reedsolomon/ReedSolomonException.h>
31
+
32
+
33
+ namespace zxing {
34
+ namespace pdf417 {
35
+
36
+ using namespace std;
37
+
38
+ Decoder::Decoder()
39
+ {
40
+ }
41
+
42
+ const int Decoder::MAX_ERRORS = 3; /* 3; / 8? */
43
+ const int Decoder::MAX_EC_CODEWORDS = 512;
44
+
45
+ Ref<DecoderResult> Decoder::decode(Ref<BitMatrix> bits) {
46
+ // Construct a parser to read the data codewords and error-correction level
47
+ BitMatrixParser parser(bits);
48
+ size_t cwsize;
49
+ ArrayRef<int> codewords(parser.readCodewords());
50
+ cwsize = codewords.size();
51
+ if (cwsize == 0) {
52
+ throw FormatException("PDF:Decoder:decode: cannot read codewords");
53
+ }
54
+
55
+ int ecLevel = parser.getECLevel();
56
+ int numECCodewords = 1 << (ecLevel + 1);
57
+ ArrayRef<int> erasures = parser.getErasures();
58
+
59
+ correctErrors(codewords, erasures, numECCodewords);
60
+ verifyCodewordCount(codewords, numECCodewords);
61
+
62
+ // Decode the codewords
63
+ return DecodedBitStreamParser::decode(codewords);
64
+ }
65
+
66
+ /**
67
+ * Verify that all is OK with the codeword array.
68
+ *
69
+ * @param codewords
70
+ * @return an index to the first data codeword.
71
+ * @throws FormatException
72
+ */
73
+ void Decoder::verifyCodewordCount(ArrayRef<int> codewords, int numECCodewords)
74
+ {
75
+ int cwsize = codewords.size();
76
+ if (cwsize < 4) {
77
+ // Codeword array size should be at least 4 allowing for
78
+ // Count CW, At least one Data CW, Error Correction CW, Error Correction CW
79
+ throw FormatException("PDF:Decoder:verifyCodewordCount: codeword array too small!");
80
+ }
81
+ // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
82
+ // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
83
+ // codewords, but excluding the number of error correction codewords.
84
+ int numberOfCodewords = codewords[0];
85
+ if (numberOfCodewords > cwsize) {
86
+ throw FormatException("PDF:Decoder:verifyCodewordCount: bad codeword number descriptor!");
87
+ }
88
+ if (numberOfCodewords == 0) {
89
+ // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
90
+ if (numECCodewords < cwsize) {
91
+ codewords[0] = cwsize - numECCodewords;
92
+ } else {
93
+ throw FormatException("PDF:Decoder:verifyCodewordCount: bad error correction cw number!");
94
+ }
95
+ }
96
+ }
97
+
98
+ int Decoder::correctErrors(ArrayRef<int> codewords,
99
+ ArrayRef<int> erasures, int numECCodewords) {
100
+ #if (defined _WIN32 && defined(DEBUG))
101
+ {
102
+ WCHAR sz[256];
103
+ wsprintf(sz,L"Decoder::correctErrors: erasures.size=%d, numECCodewords=%d\n",erasures.size(),numECCodewords);
104
+ OutputDebugString(sz);
105
+ }
106
+ #endif
107
+ int numErasures = erasures.size();
108
+ if (numErasures > numECCodewords - 3
109
+ || numECCodewords < 0 || numECCodewords > MAX_EC_CODEWORDS) {
110
+ // Too many errors or EC Codewords is corrupted
111
+ throw FormatException("PDF:Decoder:correctErrors: Too many errors or EC Codewords corrupted");
112
+ }
113
+ // Try to correct the errors
114
+ // Use class PDF417RSDecoder for Reed-Solomon error correction
115
+ Ref<PDF417RSDecoder> rsDecoder(new PDF417RSDecoder);
116
+ int synd_len = codewords.size() - codewords[0];
117
+ int numCorrections = rsDecoder->correctErrors(codewords,
118
+ erasures, /* hint: "erasures" are ignored when num_eras=0! */
119
+ 0, // erasures.size(),
120
+ codewords.size(),synd_len);
121
+ if(numCorrections < 0)
122
+ {
123
+ // Still too many errors
124
+ throw FormatException("PDF:Decoder:correctErrors: Error correction not possible!");
125
+ }
126
+
127
+ //* 2012-06-27 HFN if, despite of error correction, there are still codewords with invalid
128
+ //* value, throw an exception here:
129
+ int i;
130
+ for(i=0;i<(int)codewords.size();i++) {
131
+ if(codewords[i]<0) {
132
+ throw FormatException("PDF:Decoder:correctErrors: Error correction did not succeed!");
133
+ }
134
+ }
135
+
136
+ return numCorrections;
137
+ }
138
+
139
+ } /* namespace pdf417 */
140
+ } /* namespace zxing */
pool/shard006/C++/0083820_test_polyhedron_io.cpp ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ //
3
+ // Copyright (c) 1997 The CGAL Consortium
4
+ //
5
+ // This software and related documentation is part of an INTERNAL release
6
+ // of the Computational Geometry Algorithms Library (CGAL). It is not
7
+ // intended for general use.
8
+ //
9
+ // ----------------------------------------------------------------------------
10
+ //
11
+ // release : $CGAL_Revision: $
12
+ // release_date : $CGAL_Date: $
13
+ //
14
+ // file : test_polyhedron_io.C
15
+ // chapter : $CGAL_Chapter: Support Library ... $
16
+ // package : $CGAL_Package: Polyhedron_IO 2.11 (04 Feb 2000) $
17
+ // source : polyhedron_io.fw
18
+ // revision : $Id$
19
+ // revision_date : $Date$
20
+ // author(s) : Lutz Kettner <kettner@inf.ethz.ch>
21
+ //
22
+ // coordinator : Herve Bronnimann <Herve.Bronnimann@sophia.inria.fr>
23
+ //
24
+ // Polyhedral Surface File IO: Scanner and Writer
25
+ // ============================================================================
26
+
27
+
28
+ #include <CGAL/Cartesian.h>
29
+ #include <CGAL/Polyhedron_3.h>
30
+
31
+ // This is the test file for the new design. Skip new design test for
32
+ // disabled compilers.
33
+ #ifndef CGAL_USE_POLYHEDRON_DESIGN_ONE
34
+
35
+ #include <CGAL/IO/Polyhedron_iostream.h>
36
+ #include <CGAL/IO/print_OFF.h>
37
+ #include <CGAL/IO/print_wavefront.h>
38
+ #include <CGAL/IO/print_inventor.h>
39
+ #include <CGAL/IO/print_VRML_1.h>
40
+ #include <CGAL/IO/print_VRML_2.h>
41
+
42
+ #include <cstddef>
43
+ #include <iostream>
44
+ #include <fstream>
45
+ #include <sstream>
46
+ #include <cstring>
47
+ #include <cassert>
48
+
49
+ using namespace CGAL;
50
+
51
+ const char* triangle = "OFF\n"
52
+ "3 1 0\n"
53
+ "0 0 0\n"
54
+ "1 0 0\n"
55
+ "0 1 0\n"
56
+ "3 0 1 2\n";
57
+ const char* tetra = "OFF\n"
58
+ "4 4 0\n"
59
+ "0 0 0.707107\n"
60
+ "1 1 0.707107\n"
61
+ "0 1 0\n"
62
+ "1 0 0\n"
63
+ "3 1 3 0\n"
64
+ "3 2 1 0\n"
65
+ "3 3 2 0\n"
66
+ "3 2 3 1\n";
67
+
68
+
69
+ void test_file_IO_OFF() {
70
+ typedef Cartesian<double> Kernel;
71
+ typedef Polyhedron_3<Kernel> Polyhedron;
72
+ {
73
+ Polyhedron P;
74
+ std::istringstream in( triangle);
75
+ in >> P; /* 'in' is the stream where the object is read from. */
76
+ assert(! in.fail());
77
+ assert( P.is_triangle( P.halfedges_begin()));
78
+ std::stringstream stream;
79
+ stream << P << '\0';
80
+ P = Polyhedron();
81
+ scan_OFF( stream, P, true);
82
+ assert( ! ! stream); // ! ! to fool VC7 CL1310
83
+ assert( P.is_triangle( P.halfedges_begin()));
84
+
85
+ std::stringstream stream_new;
86
+ print_polyhedron_OFF( stream_new, P, true);
87
+ stream_new << '\0';
88
+ P = Polyhedron();
89
+ stream_new >> P;
90
+ assert( ! ! stream_new); // ! ! to fool VC7 CL1310
91
+ assert( P.is_triangle( P.halfedges_begin()));
92
+ {
93
+ std::ofstream out2( "triangle_binary.off");
94
+ print_polyhedron_OFF( out2, P, true);
95
+ }
96
+ std::ifstream filein( "triangle_binary.off");
97
+ P = Polyhedron();
98
+ filein >> P;
99
+ assert(! filein.fail());
100
+ assert( P.is_triangle( P.halfedges_begin()));
101
+ }{
102
+ Polyhedron P;
103
+ std::istringstream in( tetra);
104
+ in >> P; /* 'in' is the stream where the object is read from. */
105
+ assert( P.is_tetrahedron( P.halfedges_begin()));
106
+ std::stringstream stream;
107
+ stream << P << '\0';
108
+ P = Polyhedron();
109
+ stream >> P;
110
+ assert( P.is_tetrahedron( P.halfedges_begin()));
111
+ {
112
+ std::ofstream out2( "tetra_binary.off");
113
+ print_polyhedron_OFF( out2, P, true);
114
+ }
115
+ std::ifstream filein( "tetra_binary.off");
116
+ P = Polyhedron();
117
+ filein >> P;
118
+ assert( P.is_tetrahedron( P.halfedges_begin()));
119
+ }
120
+ }
121
+ void test_file_IO_wavefront() {}
122
+ void test_file_IO_inventor() {}
123
+ void test_file_IO_VRML_2() {}
124
+
125
+ #endif // CGAL_USE_POLYHEDRON_DESIGN_ONE //
126
+
127
+ int main(){
128
+ // This is the test file for the new design. Skip new design test for
129
+ // disabled compilers.
130
+ #ifndef CGAL_USE_POLYHEDRON_DESIGN_ONE
131
+ test_file_IO_OFF();
132
+ test_file_IO_wavefront();
133
+ test_file_IO_inventor();
134
+ test_file_IO_VRML_2();
135
+ #endif // CGAL_USE_POLYHEDRON_DESIGN_ONE //
136
+ return 0;
137
+ }
138
+ // EOF //
pool/shard006/C++/0083822_PlatformCanvas.cpp ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2011 Google Inc. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions
6
+ * are met:
7
+ *
8
+ * 1. Redistributions of source code must retain the above copyright
9
+ * notice, this list of conditions and the following disclaimer.
10
+ * 2. Redistributions in binary form must reproduce the above copyright
11
+ * notice, this list of conditions and the following disclaimer in the
12
+ * documentation and/or other materials provided with the distribution.
13
+ *
14
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
+ */
25
+
26
+ #include "config.h"
27
+
28
+ #include "PlatformCanvas.h"
29
+
30
+ #include "GraphicsContext.h"
31
+
32
+ #include "NativeImageSkia.h"
33
+ #include "PlatformContextSkia.h"
34
+ #include "SkColorPriv.h"
35
+ #include "skia/ext/platform_canvas.h"
36
+
37
+ namespace WebCore {
38
+
39
+ PlatformCanvas::PlatformCanvas()
40
+ : m_opaque(false)
41
+ {
42
+ }
43
+
44
+ PlatformCanvas::~PlatformCanvas()
45
+ {
46
+ }
47
+
48
+ void PlatformCanvas::resize(const IntSize& size)
49
+ {
50
+ if (m_size == size)
51
+ return;
52
+ m_size = size;
53
+ createBackingCanvas();
54
+ }
55
+
56
+ void PlatformCanvas::setOpaque(bool opaque)
57
+ {
58
+ if (opaque == m_opaque)
59
+ return;
60
+
61
+ m_opaque = opaque;
62
+ createBackingCanvas();
63
+ }
64
+
65
+ void PlatformCanvas::createBackingCanvas()
66
+ {
67
+ if (m_size.isEmpty())
68
+ return;
69
+
70
+ m_skiaCanvas = adoptPtr(skia::CreateBitmapCanvas(m_size.width(), m_size.height(), m_opaque));
71
+ }
72
+
73
+ PlatformCanvas::AutoLocker::AutoLocker(PlatformCanvas* canvas)
74
+ : m_canvas(canvas)
75
+ {
76
+ if (m_canvas->m_skiaCanvas) {
77
+ m_bitmap = &m_canvas->m_skiaCanvas->getDevice()->accessBitmap(false);
78
+ m_bitmap->lockPixels();
79
+ } else
80
+ m_bitmap = 0;
81
+ }
82
+
83
+ PlatformCanvas::AutoLocker::~AutoLocker()
84
+ {
85
+ if (m_bitmap)
86
+ m_bitmap->unlockPixels();
87
+ }
88
+
89
+ const uint8_t* PlatformCanvas::AutoLocker::pixels() const
90
+ {
91
+ if (m_bitmap && m_bitmap->config() == SkBitmap::kARGB_8888_Config)
92
+ return static_cast<const uint8_t*>(m_bitmap->getPixels());
93
+ return 0;
94
+ }
95
+
96
+ PlatformCanvas::Painter::Painter(PlatformCanvas* canvas, PlatformCanvas::Painter::TextOption option)
97
+ {
98
+ m_skiaContext = adoptPtr(new PlatformContextSkia(canvas->m_skiaCanvas.get()));
99
+
100
+ m_skiaContext->setDrawingToImageBuffer(option == GrayscaleText);
101
+
102
+ m_context = adoptPtr(new GraphicsContext(reinterpret_cast<PlatformGraphicsContext*>(m_skiaContext.get())));
103
+ context()->save();
104
+ }
105
+
106
+ PlatformCanvas::Painter::~Painter()
107
+ {
108
+ context()->restore();
109
+ }
110
+
111
+ } // namespace WebCore
pool/shard006/C++/0083825_MapWindowTraffic.cpp ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright_License {
3
+
4
+ XCSoar Glide Computer - http://www.xcsoar.org/
5
+ Copyright (C) 2000-2012 The XCSoar Project
6
+ A detailed list of copyright holders can be found in the file "AUTHORS".
7
+
8
+ This program is free software; you can redistribute it and/or
9
+ modify it under the terms of the GNU General Public License
10
+ as published by the Free Software Foundation; either version 2
11
+ of the License, or (at your option) any later version.
12
+
13
+ This program 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 this program; if not, write to the Free Software
20
+ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
+ }
22
+ */
23
+
24
+ #include "MapWindow.hpp"
25
+ #include "Math/Screen.hpp"
26
+ #include "Math/Earth.hpp"
27
+ #include "Screen/Icon.hpp"
28
+ #include "Screen/Fonts.hpp"
29
+ #include "Screen/Layout.hpp"
30
+ #include "Screen/TextInBox.hpp"
31
+ #include "Util/StringUtil.hpp"
32
+ #include "GlideSolvers/GlidePolar.hpp"
33
+ #include "Formatter/UserUnits.hpp"
34
+ #include "Look/TrafficLook.hpp"
35
+ #include "Renderer/TrafficRenderer.hpp"
36
+
37
+ #include <stdio.h>
38
+
39
+ /**
40
+ * Draws the FLARM traffic icons onto the given canvas
41
+ * @param canvas Canvas for drawing
42
+ */
43
+ void
44
+ MapWindow::DrawFLARMTraffic(Canvas &canvas,
45
+ const RasterPoint aircraft_pos) const
46
+ {
47
+ // Return if FLARM icons on moving map are disabled
48
+ if (!GetMapSettings().show_flarm_on_map)
49
+ return;
50
+
51
+ // Return if FLARM data is not available
52
+ const FlarmState &flarm = Basic().flarm;
53
+ if (!flarm.available)
54
+ return;
55
+
56
+ const WindowProjection &projection = render_projection;
57
+
58
+ // if zoomed in too far out, dont draw traffic since it will be too close to
59
+ // the glider and so will be meaningless (serves only to clutter, cant help
60
+ // the pilot)
61
+ if (projection.GetMapScale() > fixed_int_constant(7300))
62
+ return;
63
+
64
+ // Circle through the FLARM targets
65
+ for (auto it = flarm.traffic.begin(), end = flarm.traffic.end();
66
+ it != end; ++it) {
67
+ const FlarmTraffic &traffic = *it;
68
+
69
+ if (!traffic.location_available)
70
+ continue;
71
+
72
+ // Save the location of the FLARM target
73
+ GeoPoint target_loc = traffic.location;
74
+
75
+ // Points for the screen coordinates for the icon, name and average climb
76
+ RasterPoint sc, sc_name, sc_av;
77
+
78
+ // If FLARM target not on the screen, move to the next one
79
+ if (!projection.GeoToScreenIfVisible(target_loc, sc))
80
+ continue;
81
+
82
+ // Draw the name 16 points below the icon
83
+ sc_name = sc;
84
+ sc_name.y -= Layout::Scale(20);
85
+
86
+ // Draw the average climb value above the icon
87
+ sc_av = sc;
88
+ sc_av.y += Layout::Scale(5);
89
+
90
+ TextInBoxMode mode;
91
+ mode.mode = RM_OUTLINED;
92
+
93
+ // JMW TODO enhancement: decluttering of FLARM altitudes (sort by max lift)
94
+
95
+ int dx = sc_av.x - aircraft_pos.x;
96
+ int dy = sc_av.y - aircraft_pos.y;
97
+
98
+ // only draw labels if not close to aircraft
99
+ if (dx * dx + dy * dy > Layout::Scale(30 * 30)) {
100
+ // If FLARM callsign/name available draw it to the canvas
101
+ if (traffic.HasName() && !StringIsEmpty(traffic.name))
102
+ TextInBox(canvas, traffic.name, sc_name.x, sc_name.y,
103
+ mode, GetClientRect());
104
+
105
+ if (traffic.climb_rate_avg30s >= fixed(0.1)) {
106
+ // If average climb data available draw it to the canvas
107
+ TCHAR label_avg[100];
108
+ FormatUserVerticalSpeed(traffic.climb_rate_avg30s,
109
+ label_avg, false);
110
+ TextInBox(canvas, label_avg, sc_av.x, sc_av.y, mode, GetClientRect());
111
+ }
112
+ }
113
+
114
+ TrafficRenderer::Draw(canvas, traffic_look, traffic,
115
+ traffic.track - projection.GetScreenAngle(), sc);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Draws the teammate icon to the given canvas
121
+ * @param canvas Canvas for drawing
122
+ */
123
+ void
124
+ MapWindow::DrawTeammate(Canvas &canvas) const
125
+ {
126
+ const TeamInfo &teamcode_info = Calculated();
127
+
128
+ if (teamcode_info.teammate_available) {
129
+ RasterPoint sc;
130
+ if (render_projection.GeoToScreenIfVisible(teamcode_info.teammate_location,
131
+ sc))
132
+ traffic_look.teammate_icon.Draw(canvas, sc);
133
+ }
134
+ }
pool/shard006/C++/0083827_FontGenerator.cpp ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //#define _DEBUG_GENERATE_TGA_FILES_
2
+
3
+ #include "FontGenerator.h"
4
+ #include <pragma/image/Fonts/Font.h>
5
+ #include <pragma/types.h>
6
+ #include <ft2build.h>
7
+ #include FT_FREETYPE_H
8
+
9
+ #ifdef _DEBUG_GENERATE_TGA_FILES_
10
+ # include <pragma/image/functions.h>
11
+ #endif
12
+
13
+ static bool sFreeType_Initialized = false;
14
+ static FT_Library sLibrary;
15
+
16
+ namespace pragma
17
+ {
18
+
19
+ static void ExtractGlyph(Font::Glyph& aGlyph, FT_Face aFace, uint32 aCharCode)
20
+ {
21
+ FT_UInt lGlyphIndex = FT_Get_Char_Index( aFace, aCharCode );
22
+ FT_Load_Glyph(aFace, lGlyphIndex, 0);
23
+ FT_Render_Glyph(aFace->glyph, FT_RENDER_MODE_NORMAL);
24
+
25
+ aGlyph.mCode = aCharCode;
26
+ aGlyph.mBitmap = aFace->glyph->bitmap.buffer;
27
+ aGlyph.mWidth = aFace->glyph->bitmap.width;
28
+ aGlyph.mHeight = aFace->glyph->bitmap.rows;
29
+ aGlyph.mStartX = aFace->glyph->bitmap_left;
30
+ aGlyph.mStartY = aFace->glyph->bitmap_top;
31
+ aGlyph.mAdvanceX = aFace->glyph->advance.x;
32
+
33
+ #ifdef _DEBUG_GENERATE_TGA_FILES_
34
+ char lNane[10];
35
+ sprintf(lNane, "glyph%d.tga", aCharCode);
36
+ pragma::ExportToTGA( aGlyph.mBitmap
37
+ , aGlyph.mWidth
38
+ , aGlyph.mHeight
39
+ , lNane );
40
+ #endif
41
+ }
42
+
43
+ /**
44
+ * CreateFont_FreeType
45
+ */
46
+ void CreateFont_FreeType( const char* aFontFile, size_t aSize, uint32* aRanges, Font& aFont )
47
+ {
48
+ int error;
49
+ // Initialize FreeType library, if needed
50
+ if(!sFreeType_Initialized)
51
+ {
52
+ error = FT_Init_FreeType( &sLibrary );
53
+ if(error)
54
+ {
55
+ printf( "CreateFont_FreeType: Error initializing FreeType library\n");
56
+ return;
57
+ }
58
+ sFreeType_Initialized = true;
59
+ }
60
+
61
+ // Initialize font face
62
+ FT_Face lFace;
63
+ error = FT_New_Face( sLibrary, aFontFile, 0, &lFace );
64
+
65
+ if(error)
66
+ {
67
+ printf( "Error opening font\n");
68
+ return;
69
+ }
70
+
71
+ // Set Font size
72
+ FT_Set_Char_Size ( lFace, 0, aSize << 6, 300, 300 );
73
+ FT_Set_Pixel_Sizes( lFace, 0, aSize );
74
+
75
+ aFont.Init(aSize);
76
+
77
+ if(aRanges == 0)
78
+ { // Extract all glyphs
79
+ FT_UInt lIndex;
80
+ FT_ULong lCharCode = FT_Get_First_Char(lFace, &lIndex);
81
+ for(size_t i = 0; i < lFace->num_glyphs; ++i)
82
+ {
83
+ Font::Glyph lGlyph;
84
+ ExtractGlyph(lGlyph, lFace, lCharCode);
85
+ aFont.AddGlyph(lGlyph);
86
+ lCharCode = FT_Get_Next_Char(lFace, lCharCode, &lIndex);
87
+ }
88
+ }
89
+ else
90
+ { // Extract only a range of glyphs
91
+ while(aRanges[0] <= aRanges[1])
92
+ {
93
+ for(uint32 i = aRanges[0]; i <= aRanges[1]; ++i)
94
+ {
95
+ Font::Glyph lGlyph;
96
+ ExtractGlyph(lGlyph, lFace, i);
97
+ aFont.AddGlyph(lGlyph);
98
+ }
99
+ aRanges+=2;
100
+ }
101
+ }
102
+
103
+ }
104
+
105
+ /**
106
+ * CreateFont_FreeType
107
+ */
108
+ void CreateFont_FreeType( const char* aFontFile, size_t aSize, Font& aFont )
109
+ {
110
+ CreateFont_FreeType( aFontFile, aSize, 0, aFont);
111
+ }
112
+ }
pool/shard006/C++/0083833_shape.cc ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "shape.h"
2
+
3
+ #include "Contours.h"
4
+ #include "../common/Point.h"
5
+
6
+ namespace ncv {
7
+
8
+ namespace imgproc {
9
+
10
+ void ShapeInit(Local<Object> &target) {
11
+ // connected components algorithms types
12
+ DEFINE_CONST_ENUM(CCL_WU);
13
+ DEFINE_CONST_ENUM(CCL_DEFAULT);
14
+ DEFINE_CONST_ENUM(CCL_GRANA);
15
+
16
+ // connected components types
17
+ DEFINE_CONST_ENUM(CC_STAT_LEFT);
18
+ DEFINE_CONST_ENUM(CC_STAT_TOP);
19
+ DEFINE_CONST_ENUM(CC_STAT_WIDTH);
20
+ DEFINE_CONST_ENUM(CC_STAT_HEIGHT);
21
+ DEFINE_CONST_ENUM(CC_STAT_AREA);
22
+ DEFINE_CONST_ENUM(CC_STAT_MAX);
23
+
24
+ // contour approximation modes
25
+ DEFINE_CONST_ENUM(CHAIN_APPROX_NONE);
26
+ DEFINE_CONST_ENUM(CHAIN_APPROX_SIMPLE);
27
+ DEFINE_CONST_ENUM(CHAIN_APPROX_TC89_L1);
28
+ DEFINE_CONST_ENUM(CHAIN_APPROX_TC89_KCOS);
29
+
30
+ // rectangles intersect types
31
+ DEFINE_CONST_ENUM(INTERSECT_NONE);
32
+ DEFINE_CONST_ENUM(INTERSECT_PARTIAL);
33
+ DEFINE_CONST_ENUM(INTERSECT_FULL);
34
+
35
+ // retrieval modes
36
+ DEFINE_CONST_ENUM(RETR_EXTERNAL);
37
+ DEFINE_CONST_ENUM(RETR_LIST);
38
+ DEFINE_CONST_ENUM(RETR_CCOMP);
39
+ DEFINE_CONST_ENUM(RETR_TREE);
40
+ DEFINE_CONST_ENUM(RETR_FLOODFILL);
41
+
42
+ // shape match modes
43
+ DEFINE_CONST_ENUM(CONTOURS_MATCH_I1);
44
+ DEFINE_CONST_ENUM(CONTOURS_MATCH_I2);
45
+ DEFINE_CONST_ENUM(CONTOURS_MATCH_I3);
46
+
47
+ Nan::SetMethod(target, "approxPolyDP", ApproxPolyDP);
48
+ Nan::SetMethod(target, "arcLength", ArcLength);
49
+ Nan::SetMethod(target, "boundingRect", BoundingRect);
50
+ Nan::SetMethod(target, "boxPoints", BoxPoints);
51
+ Nan::SetMethod(target, "connectedComponents", ConnectedComponents);
52
+ Nan::SetMethod(target, "connectedComponentsWithStats", ConnectedComponentsWithStats);
53
+ Nan::SetMethod(target, "contourArea", ContourArea);
54
+ Nan::SetMethod(target, "convexHull", ConvexHull);
55
+ Nan::SetMethod(target, "convexityDefects", ConvexityDefects);
56
+ Nan::SetMethod(target, "findContours", FindContours);
57
+ Nan::SetMethod(target, "fitEllipse", FitEllipse);
58
+ Nan::SetMethod(target, "fitLine", FitLine);
59
+ Nan::SetMethod(target, "huMoments", HuMoments);
60
+ Nan::SetMethod(target, "intersectConvexConvex", IntersectConvexConvex);
61
+ Nan::SetMethod(target, "isContourConvex", IsContourConvex);
62
+ Nan::SetMethod(target, "matchShapes", MatchShapes);
63
+ Nan::SetMethod(target, "minAreaRect", MinAreaRect);
64
+ Nan::SetMethod(target, "minEnclosingCircle", MinEnclosingCircle);
65
+ Nan::SetMethod(target, "minEnclosingTriangle", MinEnclosingTriangle);
66
+ Nan::SetMethod(target, "moments", Moments);
67
+ Nan::SetMethod(target, "pointPolygonTest", PointPolygonTest);
68
+ Nan::SetMethod(target, "rotatedRectangleIntersection", RotatedRectangleIntersection);
69
+ }
70
+
71
+ NAN_METHOD(ApproxPolyDP) {
72
+ NotImplemented
73
+ }
74
+
75
+ NAN_METHOD(ArcLength) {
76
+ NotImplemented
77
+ }
78
+
79
+ NAN_METHOD(BoundingRect) {
80
+ NotImplemented
81
+ }
82
+
83
+ NAN_METHOD(BoxPoints) {
84
+ NotImplemented
85
+ }
86
+
87
+ NAN_METHOD(ConnectedComponents) {
88
+ NotImplemented
89
+ }
90
+
91
+ NAN_METHOD(ConnectedComponentsWithStats) {
92
+ NotImplemented
93
+ }
94
+
95
+ NAN_METHOD(ContourArea) {
96
+ NotImplemented
97
+ }
98
+
99
+ NAN_METHOD(ConvexHull) {
100
+ NotImplemented
101
+ }
102
+
103
+ NAN_METHOD(ConvexityDefects) {
104
+ NotImplemented
105
+ }
106
+
107
+ NAN_METHOD(FindContours) {
108
+ FUNCTION_REQUIRE_ARGUMENTS_RANGE(3, 4);
109
+ Nan::HandleScope scope;
110
+ ASSERT_INPUTOUTPUTARRAY_FROM_ARGS(image, 0);
111
+ ASSERT_INT_FROM_ARGS(mode, 1);
112
+ ASSERT_INT_FROM_ARGS(method, 2);
113
+ DEFAULT_POINT_FROM_ARGS(offset, 2, cv::Point());
114
+
115
+ Local<Object> out = Contours::NewInstance();
116
+ Contours* contours = UNWRAP_OBJECT(Contours, out);
117
+ TRY_CATCH_THROW_OPENCV(cv::findContours(image, contours->contours, contours->hierarchy, mode, method, offset));
118
+
119
+ info.GetReturnValue().Set(out);
120
+ }
121
+
122
+ NAN_METHOD(FitEllipse) {
123
+ NotImplemented
124
+ }
125
+
126
+ NAN_METHOD(FitLine) {
127
+ NotImplemented
128
+ }
129
+
130
+ NAN_METHOD(HuMoments) {
131
+ NotImplemented
132
+ }
133
+
134
+ NAN_METHOD(IntersectConvexConvex) {
135
+ NotImplemented
136
+ }
137
+
138
+ NAN_METHOD(IsContourConvex) {
139
+ NotImplemented
140
+ }
141
+
142
+ NAN_METHOD(MatchShapes) {
143
+ FUNCTION_REQUIRE_ARGUMENTS(4);
144
+ ASSERT_INPUTARRAY_FROM_ARGS(contour1, 0);
145
+ ASSERT_INPUTARRAY_FROM_ARGS(contour2, 1);
146
+ ASSERT_INT_FROM_ARGS(method, 2);
147
+ ASSERT_DOUBLE_FROM_ARGS(parameter, 3);
148
+ TRY_CATCH_THROW_OPENCV(info.GetReturnValue().Set(Nan::New<Number>(cv::matchShapes(contour1, contour2, method, parameter))));
149
+ }
150
+
151
+ NAN_METHOD(MinAreaRect) {
152
+ NotImplemented
153
+ }
154
+
155
+ NAN_METHOD(MinEnclosingCircle) {
156
+ NotImplemented
157
+ }
158
+
159
+ NAN_METHOD(MinEnclosingTriangle) {
160
+ NotImplemented
161
+ }
162
+
163
+ NAN_METHOD(Moments) {
164
+ NotImplemented
165
+ }
166
+
167
+ NAN_METHOD(PointPolygonTest) {
168
+ NotImplemented
169
+ }
170
+
171
+ NAN_METHOD(RotatedRectangleIntersection) {
172
+ NotImplemented
173
+ }
174
+
175
+ }
176
+
177
+ }
pool/shard006/C++/0083835_mat_mul.cpp ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* $Id$ */
2
+ /* --------------------------------------------------------------------------
3
+ CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell
4
+
5
+ CppAD is distributed under multiple licenses. This distribution is under
6
+ the terms of the
7
+ Eclipse Public License Version 1.0.
8
+
9
+ A copy of this license is included in the COPYING file of this distribution.
10
+ Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
11
+ -------------------------------------------------------------------------- */
12
+ /*
13
+ $begin fadbad_mat_mul.cpp$$
14
+ $spell
15
+ badiff
16
+ sq
17
+ retape
18
+ typedef
19
+ diff
20
+ Fadbad
21
+ Adolc
22
+ cppad.hpp
23
+ bool
24
+ mul
25
+ dz
26
+ CppAD
27
+ $$
28
+
29
+ $section Fadbad Speed: Matrix Multiplication$$
30
+
31
+ $index link_mat_mul, fadbad$$
32
+ $index fadbad, link_mat_mul$$
33
+ $index speed, fadbad$$
34
+ $index fadbad, speed$$
35
+ $index matrix, speed fadbad$$
36
+ $index multiply, speed fadbad$$
37
+
38
+ $head Specifications$$
39
+ See $cref link_mat_mul$$.
40
+
41
+ $head Implementation$$
42
+
43
+ $codep */
44
+ # include <FADBAD++/badiff.h>
45
+ # include <cppad/speed/mat_sum_sq.hpp>
46
+ # include <cppad/speed/uniform_01.hpp>
47
+ # include <cppad/vector.hpp>
48
+ bool link_mat_mul(
49
+ size_t size ,
50
+ size_t repeat ,
51
+ CppAD::vector<double>& x ,
52
+ CppAD::vector<double>& z ,
53
+ CppAD::vector<double>& dz )
54
+ {
55
+ // speed test global option values
56
+ extern bool global_retape, global_atomic, global_optimize;
57
+ if( ! global_retape || global_atomic || global_optimize )
58
+ return false;
59
+
60
+ // The correctness check for this test is failing, so abort (for now).
61
+ return false;
62
+
63
+ // -----------------------------------------------------
64
+ // setup
65
+
66
+ // object for computing determinant
67
+ typedef fadbad::B<double> ADScalar;
68
+ typedef CppAD::vector<ADScalar> ADVector;
69
+
70
+ size_t j; // temporary index
71
+ size_t m = 1; // number of dependent variables
72
+ size_t n = size * size; // number of independent variables
73
+ ADVector X(n); // AD domain space vector
74
+ ADVector Y(n); // Store product matrix
75
+ ADVector Z(m); // AD range space vector
76
+
77
+ // ------------------------------------------------------
78
+ while(repeat--)
79
+ { // get the next matrix
80
+ CppAD::uniform_01(n, x);
81
+
82
+ // set independent variable values
83
+ for(j = 0; j < n; j++)
84
+ X[j] = x[j];
85
+
86
+ // do the computation
87
+ mat_sum_sq(size, X, Y, Z);
88
+
89
+ // create function object f : X -> Z
90
+ Z[0].diff(0, m); // index 0 of m dependent variables
91
+
92
+ // evaluate and return gradient using reverse mode
93
+ for(j = 0; j < n; j++)
94
+ dz[j] = X[j].d(0); // partial Z[0] w.r.t X[j]
95
+ }
96
+ // return function value
97
+ z[0] = Z[0].x();
98
+
99
+ // ---------------------------------------------------------
100
+ return true;
101
+ }
102
+ /* $$
103
+ $end
104
+ */
pool/shard006/C++/0083836_core_types.cpp ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "core_types.h"
2
+ #include "error_macros.h"
3
+
4
+ #include <QVariant>
5
+ #include <QDebug>
6
+
7
+ bool Interval::isInTimePeriod(qint64 start, qint64 end) const
8
+ {
9
+ return ((start >= startTime && end <= endTime)
10
+ ||
11
+ (start >= startTime && end >= startTime && endTime >= start)
12
+ ||
13
+ (start <= startTime && end >= startTime));
14
+ }
15
+
16
+ void Activity::updateStartAndEndTime()
17
+ {
18
+ qint64 min = INT64_MAX, max = INT64_MIN;
19
+ if (intervals.count() == 0) return;
20
+
21
+ for (const Interval & interval : intervals)
22
+ {
23
+ if (interval.startTime < min) min = interval.startTime;
24
+ if (interval.endTime > max) max = interval.endTime;
25
+ }
26
+
27
+ startTime = min;
28
+ endTime = max;
29
+ }
30
+
31
+ bool Activity::belongsToTimePeriod(qint64 startTime, qint64 endTime) const
32
+ {
33
+ if (intervals.count() == 0)
34
+ {
35
+ return (startTime >= this->startTime && endTime <= this->endTime)
36
+ ||
37
+ (startTime >= this->startTime && endTime >= this->startTime && this->endTime >= startTime)
38
+ ||
39
+ (startTime <= this->startTime && endTime >= this->startTime);
40
+ }
41
+
42
+ for (const Interval & interval : intervals)
43
+ {
44
+ /* this one is better i guess
45
+ (startTime >= interval.startTime && endTime >= interval.startTime && interval.endTime >= startTime)
46
+ ||
47
+ (startTime <= interval.startTime && endTime >= interval.startTime);
48
+ */
49
+ if ((startTime >= interval.startTime && endTime <= interval.endTime)
50
+ ||
51
+ (startTime >= interval.startTime && endTime >= interval.startTime && interval.endTime >= startTime)
52
+ ||
53
+ (startTime <= interval.startTime && endTime >= interval.startTime))
54
+ {
55
+ return true;
56
+ }
57
+ }
58
+
59
+ return false;
60
+ }
61
+
62
+
63
+ qint64 Activity::duration() const
64
+ {
65
+ qint64 duration = 0;
66
+
67
+ for (const Interval & interval : intervals)
68
+ {
69
+ duration += interval.duration();
70
+ }
71
+
72
+ return duration;
73
+ }
pool/shard006/C++/0083838_QQSound.cpp ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "QQSound.h"
2
+
3
+ #include <QtCore/QDir>
4
+ #include <QtCore/QFileInfo>
5
+
6
+
7
+ QQSound::QQSound(const QString & filename,
8
+ QObject *parent)
9
+ : QSound(filename, parent)
10
+ {
11
+ }
12
+
13
+ bool QQSound::play(const QString & filename)
14
+ {
15
+ QFileInfo fi(filename);
16
+ fi.makeAbsolute();
17
+ if ( ! fi.exists()) return false;
18
+ QString fn(fi.absoluteFilePath());
19
+ fn = QDir::toNativeSeparators(fn);
20
+ QSound::play(fn);
21
+ return true;
22
+ }
pool/shard006/C++/0083843_getcomputername.cpp ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! @file getcomputername.cpp
2
+ //! @author George Fleming <v-geflem@microsoft>
3
+ //! @brief Implements GetComputerName Win32 API
4
+
5
+ #include <errno.h>
6
+ #include <unistd.h>
7
+ #include <string>
8
+ #include "getcomputername.h"
9
+
10
+ //! @brief GetComputerName retrieves the name of the host associated with
11
+ //! the current thread.
12
+ //!
13
+ //! @exception errno Passes these errors via errno to GetLastError:
14
+ //! - ERROR_INVALID_FUNCTION: getlogin_r() returned an unrecognized error code
15
+ //! - ERROR_INVALID_ADDRESS: buffer is an invalid address
16
+ //! - ERROR_GEN_FAILURE: buffer not large enough
17
+ //!
18
+ //! @retval username as UTF-8 string, or null if unsuccessful
19
+
20
+ char* GetComputerName()
21
+ {
22
+ errno = 0;
23
+ // Get computername from system, note that gethostname(2) gets the
24
+ // nodename from uname
25
+ std::string computername(_POSIX_HOST_NAME_MAX, 0);
26
+ int err = gethostname(&computername[0], computername.length());
27
+ // Map errno to Win32 Error Codes
28
+ if (err != 0)
29
+ {
30
+ switch (errno)
31
+ {
32
+ case EFAULT:
33
+ errno = ERROR_INVALID_ADDRESS;
34
+ break;
35
+ case ENAMETOOLONG:
36
+ errno = ERROR_GEN_FAILURE;
37
+ break;
38
+ default:
39
+ errno = ERROR_INVALID_FUNCTION;
40
+ }
41
+ return NULL;
42
+ }
43
+
44
+ return strdup(computername.c_str());
45
+ }
pool/shard006/C++/0083849_SdFatUtil.cpp ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Arduino SdFat Library
2
+ * Copyright (C) 2008 by William Greiman
3
+ *
4
+ * This file is part of the Arduino SdFat Library
5
+ *
6
+ * This Library is free software: you can redistribute it and/or modify
7
+ * it under the terms of the GNU General Public License as published by
8
+ * the Free Software Foundation, either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ *
11
+ * This Library is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ * GNU General Public License for more details.
15
+
16
+ * You should have received a copy of the GNU General Public License
17
+ * along with the Arduino SdFat Library. If not, see
18
+ * <http://www.gnu.org/licenses/>.
19
+ */
20
+ #include <SdFatUtil.h>
21
+ //------------------------------------------------------------------------------
22
+ /** Amount of free RAM
23
+ * \return The number of free bytes.
24
+ */
25
+ int SdFatUtil::FreeRam() {
26
+ extern int __bss_end;
27
+ extern int* __brkval;
28
+ int free_memory;
29
+ if (reinterpret_cast<int>(__brkval) == 0) {
30
+ // if no heap use from end of bss section
31
+ free_memory = reinterpret_cast<int>(&free_memory)
32
+ - reinterpret_cast<int>(&__bss_end);
33
+ } else {
34
+ // use from top of stack to heap
35
+ free_memory = reinterpret_cast<int>(&free_memory)
36
+ - reinterpret_cast<int>(__brkval);
37
+ }
38
+ return free_memory;
39
+ }
40
+ //------------------------------------------------------------------------------
41
+ /** %Print a string in flash memory.
42
+ *
43
+ * \param[in] pr Print object for output.
44
+ * \param[in] str Pointer to string stored in flash memory.
45
+ */
46
+ void SdFatUtil::print_P(Print* pr, PGM_P str) {
47
+ for (uint8_t c; (c = pgm_read_byte(str)); str++) pr->print(c);
48
+ }
49
+ //------------------------------------------------------------------------------
50
+ /** %Print a string in flash memory followed by a CR/LF.
51
+ *
52
+ * \param[in] pr Print object for output.
53
+ * \param[in] str Pointer to string stored in flash memory.
54
+ */
55
+ void SdFatUtil::println_P(Print* pr, PGM_P str) {
56
+ print_P(pr, str);
57
+ pr->println();
58
+ }
59
+ //------------------------------------------------------------------------------
60
+ /** %Print a string in flash memory to Serial.
61
+ *
62
+ * \param[in] str Pointer to string stored in flash memory.
63
+ */
64
+ void SdFatUtil::SerialPrint_P(PGM_P str) {
65
+ print_P(&Serial, str);
66
+ }
67
+ //------------------------------------------------------------------------------
68
+ /** %Print a string in flash memory to Serial followed by a CR/LF.
69
+ *
70
+ * \param[in] str Pointer to string stored in flash memory.
71
+ */
72
+ void SdFatUtil::SerialPrintln_P(PGM_P str) {
73
+ println_P(&Serial, str);
74
+ }
pool/shard006/C++/0083856_service_manager.cc ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is part of SWGANH which is released under the MIT license.
2
+ // See file LICENSE or go to http://swganh.com/LICENSE
3
+
4
+ #include "service_manager.h"
5
+
6
+ #include "anh/logger.h"
7
+
8
+ #include <algorithm>
9
+ #include <string>
10
+ #include <stdexcept>
11
+
12
+ #include "service_directory_interface.h"
13
+ #include "service_description.h"
14
+
15
+ #ifndef WIN32
16
+ #include <boost/regex.hpp>
17
+ using boost::regex;
18
+ using boost::regex_search;
19
+ #else
20
+ #include <regex>
21
+ using std::regex;
22
+ using std::regex_search;
23
+ #endif
24
+
25
+ using namespace swganh::service;
26
+ using namespace std;
27
+
28
+ ServiceManager::ServiceManager(ServiceDirectoryInterface* service_directory)
29
+ : service_directory_(service_directory)
30
+ {}
31
+
32
+ ServiceManager::~ServiceManager()
33
+ {
34
+ auto it = services_.begin();
35
+ for(it = services_.begin();it != services_.end();it++)
36
+ {
37
+
38
+ service_directory_->removeService((it)->second->GetServiceDescription());
39
+ }
40
+ }
41
+
42
+ ServiceInterface* ServiceManager::GetService(string name)
43
+ {
44
+ auto it = services_.find(name);
45
+
46
+ if (it == services_.end())
47
+ {
48
+ return nullptr;
49
+ }
50
+
51
+ return it->second.get();
52
+ }
53
+
54
+ void ServiceManager::AddService(string name, shared_ptr<ServiceInterface> service)
55
+ {
56
+ auto current_service = GetService(name);
57
+
58
+ if (current_service)
59
+ {
60
+ // throw exception here, service already exists
61
+ throw std::runtime_error("service already exists: " + name);
62
+ return;
63
+ }
64
+
65
+ auto& service_description = service->GetServiceDescription();
66
+ if (!service_directory_->registerService(service_description))
67
+ {
68
+ throw std::runtime_error("Unable to register service " + service_description.name());
69
+ }
70
+
71
+ // update the status of the service
72
+ service_description.status(swganh::service::Galaxy::LOADING);
73
+ service_directory_->updateService(service_description);
74
+
75
+ services_[name] = service;
76
+ }
77
+
78
+ void ServiceManager::Start()
79
+ {
80
+ // First pass initialization
81
+ //for (auto& service_entry : services_)
82
+
83
+ auto it = services_.begin();
84
+ for(it = services_.begin();it != services_.end();it++)
85
+ {
86
+ auto& service = it->second;
87
+ service->Initialize();
88
+ }
89
+
90
+ // After all resources are acquired services can be started
91
+ //for (auto& service_entry : services_)
92
+ //{
93
+ it = services_.begin();
94
+ for(it = services_.begin();it != services_.end();it++)
95
+ {
96
+
97
+ auto& service = it->second;
98
+
99
+ service->Startup();
100
+ service->SetStatus(Galaxy::ONLINE);
101
+
102
+ auto service_description = service->GetServiceDescription();
103
+ service_directory_->updateService(service_description);
104
+ LOG(info) << "Started " << service_description.name();
105
+ }
106
+ }
107
+
108
+ void ServiceManager::Stop()
109
+ {
110
+ //for (auto& service_entry : services_)
111
+ auto it = services_.begin();
112
+ for(it = services_.begin();it != services_.end();it++)
113
+ {
114
+ auto& service = it->second;
115
+
116
+ service->Shutdown();
117
+ service->SetStatus(Galaxy::OFFLINE);
118
+
119
+ auto service_description = service->GetServiceDescription();
120
+ service_directory_->updateService(service_description);
121
+ LOG(info) << "Stopped " << service_description.name();
122
+ }
123
+ }
pool/shard006/C++/0083858_Pawn.cpp ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Pawn.h"
2
+ #include "Board.h"
3
+
4
+
5
+
6
+
7
+ Pawn::Pawn(Coordinate coordinate) : hasYetToMove(true)
8
+ {
9
+ symbol = "";
10
+ this->coordinate = coordinate;
11
+ texture.loadFromFile("WhitePawn.png");
12
+ setTexture(texture);
13
+
14
+
15
+ int row = (int)coordinate / 8;
16
+ int column = (int)coordinate % 8;
17
+
18
+ //sf::RectangleShape::setPosition(sf::Vector2f(column * 50, 350 - row * 50));
19
+ setPosition(sf::Vector2f(column * 50, 350 - row * 50));
20
+ //setSize(sf::Vector2f(20, 20));
21
+ }
22
+
23
+ void Pawn::setCoordinate(const Coordinate position)
24
+ {
25
+ Piece::setCoordinate(position);
26
+ hasYetToMove = false;
27
+ }
28
+
29
+ void Pawn::setIsWhite(const bool isWhite)
30
+ {
31
+ this->isWhite = isWhite;
32
+
33
+ if (isWhite)
34
+ {
35
+ texture.loadFromFile("WhitePawn.png");
36
+ }
37
+ else
38
+ {
39
+ texture.loadFromFile("BlackPawn.png");
40
+ }
41
+ setTexture(texture);
42
+ }
43
+
44
+
45
+
46
+ std::vector<Coordinate> Pawn::computeMoves()
47
+ {
48
+ //first clear past movablePositions
49
+ clearMoves();
50
+
51
+ //REQUIRES CHANGING TO ACCOUNT FOR and promotions.
52
+
53
+ if (isWhite)
54
+ {
55
+ //capturing 1 up, 1 right piece
56
+ Coordinate upRight = CoordinateHelper::getCoordinateUpRight(coordinate);
57
+
58
+ if (upRight != CoordinateHelper::getMostUpRightCoordinate(coordinate) || upRight != Coordinate::Invalid)
59
+ {
60
+ addCaptureMove(upRight);
61
+ }
62
+
63
+ //capturing 1 up, 1 left piece
64
+ auto upLeft = CoordinateHelper::getCoordinateUpLeft(coordinate);
65
+
66
+ if (upLeft != CoordinateHelper::getMostUpLeftCoordinate(coordinate) || upLeft != Coordinate::Invalid)
67
+ {
68
+ addCaptureMove(upLeft);
69
+ }
70
+
71
+ auto oneUp = CoordinateHelper::getCoordinateUp(coordinate);
72
+ auto twoUp = CoordinateHelper::getCoordinateUp(oneUp);
73
+
74
+ //moving
75
+ if (hasYetToMove)
76
+ {
77
+ if (board[oneUp].getPiece() != nullptr)
78
+ {
79
+ //don't add any positions to computePosition
80
+ }
81
+ else if (board[oneUp].getPiece() == nullptr && board[twoUp].getPiece() != nullptr)
82
+ {
83
+ moves.push_back(oneUp);
84
+ }
85
+ else if (board[oneUp].getPiece() == nullptr && board[twoUp].getPiece() == nullptr)
86
+ {
87
+ moves.push_back(oneUp);
88
+ moves.push_back(twoUp);
89
+ }
90
+ }
91
+ else
92
+ {
93
+ if (board[oneUp].getPiece() == nullptr)
94
+ {
95
+ moves.push_back(oneUp);
96
+ }
97
+ }
98
+ }
99
+
100
+ else
101
+ {
102
+ //capturing 1 down, 1 right piece
103
+ auto downRight = CoordinateHelper::getCoordinateDownRight(coordinate);
104
+
105
+ if (downRight != CoordinateHelper::getMostDownRightCoordinate(coordinate) || downRight != Coordinate::Invalid)
106
+ {
107
+ addCaptureMove(downRight);
108
+ }
109
+
110
+ //capturing 1 down, 1 left piece
111
+ auto downLeft = CoordinateHelper::getCoordinateDownLeft(coordinate);
112
+
113
+ if (downLeft != CoordinateHelper::getMostDownLeftCoordinate(coordinate) || downLeft != Coordinate::Invalid)
114
+ {
115
+ addCaptureMove(downLeft);
116
+ }
117
+
118
+ auto oneDown = CoordinateHelper::getCoordinateDown(coordinate);
119
+ auto twoDown = CoordinateHelper::getCoordinateDown(oneDown);
120
+
121
+ //moving
122
+ if (hasYetToMove)
123
+ {
124
+ if (board[oneDown].getPiece() != nullptr)
125
+ {
126
+ //don't add any positions to computePosition
127
+ }
128
+ else if (board[oneDown].getPiece() == nullptr && board[twoDown].getPiece() != nullptr)
129
+ {
130
+ moves.push_back(oneDown);
131
+ }
132
+ else if (board[oneDown].getPiece() == nullptr && board[twoDown].getPiece() == nullptr)
133
+ {
134
+ moves.push_back(oneDown);
135
+ moves.push_back(twoDown);
136
+ }
137
+ }
138
+ else
139
+ {
140
+ if (board[oneDown].getPiece() == nullptr)
141
+ {
142
+ moves.push_back(oneDown);
143
+ }
144
+ }
145
+ }
146
+
147
+ return moves;
148
+ }
149
+
150
+
151
+ void Pawn::addCaptureMove(const Coordinate& coordinate)
152
+ {
153
+ if (board[coordinate].getPiece() != nullptr)
154
+ {
155
+ if (board[coordinate].getPiece()->getIsWhite() != this->isWhite)
156
+ {
157
+ moves.push_back(coordinate);
158
+
159
+ }
160
+ }
161
+ }
162
+
163
+