Pendigard commited on
Commit
e1191aa
·
verified ·
1 Parent(s): 910db9a

Upload folder using huggingface_hub (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/train/C++/0000525_main.cpp +176 -0
  2. code/train/C++/0000584_main.cpp +170 -0
  3. code/train/C++/0000623_asgn8.cpp +263 -0
  4. code/train/C++/0000658_DoAHeuristicPreferredAngle.cpp +116 -0
  5. code/train/C++/0000762_statistic.cpp +16 -0
  6. code/train/C++/0000894_7771448.cpp +110 -0
  7. code/train/C++/0001490_bip32_tests.cpp +154 -0
  8. code/train/C++/0002138_A.cpp +34 -0
  9. code/train/C++/0002412_authmessagevalidator.cpp +117 -0
  10. code/train/C++/0002530_AppMoblet.cpp +285 -0
  11. code/train/C++/0002981_vcardmanager.cpp +127 -0
  12. code/train/C++/0003712_PEMer_Lite.cpp +267 -0
  13. code/train/C++/0003837_poj1852.cc +44 -0
  14. code/train/C++/0004781_heapSort.cpp +136 -0
  15. code/train/C++/0004813_276A.cpp +46 -0
  16. code/train/C++/0005979_WorldRunnable.cpp +99 -0
  17. code/train/C++/0006023_SpecificPartialLoudnessGM.cpp +196 -0
  18. code/train/C++/0006349_XScaleBar.cpp +165 -0
  19. code/train/C++/0006416_TestStanfordCPPLib.cpp +121 -0
  20. code/train/C++/0006687_instprofile.cpp +247 -0
  21. code/train/C++/0006795_testscore.ex3.cpp +137 -0
  22. code/train/C++/0006861_sqldb.cpp +338 -0
  23. code/train/C++/0007941_solution.cpp +22 -0
  24. code/train/C++/0008009_FoxAndDoraemon.cpp +57 -0
  25. code/train/C++/0008879_IPCWorkerThread.cpp +119 -0
  26. code/train/C++/0009074_cafToggleItemsOnOthersOffFeature.cpp +162 -0
  27. code/train/C++/0009203_PathTransform.cpp +178 -0
  28. code/train/C++/0009912_zonedessin.cpp +125 -0
  29. code/train/C++/0009915_sp-switch.cpp +159 -0
  30. code/train/C++/0010000_track.cpp +93 -0
  31. code/train/C++/0010267_sgmm-acc-fmllrbasis-ali.cc +216 -0
  32. code/train/C++/0010531_CCSequence3D.cpp +232 -0
  33. code/train/C++/0010760_laser.cpp +103 -0
  34. code/train/C++/0011798_chapter04_ex16.cpp +60 -0
  35. code/train/C++/0012078_edit_distance.cc +67 -0
  36. code/train/C++/0024658_MaxPID.cpp +61 -0
  37. code/train/C++/0024892_ft_send.cpp +259 -0
  38. code/train/C++/0025348_sweeperdaemon.cpp +274 -0
  39. code/train/C++/0025395_part-tld-test.cc +64 -0
  40. code/train/C++/0025424_possibilities.cc +120 -0
  41. code/train/C++/0025962_Otsu.cc +78 -0
  42. code/train/C++/0025967_16.cpp +71 -0
  43. code/train/C++/0026485_tst_qscopedvaluerollback.cpp +203 -0
  44. code/train/C++/0026931_FEEPROM.cpp +42 -0
  45. code/train/C++/0027205_main.cpp +105 -0
  46. code/train/C++/0027411_Defines.cpp +300 -0
  47. code/train/C++/0027495_uf.cc +210 -0
  48. code/train/C++/0027730_reverse_geocoder.cpp +218 -0
  49. code/train/C++/0027996_gain_change_calculator.cc +55 -0
  50. code/train/C++/0028086_StacksDP.cpp +65 -0
code/train/C++/0000525_main.cpp ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <fstream>
3
+ #include <string>
4
+ #include <stdio.h>
5
+ #include <time.h>
6
+ #include <algorithm>
7
+ #include <vector>
8
+ #include <map>
9
+
10
+ // OpenCV headers
11
+ #include <cv.h>
12
+ #include <highgui.h>
13
+
14
+ #include <opencv2/contrib/contrib.hpp>
15
+ #include <opencv2/core/core.hpp>
16
+ #include <opencv2/highgui/highgui.hpp>
17
+
18
+ #include <opencv_workbench/utils/Stream.h>
19
+ #include <opencv_workbench/syllo/syllo.h>
20
+
21
+ #include <opencv_workbench/utils/AnnotationParser.h>
22
+ #include <opencv_workbench/plot/Plot.h>
23
+
24
+ #include <opencv_workbench/detector/Detector.h>
25
+ #include <opencv_workbench/plugin_manager/PluginManager.h>
26
+
27
+ #include <opencv_workbench/syllo/syllo.h>
28
+
29
+ using std::cout;
30
+ using std::endl;
31
+
32
+ PluginManager<Detector, Detector_maker_t> plugin_manager_;
33
+
34
+ bool myfunction (std::map<std::string,double> i, std::map<std::string,double> j)
35
+ {
36
+ if (i["FPR"] == j["FPR"]) {
37
+ return (i["TPR"] < j["TPR"]);
38
+ } else {
39
+ return (i["FPR"] < j["FPR"]);
40
+ }
41
+ }
42
+
43
+ int main(int argc, char *argv[])
44
+ {
45
+ std::string xml_dir = "";
46
+
47
+ int c;
48
+ int create_roc_file = 0;
49
+ int output_file_set = 0;
50
+ std::string output_file = "";
51
+ std::string output_dir = "./";
52
+ while ((c = getopt (argc, argv, "f:o:d:")) != -1) {
53
+ switch (c) {
54
+ //case 'a':
55
+ // aflag = 1;
56
+ // break;
57
+ //case 'b':
58
+ // bflag = 1;
59
+ // break;
60
+ case 'o':
61
+ output_dir = std::string(optarg);
62
+ create_roc_file = 1;
63
+ break;
64
+ case 'f':
65
+ output_file = std::string(optarg);
66
+ output_file_set = 1;
67
+ break;
68
+ case 'd':
69
+ xml_dir = std::string(optarg);
70
+ break;
71
+ case '?':
72
+ if (optopt == 'd') {
73
+ fprintf (stderr, "Option -%c requires an argument.\n", optopt);
74
+ } else if (isprint (optopt)) {
75
+ fprintf (stderr, "Unknown option `-%c'.\n", optopt);
76
+ } else {
77
+ fprintf (stderr,
78
+ "Unknown option character `\\x%x'.\n",
79
+ optopt);
80
+ }
81
+ return 1;
82
+ default:
83
+ abort ();
84
+ }
85
+ }
86
+
87
+ // Check existence of xml directory
88
+ if ( !boost::filesystem::exists( fs::path(xml_dir) ) ) {
89
+ cout << "Error: XML Directory doesn't exist." << endl;
90
+ return -1;
91
+ }
92
+
93
+ // Open each xml file and count metrics
94
+ std::vector<fs::path> file_paths;
95
+ syllo::get_files_with_ext(fs::path(xml_dir), ".xml",
96
+ file_paths,true);
97
+
98
+
99
+ std::vector< std::map<std::string,double> > metrics_vector;
100
+
101
+ int TP = 0, TN = 0, FP = 0, FN = 0;
102
+ for (std::vector<fs::path>::iterator it = file_paths.begin();
103
+ it != file_paths.end(); it++) {
104
+ cout << "File: " << it->string() << endl;
105
+
106
+ AnnotationParser parser;
107
+ int retcode = parser.ParseFile(it->string());
108
+ if (retcode != 0) {
109
+ cout << "Failed to parse: " << it->string();
110
+ continue;
111
+ }
112
+ std::map<std::string,double> metrics = parser.get_metrics();
113
+
114
+ metrics_vector.push_back(metrics);
115
+ }
116
+
117
+ std::sort(metrics_vector.begin(), metrics_vector.end(), myfunction);
118
+
119
+ std::string roc_fn;
120
+ if (output_file_set == 1) {
121
+ roc_fn = output_dir + "/" + output_file;
122
+ } else {
123
+ // time string generation
124
+ time_t rawtime;
125
+ struct tm * timeinfo;
126
+ char buffer [80];
127
+ time (&rawtime);
128
+ timeinfo = localtime (&rawtime);
129
+ strftime (buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo);
130
+ std::string time_str = std::string(buffer);
131
+
132
+ roc_fn = output_dir + "/" + time_str + "_ROC.csv";
133
+ }
134
+
135
+ std::ofstream roc_stream;
136
+ if (create_roc_file) {
137
+ cout << "ROC Output file: " << roc_fn << endl;
138
+ roc_stream.open (roc_fn.c_str(), std::ofstream::out);
139
+ roc_stream << "# FPR,TPR,thresh,FP,FN,TP,TN," << endl;
140
+ }
141
+
142
+ for(std::vector< std::map<std::string,double> >::iterator it = metrics_vector.begin();
143
+ it != metrics_vector.end(); it++) {
144
+
145
+ // 0 for threshold place holder for now: TODO
146
+ roc_stream << (*it)["FPR"] <<","<< (*it)["TPR"] << ",0,"
147
+ << (*it)["FP"] <<","<< (*it)["FN"] <<","
148
+ << (*it)["TP"] <<","<< (*it)["TN"] <<","
149
+ << endl;
150
+
151
+ TP += (*it)["TP"];
152
+ TN += (*it)["TN"];
153
+ FP += (*it)["FP"];
154
+ FN += (*it)["FN"];
155
+ }
156
+
157
+ roc_stream.close();
158
+
159
+ double TPR = 0, FPR = 0;
160
+
161
+ TPR = (double)TP / (double)(TP + FN) ;
162
+ FPR = (double)FP / (double)(FP + TN) ;
163
+
164
+ // Display results
165
+ syllo::fill_line("+");
166
+ cout << "Totals... " << endl;
167
+ cout << "True Positives: " << TP << endl;
168
+ cout << "True Negatives: " << TN << endl;
169
+ cout << "False Positives: " << FP << endl;
170
+ cout << "False Negatives: " << FN << endl;
171
+ cout << "True Positive Rate: " << TPR << endl;
172
+ cout << "False Positive Rate: " << FPR << endl;
173
+ syllo::fill_line("+");
174
+
175
+ return 0;
176
+ }
code/train/C++/0000584_main.cpp ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /****************************************************************************
2
+ **
3
+ ** Copyright (C) 2016 The Qt Company Ltd.
4
+ ** Contact: https://www.qt.io/licensing/
5
+ **
6
+ ** This file is part of the examples of the Qt Toolkit.
7
+ **
8
+ ** $QT_BEGIN_LICENSE:BSD$
9
+ ** Commercial License Usage
10
+ ** Licensees holding valid commercial Qt licenses may use this file in
11
+ ** accordance with the commercial license agreement provided with the
12
+ ** Software or, alternatively, in accordance with the terms contained in
13
+ ** a written agreement between you and The Qt Company. For licensing terms
14
+ ** and conditions see https://www.qt.io/terms-conditions. For further
15
+ ** information use the contact form at https://www.qt.io/contact-us.
16
+ **
17
+ ** BSD License Usage
18
+ ** Alternatively, you may use this file under the terms of the BSD license
19
+ ** as follows:
20
+ **
21
+ ** "Redistribution and use in source and binary forms, with or without
22
+ ** modification, are permitted provided that the following conditions are
23
+ ** met:
24
+ ** * Redistributions of source code must retain the above copyright
25
+ ** notice, this list of conditions and the following disclaimer.
26
+ ** * Redistributions in binary form must reproduce the above copyright
27
+ ** notice, this list of conditions and the following disclaimer in
28
+ ** the documentation and/or other materials provided with the
29
+ ** distribution.
30
+ ** * Neither the name of The Qt Company Ltd nor the names of its
31
+ ** contributors may be used to endorse or promote products derived
32
+ ** from this software without specific prior written permission.
33
+ **
34
+ **
35
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46
+ **
47
+ ** $QT_END_LICENSE$
48
+ **
49
+ ****************************************************************************/
50
+
51
+ #include <QtGui>
52
+
53
+ #include "rasterwindow.h"
54
+
55
+ //! [5]
56
+ class AnalogClockWindow : public RasterWindow
57
+ {
58
+ public:
59
+ AnalogClockWindow();
60
+
61
+ protected:
62
+ void timerEvent(QTimerEvent *) override;
63
+ void render(QPainter *p) override;
64
+
65
+ private:
66
+ int m_timerId;
67
+ };
68
+ //! [5]
69
+
70
+
71
+ //! [6]
72
+ AnalogClockWindow::AnalogClockWindow()
73
+ {
74
+ setTitle("Analog Clock");
75
+ resize(200, 200);
76
+
77
+ m_timerId = startTimer(1000);
78
+ }
79
+ //! [6]
80
+
81
+ //! [7]
82
+ void AnalogClockWindow::timerEvent(QTimerEvent *event)
83
+ {
84
+ if (event->timerId() == m_timerId)
85
+ renderLater();
86
+ }
87
+ //! [7]
88
+
89
+ //! [1] //! [14]
90
+ void AnalogClockWindow::render(QPainter *p)
91
+ {
92
+ //! [14]
93
+ //! [8]
94
+ static const QPoint hourHand[3] = {
95
+ QPoint(7, 8),
96
+ QPoint(-7, 8),
97
+ QPoint(0, -40)
98
+ };
99
+ static const QPoint minuteHand[3] = {
100
+ QPoint(7, 8),
101
+ QPoint(-7, 8),
102
+ QPoint(0, -70)
103
+ };
104
+
105
+ QColor hourColor(127, 0, 127);
106
+ QColor minuteColor(0, 127, 127, 191);
107
+ //! [8]
108
+
109
+ //! [9]
110
+ p->setRenderHint(QPainter::Antialiasing);
111
+ //! [9] //! [10]
112
+ p->translate(width() / 2, height() / 2);
113
+
114
+ int side = qMin(width(), height());
115
+ p->scale(side / 200.0, side / 200.0);
116
+ //! [1] //! [10]
117
+
118
+ //! [11]
119
+ p->setPen(Qt::NoPen);
120
+ p->setBrush(hourColor);
121
+ //! [11]
122
+
123
+ //! [2]
124
+ QTime time = QTime::currentTime();
125
+
126
+ p->save();
127
+ p->rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
128
+ p->drawConvexPolygon(hourHand, 3);
129
+ p->restore();
130
+ //! [2]
131
+
132
+ //! [12]
133
+ p->setPen(hourColor);
134
+
135
+ for (int i = 0; i < 12; ++i) {
136
+ p->drawLine(88, 0, 96, 0);
137
+ p->rotate(30.0);
138
+ }
139
+ //! [12] //! [13]
140
+ p->setPen(Qt::NoPen);
141
+ p->setBrush(minuteColor);
142
+ //! [13]
143
+
144
+ //! [3]
145
+ p->save();
146
+ p->rotate(6.0 * (time.minute() + time.second() / 60.0));
147
+ p->drawConvexPolygon(minuteHand, 3);
148
+ p->restore();
149
+ //! [3]
150
+
151
+ //! [4]
152
+ p->setPen(minuteColor);
153
+
154
+ for (int j = 0; j < 60; ++j) {
155
+ if ((j % 5) != 0)
156
+ p->drawLine(92, 0, 96, 0);
157
+ p->rotate(6.0);
158
+ }
159
+ //! [4]
160
+ }
161
+
162
+ int main(int argc, char **argv)
163
+ {
164
+ QGuiApplication app(argc, argv);
165
+
166
+ AnalogClockWindow clock;
167
+ clock.show();
168
+
169
+ return app.exec();
170
+ }
code/train/C++/0000623_asgn8.cpp ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ CSCI 240 - Program 7 - Spring 2008
3
+
4
+ Name: Joe Dan Parker
5
+ Z-Number: 158012
6
+ Section: 8
7
+ TA: Kalpana Mangalarapu
8
+
9
+ Purpose: Create a program that will analyze three types of household utility
10
+ expenses (gas, electricity and water) over 12 months.
11
+ ******************************************************************************/
12
+
13
+ #include <iostream>
14
+ #include <iomanip>
15
+ #include <fstream>
16
+
17
+ using namespace std;
18
+
19
+ // I initialized these variables outside of any function, so that they are available to the entire program, not just within any one scope.
20
+ string caption;
21
+
22
+ int numScores;
23
+
24
+ double mean;
25
+ int median;
26
+ int hi;
27
+ int lo;
28
+
29
+ int ar[200];
30
+
31
+ /* Function Prototypes */
32
+
33
+ int buildArray( int[] );
34
+
35
+ void showArray( string, int[], int );
36
+
37
+ void sortArray( int[], int );
38
+
39
+ void doStatsRef( int[], int, double&, int&, int&, int& );
40
+
41
+ void meanAndMedianRef( int[], int, double&, int& );
42
+
43
+ void hiAndLoRef( int[], int, int&, int& );
44
+
45
+ double calcAverage( int[], int );
46
+
47
+ int calcMedian( int[], int );
48
+
49
+ int calcLo( int[], int );
50
+
51
+ int calcHi( int[], int);
52
+
53
+ void getScores(int[], int, int[]);
54
+
55
+ int main()
56
+ {
57
+ int counts[6] = {0,0,0,0,0};
58
+
59
+ numScores = buildArray( ar );
60
+
61
+ showArray( "*** Scores ***", ar, numScores );
62
+
63
+ doStatsRef( ar, numScores, mean, median, hi, lo );
64
+
65
+ getScores( ar, numScores, counts );
66
+
67
+ cout << "Mean = " << mean << endl;
68
+ cout << "Median = " << median << endl;
69
+ cout << "Highest Score = " << hi << endl;
70
+ cout << "Lowest Score = " << lo << endl;
71
+ cout << endl;
72
+ cout << "Number of A's = " << counts[0] << endl;
73
+ cout << "Number of B's = " << counts[1] << endl;
74
+ cout << "Number of C's = " << counts[2] << endl;
75
+ cout << "Number of D's = " << counts[3] << endl;
76
+ cout << "Number of E's = " << counts[4] << endl;
77
+ cout << "Number of F's = " << counts[5] << endl;
78
+ }
79
+
80
+ /********** Code your Functions below this line **********/
81
+
82
+ int buildArray( int ar[] )
83
+ {
84
+ ifstream inFile;
85
+
86
+ int i = 0,
87
+ num;
88
+
89
+ inFile.open("scores.txt");
90
+ if (inFile.fail())
91
+ {
92
+ cout << "Unable to open scores.txt file\n";
93
+ exit(1);
94
+ }
95
+ inFile >> num;
96
+
97
+ while ( inFile )
98
+ {
99
+ ar[i] = num;
100
+ i++;
101
+ inFile >> num;
102
+ }
103
+
104
+ inFile.close();
105
+ return i;
106
+ }
107
+
108
+ void showArray( string caption, int ar[], int numScores )
109
+ {
110
+ int temp_int = 0,
111
+ i;
112
+
113
+ cout << caption << endl << endl;
114
+
115
+ while ( temp_int < numScores )
116
+ {
117
+ for (i = 1; i <= 8; i++ )
118
+ {
119
+ if ( ar[temp_int] != 0 )
120
+ {
121
+ cout << ar[temp_int] << ' ';
122
+ temp_int ++;
123
+ }
124
+ }
125
+ cout << endl;
126
+ }
127
+ cout << endl << temp_int + 1 << " Scores" << endl << endl;
128
+ }
129
+
130
+ void sortArray(int ar[], int numScores)
131
+ {
132
+ int i, j;
133
+ int max;
134
+ int temp;
135
+
136
+ for (i = 0; i <= numScores; i++)
137
+ {
138
+ max = i;
139
+ for (j = i+1; j <= numScores; j++)
140
+ {
141
+ if (ar[j] > ar[max])
142
+ max = j;
143
+ }
144
+ temp = ar[i];
145
+ ar[i] = ar[max];
146
+ ar[max] = temp;
147
+ }
148
+ }
149
+
150
+ void doStatsRef( int ar[], int numScores, double & mean, int & median, int & hi, int & lo )
151
+ {
152
+ int sortedAr[200],
153
+ i;
154
+
155
+ for (i = 0; i <= 200; i++)
156
+ {
157
+ sortedAr[i] = ar[i];
158
+ }
159
+ sortArray( sortedAr, numScores );
160
+
161
+ meanAndMedianRef( sortedAr, numScores, mean, median );
162
+
163
+ hiAndLoRef( sortedAr, numScores, hi, lo );
164
+ }
165
+
166
+ void meanAndMedianRef( int sortedAr[], int numScores, double & mean, int & median )
167
+ {
168
+ mean = calcAverage(sortedAr, numScores);
169
+
170
+ median = calcMedian(sortedAr, numScores);
171
+ }
172
+
173
+ void hiAndLoRef( int sortedAr[], int numScores, int& hi, int& lo )
174
+ {
175
+ hi = calcHi( sortedAr, numScores );
176
+
177
+ lo = calcLo( sortedAr, numScores );
178
+ }
179
+
180
+ double calcAverage( int sortedAr[], int numScores )
181
+ {
182
+ int i;
183
+
184
+ int temp_int = 0;
185
+
186
+ for ( i = 1; i <= numScores; i ++ )
187
+ {
188
+ temp_int += sortedAr[i];
189
+ }
190
+ return ((double) temp_int / (double) numScores);
191
+ }
192
+
193
+ int calcMedian( int sortedAr[], int numScores )
194
+ {
195
+ return sortedAr[(( numScores / 2 ) + 1)];
196
+ }
197
+
198
+ int calcHi( int ar[], int numScores )
199
+ {
200
+ int i,
201
+ j = 1;
202
+
203
+ int temp_int = 0;
204
+
205
+ for ( i = 0; i <= numScores; i ++ )
206
+ {
207
+ if (ar[j] < ar[i])
208
+ {
209
+ ar[j] = ar[i];
210
+ }
211
+ }
212
+ return ar[j];
213
+ }
214
+
215
+ int calcLo( int ar[], int numScores )
216
+ {
217
+ int i,
218
+ j = 1;
219
+
220
+ double temp_int = 0;
221
+
222
+ for ( i = 0; i <= numScores; i ++ )
223
+ {
224
+ if (ar[j] > ar[i])
225
+ {
226
+ ar[j] = ar[i];
227
+ }
228
+ }
229
+ return ar[j];
230
+ }
231
+
232
+ void getScores ( int sortedAr[], int numScores, int counts[] )
233
+ {
234
+ int i;
235
+ for (i = 0; i <= numScores; i++)
236
+ {
237
+ if ( sortedAr[i] >= 90 )
238
+ {
239
+ counts[0]++;
240
+ }
241
+ else if ( sortedAr[i] < 90 && sortedAr[i] >= 80 )
242
+ {
243
+ counts[1]++;
244
+ }
245
+ else if ( sortedAr[i] < 80 && sortedAr[i] >= 70 )
246
+ {
247
+ counts[2]++;
248
+ }
249
+ else if ( sortedAr[i] < 70 && sortedAr[i] >= 60 )
250
+ {
251
+ counts[3]++;
252
+ }
253
+ else if ( sortedAr[i] < 60 && sortedAr[i] >= 50 )
254
+ {
255
+ counts[4]++;
256
+ }
257
+ if ( sortedAr[i] < 50 )
258
+ {
259
+ counts[5]++;
260
+ }
261
+ }
262
+ }
263
+
code/train/C++/0000658_DoAHeuristicPreferredAngle.cpp ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * This file is part of openWNS (open Wireless Network Simulator)
3
+ * _____________________________________________________________________________
4
+ *
5
+ * Copyright (C) 2004-2009
6
+ * Chair of Communication Networks (ComNets)
7
+ * Kopernikusstr. 5, D-52074 Aachen, Germany
8
+ * phone: ++49-241-80-27910,
9
+ * fax: ++49-241-80-22242
10
+ * email: info@openwns.org
11
+ * www: http://www.openwns.org
12
+ * _____________________________________________________________________________
13
+ *
14
+ * openWNS is free software; you can redistribute it and/or modify it under the
15
+ * terms of the GNU Lesser General Public License version 2 as published by the
16
+ * Free Software Foundation;
17
+ *
18
+ * openWNS is distributed in the hope that it will be useful, but WITHOUT ANY
19
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20
+ * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21
+ * details.
22
+ *
23
+ * You should have received a copy of the GNU Lesser General Public License
24
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
25
+ *
26
+ ******************************************************************************/
27
+
28
+ #include "DoAHeuristicPreferredAngle.hpp"
29
+
30
+ #include <WNS/pyconfig/View.hpp>
31
+ #include <WNS/StaticFactory.hpp>
32
+
33
+ #include <list>
34
+ #include <math.h>
35
+ #include <algorithm>
36
+
37
+ using namespace wns::scheduler;
38
+ using namespace wns::scheduler::grouper;
39
+
40
+
41
+ STATIC_FACTORY_REGISTER_WITH_CREATOR(DoAHeuristicPreferredAngle, GroupingProviderInterface, "DoAHeuristicPreferredAngle", wns::PyConfigViewCreator);
42
+
43
+
44
+ DoAHeuristicPreferredAngle::DoAHeuristicPreferredAngle(const wns::pyconfig::View& config)
45
+ : DoATreeBasedGrouper(config),
46
+ minAngle(config.get<float>("minAngleDegree")*M_PI/180.0),
47
+ weight(config.get<float>("weight"))
48
+ {
49
+ }
50
+
51
+
52
+ float
53
+ DoAHeuristicPreferredAngle::groupingCostForAUser(UserSet group, UserID newUser) {
54
+ float cost = 0.0;
55
+ float threshold = minAngle;
56
+ // float threshold = 20.0 / 180.0 * M_PI;
57
+ float penalty = 1000.0;
58
+ float min = M_PI;
59
+
60
+ float newUserDoA = getNormalizedDoA(newUser);
61
+
62
+ // if (Debug)
63
+ // std::cout << "New user at " << rad2deg(newUserDoA) << " degrees\n";
64
+
65
+ for (UserSet::const_iterator iter = group.begin();
66
+ iter != group.end(); ++iter) {
67
+ float userDoA = getNormalizedDoA(*iter);
68
+
69
+ // if (Debug)
70
+ // std::cout << "Group user at " << rad2deg(userDoA) << " degrees\n";
71
+
72
+ float diff = userDoA - newUserDoA;
73
+ // normalize angles to [0.0, M_PI]
74
+ if (diff < 0.0)
75
+ diff = diff + 2*M_PI;
76
+ if (diff > M_PI)
77
+ diff = 2*M_PI - diff;
78
+
79
+ if (fabs(diff) < min)
80
+ min = fabs(diff);
81
+ }
82
+
83
+ // if (Debug)
84
+ // std::cout << "Minimum " << rad2deg(min) << " degrees\n";
85
+
86
+ // calculate cost to add user
87
+ if (min < threshold)
88
+ cost = penalty;
89
+ else
90
+ {
91
+ // 0..threshold verboten
92
+ // threshold .. 2.5X threshold erwuenscht mit minimalen kosten bei 2x
93
+ // threshold. von 2.5x threshold bis 180 konstanter langsam wachsender
94
+ // wert auf 1+mincost
95
+
96
+ float minCost = threshold / M_PI;
97
+ if (min < 2.5*threshold)
98
+ cost = weight*(fabs(min-2*threshold)/threshold+minCost);
99
+ else
100
+ // fange bei 2.5*th mit 0.5+minCost an, dann steiger dich auf
101
+ // 1+minCost bei M_PI
102
+ cost = weight*((min-2.5*threshold)*(0.5/(M_PI-2.5*threshold)) +0.5+minCost );
103
+
104
+ }
105
+
106
+ // if (Debug)
107
+ // std::cout << "Resulting in cost of " << cost << " \n\n";
108
+
109
+ return cost;
110
+ }
111
+
112
+
113
+
114
+
115
+
116
+
code/train/C++/0000762_statistic.cpp ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <cstdio>
3
+ using namespace std;
4
+ #define INF 0x3f3f3f3f
5
+ int main() {
6
+ int n = 0, mmin = INF, mmax = -INF, sum = 0;
7
+ int x;
8
+ while(scanf("%d", &x) == 1){
9
+ n ++;
10
+ sum += x;
11
+ if(x > mmax) mmax = x;
12
+ if(x < mmin) mmin = x;
13
+ }
14
+ printf("%d %d %.3f",mmin, mmax, (double)sum / n);
15
+ return 0;
16
+ }
code/train/C++/0000894_7771448.cpp ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //Language: GNU C++
2
+
3
+
4
+ #include<cstdio>
5
+ #include<set>
6
+ #include<cstring>
7
+ #include<iostream>
8
+ #include<stdlib.h>
9
+ #include<vector>
10
+ #include<map>
11
+ #include<stack>
12
+ #include<algorithm>
13
+ #include<queue>
14
+ #include<cmath>
15
+ #include<functional>
16
+ #include<string>
17
+ #include<assert.h>
18
+ using namespace std;
19
+
20
+ #define LL long long
21
+ #define uLL unsigned long long
22
+ #define B puts("^_^");
23
+ #define FILEIN freopen("in", "r", stdin);
24
+ #define MP make_pair
25
+ #define PB push_back
26
+ #define fi first
27
+ #define se second
28
+ #define PI pair<int, int>
29
+ #define VI vector<int>
30
+ #define FOR(i, x, y) for(int i=(x); i<(y); ++i)
31
+ #define F(x) for(int i=0; i<(x); ++i)
32
+ #define F1(x) for(int i=1; i<=(x); ++i)
33
+ #define FJ(x) for(int j=0; j<(x); ++j)
34
+ #define FJ1(x) for(int j=1; j<=(x); ++j)
35
+ #define FK(x) for(int k=0; k<=(x); ++k)
36
+ #define lson (u<<1)
37
+ #define rson (u<<1|1)
38
+ const int N=500005;
39
+ const int INF=0x3f3f3f3f;
40
+ //const int M=7+1e9;
41
+ inline int IN() {int x; scanf("%d", &x); return x;}
42
+ #define GET(x) int x=IN()
43
+ inline void OUT(int x) {printf("%d\n", x);}
44
+
45
+ int fst[N], nxt[N], from[N], to[N], w[N], h;
46
+ #define bian for(int i=fst[u]; ~i; i=nxt[i])
47
+ void jiabian(int u, int v, int x){
48
+ nxt[h]=fst[u], from[h]=u, to[h]=v, w[h]=x, fst[u]=h++;
49
+ }
50
+
51
+ int n, m;
52
+ int d[N], t[N][20], _t[N];
53
+ int fa[N][20];
54
+ VI ch[N];
55
+ vector<pair<int, int> > query;
56
+ int zuo[N];
57
+ int _root[N];
58
+
59
+ void dfs(int u, int f){
60
+ if(f==-1) fa[u][0]=u, d[u]=0;
61
+ else t[u][0]=_t[u], fa[u][0]=f, d[u]=d[f]+1;
62
+ F1(19) fa[u][i]=fa[fa[u][i-1]][i-1], t[u][i]=max(t[fa[u][i-1]][i-1], t[u][i-1]);
63
+ int sz=ch[u].size();
64
+ F(sz){
65
+ int v=ch[u][i];
66
+ dfs(v, u);
67
+ }
68
+ }
69
+
70
+ int get(int u, int d){
71
+ F(20) if(d&(1<<i)) u=fa[u][i];
72
+ return u;
73
+ }
74
+
75
+ int rmq(int u, int d){
76
+ int ret=-1;
77
+ F(20) if(d&(1<<i)) ret=max(ret, t[u][i]), u=fa[u][i];
78
+ return ret;
79
+ }
80
+
81
+ int main(){
82
+ //FILEIN
83
+ n=IN(), m=IN();
84
+ int T=0;
85
+ F(m){
86
+ int o=IN();
87
+ int x, y;
88
+ if(o==1){
89
+ x=IN(), y=IN();
90
+ _t[x]=T, ch[y].PB(x);
91
+ } else if(o==2){
92
+ int x=IN();
93
+ zuo[++T]=x;
94
+ } else{
95
+ int x=IN(), y=IN();
96
+ query.PB(MP(x, y));
97
+ }
98
+ }
99
+ F1(n) FJ(ch[i].size()) _root[ch[i][j]]=1;
100
+ F1(n) if(!_root[i]) ch[0].PB(i);
101
+ dfs(0, -1);
102
+ int sz=query.size();
103
+ F(sz){
104
+ int f=query[i].fi, u=zuo[query[i].se];
105
+ if(d[u]<d[f] || get(u, d[u]-d[f])!=f || rmq(u, d[u]-d[f])>=query[i].se)
106
+ puts("NO");
107
+ else puts("YES");
108
+ }
109
+ return 0;
110
+ }
code/train/C++/0001490_bip32_tests.cpp ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2013-2019 TurboCoin
2
+ // Distributed under the MIT software license, see the accompanying
3
+ // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
+
5
+ #include <boost/test/unit_test.hpp>
6
+
7
+ #include <key.h>
8
+ #include <key_io.h>
9
+ #include <uint256.h>
10
+ #include <util/system.h>
11
+ #include <util/strencodings.h>
12
+ #include <test/setup_common.h>
13
+
14
+ #include <string>
15
+ #include <vector>
16
+
17
+ struct TestDerivation {
18
+ std::string pub;
19
+ std::string prv;
20
+ unsigned int nChild;
21
+ };
22
+
23
+ struct TestVector {
24
+ std::string strHexMaster;
25
+ std::vector<TestDerivation> vDerive;
26
+
27
+ explicit TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
28
+
29
+ TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {
30
+ vDerive.push_back(TestDerivation());
31
+ TestDerivation &der = vDerive.back();
32
+ der.pub = pub;
33
+ der.prv = prv;
34
+ der.nChild = nChild;
35
+ return *this;
36
+ }
37
+ };
38
+
39
+ TestVector test1 =
40
+ TestVector("000102030405060708090a0b0c0d0e0f")
41
+ ("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
42
+ "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
43
+ 0x80000000)
44
+ ("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw",
45
+ "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
46
+ 1)
47
+ ("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ",
48
+ "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
49
+ 0x80000002)
50
+ ("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5",
51
+ "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
52
+ 2)
53
+ ("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV",
54
+ "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
55
+ 1000000000)
56
+ ("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy",
57
+ "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
58
+ 0);
59
+
60
+ TestVector test2 =
61
+ TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")
62
+ ("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
63
+ "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
64
+ 0)
65
+ ("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH",
66
+ "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
67
+ 0xFFFFFFFF)
68
+ ("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a",
69
+ "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
70
+ 1)
71
+ ("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
72
+ "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
73
+ 0xFFFFFFFE)
74
+ ("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
75
+ "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
76
+ 2)
77
+ ("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt",
78
+ "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
79
+ 0);
80
+
81
+ TestVector test3 =
82
+ TestVector("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be")
83
+ ("xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13",
84
+ "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6",
85
+ 0x80000000)
86
+ ("xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y",
87
+ "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
88
+ 0);
89
+
90
+ static void RunTest(const TestVector &test) {
91
+ std::vector<unsigned char> seed = ParseHex(test.strHexMaster);
92
+ CExtKey key;
93
+ CExtPubKey pubkey;
94
+ key.SetSeed(seed.data(), seed.size());
95
+ pubkey = key.Neuter();
96
+ for (const TestDerivation &derive : test.vDerive) {
97
+ unsigned char data[74];
98
+ key.Encode(data);
99
+ pubkey.Encode(data);
100
+
101
+ // Test private key
102
+ BOOST_CHECK(EncodeExtKey(key) == derive.prv);
103
+ BOOST_CHECK(DecodeExtKey(derive.prv) == key); //ensure a base58 decoded key also matches
104
+
105
+ // Test public key
106
+ BOOST_CHECK(EncodeExtPubKey(pubkey) == derive.pub);
107
+ BOOST_CHECK(DecodeExtPubKey(derive.pub) == pubkey); //ensure a base58 decoded pubkey also matches
108
+
109
+ // Derive new keys
110
+ CExtKey keyNew;
111
+ BOOST_CHECK(key.Derive(keyNew, derive.nChild));
112
+ CExtPubKey pubkeyNew = keyNew.Neuter();
113
+ if (!(derive.nChild & 0x80000000)) {
114
+ // Compare with public derivation
115
+ CExtPubKey pubkeyNew2;
116
+ BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));
117
+ BOOST_CHECK(pubkeyNew == pubkeyNew2);
118
+ }
119
+ key = keyNew;
120
+ pubkey = pubkeyNew;
121
+
122
+ CDataStream ssPub(SER_DISK, CLIENT_VERSION);
123
+ ssPub << pubkeyNew;
124
+ BOOST_CHECK(ssPub.size() == 75);
125
+
126
+ CDataStream ssPriv(SER_DISK, CLIENT_VERSION);
127
+ ssPriv << keyNew;
128
+ BOOST_CHECK(ssPriv.size() == 75);
129
+
130
+ CExtPubKey pubCheck;
131
+ CExtKey privCheck;
132
+ ssPub >> pubCheck;
133
+ ssPriv >> privCheck;
134
+
135
+ BOOST_CHECK(pubCheck == pubkeyNew);
136
+ BOOST_CHECK(privCheck == keyNew);
137
+ }
138
+ }
139
+
140
+ BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup)
141
+
142
+ BOOST_AUTO_TEST_CASE(bip32_test1) {
143
+ RunTest(test1);
144
+ }
145
+
146
+ BOOST_AUTO_TEST_CASE(bip32_test2) {
147
+ RunTest(test2);
148
+ }
149
+
150
+ BOOST_AUTO_TEST_CASE(bip32_test3) {
151
+ RunTest(test3);
152
+ }
153
+
154
+ BOOST_AUTO_TEST_SUITE_END()
code/train/C++/0002138_A.cpp ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This is a personal academic project. Dear PVS-Studio, please check it.
2
+ // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
3
+ // PVS-settings
4
+
5
+ // PVS-settings end
6
+ #include<iostream>
7
+ #include<vector>
8
+ #include<algorithm>
9
+
10
+ using namespace std;
11
+
12
+ int main()
13
+ {
14
+ int n, a, m;
15
+ cin >> n;
16
+ vector<pair<int, int> > arr(n);
17
+ for (int i = 0; i < n; ++i)
18
+ {
19
+ cin >> a;
20
+ arr[i] = make_pair(a, i + 1);
21
+ }
22
+ sort(arr.begin(), arr.end());
23
+ m = 2000000005;
24
+ for (int i = 1; i < n; ++i)
25
+ if (arr[i].first - arr[i - 1].first < m)
26
+ {
27
+ a = i;
28
+ m = arr[i].first - arr[i - 1].first;
29
+ }
30
+ cout << m << endl <<
31
+ ((arr[a - 1].second > arr[a].second) ? arr[a].second : arr[a - 1].second) << ' ' <<
32
+ ((arr[a - 1].second > arr[a].second) ? arr[a - 1].second : arr[a].second);
33
+ return 0;
34
+ }
code/train/C++/0002412_authmessagevalidator.cpp ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*****************************************************************************
2
+ * PokerTH - The open source texas holdem engine *
3
+ * Copyright (C) 2006-2012 Felix Hammer, Florian Thauer, Lothar May *
4
+ * *
5
+ * This program is free software: you can redistribute it and/or modify *
6
+ * it under the terms of the GNU Affero General Public License as *
7
+ * published by the Free Software Foundation, either version 3 of the *
8
+ * License, or (at your option) any later version. *
9
+ * *
10
+ * This program is distributed in the hope that it will be useful, *
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13
+ * GNU Affero General Public License for more details. *
14
+ * *
15
+ * You should have received a copy of the GNU Affero General Public License *
16
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
17
+ * *
18
+ * *
19
+ * Additional permission under GNU AGPL version 3 section 7 *
20
+ * *
21
+ * If you modify this program, or any covered work, by linking or *
22
+ * combining it with the OpenSSL project's OpenSSL library (or a *
23
+ * modified version of that library), containing parts covered by the *
24
+ * terms of the OpenSSL or SSLeay licenses, the authors of PokerTH *
25
+ * (Felix Hammer, Florian Thauer, Lothar May) grant you additional *
26
+ * permission to convey the resulting work. *
27
+ * Corresponding Source for a non-source form of such a combination *
28
+ * shall include the source code for the parts of OpenSSL used as well *
29
+ * as that of the covered work. *
30
+ *****************************************************************************/
31
+
32
+ #include <net/validation/authmessagevalidator.h>
33
+ #include <net/validation/validationhelper.h>
34
+
35
+ using namespace std;
36
+
37
+
38
+ AuthMessageValidator::AuthMessageValidator()
39
+ {
40
+ m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthClientRequestMessage, ValidateAuthClientRequestMessage));
41
+ m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthServerChallengeMessage, ValidateAuthServerChallengeMessage));
42
+ m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthClientResponseMessage, ValidateAuthClientResponseMessage));
43
+ m_validationMap.insert(make_pair(AuthMessage_AuthMessageType_Type_AuthServerVerificationMessage, ValidateAuthServerVerificationMessage));
44
+ }
45
+
46
+ bool
47
+ AuthMessageValidator::IsValidMessage(const AuthMessage &msg) const
48
+ {
49
+ // Default: Invalid packet.
50
+ bool retVal = false;
51
+ ValidateFunctorMap::const_iterator pos = m_validationMap.find(msg.messagetype());
52
+ if (pos != m_validationMap.end()) {
53
+ // Call validation functor.
54
+ retVal = pos->second(msg);
55
+ }
56
+ return retVal;
57
+ }
58
+
59
+ bool
60
+ AuthMessageValidator::ValidateAuthClientRequestMessage(const AuthMessage &msg)
61
+ {
62
+ bool retVal = false;
63
+ if (msg.has_authclientrequestmessage()) {
64
+ const AuthClientRequestMessage &request = msg.authclientrequestmessage();
65
+ if (VALIDATE_IS_UINT16(request.requestedversion().majorversion())
66
+ && VALIDATE_IS_UINT16(request.requestedversion().minorversion())
67
+ && (!request.has_mylastsessionid() || request.mylastsessionid().size() == 16)
68
+ && (!request.has_authserverpassword() || VALIDATE_STRING_SIZE(request.authserverpassword(), 1, 64))
69
+ && (!request.has_nickname() || VALIDATE_STRING_SIZE(request.nickname(), 1, 64))
70
+ && (!request.has_clientuserdata() || VALIDATE_STRING_SIZE(request.clientuserdata(), 1, 256))
71
+ && (!request.has_avatarhash() || request.avatarhash().size() == 16)) {
72
+
73
+ retVal = true;
74
+ }
75
+ }
76
+ return retVal;
77
+ }
78
+
79
+ bool
80
+ AuthMessageValidator::ValidateAuthServerChallengeMessage(const AuthMessage &msg)
81
+ {
82
+ bool retVal = false;
83
+ if (msg.has_authserverchallengemessage()) {
84
+ const AuthServerChallengeMessage &challenge = msg.authserverchallengemessage();
85
+ if (VALIDATE_STRING_SIZE(challenge.serverchallenge(), 1, 256)) {
86
+ retVal = true;
87
+ }
88
+ }
89
+ return retVal;
90
+ }
91
+
92
+ bool
93
+ AuthMessageValidator::ValidateAuthClientResponseMessage(const AuthMessage &msg)
94
+ {
95
+ bool retVal = false;
96
+ if (msg.has_authclientresponsemessage()) {
97
+ const AuthClientResponseMessage &response = msg.authclientresponsemessage();
98
+ if (VALIDATE_STRING_SIZE(response.clientresponse(), 1, 256)) {
99
+ retVal = true;
100
+ }
101
+ }
102
+ return retVal;
103
+ }
104
+
105
+ bool
106
+ AuthMessageValidator::ValidateAuthServerVerificationMessage(const AuthMessage &msg)
107
+ {
108
+ bool retVal = false;
109
+ if (msg.has_authserververificationmessage()) {
110
+ const AuthServerVerificationMessage &verification = msg.authserververificationmessage();
111
+ if (VALIDATE_STRING_SIZE(verification.serververification(), 1, 256)) {
112
+ retVal = true;
113
+ }
114
+ }
115
+ return retVal;
116
+ }
117
+
code/train/C++/0002530_AppMoblet.cpp ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2013 David Axmark
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ */
15
+
16
+ /**
17
+ * @file AppMoblet.cpp
18
+ * @author Bogdan Iusco
19
+ *
20
+ * AppMoblet class shows how to:
21
+ * - open and close contacts list.
22
+ * - create contact item.
23
+ * - remove contact item from the list.
24
+ */
25
+
26
+ // Minimum number of values for drag events.
27
+ #define MIN_DRAG_VALUES 5
28
+
29
+ #include <conprint.h>
30
+ #include <IX_PIM.h>
31
+ #include <maapi.h>
32
+
33
+ #include "AppMoblet.h"
34
+ #include "Util.h"
35
+ #include "PIMContact.h"
36
+
37
+ /**
38
+ * Constructor.
39
+ */
40
+ AppMoblet::AppMoblet() :
41
+ Moblet(),
42
+ mHandlePointerEvent(false)
43
+ {
44
+ this->startPIM();
45
+ }
46
+
47
+ /**
48
+ * Destructor.
49
+ */
50
+ AppMoblet::~AppMoblet()
51
+ {
52
+
53
+ }
54
+
55
+ /**
56
+ * This function is called with a coordinate when a pointer is moved.
57
+ */
58
+ void AppMoblet::pointerMoveEvent(MAPoint2d point)
59
+ {
60
+ if (mHandlePointerEvent)
61
+ {
62
+ mDragValues.add(point.x);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * This function is called with a coordinate when a pointer is released.
68
+ */
69
+ void AppMoblet::pointerReleaseEvent(MAPoint2d point)
70
+ {
71
+ // Handle this event only if no PIM action is on progress.
72
+ if (mHandlePointerEvent)
73
+ {
74
+ // Check if there are enough drag events for analysis.
75
+ if (MIN_DRAG_VALUES > mDragValues.size())
76
+ {
77
+ return;
78
+ }
79
+
80
+ // Check if drag is from left to right of from right to left.
81
+ bool dragFromLeftToRight = true;
82
+ bool dragFromRightToLeft = true;
83
+ int previousValue = mDragValues[0];
84
+ for (int i = 1; (i < mDragValues.size()) && (dragFromLeftToRight
85
+ || dragFromRightToLeft); i++)
86
+ {
87
+ int currentValue = mDragValues[i];
88
+ if (previousValue > currentValue)
89
+ {
90
+ dragFromLeftToRight = false;
91
+ }
92
+ if (previousValue < currentValue)
93
+ {
94
+ dragFromRightToLeft = false;
95
+ }
96
+
97
+ previousValue = currentValue;
98
+ }
99
+
100
+ // If drag is from left to right print the next contact, otherwise
101
+ // close the PIM contacts list.
102
+ if (dragFromLeftToRight)
103
+ {
104
+ this->printNextContact();
105
+ }
106
+ else if (dragFromRightToLeft)
107
+ {
108
+ this->closePIMContactsList();
109
+ }
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Called when the screen is touched.
115
+ */
116
+ void AppMoblet::pointerPressEvent(MAPoint2d point)
117
+ {
118
+ if (mHandlePointerEvent)
119
+ {
120
+ mDragValues.clear();
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Method called when a key is pressed.
126
+ */
127
+ void AppMoblet::keyPressEvent(int keyCode, int nativeCode)
128
+ {
129
+ // Close the application if the back key is pressed.
130
+ if(MAK_BACK == keyCode)
131
+ {
132
+ close();
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Start working with PIM.
138
+ * Add, modify and remove a PIM contact.
139
+ */
140
+ void AppMoblet::startPIM()
141
+ {
142
+ // Open PIM contacts list.
143
+ this->openPIMContactsList();
144
+
145
+ // Create new contact and add data into fields.
146
+ PIMContact* newContact = this->createContact();
147
+ if (NULL == newContact)
148
+ {
149
+ return;
150
+ }
151
+ newContact->addDataToContact();
152
+
153
+ // Modify the new contact.
154
+ this->modifyContact(newContact);
155
+
156
+ // Remove the new contact from the list and delete the object.
157
+ this->removeContact(newContact);
158
+ delete newContact;
159
+
160
+ // Print options on the screen and wait for drag events.
161
+ this->printInfo();
162
+ }
163
+
164
+ /**
165
+ * Open PIM contacts list.
166
+ */
167
+ void AppMoblet::openPIMContactsList()
168
+ {
169
+ printf("\n==============Open contacts list===============");
170
+
171
+ // Get a handle to the list of contacts.
172
+ mContactsListHandle = maPimListOpen(MA_PIM_CONTACTS);
173
+ checkResultCode(mContactsListHandle);
174
+ }
175
+
176
+ /**
177
+ * Print the next contact from the PIM contacts list.
178
+ */
179
+ void AppMoblet::printNextContact()
180
+ {
181
+ // Ignore all drag events handled by this moblet.
182
+ mHandlePointerEvent = false;
183
+
184
+ printf("\n=============Printing next contact=============\n");
185
+
186
+ // Get a hold on a contact item.
187
+ MAHandle pimItemHandle = maPimListNext(mContactsListHandle);
188
+
189
+ // Check if the new contact handle is valid.
190
+ if (0 < pimItemHandle)
191
+ {
192
+ // Create new contact item and print it on the screen.
193
+ PIMContact* item = new PIMContact(pimItemHandle);
194
+ item->printContact();
195
+ delete item;
196
+ }
197
+ else if (pimItemHandle == 0)
198
+ {
199
+ // Reached at the end of the list.
200
+ printf("The contacts list does not contain more items.");
201
+ }
202
+ else
203
+ {
204
+ // Print the error on the screen.
205
+ printResultCode(pimItemHandle);
206
+ }
207
+
208
+ // Print options on the screen and wait for drag events.
209
+ this->printInfo();
210
+ }
211
+
212
+ /**
213
+ * Create a new contact.
214
+ * @return The new created contact, or NULL in case of error.
215
+ * The ownership of the result is passed to the caller.
216
+ */
217
+ PIMContact* AppMoblet::createContact()
218
+ {
219
+ // Get a handle to the new created contact.
220
+ printf("\n==============Create new contact==============\n");
221
+ MAHandle newContantHandle = maPimItemCreate(mContactsListHandle);
222
+
223
+ // Check for errors.
224
+ if (0 > newContantHandle)
225
+ {
226
+ printf("Cann't create new contact.");
227
+ printResultCode(newContantHandle);
228
+ return NULL;
229
+ }
230
+
231
+ // Create and return the new contact.
232
+ PIMContact* newContact = new PIMContact(newContantHandle);
233
+ return newContact;
234
+ }
235
+
236
+ /**
237
+ * Modify the address field of a specified contact.
238
+ * Remove the first value from the phone field.
239
+ * @param contact The given contact item.
240
+ */
241
+ void AppMoblet::modifyContact(PIMContact* contact)
242
+ {
243
+ contact->modifyAddressField();
244
+
245
+ printf("\n====Remove field value from the new contact====\n");
246
+ contact->removeFieldValue(MA_PIM_FIELD_CONTACT_TEL, 0);
247
+ }
248
+
249
+ /**
250
+ * Remove a specified contact from the list.
251
+ * It also closes the item.
252
+ * @param contact The given contact item.
253
+ */
254
+ void AppMoblet::removeContact(PIMContact* contact)
255
+ {
256
+ printf("\n===========Remove the new contact=============\n");
257
+ int resultCode = maPimItemRemove(mContactsListHandle, contact->getHandle());
258
+ printResultCode(resultCode);
259
+ }
260
+
261
+ /**
262
+ * Close the PIM contacts list.
263
+ */
264
+ void AppMoblet::closePIMContactsList()
265
+ {
266
+ printf("\n ==============Close the contacts list=========\n");
267
+ printResultCode(maPimListClose(mContactsListHandle));
268
+
269
+ // Start again working with PIM>
270
+ this->startPIM();
271
+ }
272
+
273
+ /**
274
+ * Print show next contact / close pim list options on the screen.
275
+ */
276
+ void AppMoblet::printInfo()
277
+ {
278
+ printf("\n==============================================");
279
+ printf("Drag from left to right to show the next \n contact");
280
+ printf("Drag from right to left to close the contacts \n list");
281
+ printf("==============================================\n\n");
282
+
283
+ // Allow this moblet to handle pointer events.
284
+ mHandlePointerEvent = true;
285
+ }
code/train/C++/0002981_vcardmanager.cpp ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (c) 2006-2009 by Jakob Schroeter <js@camaya.net>
3
+ This file is part of the gloox library. http://camaya.net/gloox
4
+
5
+ This software is distributed under a license. The full license
6
+ agreement can be found in the file LICENSE in this distribution.
7
+ This software may not be copied, modified, sold or distributed
8
+ other than expressed in the named license agreement.
9
+
10
+ This software is distributed without any warranty.
11
+ */
12
+
13
+
14
+ #include "vcardmanager.h"
15
+ #include "vcardhandler.h"
16
+ #include "vcard.h"
17
+ #include "clientbase.h"
18
+ #include "disco.h"
19
+ #include "error.h"
20
+
21
+ namespace gloox
22
+ {
23
+
24
+ VCardManager::VCardManager( ClientBase* parent )
25
+ : m_parent( parent )
26
+ {
27
+ if( m_parent )
28
+ {
29
+ m_parent->registerIqHandler( this, ExtVCard );
30
+ m_parent->disco()->addFeature( XMLNS_VCARD_TEMP );
31
+ m_parent->registerStanzaExtension( new VCard() );
32
+ }
33
+ }
34
+
35
+ VCardManager::~VCardManager()
36
+ {
37
+ if( m_parent )
38
+ {
39
+ m_parent->disco()->removeFeature( XMLNS_VCARD_TEMP );
40
+ m_parent->removeIqHandler( this, ExtVCard );
41
+ m_parent->removeIDHandler( this );
42
+ }
43
+ }
44
+
45
+ void VCardManager::fetchVCard( const JID& jid, VCardHandler* vch )
46
+ {
47
+ if( !m_parent || !vch )
48
+ return;
49
+
50
+ TrackMap::const_iterator it = m_trackMap.find( jid.bare() );
51
+ if( it != m_trackMap.end() )
52
+ return;
53
+
54
+ const std::string& id = m_parent->getID();
55
+ IQ iq ( IQ::Get, jid, id );
56
+ iq.addExtension( new VCard() );
57
+
58
+ m_trackMap[id] = vch;
59
+ m_parent->send( iq, this,VCardHandler::FetchVCard );
60
+ }
61
+
62
+ void VCardManager::cancelVCardOperations( VCardHandler* vch )
63
+ {
64
+ TrackMap::iterator t;
65
+ TrackMap::iterator it = m_trackMap.begin();
66
+ while( it != m_trackMap.end() )
67
+ {
68
+ t = it;
69
+ ++it;
70
+ if( (*t).second == vch )
71
+ m_trackMap.erase( t );
72
+ }
73
+ }
74
+
75
+ void VCardManager::storeVCard( VCard* vcard, VCardHandler* vch )
76
+ {
77
+ if( !m_parent || !vch )
78
+ return;
79
+
80
+ const std::string& id = m_parent->getID();
81
+ IQ iq( IQ::Set, JID(), id );
82
+ iq.addExtension( vcard );
83
+
84
+ m_trackMap[id] = vch;
85
+ m_parent->send( iq, this, VCardHandler::StoreVCard );
86
+ }
87
+
88
+ void VCardManager::handleIqID( const IQ& iq, int context )
89
+ {
90
+ TrackMap::iterator it = m_trackMap.find( iq.id() );
91
+ if( it != m_trackMap.end() )
92
+ {
93
+ switch( iq.subtype() )
94
+ {
95
+ case IQ::Result:
96
+ {
97
+ switch( context )
98
+ {
99
+ case VCardHandler::FetchVCard:
100
+ {
101
+ const VCard* v = iq.findExtension<VCard>( ExtVCard );
102
+ (*it).second->handleVCard( iq.from(), v );
103
+ break;
104
+ }
105
+ case VCardHandler::StoreVCard:
106
+ (*it).second->handleVCardResult( VCardHandler::StoreVCard, iq.from() );
107
+ break;
108
+ }
109
+ }
110
+ break;
111
+ case IQ::Error:
112
+ {
113
+ (*it).second->handleVCardResult( (VCardHandler::VCardContext)context,
114
+ iq.from(),
115
+ iq.error() ? iq.error()->error()
116
+ : StanzaErrorUndefined );
117
+ break;
118
+ }
119
+ default:
120
+ break;
121
+ }
122
+
123
+ m_trackMap.erase( it );
124
+ }
125
+ }
126
+
127
+ }
code/train/C++/0003712_PEMer_Lite.cpp ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Name: saminput
3
+ Author: Lars Zerbe <larszerbe@live.de>
4
+ Author: Stephan Peter <s.peter@fu-berlin.de>
5
+ Maintainer: Lars Zerbe <larszerbe@live.de>
6
+ License: GPL v3
7
+ Copyright: 2008-2012, FU Berlin
8
+ Status: under development
9
+ */
10
+
11
+ #include "PEMer_Lite.h"
12
+
13
+
14
+ bool candidateSortFunction(candidate &x, candidate &y)
15
+ {
16
+ try{return (x.pos < y.pos);}
17
+ catch(std::exception allgemeineException){return false;}
18
+ }
19
+
20
+ int samSort(candidates &save)
21
+ {
22
+ std::cout << "samSort" << std::endl;
23
+ std::sort(save.begin(),save.end(),candidateSortFunction);
24
+
25
+ return 0;
26
+ }
27
+
28
+ seqan::ArgumentParser::ParseResult commands(modifier &options, int argc, char const ** argv)
29
+ {
30
+ std::cout << "Parser" << std::endl;
31
+ seqan::ArgumentParser parser("PEMer_Lite");
32
+
33
+ // Optionen hinzufügen
34
+ addOption(parser, seqan::ArgParseOption("i","input-file","Input SAM-file.",seqan::ArgParseArgument::INPUTFILE));
35
+ setValidValues(parser, "input-file", "sam");
36
+ setRequired(parser, "input-file");
37
+
38
+ addOption(parser,seqan::ArgParseOption("x","SD-variable", "Variable to use for multiples of standard degression.",seqan::ArgParseArgument::INTEGER, "INT"));
39
+ setMinValue(parser, "SD-variable", "1");
40
+ setDefaultValue(parser,"SD-variable","1");
41
+
42
+ addOption(parser,seqan::ArgParseOption("y","Del_SD-variable", "Variable to spezify multiples of standard degression for deletions.",seqan::ArgParseArgument::INTEGER, "INT"));
43
+ setMinValue(parser, "Del_SD-variable", "1");
44
+ setDefaultValue(parser,"Del_SD-variable","1");
45
+
46
+ addOption(parser,seqan::ArgParseOption("s","standard_degression", "Variable to use for standard degression for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT"));
47
+ setMinValue(parser, "standard_degression", "1");
48
+
49
+ addOption(parser,seqan::ArgParseOption("e","expected_value", "Variable to use for the expected value for length of fragments.",seqan::ArgParseArgument::INTEGER, "INT"));
50
+ setMinValue(parser, "expected_value", "1");
51
+
52
+ addOption(parser, seqan::ArgParseOption("p","Print", "Select to print temporary solutions."));
53
+
54
+ // verarbeitet die Kommandozeile
55
+ seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv);
56
+
57
+ // Überprüfung der richtigen Ausführung von commands()
58
+ if (res != seqan::ArgumentParser::PARSE_OK)
59
+ return res;
60
+
61
+ // extrahiert Werte aus der parser.
62
+ getOptionValue(options.x, parser, "SD-variable");
63
+ getOptionValue(options.y, parser, "Del_SD-variable");
64
+ getOptionValue(options.e, parser, "expected_value");
65
+ getOptionValue(options.sd, parser, "standard_degression");
66
+ options.p = isSet(parser, "Print");
67
+ getOptionValue(options.inputFile, parser, "input-file");
68
+
69
+ return seqan::ArgumentParser::PARSE_OK;
70
+ }
71
+
72
+ unsigned generateStandardDegression(candidates &input,int e_value) //erzeugt die Standartabweichung
73
+ {
74
+ std::cout << "SD" << std::endl;
75
+ unsigned standardDegression=0;
76
+
77
+ unsigned n = input.size();
78
+ for (unsigned i=0;i<n;i++)
79
+ {
80
+ standardDegression += (input[i].len-e_value)*(input[i].len-e_value);
81
+ }
82
+ standardDegression /= n;
83
+ standardDegression = (unsigned)sqrt((double)standardDegression);
84
+
85
+ return standardDegression;
86
+ }
87
+
88
+ int saminput(candidates &save, modifier &options, statisticals &stats) // impotiert eine SAM-Datei und speichert sie im Format candidates
89
+ {
90
+ std::cout << "Saminput" << std::endl;
91
+ candidate tmp;
92
+ medianTree median;
93
+
94
+ // BamStream öffnet Eingangsdatenstrom
95
+ seqan::BamStream SamInput(toCString(options.inputFile));
96
+ if (!isGood(SamInput))
97
+ {
98
+ std::cerr << "-ERROR- Could not open" << std::endl;
99
+ return 1;
100
+ }
101
+ /*
102
+ for (unsigned i = 0; i < length(SamInput.header.sequenceInfos); ++i)
103
+ {
104
+ header << SamInput.header.sequenceInfos[i].i1 << "\t" << SamInput.header.sequenceInfos[i].i2 << "\n";
105
+ }*/
106
+ // record enthält die inhalte aus einer SAM-Datei
107
+ seqan::BamAlignmentRecord record;
108
+
109
+ while (!atEnd(SamInput))
110
+ {
111
+ readRecord(record, SamInput);
112
+ if(record.tLen>0)
113
+ {
114
+ median.add(record.tLen);
115
+ std::cout << record.tLen << "\t" << median.getMedian() << std::endl;
116
+ tmp.addvalues(record.rID,record.beginPos,record.tLen,candidate::undefine);
117
+ save.push_back(tmp);
118
+ }
119
+ }
120
+ std::cout << options.e << std::endl;
121
+ if(options.e==0)
122
+ {
123
+ stats.e_value=median.getMedian();
124
+ }
125
+ else
126
+ {
127
+ stats.e_value=options.e;
128
+ }
129
+ if(options.sd==0)
130
+ {
131
+ stats.standardDegression=generateStandardDegression(save,stats.e_value);
132
+ }
133
+ else
134
+ {
135
+ stats.standardDegression=options.sd;
136
+ }
137
+
138
+ return 0;
139
+ }
140
+
141
+ int devide(candidates &input, candidates &result, modifier &options, statisticals &stats) // sucht nach insertions und deletions
142
+ {
143
+ std::cout << "devide\t" << stats.e_value << "\t" << stats.standardDegression << std::endl;
144
+ for (unsigned i=0;i<input.size();i++)
145
+ {
146
+ std::cout << input[i].len << " "<< (input[i].len>(stats.e_value+(options.y * stats.standardDegression))) << (input[i].len<(stats.e_value-(options.x * stats.standardDegression))) << std::endl;
147
+ bool second = (input[i].len>(stats.e_value+(options.y * stats.standardDegression)));
148
+ bool first = (input[i].len<(stats.e_value-(options.x * stats.standardDegression)));
149
+ if(first)
150
+ {
151
+ std::cout << "d" << std::endl;
152
+
153
+ //result.push_back(input[i]);
154
+ //result[i].type=candidate::deletion;
155
+ }
156
+ if(second)
157
+ {
158
+ std::cout << "i" << std::endl;
159
+ //result.push_back(input[i]);
160
+ //result[i].type=candidate::insertion;
161
+ }
162
+ }
163
+ std::cout << "devie_end" <<std::endl;
164
+ return 0;
165
+ }
166
+
167
+ int output(std::vector<std::vector<unsigned>> &input,candidates &ref, char *out)
168
+ {
169
+ std::cout << "out" << std::endl;
170
+ std::fstream outFile(out, std::ios::out);
171
+
172
+ if (!outFile)
173
+ {
174
+ std::cerr << "-ERROR- Could not open output file" << std::endl;
175
+ return 1;
176
+ }
177
+ else
178
+ {
179
+ outFile << "ID\tPOS\tLEN\tBegin\tEND\tTYPE " << std::endl;
180
+ if(!input.empty())
181
+ {
182
+ for (unsigned i=0;i<input.size();i++)
183
+ {
184
+ unsigned targetSize=0;
185
+ unsigned maxBegin=0;
186
+ unsigned minEnd=0;
187
+ unsigned n=input[i].size();
188
+
189
+ if(!input[i].empty())
190
+ {
191
+ for(auto j=input[i].begin();j != input[i].end();j++)
192
+ {
193
+ targetSize += ref[*j].len;
194
+
195
+ if(ref[*j].pos > maxBegin){maxBegin=ref[*j].pos;}
196
+ if((ref[*j].pos+ref[*j].len) < minEnd||minEnd==0){minEnd=(ref[*j].pos+ref[*j].len);}
197
+ }
198
+ }
199
+ if(n!=0)
200
+ {
201
+ targetSize /= n;
202
+
203
+ outFile << ref[0].ref << "\t" << (maxBegin+minEnd)/2<< "\t" << targetSize << "\t" << maxBegin << "\t" << minEnd << "\t" << (candidate::form)ref[0].type << std::endl;
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ outFile.close();
210
+
211
+ return 0;
212
+ }
213
+
214
+ int findCluster(candidates &input, std::vector<std::vector<unsigned> > &dest, candidate::form indel)
215
+ {
216
+ std::cout << "findCluster" << std::endl;
217
+ std::vector<unsigned> currentCluster;
218
+ unsigned currentClusterEndPos;
219
+
220
+ // Iterieren über alle Funde
221
+ for(unsigned i = 0; i < input.size(); ++i)
222
+ {
223
+ // Insertionen bzw. Deletionen herausfiltern
224
+ if(input[i].type == indel)
225
+ {
226
+ if(currentCluster.empty())
227
+ {
228
+ // ersten Fund zu bisher leerem ersten Cluster hinzufügen
229
+ currentCluster.push_back(i);
230
+ currentClusterEndPos = input[i].pos + input[i].len - 1;
231
+ }
232
+
233
+ else
234
+ {
235
+ // Fall 1: Fund liegt innerhalb der Grenzen eines vorherigen Fundes
236
+ if(input[i].pos + input[i].len - 1 <= currentClusterEndPos){
237
+ currentCluster.push_back(i);
238
+ }
239
+
240
+ else
241
+ {
242
+ unsigned overlapLen = std::max((int)(currentClusterEndPos - input[i].pos + 1), 0);
243
+
244
+ // Fall 2: Fund überlappt ausreichend mit dem Cluster
245
+ if(overlapLen / std::min(currentClusterEndPos - input[currentCluster.back()].pos + 1, input[i].pos + input[i].len - 1) > 0.5){
246
+ currentCluster.push_back(i);
247
+ }
248
+ // Fall 3: Fund überlappt nicht ausreichend mit dem Cluster
249
+ else
250
+ {
251
+ dest.push_back(currentCluster);
252
+ currentCluster.clear();
253
+ currentCluster.push_back(i);
254
+ }
255
+
256
+ currentClusterEndPos = input[i].pos + input[i].len - 1;
257
+ }
258
+
259
+ }
260
+ }
261
+ }
262
+
263
+ dest.push_back(currentCluster);
264
+
265
+ return 0;
266
+ }
267
+
code/train/C++/0003837_poj1852.cc ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include<iostream>
2
+ #include<algorithm>
3
+ #include<cstdio>
4
+ #include<cstdlib>
5
+ #include<vector>
6
+ #include<map>
7
+ #include<queue>
8
+ #include<set>
9
+ #include<stack>
10
+ #include<cctype>
11
+ #include<cstring>
12
+ #include<utility>
13
+ using namespace std;
14
+ const int inf=0x7fffffff;
15
+ int main()
16
+ {
17
+
18
+ #ifdef DEBUG
19
+ // freopen("in", "r", stdin);
20
+ // freopen("out", "w", stdout);
21
+ #endif
22
+ int KT;
23
+ scanf("%d",&KT);
24
+ while(KT--)
25
+ {
26
+ int n,num;
27
+ scanf("%d%d",&n,&num);
28
+ int best=0;
29
+ int worst=0;
30
+ int x;
31
+ while(num--)
32
+ {
33
+ scanf("%d",&x);
34
+ best=max(best,min(n-x,x));
35
+ worst=max(worst,max(n-x,x));
36
+ }
37
+ printf("%d %d\n",best
38
+ ,worst);
39
+ }
40
+
41
+
42
+ //insert code
43
+ return 0;
44
+ }
code/train/C++/0004781_heapSort.cpp ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Algorithm : Heap Sort
3
+ Refer : CLRS Chapter on heap sort
4
+ Author : manojpandey
5
+ */
6
+
7
+ #include <iostream>
8
+ #include <cstdio>
9
+ #include <string>
10
+ #include <utility> // pair
11
+ #include <vector>
12
+ #include <algorithm>
13
+ #include <cmath>
14
+ #include <cstring> //memset
15
+ using namespace std;
16
+
17
+ typedef vector<int> vi;
18
+ typedef vector<vi> vvi;
19
+ typedef pair<int,int> ii;
20
+ typedef long long ll;
21
+ #define sz(a) int((a).size())
22
+ #define pb push_back
23
+ #define all(c) (c).begin(),(c).end()
24
+ #define present(c,x) ((c).find(x) != (c).end())
25
+ #define cpresent(c,x) (find(all(c),x) != (c).end())
26
+ #define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
27
+ #define rep(i,n) for (i=0; i<n ; i++)
28
+ #define rep1(i,n) for (i=1; i<=n ; i++)
29
+ #define MAX 1111111
30
+
31
+ #define parent(i) (i/2)
32
+ #define left(i) (2*i)
33
+ #define right(i) (2*i)+1
34
+
35
+ int a[MAX];
36
+ int N, heapSize;
37
+
38
+
39
+ // Custom print function to
40
+ // print in the form of tree
41
+ void PRINT(int a[], int i) {
42
+
43
+ if(i<=N/2) {
44
+ for (int k = 1;k<=log2(2*i);k++)
45
+ cout << " |";
46
+ cout << a[2*i] << "\n";
47
+ PRINT(a, 2*i);
48
+ for (int k = 1;k<=log2(2*i+1);k++)
49
+ cout << " |";
50
+ cout << a[2*i+1] << "\n";
51
+ PRINT(a,2*i+1);
52
+ }
53
+ }
54
+
55
+ void maxHeapify(int a[], int i) {
56
+
57
+ int l, r, largest, j;
58
+
59
+ l = left(i);
60
+ r = right(i);
61
+ if(l <= heapSize && a[l] > a[i])
62
+ largest = l;
63
+ else largest = i;
64
+ if(r <= heapSize && a[r] > a[largest])
65
+ largest = r;
66
+ if(largest != i) {
67
+ swap(a[i], a[largest]);
68
+ maxHeapify(a, largest);
69
+ }
70
+ }
71
+
72
+ void buildMaxHeap(int a[]) {
73
+ for (int i = N/2 ; i >0 ; i--)
74
+ maxHeapify(a, i);
75
+ }
76
+
77
+ void HeapSort(int a[]) {
78
+ buildMaxHeap(a);
79
+ for (int i = N ; i > 1 ; i--) {
80
+ swap(a[1], a[i]);
81
+ heapSize--;
82
+ maxHeapify(a, 1);
83
+ }
84
+ }
85
+
86
+ int main() {
87
+
88
+ freopen ("in.txt", "r", stdin);
89
+ int i;
90
+ cin >> N;
91
+ heapSize = N;
92
+ rep1(i, N) cin >> a[i];
93
+ cout << "INPUT:\n";
94
+ cout << a[1] << "\n";
95
+ PRINT(a,1);
96
+
97
+ HeapSort(a);
98
+ cout << "OUTPUT:\n";
99
+ cout << a[1] << "\n";
100
+ PRINT(a,1);
101
+ return 0;
102
+ }
103
+
104
+ /*
105
+
106
+ 10
107
+ 4 1 3 2 16 9 10 14 8 7
108
+
109
+
110
+ INPUT:
111
+ 4
112
+ |1
113
+ | |2
114
+ | | |14
115
+ | | |8
116
+ | |16
117
+ | | |7
118
+ | | |0
119
+ |3
120
+ | |9
121
+ | |10
122
+ OUTPUT:
123
+ 1
124
+ |2
125
+ | |4
126
+ | | |10
127
+ | | |14
128
+ | |7
129
+ | | |16
130
+ | | |0
131
+ |3
132
+ | |8
133
+ | |9
134
+
135
+
136
+ */
code/train/C++/0004813_276A.cpp ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cstdio>
2
+ #include <algorithm>
3
+ #include <cstring>
4
+ #include <string>
5
+ #include <vector>
6
+ #include <queue>
7
+ #include <map>
8
+ #include <iostream>
9
+ #include <climits>
10
+ #include <set>
11
+ #include <cmath>
12
+ #define ll long long
13
+
14
+ using namespace std;
15
+
16
+ struct aa {
17
+ int x, y;
18
+ bool operator < (const aa &b) {return x < b.x;}
19
+ };
20
+
21
+ bool cmp(int a, int b) {return a > b;}
22
+ int bsearch(int *a, int n, int k);
23
+
24
+ int main() {
25
+ ll n, k, m = LLONG_MIN;
26
+ cin >> n >> k;
27
+ for (int i=0;i<n;i++) {
28
+ ll f, t;
29
+ cin >> f >> t;
30
+ if (t > k) m = max(m, f - (t - k));
31
+ else m = max(m, f);
32
+ }
33
+ cout << m;
34
+ return 0;
35
+ }
36
+
37
+ int bsearch(int *a, int n, int k) {
38
+ int l = 0, h = n;
39
+ while (l < h) {
40
+ int m = (l + h) / 2;
41
+ if (a[m] == k) return m;
42
+ else if (a[m] > k) h = m;
43
+ else l = m + 1;
44
+ }
45
+ return l;
46
+ }
code/train/C++/0005979_WorldRunnable.cpp ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
3
+ * Copyright (C) 2009-2010 MaNGOSZero <http://github.com/mangoszero/mangoszero/>
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation; either version 2 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program; if not, write to the Free Software
17
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
+ */
19
+
20
+ /** \file
21
+ \ingroup mangosd
22
+ */
23
+
24
+ #include "WorldSocketMgr.h"
25
+ #include "Common.h"
26
+ #include "World.h"
27
+ #include "WorldRunnable.h"
28
+ #include "Timer.h"
29
+ #include "ObjectAccessor.h"
30
+ #include "MapManager.h"
31
+ #include "BattleGroundMgr.h"
32
+
33
+ #include "Database/DatabaseEnv.h"
34
+
35
+ #ifdef WIN32
36
+ #define WORLD_SLEEP_CONST 50
37
+ #else
38
+ #define WORLD_SLEEP_CONST 100 //Is this still needed?? [On linux some time ago not working 50ms]
39
+ #endif
40
+
41
+ #ifdef WIN32
42
+ #include "ServiceWin32.h"
43
+ extern int m_ServiceStatus;
44
+ #endif
45
+
46
+ /// Heartbeat for the World
47
+ void WorldRunnable::run()
48
+ {
49
+ ///- Init new SQL thread for the world database
50
+ WorldDatabase.ThreadStart(); // let thread do safe mySQL requests (one connection call enough)
51
+ sWorld.InitResultQueue();
52
+
53
+ uint32 realCurrTime = 0;
54
+ uint32 realPrevTime = getMSTime();
55
+
56
+ uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST
57
+
58
+ ///- While we have not World::m_stopEvent, update the world
59
+ while (!World::IsStopped())
60
+ {
61
+ ++World::m_worldLoopCounter;
62
+ realCurrTime = getMSTime();
63
+
64
+ uint32 diff = getMSTimeDiff(realPrevTime,realCurrTime);
65
+
66
+ sWorld.Update( diff );
67
+ realPrevTime = realCurrTime;
68
+
69
+ // diff (D0) include time of previous sleep (d0) + tick time (t0)
70
+ // we want that next d1 + t1 == WORLD_SLEEP_CONST
71
+ // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement
72
+ // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0
73
+ if (diff <= WORLD_SLEEP_CONST+prevSleepTime)
74
+ {
75
+ prevSleepTime = WORLD_SLEEP_CONST+prevSleepTime-diff;
76
+ ACE_Based::Thread::Sleep(prevSleepTime);
77
+ }
78
+ else
79
+ prevSleepTime = 0;
80
+
81
+ #ifdef WIN32
82
+ if (m_ServiceStatus == 0) World::StopNow(SHUTDOWN_EXIT_CODE);
83
+ while (m_ServiceStatus == 2) Sleep(1000);
84
+ #endif
85
+ }
86
+
87
+ sWorld.KickAll(); // save and kick all players
88
+ sWorld.UpdateSessions( 1 ); // real players unload required UpdateSessions call
89
+
90
+ // unload battleground templates before different singletons destroyed
91
+ sBattleGroundMgr.DeleteAllBattleGrounds();
92
+
93
+ sWorldSocketMgr->StopNetwork();
94
+
95
+ sMapMgr.UnloadAll(); // unload all grids (including locked in memory)
96
+
97
+ ///- End the database thread
98
+ WorldDatabase.ThreadEnd(); // free mySQL thread resources
99
+ }
code/train/C++/0006023_SpecificPartialLoudnessGM.cpp ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2014 Dominic Ward <contactdominicward@gmail.com>
3
+ *
4
+ * This file is part of Loudness
5
+ *
6
+ * Loudness 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
+ * Loudness 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 Loudness. If not, see <http://www.gnu.org/licenses/>.
18
+ */
19
+
20
+ #include "SpecificPartialLoudnessGM.h"
21
+ #include "../Support/AuditoryTools.h"
22
+
23
+ namespace loudness{
24
+
25
+ SpecificPartialLoudnessGM::SpecificPartialLoudnessGM(bool ansiS3407) :
26
+ Module("SpecificPartialLoudnessGM"),
27
+ ansiS3407_(ansiS3407)
28
+ {}
29
+
30
+ SpecificPartialLoudnessGM::~SpecificPartialLoudnessGM() {}
31
+
32
+ bool SpecificPartialLoudnessGM::initializeInternal(const TrackBank &input)
33
+ {
34
+ if (input.getNTracks() % 2 != 0)
35
+ {
36
+ LOUDNESS_ERROR(name_ << ": TrackBank must have an even number of tracks");
37
+ }
38
+ //c value from ANSI 2007
39
+ cParam_ = 0.046871;
40
+ c2Param_ = 0.0000459608; // C_2 = C / (1.04 x 10^6)^0.5
41
+
42
+ Real eThrqdB500Hz = IntExc(500);
43
+
44
+ //Number of filters below 500Hz
45
+ nFiltersLT500_ = 0;
46
+
47
+ //fill loudness parameter vectors
48
+ Real fcPrev = input.getCentreFreq(0);
49
+ for(int i=0; i<input.getNChannels(); i++)
50
+ {
51
+ Real fc = input.getCentreFreq(i);
52
+
53
+ if(fc<fcPrev)
54
+ LOUDNESS_ERROR("SpecificPartialLoudnessGM: Centre frequencies are not in ascending order!");
55
+ fcPrev = fc;
56
+
57
+ Real eThrqdB = IntExc(fc);
58
+ if (fc < 500)
59
+ {
60
+ eThrqParam_.push_back(pow(10,eThrqdB/10.0));
61
+ nFiltersLT500_++;
62
+ }
63
+ else
64
+ {
65
+ eThrqParam_.push_back(pow(10,eThrqdB500Hz/10));
66
+ }
67
+
68
+ Real gdB = eThrqdB500Hz-eThrqdB;
69
+ k_.push_back(pow(10, kdB(fc)/10));
70
+ gParam_.push_back(pow(10, gdB/10.0));
71
+ aParam_.push_back(GdBToA(gdB));
72
+ alphaParam_.push_back(GdBToAlpha(gdB));
73
+ }
74
+ LOUDNESS_DEBUG("SpecificPartialLoudnessGM: number of filters <500 Hz: " << nFiltersLT500_);
75
+
76
+ //output TrackBank
77
+ output_.initialize(input.getNTracks() / 2, input.getNChannels(), input.getNSamples(), input.getFs());
78
+ output_.setCentreFreqs(input.getCentreFreqs());
79
+
80
+ return 1;
81
+ }
82
+
83
+ void SpecificPartialLoudnessGM::processInternal(const TrackBank &input)
84
+ {
85
+ Real eSig, eNoise, eThrn, sl, slSum, plSum, pl=0.0;
86
+ int masker, nTracks;
87
+
88
+ nTracks = input.getNTracks() / 2;
89
+
90
+ for (int target = 0; target < nTracks; target++)
91
+ {
92
+ slSum = 0;
93
+ plSum = 0;
94
+ masker = target + nTracks;
95
+ for(int freq = 0; freq < input.getNChannels(); freq++)
96
+ {
97
+ eSig = input.getSample(target, freq, 0);
98
+ eNoise = input.getSample(masker, freq, 0);
99
+ eThrn = k_[freq] * eNoise + eThrqParam_[freq];
100
+
101
+ // partial loudness calculation (the target signal in noise)
102
+ if (eSig + eNoise > 1e10)
103
+ {
104
+ if (eSig >= eThrqParam_[freq]) // equation 19 from Glasberg and Moore 1997
105
+ {
106
+ pl = c2Param_ * pow(eSig + eNoise, 0.5)
107
+ - c2Param_ * (pow((1 + k_[freq]) * eNoise + eThrqParam_[freq], 0.5)
108
+ - pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq])
109
+ + pow(aParam_[freq], alphaParam_[freq]))
110
+ * pow(eThrqParam_[freq] / eSig, 0.3);
111
+ }
112
+ else // equation 20 from Glasberg and Moore 1997
113
+ {
114
+ pl = cParam_
115
+ * pow(2 * eSig / (eSig + eThrqParam_[freq]), 1.5)
116
+ * ((pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq])
117
+ - pow(aParam_[freq], alphaParam_[freq]))
118
+ / (pow(eNoise * (1 + k_[freq]) + eThrqParam_[freq], 0.5) - pow(eNoise, 0.5)))
119
+ * (pow(eSig + eNoise, 0.5) - pow(eNoise, 0.5));
120
+ }
121
+ }
122
+ else // eSig + eNoise <= 1e10
123
+ {
124
+ if (eSig >= eThrn) // // equation 17 from Glasberg and Moore 1997
125
+ {
126
+ pl = cParam_ * (pow((eSig + eNoise) * gParam_[freq] + aParam_[freq], alphaParam_[freq])
127
+ - pow(aParam_[freq], alphaParam_[freq]))
128
+ - cParam_
129
+ * (pow((eNoise * (1 + k_[freq]) + eThrqParam_[freq]) * gParam_[freq] + aParam_[freq], alphaParam_[freq])
130
+ - pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq]))
131
+ * pow(eThrn / eSig, 0.3);
132
+ }
133
+ else // equation 18 from Glasberg and Moore 1997
134
+ {
135
+ pl = cParam_
136
+ * pow(2 * eSig / (eSig + eThrqParam_[freq]), 1.5)
137
+ * ((pow(eThrqParam_[freq] * gParam_[freq] + aParam_[freq], alphaParam_[freq])
138
+ - pow(aParam_[freq], alphaParam_[freq]))
139
+ / (pow(eNoise * (1 + k_[freq]) + eThrqParam_[freq], 0.5) - pow(eNoise, 0.5)));
140
+ }
141
+ }
142
+
143
+ // set partial loudness at output channel 1
144
+ output_.setSample(target, freq, 1, pl);
145
+ //plSum += pl;
146
+
147
+ // loudness calculation (the isolated target signal)
148
+ //high level
149
+ if (eSig > 1e10)
150
+ {
151
+ if(ansiS3407_)
152
+ sl = pow((eSig/1.0707),0.2);
153
+ else
154
+ sl = pow((eSig/1.04e6),0.5);
155
+ }
156
+ else if(freq<nFiltersLT500_) //low freqs
157
+ {
158
+ if(eSig>eThrqParam_[freq]) //medium level
159
+ {
160
+ sl = (pow(gParam_[freq]*eSig+aParam_[freq], alphaParam_[freq])-
161
+ pow(aParam_[freq],alphaParam_[freq]));
162
+ }
163
+ else //low level
164
+ {
165
+ sl = pow((2*eSig)/(eSig+eThrqParam_[freq]), 1.5)*
166
+ (pow(gParam_[freq]*eSig+aParam_[freq],alphaParam_[freq])
167
+ -pow(aParam_[freq],alphaParam_[freq]));
168
+ }
169
+ }
170
+ else //high freqs (variables are constant >= 500 Hz)
171
+ {
172
+ if(eSig>2.3604782331805771) //medium level
173
+ {
174
+ sl = pow(eSig+4.72096, 0.2)-1.3639739128330546;
175
+ }
176
+ else //low level
177
+ {
178
+ sl = pow((2*eSig)/(eSig+2.3604782331805771), 1.5)*
179
+ (pow(eSig+4.72096, 0.2)-1.3639739128330546);
180
+ }
181
+ }
182
+
183
+ // set loudness at output channel 0
184
+ output_.setSample(target, freq, 0, cParam_*sl);
185
+ //slSum += sl;
186
+ }
187
+ //output_.setSample(0, 0, 0, cParam_*slSum);
188
+ //output_.setSample(0, 0, 1, plSum);
189
+ }
190
+ }
191
+
192
+ void SpecificPartialLoudnessGM::resetInternal(){};
193
+ }
194
+
195
+
196
+
code/train/C++/0006349_XScaleBar.cpp ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* FTSPlot - fast time series dataset plotter
2
+ Copyright (C) 2013 Michael Riss <Michael.Riss@gmail.com>
3
+
4
+ This library is free software; you can redistribute it and/or
5
+ modify it under the terms of the GNU Lesser General Public
6
+ License as published by the Free Software Foundation; either
7
+ version 2.1 of the License, or (at your option) any later version.
8
+
9
+ This library 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 GNU
12
+ Lesser General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Lesser General Public
15
+ License along with this library; if not, write to the Free Software
16
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
17
+
18
+
19
+ #include <math.h>
20
+ #include "XScaleBar.h"
21
+
22
+ #define MAX(a,b) a<b?b:a
23
+
24
+ using namespace FTSPlot;
25
+
26
+ XScaleBar::XScaleBar( QWidget* parent )
27
+ : QGLWidget( parent )
28
+ {
29
+ qtminDeltaticks = 3;
30
+ Xcursor = 0;
31
+ Xscale = 1;
32
+ Xmax = 1;
33
+
34
+ fixedFont.setFamily( "fixed" );
35
+ fixedFont.setPointSize( 8 );
36
+ fixedFont.setStyleStrategy( QFont::OpenGLCompatible );
37
+ fixedFont.setStyleHint( QFont::TypeWriter );
38
+ fm = new QFontMetrics( fixedFont );
39
+ }
40
+
41
+ void XScaleBar::initializeGL()
42
+ {
43
+ glClearColor(1.0, 1.0, 1.0, 0.0);
44
+ glShadeModel(GL_FLAT);
45
+ glEnable( GL_LINE_SMOOTH );
46
+ glEnable( GL_BLEND );
47
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
48
+ glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
49
+ glLineWidth(1.0);
50
+ glDisable(GL_DEPTH_TEST);
51
+ }
52
+
53
+ void XScaleBar::resizeGL ( int width, int height )
54
+ {
55
+ this->width = width;
56
+ this->height = height;
57
+ glViewport(0, 0, (GLint)width, (GLint)height);
58
+ glMatrixMode ( GL_PROJECTION );
59
+ glLoadIdentity ();
60
+ gluOrtho2D( 0.0, (double) width, (double) height, 0 );
61
+ }
62
+
63
+ void XScaleBar::paintGL()
64
+ {
65
+ glClear ( GL_COLOR_BUFFER_BIT );
66
+
67
+ glColor3f ( 0.0, 0.0, 0.0 );
68
+ glLineWidth( 2.0 );
69
+ glBegin ( GL_LINES );
70
+ glVertex2d ( 0, 0 );
71
+ glVertex2d ( width, 0 );
72
+ glEnd();
73
+ glLineWidth( 1.0 );
74
+
75
+ // Draw tick marks
76
+ long double XDelta = Xscale * (double) width;
77
+ long double XMax = Xcursor + XDelta;
78
+ qtlabelbuffer = " " + QString::number( XMax, 'f', 0 );
79
+ int labelWidth = fm->width( qtlabelbuffer );
80
+ long double powerDueToLabel = ceill( log10l( XDelta / ( (long double) width / labelWidth ))) - 1;
81
+ long double power = MAX( 0, ceill( log10l( XDelta / ( (long double)width / (long double)qtminDeltaticks ) ) ) );
82
+ power = MAX( power, powerDueToLabel );
83
+ long double XStart = powl( 10, power ) * ceill( Xcursor / powl(10, power) );
84
+ long double XEnd = powl( 10, power ) * floorl( screen2data(width) / powl(10, power) );
85
+
86
+ glBegin ( GL_LINES );
87
+ for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power) )
88
+ {
89
+ glVertex2d( data2screen(idx), 0 );
90
+ glVertex2d( data2screen(idx), 5 );
91
+ }
92
+
93
+ XStart = powl( 10, power+1 ) * ceill( Xcursor / powl(10, power+1) ) - powl(10, power+1)/2.0 ;
94
+ if ( XStart < Xcursor )
95
+ {
96
+ XStart += powl(10, power+1);
97
+ }
98
+ XEnd = powl( 10, power+1 ) * floorl( screen2data(width) / powl(10, power+1) );
99
+ glBegin ( GL_LINES );
100
+ for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) )
101
+ {
102
+ glVertex2d( data2screen(idx), 0 );
103
+ glVertex2d( data2screen(idx), 8 );
104
+ }
105
+
106
+ XStart = powl( 10, power+1 ) * ceill( Xcursor / powl(10, power+1) );
107
+ XEnd = powl( 10, power+1 ) * floorl( screen2data(width) / powl(10, power+1) );
108
+ for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) )
109
+ {
110
+ glVertex2d( data2screen(idx), 0 );
111
+ glVertex2d( data2screen(idx), 10 );
112
+ }
113
+
114
+ glEnd();
115
+
116
+
117
+ for ( long double idx = XStart; idx <= XEnd; idx += powl(10, power+1) )
118
+ {
119
+ qtlabelbuffer = QString::number( idx, 'f', 0 );
120
+ renderText( data2screen(idx) - fm->width( qtlabelbuffer ) / 2, 20, qtlabelbuffer, fixedFont );
121
+ }
122
+
123
+ glFlush();
124
+ }
125
+
126
+ void XScaleBar::updateCoords( long double Xcursor, double Xscale )
127
+ {
128
+ this->Xcursor = Xcursor;
129
+ this->Xscale = Xscale;
130
+ this->makeCurrent();
131
+ update();
132
+ }
133
+
134
+ long double XScaleBar::screen2data( int screenCoord)
135
+ {
136
+ return Xcursor + (long double) screenCoord * (long double) Xscale;
137
+ }
138
+
139
+ int XScaleBar::data2screen( long double dataCoord )
140
+ {
141
+ return (int) ( ( (long double) dataCoord - Xcursor) / (long double) Xscale );
142
+ }
143
+
144
+ void XScaleBar::setNewXmin(long double Xmin)
145
+ {
146
+ this->Xmin = Xmin;
147
+ }
148
+
149
+ void XScaleBar::setNewXmax( long double Xmax )
150
+ {
151
+ this->Xmax = Xmax;
152
+
153
+ // Cached Calculations
154
+ stringstream buffer;
155
+ buffer << Xmax;
156
+
157
+ QString label;
158
+ label = QString::number( Xmax, 'f', 0 );
159
+ int qtlabelwidth = fm->width(label);
160
+ qtminDeltaticks = MAX( 3, ceill( qtlabelwidth / 10.0 ) );
161
+
162
+ update();
163
+ }
164
+
165
+ // kate: indent-mode cstyle; space-indent on; indent-width 0;
code/train/C++/0006416_TestStanfordCPPLib.cpp ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * File: TestStanfordCPPLib.cpp
3
+ * ----------------------------
4
+ * This file tests the C++ library packages used at Stanford.
5
+ */
6
+
7
+ /*************************************************************************/
8
+ /* Stanford Portable Library */
9
+ /* Copyright (c) 2014 by Eric Roberts <eroberts@cs.stanford.edu> */
10
+ /* */
11
+ /* This program is free software: you can redistribute it and/or modify */
12
+ /* it under the terms of the GNU General Public License as published by */
13
+ /* the Free Software Foundation, either version 3 of the License, or */
14
+ /* (at your option) any later version. */
15
+ /* */
16
+ /* This program is distributed in the hope that it will be useful, */
17
+ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
18
+ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
19
+ /* GNU General Public License for more details. */
20
+ /* */
21
+ /* You should have received a copy of the GNU General Public License */
22
+ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */
23
+ /*************************************************************************/
24
+
25
+ #include <iostream>
26
+ #include <string>
27
+ #include "console.h" // JL
28
+ #include "strlib.h"
29
+ #include "unittest.h"
30
+
31
+ using namespace std;
32
+
33
+ void testFilelibLibrary();
34
+ void testRandomLibrary();
35
+ void testSimpioLibrary();
36
+ void testStrlibLibrary();
37
+ void testDirectionType();
38
+ void testGraphClass();
39
+ void testGridClass();
40
+ void testHashMapClass();
41
+ void testHashSetClass();
42
+ void testLexiconClass();
43
+ void testMapClass();
44
+ void testPriorityQueueClass();
45
+ void testQueueClass();
46
+ void testSetClass();
47
+ void testStackClass();
48
+ void testTokenScannerClass();
49
+ void testVectorClass();
50
+ void testForeachStatement();
51
+
52
+ /*
53
+ * Type: TestEntry
54
+ * ---------------
55
+ * This structure associates a key with a test function.
56
+ */
57
+
58
+ struct TestEntry {
59
+ string name;
60
+ void (*fn)();
61
+ };
62
+
63
+ const TestEntry TESTS[] = {
64
+ { "fileliblibrary", testFilelibLibrary },
65
+ { "randomlibrary", testRandomLibrary },
66
+ { "simpiolibrary", testSimpioLibrary },
67
+ { "strliblibrary", testStrlibLibrary },
68
+ { "directiontype", testDirectionType },
69
+ { "graphclass", testGraphClass },
70
+ { "gridclass", testGridClass },
71
+ { "hashmapclass", testHashMapClass },
72
+ { "hashsetclass", testHashSetClass },
73
+ { "lexiconclass", testLexiconClass },
74
+ { "mapclass", testMapClass },
75
+ { "priorityqueueclass", testPriorityQueueClass },
76
+ { "queueclass", testQueueClass },
77
+ { "setclass", testSetClass },
78
+ { "stackclass", testStackClass },
79
+ { "tokenscannerclass", testTokenScannerClass },
80
+ { "vectorclass", testVectorClass },
81
+ { "foreachstatement", testForeachStatement }
82
+ };
83
+ const int N_TESTS = sizeof TESTS / sizeof TESTS[0];
84
+
85
+ int findTest(string key) {
86
+ int index = -1;
87
+ key = toLowerCase(key);
88
+ for (int i = 0; i < N_TESTS; i++) {
89
+ if (startsWith(TESTS[i].name, key)) {
90
+ if (index != -1) return -1;
91
+ index = i;
92
+ }
93
+ }
94
+ return index;
95
+ }
96
+
97
+ int main() {
98
+ setConsolePrintExceptions(true); // JL
99
+ int argc = getArgumentCount();
100
+ char **argv = getArguments();
101
+ int base = 1;
102
+ if (argc > 1 && startsWith("-verbose", argv[base])) {
103
+ setVerboseTestingFlag(true);
104
+ base++;
105
+ }
106
+ if (base == argc) {
107
+ for (int i = 0; i < N_TESTS; i++) {
108
+ TESTS[i].fn();
109
+ }
110
+ } else {
111
+ for (int i = base; i < argc; i++) {
112
+ int index = findTest(argv[i]);
113
+ if (index == -1) {
114
+ cout << "Unrecognized test: " << argv[i] << endl;
115
+ } else {
116
+ TESTS[index].fn();
117
+ }
118
+ }
119
+ }
120
+ return 0;
121
+ }
code/train/C++/0006687_instprofile.cpp ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**************************************************************************
2
+ *Copyright (C) 2003-2006 Intel Corporation
3
+ *
4
+ *This program is free software; you can redistribute it and/or
5
+ *modify it under the terms of the GNU General Public License
6
+ *as published by the Free Software Foundation; either version 2
7
+ *of the License, or (at your option) any later version.
8
+ *
9
+ *This program is distributed in the hope that it will be useful,
10
+ *but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ *GNU 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
+ */
18
+
19
+ //
20
+ // Author: Srilatha Manne
21
+ //
22
+
23
+ #include "asim/provides/inst_stats.h"
24
+
25
+ //
26
+ // PERINST_ENTRY
27
+ //
28
+
29
+ /**************************
30
+ * Constructor
31
+ **************************/
32
+
33
+
34
+ PERINST_ENTRY_CLASS::PERINST_ENTRY_CLASS(const char* des_str, UINT64 a) :
35
+ addr(a),
36
+ commHist(LAST_COUNTER),
37
+ noncommHist(LAST_COUNTER)
38
+ {
39
+
40
+ strncpy (des, des_str, 99);
41
+
42
+ //
43
+ // Initialize row names. We will register the stats at the end because
44
+ // that's the only time we'll have a ASIM_REGISTRY object with which to
45
+ // register the stats.
46
+ commHist.RowNames(PERINST_COUNTER_STRING);
47
+ noncommHist.RowNames(PERINST_COUNTER_STRING);
48
+ }
49
+
50
+ /**************************
51
+ * Stats Registration
52
+ **************************/
53
+
54
+ void
55
+ PERINST_ENTRY_CLASS::RegisterEntry(ASIM_REGISTRY reg)
56
+ {
57
+ // Register stats
58
+ // Convert the address to a string.
59
+ ostringstream os1, os2;
60
+ if (ENABLE_INST_PROFILE == 2)
61
+ {
62
+ os1 << "Committed_" << hex << addr;
63
+ os2 << "NonCommitted_" << hex << addr;
64
+ }
65
+ else if (ENABLE_INST_PROFILE == 1 || ENABLE_INST_PROFILE == 0)
66
+ {
67
+ os1 << "Committed_" << des;
68
+ os2 << "NonCommitted_" << des;
69
+ }
70
+ else
71
+ {
72
+ ASSERTX("Unknown instruction profile type.");
73
+ }
74
+
75
+ // cout << "Address: " << os.str() << endl;
76
+
77
+ reg->RegisterState(&commHist, os1.str().c_str(), des);
78
+ reg->RegisterState(&noncommHist, os2.str().c_str(), des);
79
+
80
+ // Update the histogram with the correct data.
81
+ for (UINT32 i = 0; i < LAST_COUNTER; i++)
82
+ {
83
+ commHist.AddEvent(i, 0, commInst.Get((PERINST_COUNTER)i));
84
+ noncommHist.AddEvent(i, 0, noncommInst.Get((PERINST_COUNTER)i));
85
+ }
86
+ }
87
+
88
+ //
89
+ // PERINST_PAGE
90
+ //
91
+
92
+ /**************************
93
+ * Destructor
94
+ **************************/
95
+ PERINST_PAGE_CLASS::~PERINST_PAGE_CLASS()
96
+ {
97
+ /*
98
+ for (UINT32 i = 0; i < ENTRIES_PER_PAGE; i++)
99
+ {
100
+ if (page[i] != NULL)
101
+ {
102
+ delete page[i];
103
+ }
104
+ }
105
+ */
106
+ }
107
+
108
+
109
+ /**************************
110
+ * Update information for an instruction.
111
+ **************************/
112
+
113
+ void
114
+ PERINST_PAGE_CLASS::UpdateInst(const UINT64 addr,
115
+ const char *inst_name,
116
+ const PERINST_STATS_CLASS &ifs,
117
+ bool commit)
118
+ {
119
+ UINT64 offset = addr - pageAddr;
120
+
121
+ // cout << "Updating instruction, Addr: " << addr << ", offset: " << offset << endl;
122
+
123
+ ASSERTX(offset < ENTRIES_PER_PAGE);
124
+ if (page[offset] == NULL)
125
+ {
126
+ //
127
+ // Null pointer, which means first time inst is seen.
128
+ page[offset] = new PERINST_ENTRY_CLASS(inst_name, addr);
129
+ UINT32 n = numInst++;
130
+ if (n > MAX_NUM_INSTS)
131
+ {
132
+ VERIFY(false, "Exceeding maximum number of static inst: 100000\n");
133
+ }
134
+ }
135
+ //
136
+ // Update
137
+ ASSERTX(page[offset]->GetAddr() == addr);
138
+
139
+ page[offset]->UpdateInst(ifs, commit);
140
+ }
141
+
142
+ /**************************
143
+ * Register stats for a page
144
+ **************************/
145
+ //
146
+ // Register a page of stats.
147
+ void
148
+ PERINST_PAGE_CLASS::RegisterPage(ASIM_REGISTRY reg)
149
+ {
150
+ for (UINT32 i = 0; i < ENTRIES_PER_PAGE; i++)
151
+ {
152
+ if (page[i] != NULL)
153
+ {
154
+ // cout << "Registering page" << endl;
155
+ page[i]->RegisterEntry(reg);
156
+ }
157
+ }
158
+ }
159
+
160
+
161
+
162
+ //
163
+ // PERINST_CACHE
164
+ //
165
+
166
+ /**************************
167
+ * Destructor
168
+ **************************/
169
+
170
+ PERINST_CACHE_CLASS::~PERINST_CACHE_CLASS()
171
+ {
172
+ STAT_CACHE::iterator i = statCache.begin();
173
+ STAT_CACHE::iterator prev;
174
+
175
+ while (i != statCache.end())
176
+ {
177
+ delete (*i).second;
178
+ prev = i;
179
+ ++i;
180
+ statCache.erase(prev);
181
+ }
182
+ }
183
+
184
+ /**************************
185
+ * Update stats
186
+ **************************/
187
+
188
+ void
189
+ PERINST_CACHE_CLASS::UpdateStats(UINT64 addr,
190
+ const char* name,
191
+ const PERINST_STATS_CLASS& ifs,
192
+ bool commit)
193
+ {
194
+
195
+ PERINST_PAGE page;
196
+
197
+ //
198
+ // Update per-inst stats.
199
+ //
200
+ if (lastPage &&
201
+ (addr & (~((1 << LOG2_ENTRIES_PER_PAGE) - 1)))==lastPage->PageAddr())
202
+ {
203
+ // cout << "Using lastpage" << endl;
204
+ page = lastPage;
205
+ }
206
+ else
207
+ {
208
+ STAT_CACHE::iterator i = statCache.find((addr >> LOG2_ENTRIES_PER_PAGE));
209
+ if (i != statCache.end()) {
210
+ page = (*i).second;
211
+ lastPage = page;
212
+ // cout << "Finding page in stat cache" << endl;
213
+ }
214
+ else
215
+ {
216
+ //
217
+ // Page doesn't currently exist.
218
+ //
219
+ UINT64 page_addr = addr & (~((1 << LOG2_ENTRIES_PER_PAGE) - 1));
220
+ page = new PERINST_PAGE_CLASS(page_addr);
221
+ // cout << "Creating new page" << endl;
222
+ //
223
+ // Place new page into cache
224
+ //
225
+ statCache[(addr >> LOG2_ENTRIES_PER_PAGE)] = page;
226
+ lastPage = page;
227
+ }
228
+ }
229
+ // Update stats per address
230
+ page->UpdateInst(addr, name, ifs, commit);
231
+ }
232
+
233
+ /**************************
234
+ * Register stats
235
+ **************************/
236
+ void
237
+ PERINST_CACHE_CLASS::RegisterPerinstStats(ASIM_REGISTRY reg)
238
+ {
239
+ STAT_CACHE::iterator i = statCache.begin();
240
+ while (i != statCache.end())
241
+ {
242
+ // cout << "Registering page: " << i << endl;
243
+ (*i).second->RegisterPage(reg);
244
+ ++i;
245
+ }
246
+ }
247
+
code/train/C++/0006795_testscore.ex3.cpp ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This program will read in a group of test scores (positive integers
2
+ // from 1 to 100) from the keyboard and then calculates and outputs
3
+ // the average score as well as the highest and lowest score.
4
+ // There will be a maximum of 100 scores.
5
+ //
6
+ // ** This version is designed to take file input from 'gradfile.txt'
7
+ // instead of from stdin **
8
+ //
9
+ // Walter B. Vaughan
10
+
11
+ #include <iostream>
12
+ #include <fstream>
13
+ #include <limits> // for limits
14
+ using namespace std;
15
+
16
+ typedef int GradeType[100]; // declares a new data type:
17
+ // an integer array of 100 elements
18
+
19
+ float findAverage( const GradeType, int ); // finds average of all grades
20
+ int findHighest( const GradeType, int ); // finds highest of all grades
21
+ int findLowest( const GradeType, int ); // finds lowest of all grades
22
+
23
+ int main() {
24
+ GradeType grades; // the array holding the grades.
25
+ int numberOfGrades; // the number of grades read.
26
+ int pos; // index to the array.
27
+
28
+ float avgOfGrades; // contains the average of the grades.
29
+ int highestGrade; // contains the highest grade.
30
+ int lowestGrade; // contains the lowest grade.
31
+
32
+ ifstream f ("gradfile.txt");
33
+
34
+ // Read in the values into the array
35
+ pos = 0;
36
+ while ( pos < 100 and f.good() ) {
37
+ f >> grades[pos];
38
+ pos++;
39
+ }
40
+ pos--; // truncate the size to ignore end of array (-99 or bounds error)
41
+
42
+ if ( pos == -1 ) {
43
+ std::cerr << "**Error Opening 'gradfile.txt'**";
44
+ return 1; // error value returned
45
+ }
46
+
47
+ numberOfGrades = pos; // Fill blank with appropriate identifier
48
+
49
+ // call to the function to find average
50
+ avgOfGrades = findAverage( grades, numberOfGrades );
51
+
52
+ cout << endl << "The average of all the grades is " << avgOfGrades << endl;
53
+
54
+ // Fill in the call to the function that calculates highest grade
55
+ highestGrade = findHighest( grades, numberOfGrades );
56
+
57
+ cout << endl << "The highest grade is " << highestGrade << endl;
58
+
59
+ // Fill in the call to the function that calculates lowest grade
60
+ lowestGrade = findLowest( grades, numberOfGrades );
61
+
62
+ // Fill in code to write the lowest to the screen
63
+ cout << endl << "The lowest grade is " << lowestGrade << endl;
64
+
65
+ return 0;
66
+ }
67
+
68
+
69
+ //******************************************************************************
70
+ // findAverage
71
+ //
72
+ // task: This function receives an array of integers and its size.
73
+ // It finds and returns the average of the numbers in the array
74
+ // data in: array of floating point numbers
75
+ // data returned: avarage of the numbers in the array
76
+ //
77
+ //******************************************************************************
78
+ float findAverage( const GradeType array, int size ) {
79
+ float sum = 0; // holds the sum of all the numbers
80
+
81
+ for (int pos = 0; pos < size; pos++)
82
+ sum = sum + array[pos];
83
+
84
+ return (sum / size); //returns the average
85
+ }
86
+
87
+
88
+ //******************************************************************************
89
+ // findHighest
90
+ //
91
+ // task: This function receives an array of integers and its size.
92
+ // It finds and returns the highest value of the numbers in
93
+ // the array
94
+ // data in: array of floating point numbers
95
+ // data returned: highest value of the numbers in the array
96
+ //
97
+ //******************************************************************************
98
+ int findHighest( const GradeType array, int size ) {
99
+ // Fill in the code for this function
100
+ int max = std::numeric_limits<int>::min(); // start with lowest int
101
+
102
+ if ( size == 0 ) {
103
+ std::cerr << "Note: Empty grade list given, INT_MIN returned";
104
+ }
105
+
106
+ for ( int i = 0 ; i < size ; i++ )
107
+ if ( array[i] > max)
108
+ max = array[i];
109
+
110
+ return max;
111
+ }
112
+
113
+
114
+ //******************************************************************************
115
+ // findLowest
116
+ //
117
+ // task: This function receives an array of integers and its size.
118
+ // It finds and returns the lowest value of the numbers in
119
+ // the array
120
+ // data in: array of floating point numbers
121
+ // data returned: lowest value of the numbers in the array
122
+ //
123
+ //******************************************************************************
124
+ int findLowest( const GradeType array, int size ) {
125
+ // Fill in the code for this function
126
+ int min = std::numeric_limits<int>::max(); // start with largest int
127
+
128
+ if ( size == 0 ) {
129
+ std::cerr << "Note: Empty grade list given, INT_MAX returned";
130
+ }
131
+
132
+ for ( int i = 0 ; i < size ; i++ )
133
+ if ( array[i] < min)
134
+ min = array[i];
135
+
136
+ return min;
137
+ }
code/train/C++/0006861_sqldb.cpp ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ////////////////////////////////////////////////////////////////////////////
2
+ // SQL Database MMF Extension
3
+ // (c) 2004-2005, Jim St. Jean
4
+ //
5
+ // SQL DB wrapper utilities source file
6
+ //
7
+ // The file provides wrapper routines to the MMF extension so, for
8
+ // example, the underlying SQLite implementation can be swapped or changed
9
+ // to be encrypted etc.
10
+ //
11
+ ////////////////////////////////////////////////////////////////////////////
12
+
13
+
14
+ // Database engine wrapper
15
+ #include "sqldb.h"
16
+ #include "common.h"
17
+
18
+ ////////////////////////////////////////////////////////////////////////////////
19
+ // Prototypes for SQLite functions not included in SQLite DLL, but copied below
20
+ // from SQLite encode.c
21
+ ////////////////////////////////////////////////////////////////////////////////
22
+ int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out);
23
+ int sqlite3_decode_binary(const unsigned char *in, unsigned char *out);
24
+
25
+
26
+ /*
27
+ ** A function to open a new sqlite database.
28
+ **
29
+ */
30
+ sqldb *sqldb_open(const char *filename, char **errmsg)
31
+ {
32
+ sqldb *db;
33
+ if (SQLITE_OK != sqlite3_open(filename, &db)) {
34
+ // get error message
35
+ strcpy(*errmsg,sqlite3_errmsg(db));
36
+ }
37
+ return db;
38
+ }
39
+
40
+ /*
41
+ ** A function to close the database.
42
+ **
43
+ */
44
+ void sqldb_close(sqldb *db)
45
+ {
46
+ sqlite3_close(db);
47
+ }
48
+
49
+ /*
50
+ ** The following routine
51
+ ** returns the integer key of the most recent insert in the database.
52
+ */
53
+ int sqldb_last_insert_rowid(sqldb *db)
54
+ {
55
+ return sqlite3_last_insert_rowid(db);
56
+ }
57
+
58
+ /*
59
+ ** This function returns the number of database rows that were changed
60
+ ** (or inserted or deleted) by the most recent called sqlite_exec().
61
+ **
62
+ */
63
+ int sqldb_changes(sqldb *db)
64
+ {
65
+ return sqlite3_changes(db);
66
+ }
67
+
68
+ /*
69
+ ** This next routine is really just a wrapper around sqlite_exec().
70
+ ** Instead of invoking a user-supplied callback for each row of the
71
+ ** result, this routine remembers each row of the result in memory
72
+ ** obtained from malloc(), then returns all of the result after the
73
+ ** query has finished.
74
+ **
75
+ */
76
+ int sqldb_get_table(
77
+ sqldb* db, /* An open database */
78
+ const char *sql, /* SQL to be executed */
79
+ char ***resultp, /* Result written to a char *[] that this points to */
80
+ int *nrow, /* Number of result rows written here */
81
+ int *ncolumn, /* Number of result columns written here */
82
+ char **errmsg /* Error msg written here */
83
+ )
84
+ {
85
+ return sqlite3_get_table(
86
+ db, /* An open database */
87
+ sql, /* SQL to be executed */
88
+ resultp, /* Result written to a char *[] that this points to */
89
+ nrow, /* Number of result rows written here */
90
+ ncolumn, /* Number of result columns written here */
91
+ errmsg /* Error msg written here */
92
+ );
93
+ }
94
+
95
+ /*
96
+ ** Call this routine to free the memory that sqlite_get_table() allocated.
97
+ */
98
+ void sqldb_free_table(char **result)
99
+ {
100
+ sqlite3_free_table(result);
101
+ }
102
+
103
+
104
+ /*
105
+ ** Windows systems should call this routine to free memory that
106
+ ** is returned in the in the errmsg parameter of sqlite_open() when
107
+ ** SQLite is a DLL. For some reason, it does not work to call free()
108
+ ** directly.
109
+ **
110
+ ** As of sqlite3, this is no longer needed! Still provided for backwards compatibility...
111
+ */
112
+ void sqldb_freemem(void *p)
113
+ {
114
+ //sqlite_freemem(p);
115
+ }
116
+
117
+
118
+ /*
119
+ ** Encode a binary buffer "in" of size n bytes so that it contains
120
+ ** no instances of characters '\'' or '\000'. The output is
121
+ ** null-terminated and can be used as a string value in an INSERT
122
+ ** or UPDATE statement. Use sqlite_decode_binary() to convert the
123
+ ** string back into its original binary.
124
+ **
125
+ */
126
+ int sqldb_encode_binary(const unsigned char *in, int n, unsigned char *out)
127
+ {
128
+ return sqlite3_encode_binary(in, n, out);
129
+ }
130
+
131
+ /*
132
+ ** Decode the string "in" into binary data and write it into "out".
133
+ ** This routine reverses the encoding created by sqlite_encode_binary().
134
+ ** The output will always be a few bytes less than the input. The number
135
+ ** of bytes of output is returned. If the input is not a well-formed
136
+ ** encoding, -1 is returned.
137
+ **
138
+ */
139
+ int sqldb_decode_binary(const unsigned char *in, unsigned char *out)
140
+ {
141
+ return sqlite3_decode_binary(in, out);
142
+ }
143
+
144
+ ////////////////////////////////////////////////////////////////////////////////
145
+ // SQLite encode.c reproduced here, containing implementation notes and source
146
+ // for sqlite3_encode_binary() and sqlite3_decode_binary()
147
+ ////////////////////////////////////////////////////////////////////////////////
148
+
149
+ /*
150
+ ** 2002 April 25
151
+ **
152
+ ** The author disclaims copyright to this source code. In place of
153
+ ** a legal notice, here is a blessing:
154
+ **
155
+ ** May you do good and not evil.
156
+ ** May you find forgiveness for yourself and forgive others.
157
+ ** May you share freely, never taking more than you give.
158
+ **
159
+ *************************************************************************
160
+ ** This file contains helper routines used to translate binary data into
161
+ ** a null-terminated string (suitable for use in SQLite) and back again.
162
+ ** These are convenience routines for use by people who want to store binary
163
+ ** data in an SQLite database. The code in this file is not used by any other
164
+ ** part of the SQLite library.
165
+ **
166
+ ** $Id: encode.c,v 1.10 2004/01/14 21:59:23 drh Exp $
167
+ */
168
+
169
+ /*
170
+ ** How This Encoder Works
171
+ **
172
+ ** The output is allowed to contain any character except 0x27 (') and
173
+ ** 0x00. This is accomplished by using an escape character to encode
174
+ ** 0x27 and 0x00 as a two-byte sequence. The escape character is always
175
+ ** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
176
+ ** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally,
177
+ ** the escape character itself is encoded as the two-character sequence
178
+ ** 0x01 0x02.
179
+ **
180
+ ** To summarize, the encoder works by using an escape sequences as follows:
181
+ **
182
+ ** 0x00 -> 0x01 0x01
183
+ ** 0x01 -> 0x01 0x02
184
+ ** 0x27 -> 0x01 0x03
185
+ **
186
+ ** If that were all the encoder did, it would work, but in certain cases
187
+ ** it could double the size of the encoded string. For example, to
188
+ ** encode a string of 100 0x27 characters would require 100 instances of
189
+ ** the 0x01 0x03 escape sequence resulting in a 200-character output.
190
+ ** We would prefer to keep the size of the encoded string smaller than
191
+ ** this.
192
+ **
193
+ ** To minimize the encoding size, we first add a fixed offset value to each
194
+ ** byte in the sequence. The addition is modulo 256. (That is to say, if
195
+ ** the sum of the original character value and the offset exceeds 256, then
196
+ ** the higher order bits are truncated.) The offset is chosen to minimize
197
+ ** the number of characters in the string that need to be escaped. For
198
+ ** example, in the case above where the string was composed of 100 0x27
199
+ ** characters, the offset might be 0x01. Each of the 0x27 characters would
200
+ ** then be converted into an 0x28 character which would not need to be
201
+ ** escaped at all and so the 100 character input string would be converted
202
+ ** into just 100 characters of output. Actually 101 characters of output -
203
+ ** we have to record the offset used as the first byte in the sequence so
204
+ ** that the string can be decoded. Since the offset value is stored as
205
+ ** part of the output string and the output string is not allowed to contain
206
+ ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
207
+ **
208
+ ** Here, then, are the encoding steps:
209
+ **
210
+ ** (1) Choose an offset value and make it the first character of
211
+ ** output.
212
+ **
213
+ ** (2) Copy each input character into the output buffer, one by
214
+ ** one, adding the offset value as you copy.
215
+ **
216
+ ** (3) If the value of an input character plus offset is 0x00, replace
217
+ ** that one character by the two-character sequence 0x01 0x01.
218
+ ** If the sum is 0x01, replace it with 0x01 0x02. If the sum
219
+ ** is 0x27, replace it with 0x01 0x03.
220
+ **
221
+ ** (4) Put a 0x00 terminator at the end of the output.
222
+ **
223
+ ** Decoding is obvious:
224
+ **
225
+ ** (5) Copy encoded characters except the first into the decode
226
+ ** buffer. Set the first encoded character aside for use as
227
+ ** the offset in step 7 below.
228
+ **
229
+ ** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
230
+ ** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27.
231
+ **
232
+ ** (7) Subtract the offset value that was the first character of
233
+ ** the encoded buffer from all characters in the output buffer.
234
+ **
235
+ ** The only tricky part is step (1) - how to compute an offset value to
236
+ ** minimize the size of the output buffer. This is accomplished by testing
237
+ ** all offset values and picking the one that results in the fewest number
238
+ ** of escapes. To do that, we first scan the entire input and count the
239
+ ** number of occurances of each character value in the input. Suppose
240
+ ** the number of 0x00 characters is N(0), the number of occurances of 0x01
241
+ ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
242
+ ** An offset of 0 is not allowed so we don't have to test it. The number
243
+ ** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
244
+ ** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
245
+ ** In this way we find the offset that gives the minimum number of escapes,
246
+ ** and thus minimizes the length of the output string.
247
+ */
248
+
249
+ /*
250
+ ** Encode a binary buffer "in" of size n bytes so that it contains
251
+ ** no instances of characters '\'' or '\000'. The output is
252
+ ** null-terminated and can be used as a string value in an INSERT
253
+ ** or UPDATE statement. Use sqlite3_decode_binary() to convert the
254
+ ** string back into its original binary.
255
+ **
256
+ ** The result is written into a preallocated output buffer "out".
257
+ ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
258
+ ** In other words, the output will be expanded by as much as 3
259
+ ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
260
+ ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
261
+ **
262
+ ** The return value is the number of characters in the encoded
263
+ ** string, excluding the "\000" terminator.
264
+ */
265
+ int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){
266
+ int i, j, e, m;
267
+ int cnt[256];
268
+ if( n<=0 ){
269
+ out[0] = 'x';
270
+ out[1] = 0;
271
+ return 1;
272
+ }
273
+ memset(cnt, 0, sizeof(cnt));
274
+ for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
275
+ m = n;
276
+ for(i=1; i<256; i++){
277
+ int sum;
278
+ if( i=='\'' ) continue;
279
+ sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
280
+ if( sum<m ){
281
+ m = sum;
282
+ e = i;
283
+ if( m==0 ) break;
284
+ }
285
+ }
286
+ out[0] = e;
287
+ j = 1;
288
+ for(i=0; i<n; i++){
289
+ int c = (in[i] - e)&0xff;
290
+ if( c==0 ){
291
+ out[j++] = 1;
292
+ out[j++] = 1;
293
+ }else if( c==1 ){
294
+ out[j++] = 1;
295
+ out[j++] = 2;
296
+ }else if( c=='\'' ){
297
+ out[j++] = 1;
298
+ out[j++] = 3;
299
+ }else{
300
+ out[j++] = c;
301
+ }
302
+ }
303
+ out[j] = 0;
304
+ return j;
305
+ }
306
+
307
+ /*
308
+ ** Decode the string "in" into binary data and write it into "out".
309
+ ** This routine reverses the encoding created by sqlite3_encode_binary().
310
+ ** The output will always be a few bytes less than the input. The number
311
+ ** of bytes of output is returned. If the input is not a well-formed
312
+ ** encoding, -1 is returned.
313
+ **
314
+ ** The "in" and "out" parameters may point to the same buffer in order
315
+ ** to decode a string in place.
316
+ */
317
+ int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){
318
+ int i, c, e;
319
+ e = *(in++);
320
+ i = 0;
321
+ while( (c = *(in++))!=0 ){
322
+ if( c==1 ){
323
+ c = *(in++);
324
+ if( c==1 ){
325
+ c = 0;
326
+ }else if( c==2 ){
327
+ c = 1;
328
+ }else if( c==3 ){
329
+ c = '\'';
330
+ }else{
331
+ return -1;
332
+ }
333
+ }
334
+ out[i++] = (c + e)&0xff;
335
+ }
336
+ return i;
337
+ }
338
+
code/train/C++/0007941_solution.cpp ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../common.h"
2
+
3
+ class Solution
4
+ {
5
+ public:
6
+ int maxProfit(const vector<int> &prices)
7
+ {
8
+ if (prices.size() <= 1)
9
+ {
10
+ return 0;
11
+ }
12
+ int result = prices[1] - prices[0];
13
+ int last = result;
14
+ for (int i = 2; i < prices.size(); i++)
15
+ {
16
+ int diff = prices[i] - prices[i - 1];
17
+ last = last > 0 ? last + diff : diff;
18
+ result = max(result, last);
19
+ }
20
+ return result > 0 ? result : 0;
21
+ }
22
+ };
code/train/C++/0008009_FoxAndDoraemon.cpp ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <algorithm>
2
+ #include <cassert>
3
+ #include <cstdio>
4
+ #include <cstdlib>
5
+ #include <cstring>
6
+ #include <ctime>
7
+ #include <iostream>
8
+ #include <sstream>
9
+ #include <string>
10
+ #include <vector>
11
+ #include <functional>
12
+
13
+ using namespace std;
14
+
15
+ vector<int> W;
16
+ int C;
17
+ bool can(int T) {
18
+ long long foxes = 1;
19
+ int cur = 0;
20
+ for (int i=0; i<(int)W.size(); ++i) {
21
+ if (foxes==0 || cur+W[i]>T) {
22
+ return false;
23
+ }
24
+ int nsplits = (T-cur-W[i])/C;
25
+ while (i+foxes<(int)W.size() && nsplits--) {
26
+ foxes <<= 1;
27
+ cur += C;
28
+ }
29
+ assert(cur + W[i] <= T);
30
+ --foxes;
31
+ }
32
+ return true;
33
+ }
34
+ class FoxAndDoraemon {
35
+ public:
36
+ int minTime(vector <int> workCost, int splitCost) {
37
+ W = workCost;
38
+ sort(W.begin(), W.end(), greater<int>());
39
+ C = splitCost;
40
+ int lo = 1;
41
+ int hi = 2;
42
+ while (!can(hi)) {
43
+ lo = hi + 1;
44
+ hi <<= 1;
45
+ }
46
+
47
+ while (lo < hi) {
48
+ int mid = lo + (hi-lo)/2;
49
+ if (can(mid)) {
50
+ hi = mid;
51
+ } else {
52
+ lo = mid + 1;
53
+ }
54
+ }
55
+ return lo;
56
+ }
57
+ };
code/train/C++/0008879_IPCWorkerThread.cpp ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Free RIL implementation for Samsung Android-based smartphones.
3
+ * Copyright (C) 2012 Sergey Gridasov <grindars@gmail.com>
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include <stdio.h>
20
+ #include <unistd.h>
21
+
22
+ #include "IPCWorkerThread.h"
23
+ #include "IIPCTransport.h"
24
+ #include "IIPCSocket.h"
25
+ #include "SocketHandler.h"
26
+ #include "Log.h"
27
+ #include "IPCSocketHandler.h"
28
+
29
+ using namespace SamsungIPC;
30
+
31
+ IPCWorkerThread::IPCWorkerThread() {
32
+ if(pipe(m_controlPipe) == -1)
33
+ Log::panicErrno("pipe");
34
+ }
35
+
36
+ IPCWorkerThread::~IPCWorkerThread() {
37
+ close(m_controlPipe[0]);
38
+ close(m_controlPipe[1]);
39
+ }
40
+
41
+ int IPCWorkerThread::run() {
42
+ dispatchEvents();
43
+
44
+ for(std::list<SocketHandler *>::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) {
45
+ delete *it;
46
+ }
47
+
48
+ return 0;
49
+ }
50
+
51
+ void IPCWorkerThread::addHandler(SocketHandler *handler) {
52
+ m_handlers.push_back(handler);
53
+ }
54
+
55
+ void IPCWorkerThread::removeHandler(SocketHandler *handler) {
56
+ m_handlers.remove(handler);
57
+ }
58
+
59
+ void IPCWorkerThread::dispatchEvents() {
60
+ while(1) {
61
+ int maxfd = 0;
62
+ fd_set read_set, write_set;
63
+
64
+ for(std::list<SocketHandler *>::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) {
65
+ SocketHandler *handler = *it;
66
+ int fd = handler->fd();
67
+
68
+ maxfd = std::max<int>(maxfd, fd);
69
+
70
+ if(handler->wantRead())
71
+ FD_SET(fd, &read_set);
72
+
73
+ if(handler->wantWrite())
74
+ FD_SET(fd, &write_set);
75
+ }
76
+
77
+ FD_SET(m_controlPipe[0], &read_set);
78
+
79
+ int ret = select(maxfd + 1, &read_set, &write_set, NULL, NULL);
80
+
81
+ if(ret == -1)
82
+ Log::panicErrno("select");
83
+
84
+ for(std::list<SocketHandler *>::iterator it = m_handlers.begin(), end = m_handlers.end(); it != end; it++) {
85
+ SocketHandler *handler = *it;
86
+ int fd = handler->fd();
87
+
88
+ if(FD_ISSET(fd, &read_set))
89
+ handler->readable();
90
+
91
+ if(FD_ISSET(fd, &write_set))
92
+ handler->writable();
93
+ }
94
+
95
+ if(FD_ISSET(m_controlPipe[0], &read_set)) {
96
+ Message *msg;
97
+
98
+ int bytes = read(m_controlPipe[0], &msg, sizeof(msg));
99
+ if(bytes == -1)
100
+ Log::panicErrno("read(controlPipe)");
101
+
102
+ if(msg == NULL) {
103
+ Log::info("Shutdown requested");
104
+
105
+ break;
106
+ } else {
107
+ static_cast<IPCSocketHandler *>(m_handlers.front())->submit(msg);
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ void IPCWorkerThread::submit(Message *message) {
114
+ int bytes = write(m_controlPipe[1], &message, sizeof(message));
115
+
116
+ if(bytes != sizeof(message))
117
+ Log::panicErrno("write(controlPipe)");
118
+ }
119
+
code/train/C++/0009074_cafToggleItemsOnOthersOffFeature.cpp ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //##################################################################################################
2
+ //
3
+ // Custom Visualization Core library
4
+ // Copyright (C) 2019- Ceetron Solutions AS
5
+ //
6
+ // This library may be used under the terms of either the GNU General Public License or
7
+ // the GNU Lesser General Public License as follows:
8
+ //
9
+ // GNU General Public License Usage
10
+ // This library is free software: you can redistribute it and/or modify
11
+ // it under the terms of the GNU General Public License as published by
12
+ // the Free Software Foundation, either version 3 of the License, or
13
+ // (at your option) any later version.
14
+ //
15
+ // This library is distributed in the hope that it will be useful, but WITHOUT ANY
16
+ // WARRANTY; without even the implied warranty of MERCHANTABILITY or
17
+ // FITNESS FOR A PARTICULAR PURPOSE.
18
+ //
19
+ // See the GNU General Public License at <<http://www.gnu.org/licenses/gpl.html>>
20
+ // for more details.
21
+ //
22
+ // GNU Lesser General Public License Usage
23
+ // This library is free software; you can redistribute it and/or modify
24
+ // it under the terms of the GNU Lesser General Public License as published by
25
+ // the Free Software Foundation; either version 2.1 of the License, or
26
+ // (at your option) any later version.
27
+ //
28
+ // This library is distributed in the hope that it will be useful, but WITHOUT ANY
29
+ // WARRANTY; without even the implied warranty of MERCHANTABILITY or
30
+ // FITNESS FOR A PARTICULAR PURPOSE.
31
+ //
32
+ // See the GNU Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
33
+ // for more details.
34
+ //
35
+ //##################################################################################################
36
+
37
+ #include "cafToggleItemsOnOthersOffFeature.h"
38
+
39
+ #include "cafToggleItemsFeatureImpl.h"
40
+
41
+ #include "cafSelectionManager.h"
42
+
43
+ #include "cafPdmObject.h"
44
+ #include "cafPdmObjectHandle.h"
45
+ #include "cafPdmUiItem.h"
46
+ #include <QAction>
47
+
48
+ namespace caf
49
+ {
50
+ CAF_CMD_SOURCE_INIT( ToggleItemsOnOthersOffFeature, "cafToggleItemsOnOthersOffFeature" );
51
+
52
+ //--------------------------------------------------------------------------------------------------
53
+ ///
54
+ //--------------------------------------------------------------------------------------------------
55
+ bool ToggleItemsOnOthersOffFeature::isCommandEnabled()
56
+ {
57
+ std::vector<caf::PdmObject*> selectedObjects;
58
+ caf::SelectionManager::instance()->objectsByType( &selectedObjects );
59
+
60
+ caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects );
61
+ std::vector<caf::PdmObjectHandle*> children = childObjects( commonParent );
62
+
63
+ return commonParent != nullptr && children.size() > 0 && objectToggleField( children.front() ) &&
64
+ children.size() > selectedObjects.size();
65
+ }
66
+
67
+ //--------------------------------------------------------------------------------------------------
68
+ ///
69
+ //--------------------------------------------------------------------------------------------------
70
+ void ToggleItemsOnOthersOffFeature::onActionTriggered( bool isChecked )
71
+ {
72
+ std::vector<caf::PdmObject*> selectedObjects;
73
+ caf::SelectionManager::instance()->objectsByType( &selectedObjects );
74
+
75
+ // First toggle off all siblings
76
+
77
+ caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects );
78
+
79
+ for ( caf::PdmObjectHandle* child : childObjects( commonParent ) )
80
+ {
81
+ caf::PdmField<bool>* field = objectToggleField( child );
82
+
83
+ if ( field )
84
+ {
85
+ field->setValueWithFieldChanged( false );
86
+ }
87
+ }
88
+
89
+ // Then toggle on the selected item(s)
90
+ for ( caf::PdmObject* selectedObject : selectedObjects )
91
+ {
92
+ caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>( selectedObject->objectToggleField() );
93
+
94
+ field->setValueWithFieldChanged( true );
95
+ }
96
+ }
97
+
98
+ //--------------------------------------------------------------------------------------------------
99
+ ///
100
+ //--------------------------------------------------------------------------------------------------
101
+ void ToggleItemsOnOthersOffFeature::setupActionLook( QAction* actionToSetup )
102
+ {
103
+ actionToSetup->setText( "On - Others Off" );
104
+
105
+ actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOnOthersOffL16x16.png" ) );
106
+ }
107
+
108
+ //--------------------------------------------------------------------------------------------------
109
+ ///
110
+ //--------------------------------------------------------------------------------------------------
111
+ caf::PdmFieldHandle*
112
+ ToggleItemsOnOthersOffFeature::verifySameParentForSelection( const std::vector<caf::PdmObject*>& selection )
113
+ {
114
+ caf::PdmFieldHandle* sameParent = nullptr;
115
+
116
+ for ( caf::PdmObject* obj : selection )
117
+ {
118
+ caf::PdmFieldHandle* parent = obj->parentField();
119
+ if ( parent )
120
+ {
121
+ if ( !sameParent )
122
+ {
123
+ sameParent = parent;
124
+ }
125
+ else if ( parent != sameParent )
126
+ {
127
+ // Different parents detected
128
+
129
+ return nullptr;
130
+ }
131
+ }
132
+ }
133
+ return sameParent;
134
+ }
135
+
136
+ //--------------------------------------------------------------------------------------------------
137
+ ///
138
+ //--------------------------------------------------------------------------------------------------
139
+ std::vector<caf::PdmObjectHandle*> ToggleItemsOnOthersOffFeature::childObjects( caf::PdmFieldHandle* parent )
140
+ {
141
+ std::vector<caf::PdmObjectHandle*> children;
142
+ if ( parent )
143
+ {
144
+ parent->childObjects( &children );
145
+ }
146
+ return children;
147
+ }
148
+
149
+ //--------------------------------------------------------------------------------------------------
150
+ ///
151
+ //--------------------------------------------------------------------------------------------------
152
+ caf::PdmField<bool>* ToggleItemsOnOthersOffFeature::objectToggleField( caf::PdmObjectHandle* objectHandle )
153
+ {
154
+ caf::PdmUiObjectHandle* childUiObject = uiObj( objectHandle );
155
+ if ( childUiObject && childUiObject->objectToggleField() )
156
+ {
157
+ return dynamic_cast<caf::PdmField<bool>*>( childUiObject->objectToggleField() );
158
+ }
159
+ return nullptr;
160
+ }
161
+
162
+ } // namespace caf
code/train/C++/0009203_PathTransform.cpp ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (C) 2011 Róbert Vašek <gman@codefreax.org>
3
+
4
+ This file is part of fsync.
5
+
6
+ fsync 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
+ fsync 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 fsync. If not, see <http://www.gnu.org/licenses/>.
18
+ */
19
+
20
+ #include <cstring>
21
+ #include <iostream>
22
+ #include <boost/lexical_cast.hpp>
23
+ #include "PathTransform.h"
24
+ #include "LogManager.h"
25
+ #include "defs.h"
26
+
27
+ using namespace std;
28
+ using namespace boost::filesystem;
29
+
30
+ path PathTransform::getPath(PathId id)
31
+ {
32
+ for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++)
33
+ {
34
+ if (i->first == id)
35
+ {
36
+ if (id >= 0)
37
+ return i->second;
38
+ else
39
+ {
40
+ path parentPath = getPath(id * -1);
41
+ parentPath /= i->second;
42
+
43
+ return parentPath;
44
+ }
45
+ }
46
+ }
47
+
48
+ return path();
49
+ }
50
+
51
+ PathId PathTransform::getPathId(const path & p)
52
+ {
53
+ for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++)
54
+ {
55
+ if (i->second == p)
56
+ return i->first;
57
+ }
58
+
59
+ return 0;
60
+ }
61
+
62
+ bool PathTransform::checkPathAndLog(const path & p, PathId pathId)
63
+ {
64
+ if (strlen(p.c_str()) == 0)
65
+ {
66
+ string errMsg = "Path with id ";
67
+ errMsg += boost::lexical_cast<string>(pathId);
68
+ errMsg += " is not defined, skipping";
69
+ LogManager::getInstancePtr()->log(errMsg, LogManager::L_WARNING);
70
+
71
+ return false;
72
+ }
73
+
74
+ return true;
75
+ }
76
+
77
+ void PathTransform::cutPath(PathId pathId, const char * pth, char * outPath)
78
+ {
79
+ path p = getPath(pathId);
80
+ strcpy(outPath, (pth + strlen(p.c_str()) + 1)); // +1 because of the directory separator
81
+ }
82
+
83
+ path PathTransform::glueCutPath(PathId pathId, const char * p)
84
+ {
85
+ return getPath(pathId) / p;
86
+ }
87
+
88
+ PathList PathTransform::getIncludingPaths()
89
+ {
90
+ PathList pl;
91
+
92
+ for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++)
93
+ {
94
+ if (i->first >= 0)
95
+ pl.push_back(i->second);
96
+ }
97
+
98
+ return pl;
99
+ }
100
+
101
+ PathList PathTransform::getExcludingPaths()
102
+ {
103
+ PathList pl;
104
+
105
+ for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++)
106
+ {
107
+ PathId id = i->first;
108
+
109
+ if (id < 0)
110
+ {
111
+ path parentPath = getPath(id * -1);
112
+ parentPath /= i->second;
113
+
114
+ pl.push_back(parentPath);
115
+ }
116
+ }
117
+
118
+ return pl;
119
+ }
120
+
121
+ bool PathTransform::isExcluded(const path & currentPath, PathId pathId)
122
+ {
123
+ vector<path> absoluteExcldPaths;
124
+ path parentPath = getPath(pathId);
125
+ PathId excldPathId = pathId * -1;
126
+
127
+ for (ID_Path_pairList::const_iterator i = m_id_path_pairList.begin(); i != m_id_path_pairList.end(); i++)
128
+ {
129
+ if (i->first == excldPathId)
130
+ absoluteExcldPaths.push_back(parentPath / i->second);
131
+ }
132
+
133
+ if (absoluteExcldPaths.empty())
134
+ return false;
135
+
136
+ vector<string> currentPathParts = makeParts(currentPath);
137
+ int currentPartsSize = currentPathParts.size();
138
+
139
+ for (vector<path>::const_iterator i = absoluteExcldPaths.begin(); i != absoluteExcldPaths.end(); i++)
140
+ {
141
+ vector<string> absoluteExcldParts = makeParts(*i);
142
+ int excldPartsSize = absoluteExcldParts.size();
143
+
144
+ if (currentPartsSize < excldPartsSize)
145
+ continue;
146
+
147
+ bool isExcluded = true;
148
+
149
+ for (int j = 0; j < excldPartsSize; j++)
150
+ {
151
+ if (currentPathParts[j] != absoluteExcldParts[j])
152
+ {
153
+ isExcluded = false;
154
+ break;
155
+ }
156
+ }
157
+
158
+ if (isExcluded)
159
+ return true;
160
+ }
161
+
162
+ return false;
163
+ }
164
+
165
+ vector<string> PathTransform::makeParts(const path & p) const
166
+ {
167
+ vector<string> parts;
168
+
169
+ for (path::const_iterator i = p.begin(); i != p.end(); i++)
170
+ parts.push_back(i->string());
171
+
172
+ return parts;
173
+ }
174
+
175
+ path PathTransform::operator[](PathId id)
176
+ {
177
+ return getPath(id);
178
+ }
code/train/C++/0009912_zonedessin.cpp ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "zonedessin.h"
2
+
3
+ zoneDessin::zoneDessin(QRect geometry, QWidget *parent):QWidget(parent)
4
+ {
5
+ setGeometry(geometry);
6
+ setStyleSheet("background-color: white;");
7
+ }
8
+
9
+ void zoneDessin::spectre()
10
+ {
11
+ donnees.clear();
12
+ valMax=0;
13
+ //int hz=info.retourFrequenceI();
14
+ QFile file(info.retourChemin());
15
+ tailleFichier=file.size()-44;
16
+ if(file.open(QFile::ReadOnly)){
17
+ QByteArray data=file.readAll();
18
+ QDataStream analyse(&data,QIODevice::ReadOnly);
19
+
20
+ //Passer les metadonnées
21
+ if(info.retourExtension()=="wav"){
22
+ analyse.setByteOrder(QDataStream::LittleEndian);
23
+ char meta[44];
24
+ analyse.readRawData(meta,44);
25
+ }
26
+
27
+ if(info.retourExtension()=="aif" || info.retourExtension()=="aiff"){
28
+ analyse.setByteOrder(QDataStream::BigEndian);
29
+ char meta[28];
30
+ analyse.readRawData(meta,28);
31
+ }
32
+
33
+ //int saut=(tailleFichier/width())+info.retourEchantillonageI();
34
+ int saut=info.retourEchantillonageI();
35
+ //char SData[16];
36
+ char sautDonnees[saut];
37
+ qint16 don;
38
+ int x=0;
39
+ while(!analyse.atEnd()){
40
+ //analyse.readRawData(SData,16);
41
+ //donnees[x]=QString::fromLatin1(SData).toInt();
42
+ analyse>>don;
43
+ donnees<<don;
44
+ if(donnees[x]>valMax)
45
+ valMax=donnees[x];
46
+ analyse.readRawData(sautDonnees,saut);
47
+ x++;
48
+ }
49
+ /*for(int x=0;x<10000;x++)
50
+ donnees.removeLast();*/
51
+
52
+ //Mise à l'échelle
53
+ valMax-=10;
54
+ for(int x=0;x<donnees.length();x++){
55
+ donnees[x]=(donnees[x]*height()/2)/valMax;
56
+ if(donnees[x]<0)
57
+ donnees[x]*=(-1);
58
+ if(donnees[x]==0)
59
+ donnees[x]=height()/2;
60
+ else donnees[x]+=height()/2;
61
+ }
62
+ }
63
+ update();
64
+ }
65
+
66
+ void zoneDessin::paintEvent(QPaintEvent *event)
67
+ {
68
+ //Permettre l'utilisation de StyleSheet
69
+ QStyleOption opt;
70
+ opt.init(this);
71
+ QPainter p(this);
72
+ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
73
+
74
+ //Créer le painter
75
+ QPainter painter(this);
76
+ painter.setRenderHint(QPainter::Antialiasing);
77
+ painter.setPen(pen);
78
+ pen.setWidth(2);
79
+ painter.drawLine(0,height()/2,width(),height()/2);
80
+ pen.setWidth(1);
81
+ pen.setColor(Qt::black);
82
+ //Vidage de la liste
83
+ for(int x=0;x<width();x++){
84
+ courbe<<height()/2;
85
+ }
86
+ //Création de la courbe
87
+ int posX=0;
88
+ int moy=donnees.length()/width();
89
+ for(int x=0;posX<width();x+=moy){
90
+ int temp=0;
91
+ for(int y=0;y<moy;y++)
92
+ if(x+y<donnees.length())
93
+ temp+=donnees[x+y];
94
+ temp/=moy;
95
+ courbe[posX++]=temp;
96
+ }
97
+ //Définition de l'échelle
98
+ int high=0;
99
+ int low=height();
100
+ for(int x=0;x<courbe.length();x++){
101
+ if(courbe[x]>high)
102
+ high=courbe[x];
103
+ if(courbe[x]<low)
104
+ low=courbe[x];
105
+ }
106
+ //int pour=(height()-5)-(height()/2);
107
+ float coeff=(float)(height()-5)/(float)high;
108
+ /*for(int x=0;x<courbe.length();x++){
109
+ courbe[x]*=(courbe[x]*coeff)/high;
110
+ }*/
111
+ //Dessin sur le widget
112
+ int y=0;
113
+ /*for(int x=1;x<width();x++){
114
+ painter.drawLine(y,courbe[x-1],y+1,courbe[x]);
115
+ painter.drawLine(y,height()/2-(courbe[x-1]-(height()/2)),y+1,(height()/2)-(courbe[x]-(height()/2)));
116
+ y++;
117
+ }*/
118
+ for(int x=1;x<width();x++){
119
+ painter.drawLine(y,courbe[x-1]*((courbe[x-1]*coeff)/high),y+1,courbe[x]*((courbe[x]*coeff)/high));
120
+ painter.drawLine(y,height()/2-(courbe[x-1]*((courbe[x-1]*coeff)/high)-(height()/2)),y+1,(height()/2)-(courbe[x]*((courbe[x]*coeff)/high)-(height()/2)));
121
+ y++;
122
+ }
123
+ painter.end();
124
+ event->accept();
125
+ }
code/train/C++/0009915_sp-switch.cpp ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * SVG <switch> implementation
3
+ *
4
+ * Authors:
5
+ * Andrius R. <knutux@gmail.com>
6
+ * MenTaLguY <mental@rydia.net>
7
+ * Jon A. Cruz <jon@joncruz.org>
8
+ * Abhishek Sharma
9
+ *
10
+ * Copyright (C) 2006 authors
11
+ *
12
+ * Released under GNU GPL, read the file 'COPYING' for more information
13
+ */
14
+
15
+ #include <glibmm/i18n.h>
16
+
17
+ #include "sp-switch.h"
18
+ #include "display/drawing-group.h"
19
+ #include "conditions.h"
20
+
21
+ #include <sigc++/functors/ptr_fun.h>
22
+ #include <sigc++/adaptors/bind.h>
23
+
24
+ SPSwitch::SPSwitch() : SPGroup() {
25
+ this->_cached_item = 0;
26
+ }
27
+
28
+ SPSwitch::~SPSwitch() {
29
+ _releaseLastItem(_cached_item);
30
+ }
31
+
32
+ SPObject *SPSwitch::_evaluateFirst() {
33
+ SPObject *first = 0;
34
+
35
+ for (SPObject *child = this->firstChild() ; child && !first ; child = child->getNext() ) {
36
+ if (SP_IS_ITEM(child) && sp_item_evaluate(SP_ITEM(child))) {
37
+ first = child;
38
+ }
39
+ }
40
+
41
+ return first;
42
+ }
43
+
44
+ std::vector<SPObject*> SPSwitch::_childList(bool add_ref, SPObject::Action action) {
45
+ if ( action != SPObject::ActionGeneral ) {
46
+ return this->childList(add_ref, action);
47
+ }
48
+
49
+ SPObject *child = _evaluateFirst();
50
+ std::vector<SPObject*> x;
51
+ if (NULL == child)
52
+ return x;
53
+
54
+ if (add_ref) {
55
+ //g_object_ref (G_OBJECT (child));
56
+ sp_object_ref(child);
57
+ }
58
+ x.push_back(child);
59
+ return x;
60
+ }
61
+
62
+ const char *SPSwitch::displayName() const {
63
+ return _("Conditional Group");
64
+ }
65
+
66
+ gchar *SPSwitch::description() const {
67
+ gint len = this->getItemCount();
68
+ return g_strdup_printf(
69
+ ngettext(_("of <b>%d</b> object"), _("of <b>%d</b> objects"), len), len);
70
+ }
71
+
72
+ void SPSwitch::child_added(Inkscape::XML::Node* child, Inkscape::XML::Node* ref) {
73
+ SPGroup::child_added(child, ref);
74
+
75
+ this->_reevaluate(true);
76
+ }
77
+
78
+ void SPSwitch::remove_child(Inkscape::XML::Node *child) {
79
+ SPGroup::remove_child(child);
80
+
81
+ this->_reevaluate();
82
+ }
83
+
84
+ void SPSwitch::order_changed (Inkscape::XML::Node *child, Inkscape::XML::Node *old_ref, Inkscape::XML::Node *new_ref)
85
+ {
86
+ SPGroup::order_changed(child, old_ref, new_ref);
87
+
88
+ this->_reevaluate();
89
+ }
90
+
91
+ void SPSwitch::_reevaluate(bool /*add_to_drawing*/) {
92
+ SPObject *evaluated_child = _evaluateFirst();
93
+ if (!evaluated_child || _cached_item == evaluated_child) {
94
+ return;
95
+ }
96
+
97
+ _releaseLastItem(_cached_item);
98
+
99
+ std::vector<SPObject*> item_list = _childList(false, SPObject::ActionShow);
100
+ for ( std::vector<SPObject*>::const_reverse_iterator iter=item_list.rbegin();iter!=item_list.rend();++iter) {
101
+ SPObject *o = *iter;
102
+ if ( !SP_IS_ITEM (o) ) {
103
+ continue;
104
+ }
105
+
106
+ SPItem * child = SP_ITEM(o);
107
+ child->setEvaluated(o == evaluated_child);
108
+ }
109
+
110
+ _cached_item = evaluated_child;
111
+ _release_connection = evaluated_child->connectRelease(sigc::bind(sigc::ptr_fun(&SPSwitch::_releaseItem), this));
112
+
113
+ this->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
114
+ }
115
+
116
+ void SPSwitch::_releaseItem(SPObject *obj, SPSwitch *selection)
117
+ {
118
+ selection->_releaseLastItem(obj);
119
+ }
120
+
121
+ void SPSwitch::_releaseLastItem(SPObject *obj)
122
+ {
123
+ if (NULL == this->_cached_item || this->_cached_item != obj)
124
+ return;
125
+
126
+ this->_release_connection.disconnect();
127
+ this->_cached_item = NULL;
128
+ }
129
+
130
+ void SPSwitch::_showChildren (Inkscape::Drawing &drawing, Inkscape::DrawingItem *ai, unsigned int key, unsigned int flags) {
131
+ SPObject *evaluated_child = this->_evaluateFirst();
132
+
133
+ std::vector<SPObject*> l = this->_childList(false, SPObject::ActionShow);
134
+
135
+ for ( std::vector<SPObject*>::const_reverse_iterator iter=l.rbegin();iter!=l.rend();++iter) {
136
+ SPObject *o = *iter;
137
+
138
+ if (SP_IS_ITEM (o)) {
139
+ SPItem * child = SP_ITEM(o);
140
+ child->setEvaluated(o == evaluated_child);
141
+ Inkscape::DrawingItem *ac = child->invoke_show (drawing, key, flags);
142
+
143
+ if (ac) {
144
+ ai->appendChild(ac);
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ /*
151
+ Local Variables:
152
+ mode:c++
153
+ c-file-style:"stroustrup"
154
+ c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
155
+ indent-tabs-mode:nil
156
+ fill-column:99
157
+ End:
158
+ */
159
+ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
code/train/C++/0010000_track.cpp ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "map/track.hpp"
2
+
3
+ #include "map/bookmark_helpers.hpp"
4
+ #include "map/user_mark_id_storage.hpp"
5
+
6
+ #include "geometry/distance_on_sphere.hpp"
7
+ #include "geometry/mercator.hpp"
8
+
9
+ #include <utility>
10
+
11
+ Track::Track(kml::TrackData && data)
12
+ : Base(data.m_id == kml::kInvalidTrackId ? UserMarkIdStorage::Instance().GetNextTrackId() : data.m_id)
13
+ , m_data(std::move(data))
14
+ , m_groupID(0)
15
+ {
16
+ m_data.m_id = GetId();
17
+ ASSERT_GREATER(m_data.m_points.size(), 1, ());
18
+ }
19
+
20
+ std::string Track::GetName() const
21
+ {
22
+ return GetPreferredBookmarkStr(m_data.m_name);
23
+ }
24
+
25
+ m2::RectD Track::GetLimitRect() const
26
+ {
27
+ m2::RectD rect;
28
+ for (auto const & point : m_data.m_points)
29
+ rect.Add(point);
30
+ return rect;
31
+ }
32
+
33
+ double Track::GetLengthMeters() const
34
+ {
35
+ double res = 0.0;
36
+
37
+ auto it = m_data.m_points.begin();
38
+ double lat1 = MercatorBounds::YToLat(it->y);
39
+ double lon1 = MercatorBounds::XToLon(it->x);
40
+ for (++it; it != m_data.m_points.end(); ++it)
41
+ {
42
+ double const lat2 = MercatorBounds::YToLat(it->y);
43
+ double const lon2 = MercatorBounds::XToLon(it->x);
44
+ res += ms::DistanceOnEarth(lat1, lon1, lat2, lon2);
45
+ lat1 = lat2;
46
+ lon1 = lon2;
47
+ }
48
+
49
+ return res;
50
+ }
51
+
52
+ df::DepthLayer Track::GetDepthLayer() const
53
+ {
54
+ return df::DepthLayer::UserLineLayer;
55
+ }
56
+
57
+ size_t Track::GetLayerCount() const
58
+ {
59
+ return m_data.m_layers.size();
60
+ }
61
+
62
+ dp::Color Track::GetColor(size_t layerIndex) const
63
+ {
64
+ CHECK_LESS(layerIndex, m_data.m_layers.size(), ());
65
+ return dp::Color(m_data.m_layers[layerIndex].m_color.m_rgba);
66
+ }
67
+
68
+ float Track::GetWidth(size_t layerIndex) const
69
+ {
70
+ CHECK_LESS(layerIndex, m_data.m_layers.size(), ());
71
+ return static_cast<float>(m_data.m_layers[layerIndex].m_lineWidth);
72
+ }
73
+
74
+ float Track::GetDepth(size_t layerIndex) const
75
+ {
76
+ return layerIndex * 10;
77
+ }
78
+
79
+ std::vector<m2::PointD> const & Track::GetPoints() const
80
+ {
81
+ return m_data.m_points;
82
+ }
83
+
84
+ void Track::Attach(kml::MarkGroupId groupId)
85
+ {
86
+ ASSERT(!m_groupID, ());
87
+ m_groupID = groupId;
88
+ }
89
+
90
+ void Track::Detach()
91
+ {
92
+ m_groupID = 0;
93
+ }
code/train/C++/0010267_sgmm-acc-fmllrbasis-ali.cc ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sgmmbin/sgmm-acc-fmllrbasis-ali.cc
2
+
3
+ // Copyright 2009-2011 Saarland University
4
+ // Author: Arnab Ghoshal
5
+
6
+ // See ../../COPYING for clarification regarding multiple authors
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
+ // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
16
+ // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
17
+ // MERCHANTABLITY OR NON-INFRINGEMENT.
18
+ // See the Apache 2 License for the specific language governing permissions and
19
+ // limitations under the License.
20
+
21
+ #include <vector>
22
+
23
+ #include "util/common-utils.h"
24
+ #include "hmm/transition-model.h"
25
+ #include "sgmm/am-sgmm.h"
26
+ #include "sgmm/fmllr-sgmm.h"
27
+
28
+ int main(int argc, char *argv[]) {
29
+ try {
30
+ using namespace kaldi;
31
+ const char *usage =
32
+ "Accumulate stats for FMLLR bases training.\n"
33
+ "Usage: sgmm-acc-fmllrbasis-ali [options] <model-in> <feature-rspecifier> "
34
+ "<alignments-rspecifier> <spk2utt-rspecifier> <stats-out>\n"
35
+ "e.g.: sgmm-acc-fmllrbasis-ali 1.mdl scp:train.scp ark:1.ali 1.acc\n";
36
+
37
+ ParseOptions po(usage);
38
+ bool binary_write = true;
39
+ std::string gselect_rspecifier, spkvecs_rspecifier, silphones_str;
40
+ BaseFloat sil_weight = 0.0;
41
+ kaldi::SgmmGselectConfig sgmm_opts;
42
+ po.Register("binary", &binary_write, "Write output in binary mode");
43
+ po.Register("gselect", &gselect_rspecifier,
44
+ "Precomputed Gaussian indices (rspecifier)");
45
+ po.Register("spk-vecs", &spkvecs_rspecifier,
46
+ "Speaker vectors to use during aligment (rspecifier)");
47
+ po.Register("sil-phone-list", &silphones_str,
48
+ "Colon-separated list of phones (to weigh differently)");
49
+ po.Register("sil-weight", &sil_weight, "Weight for \"silence\" phones.");
50
+ sgmm_opts.Register(&po);
51
+ po.Read(argc, argv);
52
+
53
+ if (po.NumArgs() != 5) {
54
+ po.PrintUsage();
55
+ exit(1);
56
+ }
57
+
58
+ std::string model_filename = po.GetArg(1),
59
+ feature_rspecifier = po.GetArg(2),
60
+ alignments_rspecifier = po.GetArg(3),
61
+ spk2utt_rspecifier = po.GetArg(4),
62
+ accs_wxfilename = po.GetArg(5);
63
+
64
+ typedef kaldi::int32 int32;
65
+
66
+ AmSgmm am_sgmm;
67
+ TransitionModel trans_model;
68
+ SgmmFmllrGlobalParams fmllr_globals;
69
+ {
70
+ bool binary;
71
+ Input ki(model_filename, &binary);
72
+ trans_model.Read(ki.Stream(), binary);
73
+ am_sgmm.Read(ki.Stream(), binary);
74
+ fmllr_globals.Read(ki.Stream(), binary);
75
+ }
76
+
77
+ SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
78
+ RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
79
+ RandomAccessInt32VectorReader alignments_reader(alignments_rspecifier);
80
+
81
+ RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier);
82
+
83
+ RandomAccessBaseFloatVectorReader spkvecs_reader(spkvecs_rspecifier);
84
+
85
+ std::vector<int32> silence_phones;
86
+ if (!SplitStringToIntegers(silphones_str, ":", false, &silence_phones)) {
87
+ KALDI_ERR << "Silence-phones string has wrong format "
88
+ << silphones_str;
89
+ }
90
+ ConstIntegerSet<int32> silence_set(silence_phones); // faster lookup.
91
+
92
+
93
+ kaldi::SgmmPerFrameDerivedVars per_frame_vars;
94
+ SpMatrix<double> fmllr_grad_scatter;
95
+ int32 dim = am_sgmm.FeatureDim();
96
+ fmllr_grad_scatter.Resize(dim * (dim + 1), kSetZero);
97
+ FmllrSgmmAccs spk_stats;
98
+ spk_stats.Init(dim, am_sgmm.NumGauss());
99
+
100
+ double tot_like = 0.0, tot_t = 0.0;
101
+ int32 num_done = 0, num_no_alignment = 0, num_other_error = 0;
102
+
103
+ for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
104
+ spk_stats.SetZero();
105
+ string spk = spk2utt_reader.Key();
106
+ const std::vector<string> &uttlist = spk2utt_reader.Value();
107
+
108
+ SgmmPerSpkDerivedVars spk_vars;
109
+ if (spkvecs_reader.IsOpen()) {
110
+ if (spkvecs_reader.HasKey(spk)) {
111
+ spk_vars.v_s = spkvecs_reader.Value(spk);
112
+ am_sgmm.ComputePerSpkDerivedVars(&spk_vars);
113
+ } else {
114
+ KALDI_WARN << "Cannot find speaker vector for " << spk;
115
+ num_other_error++;
116
+ continue;
117
+ }
118
+ } // else spk_vars is "empty"
119
+
120
+ for (size_t i = 0; i < uttlist.size(); i++) {
121
+ std::string utt = uttlist[i];
122
+ if (!alignments_reader.HasKey(utt)) {
123
+ num_no_alignment++;
124
+ continue;
125
+ }
126
+ const std::vector<int32> &alignment = alignments_reader.Value(utt);
127
+
128
+ if (!feature_reader.HasKey(utt)) {
129
+ KALDI_WARN << "Did not find features for utterance " << utt;
130
+ num_other_error++;
131
+ continue;
132
+ }
133
+ const Matrix<BaseFloat> &feats = feature_reader.Value(utt);
134
+
135
+ if (alignment.size() != feats.NumRows()) {
136
+ KALDI_WARN << "Alignments has wrong size "<< (alignment.size()) <<
137
+ " vs. "<< (feats.NumRows());
138
+ num_other_error++;
139
+ continue;
140
+ }
141
+
142
+ bool have_gselect = false;
143
+ if (gselect_reader.IsOpen()) {
144
+ if (gselect_reader.HasKey(utt)) {
145
+ have_gselect = (gselect_reader.Value(utt).size() == feats.NumRows());
146
+ if (!have_gselect)
147
+ KALDI_WARN << "Gaussian-selection info available for utterance "
148
+ << utt << " has wrong size.";
149
+ } else {
150
+ KALDI_WARN << "No Gaussian-selection info available for utterance "
151
+ << utt;
152
+ }
153
+ }
154
+
155
+ const std::vector<std::vector<int32> > *gselect =
156
+ (have_gselect ? &gselect_reader.Value(utt) : NULL);
157
+ double file_like = 0.0, file_t = 0.0;
158
+
159
+
160
+ for (size_t i = 0; i < alignment.size(); i++) {
161
+ int32 tid = alignment[i]; // transition identifier.
162
+ int32 pdf_id = trans_model.TransitionIdToPdf(tid),
163
+ phone = trans_model.TransitionIdToPhone(tid);
164
+ BaseFloat weight = 1.0;
165
+ if (silence_set.count(phone) != 0) { // is a silence.
166
+ if (sil_weight > 0.0)
167
+ weight = sil_weight;
168
+ else
169
+ continue;
170
+ }
171
+
172
+ std::vector<int32> this_gselect;
173
+ if (gselect != NULL)
174
+ this_gselect = (*gselect)[i];
175
+ else
176
+ am_sgmm.GaussianSelection(sgmm_opts, feats.Row(i), &this_gselect);
177
+ am_sgmm.ComputePerFrameVars(feats.Row(i), this_gselect, spk_vars, 0.0,
178
+ &per_frame_vars);
179
+ file_like +=
180
+ spk_stats.Accumulate(am_sgmm, spk_vars, feats.Row(i),
181
+ per_frame_vars, pdf_id, weight);
182
+ file_t += weight;
183
+ } // end looping over all the frames in the utterance
184
+ KALDI_VLOG(1) << "Average likelihood for utterance " << utt << " is "
185
+ << (file_like/file_t) << " over " << file_t << " frames";
186
+ tot_like += file_like;
187
+ tot_t += file_t;
188
+ num_done++;
189
+ if (num_done % 20 == 0)
190
+ KALDI_VLOG(1) << "After " << num_done << " utterances: Average "
191
+ << "likelihood per frame = " << (tot_like/tot_t)
192
+ << ", over " << tot_t << " frames";
193
+ } // end looping over all utterance for a given speaker
194
+ spk_stats.AccumulateForFmllrSubspace(am_sgmm, fmllr_globals, &fmllr_grad_scatter);
195
+ } // end looping over all speakers
196
+
197
+ KALDI_LOG << "Done " << num_done << " files, " << num_no_alignment
198
+ << " with no alignments, " << num_other_error
199
+ << " with other errors.";
200
+
201
+ KALDI_LOG << "Overall likelihood per frame frame = " << (tot_like/tot_t)
202
+ << " over " << tot_t << " frames.";
203
+
204
+ {
205
+ Output ko(accs_wxfilename, binary_write);
206
+ fmllr_grad_scatter.Write(ko.Stream(), binary_write);
207
+ KALDI_LOG << "Written accs to: " << accs_wxfilename;
208
+ }
209
+ return (num_done != 0 ? 0 : 1);
210
+ } catch(const std::exception &e) {
211
+ std::cerr << e.what();
212
+ return -1;
213
+ }
214
+ }
215
+
216
+
code/train/C++/0010531_CCSequence3D.cpp ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /****************************************************************************
2
+ Copyright (c) 2014 Chukong Technologies Inc.
3
+
4
+ http://www.cocos2d-x.org
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
23
+ ****************************************************************************/
24
+
25
+ #include "CCSequence3D.h"
26
+
27
+ NS_CC_BEGIN
28
+
29
+ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
30
+ Sequence3D* Sequence3D::variadicCreate(Animate3D *action1, ...)
31
+ {
32
+ va_list params;
33
+ va_start(params, action1);
34
+
35
+ Sequence3D *ret = Sequence3D::createWithVariableList(action1, params);
36
+
37
+ va_end(params);
38
+
39
+ return ret;
40
+ }
41
+ #else
42
+ Sequence3D* Sequence3D::create(Animate3D *action1, ...)
43
+ {
44
+ va_list params;
45
+ va_start(params, action1);
46
+
47
+ Sequence3D *ret = Sequence3D::createWithVariableList(action1, params);
48
+
49
+ va_end(params);
50
+
51
+ return ret;
52
+ }
53
+ #endif
54
+
55
+ Sequence3D* Sequence3D::createWithVariableList(Animate3D *action1, va_list args)
56
+ {
57
+ Animate3D *now;
58
+
59
+ Vector<Animate3D*> actions;
60
+ if (action1)
61
+ actions.pushBack(action1);
62
+
63
+ while (action1)
64
+ {
65
+ now = va_arg(args, Animate3D*);
66
+ if (now)
67
+ {
68
+ actions.pushBack(now);
69
+ }
70
+ else
71
+ break;
72
+ }
73
+
74
+ return create(actions);
75
+ }
76
+
77
+ Sequence3D* Sequence3D::create(const Vector<Animate3D*>& arrayOfActions)
78
+ {
79
+ Sequence3D* ret = nullptr;
80
+
81
+ ret = new (std::nothrow) Sequence3D();
82
+ if (ret->initWithActions(arrayOfActions))
83
+ {
84
+ ret->autorelease();
85
+ return ret;
86
+ }
87
+
88
+ CC_SAFE_RELEASE(ret);
89
+ return ret;
90
+ }
91
+
92
+ bool Sequence3D::initWithActions(const Vector<Animate3D*>& arrayOfActions)
93
+ {
94
+ if (arrayOfActions.size() == 0)
95
+ return false;
96
+
97
+ _actions.clear();
98
+ _startTime.clear();
99
+ _endTime.clear();
100
+
101
+ Animate3D* preAction = nullptr;
102
+ float duration = 0.f, dur = 0.f;
103
+ _startTime.push_back(duration);
104
+ for (auto& it : arrayOfActions) {
105
+ float d1 = 0.f;
106
+ if (preAction)
107
+ d1 = preAction->getDuration();
108
+
109
+ float d2 = it->getDuration();
110
+ if (d1 < Animate3D::getTransitionTime() || d2 < Animate3D::getTransitionTime())
111
+ dur = d1 > d2 ? d1 : d2;
112
+ else
113
+ dur = d1 + d2 - Animate3D::getTransitionTime();
114
+
115
+ preAction = it;
116
+ _actions.pushBack(it);
117
+ _startTime.push_back(dur);
118
+ _endTime.push_back(dur);
119
+ duration += dur;
120
+ }
121
+ _startTime.erase(_startTime.end() - 1);
122
+ for (ssize_t i = 0; i < _startTime.size(); i++) {
123
+ _startTime[i] /= duration;
124
+ _endTime[i] /= duration;
125
+ }
126
+ setDuration(duration);
127
+ _curActionIdx = -1;
128
+ return true;
129
+ }
130
+
131
+ Sequence3D* Sequence3D::clone() const
132
+ {
133
+ // no copy constructor
134
+ auto seq3d = new (std::nothrow) Sequence3D();
135
+ seq3d->initWithActions(_actions);
136
+ seq3d->autorelease();
137
+ return seq3d;
138
+ }
139
+
140
+ Sequence3D::Sequence3D()
141
+ : _curActionIdx(-1)
142
+ {
143
+
144
+ }
145
+
146
+ Sequence3D::~Sequence3D(void)
147
+ {
148
+ _actions.clear();
149
+ }
150
+
151
+ void Sequence3D::startWithTarget(Node *target)
152
+ {
153
+ ActionInterval::startWithTarget(target);
154
+ _curActionIdx = -1;
155
+ }
156
+
157
+ void Sequence3D::stop(void)
158
+ {
159
+ for (auto& action : _actions) {
160
+ action->stop();
161
+ }
162
+
163
+ ActionInterval::stop();
164
+ }
165
+
166
+ Sequence3D* Sequence3D::reverse() const
167
+ {
168
+ Vector<Animate3D*> actions;
169
+ for (auto it = _actions.rbegin(); it != _actions.rend(); ++it) {
170
+ actions.pushBack(*it);
171
+ }
172
+
173
+ return create(actions);
174
+ }
175
+
176
+ void Sequence3D::update(float t)
177
+ {
178
+ if (_target)
179
+ {
180
+ int nextIdx = _curActionIdx + 1;
181
+ if (nextIdx < _actions.size())
182
+ {
183
+ if (t >= _startTime[nextIdx])
184
+ {
185
+ _actions.at(nextIdx)->startWithTarget(_target);
186
+ }
187
+ }
188
+ //update action
189
+ int preActionIdx = _curActionIdx - 1;
190
+ if (preActionIdx >= 0 && _endTime[preActionIdx] > t)
191
+ {
192
+ float newt = (t - _startTime[preActionIdx]) / (_endTime[preActionIdx] - _startTime[preActionIdx]);
193
+ _actions.at(preActionIdx)->update(newt);
194
+ }
195
+ if (_curActionIdx >= 0 && _curActionIdx < _actions.size())
196
+ {
197
+ float newt = (t - _startTime[_curActionIdx]) / (_endTime[_curActionIdx] - _startTime[_curActionIdx]);
198
+ _actions.at(_curActionIdx)->update(newt);
199
+ }
200
+ }
201
+ }
202
+ void Sequence3D::step(float t)
203
+ {
204
+ ActionInterval::step(t) ;
205
+ if (_target)
206
+ {
207
+ float newt=MAX(0, MIN(1, _elapsed /MAX(_duration, FLT_EPSILON)));
208
+ int nextIdx = _curActionIdx + 1;
209
+ if (nextIdx < _actions.size())
210
+ {
211
+ if (newt >= _startTime[nextIdx])
212
+ {
213
+ _curActionIdx = nextIdx;
214
+ }
215
+ }
216
+ //update action
217
+ int preActionIdx = _curActionIdx - 1;
218
+ if (preActionIdx >= 0 && _endTime[preActionIdx] >newt)
219
+ {
220
+
221
+ _actions.at(preActionIdx)->step(t);
222
+
223
+ }
224
+ if (_curActionIdx >= 0 && _curActionIdx < _actions.size())
225
+ {
226
+ _actions.at(_curActionIdx)->step(t);
227
+
228
+ }
229
+ }
230
+ }
231
+
232
+ NS_CC_END
code/train/C++/0010760_laser.cpp ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cstdio>
2
+ #include <cstring>
3
+ #include <vector>
4
+ using namespace std;
5
+
6
+
7
+ #define MAXN 700
8
+
9
+
10
+ typedef unsigned char uch;
11
+ typedef unsigned int u32;
12
+
13
+
14
+ //
15
+ // Hash Map
16
+ //
17
+ #define HASHB 4096
18
+ const size_t KeySz = sizeof(int) * 2;
19
+ struct HM {
20
+ struct Key {
21
+ int d[2];
22
+ Key(int *D) { memcpy(d, D, KeySz); }
23
+ bool operator==(const Key &x) const {
24
+ return memcmp(d, x.d, KeySz) == 0; }
25
+ };
26
+ struct KV {
27
+ Key k; int v;
28
+ KV(const Key &K, int V) : k(K), v(V) {}
29
+ };
30
+ typedef vector<KV> KVV; KVV b[HASHB];
31
+ u32 fnv_hash(const Key &k, int len) const {
32
+ uch *p = reinterpret_cast<uch*>(const_cast<int*>(k.d));
33
+ u32 h = 2166136261U;
34
+ for (int i = 0; i < len; ++i) h = (h * 16777619U) ^ p[i];
35
+ return h;
36
+ }
37
+ int add(const Key &k) {
38
+ int i = fnv_hash(k, KeySz) % HASHB;
39
+ for (int j = 0, J = b[i].size(); j < J; ++j)
40
+ if (b[i][j].k == k)
41
+ return ++b[i][j].v;
42
+ b[i].push_back(KV(k, 2));
43
+ return 2;
44
+ return true;
45
+ }
46
+ };
47
+
48
+
49
+ template<typename T>
50
+ T gcd(T a, T b) { for (T c = a%b; c != 0; a=b,b=c,c=a%b); return b; }
51
+
52
+
53
+ int n;
54
+ int pts[MAXN][2];
55
+
56
+
57
+ int solve()
58
+ {
59
+ if (n <= 2) return n;
60
+ int ans = 0;
61
+
62
+ int m[2]; // slope, as a rational number
63
+
64
+ for (int i = 0; i < n; ++i) {
65
+ HM hm;
66
+
67
+ for (int j = i + 1; j < n; ++j) {
68
+ if (pts[i][0] == pts[j][0])
69
+ m[0] = m[1] = 0;
70
+ else {
71
+ m[0] = pts[j][1] - pts[i][1];
72
+ m[1] = pts[j][0] - pts[i][0];
73
+
74
+ int g = gcd(m[0], m[1]);
75
+ m[0] /= g;
76
+ m[1] /= g;
77
+ }
78
+
79
+ int coll = hm.add(HM::Key(m));
80
+ if (coll > ans) ans = coll;
81
+ }
82
+ }
83
+
84
+ return ans;
85
+ }
86
+
87
+ int main()
88
+ {
89
+ int T;
90
+ scanf("%d", &T);
91
+
92
+ int ncase = 0;
93
+ while (T--) {
94
+ scanf("%d", &n);
95
+
96
+ for (int i = 0; i < n; ++i)
97
+ scanf("%d%d", &pts[i][0], &pts[i][1]);
98
+
99
+ printf("Case %d: %d\n", ++ncase, solve());
100
+ }
101
+
102
+ return 0;
103
+ }
code/train/C++/0011798_chapter04_ex16.cpp ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Chapter 04, exercise 16: find the mode in a vector of integers entered by
2
+ // user (only the first, not all of them)
3
+
4
+ #include "../lib_files/std_lib_facilities.h"
5
+
6
+ int get_mode(vector<int> v)
7
+ {
8
+ sort(v.begin(),v.end());
9
+ int mode_cdt = v[0];
10
+ int mode_cdt_ctr = 1;
11
+ int mode = 0;
12
+ int mode_ctr = 1;
13
+ for (int i = 1; i<v.size(); ++i) {
14
+ if (v[i]==mode_cdt) {
15
+ ++mode_cdt_ctr;
16
+ if (mode_cdt_ctr>mode_ctr) {
17
+ mode = mode_cdt;
18
+ mode_ctr = mode_cdt_ctr;
19
+ }
20
+ }
21
+ else {
22
+ mode_cdt = v[i];
23
+ mode_cdt_ctr = 1;
24
+ }
25
+ }
26
+ cout << "Top value appears " << mode_ctr << " times.\n";
27
+ return mode;
28
+ }
29
+
30
+ int main()
31
+ {
32
+ int n = 0;
33
+ int smallest = 0;
34
+ int largest = 0;
35
+ int mode = 0;
36
+ vector<int> vals;
37
+ bool is_first = true;
38
+
39
+ cout << "Enter sequence of integers:\n";
40
+
41
+ while (cin >> n) {
42
+ if (n < smallest || is_first)
43
+ smallest = n;
44
+ if (n > largest || is_first)
45
+ largest = n;
46
+ vals.push_back(n);
47
+ is_first = false;
48
+ }
49
+
50
+ mode = get_mode(vals);
51
+ cout << "smallest value: " << smallest << endl;
52
+ cout << "largest value: " << largest << endl;
53
+ cout << "mode: " << mode << endl;
54
+
55
+ sort(vals.begin(),vals.end());
56
+ cout << "values:" << endl;
57
+ for (int i = 0; i<vals.size(); ++i)
58
+ cout << vals[i] << endl;
59
+ return 0;
60
+ }
code/train/C++/0012078_edit_distance.cc ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 Google Inc. All Rights Reserved.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ #include "edit_distance.h"
16
+
17
+ #include <algorithm>
18
+ #include <vector>
19
+
20
+ int EditDistance(const StringPiece& s1,
21
+ const StringPiece& s2,
22
+ bool allow_replacements,
23
+ int max_edit_distance) {
24
+ // The algorithm implemented below is the "classic"
25
+ // dynamic-programming algorithm for computing the Levenshtein
26
+ // distance, which is described here:
27
+ //
28
+ // http://en.wikipedia.org/wiki/Levenshtein_distance
29
+ //
30
+ // Although the algorithm is typically described using an m x n
31
+ // array, only two rows are used at a time, so this implementation
32
+ // just keeps two separate vectors for those two rows.
33
+ int m = s1.len_;
34
+ int n = s2.len_;
35
+
36
+ vector<int> previous(n + 1);
37
+ vector<int> current(n + 1);
38
+
39
+ for (int i = 0; i <= n; ++i)
40
+ previous[i] = i;
41
+
42
+ for (int y = 1; y <= m; ++y) {
43
+ current[0] = y;
44
+ int best_this_row = current[0];
45
+
46
+ for (int x = 1; x <= n; ++x) {
47
+ if (allow_replacements) {
48
+ current[x] = min(previous[x-1] + (s1.str_[y-1] == s2.str_[x-1] ? 0 : 1),
49
+ min(current[x-1], previous[x])+1);
50
+ }
51
+ else {
52
+ if (s1.str_[y-1] == s2.str_[x-1])
53
+ current[x] = previous[x-1];
54
+ else
55
+ current[x] = min(current[x-1], previous[x]) + 1;
56
+ }
57
+ best_this_row = min(best_this_row, current[x]);
58
+ }
59
+
60
+ if (max_edit_distance && best_this_row > max_edit_distance)
61
+ return max_edit_distance + 1;
62
+
63
+ current.swap(previous);
64
+ }
65
+
66
+ return previous[n];
67
+ }
code/train/C++/0024658_MaxPID.cpp ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Copyright (C) 2012,2013
3
+ Max Planck Institute for Polymer Research
4
+ Copyright (C) 2008,2009,2010,2011
5
+ Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
6
+
7
+ This file is part of ESPResSo++.
8
+
9
+ ESPResSo++ is free software: you can redistribute it and/or modify
10
+ it under the terms of the GNU General Public License as published by
11
+ the Free Software Foundation, either version 3 of the License, or
12
+ (at your option) any later version.
13
+
14
+ ESPResSo++ is distributed in the hope that it will be useful,
15
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ GNU General Public License for more details.
18
+
19
+ You should have received a copy of the GNU General Public License
20
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ */
22
+
23
+ #include "python.hpp"
24
+ #include "MaxPID.hpp"
25
+ #include "storage/DomainDecomposition.hpp"
26
+ #include "iterator/CellListIterator.hpp"
27
+
28
+ using namespace espressopp;
29
+ using namespace iterator;
30
+
31
+ namespace espressopp {
32
+ namespace analysis {
33
+ real MaxPID::compute() const {
34
+
35
+ long myMaxPID, systemMaxPID;
36
+ System& system = getSystemRef();
37
+ CellList realCells = system.storage->getRealCells();
38
+
39
+ myMaxPID = 0;
40
+ for (CellListIterator cit(realCells); !cit.isDone(); ++cit) {
41
+ long pid = cit->id();
42
+ if (pid > myMaxPID) {
43
+ myMaxPID = pid;
44
+ }
45
+ }
46
+
47
+ // it was reduce
48
+ boost::mpi::all_reduce(*getSystem()->comm, myMaxPID, systemMaxPID, mpi::maximum<long>());
49
+
50
+ return 1.0*systemMaxPID;
51
+
52
+ }
53
+
54
+ void MaxPID::registerPython() {
55
+ using namespace espressopp::python;
56
+ class_<MaxPID, bases< Observable > >
57
+ ("analysis_MaxPID", init< shared_ptr< System > >())
58
+ ;
59
+ }
60
+ }
61
+ }
code/train/C++/0024892_ft_send.cpp ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2004-2016 by Jakob Schröter <js@camaya.net>
3
+ * This file is part of the gloox library. http://camaya.net/gloox
4
+ *
5
+ * This software is distributed under a license. The full license
6
+ * agreement can be found in the file LICENSE in this distribution.
7
+ * This software may not be copied, modified, sold or distributed
8
+ * other than expressed in the named license agreement.
9
+ *
10
+ * This software is distributed without any warranty.
11
+ */
12
+
13
+ #include "../client.h"
14
+ #include "../connectionlistener.h"
15
+ #include "../stanza.h"
16
+ #include "../gloox.h"
17
+ #include "../disco.h"
18
+ #include "../loghandler.h"
19
+ #include "../logsink.h"
20
+ #include "../siprofileft.h"
21
+ #include "../siprofilefthandler.h"
22
+ #include "../bytestreamdatahandler.h"
23
+ #include "../socks5bytestreamserver.h"
24
+ using namespace gloox;
25
+
26
+ #include <sys/types.h>
27
+ #include <sys/stat.h>
28
+ #include <unistd.h>
29
+ #include <stdio.h>
30
+ #include <string>
31
+ #include <fstream>
32
+ #include <ios>
33
+
34
+ #include <cstdio> // [s]print[f]
35
+
36
+ #if defined( WIN32 ) || defined( _WIN32 )
37
+ # include <windows.h>
38
+ #endif
39
+
40
+ /**
41
+ * Usage:
42
+ * ft_send jid@server/full /path/to/file
43
+ *
44
+ * Sends the given file to the given full JID.
45
+ */
46
+ class FTTest : public LogHandler, ConnectionListener, SIProfileFTHandler, BytestreamDataHandler
47
+ {
48
+ public:
49
+ FTTest( const JID& to, const std::string& file ) : m_bs( 0 ), m_to( to ), m_file( file ), m_quit( false ) {}
50
+
51
+ virtual ~FTTest() {}
52
+
53
+ void start()
54
+ {
55
+
56
+ struct stat f_stat;
57
+ if( stat( m_file.c_str(), &f_stat ) )
58
+ return;
59
+
60
+ m_size = f_stat.st_size;
61
+ std::ifstream ifile( m_file.c_str(), std::ios_base::in | std::ios_base::binary );
62
+ if( !ifile )
63
+ return;
64
+
65
+ JID jid( "hurkhurk@example.net/glooxsendfile" );
66
+ j = new Client( jid, "hurkhurks" );
67
+ j->registerConnectionListener( this );
68
+ j->disco()->setVersion( "ftsend", GLOOX_VERSION, "Linux" );
69
+ j->disco()->setIdentity( "client", "bot" );
70
+ StringList ca;
71
+ ca.push_back( "/path/to/cacert.crt" );
72
+ j->setCACerts( ca );
73
+
74
+ j->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this );
75
+
76
+
77
+ m_server = new SOCKS5BytestreamServer( j->logInstance(), 6666 );
78
+ printf( "about to listen\n" );
79
+ ConnectionError le = ConnNoError;
80
+ if( ( le = m_server->listen() ) != ConnNoError )
81
+ printf( "listen returned: %d\n", le );
82
+ printf( "listening\n" );
83
+
84
+ f = new SIProfileFT( j, this );
85
+ f->registerSOCKS5BytestreamServer( m_server );
86
+ f->addStreamHost( j->jid(), "192.168.100.20", 6666 );
87
+ // you should obtain this using disco, really:
88
+ // f->addStreamHost( JID( "reflector.amessage.eu" ), "reflector.amessage.eu", 6565 );
89
+ // f->addStreamHost( JID( "proxy.jabber.org" ), "208.245.212.98", 7777 );
90
+
91
+ if( j->connect( false ) )
92
+ {
93
+ char input[200024];
94
+ ConnectionError ce = ConnNoError;
95
+ ConnectionError se = ConnNoError;
96
+ while( ce == ConnNoError )
97
+ {
98
+ if( m_quit )
99
+ j->disconnect();
100
+
101
+ ce = j->recv( 1 );
102
+ if( m_server )
103
+ {
104
+ se = m_server->recv( 1 );
105
+ if( se != ConnNoError )
106
+ {
107
+ printf( "SOCKS5BytestreamServer returned: %d\n", se );
108
+ delete m_server;
109
+ m_server = 0;
110
+ m_quit = true;
111
+ }
112
+ }
113
+ if( m_bs && !ifile.eof() )
114
+ {
115
+ if( m_bs->isOpen() )
116
+ {
117
+ ifile.read( input, 200024 );
118
+ std::string t( input, ifile.gcount() );
119
+ if( !m_bs->send( t ) )
120
+ m_quit = true;
121
+ }
122
+ m_bs->recv( 1 );
123
+ }
124
+ else if( m_bs )
125
+ m_bs->close();
126
+ }
127
+ printf( "ce: %d\n", ce );
128
+ }
129
+
130
+ f->dispose( m_bs );
131
+ delete f;
132
+ delete m_server;
133
+ delete j;
134
+ }
135
+
136
+ virtual void onConnect()
137
+ {
138
+ printf( "connected!!!\n" );
139
+ f->requestFT( m_to, m_file, m_size );
140
+ }
141
+
142
+ virtual void onDisconnect( ConnectionError e )
143
+ {
144
+ printf( "ft_send: disconnected: %d\n", e );
145
+ if( e == ConnAuthenticationFailed )
146
+ printf( "auth failed. reason: %d\n", j->authError() );
147
+ }
148
+
149
+ virtual bool onTLSConnect( const CertInfo& info )
150
+ {
151
+ time_t from( info.date_from );
152
+ time_t to( info.date_to );
153
+
154
+ printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
155
+ "from: %s\nto: %s\n",
156
+ info.status, info.issuer.c_str(), info.server.c_str(),
157
+ info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
158
+ info.compression.c_str(), ctime( &from ), ctime( &to ) );
159
+ return true;
160
+ }
161
+
162
+ virtual void handleLog( LogLevel level, LogArea area, const std::string& message )
163
+ {
164
+ printf("log: level: %d, area: %d, %s\n", level, area, message.c_str() );
165
+ }
166
+
167
+ virtual void handleFTRequest( const JID& from, const JID& /*to*/, const std::string& sid,
168
+ const std::string& name, long size, const std::string& hash,
169
+ const std::string& date, const std::string& mimetype,
170
+ const std::string& desc, int /*stypes*/ )
171
+ {
172
+ printf( "received ft request from %s: %s (%ld bytes, sid: %s). hash: %s, date: %s, mime-type: %s\n"
173
+ "desc: %s\n",
174
+ from.full().c_str(), name.c_str(), size, sid.c_str(), hash.c_str(), date.c_str(),
175
+ mimetype.c_str(), desc.c_str() );
176
+ f->acceptFT( from, sid, SIProfileFT::FTTypeS5B );
177
+ }
178
+
179
+ // virtual void handleFTRequestResult( const JID& /*from*/, const std::string& /*sid*/ )
180
+ // {
181
+ // }
182
+
183
+ virtual void handleFTRequestError( const IQ& /*iq*/, const std::string& /*sid*/ )
184
+ {
185
+ printf( "ft request error\n" );
186
+ m_quit = true;
187
+ }
188
+
189
+ virtual void handleFTBytestream( Bytestream* bs )
190
+ {
191
+ printf( "received bytestream of type: %s", bs->type() == Bytestream::S5B ? "s5b" : "ibb" );
192
+ m_bs = bs;
193
+ m_bs->registerBytestreamDataHandler( this );
194
+ if( m_bs->connect() )
195
+ {
196
+ if( bs->type() == Bytestream::S5B )
197
+ printf( "ok! s5b connected to streamhost\n" );
198
+ else
199
+ printf( "ok! ibb sent request to remote entity\n" );
200
+ }
201
+ }
202
+
203
+ virtual const std::string handleOOBRequestResult( const JID& /*from*/, const JID& /*to*/, const std::string& /*sid*/ )
204
+ {
205
+ return std::string();
206
+ };
207
+
208
+ virtual void handleBytestreamData( Bytestream* /*bs*/, const std::string& data )
209
+ {
210
+ printf( "received %d bytes of data:\n%s\n", data.length(), data.c_str() );
211
+ }
212
+
213
+ virtual void handleBytestreamError( Bytestream* /*bs*/, const IQ& /*iq*/ )
214
+ {
215
+ printf( "bytestream error\n" );
216
+ }
217
+
218
+ virtual void handleBytestreamOpen( Bytestream* /*bs*/ )
219
+ {
220
+ printf( "bytestream opened\n" );
221
+ }
222
+
223
+ virtual void handleBytestreamClose( Bytestream* /*bs*/ )
224
+ {
225
+ printf( "bytestream closed\n" );
226
+ m_quit = true;
227
+ }
228
+
229
+ private:
230
+ Client *j;
231
+ SIProfileFT* f;
232
+ Bytestream* m_bs;
233
+ SOCKS5BytestreamServer* m_server;
234
+ JID m_to;
235
+ std::string m_file;
236
+ bool m_quit;
237
+ int m_size;
238
+ };
239
+
240
+ int main( int argc, char** argv )
241
+ {
242
+ if( argc == 3 )
243
+ {
244
+ JID j( argv[1] );
245
+ if( j.resource().empty() )
246
+ {
247
+ printf( "error: need full jid\n" );
248
+ return 1;
249
+ }
250
+ FTTest *r = new FTTest( j, argv[2] );
251
+ r->start();
252
+ delete( r );
253
+ }
254
+ else
255
+ {
256
+ printf( "error: need jid + file\n" );
257
+ }
258
+ return 0;
259
+ }
code/train/C++/0025348_sweeperdaemon.cpp ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * STaRS, Scalable Task Routing approach to distributed Scheduling
3
+ * Copyright (C) 2012 Javier Celaya
4
+ *
5
+ * This file is part of STaRS.
6
+ *
7
+ * STaRS is free software; you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation; either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * STaRS 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 STaRS; if not, see <http://www.gnu.org/licenses/>.
19
+ */
20
+
21
+ #include <sys/types.h>
22
+ #include <sys/stat.h>
23
+ #include <sys/wait.h>
24
+ #include <fcntl.h>
25
+ #include <unistd.h>
26
+ #include <csignal>
27
+ #include <sstream>
28
+ #include <iostream>
29
+ #include <fstream>
30
+ #include <list>
31
+ #include <map>
32
+ #include <string>
33
+ #include <boost/thread.hpp>
34
+ #include <boost/thread/condition.hpp>
35
+ #include <boost/bind.hpp>
36
+ #include <boost/filesystem.hpp>
37
+ using namespace std;
38
+ using namespace boost;
39
+ namespace fs = boost::filesystem;
40
+
41
+
42
+ unsigned long int getAvailableMemory() {
43
+ unsigned long int free;
44
+ unsigned long int total;
45
+ string dummy;
46
+ ifstream file("/proc/meminfo");
47
+ file >> dummy >> total;
48
+ file.ignore(1000, '\n');
49
+ file >> dummy >> free;
50
+ return (free - total / 10) >> 10; // Approx 90% of total memory
51
+ }
52
+
53
+
54
+ class Simulations {
55
+ public:
56
+ static Simulations & getInstance() {
57
+ static Simulations s;
58
+ return s;
59
+ }
60
+
61
+ void parseCmdLine(int argc, char * argv[]);
62
+ int run(int argc, char * argv[]);
63
+ void stop();
64
+ void getNewCases();
65
+ void waitProcesses();
66
+
67
+ pid_t spawnProcess(const map<string, string> & properties);
68
+ unsigned long int getMemoryLimit(const map<string, string> & properties) const {
69
+ unsigned long int mem = 0;
70
+ auto it = properties.find("max_mem");
71
+ if (it != properties.end())
72
+ istringstream(it->second) >> mem;
73
+ return mem;
74
+ }
75
+ void reschedule();
76
+
77
+ private:
78
+ list<map<string, string> > caseInstances;
79
+ bool end, waitOnPipe;
80
+ unsigned int numProcesses;
81
+ unsigned long int availableMemory;
82
+ list<pair<pid_t, unsigned long int> > processes;
83
+ string simExec, pipeName;
84
+ thread pipeThread, waitThread;
85
+ mutex m; ///< Mutex to put and get queue messages.
86
+ condition newCasesOrProcesses; ///< Barrier to wait for a message
87
+ condition children; ///< Barrier to wait for children
88
+
89
+ Simulations() : end(false), waitOnPipe(false), numProcesses(1), availableMemory(getAvailableMemory()), pipeName("sweeperpipe") {}
90
+ };
91
+
92
+
93
+ void getPropertiesList(const string & fileName, std::list<std::map<std::string, std::string> > & combinations);
94
+
95
+
96
+ void finish(int param) {
97
+ Simulations::getInstance().stop();
98
+ }
99
+
100
+
101
+ int main(int argc, char * argv[]) {
102
+ return Simulations::getInstance().run(argc, argv);
103
+ }
104
+
105
+
106
+ void Simulations::parseCmdLine(int argc, char * argv[]) {
107
+ for (int i = 1; i < argc; i++) {
108
+ if (argv[i] == string("-f") && ++i < argc)
109
+ pipeName = argv[i];
110
+ else if (argv[i] == string("-e") && ++i < argc)
111
+ simExec = argv[i];
112
+ else if (argv[i] == string("-p") && ++i < argc)
113
+ istringstream(argv[i]) >> numProcesses;
114
+ else if (argv[i] == string("-m") && ++i < argc)
115
+ istringstream(argv[i]) >> availableMemory;
116
+ }
117
+ }
118
+
119
+
120
+ void Simulations::getNewCases() {
121
+ while (true) {
122
+ list<map<string, string> > newInstances;
123
+ getPropertiesList(pipeName, newInstances);
124
+ this_thread::interruption_point();
125
+ if (newInstances.empty()) continue;
126
+ cout << "Adding " << newInstances.size() << " more cases." << endl;
127
+ {
128
+ mutex::scoped_lock lock(m);
129
+ caseInstances.splice(caseInstances.end(), newInstances);
130
+ }
131
+ newCasesOrProcesses.notify_all();
132
+ }
133
+ }
134
+
135
+
136
+ void Simulations::waitProcesses() {
137
+ while (true) {
138
+ {
139
+ mutex::scoped_lock lock(m);
140
+ if (processes.empty()) {
141
+ if (end)
142
+ return;
143
+ children.wait(lock);
144
+ if (end)
145
+ return;
146
+ }
147
+ }
148
+ pid_t pid = wait(NULL);
149
+ if (pid != -1) {
150
+ cout << "Process " << pid << " ended." << endl;
151
+ {
152
+ mutex::scoped_lock lock(m);
153
+ for (auto it = processes.begin(); it != processes.end(); ++it) {
154
+ if (it->first == pid) {
155
+ availableMemory += it->second;
156
+ processes.erase(it);
157
+ break;
158
+ }
159
+ }
160
+ }
161
+ newCasesOrProcesses.notify_all();
162
+ }
163
+ }
164
+ }
165
+
166
+
167
+ int Simulations::run(int argc, char * argv[]) {
168
+ signal(SIGTERM, finish);
169
+ signal(SIGINT, finish);
170
+
171
+ parseCmdLine(argc, argv);
172
+ if (simExec == "") {
173
+ cerr << "Usage: " << argv[0] << " -e sim_program [-f pipe_name] [-p num_processes] [-m max_memory]" << endl;
174
+ return 1;
175
+ }
176
+ cout << "Using " << numProcesses << " processors and " << availableMemory << " megabytes of memory." << endl;
177
+
178
+ if (fs::exists(pipeName) && fs::is_regular_file(pipeName)) {
179
+ cout << "Reading configuration from " << pipeName << endl;
180
+ getPropertiesList(pipeName, caseInstances);
181
+ waitOnPipe = false;
182
+ } else {
183
+ mknod(pipeName.c_str(), S_IFIFO | 0600, 0);
184
+ cout << "Listening on " << pipeName << endl;
185
+ pipeThread = thread(bind(&Simulations::getNewCases, this));
186
+ waitOnPipe = true;
187
+ }
188
+
189
+ waitThread = thread(bind(&Simulations::waitProcesses, this));
190
+
191
+ do {
192
+ mutex::scoped_lock lock(m);
193
+ reschedule();
194
+ if (!waitOnPipe && caseInstances.empty()) {
195
+ end = true;
196
+ } else {
197
+ if (processes.empty() && waitOnPipe) {
198
+ cout << "Waiting for tests..." << endl;
199
+ }
200
+ newCasesOrProcesses.wait(lock);
201
+ }
202
+ } while (!end);
203
+
204
+ pipeThread.join();
205
+ waitThread.join();
206
+ return 0;
207
+ }
208
+
209
+
210
+ void Simulations::reschedule() {
211
+ // Schedule as many cases as possible until memory is full
212
+ auto instance = caseInstances.begin();
213
+ while (processes.size() < numProcesses && instance != caseInstances.end()) {
214
+ // Try to launch this case
215
+ unsigned long int mem = getMemoryLimit(*instance);
216
+ if (mem <= availableMemory) {
217
+ pid_t pid = spawnProcess(*instance);
218
+ availableMemory -= mem;
219
+ processes.push_back(make_pair(pid, mem));
220
+ children.notify_all();
221
+ instance = caseInstances.erase(instance);
222
+ }
223
+ else {
224
+ if (processes.empty()) {
225
+ cout << "Unable to run simulation, not enough memory." << endl;
226
+ instance = caseInstances.erase(instance);
227
+ } else ++instance;
228
+ }
229
+ }
230
+ }
231
+
232
+
233
+ pid_t Simulations::spawnProcess(const map<string, string> & properties) {
234
+ // Redirect stdio
235
+ int fd[2];
236
+ pipe(fd);
237
+ pid_t pid;
238
+ if ((pid = fork())) {
239
+ // Close read end
240
+ close(fd[0]);
241
+ // Feed configuration through write end
242
+ ostringstream oss;
243
+ for (auto & i : properties) {
244
+ oss << i.first << "=" << i.second << endl;
245
+ }
246
+ write(fd[1], oss.str().c_str(), oss.tellp());
247
+ close(fd[1]);
248
+ return pid;
249
+ } else {
250
+ // Close write end
251
+ close(fd[1]);
252
+ // Set read end as standard input
253
+ dup2(fd[0], 0);
254
+ execl(simExec.c_str(), simExec.c_str(), "-", NULL);
255
+ // This function only returns on error
256
+ cout << "Error running simulation." << endl;
257
+ close(fd[0]);
258
+ exit(1);
259
+ }
260
+ }
261
+
262
+
263
+ void Simulations::stop() {
264
+ end = true;
265
+ pipeThread.interrupt();
266
+ //waitThread.interrupt();
267
+ cout << "Stopping current processes." << endl;
268
+ for (list<pair<pid_t, unsigned long int> >::iterator it = processes.begin(); it != processes.end(); it++)
269
+ kill(it->first, SIGTERM);
270
+ children.notify_all();
271
+ // Signal end of file in the pipe
272
+ ofstream(pipeName.c_str(), ios::out | ios::app).close();
273
+ newCasesOrProcesses.notify_all();
274
+ }
code/train/C++/0025395_part-tld-test.cc ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <fstream>
3
+
4
+ #include "common/Arguments.hpp"
5
+ #include "core/Sequence.hpp"
6
+ #include "parttld/PartTLD.hpp"
7
+
8
+ int main(int argc, char** args) {
9
+ Arguments arguments = Arguments(argc, args);
10
+
11
+ string key = arguments.getString("sequence");
12
+ int limit = arguments.getIntOrDefault("limit", NO_LIMIT);
13
+
14
+ printf("Going to run for %s\n", key.c_str());
15
+ Sequence sequence = Sequence(key, 0, limit);
16
+ Frame* firstFrame = sequence.next();
17
+ Box* initBox = sequence.initBox;
18
+ initBox->isValid = true;
19
+
20
+ initBox->x1 -= 1.0;
21
+ initBox->y1 -= 1.0;
22
+ initBox->x2 -= 1.0;
23
+ initBox->y2 -= 1.0;
24
+
25
+ PartTLD* tld = new PartTLD();
26
+
27
+ Shape* shape0 = tld->init(firstFrame, initBox);
28
+
29
+ Frame* previous = firstFrame;
30
+ while (sequence.hasNext()) {
31
+ Frame* current = sequence.next();
32
+ printf("Frame(%d) >> Frame(%d)\n", previous->id, current->id);
33
+
34
+ Shape* shape1 = tld->track(previous, current, shape0);
35
+
36
+ vector<Box*> currentCorrectedBoxList = shape1->parts;
37
+ ImageBuilder* builder = new ImageBuilder(current);
38
+ int nrOfModels = (int) currentCorrectedBoxList.size();
39
+ for (int i = 0; i < nrOfModels; i++) {
40
+ Box* box = currentCorrectedBoxList[i];
41
+
42
+ if (box != nullptr) {
43
+ // string boxString = box->toTLDString();
44
+ builder->withBox(box, Colors::colors[i]);
45
+ } else {
46
+ printf("Frame(%d) >> Frame(%d) FAILED\n", previous->id, current->id);
47
+ }
48
+ }
49
+
50
+ builder->withCircle(shape1->center, 10);
51
+
52
+ builder->display(1);
53
+
54
+ shape0 = shape1;
55
+
56
+ delete previous;
57
+ previous = current;
58
+ }
59
+
60
+ delete previous;
61
+ delete tld;
62
+
63
+ return EXIT_SUCCESS;
64
+ }
code/train/C++/0025424_possibilities.cc ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "tournament.h"
2
+ #include <iostream>
3
+ #include <iomanip>
4
+ #include <algorithm>
5
+ #include <iterator>
6
+ #include <stdint.h>
7
+ #include "ez/progress.h"
8
+
9
+ struct PossibleScore {
10
+ int pickIndex;
11
+ int score;
12
+ int champ;
13
+ } _PossibleScore;
14
+
15
+ bool sortScores(const PossibleScore& first, const PossibleScore& second) {
16
+ return first.score > second.score;
17
+ }
18
+
19
+ Tournament::Possibilities::Possibilities(const Tournament::Bracket& b, const Tournament::Scorer& s, int batch, int num_batches) :
20
+ bracket_(b), scorer_(s), batch_(batch), number_of_batches_(num_batches), shifts_(NULL) {
21
+ reset();
22
+ }
23
+
24
+ Tournament::Possibilities::~Possibilities() {
25
+ delete shifts_;
26
+ }
27
+
28
+ void Tournament::Possibilities::reset() {
29
+ if (shifts_) {
30
+ delete shifts_;
31
+ }
32
+ games_left_ = bracket_.totalGames() - bracket_.gamesPlayed();
33
+ shifts_ = new std::vector<int>(games_left_ + 1);
34
+ uint64_t left = Tournament::flipBits(bracket_.played());
35
+ uint64_t offset = 0ULL;
36
+ uint64_t limit = bracket_.numberOfOutcomes();
37
+ if (number_of_batches_ > 1) {
38
+ limit = (uint64_t) ((double) limit / number_of_batches_ + 0.5);
39
+ offset = limit * batch_;
40
+ }
41
+ int shift_count = 0;
42
+ for (int left_bit = 0; left_bit < bracket_.numberOfTeams(); ++left_bit) {
43
+ if (left & (1ULL << left_bit)) {
44
+ shifts_->at(shift_count++) = left_bit;
45
+ }
46
+ }
47
+ start_ = bracket_.numberOfOutcomes() - 1ULL - offset;
48
+ end_ = batch_ == number_of_batches_ - 1 ? 0ULL : bracket_.numberOfOutcomes() - offset - limit;
49
+ }
50
+
51
+ std::vector<Tournament::Stats>
52
+ Tournament::Possibilities::scorePicks(const std::vector<Tournament::Bracket>& picks,
53
+ bool debug) {
54
+ uint64_t possibility = start_;
55
+ uint64_t played = (1ULL << (bracket_.numberOfTeams() - 1)) - 1;
56
+ uint64_t total = start_ - end_ + 1;
57
+ if (debug) {
58
+ std::cout << "Checking " << total << " outcomes of bracket: " << bracket_ << std::endl;
59
+ std::cout << "Number of entries: " << picks.size() << std::endl;
60
+ std::cout << "Start: " << start_ << " -> End: " << end_ << std::endl;
61
+ std::cout << "Total Outcomes: " << bracket_.numberOfOutcomes() << std::endl;
62
+ }
63
+
64
+ ez::Progress progress(total);
65
+ progress.width = 60;
66
+
67
+ std::vector<Stats> allStats(picks.size());
68
+ std::vector<PossibleScore> pickScores(picks.size());
69
+ if (debug) {
70
+ progress.start();
71
+ }
72
+ while (possibility != end_) {
73
+ uint64_t real_poss = 0;
74
+ for(int i = 0; i < games_left_; ++i) {
75
+ real_poss |= (((possibility & (1ULL << i)) ? 1ULL : 0ULL) << shifts_->at(i));
76
+ }
77
+ real_poss = bracket_.results() | real_poss;
78
+ Tournament::Bracket possible_bracket(bracket_.numberOfTeams(), real_poss, played);
79
+ for(int p = 0; p < picks.size(); p++) {
80
+ Tournament::Scorer::Score score = scorer_.score(possible_bracket, picks[p]);
81
+ pickScores[p].pickIndex = p;
82
+ pickScores[p].score = score.score;
83
+ pickScores[p].champ = possible_bracket.winner();
84
+ //std::cout << "POSS: " << possibility << ": " << picks[p] << " <-> " << possible_bracket << ": score=" << score.score << " max=" << score.max << std::endl;
85
+ }
86
+ std::sort(pickScores.begin(), pickScores.end(), sortScores);
87
+ int currentScore = pickScores[0].score;
88
+ int actualRank = 1;
89
+ for(int i = 0; i < picks.size(); ++i) {
90
+ PossibleScore& score = pickScores[i];
91
+ Tournament::Stats& stats = allStats[score.pickIndex];
92
+ if (score.score < currentScore) {
93
+ actualRank++;
94
+ currentScore = score.score;
95
+ }
96
+ if (score.score > stats.maxScore) {
97
+ stats.maxScore = score.score;
98
+ }
99
+ if (actualRank < stats.maxRank) {
100
+ stats.maxRank = actualRank;
101
+ }
102
+ if (actualRank > stats.minRank) {
103
+ stats.minRank = actualRank;
104
+ }
105
+ if (actualRank == 1) {
106
+ stats.champCounts[score.champ]++;
107
+ }
108
+ }
109
+
110
+ if (possibility == end_) {
111
+ break;
112
+ }
113
+ if (debug) {
114
+ ++progress;
115
+ }
116
+ possibility--;
117
+ }
118
+ if (debug) { std::cout << std::endl << "Done." << std::endl; }
119
+ return allStats;
120
+ }
code/train/C++/0025962_Otsu.cc ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*-c++-*-
2
+
3
+ This file is part of the IC reverse engineering tool degate.
4
+
5
+ Copyright 2013 by Taekgwan Kim
6
+
7
+ Degate is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ any later version.
11
+
12
+ Degate 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 degate. If not, see <http://www.gnu.org/licenses/>.
19
+
20
+ */
21
+
22
+ #include <Otsu.h>
23
+
24
+ using namespace degate;
25
+
26
+ Otsu::Otsu() :
27
+ otsu_threshold(0) {}
28
+
29
+ Otsu::~Otsu() {}
30
+
31
+ double Otsu::get_otsu_threshold() {
32
+ return otsu_threshold;
33
+ }
34
+
35
+ void Otsu::run(TileImage_GS_DOUBLE_shptr gray) {
36
+ unsigned long histData[256] = {0,};
37
+
38
+ for(unsigned int y = 0; y < gray->get_height(); y++)
39
+ for(unsigned int x = 0; x < gray->get_width(); x++) {
40
+ gs_byte_pixel_t h = gray->get_pixel_as<gs_byte_pixel_t>(x, y);
41
+ assert((h >= 0) && (h < 256));
42
+ histData[h]++;
43
+ }
44
+
45
+ unsigned long total = gray->get_height() * gray->get_width();
46
+
47
+ double sum = 0;
48
+ for(int t=0; t < 256; t++)
49
+ sum += t * histData[t];
50
+
51
+ double sumB = 0;
52
+ unsigned long wB = 0;
53
+ unsigned long wF = 0;
54
+
55
+ double varMax = 0;
56
+
57
+ for(int t=0; t<256; t++)
58
+ {
59
+ wB += histData[t];
60
+ if(wB == 0)
61
+ continue;
62
+
63
+ wF = total - wB;
64
+ if(wF == 0)
65
+ break;
66
+ sumB += (double)(t * histData[t]);
67
+
68
+ double mB = sumB / wB;
69
+ double mF = (sum - sumB) /wF;
70
+ double varBetween = (double)wB * (double)wF * (mB-mF) * (mB-mF);
71
+
72
+ if(varBetween > varMax)
73
+ {
74
+ varMax = varBetween;
75
+ otsu_threshold = t;
76
+ }
77
+ }
78
+ }
code/train/C++/0025967_16.cpp ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "stdafx.h"
2
+ #include <vector>
3
+ #include <map>
4
+ #include <unordered_set>
5
+ #include <string>
6
+ #include <iostream>
7
+ #include <assert.h>
8
+ #include <algorithm>
9
+ using namespace std;
10
+
11
+
12
+ // https://leetcode.com/problems/3sum-closest/
13
+ class Solution {
14
+ public:
15
+
16
+ int threeSumClosest(vector<int>& nums, int target) {
17
+ int result = -1;
18
+ int minDiffSoFar = INT32_MAX;
19
+
20
+ if (nums.size() < 3) {
21
+ return result;
22
+ }
23
+ else if (nums.size() == 3) {
24
+ return (nums[0] + nums[1] + nums[2]);
25
+ }
26
+
27
+ std::sort(nums.begin(), nums.end());
28
+
29
+ int n = nums.size();
30
+ for (int i = 0; i < n - 2; i++) {
31
+ int a = nums[i];
32
+ int start = i + 1;
33
+ int end = n - 1;
34
+ while (start < end) {
35
+ assert(i != start);
36
+ assert(i != end);
37
+ assert(start != end);
38
+ int b = nums[start];
39
+ int c = nums[end];
40
+ int sum = a + b + c;
41
+ int diff = sum - target;
42
+ int absDiff = abs(diff);
43
+ if (absDiff < minDiffSoFar) {
44
+ minDiffSoFar = absDiff;
45
+ result = sum;
46
+ }
47
+
48
+ if (diff > 0) {
49
+ end--;
50
+ }
51
+ else if(diff < 0) {
52
+ start++;
53
+ }
54
+
55
+ if (diff == 0) {
56
+ return target;
57
+ }
58
+ }
59
+ }
60
+ return result;
61
+ }
62
+ };
63
+
64
+ int _16(int argc, _TCHAR* argv[])
65
+ {
66
+ Solution s;
67
+ vector<int> input = { 1,1,1,1 };
68
+
69
+ printf("%d\n", s.threeSumClosest(input, 0));
70
+ return 0;
71
+ }
code/train/C++/0026485_tst_qscopedvaluerollback.cpp ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /****************************************************************************
2
+ **
3
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4
+ ** Contact: http://www.qt-project.org/legal
5
+ **
6
+ ** This file is part of the test suite of the Qt Toolkit.
7
+ **
8
+ ** $QT_BEGIN_LICENSE:LGPL$
9
+ ** Commercial License Usage
10
+ ** Licensees holding valid commercial Qt licenses may use this file in
11
+ ** accordance with the commercial license agreement provided with the
12
+ ** Software or, alternatively, in accordance with the terms contained in
13
+ ** a written agreement between you and Digia. For licensing terms and
14
+ ** conditions see http://qt.digia.com/licensing. For further information
15
+ ** use the contact form at http://qt.digia.com/contact-us.
16
+ **
17
+ ** GNU Lesser General Public License Usage
18
+ ** Alternatively, this file may be used under the terms of the GNU Lesser
19
+ ** General Public License version 2.1 as published by the Free Software
20
+ ** Foundation and appearing in the file LICENSE.LGPL included in the
21
+ ** packaging of this file. Please review the following information to
22
+ ** ensure the GNU Lesser General Public License version 2.1 requirements
23
+ ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
+ **
25
+ ** In addition, as a special exception, Digia gives you certain additional
26
+ ** rights. These rights are described in the Digia Qt LGPL Exception
27
+ ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28
+ **
29
+ ** GNU General Public License Usage
30
+ ** Alternatively, this file may be used under the terms of the GNU
31
+ ** General Public License version 3.0 as published by the Free Software
32
+ ** Foundation and appearing in the file LICENSE.GPL included in the
33
+ ** packaging of this file. Please review the following information to
34
+ ** ensure the GNU General Public License version 3.0 requirements will be
35
+ ** met: http://www.gnu.org/copyleft/gpl.html.
36
+ **
37
+ **
38
+ ** $QT_END_LICENSE$
39
+ **
40
+ ****************************************************************************/
41
+
42
+ #include <QtTest/QtTest>
43
+ #include <QtCore/QScopedValueRollback>
44
+
45
+ /*!
46
+ \class tst_QScopedValueRollback
47
+ \internal
48
+ \since 4.8
49
+ \brief Tests class QScopedValueRollback.
50
+
51
+ */
52
+ class tst_QScopedValueRollback : public QObject
53
+ {
54
+ Q_OBJECT
55
+
56
+ private Q_SLOTS:
57
+ void leavingScope();
58
+ void leavingScopeAfterCommit();
59
+ void rollbackToPreviousCommit();
60
+ void exceptions();
61
+ void earlyExitScope();
62
+ private:
63
+ void earlyExitScope_helper(int exitpoint, int &member);
64
+ };
65
+
66
+ void tst_QScopedValueRollback::leavingScope()
67
+ {
68
+ int i = 0;
69
+ bool b = false;
70
+ QString s("This is useful");
71
+
72
+ //test rollback on going out of scope
73
+ {
74
+ QScopedValueRollback<int> ri(i);
75
+ QScopedValueRollback<bool> rb(b);
76
+ QScopedValueRollback<QString> rs(s);
77
+ QCOMPARE(b, false);
78
+ QCOMPARE(i, 0);
79
+ QCOMPARE(s, QString("This is useful"));
80
+ b = true;
81
+ i = 1;
82
+ s = "Useless";
83
+ QCOMPARE(b, true);
84
+ QCOMPARE(i, 1);
85
+ QCOMPARE(s, QString("Useless"));
86
+ }
87
+ QCOMPARE(b, false);
88
+ QCOMPARE(i, 0);
89
+ QCOMPARE(s, QString("This is useful"));
90
+ }
91
+
92
+ void tst_QScopedValueRollback::leavingScopeAfterCommit()
93
+ {
94
+ int i = 0;
95
+ bool b = false;
96
+ QString s("This is useful");
97
+
98
+ //test rollback on going out of scope
99
+ {
100
+ QScopedValueRollback<int> ri(i);
101
+ QScopedValueRollback<bool> rb(b);
102
+ QScopedValueRollback<QString> rs(s);
103
+ QCOMPARE(b, false);
104
+ QCOMPARE(i, 0);
105
+ QCOMPARE(s, QString("This is useful"));
106
+ b = true;
107
+ i = 1;
108
+ s = "Useless";
109
+ QCOMPARE(b, true);
110
+ QCOMPARE(i, 1);
111
+ QCOMPARE(s, QString("Useless"));
112
+ ri.commit();
113
+ rb.commit();
114
+ rs.commit();
115
+ }
116
+ QCOMPARE(b, true);
117
+ QCOMPARE(i, 1);
118
+ QCOMPARE(s, QString("Useless"));
119
+ }
120
+
121
+ void tst_QScopedValueRollback::rollbackToPreviousCommit()
122
+ {
123
+ int i=0;
124
+ {
125
+ QScopedValueRollback<int> ri(i);
126
+ i++;
127
+ ri.commit();
128
+ i++;
129
+ }
130
+ QCOMPARE(i,1);
131
+ {
132
+ QScopedValueRollback<int> ri1(i);
133
+ i++;
134
+ ri1.commit();
135
+ i++;
136
+ ri1.commit();
137
+ i++;
138
+ }
139
+ QCOMPARE(i,3);
140
+ }
141
+
142
+ void tst_QScopedValueRollback::exceptions()
143
+ {
144
+ bool b = false;
145
+ bool caught = false;
146
+ QT_TRY
147
+ {
148
+ QScopedValueRollback<bool> rb(b);
149
+ b = true;
150
+ QT_THROW(std::bad_alloc()); //if Qt compiled without exceptions this is noop
151
+ rb.commit(); //if Qt compiled without exceptions, true is committed
152
+ }
153
+ QT_CATCH(...)
154
+ {
155
+ caught = true;
156
+ }
157
+ QCOMPARE(b, !caught); //expect false if exception was thrown, true otherwise
158
+ }
159
+
160
+ void tst_QScopedValueRollback::earlyExitScope()
161
+ {
162
+ int i=0;
163
+ int j=0;
164
+ while (true) {
165
+ QScopedValueRollback<int> ri(i);
166
+ i++;
167
+ j=i;
168
+ if (i>8) break;
169
+ ri.commit();
170
+ }
171
+ QCOMPARE(i,8);
172
+ QCOMPARE(j,9);
173
+
174
+ for (i = 0; i < 5; i++) {
175
+ j=1;
176
+ earlyExitScope_helper(i,j);
177
+ QCOMPARE(j, 1<<i);
178
+ }
179
+ }
180
+
181
+ void tst_QScopedValueRollback::earlyExitScope_helper(int exitpoint, int& member)
182
+ {
183
+ QScopedValueRollback<int> r(member);
184
+ member *= 2;
185
+ if (exitpoint == 0)
186
+ return;
187
+ r.commit();
188
+ member *= 2;
189
+ if (exitpoint == 1)
190
+ return;
191
+ r.commit();
192
+ member *= 2;
193
+ if (exitpoint == 2)
194
+ return;
195
+ r.commit();
196
+ member *= 2;
197
+ if (exitpoint == 3)
198
+ return;
199
+ r.commit();
200
+ }
201
+
202
+ QTEST_MAIN(tst_QScopedValueRollback)
203
+ #include "tst_qscopedvaluerollback.moc"
code/train/C++/0026931_FEEPROM.cpp ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //all the functions are defined in the header file .cpp file have the constructor the wrapped up class is in the header file
2
+
3
+ #include "FEEPROM.h" // access to the definitions of the hmorse header file
4
+
5
+ FEEPROM::FEEPROM(word sA, word eA) //constructor when a object of this type is created this constructor is called
6
+ {
7
+ startAdd = sA;
8
+ endAdd = eA;
9
+ }
10
+
11
+ void FEEPROM::clearAllFEEPROM(void) //this function clears all the values in the eeprom block
12
+ {
13
+ for(word i=0; i<=endAdd; i+=4)
14
+ {
15
+ EEPROM.put(i,0);
16
+ }
17
+ }
18
+
19
+ void FEEPROM::writeCircularFEEPROM(float f) //this function will write values in a circular buffer way
20
+ {
21
+ static word add = startAdd;
22
+ EEPROM.put(add,f);
23
+ add+=4;
24
+ if(add>endAdd)
25
+ add=startAdd;
26
+ }
27
+
28
+ float FEEPROM::readMaxFEEPROM(void) //returns max value of a block
29
+ {
30
+ static float maxValue=0.0;
31
+ EEPROM.get(startAdd,maxValue);
32
+ for(word i=startAdd; i<=endAdd; i+=4)
33
+ {
34
+ float tmp;
35
+ EEPROM.get(i,tmp);
36
+ maxValue=max(tmp,maxValue);
37
+ }
38
+ return maxValue;
39
+ }
40
+
41
+
42
+
code/train/C++/0027205_main.cpp ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // https://github.com/KubaO/stackoverflown/tree/master/questions/process-fix-binary-crlf-51519654
2
+ #include <QtCore>
3
+ #include <algorithm>
4
+
5
+ bool appendBinFix(QByteArray &buf, const char *src, int size) {
6
+ bool okData = true;
7
+ if (!size) return okData;
8
+ constexpr char CR = '\x0d';
9
+ constexpr char LF = '\x0a';
10
+ bool hasCR = buf.endsWith(CR);
11
+ buf.resize(buf.size() + size);
12
+ char *dst = buf.end() - size;
13
+ const char *lastSrc = src;
14
+ for (const char *const end = src + size; src != end; src++) {
15
+ char const c = *src;
16
+ if (c == LF) {
17
+ if (hasCR) {
18
+ std::copy(lastSrc, src, dst);
19
+ dst += (src - lastSrc);
20
+ dst[-1] = LF;
21
+ lastSrc = src + 1;
22
+ } else
23
+ okData = false;
24
+ }
25
+ hasCR = (c == CR);
26
+ }
27
+ dst = std::copy(lastSrc, src, dst);
28
+ buf.resize(dst - buf.constData());
29
+ return okData;
30
+ }
31
+
32
+ bool appendBinFix(QByteArray &buf, const QByteArray &src) {
33
+ return appendBinFix(buf, src.data(), src.size());
34
+ }
35
+
36
+ #include <QtTest>
37
+ #include <cstdio>
38
+ #ifdef Q_OS_WIN
39
+ #include <fcntl.h>
40
+ #include <io.h>
41
+ #endif
42
+
43
+ const auto dataFixed = QByteArrayLiteral("\x00\x11\x0d\x0a\x33");
44
+ const auto data = QByteArrayLiteral("\x00\x11\x0d\x0d\x0a\x33");
45
+
46
+ int writeOutput() {
47
+ #ifdef Q_OS_WIN
48
+ _setmode(_fileno(stdout), _O_BINARY);
49
+ #endif
50
+ auto size = fwrite(data.data(), 1, data.size(), stdout);
51
+ qDebug() << size << data.size();
52
+ return (size == data.size()) ? 0 : 1;
53
+ }
54
+
55
+ class AppendTest : public QObject {
56
+ Q_OBJECT
57
+ struct Result {
58
+ QByteArray d;
59
+ bool ok;
60
+ bool operator==(const Result &o) const { return ok == o.ok && d == o.d; }
61
+ };
62
+ static Result getFixed(const QByteArray &src, int split) {
63
+ Result f;
64
+ f.ok = appendBinFix(f.d, src.data(), split);
65
+ f.ok = appendBinFix(f.d, src.data() + split, src.size() - split) && f.ok;
66
+ return f;
67
+ }
68
+ Q_SLOT void worksWithLFCR() {
69
+ const auto lf_cr = QByteArrayLiteral("\x00\x11\x0a\x0d\x33");
70
+ for (int i = 0; i < lf_cr.size(); ++i)
71
+ QCOMPARE(getFixed(lf_cr, i), (Result{lf_cr, false}));
72
+ }
73
+ Q_SLOT void worksWithCRLF() {
74
+ const auto cr_lf = QByteArrayLiteral("\x00\x11\x0d\x0a\x33");
75
+ const auto cr_lf_fixed = QByteArrayLiteral("\x00\x11\x0a\x33");
76
+ for (int i = 0; i < cr_lf.size(); ++i)
77
+ QCOMPARE(getFixed(cr_lf, i), (Result{cr_lf_fixed, true}));
78
+ }
79
+ Q_SLOT void worksWithCRCRLF() {
80
+ for (int i = 0; i < data.size(); ++i) QCOMPARE(getFixed(data, i).d, dataFixed);
81
+ }
82
+ Q_SLOT void worksWithQProcess() {
83
+ QProcess proc;
84
+ proc.start(QCoreApplication::applicationFilePath(), {"output"},
85
+ QIODevice::ReadOnly);
86
+ proc.waitForFinished(5000);
87
+ QCOMPARE(proc.exitCode(), 0);
88
+ QCOMPARE(proc.exitStatus(), QProcess::NormalExit);
89
+
90
+ QByteArray out = proc.readAllStandardOutput();
91
+ QByteArray fixed;
92
+ appendBinFix(fixed, out);
93
+ QCOMPARE(out, data);
94
+ QCOMPARE(fixed, dataFixed);
95
+ }
96
+ };
97
+
98
+ int main(int argc, char *argv[]) {
99
+ QCoreApplication app(argc, argv);
100
+ if (app.arguments().size() > 1) return writeOutput();
101
+ AppendTest test;
102
+ QTEST_SET_MAIN_SOURCE_PATH
103
+ return QTest::qExec(&test, argc, argv);
104
+ }
105
+ #include "main.moc"
code/train/C++/0027411_Defines.cpp ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Common/Defines.h"
2
+ #include "Crypto/Commit.h"
3
+ #include "Common/BitVector.h"
4
+ //#include "Common/Timer.h"
5
+ #include <boost/math/special_functions/binomial.hpp>
6
+ #include <boost/multiprecision/cpp_bin_float.hpp>
7
+
8
+ namespace bOPRF {
9
+
10
+ Timer gTimer;
11
+ const block ZeroBlock = _mm_set_epi64x(0, 0);
12
+ const block OneBlock = _mm_set_epi64x(0, 1);
13
+ const block AllOneBlock = _mm_set_epi64x(u64(-1), u64(-1));
14
+ const block CCBlock = ([]() {block cc; memset(&cc, 0xcc, sizeof(block)); return cc; })();
15
+
16
+ std::ostream& operator<<(std::ostream& out, const block& blk)
17
+ {
18
+ out << std::hex;
19
+ u64* data = (u64*)&blk;
20
+
21
+ out << std::setw(16) << std::setfill('0') << data[0]
22
+ << std::setw(16) << std::setfill('0') << data[1];
23
+
24
+ out << std::dec << std::setw(0);
25
+
26
+ return out;
27
+ }
28
+
29
+ std::ostream& operator<<(std::ostream& out, const blockBop& blk)
30
+ {
31
+ out << std::hex;
32
+ u64* data = (u64*)&blk;
33
+
34
+ out << std::setw(16) << std::setfill('0') << data[0] << "..."
35
+ //<< std::setw(16) << std::setfill('0') << data[1]
36
+ //<< std::setw(16) << std::setfill('0') << data[2]
37
+ //<< std::setw(16) << std::setfill('0') << data[3]
38
+ //<< std::setw(16) << std::setfill('0') << data[4]
39
+ //<< std::setw(16) << std::setfill('0') << data[5]
40
+ << std::setw(16) << std::setfill('0') << data[6];
41
+
42
+ out << std::dec << std::setw(0);
43
+
44
+ return out;
45
+ }
46
+
47
+
48
+ std::ostream* gOut = &std::cout;
49
+
50
+
51
+
52
+ std::ostream& operator<<(std::ostream& out, const Commit& comm)
53
+ {
54
+ out << std::hex;
55
+
56
+ u32* data = (u32*)comm.data();
57
+
58
+ out << std::setw(8) << std::setfill('0') << data[0]
59
+ << std::setw(8) << std::setfill('0') << data[1]
60
+ << std::setw(8) << std::setfill('0') << data[2]
61
+ << std::setw(8) << std::setfill('0') << data[3]
62
+ << std::setw(8) << std::setfill('0') << data[4];
63
+
64
+ out << std::dec << std::setw(0);
65
+
66
+ return out;
67
+ }
68
+ block PRF(const block& b, u64 i)
69
+ {
70
+ //TODO("REMOVE THIS!!");
71
+ //return b;
72
+
73
+
74
+
75
+
76
+
77
+ block ret, tweak = _mm_set1_epi64x(i), enc;
78
+
79
+ ret = b ^ tweak;
80
+
81
+ mAesFixedKey.ecbEncBlock(ret, enc);
82
+
83
+ ret = ret ^ enc; // H( a0 )
84
+
85
+ return ret;
86
+ }
87
+
88
+ void split(const std::string &s, char delim, std::vector<std::string> &elems) {
89
+ std::stringstream ss(s);
90
+ std::string item;
91
+ while (std::getline(ss, item, delim)) {
92
+ elems.push_back(item);
93
+ }
94
+ }
95
+
96
+ std::vector<std::string> split(const std::string &s, char delim) {
97
+ std::vector<std::string> elems;
98
+ split(s, delim, elems);
99
+ return elems;
100
+ }
101
+
102
+ const int tab64[64] = {
103
+ 63, 0, 58, 1, 59, 47, 53, 2,
104
+ 60, 39, 48, 27, 54, 33, 42, 3,
105
+ 61, 51, 37, 40, 49, 18, 28, 20,
106
+ 55, 30, 34, 11, 43, 14, 22, 4,
107
+ 62, 57, 46, 52, 38, 26, 32, 41,
108
+ 50, 36, 17, 19, 29, 10, 13, 21,
109
+ 56, 45, 25, 31, 35, 16, 9, 12,
110
+ 44, 24, 15, 8, 23, 7, 6, 5 };
111
+
112
+
113
+ u64 log2floor(u64 value)
114
+ {
115
+ value |= value >> 1;
116
+ value |= value >> 2;
117
+ value |= value >> 4;
118
+ value |= value >> 8;
119
+ value |= value >> 16;
120
+ value |= value >> 32;
121
+ return tab64[((uint64_t)((value - (value >> 1)) * 0x07EDD5E59A4E28C2)) >> 58];
122
+ }
123
+
124
+ u64 log2ceil(u64 value)
125
+ {
126
+ return u64(std::ceil(std::log2(value)));
127
+ }
128
+
129
+ u64 get_stash_size(u64 neles) {
130
+ if (neles >= (1 << 24))
131
+ return 2;
132
+ if (neles >= (1 << 20))
133
+ return 3;
134
+ if (neles >= (1 << 16))
135
+ return 4;
136
+ if (neles >= (1 << 12))
137
+ return 6;
138
+ if (neles >= (1 << 8))
139
+ return 12;
140
+
141
+ return 12; //other
142
+
143
+ throw std::runtime_error("get_stash_size: rt error at " LOCATION);
144
+
145
+ }
146
+
147
+ //template<unsigned int N = 16>
148
+ double getBinOverflowProb(u64 numBins, u64 numBalls, u64 binSize, double epsilon = 0.0001)
149
+ {
150
+ if (numBalls <= binSize)
151
+ return std::numeric_limits<double>::max();
152
+
153
+ if (numBalls > unsigned(-1))
154
+ {
155
+ auto msg = ("boost::math::binomial_coefficient(...) only supports " + std::to_string(sizeof(unsigned) * 8) + " bit inputs which was exceeded." LOCATION);
156
+ std::cout << msg << std::endl;
157
+ throw std::runtime_error(msg);
158
+ }
159
+
160
+ //try
161
+ //{
162
+
163
+ //std::cout << numBalls << " " << numBins << " " << binSize << std::endl;
164
+ typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<16>> T;
165
+ T sum = 0.0;
166
+ T sec = 0.0;// minSec + 1;
167
+ T diff = 1;
168
+ u64 i = binSize + 1;
169
+
170
+
171
+ while (diff > T(epsilon) && numBalls >= i /*&& sec > minSec*/)
172
+ {
173
+ sum += numBins * boost::math::binomial_coefficient<T>(numBalls, i)
174
+ * boost::multiprecision::pow(T(1.0) / numBins, i) * boost::multiprecision::pow(1 - T(1.0) / numBins, numBalls - i);
175
+
176
+ //std::cout << "sum[" << i << "] " << sum << std::endl;
177
+
178
+ T sec2 = boost::multiprecision::log2(sum);
179
+ diff = boost::multiprecision::abs(sec - sec2);
180
+ //std::cout << diff << std::endl;
181
+ sec = sec2;
182
+
183
+ i++;
184
+ }
185
+
186
+ return std::max<double>(0, (double)-sec);
187
+ //}
188
+ //catch (std::exception& e)
189
+ //{
190
+ // if (N == 16)
191
+ // {
192
+ // std::cout << "percision failure at " << LOCATION << "\n tring again with high percision (performance penalty)" << std::endl;
193
+ // // try again with higher percition
194
+ // return getBinOverflowProb<128>(numBins, numBalls, binSize);
195
+ // }
196
+ //
197
+ // std::cout << "retry percision failure at " << LOCATION << "\n" << e.what() << std::endl;
198
+ // throw;
199
+ //}
200
+ }
201
+
202
+ u64 get_bin_size(u64 numBins, u64 numBalls, u64 statSecParam)
203
+ {
204
+
205
+ auto B = std::max<u64>(1, numBalls / numBins);
206
+
207
+ double currentProb = 0;
208
+ u64 step = 1;
209
+
210
+ bool doubling = true;
211
+
212
+ while (currentProb < statSecParam || step > 1)
213
+ {
214
+ if (!step)
215
+ throw std::runtime_error(LOCATION);
216
+
217
+
218
+ if (statSecParam > currentProb)
219
+ {
220
+ if (doubling) step = std::max<u64>(1, step * 2);
221
+ else step = std::max<u64>(1, step / 2);
222
+
223
+ B += step;
224
+ }
225
+ else
226
+ {
227
+ doubling = false;
228
+ step = std::max<u64>(1, step / 2);
229
+ B -= step;
230
+ }
231
+ currentProb = getBinOverflowProb(numBins, numBalls, B);
232
+ }
233
+
234
+
235
+
236
+ return B;
237
+ //if (simpleSize <= cuckooSize)
238
+ //{
239
+
240
+ // if (simpleSize >= (1 << 24))
241
+ // return 28;
242
+ // if (simpleSize >= (1 << 20))
243
+ // return 27;
244
+ // if (simpleSize >= (1 << 16))
245
+ // return 26;
246
+ // if (simpleSize >= (1 << 12))
247
+ // return 25;
248
+ // if (simpleSize >= (1 << 8))
249
+ // return 24;
250
+
251
+ // //return 30; //other
252
+ //}
253
+ //else
254
+ //{
255
+ // return simpleSize / cuckooSize + 16 + 4 * std::sqrt(simpleSize * std::log2(cuckooSize) / cuckooSize);
256
+ //}
257
+
258
+ //throw std::runtime_error("get_bin_size: rt error at " LOCATION);
259
+ }
260
+
261
+ u64 get_codeword_size(u64 neles) {
262
+ if (neles >= (1 << 24))
263
+ return 448 / 8; // in byte
264
+ if (neles >= (1 << 20))
265
+ return 448 / 8;
266
+ if (neles >= (1 << 16))
267
+ return 440 / 8;
268
+ if (neles >= (1 << 12))
269
+ return 432 / 8;
270
+ if (neles >= (1 << 8))
271
+ return 424 / 8;
272
+
273
+ return 424 / 8;
274
+
275
+ //throw std::runtime_error("get_codeword_size: rt error at " LOCATION);
276
+ }
277
+ u64 get_mask_size(u64 neles, u64 othersize, u64 statSecParam) {
278
+
279
+
280
+ return (statSecParam + log2(neles * othersize) + 7 ) / 8;
281
+
282
+ //if (neles >= (1 << 24))
283
+ // return 88 / 8; // in byte
284
+ //if (neles >= (1 << 20))
285
+ // return 80 / 8;
286
+ //if (neles >= (1 << 16))
287
+ // return 72 / 8;
288
+ //if (neles >= (1 << 12))
289
+ // return 64 / 8;
290
+ //if (neles >= (1 << 8))
291
+ // return 56 / 8;
292
+
293
+ //return 56 / 8;
294
+ ////return (40 + 2 * log(neles)) / 8;
295
+
296
+ // throw std::runtime_error("get_codeword_size: rt error at " LOCATION);
297
+ }
298
+ }
299
+
300
+
code/train/C++/0027495_uf.cc ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // libsemigroups - C++ library for semigroups and monoids
3
+ // Copyright (C) 2017 Michael Torpey
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU General Public License
16
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ //
18
+
19
+ // This file defines UF, a class used to make an equivalence relation on
20
+ // the integers {1 .. n}, using the UNION-FIND METHOD: new pairs can be added
21
+ // and the appropriate classes combined quickly.
22
+
23
+ #include "uf.h"
24
+
25
+ #include "libsemigroups-debug.h"
26
+
27
+ namespace libsemigroups {
28
+
29
+ // Copy constructor
30
+ UF::UF(const UF& copy)
31
+ : _size(copy._size),
32
+ _table(new table_t(*copy._table)),
33
+ _blocks(nullptr),
34
+ _haschanged(copy._haschanged) {
35
+ if (copy._blocks != nullptr) {
36
+ // Copy the blocks as well
37
+ _blocks = new blocks_t();
38
+ _blocks->reserve(copy._blocks->size());
39
+ for (auto const& block : *copy._blocks) {
40
+ if (block == nullptr) {
41
+ _blocks->push_back(nullptr);
42
+ } else {
43
+ _blocks->push_back(new table_t(*block));
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ // Constructor by table
50
+ UF::UF(const table_t& table)
51
+ : _size(table.size()),
52
+ _table(new table_t(table)),
53
+ _blocks(nullptr),
54
+ _haschanged(true),
55
+ _next_rep(0) {}
56
+
57
+ // Constructor by size
58
+ UF::UF(size_t size)
59
+ : _size(size),
60
+ _table(new table_t()),
61
+ _blocks(nullptr),
62
+ _haschanged(false),
63
+ _next_rep(0) {
64
+ _table->reserve(size);
65
+ for (size_t i = 0; i < size; i++) {
66
+ _table->push_back(i);
67
+ }
68
+ }
69
+
70
+ // Destructor
71
+ UF::~UF() {
72
+ delete _table;
73
+ if (_blocks != nullptr) {
74
+ for (size_t i = 0; i < _blocks->size(); i++) {
75
+ delete _blocks->at(i);
76
+ }
77
+ delete _blocks;
78
+ }
79
+ }
80
+
81
+ // Getters
82
+ size_t UF::get_size() {
83
+ return _size;
84
+ }
85
+
86
+ UF::table_t* UF::get_table() {
87
+ return _table;
88
+ }
89
+
90
+ // get_blocks
91
+ UF::blocks_t* UF::get_blocks() {
92
+ table_t* block;
93
+ // Is _blocks "bound" yet?
94
+ if (_blocks == nullptr) {
95
+ _blocks = new blocks_t();
96
+ _blocks->reserve(_size);
97
+ for (size_t i = 0; i < _size; i++) {
98
+ block = new table_t(1, i);
99
+ _blocks->push_back(block);
100
+ }
101
+ }
102
+ // Do we need to update the blocks?
103
+ if (_haschanged) {
104
+ size_t ii;
105
+ for (size_t i = 0; i < _size; i++) {
106
+ if (_blocks->at(i) != nullptr) {
107
+ ii = find(i);
108
+ if (ii != i) {
109
+ // Combine the two blocks
110
+ _blocks->at(ii)->reserve(_blocks->at(ii)->size()
111
+ + _blocks->at(i)->size());
112
+ _blocks->at(ii)->insert(_blocks->at(ii)->end(),
113
+ _blocks->at(i)->begin(),
114
+ _blocks->at(i)->end());
115
+ delete _blocks->at(i);
116
+ _blocks->at(i) = nullptr;
117
+ }
118
+ }
119
+ }
120
+ _haschanged = false;
121
+ }
122
+ return _blocks;
123
+ }
124
+
125
+ // find
126
+ size_t UF::find(size_t i) {
127
+ size_t ii;
128
+ LIBSEMIGROUPS_ASSERT(_size == _table->size());
129
+ do {
130
+ ii = i;
131
+ LIBSEMIGROUPS_ASSERT(ii < _size);
132
+ i = (*_table)[ii];
133
+ } while (ii != i);
134
+ return i;
135
+ }
136
+
137
+ // union
138
+ void UF::unite(size_t i, size_t j) {
139
+ size_t ii, jj;
140
+ LIBSEMIGROUPS_ASSERT(_size == _table->size());
141
+ ii = find(i);
142
+ jj = find(j);
143
+ if (ii < jj) {
144
+ LIBSEMIGROUPS_ASSERT(jj < _size);
145
+ (*_table)[jj] = ii;
146
+ } else {
147
+ LIBSEMIGROUPS_ASSERT(ii < _size);
148
+ (*_table)[ii] = jj;
149
+ }
150
+ _haschanged = true;
151
+ }
152
+
153
+ // flatten
154
+ void UF::flatten() {
155
+ LIBSEMIGROUPS_ASSERT(_size == _table->size());
156
+ for (size_t i = 0; i < _size; i++) {
157
+ (*_table)[i] = find(i);
158
+ }
159
+ }
160
+
161
+ // add_entry
162
+ void UF::add_entry() {
163
+ _table->push_back(_size);
164
+ if (_blocks != nullptr) {
165
+ _blocks->push_back(new table_t(1, _size));
166
+ }
167
+ _size++;
168
+ }
169
+
170
+ // nr_blocks
171
+ size_t UF::nr_blocks() {
172
+ LIBSEMIGROUPS_ASSERT(_size == _table->size());
173
+ if (_size == 0) {
174
+ return 0;
175
+ }
176
+ size_t count = 1;
177
+ size_t max = 0;
178
+ flatten(); // So we can use [i] instead of ->find(i)
179
+ LIBSEMIGROUPS_ASSERT((*_table)[0] == 0);
180
+ for (size_t i = 1; i < _size; i++) {
181
+ if ((*_table)[i] > max) {
182
+ max = (*_table)[i];
183
+ count++;
184
+ }
185
+ }
186
+ return count;
187
+ }
188
+
189
+ void UF::reset_next_rep() {
190
+ flatten();
191
+ _next_rep = 0;
192
+ }
193
+
194
+ // Returns the next representative of a block, invalidated by anything that
195
+ // changes the partition
196
+ size_t UF::next_rep() {
197
+ size_t current_rep = _next_rep;
198
+ while (_next_rep < _size && (*_table)[_next_rep] <= current_rep) {
199
+ _next_rep++;
200
+ }
201
+ return current_rep;
202
+ }
203
+
204
+ void UF::join(UF const& uf) {
205
+ LIBSEMIGROUPS_ASSERT(this->_size == uf._size);
206
+ for (size_t i = 0; i < _size; i++) {
207
+ unite((*_table)[i], (*uf._table)[i]);
208
+ }
209
+ }
210
+ } // namespace libsemigroups
code/train/C++/0027730_reverse_geocoder.cpp ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "reverse_geocoder.hpp"
2
+
3
+ #include "search/mwm_context.hpp"
4
+
5
+ #include "indexer/feature.hpp"
6
+ #include "indexer/feature_algo.hpp"
7
+ #include "indexer/ftypes_matcher.hpp"
8
+ #include "indexer/index.hpp"
9
+ #include "indexer/scales.hpp"
10
+ #include "indexer/search_string_utils.hpp"
11
+
12
+ #include "base/stl_helpers.hpp"
13
+
14
+ #include "std/limits.hpp"
15
+
16
+ namespace search
17
+ {
18
+ namespace
19
+ {
20
+ size_t constexpr kSimilarityThresholdPercent = 10;
21
+ int constexpr kQueryScale = scales::GetUpperScale();
22
+ /// Max number of tries (nearest houses with housenumber) to check when getting point address.
23
+ size_t constexpr kMaxNumTriesToApproxAddress = 10;
24
+ } // namespace
25
+
26
+ ReverseGeocoder::ReverseGeocoder(Index const & index) : m_index(index) {}
27
+
28
+ void ReverseGeocoder::GetNearbyStreets(MwmSet::MwmId const & id, m2::PointD const & center,
29
+ vector<Street> & streets) const
30
+ {
31
+ m2::RectD const rect = GetLookupRect(center, kLookupRadiusM);
32
+
33
+ auto const addStreet = [&](FeatureType & ft)
34
+ {
35
+ if (ft.GetFeatureType() != feature::GEOM_LINE ||
36
+ !ftypes::IsStreetChecker::Instance()(ft))
37
+ {
38
+ return;
39
+ }
40
+
41
+ string name;
42
+ if (!ft.GetName(StringUtf8Multilang::kDefaultCode, name))
43
+ return;
44
+
45
+ ASSERT(!name.empty(), ());
46
+
47
+ streets.emplace_back(ft.GetID(), feature::GetMinDistanceMeters(ft, center), name);
48
+ };
49
+
50
+ MwmSet::MwmHandle mwmHandle = m_index.GetMwmHandleById(id);
51
+ if (mwmHandle.IsAlive())
52
+ {
53
+ search::MwmContext(move(mwmHandle)).ForEachFeature(rect, addStreet);
54
+ sort(streets.begin(), streets.end(), my::LessBy(&Street::m_distanceMeters));
55
+ }
56
+ }
57
+
58
+ void ReverseGeocoder::GetNearbyStreets(FeatureType & ft, vector<Street> & streets) const
59
+ {
60
+ ASSERT(ft.GetID().IsValid(), ());
61
+ GetNearbyStreets(ft.GetID().m_mwmId, feature::GetCenter(ft), streets);
62
+ }
63
+
64
+ // static
65
+ size_t ReverseGeocoder::GetMatchedStreetIndex(strings::UniString const & keyName,
66
+ vector<Street> const & streets)
67
+ {
68
+ // Find the exact match or the best match in kSimilarityTresholdPercent limit.
69
+ size_t const count = streets.size();
70
+ size_t result = count;
71
+ size_t minPercent = kSimilarityThresholdPercent + 1;
72
+
73
+ for (size_t i = 0; i < count; ++i)
74
+ {
75
+ strings::UniString const actual = GetStreetNameAsKey(streets[i].m_name);
76
+
77
+ size_t const editDistance = strings::EditDistance(keyName.begin(), keyName.end(),
78
+ actual.begin(), actual.end());
79
+
80
+ if (editDistance == 0)
81
+ return i;
82
+
83
+ if (actual.empty())
84
+ continue;
85
+
86
+ size_t const percent = editDistance * 100 / actual.size();
87
+ if (percent < minPercent)
88
+ {
89
+ result = i;
90
+ minPercent = percent;
91
+ }
92
+ }
93
+
94
+ return result;
95
+ }
96
+
97
+ pair<vector<ReverseGeocoder::Street>, uint32_t>
98
+ ReverseGeocoder::GetNearbyFeatureStreets(FeatureType & ft) const
99
+ {
100
+ pair<vector<ReverseGeocoder::Street>, uint32_t> result;
101
+
102
+ GetNearbyStreets(ft, result.first);
103
+
104
+ HouseTable table(m_index);
105
+ if (!table.Get(ft.GetID(), result.second))
106
+ result.second = numeric_limits<uint32_t>::max();
107
+
108
+ return result;
109
+ }
110
+
111
+ void ReverseGeocoder::GetNearbyAddress(m2::PointD const & center, Address & addr) const
112
+ {
113
+ vector<Building> buildings;
114
+ GetNearbyBuildings(center, buildings);
115
+
116
+ HouseTable table(m_index);
117
+ size_t triesCount = 0;
118
+
119
+ for (auto const & b : buildings)
120
+ {
121
+ // It's quite enough to analize nearest kMaxNumTriesToApproxAddress houses for the exact nearby address.
122
+ // When we can't guarantee suitable address for the point with distant houses.
123
+ if (GetNearbyAddress(table, b, addr) || (++triesCount == kMaxNumTriesToApproxAddress))
124
+ break;
125
+ }
126
+ }
127
+
128
+ bool ReverseGeocoder::GetExactAddress(FeatureType & ft, Address & addr) const
129
+ {
130
+ if (ft.GetHouseNumber().empty())
131
+ return false;
132
+ HouseTable table(m_index);
133
+ return GetNearbyAddress(table, FromFeature(ft, 0.0 /* distMeters */), addr);
134
+ }
135
+
136
+ bool ReverseGeocoder::GetNearbyAddress(HouseTable & table, Building const & bld,
137
+ Address & addr) const
138
+ {
139
+ string street;
140
+ if (osm::Editor::Instance().GetEditedFeatureStreet(bld.m_id, street))
141
+ {
142
+ addr.m_building = bld;
143
+ addr.m_street.m_name = street;
144
+ return true;
145
+ }
146
+
147
+ uint32_t ind;
148
+ if (!table.Get(bld.m_id, ind))
149
+ return false;
150
+
151
+ vector<Street> streets;
152
+ GetNearbyStreets(bld.m_id.m_mwmId, bld.m_center, streets);
153
+ if (ind < streets.size())
154
+ {
155
+ addr.m_building = bld;
156
+ addr.m_street = streets[ind];
157
+ return true;
158
+ }
159
+ else
160
+ {
161
+ LOG(LWARNING, ("Out of bound street index", ind, "for", bld.m_id));
162
+ return false;
163
+ }
164
+ }
165
+
166
+ void ReverseGeocoder::GetNearbyBuildings(m2::PointD const & center, vector<Building> & buildings) const
167
+ {
168
+ m2::RectD const rect = GetLookupRect(center, kLookupRadiusM);
169
+
170
+ auto const addBuilding = [&](FeatureType & ft)
171
+ {
172
+ if (!ft.GetHouseNumber().empty())
173
+ buildings.push_back(FromFeature(ft, feature::GetMinDistanceMeters(ft, center)));
174
+ };
175
+
176
+ m_index.ForEachInRect(addBuilding, rect, kQueryScale);
177
+ sort(buildings.begin(), buildings.end(), my::LessBy(&Building::m_distanceMeters));
178
+ }
179
+
180
+ // static
181
+ ReverseGeocoder::Building ReverseGeocoder::FromFeature(FeatureType & ft, double distMeters)
182
+ {
183
+ return { ft.GetID(), distMeters, ft.GetHouseNumber(), feature::GetCenter(ft) };
184
+ }
185
+
186
+ // static
187
+ m2::RectD ReverseGeocoder::GetLookupRect(m2::PointD const & center, double radiusM)
188
+ {
189
+ return MercatorBounds::RectByCenterXYAndSizeInMeters(center, radiusM);
190
+ }
191
+
192
+ bool ReverseGeocoder::HouseTable::Get(FeatureID const & fid, uint32_t & streetIndex)
193
+ {
194
+ if (!m_table || m_handle.GetId() != fid.m_mwmId)
195
+ {
196
+ m_handle = m_index.GetMwmHandleById(fid.m_mwmId);
197
+ if (!m_handle.IsAlive())
198
+ {
199
+ LOG(LWARNING, ("MWM", fid, "is dead"));
200
+ return false;
201
+ }
202
+ m_table = search::HouseToStreetTable::Load(*m_handle.GetValue<MwmValue>());
203
+ }
204
+
205
+ return m_table->Get(fid.m_index, streetIndex);
206
+ }
207
+
208
+ string DebugPrint(ReverseGeocoder::Object const & obj)
209
+ {
210
+ return obj.m_name;
211
+ }
212
+
213
+ string DebugPrint(ReverseGeocoder::Address const & addr)
214
+ {
215
+ return "{ " + DebugPrint(addr.m_building) + ", " + DebugPrint(addr.m_street) + " }";
216
+ }
217
+
218
+ } // namespace search
code/train/C++/0027996_gain_change_calculator.cc ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2017 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 "webrtc/modules/audio_mixer/gain_change_calculator.h"
12
+
13
+ #include <math.h>
14
+ #include <vector>
15
+
16
+ namespace webrtc {
17
+
18
+ namespace {
19
+ constexpr int16_t kReliabilityThreshold = 100;
20
+ } // namespace
21
+
22
+ float GainChangeCalculator::CalculateGainChange(
23
+ rtc::ArrayView<const int16_t> in,
24
+ rtc::ArrayView<const int16_t> out) {
25
+ RTC_DCHECK_EQ(in.size(), out.size());
26
+
27
+ std::vector<float> gain(in.size());
28
+ CalculateGain(in, out, gain);
29
+ return CalculateDifferences(gain);
30
+ }
31
+
32
+ void GainChangeCalculator::CalculateGain(rtc::ArrayView<const int16_t> in,
33
+ rtc::ArrayView<const int16_t> out,
34
+ rtc::ArrayView<float> gain) {
35
+ RTC_DCHECK_EQ(in.size(), out.size());
36
+ RTC_DCHECK_EQ(in.size(), gain.size());
37
+
38
+ for (size_t i = 0; i < in.size(); ++i) {
39
+ if (std::abs(in[i]) >= kReliabilityThreshold) {
40
+ last_reliable_gain_ = out[i] / static_cast<float>(in[i]);
41
+ }
42
+ gain[i] = last_reliable_gain_;
43
+ }
44
+ }
45
+
46
+ float GainChangeCalculator::CalculateDifferences(
47
+ rtc::ArrayView<const float> values) {
48
+ float res = 0;
49
+ for (float f : values) {
50
+ res += fabs(f - last_value_);
51
+ last_value_ = f;
52
+ }
53
+ return res;
54
+ }
55
+ } // namespace webrtc
code/train/C++/0028086_StacksDP.cpp ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <string.h>
4
+
5
+ #include <string>
6
+ using std::string;
7
+
8
+ #include <iostream>
9
+ using std::cin;
10
+ using std::cout;
11
+ using std::stringstream;
12
+
13
+ #include <sstream>
14
+ #include "StacksAD.cpp"
15
+
16
+ using namespace std;
17
+
18
+
19
+ class StacksDP
20
+ {
21
+ private:
22
+ Nodo *FirstNode, *tempNode;
23
+ public:
24
+ string push(string info){
25
+ if(FirstNode == NULL){
26
+ FirstNode = new Nodo(info);
27
+ FirstNode->setNext(NULL);
28
+ return "Exitosamente Guardado: "+info;
29
+ }
30
+ else{
31
+ tempNode = FirstNode;
32
+ FirstNode = new Nodo(info);
33
+ FirstNode->setNext(tempNode);
34
+ return "Exitosamente Guardado: " + info;
35
+ }
36
+ }
37
+ string pop(void){
38
+
39
+ if (FirstNode == NULL) {
40
+ return "EMPTY LIST";
41
+ }
42
+
43
+ string result = FirstNode->getString();
44
+ FirstNode = FirstNode->getNext();
45
+ return result;
46
+ }
47
+ string desplegar(void){
48
+ string result ="";
49
+
50
+ if (FirstNode == NULL) {
51
+ return "NULL LIST";
52
+ }
53
+
54
+ Nodo *cursor = FirstNode;
55
+ while(cursor!=NULL){
56
+ result += cursor->getString() +"\n";
57
+ cursor = cursor->getNext();
58
+ }
59
+ return result;
60
+ }
61
+ void getData(void);
62
+ void saveData(void);
63
+
64
+ };
65
+