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

Upload folder using huggingface_hub (part 71)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pool/shard006/C++/0073974_binding.cc +39 -0
  2. pool/shard006/C++/0073980_removeuiobjectmembervisitor.cpp +142 -0
  3. pool/shard006/C++/0073981_DMS.cpp +122 -0
  4. pool/shard006/C++/0073983_developerview.cpp +93 -0
  5. pool/shard006/C++/0073986_DOMFileSystem.cpp +182 -0
  6. pool/shard006/C++/0073998_chan-quote.cpp +175 -0
  7. pool/shard006/C++/0073999_xml_viewer.cpp +34 -0
  8. pool/shard006/C++/0074000_DeviceOpenGL.cpp +164 -0
  9. pool/shard006/C++/0074003_RifCsvUserData.cpp +168 -0
  10. pool/shard006/C++/0074007_Client.cpp +84 -0
  11. pool/shard006/C++/0074014_quiz3.cpp +119 -0
  12. pool/shard006/C++/0074015_code_763.cpp +44 -0
  13. pool/shard006/C++/0074016_x11_event_source_glib.cc +102 -0
  14. pool/shard006/C++/0074017_runtimecolorfilter.cpp +199 -0
  15. pool/shard006/C++/0074020_proto2.cpp +121 -0
  16. pool/shard006/C++/0074021_config.cpp +98 -0
  17. pool/shard006/C++/0074028_fib_bench.cc +55 -0
  18. pool/shard006/C++/0074029_WiFi_Run_Dut_Cmd.cpp +260 -0
  19. pool/shard006/C++/0074040_Bob.cpp +199 -0
  20. pool/shard006/C++/0074053_CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp +180 -0
  21. pool/shard006/C++/0074056_idle_action_warning_observer.cc +103 -0
  22. pool/shard006/C++/0074063_main.cpp +35 -0
  23. pool/shard006/C++/0074069_importCtxtsSum.cpp +71 -0
  24. pool/shard006/C++/0074075_Experience.cpp +78 -0
  25. pool/shard006/C++/0074085_ImageTexture.cpp +86 -0
  26. pool/shard006/C++/0074092_rulebased_fuzzer.cc +107 -0
  27. pool/shard006/C++/0074094_signal.cpp +40 -0
  28. pool/shard006/C++/0074103_urlfilterbuilder.cc +41 -0
  29. pool/shard006/C++/0074109_TEvhttpServer.cpp +159 -0
  30. pool/shard006/C++/0074118_unlinkd_daemon.cc +74 -0
  31. pool/shard006/C++/0074121_system_clock_client.cc +226 -0
  32. pool/shard006/C++/0074130_instance_endtime.cpp +204 -0
  33. pool/shard006/C++/0074139_password_manager_exporter.cc +222 -0
  34. pool/shard006/C++/0074141_smoothFit.cpp +165 -0
  35. pool/shard006/C++/0074149_BasilarMembraneNonlinearGammatone.cpp +234 -0
  36. pool/shard006/C++/0074151_HumanPodController.cpp +26 -0
  37. pool/shard006/C++/0074156_edittooldlg.cpp +91 -0
  38. pool/shard006/C++/0074157_mediainfo.cpp +51 -0
  39. pool/shard006/C++/0074164_wld_mode_setpoint.cpp +146 -0
  40. pool/shard006/C++/0074166_force_mic_volume_max.cc +47 -0
  41. pool/shard006/C++/0074168_DispalyingVideo.cpp +22 -0
  42. pool/shard006/C++/0074173_UnionTypesModules.cpp +84 -0
  43. pool/shard006/C++/0074174_AP_Parachute.cpp +152 -0
  44. pool/shard006/C++/0074176_bosh_example.cpp +203 -0
  45. pool/shard006/C++/0074177_EdgeIntersectionList.cpp +254 -0
  46. pool/shard006/C++/0074181_r_clipsegment.cpp +186 -0
  47. pool/shard006/C++/0074184_main.cpp +64 -0
  48. pool/shard006/C++/0074187_vector2.cpp +158 -0
  49. pool/shard006/C++/0074188_fundwitnessdialog.cpp +176 -0
  50. pool/shard006/C++/0074189_DescribeTaskSetsResult.cpp +52 -0
pool/shard006/C++/0073974_binding.cc ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <node.h>
2
+ #include <assert.h>
3
+ #include <openssl/rand.h>
4
+ #include <openssl/ssl.h>
5
+
6
+ namespace {
7
+
8
+ inline void RandomBytes(const v8::FunctionCallbackInfo<v8::Value>& info) {
9
+ assert(info[0]->IsArrayBufferView());
10
+ auto view = info[0].As<v8::ArrayBufferView>();
11
+ auto byte_offset = view->ByteOffset();
12
+ auto byte_length = view->ByteLength();
13
+ assert(view->HasBuffer());
14
+ auto buffer = view->Buffer();
15
+ auto contents = buffer->GetBackingStore();
16
+ auto data = static_cast<unsigned char*>(contents->Data()) + byte_offset;
17
+ assert(RAND_poll());
18
+ auto rval = RAND_bytes(data, static_cast<int>(byte_length));
19
+ info.GetReturnValue().Set(rval > 0);
20
+ }
21
+
22
+ inline void Initialize(v8::Local<v8::Object> exports,
23
+ v8::Local<v8::Value> module,
24
+ v8::Local<v8::Context> context) {
25
+ auto isolate = context->GetIsolate();
26
+ auto key = v8::String::NewFromUtf8(
27
+ isolate, "randomBytes").ToLocalChecked();
28
+ auto value = v8::FunctionTemplate::New(isolate, RandomBytes)
29
+ ->GetFunction(context)
30
+ .ToLocalChecked();
31
+ assert(exports->Set(context, key, value).IsJust());
32
+
33
+ const SSL_METHOD* method = TLSv1_2_server_method();
34
+ assert(method != nullptr);
35
+ }
36
+
37
+ } // anonymous namespace
38
+
39
+ NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize)
pool/shard006/C++/0073980_removeuiobjectmembervisitor.cpp ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**************************************************************************
2
+ **
3
+ ** This file is part of Qt Creator
4
+ **
5
+ ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
6
+ **
7
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
8
+ **
9
+ ** Commercial Usage
10
+ **
11
+ ** Licensees holding valid Qt Commercial licenses may use this file in
12
+ ** accordance with the Qt Commercial License Agreement provided with the
13
+ ** Software or, alternatively, in accordance with the terms contained in
14
+ ** a written agreement between you and Nokia.
15
+ **
16
+ ** GNU Lesser General Public License Usage
17
+ **
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
+ ** If you are unsure which license is appropriate for your use, please
26
+ ** contact the sales department at http://qt.nokia.com/contact.
27
+ **
28
+ **************************************************************************/
29
+
30
+ #include "removeuiobjectmembervisitor.h"
31
+
32
+ #include <qmljs/parser/qmljsast_p.h>
33
+ #include <qmljs/parser/qmljsengine_p.h>
34
+
35
+ #include <QDebug>
36
+
37
+ using namespace QmlDesigner;
38
+ using namespace QmlDesigner::Internal;
39
+ using namespace QmlJS;
40
+ using namespace QmlJS::AST;
41
+
42
+ RemoveUIObjectMemberVisitor::RemoveUIObjectMemberVisitor(QmlDesigner::TextModifier &modifier,
43
+ quint32 objectLocation):
44
+ QMLRewriter(modifier),
45
+ objectLocation(objectLocation)
46
+ {
47
+ }
48
+
49
+ bool RemoveUIObjectMemberVisitor::preVisit(Node *ast)
50
+ {
51
+ parents.push(ast);
52
+
53
+ return true;
54
+ }
55
+
56
+ void RemoveUIObjectMemberVisitor::postVisit(Node *)
57
+ {
58
+ parents.pop();
59
+ }
60
+
61
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiPublicMember *ast) { return visitObjectMember(ast); }
62
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectDefinition *ast) { return visitObjectMember(ast); }
63
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiSourceElement *ast) { return visitObjectMember(ast); }
64
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiObjectBinding *ast) { return visitObjectMember(ast); }
65
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiScriptBinding *ast) { return visitObjectMember(ast); }
66
+ bool RemoveUIObjectMemberVisitor::visit(QmlJS::AST::UiArrayBinding *ast) { return visitObjectMember(ast); }
67
+
68
+ // FIXME: duplicate code in the QmlJS::Rewriter class, remove this
69
+ bool RemoveUIObjectMemberVisitor::visitObjectMember(QmlJS::AST::UiObjectMember *ast)
70
+ {
71
+ const quint32 memberStart = ast->firstSourceLocation().offset;
72
+
73
+ if (memberStart == objectLocation) {
74
+ // found it
75
+ int start = objectLocation;
76
+ int end = ast->lastSourceLocation().end();
77
+
78
+ if (UiArrayBinding *parentArray = containingArray()) {
79
+ extendToLeadingOrTrailingComma(parentArray, ast, start, end);
80
+ } else {
81
+ includeSurroundingWhitespace(start, end);
82
+ }
83
+
84
+ includeLeadingEmptyLine(start);
85
+ replace(start, end - start, QLatin1String(""));
86
+
87
+ setDidRewriting(true);
88
+
89
+ return false;
90
+ } else if (ast->lastSourceLocation().end() <= objectLocation) {
91
+ // optimization: if the location of the object-to-be-removed is not inside the current member, skip any children
92
+ return false;
93
+ } else {
94
+ // only visit children if the rewriting isn't done yet.
95
+ return !didRewriting();
96
+ }
97
+ }
98
+
99
+ UiArrayBinding *RemoveUIObjectMemberVisitor::containingArray() const
100
+ {
101
+ if (parents.size() > 2) {
102
+ if (cast<UiArrayMemberList*>(parents[parents.size() - 2])) {
103
+ return cast<UiArrayBinding*>(parents[parents.size() - 3]);
104
+ }
105
+ }
106
+
107
+ return 0;
108
+ }
109
+
110
+ // FIXME: duplicate code in the QmlJS::Rewriter class, remove this
111
+ void RemoveUIObjectMemberVisitor::extendToLeadingOrTrailingComma(QmlJS::AST::UiArrayBinding *parentArray,
112
+ QmlJS::AST::UiObjectMember *ast,
113
+ int &start,
114
+ int &end) const
115
+ {
116
+ UiArrayMemberList *currentMember = 0;
117
+ for (UiArrayMemberList *it = parentArray->members; it; it = it->next) {
118
+ if (it->member == ast) {
119
+ currentMember = it;
120
+ break;
121
+ }
122
+ }
123
+
124
+ if (!currentMember)
125
+ return;
126
+
127
+ if (currentMember->commaToken.isValid()) {
128
+ // leading comma
129
+ start = currentMember->commaToken.offset;
130
+ if (includeSurroundingWhitespace(start, end))
131
+ --end;
132
+ } else if (currentMember->next && currentMember->next->commaToken.isValid()) {
133
+ // trailing comma
134
+ end = currentMember->next->commaToken.end();
135
+ includeSurroundingWhitespace(start, end);
136
+ } else {
137
+ // array with 1 element, so remove the complete binding
138
+ start = parentArray->firstSourceLocation().offset;
139
+ end = parentArray->lastSourceLocation().end();
140
+ includeSurroundingWhitespace(start, end);
141
+ }
142
+ }
pool/shard006/C++/0073981_DMS.cpp ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //------------------------------------------------------
2
+ // @file DMS.cpp
3
+ // @version 1.0
4
+ //
5
+ // @section License
6
+ // Copyright (C) 2016, SlashDevin
7
+ //
8
+ // This library is free software; you can redistribute it and/or
9
+ // modify it under the terms of the GNU Lesser General Public
10
+ // License as published by the Free Software Foundation; either
11
+ // version 2.1 of the License, or (at your option) any later version.
12
+ //
13
+ // This library is distributed in the hope that it will be useful,
14
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ // Lesser General Public License for more details.
17
+ //
18
+
19
+ #include "DMS.h"
20
+
21
+ #include <Print.h>
22
+
23
+ //----------------------------------------------------------------
24
+ // Note that no division is used, and shifts are on byte boundaries. Fast!
25
+
26
+ void DMS_t::From( int32_t deg_1E7 )
27
+ {
28
+ const uint32_t E7 = 10000000UL;
29
+
30
+ if (deg_1E7 < 0) {
31
+ deg_1E7 = -deg_1E7;
32
+ hemisphere = SOUTH_H; // or WEST_H
33
+ } else
34
+ hemisphere = NORTH_H; // or EAST_H
35
+
36
+ const uint32_t div_E32 = 429; // 1e-07 * 2^32
37
+ degrees = ((deg_1E7 >> 16) * div_E32) >> 16;
38
+ uint32_t remainder = deg_1E7 - degrees * E7;
39
+
40
+ remainder *= 60; // to minutes * E7
41
+ minutes = ((remainder >> 16) * div_E32) >> 16;
42
+ remainder -= minutes * E7;
43
+
44
+ remainder *= 60; // to seconds * E7
45
+ uint32_t secs = ((remainder >> 16) * div_E32) >> 16;
46
+ remainder -= secs * E7;
47
+
48
+ const uint32_t div_1E4_E24 = 1677; // 0.00001 * 2^24
49
+ seconds_frac = (((remainder >> 8) * div_1E4_E24) >> 16); // thousandths
50
+ seconds_whole = secs;
51
+
52
+ // Carry if thousandths too big
53
+ if (seconds_frac >= 1000) {
54
+ seconds_frac -= 1000;
55
+ seconds_whole++;
56
+ if (seconds_whole >= 60) {
57
+ seconds_whole -= 60;
58
+ minutes++;
59
+ if (minutes >= 60) {
60
+ minutes -= 60;
61
+ degrees++;
62
+ }
63
+ }
64
+ }
65
+
66
+ } // From
67
+
68
+ //----------------------------------------------------------------
69
+
70
+ Print & operator << ( Print & outs, const DMS_t & dms )
71
+ {
72
+ if (dms.degrees < 10)
73
+ outs.write( '0' );
74
+ outs.print( dms.degrees );
75
+ outs.write( ' ' );
76
+ if (dms.minutes < 10)
77
+ outs.write( '0' );
78
+ outs.print( dms.minutes );
79
+ outs.print( F("\' ") );
80
+ if (dms.seconds_whole < 10)
81
+ outs.write( '0' );
82
+ outs.print( dms.seconds_whole );
83
+ outs.write( '.' );
84
+ if (dms.seconds_frac < 100)
85
+ outs.write( '0' );
86
+ if (dms.seconds_frac < 10)
87
+ outs.write( '0' );
88
+ outs.print( dms.seconds_frac );
89
+ outs.print( F("\" ") );
90
+
91
+ return outs;
92
+
93
+ } // operator <<
94
+
95
+ //----------------------------------------------------------------
96
+
97
+ void DMS_t::printDDDMMmmmm( Print & outs ) const
98
+ {
99
+ outs.print( degrees );
100
+
101
+ if (minutes < 10)
102
+ outs.print( '0' );
103
+ outs.print( minutes );
104
+ outs.print( '.' );
105
+
106
+ // Calculate the fractional minutes from the seconds,
107
+ // *without* using floating-point numbers.
108
+
109
+ uint16_t mmmm = seconds_whole * 166; // same as 10000/60, less .66666...
110
+ mmmm += (seconds_whole * 2 + seconds_frac/2 ) / 3; // ... plus the remaining .66666
111
+ // ... plus the seconds_frac, scaled by 10000/(60*1000) = 1/6, which
112
+ // is implemented above as 1/2 * 1/3
113
+
114
+ // print leading zeroes, if necessary
115
+ if (mmmm < 1000)
116
+ outs.print( '0' );
117
+ if (mmmm < 100)
118
+ outs.print( '0' );
119
+ if (mmmm < 10)
120
+ outs.print( '0' );
121
+ outs.print( mmmm );
122
+ }
pool/shard006/C++/0073983_developerview.cpp ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "developerview.h"
2
+
3
+ #include <QLabel>
4
+ #include <QVBoxLayout>
5
+ #include <QKeyEvent>
6
+
7
+ DeveloperView::DeveloperView(QWidget *parent) :
8
+ QDockWidget("Developer View", parent, Qt::Window)
9
+ {
10
+ _index = 0;
11
+ _sendButton = new QPushButton ("Send Command");
12
+ _sendButton->setEnabled(false);
13
+ _sendButton->setDefault(true);
14
+
15
+ _commandLine = new QLineEdit;
16
+ _commandLine->installEventFilter(this);
17
+
18
+ _commandsSent = new QStringList;
19
+
20
+ _history = new QTextEdit;
21
+ _history->setReadOnly(true);
22
+
23
+ _console = new QTextEdit;
24
+ _console->setReadOnly(true);
25
+
26
+ QVBoxLayout *mainLayout = new QVBoxLayout;
27
+ mainLayout->addWidget(new QLabel ("Command:"));
28
+
29
+ QHBoxLayout *commandLayout = new QHBoxLayout;
30
+ commandLayout->addWidget(_commandLine);
31
+ commandLayout->addWidget(_sendButton);
32
+
33
+ mainLayout->addLayout(commandLayout);
34
+ mainLayout->addWidget(new QLabel("Commands sent:"));
35
+ mainLayout->addWidget(_history);
36
+ mainLayout->addWidget(new QLabel("Ginga Console"));
37
+ mainLayout->addWidget(_console);
38
+
39
+ QWidget *dock = new QWidget;
40
+ dock->setLayout(mainLayout);
41
+
42
+ setWidget(dock);
43
+
44
+ connect (_sendButton, SIGNAL(pressed()), this, SLOT(sendButtonPressed()));
45
+ connect (_commandLine, SIGNAL(textChanged(QString)), this, SLOT(changeSendButtonStatus()));
46
+ connect (_commandLine, SIGNAL(returnPressed()), _sendButton, SLOT(click()));
47
+ }
48
+
49
+ void DeveloperView::sendButtonPressed()
50
+ {
51
+ QString currentCommand = _commandLine->text();
52
+ _commandLine->clear();
53
+
54
+ if (currentCommand != "")
55
+ {
56
+ _commandsSent->append(currentCommand);
57
+ _index = _commandsSent->count();
58
+
59
+ emit sendCommandRequested(currentCommand);
60
+ _history->append(currentCommand);
61
+ }
62
+ }
63
+
64
+ void DeveloperView::changeSendButtonStatus()
65
+ {
66
+ _sendButton->setEnabled(_commandLine->text() != "");
67
+ }
68
+
69
+ bool DeveloperView::eventFilter(QObject *obj, QEvent *event)
70
+ {
71
+ if (obj == _commandLine && event->type() == QEvent::KeyPress)
72
+ {
73
+ if (((QKeyEvent *)event)->key() == Qt::Key_Up)
74
+ {
75
+ if (_index > 0)
76
+ {
77
+ _index--;
78
+ _commandLine->setText(_commandsSent->at(_index));
79
+ }
80
+ return true;
81
+ }
82
+ else if (((QKeyEvent *)event)->key() == Qt::Key_Down)
83
+ {
84
+ if (_index < _commandsSent->count() - 1)
85
+ {
86
+ _index++;
87
+ _commandLine->setText(_commandsSent->at(_index));
88
+ }
89
+ return true;
90
+ }
91
+ }
92
+ return false;
93
+ }
pool/shard006/C++/0073986_DOMFileSystem.cpp ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2010 Google Inc. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions are
6
+ * met:
7
+ *
8
+ * * Redistributions of source code must retain the above copyright
9
+ * notice, this list of conditions and the following disclaimer.
10
+ * * Redistributions in binary form must reproduce the above
11
+ * copyright notice, this list of conditions and the following disclaimer
12
+ * in the documentation and/or other materials provided with the
13
+ * distribution.
14
+ * * Neither the name of Google Inc. nor the names of its
15
+ * contributors may be used to endorse or promote products derived from
16
+ * this software without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ */
30
+
31
+ #include "config.h"
32
+ #include "modules/filesystem/DOMFileSystem.h"
33
+
34
+ #include "modules/filesystem/DOMFilePath.h"
35
+ #include "modules/filesystem/DirectoryEntry.h"
36
+ #include "modules/filesystem/ErrorCallback.h"
37
+ #include "modules/filesystem/FileCallback.h"
38
+ #include "modules/filesystem/FileEntry.h"
39
+ #include "modules/filesystem/FileSystemCallbacks.h"
40
+ #include "modules/filesystem/FileWriter.h"
41
+ #include "modules/filesystem/FileWriterBaseCallback.h"
42
+ #include "modules/filesystem/FileWriterCallback.h"
43
+ #include "modules/filesystem/MetadataCallback.h"
44
+ #include "platform/FileMetadata.h"
45
+ #include "platform/weborigin/DatabaseIdentifier.h"
46
+ #include "platform/weborigin/SecurityOrigin.h"
47
+ #include "public/platform/WebFileSystem.h"
48
+ #include "public/platform/WebFileSystemCallbacks.h"
49
+ #include "wtf/OwnPtr.h"
50
+ #include "wtf/text/StringBuilder.h"
51
+ #include "wtf/text/WTFString.h"
52
+
53
+ namespace blink {
54
+
55
+ // static
56
+ DOMFileSystem* DOMFileSystem::create(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL)
57
+ {
58
+ DOMFileSystem* fileSystem(new DOMFileSystem(context, name, type, rootURL));
59
+ fileSystem->suspendIfNeeded();
60
+ return fileSystem;
61
+ }
62
+
63
+ DOMFileSystem* DOMFileSystem::createIsolatedFileSystem(ExecutionContext* context, const String& filesystemId)
64
+ {
65
+ if (filesystemId.isEmpty())
66
+ return 0;
67
+
68
+ StringBuilder filesystemName;
69
+ filesystemName.append(createDatabaseIdentifierFromSecurityOrigin(context->securityOrigin()));
70
+ filesystemName.appendLiteral(":Isolated_");
71
+ filesystemName.append(filesystemId);
72
+
73
+ // The rootURL created here is going to be attached to each filesystem request and
74
+ // is to be validated each time the request is being handled.
75
+ StringBuilder rootURL;
76
+ rootURL.appendLiteral("filesystem:");
77
+ rootURL.append(context->securityOrigin()->toString());
78
+ rootURL.append('/');
79
+ rootURL.append(isolatedPathPrefix);
80
+ rootURL.append('/');
81
+ rootURL.append(filesystemId);
82
+ rootURL.append('/');
83
+
84
+ return DOMFileSystem::create(context, filesystemName.toString(), FileSystemTypeIsolated, KURL(ParsedURLString, rootURL.toString()));
85
+ }
86
+
87
+ DOMFileSystem::DOMFileSystem(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL)
88
+ : DOMFileSystemBase(context, name, type, rootURL)
89
+ , ActiveDOMObject(context)
90
+ , m_numberOfPendingCallbacks(0)
91
+ {
92
+ }
93
+
94
+ DirectoryEntry* DOMFileSystem::root()
95
+ {
96
+ return DirectoryEntry::create(this, DOMFilePath::root);
97
+ }
98
+
99
+ void DOMFileSystem::addPendingCallbacks()
100
+ {
101
+ ++m_numberOfPendingCallbacks;
102
+ }
103
+
104
+ void DOMFileSystem::removePendingCallbacks()
105
+ {
106
+ ASSERT(m_numberOfPendingCallbacks > 0);
107
+ --m_numberOfPendingCallbacks;
108
+ }
109
+
110
+ bool DOMFileSystem::hasPendingActivity() const
111
+ {
112
+ ASSERT(m_numberOfPendingCallbacks >= 0);
113
+ return m_numberOfPendingCallbacks;
114
+ }
115
+
116
+ void DOMFileSystem::reportError(ErrorCallback* errorCallback, FileError* fileError)
117
+ {
118
+ scheduleCallback(errorCallback, fileError);
119
+ }
120
+
121
+ namespace {
122
+
123
+ class ConvertToFileWriterCallback : public FileWriterBaseCallback {
124
+ public:
125
+ static ConvertToFileWriterCallback* create(FileWriterCallback* callback)
126
+ {
127
+ return new ConvertToFileWriterCallback(callback);
128
+ }
129
+
130
+ void trace(Visitor* visitor)
131
+ {
132
+ visitor->trace(m_callback);
133
+ FileWriterBaseCallback::trace(visitor);
134
+ }
135
+
136
+ void handleEvent(FileWriterBase* fileWriterBase)
137
+ {
138
+ m_callback->handleEvent(static_cast<FileWriter*>(fileWriterBase));
139
+ }
140
+ private:
141
+ explicit ConvertToFileWriterCallback(FileWriterCallback* callback)
142
+ : m_callback(callback)
143
+ {
144
+ }
145
+ Member<FileWriterCallback> m_callback;
146
+ };
147
+
148
+ }
149
+
150
+ void DOMFileSystem::createWriter(const FileEntry* fileEntry, FileWriterCallback* successCallback, ErrorCallback* errorCallback)
151
+ {
152
+ ASSERT(fileEntry);
153
+
154
+ if (!fileSystem()) {
155
+ reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
156
+ return;
157
+ }
158
+
159
+ FileWriter* fileWriter = FileWriter::create(executionContext());
160
+ FileWriterBaseCallback* conversionCallback = ConvertToFileWriterCallback::create(successCallback);
161
+ OwnPtr<AsyncFileSystemCallbacks> callbacks = FileWriterBaseCallbacks::create(fileWriter, conversionCallback, errorCallback, m_context);
162
+ fileSystem()->createFileWriter(createFileSystemURL(fileEntry), fileWriter, callbacks.release());
163
+ }
164
+
165
+ void DOMFileSystem::createFile(const FileEntry* fileEntry, FileCallback* successCallback, ErrorCallback* errorCallback)
166
+ {
167
+ KURL fileSystemURL = createFileSystemURL(fileEntry);
168
+ if (!fileSystem()) {
169
+ reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
170
+ return;
171
+ }
172
+
173
+ fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, SnapshotFileCallback::create(this, fileEntry->name(), fileSystemURL, successCallback, errorCallback, m_context));
174
+ }
175
+
176
+ void DOMFileSystem::trace(Visitor* visitor)
177
+ {
178
+ DOMFileSystemBase::trace(visitor);
179
+ ActiveDOMObject::trace(visitor);
180
+ }
181
+
182
+ } // namespace blink
pool/shard006/C++/0073998_chan-quote.cpp ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ chan-quote.cpp
3
+ */
4
+
5
+ #include "../../../core/src/IRCBot/include/command-interface.hpp"
6
+ #include "../../../core/src/IRCBot/include/bot.hpp"
7
+ #include "../../../core/src/IRCBot/include/packet.hpp"
8
+
9
+ #include <string>
10
+ #include <vector>
11
+ #include <unordered_map>
12
+
13
+ #include <locale>
14
+ #include <cctype>
15
+
16
+ #include <algorithm>
17
+
18
+ #include <sstream>
19
+ #include <iostream>
20
+
21
+ #include <regex>
22
+
23
+ #include <random>
24
+ #include <chrono>
25
+
26
+ #include <stdexcept>
27
+
28
+ static inline void strip(std::string& s);
29
+
30
+ class ChanQuotesPlugin : protected IRC::CommandInterface {
31
+
32
+ const std::regex COMMAND_PATTERN{"^@((?:grab)|(?:rq))\\s*([-0-9a-zA-Z_]+)?"};
33
+ const int LINES_TO_TRACK = 10;
34
+
35
+ std::unordered_map<std::string, std::vector<std::string>> quotes;
36
+
37
+ std::vector<std::string> recorded_users;
38
+
39
+ struct line {
40
+ std::string sender;
41
+ std::string msg;
42
+ };
43
+
44
+ std::vector<line> last_n_lines;
45
+ int most_recent_line;
46
+
47
+ std::minstd_rand gen;
48
+
49
+ public:
50
+
51
+ ChanQuotesPlugin() : IRC::CommandInterface("channel quotes", "@grab: take last line as quote; @rq [user] get a quote (optionally from a user)") {
52
+ gen.seed(std::chrono::system_clock::now().time_since_epoch().count());
53
+
54
+ most_recent_line = LINES_TO_TRACK;
55
+ last_n_lines.resize(LINES_TO_TRACK);
56
+ }
57
+
58
+ bool triggered(const IRC::Packet& p) {
59
+ bool ans = false;
60
+ try {
61
+ std::vector<std::string>::iterator it;
62
+ switch (p.type) {
63
+ case IRC::Packet::PacketType::NICK:
64
+ /* update nick changes. */
65
+ quotes[p.content] = std::move(quotes[p.sender]);
66
+ quotes[p.sender].clear();
67
+
68
+ /* update vector of users */
69
+ it = std::find(recorded_users.begin(), recorded_users.end(), p.sender);
70
+ if (it != recorded_users.end()) {
71
+ *it = p.content;
72
+ }
73
+
74
+ break;
75
+ case IRC::Packet::PacketType::PRIVMSG:
76
+ ans = std::regex_search(p.content, COMMAND_PATTERN);
77
+ if (!ans) {
78
+ ++most_recent_line;
79
+ most_recent_line %= LINES_TO_TRACK;
80
+
81
+ last_n_lines.at(most_recent_line) = {p.sender, p.content};
82
+
83
+ /* strip the whitespace */
84
+ strip(last_n_lines.at(most_recent_line).msg);
85
+ }
86
+ break;
87
+ default: /* error occurs because of unhandled cases, so i put this line. */
88
+ ;
89
+ }
90
+ } catch (std::exception& e) {
91
+ std::cerr << "Error in ChanQuotesPlugin::triggered(): " << e.what() << "\n";
92
+ ans = false;
93
+ }
94
+ /* if we get here, it isn't a privmsg. */
95
+ return ans;
96
+ }
97
+
98
+ void run(const IRC::Packet& p) {
99
+ try {
100
+ std::smatch match;
101
+ std::regex_search(p.content, match, COMMAND_PATTERN);
102
+
103
+ /* add quote if that's what was requested. */
104
+ if (match[1] == "grab") {
105
+ int optional_offset;
106
+ try {
107
+ optional_offset = std::stoi(match[2].str());
108
+ if (optional_offset < 0 || optional_offset >= LINES_TO_TRACK) {
109
+ std::stringstream err;
110
+ err << "\x03" << "04Invalid index.\x0f";
111
+ p.reply(err.str());
112
+ return;
113
+ }
114
+
115
+ optional_offset %= LINES_TO_TRACK;
116
+ } catch (...) {
117
+ optional_offset = 0;
118
+ }
119
+
120
+ int index = most_recent_line - optional_offset;
121
+ const line& last_line = last_n_lines.at(index < 0 ? index + LINES_TO_TRACK : index);
122
+
123
+ /* this is how we know that last_line wasn't default initialized. */
124
+ if (!last_line.sender.empty())
125
+ quotes[last_line.sender].push_back(last_line.msg);
126
+
127
+ /* this is how we can tell if the user hasn't yet been quoted */
128
+ if (quotes[last_line.sender].size() <= 1) {
129
+ recorded_users.push_back(last_line.sender);
130
+ }
131
+
132
+ std::stringstream res;
133
+ res << "Grabbed: \"" << quotes[last_line.sender].back() << "\" -- " << last_line.sender;
134
+ p.reply(res.str());
135
+ return;
136
+ }
137
+
138
+ /* if we get here, we are serving a random quote. */
139
+ std::stringstream quote;
140
+
141
+ /* avoiding sigfpe */
142
+ if (recorded_users.empty()) {
143
+ p.reply("No quotes available.");
144
+ return;
145
+ }
146
+
147
+ const std::string& user = match[2].str().empty() ? recorded_users.at(gen() % recorded_users.size()) : match[2].str();
148
+
149
+ if (quotes[user].empty()) {
150
+ quote << "No quotes available from that user.";
151
+ } else {
152
+ quote << "\"" << quotes[user].at(gen() % quotes[user].size()) << "\" -- " << user;
153
+ }
154
+ p.reply(quote.str());
155
+ } catch (std::exception& e) {
156
+ std::cerr << "Error in ChanQuotesPlugin::run(): " << e.what() << "\n";
157
+ }
158
+ }
159
+ };
160
+
161
+ extern "C" IRC::CommandInterface* maker(IRC::Bot* b = nullptr) {
162
+ return (IRC::CommandInterface*)(new ChanQuotesPlugin);
163
+ }
164
+
165
+ static inline void strip(std::string& s) {
166
+ /* trim left side */
167
+ s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
168
+ return !std::isspace(ch);
169
+ }));
170
+
171
+ /* trim right side */
172
+ s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
173
+ return !std::isspace(ch);
174
+ }).base(), s.end());
175
+ }
pool/shard006/C++/0073999_xml_viewer.cpp ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "xml_viewer.h"
2
+ #include "ui_xml_viewer.h"
3
+
4
+ #include "acbrlib.h"
5
+ #include "application.h"
6
+
7
+ XML_Viewer::XML_Viewer(const QString &content, QWidget *parent) : QDialog(parent), xml(content), ui(new Ui::XML_Viewer) {
8
+ ui->setupUi(this);
9
+
10
+ setWindowFlags(Qt::Window);
11
+
12
+ ui->treeView->setModel(&xml.model);
13
+ ui->treeView->expandAll();
14
+
15
+ setConnections();
16
+
17
+ show();
18
+ }
19
+
20
+ XML_Viewer::~XML_Viewer() { delete ui; }
21
+
22
+ void XML_Viewer::setConnections() {
23
+ const auto connectionType = static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection);
24
+
25
+ connect(ui->pushButtonDanfe, &QPushButton::clicked, this, &XML_Viewer::on_pushButtonDanfe_clicked, connectionType);
26
+ }
27
+
28
+ void XML_Viewer::on_pushButtonDanfe_clicked() {
29
+ #ifdef Q_OS_WIN
30
+ ACBrLib::gerarDanfe(xml.fileContent, true);
31
+ #else
32
+ throw RuntimeException("Não implementado para linux!");
33
+ #endif
34
+ }
pool/shard006/C++/0074000_DeviceOpenGL.cpp ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ Copyright ©2014 Advanced Micro Devices, Inc. All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1 Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+ 2 Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the
11
+ documentation and/or other materials provided with the distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
17
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
+ THE POSSIBILITY OF SUCH DAMAGE.
24
+ ******************************************************************************/
25
+
26
+ /**
27
+ *******************************************************************************
28
+ * @file <DeviceOpenGL.cpp>
29
+ *
30
+ * @brief Source file for OpenGL Device
31
+ *
32
+ *******************************************************************************
33
+ */
34
+
35
+ #include "DeviceOpenGL.h"
36
+ #include "CmdLogger.h"
37
+ #include <set>
38
+
39
+ #pragma comment(lib, "opengl32.lib")
40
+
41
+
42
+ static bool ReportGLErrors(const char* file, int line)
43
+ {
44
+ unsigned int err = glGetError();
45
+ if(err != GL_NO_ERROR)
46
+ {
47
+ std::wstringstream ss;
48
+ ss << "GL failed. Error numbers: ";
49
+ while(err != GL_NO_ERROR)
50
+ {
51
+ ss << std::hex << err << ", ";
52
+ err = glGetError();
53
+ }
54
+ ss << std::dec << " file: " << file << ", line: " << line;
55
+ LOG_ERROR(ss.str());
56
+ return false;
57
+ }
58
+ return true;
59
+ }
60
+
61
+
62
+ #define CALL_GL(exp) \
63
+ { \
64
+ exp; \
65
+ if( !ReportGLErrors(__FILE__, __LINE__) ) return AMF_FAIL; \
66
+ }
67
+
68
+ DeviceOpenGL::DeviceOpenGL() :
69
+ m_hDC(NULL),
70
+ m_hContextOGL(NULL),
71
+ m_hWnd(NULL),
72
+ m_adaptersCount(0)
73
+ {
74
+ memset(m_adaptersIndexes, 0, sizeof(m_adaptersIndexes));
75
+ }
76
+
77
+ DeviceOpenGL::~DeviceOpenGL()
78
+ {
79
+ Terminate();
80
+ }
81
+
82
+ AMF_RESULT DeviceOpenGL::Init(HWND hWnd, const wchar_t* displayDeviceName)
83
+ {
84
+ DWORD error = 0;
85
+
86
+ if(hWnd == ::GetDesktopWindow() && displayDeviceName)
87
+ {
88
+ LOG_INFO("OPENGL : Choosen Device " << displayDeviceName);
89
+ m_hDC = CreateDC(displayDeviceName, NULL, NULL, NULL);
90
+ }
91
+ else
92
+ {
93
+ m_hWnd = hWnd;
94
+ m_hDC = GetDC(hWnd);
95
+ }
96
+ if(!m_hDC)
97
+ {
98
+ LOG_ERROR("Could not GetDC. Error: " << GetLastError());
99
+ return AMF_FAIL;
100
+ }
101
+
102
+ static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
103
+ {
104
+ sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
105
+ 1, // Version Number
106
+ PFD_DRAW_TO_WINDOW | // Format Must Support Window
107
+ PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
108
+ PFD_DOUBLEBUFFER, // Must Support Double Buffering
109
+ PFD_TYPE_RGBA, // Request An RGBA Format
110
+ 24, // Select Our Color Depth
111
+ 0, 0, 0, 0, 0, 0, // Color Bits Ignored
112
+ 0, // No Alpha Buffer
113
+ 0, // Shift Bit Ignored
114
+ 0, // No Accumulation Buffer
115
+ 0, 0, 0, 0, // Accumulation Bits Ignored
116
+ 16, // 16Bit Z-Buffer (Depth Buffer)
117
+ 0, // No Stencil Buffer
118
+ 0, // No Auxiliary Buffer
119
+ PFD_MAIN_PLANE, // Main Drawing Layer
120
+ 0, // Reserved
121
+ 0, 0, 0 // Layer Masks Ignored
122
+ };
123
+
124
+ GLuint pixelFormat = (GLuint)ChoosePixelFormat(m_hDC, &pfd);
125
+
126
+ BOOL res = SetPixelFormat(m_hDC, (int)pixelFormat, &pfd);
127
+ if(!res)
128
+ {
129
+ LOG_ERROR("SetPixelFormat() failed. Error: " << GetLastError());
130
+ return AMF_FAIL;
131
+ }
132
+
133
+ m_hContextOGL= wglCreateContext(m_hDC);
134
+ if(!m_hContextOGL)
135
+ {
136
+ LOG_ERROR("wglCreateContext() failed. Error: " << GetLastError());
137
+ return AMF_FAIL;
138
+ }
139
+ return AMF_OK;
140
+ }
141
+
142
+ AMF_RESULT DeviceOpenGL::Terminate()
143
+ {
144
+ if(m_hContextOGL)
145
+ {
146
+ wglMakeCurrent( NULL , NULL );
147
+ wglDeleteContext(m_hContextOGL);
148
+ m_hContextOGL = NULL;
149
+ }
150
+ if(m_hDC)
151
+ {
152
+ if(m_hWnd == NULL)
153
+ {
154
+ ::DeleteDC(m_hDC);
155
+ }
156
+ else
157
+ {
158
+ ::ReleaseDC(m_hWnd, m_hDC);
159
+ }
160
+ m_hDC = NULL;
161
+ m_hWnd = NULL;
162
+ }
163
+ return AMF_OK;
164
+ }
pool/shard006/C++/0074003_RifCsvUserData.cpp ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /////////////////////////////////////////////////////////////////////////////////
2
+ //
3
+ // Copyright (C) 2017- Statoil ASA
4
+ //
5
+ // ResInsight 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
+ // ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
11
+ // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
+ // FITNESS FOR A PARTICULAR PURPOSE.
13
+ //
14
+ // See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
15
+ // for more details.
16
+ //
17
+ /////////////////////////////////////////////////////////////////////////////////
18
+
19
+ #include "RifCsvUserData.h"
20
+
21
+ #include "RiaDateStringParser.h"
22
+ #include "RiaLogging.h"
23
+ #include "RiaQDateTimeTools.h"
24
+
25
+ #include "RifCsvUserDataParser.h"
26
+ #include "RifEclipseUserDataKeywordTools.h"
27
+ #include "RifEclipseUserDataParserTools.h"
28
+
29
+ #include "cafUtils.h"
30
+
31
+ #include <QDateTime>
32
+ #include <QFile>
33
+ #include <QTextStream>
34
+
35
+ //--------------------------------------------------------------------------------------------------
36
+ ///
37
+ //--------------------------------------------------------------------------------------------------
38
+ RifCsvUserData::RifCsvUserData()
39
+ {
40
+ }
41
+
42
+ //--------------------------------------------------------------------------------------------------
43
+ ///
44
+ //--------------------------------------------------------------------------------------------------
45
+ RifCsvUserData::~RifCsvUserData()
46
+ {
47
+ }
48
+
49
+ //--------------------------------------------------------------------------------------------------
50
+ ///
51
+ //--------------------------------------------------------------------------------------------------
52
+ bool RifCsvUserData::parse( const QString& fileName, const AsciiDataParseOptions& parseOptions, QString* errorText )
53
+ {
54
+ m_allResultAddresses.clear();
55
+ m_mapFromAddressToResultIndex.clear();
56
+
57
+ m_parser = std::unique_ptr<RifCsvUserDataFileParser>( new RifCsvUserDataFileParser( fileName, errorText ) );
58
+ if ( !m_parser->parse( parseOptions ) )
59
+ {
60
+ RiaLogging::error( QString( "Failed to parse file" ) );
61
+ return false;
62
+ }
63
+
64
+ buildTimeStepsAndMappings();
65
+
66
+ return true;
67
+ }
68
+
69
+ //--------------------------------------------------------------------------------------------------
70
+ ///
71
+ //--------------------------------------------------------------------------------------------------
72
+ bool RifCsvUserData::values( const RifEclipseSummaryAddress& resultAddress, std::vector<double>* values ) const
73
+ {
74
+ auto search = m_mapFromAddressToResultIndex.find( resultAddress );
75
+ if ( search != m_mapFromAddressToResultIndex.end() )
76
+ {
77
+ size_t columnIndex = search->second;
78
+
79
+ const Column* ci = m_parser->columnInfo( columnIndex );
80
+ if ( !ci ) return false;
81
+
82
+ values->clear();
83
+ values->reserve( ci->values.size() );
84
+ for ( double val : ci->values )
85
+ {
86
+ values->push_back( val );
87
+ }
88
+ }
89
+
90
+ return true;
91
+ }
92
+
93
+ //--------------------------------------------------------------------------------------------------
94
+ ///
95
+ //--------------------------------------------------------------------------------------------------
96
+ const std::vector<time_t>& RifCsvUserData::timeSteps( const RifEclipseSummaryAddress& resultAddress ) const
97
+ {
98
+ // First, check whether date time values exist for the current address
99
+ auto search = m_mapFromAddressToResultIndex.find( resultAddress );
100
+ if ( search != m_mapFromAddressToResultIndex.end() )
101
+ {
102
+ size_t index = m_mapFromAddressToResultIndex.at( resultAddress );
103
+ if ( !m_parser->tableData().columnInfos()[index].dateTimeValues.empty() )
104
+ {
105
+ return m_parser->tableData().columnInfos()[index].dateTimeValues;
106
+ }
107
+ }
108
+
109
+ // Then check for a separate date time column
110
+ int index = m_parser->tableData().dateTimeColumnIndex();
111
+ if ( index >= 0 )
112
+ {
113
+ return m_parser->tableData().columnInfos()[index].dateTimeValues;
114
+ }
115
+
116
+ static std::vector<time_t> emptyVector;
117
+ return emptyVector;
118
+ }
119
+
120
+ //--------------------------------------------------------------------------------------------------
121
+ ///
122
+ //--------------------------------------------------------------------------------------------------
123
+ std::string RifCsvUserData::unitName( const RifEclipseSummaryAddress& resultAddress ) const
124
+ {
125
+ auto search = m_mapFromAddressToResultIndex.find( resultAddress );
126
+ if ( search != m_mapFromAddressToResultIndex.end() )
127
+ {
128
+ size_t columnIndex = search->second;
129
+
130
+ const Column* ci = m_parser->columnInfo( columnIndex );
131
+ if ( ci )
132
+ {
133
+ return ci->unitName;
134
+ }
135
+ }
136
+
137
+ return "";
138
+ }
139
+
140
+ //--------------------------------------------------------------------------------------------------
141
+ ///
142
+ //--------------------------------------------------------------------------------------------------
143
+ RiaDefines::EclipseUnitSystem RifCsvUserData::unitSystem() const
144
+ {
145
+ return RiaDefines::EclipseUnitSystem::UNITS_UNKNOWN;
146
+ }
147
+
148
+ //--------------------------------------------------------------------------------------------------
149
+ ///
150
+ //--------------------------------------------------------------------------------------------------
151
+ void RifCsvUserData::buildTimeStepsAndMappings()
152
+ {
153
+ auto tableData = m_parser->tableData();
154
+
155
+ for ( size_t columnIndex = 0; columnIndex < tableData.columnInfos().size(); columnIndex++ )
156
+ {
157
+ const Column& ci = tableData.columnInfos()[columnIndex];
158
+ if ( ci.dataType == Column::NUMERIC )
159
+ {
160
+ RifEclipseSummaryAddress sumAddress = ci.summaryAddress;
161
+
162
+ m_allResultAddresses.insert( sumAddress );
163
+ if ( sumAddress.isErrorResult() ) m_allErrorAddresses.insert( sumAddress );
164
+
165
+ m_mapFromAddressToResultIndex[sumAddress] = columnIndex;
166
+ }
167
+ }
168
+ }
pool/shard006/C++/0074007_Client.cpp ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Client.h"
2
+ #include "Server.h"
3
+
4
+ namespace core
5
+ {
6
+ Client::Client()
7
+ {
8
+ send_buffer_.Init(SEND_BUFFER_SIZE);
9
+ recv_buffer_.Init(RECV_BUFFER_SIZE);
10
+ }
11
+ Client::~Client()
12
+ {
13
+ }
14
+ BOOL Client::PrepareReceive()
15
+ {
16
+ IoContext * recv_ready_context = Server::io_context_pool_->Construct(IoContext(this, IO_RECV_READY));
17
+ DWORD recieved_bytes = 0;
18
+ DWORD flags = 0;
19
+
20
+ if (WSARecv(socket_, &recv_ready_context->buffer_, 1, &recieved_bytes, &flags, (LPWSAOVERLAPPED)recv_ready_context, NULL) == SOCKET_ERROR) {
21
+ if (WSAGetLastError() != WSA_IO_PENDING) {
22
+ printf("Prepare WSARecv %d\n", WSAGetLastError());
23
+ return FALSE;
24
+ }
25
+ }
26
+ return TRUE;
27
+ }
28
+ BOOL Client::Receive()
29
+ {
30
+ IoContext * recv_context = Server::io_context_pool_->Construct(IoContext(this, IO_RECV));
31
+ DWORD recieved_bytes = 0;
32
+ DWORD flags = 0;
33
+ recv_context->buffer_.len = recv_buffer_.GetRemained();
34
+ recv_context->buffer_.buf = recv_buffer_.GetBuffer();
35
+
36
+ if (WSARecv(socket_, &recv_context->buffer_, 1, &recieved_bytes, &flags, (LPWSAOVERLAPPED)recv_context, NULL) == SOCKET_ERROR) {
37
+ if (WSAGetLastError() != WSA_IO_PENDING) {
38
+ printf("WSARecv %d\n", WSAGetLastError());
39
+ return FALSE;
40
+ }
41
+ }
42
+ return TRUE;
43
+ }
44
+ BOOL Client::PostReceive(DWORD received_bytes, std::function<void(IoContext *)>& handler, IoContext& io_context)
45
+ {
46
+ UWORD packet_size = ((UWORD)*(recv_buffer_.Read()));
47
+ if(received_bytes >= packet_size - recv_buffer_.offset_)
48
+ {
49
+ recv_buffer_.Produce(Server::packet_header_size_ + packet_size);
50
+ handler(&io_context);
51
+ recv_buffer_.Consume(Server::packet_header_size_ + packet_size);
52
+ }
53
+ return TRUE;
54
+ }
55
+ BOOL Client::Send(char * data, DWORD size)
56
+ {
57
+ IoContext * send_context = Server::io_context_pool_->Construct(IoContext(this, IO_SEND));
58
+ DWORD sent;
59
+
60
+ memcpy(send_buffer_.GetBuffer(), data, size);
61
+ send_context->buffer_.len = size;
62
+ send_context->buffer_.buf = send_buffer_.GetBuffer();
63
+ send_buffer_.Produce(size);
64
+
65
+ if (WSASend(socket_, &(send_context->buffer_), 1, &sent, 0, (LPWSAOVERLAPPED)send_context, nullptr) == SOCKET_ERROR) {
66
+ if (WSAGetLastError() != WSA_IO_PENDING) {
67
+ printf("WSASend %d\n", WSAGetLastError());
68
+ return FALSE;
69
+ }
70
+ }
71
+ return TRUE;
72
+ }
73
+ BOOL Client::PostSend(DWORD sent_bytes)
74
+ {
75
+ send_buffer_.Consume(sent_bytes);
76
+ return TRUE;
77
+ }
78
+ BOOL Client::Disconnect()
79
+ {
80
+ IoContext * disconnect_context = Server::io_context_pool_->Construct(IoContext(this, IO_DISCONNECT));
81
+ core::Server::DisconnectEx(socket_, (LPWSAOVERLAPPED)disconnect_context, 0, 0);
82
+ return 0;
83
+ }
84
+ }
pool/shard006/C++/0074014_quiz3.cpp ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "stdafx.h"
2
+ #include <iostream>
3
+ #include <cassert>
4
+
5
+ class IntArray
6
+ {
7
+ public:
8
+ IntArray(int size)
9
+ : m_size(size)
10
+ {
11
+ m_array = new int[size];
12
+ }
13
+
14
+ IntArray(const IntArray &intArray)
15
+ {
16
+ resize(intArray);
17
+ }
18
+
19
+ ~IntArray()
20
+ {
21
+ delete[] m_array;
22
+ }
23
+
24
+ int& operator[] (const int index);
25
+ const int& operator[] (const int index) const;
26
+ IntArray& IntArray::operator= (const IntArray &intArray);
27
+ friend std::ostream& operator<<(std::ostream& out, const IntArray& intArray);
28
+
29
+ void resize(const IntArray& intArray);
30
+ void copyToInternalArray(const IntArray& intArray) const;
31
+
32
+ private:
33
+ int m_size;
34
+ int *m_array;
35
+ };
36
+
37
+ void IntArray::resize(const IntArray& intArray)
38
+ {
39
+ delete[] m_array;
40
+ m_size = intArray.m_size;
41
+ m_array = new int[intArray.m_size];
42
+ copyToInternalArray(intArray);
43
+ }
44
+
45
+ void IntArray::copyToInternalArray(const IntArray& intArray) const
46
+ {
47
+ for (int i = 0; i < intArray.m_size; i++)
48
+ {
49
+ m_array[i] = intArray.m_array[i];
50
+ }
51
+ }
52
+
53
+ IntArray& IntArray::operator= (const IntArray &intArray)
54
+ {
55
+ // self-assignment guard
56
+ if (this == &intArray)
57
+ return *this;
58
+
59
+ resize(intArray);
60
+
61
+ // return the existing object so we can chain this operator
62
+ return *this;
63
+ }
64
+
65
+ int& IntArray::operator[] (const int index) // for non-const objects: can be used for assignment
66
+ {
67
+ assert(index >= 0 && index < m_size);
68
+
69
+ return m_array[index];
70
+ }
71
+
72
+ const int& IntArray::operator[] (const int index) const // for const objects: can only be used for access
73
+ {
74
+ assert(index >= 0 && index < m_size);
75
+
76
+ return m_array[index];
77
+ }
78
+
79
+ std::ostream& operator<<(std::ostream& out, const IntArray& intArray)
80
+ {
81
+ for(int i=0; i<intArray.m_size; i++)
82
+ {
83
+ out << intArray.m_array[i] << " ";
84
+ }
85
+
86
+ return out;
87
+ }
88
+
89
+ IntArray fillArray()
90
+ {
91
+ IntArray a(5);
92
+ a[0] = 5;
93
+ a[1] = 8;
94
+ a[2] = 2;
95
+ a[3] = 3;
96
+ a[4] = 6;
97
+
98
+ return a;
99
+ }
100
+
101
+ void quiz3()
102
+ {
103
+
104
+ IntArray a = fillArray();
105
+ std::cout << a << '\n';
106
+
107
+ IntArray b(1);
108
+ a = a;
109
+ b = a;
110
+
111
+ std::cout << b << '\n';
112
+ }
113
+
114
+ /*
115
+ * 3) Write your own integer array class named IntArray from scratch (do not use std::array or std::vector).
116
+ * Users should pass in the size of the array when it is created, and the array should be dynamically
117
+ * allocated. Use assert statements to guard against bad data. Create any constructors or overloaded
118
+ * operators needed to make the following program operate correctly:
119
+ */
pool/shard006/C++/0074015_code_763.cpp ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution {
2
+ public:
3
+ vector<int> preorderTraversal(TreeNode *root) {
4
+ stack<TreeNode*> nodeStack;
5
+ vector<int> result;
6
+ //base case
7
+ if(root==NULL)
8
+ return result;
9
+ nodeStack.push(root);
10
+ while(!nodeStack.empty())
11
+ {
12
+ TreeNode* node= nodeStack.top();
13
+ result.push_back(node->val);
14
+ nodeStack.pop();
15
+ if(node->right)
16
+ nodeStack.push(node->right);
17
+ if(node->left)
18
+ nodeStack.push(node->left);
19
+ }
20
+ return result;
21
+
22
+ }
23
+ };
24
+ class Solution {
25
+ public:
26
+ vector<int> preorderTraversal(TreeNode *root) {
27
+ if (!root)
28
+ return vector<int>();
29
+
30
+ vector<int> ans;
31
+ list<TreeNode*> s;
32
+ s.push_back(root);
33
+ while (!s.empty()) {
34
+ auto head = s.front();
35
+ s.erase(s.begin());
36
+ ans.push_back(head->val);
37
+ if (head->right)
38
+ s.push_front(head->right);
39
+ if (head->left)
40
+ s.push_front(head->left);
41
+ }
42
+ return ans;
43
+ }
44
+ };
pool/shard006/C++/0074016_x11_event_source_glib.cc ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "ui/events/platform/x11/x11_event_source_glib.h"
6
+
7
+ #include <X11/Xlib.h>
8
+ #include <glib.h>
9
+
10
+ #include "base/memory/ptr_util.h"
11
+
12
+ namespace ui {
13
+
14
+ namespace {
15
+
16
+ struct GLibX11Source : public GSource {
17
+ // Note: The GLibX11Source is created and destroyed by GLib. So its
18
+ // constructor/destructor may or may not get called.
19
+ XDisplay* display;
20
+ GPollFD* poll_fd;
21
+ };
22
+
23
+ gboolean XSourcePrepare(GSource* source, gint* timeout_ms) {
24
+ GLibX11Source* gxsource = static_cast<GLibX11Source*>(source);
25
+ if (XPending(gxsource->display))
26
+ *timeout_ms = 0;
27
+ else
28
+ *timeout_ms = -1;
29
+ return FALSE;
30
+ }
31
+
32
+ gboolean XSourceCheck(GSource* source) {
33
+ GLibX11Source* gxsource = static_cast<GLibX11Source*>(source);
34
+ return XPending(gxsource->display);
35
+ }
36
+
37
+ gboolean XSourceDispatch(GSource* source,
38
+ GSourceFunc unused_func,
39
+ gpointer data) {
40
+ X11EventSource* x11_source = static_cast<X11EventSource*>(data);
41
+ x11_source->DispatchXEvents();
42
+ return TRUE;
43
+ }
44
+
45
+ GSourceFuncs XSourceFuncs = {
46
+ XSourcePrepare,
47
+ XSourceCheck,
48
+ XSourceDispatch,
49
+ NULL
50
+ };
51
+
52
+ } // namespace
53
+
54
+ X11EventSourceGlib::X11EventSourceGlib(XDisplay* display)
55
+ : event_source_(this, display) {
56
+ InitXSource(ConnectionNumber(display));
57
+ }
58
+
59
+ X11EventSourceGlib::~X11EventSourceGlib() {
60
+ g_source_destroy(x_source_);
61
+ g_source_unref(x_source_);
62
+ }
63
+
64
+ void X11EventSourceGlib::ProcessXEvent(XEvent* xevent) {
65
+ DispatchEvent(xevent);
66
+ }
67
+
68
+ void X11EventSourceGlib::StopCurrentEventStream() {
69
+ event_source_.StopCurrentEventStream();
70
+ }
71
+
72
+ void X11EventSourceGlib::OnDispatcherListChanged() {
73
+ event_source_.OnDispatcherListChanged();
74
+ }
75
+
76
+ void X11EventSourceGlib::InitXSource(int fd) {
77
+ DCHECK(!x_source_);
78
+ DCHECK(event_source_.display()) << "Unable to get connection to X server";
79
+
80
+ x_poll_.reset(new GPollFD());
81
+ x_poll_->fd = fd;
82
+ x_poll_->events = G_IO_IN;
83
+ x_poll_->revents = 0;
84
+
85
+ GLibX11Source* glib_x_source = static_cast<GLibX11Source*>(
86
+ g_source_new(&XSourceFuncs, sizeof(GLibX11Source)));
87
+ glib_x_source->display = event_source_.display();
88
+ glib_x_source->poll_fd = x_poll_.get();
89
+
90
+ x_source_ = glib_x_source;
91
+ g_source_add_poll(x_source_, x_poll_.get());
92
+ g_source_set_can_recurse(x_source_, TRUE);
93
+ g_source_set_callback(x_source_, NULL, &event_source_, NULL);
94
+ g_source_attach(x_source_, g_main_context_default());
95
+ }
96
+
97
+ // static
98
+ std::unique_ptr<PlatformEventSource> PlatformEventSource::CreateDefault() {
99
+ return base::WrapUnique(new X11EventSourceGlib(gfx::GetXDisplay()));
100
+ }
101
+
102
+ } // namespace ui
pool/shard006/C++/0074017_runtimecolorfilter.cpp ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Use of this source code is governed by a BSD-style license that can be
5
+ * found in the LICENSE file.
6
+ */
7
+
8
+ #include "gm/gm.h"
9
+ #include "include/core/SkCanvas.h"
10
+ #include "include/core/SkColorFilter.h"
11
+ #include "include/core/SkData.h"
12
+ #include "include/core/SkImage.h"
13
+ #include "include/core/SkPaint.h"
14
+ #include "include/core/SkRSXform.h"
15
+ #include "include/core/SkRefCnt.h"
16
+ #include "include/core/SkSize.h"
17
+ #include "include/core/SkString.h"
18
+ #include "include/core/SkSurface.h"
19
+ #include "include/core/SkVertices.h"
20
+ #include "include/effects/SkRuntimeEffect.h"
21
+ #include "tools/Resources.h"
22
+
23
+ #include <stddef.h>
24
+ #include <utility>
25
+
26
+ const char* gNoop = R"(
27
+ half4 main(half4 color) {
28
+ return color;
29
+ }
30
+ )";
31
+
32
+ const char* gLumaSrc = R"(
33
+ half4 main(half4 color) {
34
+ return dot(color.rgb, half3(0.3, 0.6, 0.1)).000r;
35
+ }
36
+ )";
37
+
38
+ // Build up the same effect with increasingly complex control flow syntax.
39
+ // All of these are semantically equivalent and can be reduced in principle to one basic block.
40
+
41
+ // Simplest to run; hardest to write?
42
+ const char* gTernary = R"(
43
+ half4 main(half4 color) {
44
+ half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
45
+
46
+ half scale = luma < 0.33333 ? 0.5
47
+ : luma < 0.66666 ? (0.166666 + 2.0 * (luma - 0.33333)) / luma
48
+ : /* else */ (0.833333 + 0.5 * (luma - 0.66666)) / luma;
49
+ return half4(color.rgb * scale, color.a);
50
+ }
51
+ )";
52
+
53
+ // Uses conditional if statements but no early return.
54
+ const char* gIfs = R"(
55
+ half4 main(half4 color) {
56
+ half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
57
+
58
+ half scale = 0;
59
+ if (luma < 0.33333) {
60
+ scale = 0.5;
61
+ } else if (luma < 0.66666) {
62
+ scale = (0.166666 + 2.0 * (luma - 0.33333)) / luma;
63
+ } else {
64
+ scale = (0.833333 + 0.5 * (luma - 0.66666)) / luma;
65
+ }
66
+ return half4(color.rgb * scale, color.a);
67
+ }
68
+ )";
69
+
70
+ // Distilled from AOSP tone mapping shaders, more like what people tend to write.
71
+ const char* gEarlyReturn = R"(
72
+ half4 main(half4 color) {
73
+ half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
74
+
75
+ half scale = 0;
76
+ if (luma < 0.33333) {
77
+ return half4(color.rgb * 0.5, color.a);
78
+ } else if (luma < 0.66666) {
79
+ scale = 0.166666 + 2.0 * (luma - 0.33333);
80
+ } else {
81
+ scale = 0.833333 + 0.5 * (luma - 0.66666);
82
+ }
83
+ return half4(color.rgb * (scale/luma), color.a);
84
+ }
85
+ )";
86
+
87
+
88
+ DEF_SIMPLE_GM(runtimecolorfilter, canvas, 256 * 3, 256 * 2) {
89
+ sk_sp<SkImage> img = GetResourceAsImage("images/mandrill_256.png");
90
+
91
+ auto draw_filter = [&](const char* src) {
92
+ auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(src));
93
+ if (!effect) {
94
+ SkDebugf("%s\n%s\n", src, err.c_str());
95
+ }
96
+ SkASSERT(effect);
97
+ SkPaint p;
98
+ p.setColorFilter(effect->makeColorFilter(nullptr));
99
+ canvas->drawImage(img, 0, 0, SkSamplingOptions(), &p);
100
+ canvas->translate(256, 0);
101
+ };
102
+
103
+ for (const char* src : { gNoop, gLumaSrc }) {
104
+ draw_filter(src);
105
+ }
106
+ canvas->translate(-256*2, 256);
107
+ for (const char* src : { gTernary, gIfs, gEarlyReturn}) {
108
+ draw_filter(src);
109
+ }
110
+ }
111
+
112
+ DEF_SIMPLE_GM(runtimecolorfilter_vertices_atlas_and_patch, canvas, 404, 404) {
113
+ constexpr SkRect r = SkRect::MakeWH(128, 128);
114
+
115
+ // Make a vertices that draws the same as SkRect 'r'.
116
+ SkPoint pos[4];
117
+ r.toQuad(pos);
118
+ constexpr SkColor kColors[] = {SK_ColorBLUE, SK_ColorGREEN, SK_ColorCYAN, SK_ColorYELLOW};
119
+ auto verts = SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, 4, pos, pos, kColors);
120
+
121
+ // Make an image from the vertices to do equivalent drawAtlas, drawPatch using an image shader.
122
+ auto info = SkImageInfo::Make({128, 128},
123
+ kRGBA_8888_SkColorType,
124
+ kPremul_SkAlphaType,
125
+ canvas->imageInfo().refColorSpace());
126
+ auto surf = SkSurface::MakeRaster(info);
127
+ surf->getCanvas()->drawVertices(verts, SkBlendMode::kDst, SkPaint());
128
+ auto atlas = surf->makeImageSnapshot();
129
+ auto xform = SkRSXform::Make(1, 0, 0, 0);
130
+
131
+ // Make a patch that draws the same as the SkRect 'r'
132
+ SkVector vx = pos[1] - pos[0];
133
+ SkVector vy = pos[3] - pos[0];
134
+ vx.setLength(vx.length()/3.f);
135
+ vy.setLength(vy.length()/3.f);
136
+ const SkPoint cubics[12] = {
137
+ pos[0], pos[0] + vx, pos[1] - vx,
138
+ pos[1], pos[1] + vy, pos[2] - vy,
139
+ pos[2], pos[2] - vx, pos[3] + vx,
140
+ pos[3], pos[3] - vy, pos[0] + vy
141
+ };
142
+
143
+ auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(gLumaSrc));
144
+ if (!effect) {
145
+ SkDebugf("%s\n%s\n", gLumaSrc, err.c_str());
146
+ }
147
+ SkASSERT(effect);
148
+ sk_sp<SkColorFilter> colorfilter = effect->makeColorFilter(nullptr);
149
+
150
+ auto makePaint = [&](bool useCF, bool useShader) {
151
+ SkPaint paint;
152
+ paint.setColorFilter(useCF ? colorfilter : nullptr);
153
+ paint.setShader(useShader ? atlas->makeShader(SkSamplingOptions{}) : nullptr);
154
+ return paint;
155
+ };
156
+
157
+ auto drawVertices = [&](float x, bool useCF, bool useShader) {
158
+ SkAutoCanvasRestore acr(canvas, /*doSave=*/true);
159
+ canvas->translate(x, 0);
160
+ // Use just the shader or just the vertex colors.
161
+ auto mode = useShader ? SkBlendMode::kSrc : SkBlendMode::kDst;
162
+ canvas->drawVertices(verts, mode, makePaint(useCF, useShader));
163
+ };
164
+
165
+ auto drawAtlas = [&](float x, bool useCF) {
166
+ SkAutoCanvasRestore acr(canvas, /*doSave=*/true);
167
+ canvas->translate(x, 0);
168
+ SkPaint paint = makePaint(useCF, /*useShader=*/false);
169
+ constexpr SkColor kColor = SK_ColorWHITE;
170
+ canvas->drawAtlas(atlas.get(),
171
+ &xform,
172
+ &r,
173
+ &kColor,
174
+ 1,
175
+ SkBlendMode::kModulate,
176
+ SkSamplingOptions{},
177
+ nullptr,
178
+ &paint);
179
+ };
180
+
181
+ auto drawPatch = [&](float x, bool useCF) {
182
+ SkAutoCanvasRestore acr(canvas, true);
183
+ canvas->translate(x, 0);
184
+ SkPaint paint = makePaint(useCF, /*useShader=*/true);
185
+ canvas->drawPatch(cubics, nullptr, pos, SkBlendMode::kModulate, paint);
186
+ };
187
+
188
+ drawVertices( 0, /*useCF=*/false, /*useShader=*/false);
189
+ drawVertices( r.width() + 10, /*useCF=*/ true, /*useShader=*/false);
190
+ drawVertices(2*(r.width() + 10), /*useCF=*/ true, /*useShader=*/ true);
191
+
192
+ canvas->translate(0, r.height() + 10);
193
+ drawAtlas( 0, /*useCF=*/false);
194
+ drawAtlas(r.width() + 10, /*useCF=*/ true);
195
+
196
+ canvas->translate(0, r.height() + 10);
197
+ drawPatch( 0, /*useCF=*/false);
198
+ drawPatch(r.width() + 10, /*useCF=*/ true);
199
+ }
pool/shard006/C++/0074020_proto2.cpp ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*BEGIN_LEGAL
2
+ Intel Open Source License
3
+
4
+ Copyright (c) 2002-2013 Intel Corporation. All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are
8
+ met:
9
+
10
+ Redistributions of source code must retain the above copyright notice,
11
+ this list of conditions and the following disclaimer. Redistributions
12
+ in binary form must reproduce the above copyright notice, this list of
13
+ conditions and the following disclaimer in the documentation and/or
14
+ other materials provided with the distribution. Neither the name of
15
+ the Intel Corporation nor the names of its contributors may be used to
16
+ endorse or promote products derived from this software without
17
+ specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
23
+ ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ END_LEGAL */
31
+
32
+ /* ===================================================================== */
33
+ /*! @file
34
+ Replace an original function with a custom function defined in the tool. The
35
+ new function can have either the same or different signature from that of its
36
+ original function.
37
+ */
38
+
39
+ /* ===================================================================== */
40
+ #include "pin.H"
41
+ #include <iostream>
42
+ #include <stdlib.h>
43
+
44
+ using namespace std;
45
+
46
+ /* ===================================================================== */
47
+ VOID Boo( UINT32 num0, UINT32 num1, UINT32 arg0, UINT32 arg1,
48
+ UINT32 num2, UINT32 num3, UINT32 num4,
49
+ UINT32 arg2, UINT32 arg3 )
50
+ {
51
+ cout << "Original Arguments = ( "
52
+ << arg0 << ", "
53
+ << arg1 << ", "
54
+ << arg2 << ", "
55
+ << arg3 << " )"
56
+ << endl << flush;
57
+
58
+ cout << "New Arguments = ( "
59
+ << num0 << ", "
60
+ << num1 << ", "
61
+ << num2 << ", "
62
+ << num3 << ", "
63
+ << num4 << " )"
64
+ << endl << flush;
65
+ }
66
+
67
+ /* ===================================================================== */
68
+ VOID ImageLoad(IMG img, VOID *v)
69
+ {
70
+ cout << IMG_Name(img) << endl;
71
+
72
+ PROTO proto = PROTO_Allocate( PIN_PARG(void), CALLINGSTD_DEFAULT,
73
+ "Bar", PIN_PARG(int), PIN_PARG(int),
74
+ PIN_PARG(int), PIN_PARG(int),
75
+ PIN_PARG_END() );
76
+
77
+ RTN rtn = RTN_FindByName(img, "Bar");
78
+ if (RTN_Valid(rtn))
79
+ {
80
+ if ( ! RTN_IsSafeForProbedReplacement( rtn ) )
81
+ {
82
+ cout << "Cannot replace " << RTN_Name(rtn) << " in " << IMG_Name(img) << endl;
83
+ exit(1);
84
+ }
85
+
86
+ cout << "Replacing " << RTN_Name(rtn) << " in " << IMG_Name(img) << endl;
87
+
88
+ RTN_ReplaceSignatureProbed(
89
+ rtn, AFUNPTR(Boo),
90
+ IARG_PROTOTYPE, proto,
91
+ IARG_UINT32, 100,
92
+ IARG_UINT32, 200,
93
+ IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
94
+ IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
95
+ IARG_UINT32, 300,
96
+ IARG_UINT32, 400,
97
+ IARG_UINT32, 500,
98
+ IARG_FUNCARG_ENTRYPOINT_VALUE, 2,
99
+ IARG_FUNCARG_ENTRYPOINT_VALUE, 3,
100
+ IARG_END);
101
+ }
102
+ PROTO_Free( proto );
103
+ }
104
+
105
+ /* ===================================================================== */
106
+ int main(INT32 argc, CHAR *argv[])
107
+ {
108
+ PIN_InitSymbols();
109
+
110
+ PIN_Init(argc, argv);
111
+
112
+ IMG_AddInstrumentFunction(ImageLoad, 0);
113
+
114
+ PIN_StartProgramProbed();
115
+
116
+ return 0;
117
+ }
118
+
119
+ /* ===================================================================== */
120
+ /* eof */
121
+ /* ===================================================================== */
pool/shard006/C++/0074021_config.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "config.h"
2
+ #include <memory>
3
+
4
+ #include <QCoreApplication>
5
+ #include <QDir>
6
+ #include <QSettings>
7
+ #include <QSize>
8
+ #include <QPoint>
9
+ #include <QMainWindow>
10
+ #include <QTreeWidget>
11
+ #include <QHeaderView>
12
+
13
+ #include "model/db.h"
14
+
15
+ namespace ConfigDef{
16
+ static const char GEO[] = "geometry";
17
+ static const char STAT[] = "state";
18
+ static const char MAX[] = "maximized";
19
+ static const char POS[] = "pos";
20
+ static const char SIZE[] = "size";
21
+ }
22
+
23
+
24
+ Config Config::singleton;
25
+
26
+ Config::Config()
27
+ {
28
+ std::unique_ptr<QSettings> settings(getSettings());
29
+ }
30
+
31
+ Config::~Config()
32
+ {
33
+ std::unique_ptr<QSettings> settings(getSettings());
34
+ settings->sync();
35
+ }
36
+
37
+
38
+ QSettings* Config::getSettings()
39
+ {
40
+ fs::path p = Db::homeDir();
41
+ QString ini = QString(p.c_str()) + "/murphoto.ini";
42
+ return new QSettings(ini,QSettings::IniFormat);
43
+ }
44
+
45
+ void Config::saveWidget(QWidget* widget)
46
+ {
47
+ std::unique_ptr<QSettings> settings(getSettings());
48
+
49
+
50
+ settings->beginGroup(widget->objectName());
51
+ settings->setValue(ConfigDef::SIZE, widget->size());
52
+ settings->setValue(ConfigDef::GEO, widget->saveGeometry());
53
+
54
+ for(;;){
55
+ QMainWindow* mainwnd = qobject_cast<QMainWindow*>(widget);
56
+ if (mainwnd != nullptr){
57
+ settings->setValue(ConfigDef::STAT, mainwnd->saveState());
58
+ settings->setValue(ConfigDef::POS, mainwnd->pos());
59
+ settings->setValue(ConfigDef::MAX, mainwnd->isMaximized());
60
+ break;
61
+ }
62
+
63
+ break;
64
+ }
65
+
66
+ settings->endGroup();
67
+ }
68
+
69
+ void Config::restoreWidget(QWidget* widget)
70
+ {
71
+ std::unique_ptr<QSettings> settings(getSettings());
72
+
73
+ settings->beginGroup(widget->objectName());
74
+ if (settings->contains(ConfigDef::GEO)){
75
+ widget->resize(settings->value(ConfigDef::SIZE).toSize());
76
+ widget->restoreGeometry(settings->value(ConfigDef::GEO).toByteArray());
77
+
78
+ for (;;){
79
+ QMainWindow* mainwnd = qobject_cast<QMainWindow*>(widget);
80
+ if (mainwnd != nullptr){
81
+ mainwnd->restoreState(settings->value(ConfigDef::STAT).toByteArray());
82
+ mainwnd->move(settings->value(ConfigDef::POS).toPoint());
83
+ if (settings->value(ConfigDef::MAX).toBool()){
84
+ mainwnd->showMaximized();
85
+ }
86
+ break;
87
+ }
88
+
89
+ break;
90
+ }
91
+ }
92
+ settings->endGroup();
93
+
94
+ }
95
+
96
+ QString Config::getConfigFilename(){
97
+ return getSettings()->fileName();
98
+ }
pool/shard006/C++/0074028_fib_bench.cc ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Adapted from: https://svn.sosy-lab.org/software/sv-benchmarks/trunk/c/pthread/fib_bench_true-unreach-call.c */
2
+
3
+ #include <assert.h>
4
+ #include <atomic>
5
+ #include <pthread.h>
6
+
7
+ std::atomic<int> i, j;
8
+
9
+ #ifndef N
10
+ # warning "N not defined, assuming 3"
11
+ # define N 3
12
+ #endif
13
+
14
+ void *t1(void* arg){
15
+ int k = 0;
16
+
17
+ for (k = 0; k < N; k++)
18
+ atomic_store(&i, atomic_load(&i) + atomic_load(&j));
19
+
20
+ return NULL;
21
+ }
22
+
23
+ void *t2(void* arg){
24
+ int k = 0;
25
+
26
+ for (k = 0; k < N; k++)
27
+ atomic_store(&j, atomic_load(&j) + atomic_load(&i));
28
+
29
+ return NULL;
30
+ }
31
+
32
+ int fib(int n) {
33
+ int cur = 1, prev = 0;
34
+ while(n--) {
35
+ int next = prev+cur;
36
+ prev = cur;
37
+ cur = next;
38
+ }
39
+ return prev;
40
+ }
41
+
42
+ int main(int argc, char **argv) {
43
+ pthread_t id1, id2;
44
+
45
+ atomic_init(&i, 1);
46
+ atomic_init(&j, 1);
47
+
48
+ pthread_create(&id1, NULL, t1, NULL);
49
+ pthread_create(&id2, NULL, t2, NULL);
50
+
51
+ int correct = fib(2+2*N);
52
+ assert(atomic_load(&i) <= correct && atomic_load(&j) <= correct);
53
+
54
+ return 0;
55
+ }
pool/shard006/C++/0074029_WiFi_Run_Dut_Cmd.cpp ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "stdafx.h"
2
+ #include "TestManager.h"
3
+ #include "WiFi_11ac_MiMo_Test.h"
4
+ #include "WiFi_11ac_MiMo_Test_Internal.h"
5
+ #include "IQmeasure.h"
6
+ #include "vDUT.h"
7
+ #include "IQlite_Timer.h"
8
+ #include "IQlite_Logger.h"
9
+
10
+ // This variable is declared in WiFi_Test_Internal.cpp
11
+ extern vDUT_ID g_WiFi_Dut;
12
+ extern TM_ID g_WiFi_Test_ID;
13
+ extern int g_WiFi_Test_timer;
14
+ extern int g_WiFi_Test_logger;
15
+
16
+ using namespace std;
17
+
18
+ #define MAX_RESULT_GROUP_NUM 3
19
+ #define LP_RESULT_FORMAT "LitePoint_Data_Format"
20
+
21
+ // Input Parameter Container
22
+ map<string, WIFI_SETTING_STRUCT> l_runDutCmdParamMap;
23
+
24
+ // Return Value Container
25
+ map<string, WIFI_SETTING_STRUCT> l_runDutCmdReturnMap;
26
+
27
+ struct tagParam
28
+ {
29
+ char DUT_COMMAND[MAX_BUFFER_SIZE];
30
+ int WAIT_TIME_MS;
31
+ } l_runDutCmdParam;
32
+
33
+ struct tagReturn
34
+ {
35
+ char RESPONSE[MAX_BUFFER_SIZE];
36
+ char ERROR_MESSAGE[MAX_BUFFER_SIZE];
37
+ } l_runDutCmdReturn;
38
+
39
+ #ifndef WIN32
40
+ int InitRunDutCommandMPSContainers = InitializeRunDutCommandContainers();
41
+ #endif
42
+
43
+ //! Insert WiFi DUT
44
+ /*!
45
+ * Input Parameters
46
+ *
47
+ * - Mandatory
48
+ * -# A string that is used to determine which DUT register function will be used
49
+ *
50
+ * Return Values
51
+ * -# A string that contains all DUT info, such as FW version, driver version, chip revision, etc.
52
+ * -# A string for error message
53
+ *
54
+ * \return 0 No error occurred
55
+ * \return -1 DUT failed to insert. Please see the returned error message for details
56
+ */
57
+
58
+ WIFI_11AC_MIMO_TEST_API int WiFi_Run_DUT_Command(void)
59
+ {
60
+ int err = ERR_OK;
61
+ int dummyValue = 0;
62
+ char vErrorMsg[MAX_BUFFER_SIZE] = {'\0'};
63
+ char logMessage[MAX_BUFFER_SIZE] = {'\0'};
64
+
65
+ /*---------------------------------------*
66
+ * Clear Return Parameters and Container *
67
+ *---------------------------------------*/
68
+ ClearReturnParameters(l_runDutCmdReturnMap);
69
+
70
+ /*------------------------*
71
+ * Respond to QUERY_INPUT *
72
+ *------------------------*/
73
+ err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_INPUT", &dummyValue);
74
+ if( ERR_OK==err )
75
+ {
76
+ RespondToQueryInput(l_runDutCmdParamMap);
77
+ return err;
78
+ }
79
+ else
80
+ {
81
+ // do nothing
82
+ }
83
+
84
+ /*-------------------------*
85
+ * Respond to QUERY_RETURN *
86
+ *-------------------------*/
87
+ err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_RETURN", &dummyValue);
88
+ if( ERR_OK==err )
89
+ {
90
+ RespondToQueryReturn(l_runDutCmdReturnMap);
91
+ return err;
92
+ }
93
+ else
94
+ {
95
+ // do nothing
96
+ }
97
+
98
+ try
99
+ {
100
+ TM_ClearReturns(g_WiFi_Test_ID);
101
+
102
+ /*----------------------*
103
+ * Get input parameters *
104
+ *----------------------*/
105
+ err = GetInputParameters(l_runDutCmdParamMap);
106
+ if ( ERR_OK!=err )
107
+ {
108
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi_11ac_MiMo] Input parameters are not complete.\n");
109
+ throw logMessage;
110
+ }
111
+ else
112
+ {
113
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] Get input parameters return OK.\n");
114
+ }
115
+
116
+ // And clear vDut parameters at beginning.
117
+ vDUT_ClearParameters(g_WiFi_Dut);
118
+
119
+ #pragma region Execute external program
120
+
121
+ // Then execute the DUT command
122
+ vDUT_AddStringParameter(g_WiFi_Dut, "DUT_COMMAND", l_runDutCmdParam.DUT_COMMAND);
123
+
124
+ /*-------------------------------*
125
+ * Passing wl cmd file into dut *
126
+ *--------------------------------*/
127
+ err = ::vDUT_Run(g_WiFi_Dut, "DUT_MISC_FUNCTION2");
128
+ if ( ERR_OK!=err )
129
+ {
130
+ // Check vDut return "ERROR_MESSAGE" or not, if "Yes", must handle it.
131
+ err = ::vDUT_GetStringReturn(g_WiFi_Dut, "ERROR_MESSAGE", vErrorMsg, MAX_BUFFER_SIZE);
132
+ if ( ERR_OK==err ) // Get "ERROR_MESSAGE" from vDut
133
+ {
134
+ err = -1; // set err to -1, means "Error".
135
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, vErrorMsg);
136
+ throw logMessage;
137
+ }
138
+ else // Just return normal error message in this case
139
+ {
140
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi_11ac_MiMo] vDUT_Run(Run_Dut_Cmd) return error.\n");
141
+ throw logMessage;
142
+ }
143
+
144
+ }
145
+ else
146
+ {
147
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] vDUT_Run(Run_Dut_Cmd) return OK.\n");
148
+
149
+
150
+ // For retrieval of the DUT info
151
+ err = ::vDUT_GetStringReturn(g_WiFi_Dut, "RESPONSE", l_runDutCmdReturn.RESPONSE, MAX_BUFFER_SIZE);
152
+ if ( ERR_OK==err )
153
+ {
154
+ LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi_11ac_MiMo] vDUT_GetStringReturn(RESPONSE) return OK.\n");
155
+ }
156
+ }
157
+ #pragma endregion
158
+
159
+ #pragma region Execute sleep enough time till external program over
160
+ Sleep(l_runDutCmdParam.WAIT_TIME_MS);
161
+ #pragma endregion
162
+
163
+ /*-----------------------*
164
+ * Return Test Results *
165
+ *-----------------------*/
166
+ if (ERR_OK==err)
167
+ {
168
+ sprintf_s(l_runDutCmdReturn.ERROR_MESSAGE, MAX_BUFFER_SIZE, "[Info] Function completed.\n");
169
+ ReturnTestResults(l_runDutCmdReturnMap);
170
+ }
171
+ }
172
+ catch(char *msg)
173
+ {
174
+ ReturnErrorMessage(l_runDutCmdReturn.ERROR_MESSAGE, msg);
175
+ }
176
+ catch(...)
177
+ {
178
+ ReturnErrorMessage(l_runDutCmdReturn.ERROR_MESSAGE, "[WiFi_11ac_MiMo] Unknown Error!\n");
179
+ }
180
+
181
+ return err;
182
+ }
183
+
184
+ int InitializeRunDutCommandContainers(void)
185
+ {
186
+ /*------------------*
187
+ * Input Parameters: *
188
+ *------------------*/
189
+ l_runDutCmdParamMap.clear();
190
+ WIFI_SETTING_STRUCT setting;
191
+
192
+ l_runDutCmdParam.WAIT_TIME_MS = 0;
193
+ setting.type = WIFI_SETTING_TYPE_INTEGER;
194
+ if (sizeof(int)==sizeof(l_runDutCmdParam.WAIT_TIME_MS)) // Type_Checking
195
+ {
196
+ setting.value = (void*)&l_runDutCmdParam.WAIT_TIME_MS;
197
+ setting.unit = "ms";
198
+ setting.helpText = "Specify the wait time before extract the value from result file.";
199
+ l_runDutCmdParamMap.insert( pair<string,WIFI_SETTING_STRUCT>("WAIT_TIME_MS", setting) );
200
+ }
201
+ else
202
+ {
203
+ printf("Parameter Type Error!\n");
204
+ exit(1);
205
+ }
206
+
207
+ setting.unit = "";
208
+ setting.helpText = "Specify DUT command to run, case sensitive\r\nSuch as: band a";
209
+ setting.type = WIFI_SETTING_TYPE_STRING;
210
+ strcpy_s(l_runDutCmdParam.DUT_COMMAND, MAX_BUFFER_SIZE, "");
211
+ if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdParam.DUT_COMMAND)) // Type_Checking
212
+ {
213
+ setting.value = (void*)l_runDutCmdParam.DUT_COMMAND;
214
+ l_runDutCmdParamMap.insert( pair<string,WIFI_SETTING_STRUCT>("DUT_COMMAND", setting) );
215
+ }
216
+ else
217
+ {
218
+ printf("Parameter Type Error!\n");
219
+ exit(1);
220
+ }
221
+
222
+ /*----------------*
223
+ * Return Values: *
224
+ * ERROR_MESSAGE *
225
+ *----------------*/
226
+ l_runDutCmdReturnMap.clear();
227
+
228
+ l_runDutCmdReturn.ERROR_MESSAGE[0] = '\0';
229
+ setting.type = WIFI_SETTING_TYPE_STRING;
230
+ if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdReturn.ERROR_MESSAGE)) // Type_Checking
231
+ {
232
+ setting.value = (void*)l_runDutCmdReturn.ERROR_MESSAGE;
233
+ setting.unit = "";
234
+ setting.helpText = "Error message occurred";
235
+ l_runDutCmdReturnMap.insert( pair<string,WIFI_SETTING_STRUCT>("ERROR_MESSAGE", setting) );
236
+ }
237
+ else
238
+ {
239
+ printf("Parameter Type Error!\n");
240
+ exit(1);
241
+ }
242
+
243
+ l_runDutCmdReturn.RESPONSE[0] = '\0';
244
+ setting.type = WIFI_SETTING_TYPE_STRING;
245
+ if (MAX_BUFFER_SIZE==sizeof(l_runDutCmdReturn.RESPONSE)) // Type_Checking
246
+ {
247
+ setting.value = (void*)l_runDutCmdReturn.RESPONSE;
248
+ setting.unit = "";
249
+ setting.helpText = "Error message occurred";
250
+ l_runDutCmdReturnMap.insert( pair<string,WIFI_SETTING_STRUCT>("RESPONSE", setting) );
251
+ }
252
+ else
253
+ {
254
+ printf("Parameter Type Error!\n");
255
+ exit(1);
256
+ }
257
+
258
+
259
+ return 0;
260
+ }
pool/shard006/C++/0074040_Bob.cpp ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <string>
3
+ #include <vector>
4
+ #include <sstream>
5
+ #include <algorithm>
6
+
7
+ using namespace std;
8
+
9
+ int compare(int i, int j)
10
+ {
11
+ if (i < j)
12
+ return (-1);
13
+ if (i == j)
14
+ return (0);
15
+ if (i > j)
16
+ return (1);
17
+ }
18
+
19
+ int main()
20
+ {
21
+ int index;
22
+ int day;
23
+ int turn;
24
+ int slash_index;
25
+ int to_die;
26
+ int num_alive;
27
+ int mine_alive;
28
+ int turn_to_return;
29
+ bool returned;
30
+ string line;
31
+ vector<int> last_returns;
32
+ vector<int> today_returns;
33
+
34
+ getline(cin, line);
35
+
36
+ if (line.compare(0, 6, "INDEX ") != 0)
37
+ {
38
+ cerr << "INVALID INDEX LINE \"" << line << "\"" << endl;
39
+
40
+ return (-1);
41
+ }
42
+
43
+ index = atoi(line.substr(6).c_str()) - 1;
44
+
45
+ while (1) // Day loop
46
+ {
47
+ getline(cin, line);
48
+ if (line.compare(0, 4, "EXIT") == 0)
49
+ {
50
+ return (0);
51
+ }
52
+ else if (line.compare(0, 9, "START_DAY") != 0 || (slash_index = line.find('/')) == string::npos)
53
+ {
54
+ cerr << "INVALID START_DAY \"" << line << "\"" << endl;
55
+ return (-1);
56
+ }
57
+
58
+ day = atoi(line.substr(10, slash_index - 10).c_str());
59
+ to_die = atoi(line.substr(slash_index + 1, line.length() - slash_index - 1).c_str());
60
+
61
+ if (day != 1)
62
+ {
63
+ if (to_die > num_alive)
64
+ {
65
+ turn_to_return = 30;
66
+ }
67
+ else
68
+ {
69
+ turn_to_return = last_returns[last_returns.size() - to_die] - 1;
70
+ }
71
+ }
72
+
73
+ returned = false;
74
+
75
+ for (turn = 1; turn <= 30; ++turn)
76
+ {
77
+ getline(cin, line);
78
+
79
+ if (line.compare(0, 4, "EXIT") == 0)
80
+ {
81
+ return (0);
82
+ }
83
+ if (line.compare(0, 7, "END_DAY") == 0)
84
+ {
85
+ goto end_day;
86
+ }
87
+ if (line.compare(0, 10, "START_TURN") != 0)
88
+ {
89
+ cerr << "INVALID START_TURN \"" << line << "\"" << endl;
90
+ }
91
+
92
+ if (day == 1)
93
+ {
94
+ switch (compare(turn, 30))
95
+ {
96
+ case -1:
97
+ cout << "S,S,S,S,S" << endl;
98
+ break;
99
+
100
+ case 0:
101
+ cout << "R,R,R,R,R" << endl;
102
+ break;
103
+
104
+ case 1:
105
+ cout << "N,N,N,N,N" << endl;
106
+ break;
107
+ }
108
+ }
109
+ else
110
+ {
111
+ if (returned)
112
+ {
113
+ cout << "N,N,N,N,N" << endl;
114
+ }
115
+ /*
116
+ else if (num_alive - today_returns.size() < to_die)
117
+ {
118
+ cout << "R,R,R,R,R" << endl;
119
+ returned = true;
120
+ }
121
+ */
122
+ else if (turn >= turn_to_return)
123
+ {
124
+ cout << "R,R,R,R,R" << endl;
125
+ returned = true;
126
+ }
127
+ else
128
+ {
129
+ cout << "S,S,S,S,S" << endl;
130
+ }
131
+ }
132
+
133
+ getline(cin, line);
134
+
135
+ if (line.compare(0, 4, "EXIT") == 0)
136
+ {
137
+ return (0);
138
+ }
139
+ if (line.compare(0, 8, "END_TURN") != 0)
140
+ {
141
+ cerr << "INVALID END_TURN \"" << line << "\"" << endl;
142
+ }
143
+
144
+ stringstream ss(line);
145
+ string item;
146
+ int i = 0;
147
+ while (getline(ss, item, ' '))
148
+ {
149
+ i++;
150
+ if (i > 2 && i - 3 != index)
151
+ {
152
+ int num_to_add = count(item.begin(), item.end(), 'R'); // Add turn to today_returns for each servant that returned
153
+ for (int j = 0; j < num_to_add; j++)
154
+ {
155
+ today_returns.push_back(turn);
156
+ }
157
+ }
158
+ }
159
+
160
+ }
161
+
162
+ getline(cin, line);
163
+
164
+ end_day:
165
+
166
+ if (line.compare(0, 4, "EXIT") == 0)
167
+ {
168
+ return (0);
169
+ }
170
+ else if (line.compare(0, 7, "END_DAY") != 0)
171
+ {
172
+ cerr << "INVALID END_DAY \"" << line << "\"" << endl;
173
+ return (-1);
174
+ }
175
+
176
+ stringstream ss(line);
177
+ string item;
178
+ int i = 0;
179
+ num_alive = 0;
180
+ while (getline(ss, item, ' '))
181
+ {
182
+ i++;
183
+ if (i > 2 && i - 3 != index)
184
+ {
185
+ num_alive += count(item.begin(), item.end(), 'A');
186
+ }
187
+ else if (i - 3 == index)
188
+ {
189
+ mine_alive = count(item.begin(), item.end(), 'A');
190
+ }
191
+ }
192
+
193
+ last_returns = today_returns;
194
+ today_returns.clear();
195
+
196
+ }
197
+
198
+ return (0);
199
+ }
pool/shard006/C++/0074053_CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* TEMPLATE GENERATED TESTCASE FILE
2
+ Filename: CWE23_Relative_Path_Traversal__wchar_t_file_open_07.cpp
3
+ Label Definition File: CWE23_Relative_Path_Traversal.label.xml
4
+ Template File: sources-sink-07.tmpl.cpp
5
+ */
6
+ /*
7
+ * @description
8
+ * CWE: 23 Relative Path Traversal
9
+ * BadSource: file Read input from a file
10
+ * GoodSource: Use a fixed file name
11
+ * Sink: open
12
+ * BadSink : Open the file named in data using open()
13
+ * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
14
+ *
15
+ * */
16
+
17
+ #include "std_testcase.h"
18
+
19
+ #ifdef _WIN32
20
+ #define BASEPATH L"c:\\temp\\"
21
+ #else
22
+ #include <wchar.h>
23
+ #define BASEPATH L"/tmp/"
24
+ #endif
25
+
26
+ #ifdef _WIN32
27
+ #define FILENAME "C:\\temp\\file.txt"
28
+ #else
29
+ #define FILENAME "/tmp/file.txt"
30
+ #endif
31
+
32
+ #ifdef _WIN32
33
+ #define OPEN _wopen
34
+ #define CLOSE _close
35
+ #else
36
+ #include <unistd.h>
37
+ #define OPEN open
38
+ #define CLOSE close
39
+ #endif
40
+
41
+ /* The variable below is not declared "const", but is never assigned
42
+ any other value so a tool should be able to identify that reads of
43
+ this will always give its initialized value. */
44
+ static int staticFive = 5;
45
+
46
+ namespace CWE23_Relative_Path_Traversal__wchar_t_file_open_07
47
+ {
48
+
49
+ #ifndef OMITBAD
50
+
51
+ void bad()
52
+ {
53
+ wchar_t * data;
54
+ wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
55
+ data = dataBuffer;
56
+ if(staticFive==5)
57
+ {
58
+ {
59
+ /* Read input from a file */
60
+ size_t dataLen = wcslen(data);
61
+ FILE * pFile;
62
+ /* if there is room in data, attempt to read the input from a file */
63
+ if (FILENAME_MAX-dataLen > 1)
64
+ {
65
+ pFile = fopen(FILENAME, "r");
66
+ if (pFile != NULL)
67
+ {
68
+ /* POTENTIAL FLAW: Read data from a file */
69
+ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
70
+ {
71
+ printLine("fgetws() failed");
72
+ /* Restore NUL terminator if fgetws fails */
73
+ data[dataLen] = L'\0';
74
+ }
75
+ fclose(pFile);
76
+ }
77
+ }
78
+ }
79
+ }
80
+ {
81
+ int fileDesc;
82
+ /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
83
+ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
84
+ if (fileDesc != -1)
85
+ {
86
+ CLOSE(fileDesc);
87
+ }
88
+ }
89
+ }
90
+
91
+ #endif /* OMITBAD */
92
+
93
+ #ifndef OMITGOOD
94
+
95
+ /* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */
96
+ static void goodG2B1()
97
+ {
98
+ wchar_t * data;
99
+ wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
100
+ data = dataBuffer;
101
+ if(staticFive!=5)
102
+ {
103
+ /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
104
+ printLine("Benign, fixed string");
105
+ }
106
+ else
107
+ {
108
+ /* FIX: Use a fixed file name */
109
+ wcscat(data, L"file.txt");
110
+ }
111
+ {
112
+ int fileDesc;
113
+ /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
114
+ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
115
+ if (fileDesc != -1)
116
+ {
117
+ CLOSE(fileDesc);
118
+ }
119
+ }
120
+ }
121
+
122
+ /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
123
+ static void goodG2B2()
124
+ {
125
+ wchar_t * data;
126
+ wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
127
+ data = dataBuffer;
128
+ if(staticFive==5)
129
+ {
130
+ /* FIX: Use a fixed file name */
131
+ wcscat(data, L"file.txt");
132
+ }
133
+ {
134
+ int fileDesc;
135
+ /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
136
+ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
137
+ if (fileDesc != -1)
138
+ {
139
+ CLOSE(fileDesc);
140
+ }
141
+ }
142
+ }
143
+
144
+ void good()
145
+ {
146
+ goodG2B1();
147
+ goodG2B2();
148
+ }
149
+
150
+ #endif /* OMITGOOD */
151
+
152
+ } /* close namespace */
153
+
154
+ /* Below is the main(). It is only used when building this testcase on
155
+ its own for testing or for building a binary to use in testing binary
156
+ analysis tools. It is not used when compiling all the testcases as one
157
+ application, which is how source code analysis tools are tested. */
158
+
159
+ #ifdef INCLUDEMAIN
160
+
161
+ using namespace CWE23_Relative_Path_Traversal__wchar_t_file_open_07; /* so that we can use good and bad easily */
162
+
163
+ int main(int argc, char * argv[])
164
+ {
165
+ /* seed randomness */
166
+ srand( (unsigned)time(NULL) );
167
+ #ifndef OMITGOOD
168
+ printLine("Calling good()...");
169
+ good();
170
+ printLine("Finished good()");
171
+ #endif /* OMITGOOD */
172
+ #ifndef OMITBAD
173
+ printLine("Calling bad()...");
174
+ bad();
175
+ printLine("Finished bad()");
176
+ #endif /* OMITBAD */
177
+ return 0;
178
+ }
179
+
180
+ #endif
pool/shard006/C++/0074056_idle_action_warning_observer.cc ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
6
+
7
+ #include "ash/public/cpp/ash_pref_names.h"
8
+ #include "base/metrics/histogram_macros.h"
9
+ #include "base/time/time.h"
10
+ #include "chrome/browser/chromeos/login/demo_mode/demo_session.h"
11
+ #include "chrome/browser/chromeos/power/idle_action_warning_dialog_view.h"
12
+ #include "chrome/browser/profiles/profile_manager.h"
13
+ #include "chromeos/dbus/dbus_thread_manager.h"
14
+ #include "chromeos/dbus/power/power_policy_controller.h"
15
+ #include "components/prefs/pref_service.h"
16
+
17
+ namespace {
18
+
19
+ // DO NOT REORDER - used to report metrics.
20
+ enum class IdleLogoutWarningEvent {
21
+ kShown = 0,
22
+ kCanceled = 1,
23
+ kMaxValue = kCanceled
24
+ };
25
+
26
+ void ReportMetricsForDemoMode(IdleLogoutWarningEvent event) {
27
+ if (chromeos::DemoSession::IsDeviceInDemoMode())
28
+ UMA_HISTOGRAM_ENUMERATION("DemoMode.IdleLogoutWarningEvent", event);
29
+ }
30
+
31
+ chromeos::PowerPolicyController::Action GetIdleAction(bool on_battery_power) {
32
+ PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
33
+ int action;
34
+ if (on_battery_power)
35
+ action = prefs->GetInteger(ash::prefs::kPowerBatteryIdleAction);
36
+ else
37
+ action = prefs->GetInteger(ash::prefs::kPowerAcIdleAction);
38
+ return static_cast<chromeos::PowerPolicyController::Action>(action);
39
+ }
40
+
41
+ } // namespace
42
+
43
+ namespace chromeos {
44
+
45
+ IdleActionWarningObserver::IdleActionWarningObserver() {
46
+ PowerManagerClient::Get()->AddObserver(this);
47
+ }
48
+
49
+ IdleActionWarningObserver::~IdleActionWarningObserver() {
50
+ PowerManagerClient::Get()->RemoveObserver(this);
51
+ if (warning_dialog_) {
52
+ warning_dialog_->GetWidget()->RemoveObserver(this);
53
+ warning_dialog_->CloseDialog();
54
+ }
55
+ }
56
+
57
+ void IdleActionWarningObserver::IdleActionImminent(
58
+ const base::TimeDelta& time_until_idle_action) {
59
+ // Only display warning if idle action is to shut down or logout.
60
+ PowerPolicyController::Action idle_action = GetIdleAction(on_battery_power_);
61
+ if (idle_action != PowerPolicyController::ACTION_STOP_SESSION &&
62
+ idle_action != PowerPolicyController::ACTION_SHUT_DOWN) {
63
+ HideDialogIfPresent();
64
+ return;
65
+ }
66
+
67
+ const base::TimeTicks idle_action_time =
68
+ base::TimeTicks::Now() + time_until_idle_action;
69
+ if (warning_dialog_) {
70
+ warning_dialog_->Update(idle_action_time);
71
+ } else {
72
+ warning_dialog_ = new IdleActionWarningDialogView(idle_action_time);
73
+ warning_dialog_->GetWidget()->AddObserver(this);
74
+ ReportMetricsForDemoMode(IdleLogoutWarningEvent::kShown);
75
+ }
76
+ }
77
+
78
+ void IdleActionWarningObserver::IdleActionDeferred() {
79
+ HideDialogIfPresent();
80
+ }
81
+
82
+ void IdleActionWarningObserver::PowerChanged(
83
+ const power_manager::PowerSupplyProperties& proto) {
84
+ on_battery_power_ =
85
+ proto.battery_state() ==
86
+ power_manager::PowerSupplyProperties_BatteryState_DISCHARGING;
87
+ }
88
+
89
+ void IdleActionWarningObserver::OnWidgetClosing(views::Widget* widget) {
90
+ DCHECK(warning_dialog_);
91
+ DCHECK_EQ(widget, warning_dialog_->GetWidget());
92
+ warning_dialog_->GetWidget()->RemoveObserver(this);
93
+ warning_dialog_ = nullptr;
94
+ }
95
+
96
+ void IdleActionWarningObserver::HideDialogIfPresent() {
97
+ if (warning_dialog_) {
98
+ warning_dialog_->CloseDialog();
99
+ ReportMetricsForDemoMode(IdleLogoutWarningEvent::kCanceled);
100
+ }
101
+ }
102
+
103
+ } // namespace chromeos
pool/shard006/C++/0074063_main.cpp ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include <string>
3
+ #include "reader.h"
4
+
5
+ using namespace std;
6
+
7
+ int main()
8
+ {
9
+ bool command = false;
10
+
11
+ cout << "Type 1 to use stack on array and 0 to use stack on list" << endl;
12
+ cin >> command;
13
+ if (command)
14
+ {
15
+ cout << "You're currently using array for calculating." << endl;
16
+ cout << "Type your sentence." << endl;
17
+ Reader<ArrayStack> run;
18
+ run.read();
19
+ run.calculate();
20
+ cout << "Current result is ";
21
+ cout << run.result();
22
+ }
23
+ else
24
+ {
25
+ cout << "You're currently using list for calculating." << endl;
26
+ cout << "Type your sentence." << endl;
27
+ Reader<Stack> run;
28
+ run.read();
29
+ run.calculate();
30
+ cout << "Current result is ";
31
+ cout << run.result();
32
+ }
33
+ cout << endl << "Farewell!" << endl;
34
+ return 0;
35
+ }
pool/shard006/C++/0074069_importCtxtsSum.cpp ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <assert.h>
2
+ #include <cstdlib>
3
+ #include <fstream>
4
+ #include <iostream>
5
+ #include <gmp.h>
6
+ #include <paillier.h>
7
+ #include <string>
8
+
9
+ int main (int argc, char *argv[])
10
+ {
11
+ // Read public key from disk and initialize it
12
+ std::fstream pubKeyFile("pubkey.txt", std::fstream::in);
13
+ std::fstream secKeyFile("seckey.txt", std::fstream::in);
14
+
15
+ assert(pubKeyFile.is_open());
16
+ assert(secKeyFile.is_open());
17
+
18
+ std::string hexPubKey;
19
+ std::string hexSecKey;
20
+ std::getline(pubKeyFile, hexPubKey);
21
+ std::getline(secKeyFile, hexSecKey);
22
+
23
+ pubKeyFile.close();
24
+ secKeyFile.close();
25
+
26
+ paillier_pubkey_t* pubKey = paillier_pubkey_from_hex(&hexPubKey[0]);
27
+ paillier_prvkey_t* secKey = paillier_prvkey_from_hex(&hexSecKey[0], pubKey);
28
+
29
+ // Read ciphertexts from file
30
+ std::fstream ctxt1File("ciphertext1.txt", std::fstream::in|std::fstream::binary);
31
+ std::fstream ctxt2File("ciphertext2.txt", std::fstream::in|std::fstream::binary);
32
+
33
+ assert(ctxt1File.is_open());
34
+ assert(ctxt2File.is_open());
35
+
36
+ // The length of the ciphertext is twice the length of the key
37
+ char* byteCtxt1 = (char*)malloc(PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
38
+ char* byteCtxt2 = (char*)malloc(PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
39
+
40
+ ctxt1File.read(byteCtxt1, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
41
+ ctxt2File.read(byteCtxt2, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
42
+
43
+ ctxt1File.close();
44
+ ctxt2File.close();
45
+
46
+ paillier_ciphertext_t* ctxt1 = paillier_ciphertext_from_bytes((void*)byteCtxt1, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
47
+ paillier_ciphertext_t* ctxt2 = paillier_ciphertext_from_bytes((void*)byteCtxt2, PAILLIER_BITS_TO_BYTES(pubKey->bits)*2);
48
+
49
+ // Initialize the ciphertext that will hold the sum with an encryption of zero
50
+ paillier_ciphertext_t* encryptedSum = paillier_create_enc_zero();
51
+
52
+ // Sum the encrypted values by multiplying the ciphertexts
53
+ paillier_mul(pubKey, encryptedSum, ctxt1, ctxt2);
54
+
55
+ // Decrypt the ciphertext (sum)
56
+ paillier_plaintext_t* dec;
57
+ dec = paillier_dec(NULL, pubKey, secKey, encryptedSum);
58
+ gmp_printf("Decrypted sum: %Zd\n", dec);
59
+
60
+ // Cleaning up
61
+ paillier_freepubkey(pubKey);
62
+ paillier_freeprvkey(secKey);
63
+ paillier_freeplaintext(dec);
64
+ paillier_freeciphertext(ctxt1);
65
+ paillier_freeciphertext(ctxt2);
66
+ paillier_freeciphertext(encryptedSum);
67
+ free(byteCtxt1);
68
+ free(byteCtxt2);
69
+
70
+ return 0;
71
+ }
pool/shard006/C++/0074075_Experience.cpp ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <AIToolbox/MDP/Experience.hpp>
2
+
3
+ #include <algorithm>
4
+
5
+ namespace AIToolbox::MDP {
6
+ Experience::Experience(const size_t s, const size_t a) :
7
+ S(s), A(a), visits_(A, Table2D(S, S)), visitsSum_(S, A), rewards_(S, A), M2s_(S, A), timesteps_(0)
8
+ {
9
+ reset();
10
+ }
11
+
12
+ void Experience::record(const size_t s, const size_t a, const size_t s1, const double rew) {
13
+ ++timesteps_;
14
+
15
+ // Count updates
16
+ visits_[a](s, s1) += 1;
17
+ visitsSum_(s, a) += 1;
18
+
19
+ const auto delta = rew - rewards_(s, a);
20
+ // Rolling average for this s,a,s1 tuple
21
+ rewards_(s, a) += delta / visitsSum_(s, a);
22
+ // Rolling sum of square diffs.
23
+ M2s_(s, a) += delta * (rew - rewards_(s, a));
24
+ }
25
+
26
+ void Experience::reset() {
27
+ for (size_t a = 0; a < A; ++a)
28
+ visits_[a].setZero();
29
+ visitsSum_.setZero();
30
+ rewards_.setZero();
31
+ M2s_.setZero();
32
+ timesteps_ = 0;
33
+ }
34
+
35
+ void Experience::setVisitsTable(const Table3D & v) {
36
+ visits_ = v;
37
+ visitsSum_.setZero();
38
+ for ( size_t s = 0; s < S; ++s )
39
+ for ( size_t a = 0; a < A; ++a )
40
+ visitsSum_(s, a) = visits_[a].row(s).sum();
41
+ }
42
+
43
+ void Experience::setRewardMatrix(const Matrix2D & r) {
44
+ rewards_ = r;
45
+ }
46
+
47
+ void Experience::setM2Matrix(const Matrix2D & mm) {
48
+ M2s_ = mm;
49
+ }
50
+
51
+ unsigned long Experience::getTimesteps() const {
52
+ return timesteps_;
53
+ }
54
+
55
+ unsigned long Experience::getVisits(const size_t s, const size_t a, const size_t s1) const {
56
+ return visits_[a](s, s1);
57
+ }
58
+
59
+ unsigned long Experience::getVisitsSum(const size_t s, const size_t a) const {
60
+ return visitsSum_(s, a);
61
+ }
62
+
63
+ double Experience::getReward(const size_t s, const size_t a) const {
64
+ return rewards_(s, a);
65
+ }
66
+
67
+ double Experience::getM2(const size_t s, const size_t a) const {
68
+ return M2s_(s, a);
69
+ }
70
+
71
+ const Table3D & Experience::getVisitsTable() const { return visits_; }
72
+ const Table2D & Experience::getVisitsTable(const size_t a) const { return visits_[a]; }
73
+ const Table2D & Experience::getVisitsSumTable() const { return visitsSum_; }
74
+ const QFunction & Experience::getRewardMatrix() const { return rewards_; }
75
+ const QFunction & Experience::getM2Matrix() const { return M2s_; }
76
+ size_t Experience::getS() const { return S; }
77
+ size_t Experience::getA() const { return A; }
78
+ }
pool/shard006/C++/0074085_ImageTexture.cpp ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2013 Pavlo Lavrenenko
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ #include <ImageTexture.h>
24
+ #include <EngineConfig.h>
25
+ #include <OpenGL.h>
26
+ #include <Logger.h>
27
+ #include <algorithm>
28
+
29
+ namespace Graphene {
30
+
31
+ ImageTexture::ImageTexture(const Image& image):
32
+ RgbaTexture(image.getWidth(), image.getHeight()) {
33
+ glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
34
+ glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
35
+
36
+ int anisotropy = GetEngineConfig().getAnisotropy();
37
+ if (anisotropy > 0 && OpenGL::isExtensionSupported("GL_ARB_texture_filter_anisotropic")) {
38
+ GLint maxAnisotropy;
39
+ glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnisotropy);
40
+ glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY, std::min<int>(anisotropy, maxAnisotropy));
41
+ } else {
42
+ LogWarn("GL_ARB_texture_filter_anisotropic unavailable, anisotropic filtering disabled");
43
+ }
44
+
45
+ this->update(image);
46
+ }
47
+
48
+ void ImageTexture::update(const Image& image) {
49
+ this->bind();
50
+
51
+ GLenum format = (image.getPixelDepth() == 32) ? GL_BGRA : GL_BGR; // Little-endian ARGB or RGB format
52
+ glTexSubImage2D(this->target, 0, 0, 0, this->width, this->height, format, GL_UNSIGNED_BYTE, image.getPixels());
53
+ glGenerateMipmap(this->target);
54
+ }
55
+
56
+ ImageCubeTexture::ImageCubeTexture(const CubeImage& cubeImage):
57
+ RgbaCubeTexture(cubeImage[0]->getWidth(), cubeImage[0]->getHeight()) {
58
+ glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
59
+ glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
60
+
61
+ int anisotropy = GetEngineConfig().getAnisotropy();
62
+ if (anisotropy > 0 && OpenGL::isExtensionSupported("GL_ARB_texture_filter_anisotropic")) {
63
+ GLint maxAnisotropy;
64
+ glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnisotropy);
65
+ glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY, std::min<int>(anisotropy, maxAnisotropy));
66
+ } else {
67
+ LogWarn("GL_ARB_texture_filter_anisotropic unavailable, anisotropic filtering disabled");
68
+ }
69
+
70
+ this->update(cubeImage);
71
+ }
72
+
73
+ void ImageCubeTexture::update(const CubeImage& cubeImage) {
74
+ this->bind();
75
+
76
+ for (int faceOffset = 0; faceOffset < 6; faceOffset++) {
77
+ auto& faceImage = cubeImage[faceOffset];
78
+ GLenum faceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceOffset;
79
+ GLenum faceFormat = (faceImage->getPixelDepth() == 32) ? GL_BGRA : GL_BGR; // Little-endian ARGB or RGB format
80
+ glTexSubImage2D(faceTarget, 0, 0, 0, faceImage->getWidth(), faceImage->getHeight(), faceFormat, GL_UNSIGNED_BYTE, faceImage->getPixels());
81
+ }
82
+
83
+ glGenerateMipmap(this->target);
84
+ }
85
+
86
+ } // namespace Graphene
pool/shard006/C++/0074092_rulebased_fuzzer.cc ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2019 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include <stddef.h>
6
+ #include <stdint.h>
7
+
8
+ #include "ash/services/ime/public/cpp/rulebased/def/us.h"
9
+ #include "ash/services/ime/public/cpp/rulebased/engine.h"
10
+ #include "ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.pb.h"
11
+ #include "ash/services/ime/public/cpp/rulebased/rules_data.h"
12
+ #include "testing/libfuzzer/proto/lpm_interface.h"
13
+
14
+ namespace rulebased = ::ash::ime::rulebased;
15
+ namespace mojom = ::ash::ime::mojom;
16
+
17
+ namespace {
18
+
19
+ // Must match ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.proto
20
+ constexpr mojom::DomCode kKeyCodes[] = {
21
+ mojom::DomCode::kBackquote, mojom::DomCode::kDigit1,
22
+ mojom::DomCode::kDigit2, mojom::DomCode::kDigit3,
23
+ mojom::DomCode::kDigit4, mojom::DomCode::kDigit5,
24
+ mojom::DomCode::kDigit6, mojom::DomCode::kDigit7,
25
+ mojom::DomCode::kDigit8, mojom::DomCode::kDigit9,
26
+ mojom::DomCode::kDigit0, mojom::DomCode::kMinus,
27
+ mojom::DomCode::kEqual, mojom::DomCode::kBackspace,
28
+ mojom::DomCode::kKeyQ, mojom::DomCode::kKeyW,
29
+ mojom::DomCode::kKeyE, mojom::DomCode::kKeyR,
30
+ mojom::DomCode::kKeyT, mojom::DomCode::kKeyY,
31
+ mojom::DomCode::kKeyU, mojom::DomCode::kKeyI,
32
+ mojom::DomCode::kKeyO, mojom::DomCode::kKeyP,
33
+ mojom::DomCode::kBracketLeft, mojom::DomCode::kBracketRight,
34
+ mojom::DomCode::kKeyA, mojom::DomCode::kKeyS,
35
+ mojom::DomCode::kKeyD, mojom::DomCode::kKeyF,
36
+ mojom::DomCode::kKeyG, mojom::DomCode::kKeyH,
37
+ mojom::DomCode::kKeyJ, mojom::DomCode::kKeyK,
38
+ mojom::DomCode::kKeyL, mojom::DomCode::kSemicolon,
39
+ mojom::DomCode::kQuote, mojom::DomCode::kBackslash,
40
+ mojom::DomCode::kIntlBackslash, mojom::DomCode::kEnter,
41
+ mojom::DomCode::kKeyZ, mojom::DomCode::kKeyX,
42
+ mojom::DomCode::kKeyC, mojom::DomCode::kKeyV,
43
+ mojom::DomCode::kKeyB, mojom::DomCode::kKeyN,
44
+ mojom::DomCode::kKeyM, mojom::DomCode::kComma,
45
+ mojom::DomCode::kPeriod, mojom::DomCode::kSlash,
46
+ mojom::DomCode::kSpace};
47
+
48
+ // Must match ash/services/ime/public/cpp/rulebased/rulebased_fuzzer.proto
49
+ constexpr const char* kEngineIds[] = {
50
+ "ar",
51
+ "bn_phone",
52
+ "ckb_ar",
53
+ "ckb_en",
54
+ "deva_phone",
55
+ "ethi",
56
+ "fa",
57
+ "gu_phone",
58
+ "km",
59
+ "kn_phone",
60
+ "lo",
61
+ "ml_phone",
62
+ "my",
63
+ "my_myansan",
64
+ "ne_inscript",
65
+ "ne_phone",
66
+ "ru_phone_aatseel",
67
+ "ru_phone_yazhert",
68
+ "si",
69
+ "ta_inscript",
70
+ "ta_itrans",
71
+ "ta_phone",
72
+ "ta_tamil99",
73
+ "ta_typewriter",
74
+ "te_phone",
75
+ "th",
76
+ "th_pattajoti",
77
+ "th_tis",
78
+ "us",
79
+ "vi_tcvn",
80
+ "vi_telex",
81
+ "vi_viqr",
82
+ "vi_vni",
83
+ };
84
+
85
+ static rulebased::Engine engines[std::size(kEngineIds)];
86
+
87
+ uint8_t GetModifierFromKeyEvent(const rulebased_fuzzer::KeyEvent& e) {
88
+ uint8_t modifiers = 0;
89
+ if (e.shift())
90
+ modifiers |= rulebased::MODIFIER_SHIFT;
91
+ if (e.altgr())
92
+ modifiers |= rulebased::MODIFIER_ALTGR;
93
+ if (e.caps_lock())
94
+ modifiers |= rulebased::MODIFIER_CAPSLOCK;
95
+ return modifiers;
96
+ }
97
+
98
+ } // namespace
99
+
100
+ DEFINE_PROTO_FUZZER(const rulebased_fuzzer::TestFuzzerInput& msg) {
101
+ auto& engine = engines[msg.engine_id()];
102
+ engine.Activate(kEngineIds[msg.engine_id()]);
103
+
104
+ for (const auto& event : msg.key_events()) {
105
+ engine.ProcessKey(kKeyCodes[event.code()], GetModifierFromKeyEvent(event));
106
+ }
107
+ }
pool/shard006/C++/0074094_signal.cpp ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ \\ Author: Karl Redmond
3
+ \\ Date: 10th Oct 2017
4
+ \\ brief A Semaphore Implementation to show serialization, where task A must happen before task B, ie taskOne before taskTwo
5
+ \ \
6
+ \\ Uses C++11 features such as mutex and condition variables to implement Semaphore
7
+
8
+ */
9
+
10
+ #include "Semaphore.h"
11
+ #include <iostream>
12
+ #include <thread>
13
+
14
+
15
+ void taskOne(std::shared_ptr<Semaphore> theSemaphore){
16
+ std::cout <<"I ";
17
+ std::cout << "must ";
18
+ std::cout << "print ";
19
+ std::cout << "first"<<std::endl;
20
+ theSemaphore->Signal();
21
+ }
22
+ void taskTwo(std::shared_ptr<Semaphore> theSemaphore){
23
+ theSemaphore->Wait();
24
+ std::cout <<"This ";
25
+ std::cout << "will ";
26
+ std::cout << "appear ";
27
+ std::cout << "second"<<std::endl;
28
+ }
29
+
30
+ int main(void){
31
+ std::thread threadOne, threadTwo;
32
+ std::shared_ptr<Semaphore> sem( new Semaphore);
33
+ /**< Launch the threads */
34
+ threadOne=std::thread(taskTwo,sem);
35
+ threadTwo=std::thread(taskOne,sem);
36
+ std::cout << "Launched from the main\n";
37
+ threadOne.join();
38
+ threadTwo.join();
39
+ return 0;
40
+ }
pool/shard006/C++/0074103_urlfilterbuilder.cc ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 Google Inc.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+
16
+ #include "sitemapservice/asteriskfilter.h"
17
+ #include "sitemapservice/urlfilterbuilder.h"
18
+
19
+ UrlFilter* UrlFilterBuilder::Build(const Url& pattern) {
20
+ AsteriskFilter* filter = new AsteriskFilter(pattern.path_url());
21
+ return filter;
22
+ }
23
+
24
+ UrlFilter* UrlFilterBuilder::Build(const std::vector<Url>& patterns) {
25
+ OrFilter* orfilter = NULL;
26
+ for (int i = 0; i < static_cast<int>(patterns.size()); ++i) {
27
+ UrlFilter* filter = Build(patterns[i]);
28
+ if (filter != NULL) {
29
+ if (orfilter == NULL) {
30
+ orfilter = new OrFilter();
31
+ }
32
+ orfilter->AddFilter(filter);
33
+ }
34
+ }
35
+
36
+ if (orfilter != NULL) {
37
+ return orfilter;
38
+ } else {
39
+ return new DummyFilter(false);
40
+ }
41
+ }
pool/shard006/C++/0074109_TEvhttpServer.cpp ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+
20
+ #include <thrift/async/TEvhttpServer.h>
21
+ #include <thrift/async/TAsyncBufferProcessor.h>
22
+ #include <thrift/transport/TBufferTransports.h>
23
+ #include <evhttp.h>
24
+ #include <event2/buffer.h>
25
+ #include <event2/buffer_compat.h>
26
+
27
+ #include <iostream>
28
+
29
+ #ifndef HTTP_INTERNAL // libevent < 2
30
+ #define HTTP_INTERNAL 500
31
+ #endif
32
+
33
+ using apache::thrift::transport::TMemoryBuffer;
34
+
35
+ namespace apache {
36
+ namespace thrift {
37
+ namespace async {
38
+
39
+ struct TEvhttpServer::RequestContext {
40
+ struct evhttp_request* req;
41
+ boost::shared_ptr<apache::thrift::transport::TMemoryBuffer> ibuf;
42
+ boost::shared_ptr<apache::thrift::transport::TMemoryBuffer> obuf;
43
+
44
+ RequestContext(struct evhttp_request* req);
45
+ };
46
+
47
+ TEvhttpServer::TEvhttpServer(boost::shared_ptr<TAsyncBufferProcessor> processor)
48
+ : processor_(processor), eb_(NULL), eh_(NULL) {
49
+ }
50
+
51
+ TEvhttpServer::TEvhttpServer(boost::shared_ptr<TAsyncBufferProcessor> processor, int port)
52
+ : processor_(processor), eb_(NULL), eh_(NULL) {
53
+ // Create event_base and evhttp.
54
+ eb_ = event_base_new();
55
+ if (eb_ == NULL) {
56
+ throw TException("event_base_new failed");
57
+ }
58
+ eh_ = evhttp_new(eb_);
59
+ if (eh_ == NULL) {
60
+ event_base_free(eb_);
61
+ throw TException("evhttp_new failed");
62
+ }
63
+
64
+ // Bind to port.
65
+ int ret = evhttp_bind_socket(eh_, NULL, port);
66
+ if (ret < 0) {
67
+ evhttp_free(eh_);
68
+ event_base_free(eb_);
69
+ throw TException("evhttp_bind_socket failed");
70
+ }
71
+
72
+ // Register a handler. If you use the other constructor,
73
+ // you will want to do this yourself.
74
+ // Don't forget to unregister before destorying this TEvhttpServer.
75
+ evhttp_set_cb(eh_, "/", request, (void*)this);
76
+ }
77
+
78
+ TEvhttpServer::~TEvhttpServer() {
79
+ if (eh_ != NULL) {
80
+ evhttp_free(eh_);
81
+ }
82
+ if (eb_ != NULL) {
83
+ event_base_free(eb_);
84
+ }
85
+ }
86
+
87
+ int TEvhttpServer::serve() {
88
+ if (eb_ == NULL) {
89
+ throw TException("Unexpected call to TEvhttpServer::serve");
90
+ }
91
+ return event_base_dispatch(eb_);
92
+ }
93
+
94
+ TEvhttpServer::RequestContext::RequestContext(struct evhttp_request* req)
95
+ : req(req),
96
+ ibuf(new TMemoryBuffer(EVBUFFER_DATA(req->input_buffer),
97
+ static_cast<uint32_t>(EVBUFFER_LENGTH(req->input_buffer)))),
98
+ obuf(new TMemoryBuffer()) {
99
+ }
100
+
101
+ void TEvhttpServer::request(struct evhttp_request* req, void* self) {
102
+ try {
103
+ static_cast<TEvhttpServer*>(self)->process(req);
104
+ } catch (std::exception& e) {
105
+ evhttp_send_reply(req, HTTP_INTERNAL, e.what(), 0);
106
+ }
107
+ }
108
+
109
+ void TEvhttpServer::process(struct evhttp_request* req) {
110
+ RequestContext* ctx = new RequestContext(req);
111
+ return processor_->process(apache::thrift::stdcxx::bind(&TEvhttpServer::complete,
112
+ this,
113
+ ctx,
114
+ apache::thrift::stdcxx::placeholders::_1),
115
+ ctx->ibuf,
116
+ ctx->obuf);
117
+ }
118
+
119
+ void TEvhttpServer::complete(RequestContext* ctx, bool success) {
120
+ (void)success;
121
+ std::auto_ptr<RequestContext> ptr(ctx);
122
+
123
+ int code = success ? 200 : 400;
124
+ const char* reason = success ? "OK" : "Bad Request";
125
+
126
+ int rv = evhttp_add_header(ctx->req->output_headers, "Content-Type", "application/x-thrift");
127
+ if (rv != 0) {
128
+ // TODO: Log an error.
129
+ std::cerr << "evhttp_add_header failed " << __FILE__ << ":" << __LINE__ << std::endl;
130
+ }
131
+
132
+ struct evbuffer* buf = evbuffer_new();
133
+ if (buf == NULL) {
134
+ // TODO: Log an error.
135
+ std::cerr << "evbuffer_new failed " << __FILE__ << ":" << __LINE__ << std::endl;
136
+ } else {
137
+ uint8_t* obuf;
138
+ uint32_t sz;
139
+ ctx->obuf->getBuffer(&obuf, &sz);
140
+ int ret = evbuffer_add(buf, obuf, sz);
141
+ if (ret != 0) {
142
+ // TODO: Log an error.
143
+ std::cerr << "evhttp_add failed with " << ret << " " << __FILE__ << ":" << __LINE__
144
+ << std::endl;
145
+ }
146
+ }
147
+
148
+ evhttp_send_reply(ctx->req, code, reason, buf);
149
+ if (buf != NULL) {
150
+ evbuffer_free(buf);
151
+ }
152
+ }
153
+
154
+ struct event_base* TEvhttpServer::getEventBase() {
155
+ return eb_;
156
+ }
157
+ }
158
+ }
159
+ } // apache::thrift::async
pool/shard006/C++/0074118_unlinkd_daemon.cc ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3
+ *
4
+ * Squid software is distributed under GPLv2+ license and includes
5
+ * contributions from numerous individuals and organizations.
6
+ * Please see the COPYING and CONTRIBUTORS files for details.
7
+ */
8
+
9
+ /* DEBUG: section -- Unlink Daemon */
10
+
11
+ #define SQUID_HELPER 1
12
+
13
+ #include "squid.h"
14
+
15
+ #if HAVE_PATHS_H
16
+ #include <paths.h>
17
+ #endif
18
+
19
+ /**
20
+ \defgroup unlinkd unlinkd
21
+ \ingroup ExternalPrograms
22
+ \par
23
+ The unlink(2) system call can cause a process to block
24
+ for a significant amount of time. Therefore we do not want
25
+ to make unlink() calls from Squid. Instead we pass them
26
+ to this external process.
27
+ */
28
+
29
+ /// \ingroup unlinkd
30
+ #define UNLINK_BUF_LEN 1024
31
+
32
+ /**
33
+ \ingroup unlinkd
34
+ \par This is the unlinkd external process.
35
+ *
36
+ \par
37
+ * unlinkd receives the full path of any files to be removed
38
+ * from stdin, each on its own line.
39
+ *
40
+ \par
41
+ * The results for each file are printed to stdout in the order
42
+ * they were received
43
+ *
44
+ \param argc Ignored.
45
+ \param argv Ignored.
46
+ \retval ERR An error occured removing the file.
47
+ \retval OK The file has been removed.
48
+ */
49
+ int
50
+ main(int argc, char *argv[])
51
+ {
52
+ char buf[UNLINK_BUF_LEN];
53
+ char *t;
54
+ int x;
55
+ setbuf(stdin, NULL);
56
+ setbuf(stdout, NULL);
57
+ close(2);
58
+ if (open(_PATH_DEVNULL, O_RDWR) < 0) {
59
+ ; // the irony of having to close(2) earlier is that we cannot report this failure.
60
+ }
61
+
62
+ while (fgets(buf, sizeof(buf), stdin)) {
63
+ if ((t = strchr(buf, '\n')))
64
+ *t = '\0';
65
+ x = unlink(buf);
66
+ if (x < 0)
67
+ printf("ERR\n");
68
+ else
69
+ printf("OK\n");
70
+ }
71
+
72
+ return 0;
73
+ }
74
+
pool/shard006/C++/0074121_system_clock_client.cc ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "chromeos/dbus/system_clock/system_clock_client.h"
6
+
7
+ #include <stdint.h>
8
+
9
+ #include <string>
10
+
11
+ #include "base/bind.h"
12
+ #include "base/callback_helpers.h"
13
+ #include "base/logging.h"
14
+ #include "base/observer_list.h"
15
+ #include "chromeos/dbus/system_clock/fake_system_clock_client.h"
16
+ #include "dbus/bus.h"
17
+ #include "dbus/message.h"
18
+ #include "dbus/object_path.h"
19
+ #include "third_party/cros_system_api/dbus/service_constants.h"
20
+
21
+ namespace chromeos {
22
+
23
+ namespace {
24
+
25
+ // Handles replies to D-Bus calls made by GetLastSyncInfo.
26
+ void OnGetLastSyncInfo(SystemClockClient::GetLastSyncInfoCallback callback,
27
+ dbus::Response* response) {
28
+ if (!response) {
29
+ LOG(ERROR) << system_clock::kSystemClockInterface << "."
30
+ << system_clock::kSystemLastSyncInfo << " request failed.";
31
+ return;
32
+ }
33
+ dbus::MessageReader reader(response);
34
+ bool network_synchronized = false;
35
+ if (!reader.PopBool(&network_synchronized)) {
36
+ LOG(ERROR) << system_clock::kSystemClockInterface << "."
37
+ << system_clock::kSystemLastSyncInfo
38
+ << " response lacks network-synchronized argument.";
39
+ return;
40
+ }
41
+ std::move(callback).Run(network_synchronized);
42
+ }
43
+
44
+ SystemClockClient* g_instance = nullptr;
45
+
46
+ } // namespace
47
+
48
+ // The SystemClockClient implementation used in production.
49
+ class SystemClockClientImpl : public SystemClockClient {
50
+ public:
51
+ explicit SystemClockClientImpl(dbus::Bus* bus)
52
+ : can_set_time_(false),
53
+ can_set_time_initialized_(false),
54
+ system_clock_proxy_(nullptr) {
55
+ CHECK(bus);
56
+ InitDBus(bus);
57
+ }
58
+
59
+ SystemClockClientImpl(const SystemClockClientImpl&) = delete;
60
+ SystemClockClientImpl& operator=(const SystemClockClientImpl&) = delete;
61
+
62
+ ~SystemClockClientImpl() override = default;
63
+
64
+ void AddObserver(Observer* observer) override {
65
+ observers_.AddObserver(observer);
66
+ }
67
+
68
+ void RemoveObserver(Observer* observer) override {
69
+ observers_.RemoveObserver(observer);
70
+ }
71
+
72
+ bool HasObserver(const Observer* observer) const override {
73
+ return observers_.HasObserver(observer);
74
+ }
75
+
76
+ void SetTime(int64_t time_in_seconds) override {
77
+ // Always try to set the time, because |can_set_time_| may be stale.
78
+ dbus::MethodCall method_call(system_clock::kSystemClockInterface,
79
+ system_clock::kSystemClockSet);
80
+ dbus::MessageWriter writer(&method_call);
81
+ writer.AppendInt64(time_in_seconds);
82
+ system_clock_proxy_->CallMethod(&method_call,
83
+ dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
84
+ base::DoNothing());
85
+ }
86
+
87
+ bool CanSetTime() override { return can_set_time_; }
88
+
89
+ void GetLastSyncInfo(GetLastSyncInfoCallback callback) override {
90
+ dbus::MethodCall method_call(system_clock::kSystemClockInterface,
91
+ system_clock::kSystemLastSyncInfo);
92
+ system_clock_proxy_->CallMethod(
93
+ &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
94
+ base::BindOnce(OnGetLastSyncInfo, std::move(callback)));
95
+ }
96
+
97
+ void WaitForServiceToBeAvailable(
98
+ dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback)
99
+ override {
100
+ system_clock_proxy_->WaitForServiceToBeAvailable(std::move(callback));
101
+ }
102
+
103
+ TestInterface* GetTestInterface() override { return nullptr; }
104
+
105
+ private:
106
+ void InitDBus(dbus::Bus* bus) {
107
+ system_clock_proxy_ = bus->GetObjectProxy(
108
+ system_clock::kSystemClockServiceName,
109
+ dbus::ObjectPath(system_clock::kSystemClockServicePath));
110
+ system_clock_proxy_->ConnectToSignal(
111
+ system_clock::kSystemClockInterface, system_clock::kSystemClockUpdated,
112
+ base::BindRepeating(&SystemClockClientImpl::TimeUpdatedReceived,
113
+ weak_ptr_factory_.GetWeakPtr()),
114
+ base::BindOnce(&SystemClockClientImpl::TimeUpdatedConnected,
115
+ weak_ptr_factory_.GetWeakPtr()));
116
+ WaitForServiceToBeAvailable(
117
+ base::BindOnce(&SystemClockClientImpl::ServiceInitiallyAvailable,
118
+ weak_ptr_factory_.GetWeakPtr()));
119
+ }
120
+
121
+ // Called once when the service initially becomes available (or immediately if
122
+ // it's already available).
123
+ void ServiceInitiallyAvailable(bool service_is_available) {
124
+ if (service_is_available)
125
+ GetCanSet();
126
+ else
127
+ LOG(ERROR) << "Failed to wait for D-Bus service availability";
128
+ }
129
+
130
+ // Called when a TimeUpdated signal is received.
131
+ void TimeUpdatedReceived(dbus::Signal* signal) {
132
+ VLOG(1) << "TimeUpdated signal received: " << signal->ToString();
133
+ dbus::MessageReader reader(signal);
134
+ for (auto& observer : observers_)
135
+ observer.SystemClockUpdated();
136
+
137
+ // Check if the system clock can be changed now.
138
+ GetCanSet();
139
+ }
140
+
141
+ // Called when the TimeUpdated signal is initially connected.
142
+ void TimeUpdatedConnected(const std::string& interface_name,
143
+ const std::string& signal_name,
144
+ bool success) {
145
+ LOG_IF(ERROR, !success) << "Failed to connect to TimeUpdated signal.";
146
+ }
147
+
148
+ // Callback for CanSetTime method.
149
+ void OnGetCanSet(dbus::Response* response) {
150
+ if (!response) {
151
+ VLOG(1) << "CanSetTime request failed.";
152
+ return;
153
+ }
154
+
155
+ dbus::MessageReader reader(response);
156
+ bool can_set_time;
157
+ if (!reader.PopBool(&can_set_time)) {
158
+ LOG(ERROR) << "CanSetTime response invalid: " << response->ToString();
159
+ return;
160
+ }
161
+
162
+ // Nothing to do if the CanSetTime response hasn't changed.
163
+ if (can_set_time_initialized_ && can_set_time_ == can_set_time)
164
+ return;
165
+
166
+ can_set_time_initialized_ = true;
167
+ can_set_time_ = can_set_time;
168
+
169
+ for (auto& observer : observers_)
170
+ observer.SystemClockCanSetTimeChanged(can_set_time);
171
+ }
172
+
173
+ // Check whether the time can be set.
174
+ void GetCanSet() {
175
+ dbus::MethodCall method_call(system_clock::kSystemClockInterface,
176
+ system_clock::kSystemClockCanSet);
177
+ dbus::MessageWriter writer(&method_call);
178
+ system_clock_proxy_->CallMethod(
179
+ &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
180
+ base::BindOnce(&SystemClockClientImpl::OnGetCanSet,
181
+ weak_ptr_factory_.GetWeakPtr()));
182
+ }
183
+
184
+ // Whether the time can be set. Value is false until the first
185
+ // CanSetTime response is received.
186
+ bool can_set_time_;
187
+ bool can_set_time_initialized_;
188
+ dbus::ObjectProxy* system_clock_proxy_;
189
+ base::ObserverList<Observer>::Unchecked observers_;
190
+
191
+ base::WeakPtrFactory<SystemClockClientImpl> weak_ptr_factory_{this};
192
+ };
193
+
194
+ SystemClockClient::SystemClockClient() {
195
+ CHECK(!g_instance);
196
+ g_instance = this;
197
+ }
198
+
199
+ SystemClockClient::~SystemClockClient() {
200
+ CHECK_EQ(this, g_instance);
201
+ g_instance = nullptr;
202
+ }
203
+
204
+ // static
205
+ void SystemClockClient::Initialize(dbus::Bus* bus) {
206
+ CHECK(bus);
207
+ new SystemClockClientImpl(bus);
208
+ }
209
+
210
+ // static
211
+ void SystemClockClient::InitializeFake() {
212
+ new FakeSystemClockClient();
213
+ }
214
+
215
+ // static
216
+ void SystemClockClient::Shutdown() {
217
+ CHECK(g_instance);
218
+ delete g_instance;
219
+ }
220
+
221
+ // static
222
+ SystemClockClient* SystemClockClient::Get() {
223
+ return g_instance;
224
+ }
225
+
226
+ } // namespace chromeos
pool/shard006/C++/0074130_instance_endtime.cpp ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/>
3
+ *
4
+ * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/>
5
+ *
6
+ * Copyright (C) 2011 TrilliumEMU <http://www.arkania.net/>
7
+ *
8
+ * This program is free software; you can redistribute it and/or modify it
9
+ * under the terms of the GNU General Public License as published by the
10
+ * Free Software Foundation; either version 2 of the License, or (at your
11
+ * option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful, but WITHOUT
14
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16
+ * more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License along
19
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ */
21
+
22
+ #include "ObjectMgr.h"
23
+ #include "ScriptMgr.h"
24
+ #include "InstanceScript.h"
25
+ #include "ScriptedCreature.h"
26
+ #include "Map.h"
27
+ #include "PoolMgr.h"
28
+ #include "AccountMgr.h"
29
+ #include "endtime.h"
30
+ #include "Player.h"
31
+ #include "WorldPacket.h"
32
+ #include "WorldSession.h"
33
+
34
+ #define MAX_ENCOUNTER 5
35
+
36
+ class instance_endtime : public InstanceMapScript
37
+ {
38
+ public:
39
+ instance_endtime() : InstanceMapScript("instance_endtime", 938) { }
40
+
41
+ struct instance_endtime_InstanceMapScript: public InstanceScript
42
+ {
43
+ instance_endtime_InstanceMapScript(InstanceMap* map) : InstanceScript(map)
44
+ {
45
+ SetBossNumber(MAX_ENCOUNTER);
46
+ uiBaine = 0;
47
+ uiJaina = 0;
48
+ uiSylvanas = 0;
49
+ uiTyrande = 0;
50
+ uiMurozond = 0;
51
+ GoHourGlassofTimeGUID = 0;
52
+ GoTimeTansitDeviceGUID = 0;
53
+ GoMurozondCacheGUID = 0;
54
+ GoBainePlatform1GUID = 0;
55
+ GoBainePlatform2GUID = 0;
56
+ GoBainePlatform3GUID = 0;
57
+ GoBainePlatform4GUID = 0;
58
+ GoFragmentsGUID = 0;
59
+
60
+ }
61
+
62
+ void OnGameObjectCreate(GameObject* go)
63
+ {
64
+ switch (go->GetEntry())
65
+ {
66
+ case HOURGLASS_OF_TIME:
67
+ GoHourGlassofTimeGUID = go->GetGUID();
68
+ break;
69
+ case BAINE_PLATFORM_1:
70
+ GoBainePlatform1GUID = go->GetGUID();
71
+ break;
72
+ case BAINE_PLATFORM_2:
73
+ GoBainePlatform2GUID = go->GetGUID();
74
+ break;
75
+ case BAINE_PLATFORM_3:
76
+ GoBainePlatform3GUID = go->GetGUID();
77
+ break;
78
+ case BAINE_PLATFORM_4:
79
+ GoBainePlatform4GUID = go->GetGUID();
80
+ break;
81
+ case JAINAS_STAFF:
82
+ GoFragmentsGUID = go->GetGUID();
83
+ go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
84
+ break;
85
+ case MUROSZONDS_TEMPORAL_CACHE:
86
+ GoMurozondCacheGUID = go->GetGUID();
87
+ break;
88
+ }
89
+ }
90
+
91
+ void OnCreatureCreate(Creature* creature, bool )
92
+ {
93
+ switch (creature->GetEntry())
94
+ {
95
+ case BOSS_BAINE:
96
+ uiBaine = creature->GetGUID();
97
+ break;
98
+ case BOSS_JAINA:
99
+ uiJaina = creature->GetGUID();
100
+ break;
101
+ case BOSS_SYLVANAS:
102
+ uiSylvanas = creature->GetGUID();
103
+ break;
104
+ case BOSS_TYRANDE:
105
+ uiTyrande = creature->GetGUID();
106
+ break;
107
+ case BOSS_MUROZOND:
108
+ uiMurozond = creature->GetGUID();
109
+ break;
110
+ }
111
+ }
112
+
113
+ uint64 getData64(uint32 index) const
114
+ {
115
+ switch (index)
116
+ {
117
+ case DATA_ECHO_OF_BAINE:
118
+ return uiBaine;
119
+ case DATA_ECHO_OF_JAINA:
120
+ return uiJaina;
121
+ case DATA_JAINAS_STAFF:
122
+ return jainasstaff;
123
+ case DATA_ECHO_OF_SYLVANAS:
124
+ return uiSylvanas;
125
+ case DATA_ECHO_OF_TYRANDE:
126
+ return uiTyrande;
127
+ case DATA_MUROZOND:
128
+ return uiMurozond;
129
+ }
130
+ return 0;
131
+ }
132
+
133
+ std::string GetSaveData()
134
+ {
135
+ OUT_SAVE_INST_DATA;
136
+
137
+ std::ostringstream saveStream;
138
+ saveStream << "H O " << GetBossSaveData();
139
+
140
+ OUT_SAVE_INST_DATA_COMPLETE;
141
+ return saveStream.str();
142
+ }
143
+
144
+ void Load(const char* in)
145
+ {
146
+ if (!in)
147
+ {
148
+ OUT_LOAD_INST_DATA_FAIL;
149
+ return;
150
+ }
151
+
152
+ OUT_LOAD_INST_DATA(in);
153
+
154
+ char dataHead1, dataHead2;
155
+ uint16 data0, data1;
156
+
157
+ std::istringstream loadStream(in);
158
+ loadStream >> dataHead1 >> dataHead2;
159
+
160
+ if (dataHead1 == 'H' && dataHead2 == 'O')
161
+ {
162
+ for (uint32 i = 0; i < EncounterCount; ++i)
163
+ {
164
+ uint32 tmpState;
165
+ loadStream >> tmpState;
166
+ if (tmpState == IN_PROGRESS || tmpState > SPECIAL)
167
+ tmpState = NOT_STARTED;
168
+ SetBossState(i, EncounterState(tmpState));
169
+ }
170
+ uint32 tmp;
171
+ loadStream >> tmp;
172
+ }
173
+ else
174
+ OUT_LOAD_INST_DATA_FAIL;
175
+
176
+ OUT_LOAD_INST_DATA_COMPLETE;
177
+ }
178
+ protected:
179
+ uint64 uiBaine;
180
+ uint64 uiJaina;
181
+ uint64 uiSylvanas;
182
+ uint64 uiTyrande;
183
+ uint64 uiMurozond;
184
+ uint64 GoHourGlassofTimeGUID;
185
+ uint64 GoTimeTansitDeviceGUID;
186
+ uint64 GoMurozondCacheGUID;
187
+ uint64 GoBainePlatform1GUID;
188
+ uint64 GoBainePlatform2GUID;
189
+ uint64 GoBainePlatform3GUID;
190
+ uint64 GoBainePlatform4GUID;
191
+ uint64 GoFragmentsGUID;
192
+ uint64 jainasstaff;
193
+ };
194
+
195
+ InstanceScript* GetInstanceScript(InstanceMap* map) const
196
+ {
197
+ return new instance_endtime_InstanceMapScript(map);
198
+ }
199
+ };
200
+
201
+ void AddSC_instance_endtime()
202
+ {
203
+ new instance_endtime();
204
+ }
pool/shard006/C++/0074139_password_manager_exporter.cc ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #include "components/password_manager/core/browser/export/password_manager_exporter.h"
6
+
7
+ #include <utility>
8
+
9
+ #include "base/bind.h"
10
+ #include "base/containers/flat_set.h"
11
+ #include "base/files/file_util.h"
12
+ #include "base/location.h"
13
+ #include "base/metrics/histogram_macros.h"
14
+ #include "base/task/lazy_thread_pool_task_runner.h"
15
+ #include "base/task/post_task.h"
16
+ #include "base/task/task_runner_util.h"
17
+ #include "build/build_config.h"
18
+ #include "components/password_manager/core/browser/export/password_csv_writer.h"
19
+ #include "components/password_manager/core/browser/password_form.h"
20
+ #include "components/password_manager/core/browser/password_list_sorter.h"
21
+ #include "components/password_manager/core/browser/password_manager_metrics_util.h"
22
+ #include "components/password_manager/core/browser/ui/credential_provider_interface.h"
23
+
24
+ namespace password_manager {
25
+
26
+ namespace {
27
+
28
+ // Multiple exports should be queued in sequence. This helps avoid race
29
+ // conditions where there are multiple simultaneous exports to the same
30
+ // destination and one of them was cancelled and will delete the file. We use
31
+ // TaskPriority::USER_VISIBLE, because a busy UI is displayed while the
32
+ // passwords are being exported.
33
+ base::LazyThreadPoolSingleThreadTaskRunner g_task_runner =
34
+ LAZY_THREAD_POOL_SINGLE_THREAD_TASK_RUNNER_INITIALIZER(
35
+ base::TaskTraits(base::MayBlock(), base::TaskPriority::USER_VISIBLE),
36
+ base::SingleThreadTaskRunnerThreadMode::SHARED);
37
+
38
+ // A wrapper for |write_function|, which can be bound and keep a copy of its
39
+ // data on the closure.
40
+ bool DoWriteOnTaskRunner(
41
+ PasswordManagerExporter::WriteCallback write_function,
42
+ PasswordManagerExporter::SetPosixFilePermissionsCallback
43
+ set_permissions_function,
44
+ const base::FilePath& destination,
45
+ const std::string& serialised) {
46
+ if (!write_function.Run(destination, serialised))
47
+ return false;
48
+
49
+ // Set file permissions. This is a no-op outside of Posix.
50
+ set_permissions_function.Run(destination, 0600 /* -rw------- */);
51
+ return true;
52
+ }
53
+
54
+ bool DefaultWriteFunction(const base::FilePath& file, base::StringPiece data) {
55
+ return base::WriteFile(file, data);
56
+ }
57
+
58
+ bool DefaultDeleteFunction(const base::FilePath& file) {
59
+ return base::DeleteFile(file);
60
+ }
61
+
62
+ std::vector<std::unique_ptr<PasswordForm>> DeduplicatePasswordsAcrossStores(
63
+ std::vector<std::unique_ptr<PasswordForm>> passwords) {
64
+ auto get_sort_key = [](const auto& password) {
65
+ return CreateSortKey(*password, IgnoreStore(true));
66
+ };
67
+ auto cmp = [&](const auto& lhs, const auto& rhs) {
68
+ return get_sort_key(lhs) < get_sort_key(rhs);
69
+ };
70
+ base::flat_set<std::unique_ptr<PasswordForm>, decltype(cmp)> unique_passwords(
71
+ std::move(passwords), cmp);
72
+ return std::move(unique_passwords).extract();
73
+ }
74
+
75
+ } // namespace
76
+
77
+ PasswordManagerExporter::PasswordManagerExporter(
78
+ CredentialProviderInterface* credential_provider_interface,
79
+ ProgressCallback on_progress)
80
+ : credential_provider_interface_(credential_provider_interface),
81
+ on_progress_(std::move(on_progress)),
82
+ last_progress_status_(ExportProgressStatus::NOT_STARTED),
83
+ write_function_(base::BindRepeating(&DefaultWriteFunction)),
84
+ delete_function_(base::BindRepeating(&DefaultDeleteFunction)),
85
+ #if defined(OS_POSIX)
86
+ set_permissions_function_(
87
+ base::BindRepeating(base::SetPosixFilePermissions)),
88
+ #else
89
+ set_permissions_function_(
90
+ base::BindRepeating([](const base::FilePath&, int) { return true; })),
91
+ #endif
92
+ task_runner_(g_task_runner.Get()) {
93
+ }
94
+
95
+ PasswordManagerExporter::~PasswordManagerExporter() = default;
96
+
97
+ void PasswordManagerExporter::PreparePasswordsForExport() {
98
+ DCHECK_EQ(GetProgressStatus(), ExportProgressStatus::NOT_STARTED);
99
+
100
+ std::vector<std::unique_ptr<PasswordForm>> password_list =
101
+ credential_provider_interface_->GetAllPasswords();
102
+
103
+ // Deduplicate passwords that are present in multiple stores, so the output
104
+ // file doesn't contain repeated data.
105
+ std::vector<std::unique_ptr<PasswordForm>> deduplicated_password_list =
106
+ DeduplicatePasswordsAcrossStores(std::move(password_list));
107
+
108
+ size_t deduplicated_password_list_size = deduplicated_password_list.size();
109
+ base::PostTaskAndReplyWithResult(
110
+ task_runner_.get(), FROM_HERE,
111
+ base::BindOnce(&PasswordCSVWriter::SerializePasswords,
112
+ std::move(deduplicated_password_list)),
113
+ base::BindOnce(&PasswordManagerExporter::SetSerialisedPasswordList,
114
+ weak_factory_.GetWeakPtr(),
115
+ deduplicated_password_list_size));
116
+ }
117
+
118
+ void PasswordManagerExporter::SetDestination(
119
+ const base::FilePath& destination) {
120
+ DCHECK_EQ(GetProgressStatus(), ExportProgressStatus::NOT_STARTED);
121
+
122
+ destination_ = destination;
123
+
124
+ if (IsReadyForExport())
125
+ Export();
126
+
127
+ OnProgress(ExportProgressStatus::IN_PROGRESS, std::string());
128
+ }
129
+
130
+ void PasswordManagerExporter::SetSerialisedPasswordList(
131
+ size_t count,
132
+ const std::string& serialised) {
133
+ serialised_password_list_ = serialised;
134
+ password_count_ = count;
135
+ if (IsReadyForExport())
136
+ Export();
137
+ }
138
+
139
+ void PasswordManagerExporter::Cancel() {
140
+ // Tasks which had their pointers invalidated won't run.
141
+ weak_factory_.InvalidateWeakPtrs();
142
+
143
+ // If we are currently still serialising, Export() will see the cancellation
144
+ // status and won't schedule writing.
145
+ OnProgress(ExportProgressStatus::FAILED_CANCELLED, std::string());
146
+
147
+ // If we are currently writing to the disk, we will have to cleanup the file
148
+ // once writing stops.
149
+ Cleanup();
150
+ }
151
+
152
+ ExportProgressStatus PasswordManagerExporter::GetProgressStatus() {
153
+ return last_progress_status_;
154
+ }
155
+
156
+ void PasswordManagerExporter::SetWriteForTesting(WriteCallback write_function) {
157
+ write_function_ = std::move(write_function);
158
+ }
159
+
160
+ void PasswordManagerExporter::SetDeleteForTesting(
161
+ DeleteCallback delete_callback) {
162
+ delete_function_ = std::move(delete_callback);
163
+ }
164
+
165
+ void PasswordManagerExporter::SetSetPosixFilePermissionsForTesting(
166
+ SetPosixFilePermissionsCallback set_permissions_callback) {
167
+ set_permissions_function_ = std::move(set_permissions_callback);
168
+ }
169
+
170
+ bool PasswordManagerExporter::IsReadyForExport() {
171
+ return !destination_.empty() && !serialised_password_list_.empty();
172
+ }
173
+
174
+ void PasswordManagerExporter::Export() {
175
+ // If cancelling was requested while we were serialising the passwords, don't
176
+ // write anything to the disk.
177
+ if (GetProgressStatus() == ExportProgressStatus::FAILED_CANCELLED) {
178
+ serialised_password_list_.clear();
179
+ return;
180
+ }
181
+
182
+ base::PostTaskAndReplyWithResult(
183
+ task_runner_.get(), FROM_HERE,
184
+ base::BindOnce(DoWriteOnTaskRunner, write_function_,
185
+ set_permissions_function_, destination_,
186
+ std::move(serialised_password_list_)),
187
+ base::BindOnce(&PasswordManagerExporter::OnPasswordsExported,
188
+ weak_factory_.GetWeakPtr()));
189
+ }
190
+
191
+ void PasswordManagerExporter::OnPasswordsExported(bool success) {
192
+ if (success) {
193
+ OnProgress(ExportProgressStatus::SUCCEEDED, std::string());
194
+ } else {
195
+ OnProgress(ExportProgressStatus::FAILED_WRITE_FAILED,
196
+ destination_.DirName().BaseName().AsUTF8Unsafe());
197
+ // Don't leave partial password files, if we tell the user we couldn't write
198
+ Cleanup();
199
+ }
200
+ }
201
+
202
+ void PasswordManagerExporter::OnProgress(ExportProgressStatus status,
203
+ const std::string& folder) {
204
+ last_progress_status_ = status;
205
+ on_progress_.Run(status, folder);
206
+ }
207
+
208
+ void PasswordManagerExporter::Cleanup() {
209
+ // The PasswordManagerExporter instance may be destroyed before the cleanup is
210
+ // executed, e.g. because a new export was initiated. The cleanup should be
211
+ // carried out regardless, so we only schedule tasks which own their
212
+ // arguments.
213
+ // TODO(crbug.com/811779) When Chrome is overwriting an existing file, cancel
214
+ // should restore the file rather than delete it.
215
+ if (!destination_.empty()) {
216
+ task_runner_->PostTask(
217
+ FROM_HERE,
218
+ base::BindOnce(base::IgnoreResult(delete_function_), destination_));
219
+ }
220
+ }
221
+
222
+ } // namespace password_manager
pool/shard006/C++/0074141_smoothFit.cpp ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // smoothFit.cpp : performs a smooth fit to scattered data
2
+ //
3
+
4
+ #include <core/UTypes.h>
5
+ #include <containers/UArray.h>
6
+ #include <core/UString.h>
7
+
8
+ #include "VectorField2D.h"
9
+ #include "ScatteredVectorData2D.h"
10
+ #include "ParameterFileReader.h"
11
+
12
+ #include <hdf5.h>
13
+ #include <hdf5_hl.h>
14
+
15
+ #include <math.h>
16
+ #include <cstdlib>
17
+
18
+
19
+ bool getParameters();
20
+
21
+ bool getGridInfo();
22
+
23
+ bool constructGriddedFieldFromScatteredField();
24
+
25
+ UString inGridFileName;
26
+ UString inScatteredFieldFileName;
27
+ UString outGridFieldFileName;
28
+
29
+ UArray<SInt32> imageSize;
30
+ UArray<double> imageBounds;
31
+
32
+ SInt32 smoothFitMinControlPointScatteredNeighbors;
33
+
34
+
35
+ int main(int argc, char * argv[])
36
+ {
37
+
38
+ if(!getParameters())
39
+ {
40
+ fprintf(stderr, "Could not read parameters\n");
41
+ return -1;
42
+ }
43
+
44
+ if(!getGridInfo())
45
+ {
46
+ fprintf(stderr, "Could not read grid file\n");
47
+ return -1;
48
+ }
49
+
50
+ if(!constructGriddedFieldFromScatteredField())
51
+ {
52
+ fprintf(stderr, "Could not perform smooth fit\n");
53
+ return -1;
54
+ }
55
+
56
+
57
+ return 0;
58
+ }
59
+
60
+
61
+ bool getParameters()
62
+ {
63
+ UString fileName = "parameters.ascii";
64
+ ParameterFileReader reader(fileName);
65
+
66
+ UString defaultParameterFile;
67
+ UString tag;
68
+ tag = "defaultParameterFile";
69
+ if(reader.getString(tag, defaultParameterFile))
70
+ {
71
+ reader.addFile(defaultParameterFile);
72
+ }
73
+
74
+ tag = "inGridFileName";
75
+ if(!reader.getString(tag, inGridFileName))
76
+ {
77
+ fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag);
78
+ return false;
79
+ }
80
+ tag = "inScatteredFieldFileName";
81
+ if(!reader.getString(tag, inScatteredFieldFileName))
82
+ {
83
+ fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag);
84
+ return false;
85
+ }
86
+ tag = "outGridFieldFileName";
87
+ if(!reader.getString(tag, outGridFieldFileName))
88
+ {
89
+ fprintf(stderr, "getParameters: Could not read tag %s\n", (const char *)tag);
90
+ return false;
91
+ }
92
+ tag = "smoothFitMinControlPointScatteredNeighbors";
93
+ if(!reader.getInteger(tag, smoothFitMinControlPointScatteredNeighbors))
94
+ {
95
+ smoothFitMinControlPointScatteredNeighbors = 16;
96
+ }
97
+ return true;
98
+ }
99
+
100
+ bool getGridInfo()
101
+ {
102
+
103
+ VectorField2D grid;
104
+
105
+ if(!grid.read(inGridFileName))
106
+ {
107
+ fprintf(stderr, "getGridInfo: Could not read grid velocity scaling from file %s\n", (const char *)inGridFileName);
108
+ return false;
109
+ }
110
+
111
+ imageSize.setSize(2);
112
+ imageSize[0] = grid.getXSize();
113
+ imageSize[1] = grid.getYSize();
114
+
115
+ imageBounds.setSize(4);
116
+ imageBounds[0] = grid.getXLower();
117
+ imageBounds[1] = grid.getXUpper();
118
+ imageBounds[2] = grid.getYLower();
119
+ imageBounds[3] = grid.getYUpper();
120
+
121
+ return true;
122
+ }
123
+
124
+ bool constructGriddedFieldFromScatteredField()
125
+ {
126
+
127
+ ScatteredVectorData2D scatteredField;
128
+ if(!scatteredField.read(inScatteredFieldFileName))
129
+ return false;
130
+
131
+ VectorField2D griddedField(imageSize[0], imageSize[1], imageBounds[0], imageBounds[1], imageBounds[2], imageBounds[3]);
132
+
133
+ double meanRes = 0.0;
134
+ UArray<vector2d> residuals;
135
+
136
+ scatteredField.smoothFit(griddedField, smoothFitMinControlPointScatteredNeighbors, residuals, meanRes);
137
+
138
+ if(!griddedField.write(outGridFieldFileName))
139
+ return false;
140
+
141
+ // add the mean residual
142
+ hid_t fileID = H5Fopen(outGridFieldFileName, H5F_ACC_RDWR, H5P_DEFAULT);
143
+ if(fileID < 0)
144
+ {
145
+ fprintf(stderr, "constructGriddedFieldFromScatteredField: Could not open file %s\n",
146
+ (const char *)outGridFieldFileName);
147
+ return false;
148
+ }
149
+
150
+ UString dataSetName = "/meanResidual";
151
+ hsize_t dimensions[2];
152
+ dimensions[0] = 1;
153
+ herr_t status = H5LTmake_dataset(fileID, dataSetName, 1, dimensions, H5T_NATIVE_DOUBLE, &meanRes);
154
+ if((status < 0))
155
+ {
156
+ fprintf(stderr, "constructGriddedFieldFromScatteredField: Could not make dataset %s in file %s\n",
157
+ (const char *)dataSetName, (const char *)outGridFieldFileName);
158
+ return false;
159
+ }
160
+
161
+ status = H5Fclose(fileID);
162
+
163
+ return true;
164
+ }
165
+
pool/shard006/C++/0074149_BasilarMembraneNonlinearGammatone.cpp ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <iostream>
2
+ #include "Earlab.h"
3
+ #include "CParameterFile.h"
4
+ #include "ParameterStatus.h"
5
+ #include <stdio.h>
6
+ #include <math.h>
7
+ #include <memory.h>
8
+ #include <string.h>
9
+ #include <fcntl.h>
10
+ #include "BasilarMembraneNonlinearGammatone.h"
11
+ #include "EarlabException.h"
12
+ #include <float.h>
13
+ #ifdef _WIN32
14
+ # include <windows.h>
15
+ #endif
16
+
17
+ using namespace std;
18
+
19
+ BasilarMembraneNonlinearGammatone::BasilarMembraneNonlinearGammatone()
20
+ {
21
+ memset(this, 0, sizeof(BasilarMembraneNonlinearGammatone));
22
+ SetModuleName("BasilarMembraneNonlinearGammatone");
23
+ }
24
+
25
+ BasilarMembraneNonlinearGammatone::~BasilarMembraneNonlinearGammatone()
26
+ {
27
+ if (mMetadataFile != NULL)
28
+ delete mMetadataFile;
29
+ if (mCFArray_Hz != NULL)
30
+ delete [] mCFArray_Hz;
31
+ if (mDRNL != NULL)
32
+ delete [] mDRNL;
33
+ if (mLowpassFilter != NULL)
34
+ delete [] mLowpassFilter;
35
+ }
36
+
37
+ int BasilarMembraneNonlinearGammatone::ReadParameters(const char *ParameterFileName)
38
+ {
39
+ return ReadParameters(ParameterFileName, ModuleName());
40
+ }
41
+
42
+ int BasilarMembraneNonlinearGammatone::ReadParameters(const char *ParameterFileName, const char *SectionName)
43
+ {
44
+ CParameterFile theParamFile(ParameterFileName);
45
+ ParameterStatus Status;
46
+
47
+ Log(" ReadParameters: %s \"%s\"", ModuleName(), ParameterFileName);
48
+
49
+ // Number of channels and Frame Size are passed as parameters to Start, see that function for details
50
+ Status = theParamFile.GetParameter(SectionName, "SampleRate_Hz", mSampleRate_Hz, mSampleRate_Hz);
51
+
52
+ // Greenwood frequency placemap parameters
53
+ // boilerplate--------------------------------| Parameter Name (in file) | Local variable | default value
54
+ Status = theParamFile.GetParameter(SectionName, "DisableNonlinearPath", mDisableNonlinearPath, false);
55
+ Status = theParamFile.GetParameter(SectionName, "A", mA, 165);
56
+ Status = theParamFile.GetParameter(SectionName, "Alpha", mAlpha, 2.1);
57
+ Status = theParamFile.GetParameter(SectionName, "K", mK, 1.0);
58
+ Status = theParamFile.GetParameter(SectionName, "CochleaLength_mm", mCochleaLength_mm, 35.0);
59
+ Status = theParamFile.GetParameter(SectionName, "BMStartPercent", mBMStartPercent, 0.0);
60
+ Status = theParamFile.GetParameter(SectionName, "BMEndPercent", mBMEndPercent, 100.0);
61
+
62
+ Status = theParamFile.GetParameter(SectionName, "ProduceOutputFile", mProduceOutputFile, false);
63
+ Status = theParamFile.GetParameter(SectionName, "BinaryOutput", mBinaryOutput, false);
64
+ Status = theParamFile.GetParameter(SectionName, "CFFileName", mCFFileName, sizeof(mCFFileName), NULL);
65
+ Status = theParamFile.GetParameter(SectionName, "InnerHaircellCouplingFrequency_Hz", InnerHaircellCouplingFrequency_Hz, 20000.0);
66
+
67
+ return 1;
68
+ }
69
+
70
+ int BasilarMembraneNonlinearGammatone::Start(int NumInputs,
71
+ EarlabDataStreamType InputTypes[EarlabMaxIOStreamCount], int InputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions],
72
+ int NumOutputs,
73
+ EarlabDataStreamType OutputTypes[EarlabMaxIOStreamCount], int OutputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions],
74
+ unsigned long OutputElementCounts[EarlabMaxIOStreamCount])
75
+ {
76
+ // Because this module produces data in a "Frequency-Time" format, the following statements apply:
77
+ // OutputSize[i][0] is the number of samples in a frame (the term "samples" includes data for all frequency channels at one time index)
78
+ // OutputSize[i][1] is the number of frequency channels provided
79
+ // OutputSize[i][2] must be 0 to mark the end of the dimension count
80
+
81
+ int i,process_counter;
82
+ double PlacemapStepSize_mm, CurrentPlace_mm, CurrentCF_Hz;
83
+ char MetadataFileName[256];
84
+
85
+ Log(" Start: %s", ModuleName());
86
+ // Perform some validation on my parameters to make sure I can handle the requested input and output streams...
87
+ if (NumInputs != 1)
88
+ throw EarlabException("%s: Currently this module can only handle one input stream. Sorry!", ModuleName());
89
+
90
+ if (NumOutputs != 1)
91
+ throw EarlabException("%s: Currently this module can only handle one output stream. Sorry!", ModuleName());
92
+
93
+ if (InputTypes[0] != WaveformData)
94
+ throw EarlabException("%s: Currently this module can only handle waveform input data streams. Sorry!", ModuleName());
95
+
96
+ if (OutputTypes[0] != WaveformData)
97
+ throw EarlabException("%s: Currently this module can only handle waveform output data streams. Sorry!", ModuleName());
98
+
99
+ if (InputSize[0][0] != OutputSize[0][0])
100
+ throw EarlabException("%s: Input and output frame lengths must be identical. Sorry!", ModuleName());
101
+
102
+ if (InputSize[0][1] != 0)
103
+ throw EarlabException("%s: Input data must be one-dimensional array. Sorry!", ModuleName());
104
+
105
+ if (OutputSize[0][2] != 0)
106
+ throw EarlabException("%s: Output signal must be two-dimensional array. Sorry!", ModuleName());
107
+
108
+ OutputElementCounts[0] = OutputSize[0][0] * OutputSize[0][1];
109
+
110
+ mFrameSize_Samples = OutputSize[0][0];
111
+ mNumChannels = OutputSize[0][1];
112
+
113
+ process_counter = 0;
114
+ /*****************************************************************************/
115
+ /* SET BASILIAR MEMBRANE ARRAYS AND CONSTANTS */
116
+ /*****************************************************************************/
117
+
118
+ mCounter = 0;
119
+ if (mProduceOutputFile)
120
+ {
121
+ #ifdef NOTWINDOWS
122
+ # define WR_BIN "w"
123
+ # define WR_TEXT "w"
124
+ #else
125
+ # define WR_BIN "wb"
126
+ # define WR_TEXT "wt"
127
+ #endif
128
+ if (mBinaryOutput)
129
+ {
130
+ #ifdef _WIN32
131
+ _fmode = _O_BINARY;
132
+ #endif
133
+ mOutputFile = OpenOutputFile(mCFFileName, WR_BIN);
134
+ }
135
+ else
136
+ {
137
+ #ifdef _WIN32
138
+ _fmode = _O_TEXT;
139
+ #endif
140
+ mOutputFile = OpenOutputFile(mCFFileName, WR_TEXT);
141
+ }
142
+
143
+ if (mOutputFile == NULL)
144
+ return 0;
145
+ }
146
+ else
147
+ mOutputFile = NULL;
148
+
149
+ mCFArray_Hz = new double [mNumChannels];
150
+ mDRNL = new LopezPovedaMeddisDualResonanceNonlinear[mNumChannels];
151
+ mCochleaStartPos_mm = mCochleaLength_mm * (mBMStartPercent / 100);
152
+ mCochleaEndPos_mm = mCochleaLength_mm * ( mBMEndPercent / 100);
153
+ mCochleaModeledLength_mm = mCochleaEndPos_mm - mCochleaStartPos_mm;
154
+ PlacemapStepSize_mm = mCochleaModeledLength_mm / (double)mNumChannels;
155
+ mLowpassFilter = new FirstOrderLowpass[mNumChannels];
156
+ for (i = 0; i < mNumChannels; i++)
157
+ {
158
+ mLowpassFilter[i].SetSampleRate_Hz(mSampleRate_Hz);
159
+ mLowpassFilter[i].SetCornerFrequency_Hz(InnerHaircellCouplingFrequency_Hz);
160
+ CurrentPlace_mm = (PlacemapStepSize_mm * i) + mCochleaStartPos_mm;
161
+ CurrentCF_Hz = mA * (pow(10.0, mAlpha * (CurrentPlace_mm / mCochleaLength_mm)) - mK);
162
+ mCFArray_Hz[i] = CurrentCF_Hz;
163
+
164
+ // Initialize the filter for this channel
165
+ mDRNL[i].Init(CurrentCF_Hz, mSampleRate_Hz);
166
+
167
+ if (mOutputFile != NULL)
168
+ {
169
+ if (mBinaryOutput)
170
+ fwrite(&CurrentCF_Hz, sizeof(double), 1, mOutputFile);
171
+ else
172
+ fprintf(mOutputFile, "%g\n", CurrentCF_Hz);
173
+ }
174
+ }
175
+ if (mOutputFile != NULL)
176
+ fclose(mOutputFile);
177
+
178
+ mInputScaleFactor = 1.0 / 3.2e10;
179
+ mOutputScaleFactor = 1.0e9 / (800 * PI);
180
+ sprintf(MetadataFileName, "%s.1.metadata", ModuleName());
181
+ mMetadataFile = new XmlMetadataFile(MetadataFileName);
182
+ mMetadataFile->SetSampleRate_Hz(mSampleRate_Hz);
183
+ mMetadataFile->Add(new XmlParameter("Units", "Membrane displacement (nm)"));
184
+ //mMetadataFile->Add(new XmlParameter("FrameSize", mFrameSize_Samples));
185
+ //mMetadataFile->Add(new XmlParameter("SampleRate_Hz", mSampleRate_Hz));
186
+ mMetadataFile->Add(new XmlDimension("Frequency (Hz)", mNumChannels, mCFArray_Hz));
187
+ mMetadataFile->SetSource(new XmlSource(ModuleName(), "BasilarMembraneNonlinearGammatone_0.1.0.0"));
188
+ mMetadataFile->Write();
189
+ return 1;
190
+ }
191
+
192
+ int BasilarMembraneNonlinearGammatone::Advance(EarlabDataStream *InputStream[EarlabMaxIOStreamCount], EarlabDataStream *OutputStream[EarlabMaxIOStreamCount])
193
+ {
194
+ int i,j;
195
+ double CurInputSample;
196
+ float CurOutputSample;
197
+ FloatMatrixN *Input, *Output;
198
+
199
+ Log(" Advance: %s", ModuleName());
200
+
201
+ Input = ((EarlabWaveformStream *)InputStream[0])->GetData(); // Only supporting one output at the present moment
202
+ Output = ((EarlabWaveformStream *)OutputStream[0])->GetData(); // Only supporting one output at the present moment
203
+
204
+ if (Input->Rank(0) != mFrameSize_Samples)
205
+ throw EarlabException("%s: Input size mismatch with Start()", ModuleName());
206
+ if ((Output->Rank(0) != mFrameSize_Samples) || (Output->Rank(1) != mNumChannels))
207
+ throw EarlabException("%s: Output size mismatch with Start()", ModuleName());
208
+
209
+ for (j = 0; j < mFrameSize_Samples; j++)
210
+ {
211
+ CurInputSample = Input->Data(j) * mInputScaleFactor;
212
+ for (i = 0; i < mNumChannels; i++)
213
+ {
214
+ CurOutputSample = (float)(mLowpassFilter[i].Filter(mDRNL[i].Filter(CurInputSample, mDisableNonlinearPath)) * mOutputScaleFactor);
215
+ mMetadataFile->UpdateMinMax(CurOutputSample);
216
+ Output->Data(j, i) = CurOutputSample;
217
+ }
218
+ mMetadataFile->AddSample();
219
+ }
220
+ return (mFrameSize_Samples * mNumChannels);
221
+ }
222
+
223
+ int BasilarMembraneNonlinearGammatone::Stop(void)
224
+ {
225
+ Log(" Stop: %s", ModuleName());
226
+ mMetadataFile->Write();
227
+ return 1;
228
+ }
229
+
230
+ int BasilarMembraneNonlinearGammatone::Unload(void)
231
+ {
232
+ Log(" Unload: %s", ModuleName());
233
+ return 1;
234
+ }
pool/shard006/C++/0074151_HumanPodController.cpp ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #import "HumanPodController.h"
2
+
3
+ void HumanPodController::Update(float dt)
4
+ {
5
+ super::Update(dt);
6
+
7
+ if (!theController.IsConnected())
8
+ {
9
+ return;
10
+ }
11
+
12
+ float leftTrigger = (theController.GetLeftTrigger() + 32768.0) / (2 * 32768.0);
13
+ float rightTrigger = (theController.GetRightTrigger() + 32768.0) / (2 * 32768.0);
14
+ float leftThrottle = theController.GetLeftThumbVec2().Y;
15
+ float rightThrottle = theController.GetRightThumbVec2().Y;
16
+
17
+ racer->leftEngine->SetLeftFlap(leftTrigger);
18
+ racer->leftEngine->SetRightFlap(rightTrigger);
19
+ racer->rightEngine->SetLeftFlap(leftTrigger);
20
+ racer->rightEngine->SetRightFlap(rightTrigger);
21
+ racer->pod->SetLeftFlap(leftTrigger);
22
+ racer->pod->SetRightFlap(rightTrigger);
23
+
24
+ racer->leftEngine->throttle = leftThrottle;
25
+ racer->rightEngine->throttle = rightThrottle;
26
+ }
pool/shard006/C++/0074156_edittooldlg.cpp ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This file is part of the Code::Blocks IDE and licensed under the GNU Lesser General Public License, version 3
3
+ * http://www.gnu.org/licenses/lgpl-3.0.html
4
+ *
5
+ * $Revision$
6
+ * $Id$
7
+ * $HeadURL$
8
+ */
9
+
10
+ #include "sdk_precomp.h"
11
+
12
+ #ifndef CB_PRECOMP
13
+ #include <wx/button.h>
14
+ #include <wx/checkbox.h>
15
+ #include <wx/intl.h>
16
+ #include <wx/radiobox.h>
17
+ #include <wx/string.h>
18
+ #include <wx/textctrl.h>
19
+ #include <wx/xrc/xmlres.h>
20
+ #include "cbtool.h"
21
+ #include "cbexception.h"
22
+ #include "globals.h"
23
+ #endif
24
+
25
+ #include "edittooldlg.h"
26
+ #include <wx/filedlg.h>
27
+
28
+
29
+ BEGIN_EVENT_TABLE(EditToolDlg, wxScrollingDialog)
30
+ EVT_BUTTON(XRCID("btnBrowseCommand"), EditToolDlg::OnBrowseCommand)
31
+ EVT_BUTTON(XRCID("btnBrowseDir"), EditToolDlg::OnBrowseDir)
32
+ EVT_UPDATE_UI(-1, EditToolDlg::OnUpdateUI)
33
+ END_EVENT_TABLE()
34
+
35
+ EditToolDlg::EditToolDlg(wxWindow* parent, cbTool* tool)
36
+ : m_Tool(tool)
37
+ {
38
+ if (!tool)
39
+ cbThrow(_T("Tool* parameter is mandatory in EditToolDlg()"));
40
+
41
+ wxXmlResource::Get()->LoadObject(this, parent, _T("dlgEditTool"),_T("wxScrollingDialog"));
42
+ XRCCTRL(*this, "txtName", wxTextCtrl)->SetValue(m_Tool->GetName());
43
+ XRCCTRL(*this, "txtCommand", wxTextCtrl)->SetValue(m_Tool->GetCommand());
44
+ XRCCTRL(*this, "txtParams", wxTextCtrl)->SetValue(m_Tool->GetParams());
45
+ XRCCTRL(*this, "txtDir", wxTextCtrl)->SetValue(m_Tool->GetWorkingDir());
46
+ XRCCTRL(*this, "rbLaunchOptions", wxRadioBox)->SetSelection(static_cast<int>(m_Tool->GetLaunchOption()));
47
+ } // end of constructor
48
+
49
+ EditToolDlg::~EditToolDlg()
50
+ {
51
+ //dtor
52
+ }
53
+
54
+ // events
55
+
56
+ void EditToolDlg::OnUpdateUI(cb_unused wxUpdateUIEvent& event)
57
+ {
58
+ const wxString name = XRCCTRL(*this, "txtName", wxTextCtrl)->GetValue();
59
+ const wxString command = XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue();
60
+ bool en = !name.IsEmpty() && !command.IsEmpty();
61
+ XRCCTRL(*this, "wxID_OK", wxButton)->Enable(en);
62
+ } // end of OnUpdateUI
63
+
64
+ void EditToolDlg::OnBrowseCommand(cb_unused wxCommandEvent& event)
65
+ {
66
+ const wxFileName file(XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue());
67
+ wxString filename = wxFileSelector(_("Select executable"), file.GetPath(wxPATH_GET_VOLUME), file.GetFullName());
68
+ if (!filename.IsEmpty())
69
+ XRCCTRL(*this, "txtCommand", wxTextCtrl)->SetValue(filename);
70
+ } // end of OnBrowseCommand
71
+
72
+ void EditToolDlg::OnBrowseDir(cb_unused wxCommandEvent& event)
73
+ {
74
+ const wxString dir = ChooseDirectory(this, _("Select working directory"), XRCCTRL(*this, "txtDir", wxTextCtrl)->GetValue());
75
+ if (!dir.IsEmpty())
76
+ XRCCTRL(*this, "txtDir", wxTextCtrl)->SetValue(dir);
77
+ } // end of OnBrowseDir
78
+
79
+ void EditToolDlg::EndModal(int retCode)
80
+ {
81
+ if (retCode == wxID_OK)
82
+ {
83
+ m_Tool->SetName(XRCCTRL(*this, "txtName", wxTextCtrl)->GetValue());
84
+ m_Tool->SetCommand(XRCCTRL(*this, "txtCommand", wxTextCtrl)->GetValue());
85
+ m_Tool->SetParams(XRCCTRL(*this, "txtParams", wxTextCtrl)->GetValue());
86
+ m_Tool->SetWorkingDir(XRCCTRL(*this, "txtDir", wxTextCtrl)->GetValue());
87
+ m_Tool->SetLaunchOption(static_cast<cbTool::eLaunchOption>(XRCCTRL(*this, "rbLaunchOptions", wxRadioBox)->GetSelection()));
88
+ }
89
+
90
+ wxScrollingDialog::EndModal(retCode);
91
+ } // end of EndModal
pool/shard006/C++/0074157_mediainfo.cpp ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "mediainfo.h"
2
+ #include "qdebug.h"
3
+
4
+ MediaInfo::MediaInfo(QString filepath, bool onlyTags) {
5
+ readed = false;
6
+ fileName = filepath.toStdWString();
7
+ TagLib::FileRef f(fileName.c_str(), !onlyTags, onlyTags ? TagLib::AudioProperties::Fast : TagLib::AudioProperties::Accurate);
8
+
9
+ if (!f.isNull()) {
10
+ size = f.file() -> length();
11
+ readed = true;
12
+ artist = QString::fromStdWString(f.tag() -> artist().toWString());
13
+ title = QString::fromStdWString(f.tag() -> title().toWString());
14
+ album = QString::fromStdWString(f.tag() -> album().toWString());
15
+ genre = QString::fromStdWString(f.tag() -> genre().toWString());
16
+ year = f.tag() -> year();
17
+ track = f.tag() -> track();
18
+
19
+ if (!onlyTags)
20
+ readInfo(f);
21
+ }
22
+ }
23
+
24
+ void MediaInfo::initInfo() {
25
+ TagLib::FileRef f(fileName.c_str(), true, TagLib::AudioProperties::Accurate);
26
+ readInfo(f);
27
+ }
28
+
29
+ void MediaInfo::readInfo(TagLib::FileRef f) {
30
+ bitrate = f.audioProperties() -> bitrate();
31
+ channels = f.audioProperties() -> channels();
32
+ duration = f.audioProperties() -> length();
33
+ sampleRate = f.audioProperties() -> sampleRate();
34
+ }
35
+
36
+ bool MediaInfo::initiated() const {
37
+ return readed;
38
+ }
39
+
40
+ QString MediaInfo::getArtist() const { return artist; }
41
+ QString MediaInfo::getTitle() const { return title; }
42
+ QString MediaInfo::getAlbum() const { return album; }
43
+ QString MediaInfo::getGenre() const { return genre; }
44
+
45
+ long MediaInfo::getSize() const { return size; }
46
+ int MediaInfo::getYear() const { return year; }
47
+ int MediaInfo::getTrack() const { return track; }
48
+ int MediaInfo::getChannels() const { return channels; }
49
+ int MediaInfo::getBitrate() const { return bitrate; }
50
+ int MediaInfo::getDuration() const { return duration; }
51
+ int MediaInfo::getSampleRate() const { return sampleRate; }
pool/shard006/C++/0074164_wld_mode_setpoint.cpp ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Platformer Game Engine by Wohlstand, a free platform for game making
3
+ * Copyright (c) 2014-2021 Vitaly Novichkov <admin@wohlnet.ru>
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
+ * 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 <common_features/main_window_ptr.h>
20
+ #include <common_features/themes.h>
21
+ #include <main_window/dock/wld_item_props.h>
22
+
23
+ #include "../wld_scene.h"
24
+ #include "../wld_item_placing.h"
25
+ #include "wld_mode_setpoint.h"
26
+
27
+ WLD_ModeSetPoint::WLD_ModeSetPoint(QGraphicsScene *parentScene, QObject *parent)
28
+ : EditMode("SetPoint", parentScene, parent)
29
+ {}
30
+
31
+ WLD_ModeSetPoint::~WLD_ModeSetPoint()
32
+ {}
33
+
34
+ void WLD_ModeSetPoint::set()
35
+ {
36
+ if(!scene) return;
37
+ WldScene *s = dynamic_cast<WldScene *>(scene);
38
+
39
+ s->resetResizers();
40
+
41
+ s->m_eraserIsEnabled = false;
42
+ s->m_pastingMode = false;
43
+ s->m_busyMode = true;
44
+ s->m_disableMoveItems = false;
45
+
46
+ s->m_viewPort->setInteractive(true);
47
+ s->m_viewPort->setCursor(Themes::Cursor(Themes::cursor_placing));
48
+ s->m_viewPort->setDragMode(QGraphicsView::NoDrag);
49
+ s->m_viewPort->setRenderHint(QPainter::Antialiasing, true);
50
+ s->m_viewPort->viewport()->setMouseTracking(true);
51
+ }
52
+
53
+ void WLD_ModeSetPoint::mousePress(QGraphicsSceneMouseEvent *mouseEvent)
54
+ {
55
+ if(!scene) return;
56
+ WldScene *s = dynamic_cast<WldScene *>(scene);
57
+ Q_ASSERT(s);
58
+
59
+ if((!s->m_isSelectionDialog) && ((mouseEvent->buttons() & Qt::RightButton) != 0))
60
+ {
61
+ MainWinConnect::pMainWin->on_actionSelect_triggered();
62
+ dontCallEvent = true;
63
+ s->m_mouseIsMovedAfterKey = true;
64
+ return;
65
+ }
66
+
67
+ if(!(mouseEvent->buttons() & Qt::LeftButton)) // Deny any other mouse buttons
68
+ return;
69
+
70
+ if(s->m_cursorItemImg)
71
+ {
72
+ s->m_cursorItemImg->setPos(QPointF(s->applyGrid(mouseEvent->scenePos().toPoint() -
73
+ QPoint(WldPlacingItems::c_offset_x,
74
+ WldPlacingItems::c_offset_y),
75
+ WldPlacingItems::gridSz,
76
+ WldPlacingItems::gridOffset)));
77
+ s->m_pointSelector.setPoint(s->m_cursorItemImg->scenePos().toPoint());
78
+ emit s->m_pointSelector.pointSelected(s->m_pointSelector.m_pointCoord);
79
+ }
80
+ dontCallEvent = true;
81
+ }
82
+
83
+ void WLD_ModeSetPoint::mouseMove(QGraphicsSceneMouseEvent *mouseEvent)
84
+ {
85
+ if(!scene) return;
86
+ WldScene *s = dynamic_cast<WldScene *>(scene);
87
+
88
+ if(s->m_cursorItemImg)
89
+ {
90
+
91
+ s->m_cursorItemImg->setPos(QPointF(s->applyGrid(mouseEvent->scenePos().toPoint() -
92
+ QPoint(WldPlacingItems::c_offset_x,
93
+ WldPlacingItems::c_offset_y),
94
+ WldPlacingItems::gridSz,
95
+ WldPlacingItems::gridOffset)));
96
+ s->m_cursorItemImg->show();
97
+
98
+ s->setMessageBoxItem(true, mouseEvent->scenePos(),
99
+ (s->m_cursorItemImg ?
100
+ (
101
+ QString::number(s->m_cursorItemImg->scenePos().toPoint().x()) + "x" +
102
+ QString::number(s->m_cursorItemImg->scenePos().toPoint().y())
103
+ )
104
+ : ""));
105
+
106
+ }
107
+ }
108
+
109
+ void WLD_ModeSetPoint::mouseRelease(QGraphicsSceneMouseEvent *)
110
+ {
111
+ if(!scene) return;
112
+ WldScene *s = dynamic_cast<WldScene *>(scene);
113
+
114
+ if(!s->m_isSelectionDialog)
115
+ {
116
+ MainWinConnect::pMainWin->on_actionSelect_triggered();
117
+ MainWinConnect::pMainWin->dock_WldItemProps->acceptWarpToCoordinates(s->m_pointSelector.m_pointCoord);
118
+ s->openProps();
119
+ //s->MouseReleaseEventOnly = true;
120
+ //s->mouseReleaseEvent(mouseEvent);
121
+ dontCallEvent = true;
122
+ }
123
+
124
+ }
125
+
126
+ void WLD_ModeSetPoint::keyPress(QKeyEvent *keyEvent)
127
+ {
128
+ Q_UNUSED(keyEvent)
129
+ }
130
+
131
+ void WLD_ModeSetPoint::keyRelease(QKeyEvent *keyEvent)
132
+ {
133
+ if(!scene) return;
134
+ WldScene *s = dynamic_cast<WldScene *>(scene);
135
+
136
+ switch(keyEvent->key())
137
+ {
138
+ case(Qt::Key_Escape):
139
+ if(s->m_isSelectionDialog) break; //Disable this key in the point selection dialog
140
+ MainWinConnect::pMainWin->on_actionSelect_triggered();
141
+ break;
142
+ default:
143
+ break;
144
+ }
145
+ }
146
+
pool/shard006/C++/0074166_force_mic_volume_max.cc ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2013 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
+ // This utility will portably force the volume of the default microphone to max.
12
+
13
+ #include <stdio.h>
14
+
15
+ #include "webrtc/base/scoped_ptr.h"
16
+ #include "webrtc/test/channel_transport/channel_transport.h"
17
+ #include "webrtc/voice_engine/include/voe_audio_processing.h"
18
+ #include "webrtc/voice_engine/include/voe_base.h"
19
+ #include "webrtc/voice_engine/include/voe_volume_control.h"
20
+
21
+ int main(int argc, char** argv) {
22
+ webrtc::VoiceEngine* voe = webrtc::VoiceEngine::Create();
23
+ if (voe == NULL) {
24
+ fprintf(stderr, "Failed to initialize voice engine.\n");
25
+ return 1;
26
+ }
27
+
28
+ webrtc::VoEBase* base = webrtc::VoEBase::GetInterface(voe);
29
+ webrtc::VoEVolumeControl* volume_control =
30
+ webrtc::VoEVolumeControl::GetInterface(voe);
31
+
32
+ if (base->Init() != 0) {
33
+ fprintf(stderr, "Failed to initialize voice engine base.\n");
34
+ return 1;
35
+ }
36
+ // Set to 0 first in case the mic is above 100%.
37
+ if (volume_control->SetMicVolume(0) != 0) {
38
+ fprintf(stderr, "Failed set volume to 0.\n");
39
+ return 1;
40
+ }
41
+ if (volume_control->SetMicVolume(255) != 0) {
42
+ fprintf(stderr, "Failed set volume to 255.\n");
43
+ return 1;
44
+ }
45
+
46
+ return 0;
47
+ }
pool/shard006/C++/0074168_DispalyingVideo.cpp ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <opencv2\highgui\highgui.hpp>
2
+
3
+ int main()
4
+ {
5
+ cvNamedWindow("Video Display", CV_WINDOW_AUTOSIZE);
6
+ CvCapture * capture = cvCreateFileCapture("C:\\Users\\sigit_000\\Downloads\\Video\\Opening a Video with Visual Studio 2013 and OpenCV 2.4.10.mp4");
7
+ IplImage* frame;
8
+ while (true)
9
+ {
10
+ frame = cvQueryFrame(capture);
11
+ if (!frame)
12
+ break;
13
+ cvShowImage("Video Display", frame);
14
+ char c = cvWaitKey(20);
15
+ if (c == 27)
16
+ break;
17
+ }
18
+ cvReleaseCapture(&capture);
19
+ //cvDestroyWindow()
20
+
21
+ return 0;
22
+ }
pool/shard006/C++/0074173_UnionTypesModules.cpp ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
6
+
7
+ #include "config.h"
8
+ #include "bindings/modules/v8/UnionTypesModules.h"
9
+
10
+
11
+ namespace blink {
12
+
13
+ BooleanOrString::BooleanOrString()
14
+ : m_type(SpecificTypeNone)
15
+ {
16
+ }
17
+
18
+ bool BooleanOrString::getAsBoolean() const
19
+ {
20
+ ASSERT(isBoolean());
21
+ return m_boolean;
22
+ }
23
+
24
+ void BooleanOrString::setBoolean(bool value)
25
+ {
26
+ ASSERT(isNull());
27
+ m_boolean = value;
28
+ m_type = SpecificTypeBoolean;
29
+ }
30
+
31
+ String BooleanOrString::getAsString() const
32
+ {
33
+ ASSERT(isString());
34
+ return m_string;
35
+ }
36
+
37
+ void BooleanOrString::setString(String value)
38
+ {
39
+ ASSERT(isNull());
40
+ m_string = value;
41
+ m_type = SpecificTypeString;
42
+ }
43
+
44
+ void V8BooleanOrString::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, BooleanOrString& impl, ExceptionState& exceptionState)
45
+ {
46
+ if (v8Value.IsEmpty())
47
+ return;
48
+
49
+ if (v8Value->IsBoolean()) {
50
+ impl.setBoolean(v8Value->ToBoolean()->Value());
51
+ return;
52
+ }
53
+
54
+ {
55
+ TOSTRING_VOID_EXCEPTIONSTATE(V8StringResource<>, cppValue, v8Value, exceptionState);
56
+ impl.setString(cppValue);
57
+ return;
58
+ }
59
+
60
+ }
61
+
62
+ v8::Local<v8::Value> toV8(const BooleanOrString& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate)
63
+ {
64
+ switch (impl.m_type) {
65
+ case BooleanOrString::SpecificTypeNone:
66
+ return v8::Null(isolate);
67
+ case BooleanOrString::SpecificTypeBoolean:
68
+ return v8Boolean(impl.getAsBoolean(), isolate);
69
+ case BooleanOrString::SpecificTypeString:
70
+ return v8String(isolate, impl.getAsString());
71
+ default:
72
+ ASSERT_NOT_REACHED();
73
+ }
74
+ return v8::Local<v8::Value>();
75
+ }
76
+
77
+ BooleanOrString NativeValueTraits<BooleanOrString>::nativeValue(const v8::Local<v8::Value>& value, v8::Isolate* isolate, ExceptionState& exceptionState)
78
+ {
79
+ BooleanOrString impl;
80
+ V8BooleanOrString::toImpl(isolate, value, impl, exceptionState);
81
+ return impl;
82
+ }
83
+
84
+ } // namespace blink
pool/shard006/C++/0074174_AP_Parachute.cpp ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "AP_Parachute.h"
2
+ #include <AP_Relay/AP_Relay.h>
3
+ #include <AP_Math/AP_Math.h>
4
+ #include <RC_Channel/RC_Channel.h>
5
+ #include <SRV_Channel/SRV_Channel.h>
6
+ #include <AP_Notify/AP_Notify.h>
7
+ #include <AP_HAL/AP_HAL.h>
8
+ #include <AP_Logger/AP_Logger.h>
9
+ #include <GCS_MAVLink/GCS.h>
10
+
11
+ extern const AP_HAL::HAL& hal;
12
+
13
+ const AP_Param::GroupInfo AP_Parachute::var_info[] = {
14
+
15
+ // @Param: ENABLED
16
+ // @DisplayName: Parachute release enabled or disabled
17
+ // @Description: Parachute release enabled or disabled
18
+ // @Values: 0:Disabled,1:Enabled
19
+ // @User: Standard
20
+ AP_GROUPINFO_FLAGS("ENABLED", 0, AP_Parachute, _enabled, 0, AP_PARAM_FLAG_ENABLE),
21
+
22
+ // @Param: TYPE
23
+ // @DisplayName: Parachute release mechanism type (relay or servo)
24
+ // @Description: Parachute release mechanism type (relay or servo)
25
+ // @Values: 0:First Relay,1:Second Relay,2:Third Relay,3:Fourth Relay,10:Servo
26
+ // @User: Standard
27
+ AP_GROUPINFO("TYPE", 1, AP_Parachute, _release_type, AP_PARACHUTE_TRIGGER_TYPE_RELAY_0),
28
+
29
+ // @Param: SERVO_ON
30
+ // @DisplayName: Parachute Servo ON PWM value
31
+ // @Description: Parachute Servo PWM value in microseconds when parachute is released
32
+ // @Range: 1000 2000
33
+ // @Units: PWM
34
+ // @Increment: 1
35
+ // @User: Standard
36
+ AP_GROUPINFO("SERVO_ON", 2, AP_Parachute, _servo_on_pwm, AP_PARACHUTE_SERVO_ON_PWM_DEFAULT),
37
+
38
+ // @Param: SERVO_OFF
39
+ // @DisplayName: Servo OFF PWM value
40
+ // @Description: Parachute Servo PWM value in microseconds when parachute is not released
41
+ // @Range: 1000 2000
42
+ // @Units: PWM
43
+ // @Increment: 1
44
+ // @User: Standard
45
+ AP_GROUPINFO("SERVO_OFF", 3, AP_Parachute, _servo_off_pwm, AP_PARACHUTE_SERVO_OFF_PWM_DEFAULT),
46
+
47
+ // @Param: ALT_MIN
48
+ // @DisplayName: Parachute min altitude in meters above home
49
+ // @Description: Parachute min altitude above home. Parachute will not be released below this altitude. 0 to disable alt check.
50
+ // @Range: 0 32000
51
+ // @Units: m
52
+ // @Increment: 1
53
+ // @User: Standard
54
+ AP_GROUPINFO("ALT_MIN", 4, AP_Parachute, _alt_min, AP_PARACHUTE_ALT_MIN_DEFAULT),
55
+
56
+ // @Param: DELAY_MS
57
+ // @DisplayName: Parachute release delay
58
+ // @Description: Delay in millseconds between motor stop and chute release
59
+ // @Range: 0 5000
60
+ // @Units: ms
61
+ // @Increment: 1
62
+ // @User: Standard
63
+ AP_GROUPINFO("DELAY_MS", 5, AP_Parachute, _delay_ms, AP_PARACHUTE_RELEASE_DELAY_MS),
64
+
65
+ AP_GROUPEND
66
+ };
67
+
68
+ /// enabled - enable or disable parachute release
69
+ void AP_Parachute::enabled(bool on_off)
70
+ {
71
+ _enabled = on_off;
72
+
73
+ // clear release_time
74
+ _release_time = 0;
75
+
76
+ AP::logger().Write_Event(_enabled ? DATA_PARACHUTE_ENABLED : DATA_PARACHUTE_DISABLED);
77
+ }
78
+
79
+ /// release - release parachute
80
+ void AP_Parachute::release()
81
+ {
82
+ // exit immediately if not enabled
83
+ if (_enabled <= 0) {
84
+ return;
85
+ }
86
+
87
+ gcs().send_text(MAV_SEVERITY_INFO,"Parachute: Released");
88
+ AP::logger().Write_Event(DATA_PARACHUTE_RELEASED);
89
+
90
+ // set release time to current system time
91
+ if (_release_time == 0) {
92
+ _release_time = AP_HAL::millis();
93
+ }
94
+
95
+ _release_initiated = true;
96
+
97
+ // update AP_Notify
98
+ AP_Notify::flags.parachute_release = 1;
99
+ }
100
+
101
+ /// update - shuts off the trigger should be called at about 10hz
102
+ void AP_Parachute::update()
103
+ {
104
+ // exit immediately if not enabled or parachute not to be released
105
+ if (_enabled <= 0) {
106
+ return;
107
+ }
108
+
109
+ // calc time since release
110
+ uint32_t time_diff = AP_HAL::millis() - _release_time;
111
+ uint32_t delay_ms = _delay_ms<=0 ? 0: (uint32_t)_delay_ms;
112
+
113
+ // check if we should release parachute
114
+ if ((_release_time != 0) && !_release_in_progress) {
115
+ if (time_diff >= delay_ms) {
116
+ if (_release_type == AP_PARACHUTE_TRIGGER_TYPE_SERVO) {
117
+ // move servo
118
+ SRV_Channels::set_output_pwm(SRV_Channel::k_parachute_release, _servo_on_pwm);
119
+ }else if (_release_type <= AP_PARACHUTE_TRIGGER_TYPE_RELAY_3) {
120
+ // set relay
121
+ _relay.on(_release_type);
122
+ }
123
+ _release_in_progress = true;
124
+ _released = true;
125
+ }
126
+ }else if ((_release_time == 0) || time_diff >= delay_ms + AP_PARACHUTE_RELEASE_DURATION_MS) {
127
+ if (_release_type == AP_PARACHUTE_TRIGGER_TYPE_SERVO) {
128
+ // move servo back to off position
129
+ SRV_Channels::set_output_pwm(SRV_Channel::k_parachute_release, _servo_off_pwm);
130
+ }else if (_release_type <= AP_PARACHUTE_TRIGGER_TYPE_RELAY_3) {
131
+ // set relay back to zero volts
132
+ _relay.off(_release_type);
133
+ }
134
+ // reset released flag and release_time
135
+ _release_in_progress = false;
136
+ _release_time = 0;
137
+ // update AP_Notify
138
+ AP_Notify::flags.parachute_release = 0;
139
+ }
140
+ }
141
+
142
+ // singleton instance
143
+ AP_Parachute *AP_Parachute::_singleton;
144
+
145
+ namespace AP {
146
+
147
+ AP_Parachute *parachute()
148
+ {
149
+ return AP_Parachute::get_singleton();
150
+ }
151
+
152
+ }
pool/shard006/C++/0074176_bosh_example.cpp ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2004-2014 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 "../messagesessionhandler.h"
15
+ #include "../messageeventhandler.h"
16
+ #include "../messageeventfilter.h"
17
+ #include "../chatstatehandler.h"
18
+ #include "../chatstatefilter.h"
19
+ #include "../connectionlistener.h"
20
+ #include "../disco.h"
21
+ #include "../message.h"
22
+ #include "../gloox.h"
23
+ #include "../lastactivity.h"
24
+ #include "../loghandler.h"
25
+ #include "../logsink.h"
26
+ #include "../connectiontcpclient.h"
27
+ #include "../connectionsocks5proxy.h"
28
+ #include "../messagehandler.h"
29
+ #include "../connectionbosh.h"
30
+ #include "../connectionhttpproxy.h"
31
+
32
+ using namespace gloox;
33
+
34
+ #include <unistd.h>
35
+ #include <stdio.h>
36
+ #include <string>
37
+
38
+ #include <cstdio> // [s]print[f]
39
+
40
+ #if defined( WIN32 ) || defined( _WIN32 )
41
+ # include <windows.h>
42
+ #endif
43
+
44
+ class MessageTest : public MessageSessionHandler, ConnectionListener, LogHandler,
45
+ MessageEventHandler, MessageHandler, ChatStateHandler
46
+ {
47
+ public:
48
+ MessageTest() : m_session( 0 ), m_messageEventFilter( 0 ), m_chatStateFilter( 0 ) {}
49
+
50
+ virtual ~MessageTest() {}
51
+
52
+ void start()
53
+ {
54
+
55
+ JID jid( "js@example.net/bosh" );
56
+ j = new Client( jid, "test" );
57
+ j->registerConnectionListener( this );
58
+ j->registerMessageSessionHandler( this, 0 );
59
+ j->disco()->setIdentity( "client", "bot" );
60
+ j->disco()->addFeature( XMLNS_CHAT_STATES );
61
+ j->setCompression(false);
62
+ //StringList ca;
63
+ //ca.push_back( "/path/to/cacert.crt" );
64
+ //j->setCACerts( ca );
65
+
66
+ j->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this );
67
+
68
+
69
+ /*
70
+ ConnectionTCPClient* conn0 = new ConnectionTCPClient( j->logInstance(), "example.net", 8081 );
71
+ ConnectionHTTPProxy* conn1 = new ConnectionHTTPProxy( conn0, j->logInstance(), "foo", 8080 );
72
+ ConnectionBOSH* conn2 = new ConnectionBOSH( j, conn1, j->logInstance(), "camaya.net", "camaya.net" );
73
+ conn2->setMode( ConnectionBOSH::ModeLegacyHTTP );
74
+ // conn2->setMode( ConnectionBOSH::ModePersistentHTTP );
75
+ j->setConnectionImpl( conn2 );
76
+ */
77
+
78
+ // this code connects to a jabber server through a BOSH connection...
79
+ ConnectionTCPClient* conn0 = new ConnectionTCPClient( j->logInstance(), "example.net", 8080 );
80
+ ConnectionBOSH* conn1 = new ConnectionBOSH( j, conn0, j->logInstance(), "example.net", "example.net" );
81
+ // conn1->setMode( ConnectionBOSH::ModeLegacyHTTP );
82
+ // conn1->setMode( ConnectionBOSH::ModePersistentHTTP );
83
+ j->setConnectionImpl( conn1 );
84
+
85
+ j->setForceNonSasl( true );
86
+
87
+
88
+
89
+
90
+ if( j->connect( false ) )
91
+ {
92
+ ConnectionError ce = ConnNoError;
93
+ while( ce == ConnNoError )
94
+ {
95
+ ce = j->recv();
96
+ }
97
+ printf( "ce: %d\n", ce );
98
+ }
99
+
100
+ delete( j );
101
+ }
102
+
103
+ virtual void onConnect()
104
+ {
105
+ printf( "connected!!!\n" );
106
+ }
107
+
108
+ virtual void onDisconnect( ConnectionError e )
109
+ {
110
+ printf( "message_test: disconnected: %d\n", e );
111
+ if( e == ConnAuthenticationFailed )
112
+ printf( "auth failed. reason: %d\n", j->authError() );
113
+ }
114
+
115
+ virtual bool onTLSConnect( const CertInfo& info )
116
+ {
117
+ time_t from( info.date_from );
118
+ time_t to( info.date_to );
119
+
120
+ printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
121
+ "from: %s\nto: %s\n",
122
+ info.status, info.issuer.c_str(), info.server.c_str(),
123
+ info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
124
+ info.compression.c_str(), ctime( &from ), ctime( &to ) );
125
+ return true;
126
+ }
127
+
128
+ virtual void handleMessage( const Message& msg, MessageSession * /*session*/ )
129
+ {
130
+ printf( "type: %d, subject: %s, message: %s, thread id: %s\n", msg.subtype(),
131
+ msg.subject().c_str(), msg.body().c_str(), msg.thread().c_str() );
132
+
133
+ std::string re = "You said:\n> " + msg.body() + "\nI like that statement.";
134
+ std::string sub;
135
+ if( !msg.subject().empty() )
136
+ sub = "Re: " + msg.subject();
137
+
138
+ m_messageEventFilter->raiseMessageEvent( MessageEventDisplayed );
139
+ m_messageEventFilter->raiseMessageEvent( MessageEventComposing );
140
+ m_chatStateFilter->setChatState( ChatStateComposing );
141
+ m_session->send( re, sub );
142
+
143
+ if( msg.body() == "quit" )
144
+ j->disconnect();
145
+ }
146
+
147
+ virtual void handleMessageEvent( const JID& from, MessageEventType event )
148
+ {
149
+ printf( "received event: %d from: %s\n", event, from.full().c_str() );
150
+ }
151
+
152
+ virtual void handleChatState( const JID& from, ChatStateType state )
153
+ {
154
+ printf( "received state: %d from: %s\n", state, from.full().c_str() );
155
+ }
156
+
157
+ virtual void handleMessageSession( MessageSession *session )
158
+ {
159
+ printf( "got new session\n");
160
+ // this example can handle only one session. so we get rid of the old session
161
+ j->disposeMessageSession( m_session );
162
+ m_session = session;
163
+ m_session->registerMessageHandler( this );
164
+ m_messageEventFilter = new MessageEventFilter( m_session );
165
+ m_messageEventFilter->registerMessageEventHandler( this );
166
+ m_chatStateFilter = new ChatStateFilter( m_session );
167
+ m_chatStateFilter->registerChatStateHandler( this );
168
+ }
169
+
170
+ virtual void handleLog( LogLevel level, LogArea area, const std::string& message )
171
+ {
172
+ printf("%d: ", int( time( 0 ) ) );
173
+ switch(area)
174
+ {
175
+ case LogAreaXmlIncoming:
176
+ printf("Received XML: ");
177
+ break;
178
+ case LogAreaXmlOutgoing:
179
+ printf("Sent XML: ");
180
+ break;
181
+ case LogAreaClassConnectionBOSH:
182
+ printf("BOSH: ");
183
+ break;
184
+ default:
185
+ printf("log: level: %d, area: %d, ", level, area);
186
+ }
187
+ printf("%s\n", message.c_str() );
188
+ }
189
+
190
+ private:
191
+ Client *j;
192
+ MessageSession *m_session;
193
+ MessageEventFilter *m_messageEventFilter;
194
+ ChatStateFilter *m_chatStateFilter;
195
+ };
196
+
197
+ int main( int /*argc*/, char** /*argv*/ )
198
+ {
199
+ MessageTest *r = new MessageTest();
200
+ r->start();
201
+ delete( r );
202
+ return 0;
203
+ }
pool/shard006/C++/0074177_EdgeIntersectionList.cpp ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**********************************************************************
2
+ * $Id$
3
+ *
4
+ * GEOS - Geometry Engine Open Source
5
+ * http://geos.refractions.net
6
+ *
7
+ * Copyright (C) 2001-2002 Vivid Solutions Inc.
8
+ *
9
+ * This is free software; you can redistribute and/or modify it under
10
+ * the terms of the GNU Lesser General Public Licence as published
11
+ * by the Free Software Foundation.
12
+ * See the COPYING file for more information.
13
+ *
14
+ **********************************************************************/
15
+
16
+ #include <geos/geomgraph.h>
17
+
18
+ #ifndef DEBUG
19
+ #define DEBUG 0
20
+ #endif
21
+
22
+ namespace geos {
23
+
24
+ EdgeIntersectionList::EdgeIntersectionList(Edge *newEdge)
25
+ {
26
+ list=new vector<EdgeIntersection*>();
27
+ edge=newEdge;
28
+ }
29
+
30
+ EdgeIntersectionList::~EdgeIntersectionList()
31
+ {
32
+ // delete edge;
33
+ for(int i=0;i<(int)list->size();i++) {
34
+ delete (*list)[i];
35
+ }
36
+ delete list;
37
+ }
38
+
39
+ EdgeIntersection*
40
+ EdgeIntersectionList::add(const Coordinate& coord, int segmentIndex, double dist)
41
+ {
42
+ #if DEBUG
43
+ cerr<<"["<<this<<"] EdgeIntersectionList::add("<<coord.toString()<<","<<segmentIndex<<","<<dist<<")"<<endl;
44
+ #endif // DEBUG
45
+ vector<EdgeIntersection *>::iterator insertIt=list->begin();
46
+ bool isInList=findInsertionPoint(segmentIndex,dist,&insertIt);
47
+ EdgeIntersection *ei;
48
+ if (!isInList)
49
+ {
50
+ #if DEBUG
51
+ cerr<<" intersection not in list"<<endl;
52
+ #endif // DEBUG
53
+ ei=new EdgeIntersection(coord,segmentIndex,dist);
54
+ list->insert(insertIt,ei);
55
+ }
56
+ else
57
+ {
58
+ ei=*insertIt;
59
+ #if DEBUG
60
+ cerr<<" intersection already in list (should merge z)"<<endl;
61
+ cerr<<" current: "<<ei->coord.toString()<<endl;
62
+ cerr<<" intersection: "<<coord.toString()<<endl;
63
+ #endif // DEBUG
64
+ }
65
+ return ei;
66
+ }
67
+
68
+ vector<EdgeIntersection*>::iterator
69
+ EdgeIntersectionList::iterator()
70
+ {
71
+ return list->begin();
72
+ }
73
+
74
+ bool
75
+ EdgeIntersectionList::isEmpty()
76
+ {
77
+ return list->empty();
78
+ }
79
+
80
+ bool
81
+ EdgeIntersectionList::findInsertionPoint(int segmentIndex, double dist,vector<EdgeIntersection*>::iterator *insertIt)
82
+ {
83
+ vector<EdgeIntersection *>::iterator findIt=list->begin();
84
+ //bool found=false;
85
+ while(findIt<list->end()) {
86
+ EdgeIntersection *ei=*findIt;
87
+ findIt++;
88
+ int compare=ei->compare(segmentIndex, dist);
89
+ // intersection found - insertIt.next() will retrieve it
90
+ if (compare==0) return true;
91
+ // this ei is past the intersection location, so intersection was not found
92
+ if (compare>0) return false;
93
+ // this ei was before the intersection point, so move to next
94
+ (*insertIt)++;
95
+ }
96
+ return false;
97
+ }
98
+
99
+ bool
100
+ EdgeIntersectionList::isIntersection(const Coordinate& pt)
101
+ {
102
+ vector<EdgeIntersection *>::iterator it;
103
+ for (it=list->begin();it<list->end();it++) {
104
+ EdgeIntersection *ei=*it;
105
+ if (ei->coord==pt)
106
+ return true;
107
+ }
108
+ return false;
109
+ }
110
+
111
+ void
112
+ EdgeIntersectionList::addEndpoints()
113
+ {
114
+ int maxSegIndex=edge->pts->getSize()-1;
115
+ add(edge->pts->getAt(0), 0, 0.0);
116
+ add(edge->pts->getAt(maxSegIndex), maxSegIndex, 0.0);
117
+ }
118
+
119
+ void
120
+ EdgeIntersectionList::addSplitEdges(vector<Edge*> *edgeList)
121
+ {
122
+ // ensure that the list has entries for the first and last point
123
+ // of the edge
124
+ addEndpoints();
125
+ vector<EdgeIntersection *>::iterator it=list->begin();
126
+ // there should always be at least two entries in the list
127
+ EdgeIntersection *eiPrev=*it;
128
+ it++;
129
+ while (it<list->end()) {
130
+ EdgeIntersection *ei=*it;
131
+ Edge *newEdge=createSplitEdge(eiPrev,ei);
132
+ edgeList->push_back(newEdge);
133
+ eiPrev=ei;
134
+ it++;
135
+ }
136
+ }
137
+
138
+ Edge*
139
+ EdgeIntersectionList::createSplitEdge(EdgeIntersection *ei0, EdgeIntersection *ei1)
140
+ {
141
+ #if DEBUG
142
+ cerr<<"["<<this<<"] EdgeIntersectionList::createSplitEdge()"<<endl;
143
+ #endif // DEBUG
144
+ int npts=ei1->segmentIndex-ei0->segmentIndex+2;
145
+ #if DEBUG
146
+ cerr<<" npts:"<<npts<<endl;
147
+ #endif // DEBUG
148
+
149
+ const Coordinate& lastSegStartPt=edge->pts->getAt(ei1->segmentIndex);
150
+
151
+ // if the last intersection point is not equal to the its segment
152
+ // start pt, add it to the points list as well.
153
+ // (This check is needed because the distance metric is not totally
154
+ // reliable!). The check for point equality is 2D only - Z values
155
+ // are ignored
156
+ bool useIntPt1=ei1->dist>0.0 || !ei1->coord.equals2D(lastSegStartPt);
157
+ if (!useIntPt1) {
158
+ npts--;
159
+ #if DEBUG
160
+ cerr<<" !useIntPt1 (npts:"<<npts<<")"<<endl;
161
+ #endif // DEBUG
162
+ }
163
+ CoordinateSequence* pts=new DefaultCoordinateSequence(npts);
164
+ int ipt=0;
165
+ //Coordinate *c=new Coordinate(ei0->coord);
166
+ //pts->setAt(*c,ipt++);
167
+ //delete c;
168
+ pts->setAt(ei0->coord,ipt++);
169
+ #if DEBUG
170
+ cerr<<" pt"<<(ipt-1)<<": "<<pts->getAt(ipt-1).toString()<<endl;
171
+ #endif // DEBUG
172
+ for(int i=ei0->segmentIndex+1; i<=ei1->segmentIndex;i++)
173
+ {
174
+ if ( ! useIntPt1 && ei1->segmentIndex == i )
175
+ {
176
+ pts->setAt(ei1->coord, ipt++);
177
+ }
178
+ else
179
+ {
180
+ pts->setAt(edge->pts->getAt(i),ipt++);
181
+ }
182
+ #if DEBUG
183
+ cerr<<" pt"<<(ipt-1)<<": "<<pts->getAt(ipt-1).toString()<<endl;
184
+ #endif // DEBUG
185
+ }
186
+ if (useIntPt1)
187
+ {
188
+ pts->setAt(ei1->coord,ipt);
189
+ #if DEBUG
190
+ cerr<<" ustIntPt1: pt"<<(ipt-1)<<": "<<pts->getAt(ipt-1).toString()<<endl;
191
+ #endif // DEBUG
192
+ }
193
+ return new Edge(pts, new Label(edge->getLabel()));
194
+ }
195
+
196
+ string
197
+ EdgeIntersectionList::print()
198
+ {
199
+ string out="Intersections: ";
200
+ vector<EdgeIntersection *>::iterator it;
201
+ for (it=list->begin();it<list->end();it++) {
202
+ EdgeIntersection *ei=*it;
203
+ out+=ei->print();
204
+ }
205
+ return out;
206
+ }
207
+
208
+ } // namespace
209
+
210
+ /**********************************************************************
211
+ * $Log$
212
+ * Revision 1.10 2004/12/08 13:54:43 strk
213
+ * gcc warnings checked and fixed, general cleanups.
214
+ *
215
+ * Revision 1.9 2004/11/23 19:53:06 strk
216
+ * Had LineIntersector compute Z by interpolation.
217
+ *
218
+ * Revision 1.8 2004/11/22 13:02:12 strk
219
+ * Forced use if computed intersection point in ::createSplitEdge (for Z computation)
220
+ *
221
+ * Revision 1.7 2004/11/17 08:13:16 strk
222
+ * Indentation changes.
223
+ * Some Z_COMPUTATION activated by default.
224
+ *
225
+ * Revision 1.6 2004/11/04 19:08:06 strk
226
+ * Cleanups, initializers list, profiling.
227
+ *
228
+ * Revision 1.5 2004/10/21 22:29:54 strk
229
+ * Indentation changes and some more COMPUTE_Z rules
230
+ *
231
+ * Revision 1.4 2004/10/20 17:32:14 strk
232
+ * Initial approach to 2.5d intersection()
233
+ *
234
+ * Revision 1.3 2004/07/08 19:34:49 strk
235
+ * Mirrored JTS interface of CoordinateSequence, factory and
236
+ * default implementations.
237
+ * Added DefaultCoordinateSequenceFactory::instance() function.
238
+ *
239
+ * Revision 1.2 2004/07/02 13:28:26 strk
240
+ * Fixed all #include lines to reflect headers layout change.
241
+ * Added client application build tips in README.
242
+ *
243
+ * Revision 1.1 2004/03/19 09:48:45 ybychkov
244
+ * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4
245
+ *
246
+ * Revision 1.18 2003/11/07 01:23:42 pramsey
247
+ * Add standard CVS headers licence notices and copyrights to all cpp and h
248
+ * files.
249
+ *
250
+ * Revision 1.17 2003/11/06 19:04:28 strk
251
+ * removed useless Coordinate copy in ::createSplitEdge()
252
+ *
253
+ **********************************************************************/
254
+
pool/shard006/C++/0074181_r_clipsegment.cpp ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //
2
+ // Copyright (C) 1993-1996 by id Software, Inc.
3
+ //
4
+ // This source is available for distribution and/or modification
5
+ // only under the terms of the DOOM Source Code License as
6
+ // published by id Software. All rights reserved.
7
+ //
8
+ // The source is distributed in the hope that it will be useful,
9
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ // FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
11
+ // for more details.
12
+ //
13
+
14
+ #include <stdlib.h>
15
+ #include "templates.h"
16
+ #include "doomdef.h"
17
+ #include "m_bbox.h"
18
+ #include "i_system.h"
19
+ #include "p_lnspec.h"
20
+ #include "p_setup.h"
21
+ #include "swrenderer/drawers/r_draw.h"
22
+ #include "swrenderer/scene/r_3dfloors.h"
23
+ #include "a_sharedglobal.h"
24
+ #include "g_level.h"
25
+ #include "p_effect.h"
26
+ #include "doomstat.h"
27
+ #include "r_state.h"
28
+ #include "swrenderer/scene/r_opaque_pass.h"
29
+ #include "v_palette.h"
30
+ #include "r_sky.h"
31
+ #include "po_man.h"
32
+ #include "r_data/colormaps.h"
33
+ #include "swrenderer/segments/r_clipsegment.h"
34
+
35
+ namespace swrenderer
36
+ {
37
+ void RenderClipSegment::Clear(short left, short right)
38
+ {
39
+ solidsegs[0].first = -0x7fff;
40
+ solidsegs[0].last = left;
41
+ solidsegs[1].first = right;
42
+ solidsegs[1].last = 0x7fff;
43
+ newend = solidsegs+2;
44
+ }
45
+
46
+ bool RenderClipSegment::Check(int first, int last)
47
+ {
48
+ cliprange_t *start;
49
+
50
+ // Find the first range that touches the range
51
+ // (adjacent pixels are touching).
52
+ start = solidsegs;
53
+ while (start->last < first)
54
+ start++;
55
+
56
+ if (first < start->first)
57
+ {
58
+ return true;
59
+ }
60
+
61
+ // Bottom contained in start?
62
+ if (last > start->last)
63
+ {
64
+ return true;
65
+ }
66
+
67
+ return false;
68
+ }
69
+
70
+ bool RenderClipSegment::IsVisible(int sx1, int sx2)
71
+ {
72
+ // Does not cross a pixel.
73
+ if (sx2 <= sx1)
74
+ return false;
75
+
76
+ cliprange_t *start = solidsegs;
77
+ while (start->last < sx2)
78
+ start++;
79
+
80
+ if (sx1 >= start->first && sx2 <= start->last)
81
+ {
82
+ // The clippost contains the new span.
83
+ return false;
84
+ }
85
+
86
+ return true;
87
+ }
88
+
89
+ bool RenderClipSegment::Clip(int first, int last, bool solid, VisibleSegmentRenderer *visitor)
90
+ {
91
+ cliprange_t *next, *start;
92
+ int i, j;
93
+ bool res = false;
94
+
95
+ // Find the first range that touches the range
96
+ // (adjacent pixels are touching).
97
+ start = solidsegs;
98
+ while (start->last < first)
99
+ start++;
100
+
101
+ if (first < start->first)
102
+ {
103
+ res = true;
104
+ if (last <= start->first)
105
+ {
106
+ // Post is entirely visible (above start).
107
+ if (!visitor->RenderWallSegment(first, last))
108
+ return true;
109
+
110
+ // Insert a new clippost for solid walls.
111
+ if (solid)
112
+ {
113
+ if (last == start->first)
114
+ {
115
+ start->first = first;
116
+ }
117
+ else
118
+ {
119
+ next = newend;
120
+ newend++;
121
+ while (next != start)
122
+ {
123
+ *next = *(next - 1);
124
+ next--;
125
+ }
126
+ next->first = first;
127
+ next->last = last;
128
+ }
129
+ }
130
+ return true;
131
+ }
132
+
133
+ // There is a fragment above *start.
134
+ if (visitor->RenderWallSegment(first, start->first) && solid)
135
+ {
136
+ start->first = first; // Adjust the clip size for solid walls
137
+ }
138
+ }
139
+
140
+ // Bottom contained in start?
141
+ if (last <= start->last)
142
+ return res;
143
+
144
+ bool clipsegment;
145
+ next = start;
146
+ while (last >= (next + 1)->first)
147
+ {
148
+ // There is a fragment between two posts.
149
+ clipsegment = visitor->RenderWallSegment(next->last, (next + 1)->first);
150
+ next++;
151
+
152
+ if (last <= next->last)
153
+ {
154
+ // Bottom is contained in next.
155
+ last = next->last;
156
+ goto crunch;
157
+ }
158
+ }
159
+
160
+ // There is a fragment after *next.
161
+ clipsegment = visitor->RenderWallSegment(next->last, last);
162
+
163
+ crunch:
164
+ if (!clipsegment)
165
+ {
166
+ return true;
167
+ }
168
+ if (solid)
169
+ {
170
+ // Adjust the clip size.
171
+ start->last = last;
172
+
173
+ if (next != start)
174
+ {
175
+ // Remove start+1 to next from the clip list,
176
+ // because start now covers their area.
177
+ for (i = 1, j = (int)(newend - next); j > 0; i++, j--)
178
+ {
179
+ start[i] = next[i];
180
+ }
181
+ newend = start + i;
182
+ }
183
+ }
184
+ return true;
185
+ }
186
+ }
pool/shard006/C++/0074184_main.cpp ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2015 J. Rick Ramstetter
3
+ * rick.ramstetter[at]gmail.[tld]
4
+ *
5
+ * Problem statement:
6
+ * https://www.hackerrank.com/challenges/building-a-list
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ */
21
+
22
+ #include <assert.h>
23
+ #include <iostream>
24
+ #include <algorithm>
25
+
26
+ void print(const std::string &prefix, /* Output prefix for the current recursion */
27
+ const std::string &input, /* Input character array */
28
+ const std::string::const_iterator start /* Start location of the char array */
29
+ ) {
30
+ for (auto iter = start; iter != input.end(); ++iter) {
31
+ std::string temp (prefix + *iter);
32
+
33
+ std::cout << temp << std::endl;
34
+
35
+ print(temp, input, iter + 1);
36
+ }
37
+ }
38
+
39
+ int handle_test_case(size_t test_num) {
40
+ size_t size;
41
+ std::cin >> size;
42
+
43
+ std::string input;
44
+ std::cin >> input;
45
+ assert(size == input.size());
46
+
47
+ /* Treat input like a vector<char> and sort it */
48
+ std::sort(input.begin(), input.end());
49
+
50
+ print("", input, input.begin());
51
+ return 0;
52
+ }
53
+
54
+ int main() {
55
+ size_t test_cases;
56
+ std::cin >> test_cases;
57
+
58
+ for (size_t i = 0; i < test_cases; ++i) {
59
+ if (handle_test_case(i))
60
+ return EXIT_FAILURE;
61
+ }
62
+
63
+ return EXIT_SUCCESS;
64
+ }
pool/shard006/C++/0074187_vector2.cpp ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
2
+ /*
3
+ * vector3.cpp
4
+ * Copyright (C) Andrew Tridgell 2012
5
+ *
6
+ * This file is free software: you can redistribute it and/or modify it
7
+ * under the terms of the GNU General Public License as published by the
8
+ * Free Software Foundation, either version 3 of the License, or
9
+ * (at your option) any later version.
10
+ *
11
+ * This file is distributed in the hope that it will be useful, but
12
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
+ * See the GNU General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU General Public License along
17
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ */
19
+
20
+ #pragma GCC optimize("O3")
21
+
22
+ #include "AP_Math.h"
23
+
24
+ template <typename T>
25
+ float Vector2<T>::length(void) const
26
+ {
27
+ return pythagorous2(x, y);
28
+ }
29
+
30
+
31
+ // dot product
32
+ template <typename T>
33
+ T Vector2<T>::operator *(const Vector2<T> &v) const
34
+ {
35
+ return x*v.x + y*v.y;
36
+ }
37
+
38
+ // cross product
39
+ template <typename T>
40
+ T Vector2<T>::operator %(const Vector2<T> &v) const
41
+ {
42
+ return x*v.y - y*v.x;
43
+ }
44
+
45
+ template <typename T>
46
+ Vector2<T> &Vector2<T>::operator *=(const T num)
47
+ {
48
+ x*=num; y*=num;
49
+ return *this;
50
+ }
51
+
52
+ template <typename T>
53
+ Vector2<T> &Vector2<T>::operator /=(const T num)
54
+ {
55
+ x /= num; y /= num;
56
+ return *this;
57
+ }
58
+
59
+ template <typename T>
60
+ Vector2<T> &Vector2<T>::operator -=(const Vector2<T> &v)
61
+ {
62
+ x -= v.x; y -= v.y;
63
+ return *this;
64
+ }
65
+
66
+ template <typename T>
67
+ bool Vector2<T>::is_nan(void) const
68
+ {
69
+ return isnan(x) || isnan(y);
70
+ }
71
+
72
+ template <typename T>
73
+ bool Vector2<T>::is_inf(void) const
74
+ {
75
+ return isinf(x) || isinf(y);
76
+ }
77
+
78
+ template <typename T>
79
+ Vector2<T> &Vector2<T>::operator +=(const Vector2<T> &v)
80
+ {
81
+ x+=v.x; y+=v.y;
82
+ return *this;
83
+ }
84
+
85
+ template <typename T>
86
+ Vector2<T> Vector2<T>::operator /(const T num) const
87
+ {
88
+ return Vector2<T>(x/num, y/num);
89
+ }
90
+
91
+ template <typename T>
92
+ Vector2<T> Vector2<T>::operator *(const T num) const
93
+ {
94
+ return Vector2<T>(x*num, y*num);
95
+ }
96
+
97
+ template <typename T>
98
+ Vector2<T> Vector2<T>::operator -(const Vector2<T> &v) const
99
+ {
100
+ return Vector2<T>(x-v.x, y-v.y);
101
+ }
102
+
103
+ template <typename T>
104
+ Vector2<T> Vector2<T>::operator +(const Vector2<T> &v) const
105
+ {
106
+ return Vector2<T>(x+v.x, y+v.y);
107
+ }
108
+
109
+ template <typename T>
110
+ Vector2<T> Vector2<T>::operator -(void) const
111
+ {
112
+ return Vector2<T>(-x,-y);
113
+ }
114
+
115
+ template <typename T>
116
+ bool Vector2<T>::operator ==(const Vector2<T> &v) const
117
+ {
118
+ return (is_equal(x,v.x) && is_equal(y,v.y));
119
+ }
120
+
121
+ template <typename T>
122
+ bool Vector2<T>::operator !=(const Vector2<T> &v) const
123
+ {
124
+ return (!is_equal(x,v.x) || !is_equal(y,v.y));
125
+ }
126
+
127
+ template <typename T>
128
+ float Vector2<T>::angle(const Vector2<T> &v2) const
129
+ {
130
+ float len = this->length() * v2.length();
131
+ if (len <= 0) {
132
+ return 0.0f;
133
+ }
134
+ float cosv = ((*this)*v2) / len;
135
+ if (fabsf(cosv) >= 1) {
136
+ return 0.0f;
137
+ }
138
+ return acosf(cosv);
139
+ }
140
+
141
+ // only define for float
142
+ template float Vector2<float>::length(void) const;
143
+ template float Vector2<float>::operator *(const Vector2<float> &v) const;
144
+ template float Vector2<float>::operator %(const Vector2<float> &v) const;
145
+ template Vector2<float> &Vector2<float>::operator *=(const float num);
146
+ template Vector2<float> &Vector2<float>::operator /=(const float num);
147
+ template Vector2<float> &Vector2<float>::operator -=(const Vector2<float> &v);
148
+ template Vector2<float> &Vector2<float>::operator +=(const Vector2<float> &v);
149
+ template Vector2<float> Vector2<float>::operator /(const float num) const;
150
+ template Vector2<float> Vector2<float>::operator *(const float num) const;
151
+ template Vector2<float> Vector2<float>::operator +(const Vector2<float> &v) const;
152
+ template Vector2<float> Vector2<float>::operator -(const Vector2<float> &v) const;
153
+ template Vector2<float> Vector2<float>::operator -(void) const;
154
+ template bool Vector2<float>::operator ==(const Vector2<float> &v) const;
155
+ template bool Vector2<float>::operator !=(const Vector2<float> &v) const;
156
+ template bool Vector2<float>::is_nan(void) const;
157
+ template bool Vector2<float>::is_inf(void) const;
158
+ template float Vector2<float>::angle(const Vector2<float> &v) const;
pool/shard006/C++/0074188_fundwitnessdialog.cpp ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2016-2019 The Gulden developers
2
+ // Authored by: Willem de Jonge (willem@isnapp.nl)
3
+ // Distributed under the GULDEN software license, see the accompanying
4
+ // file COPYING
5
+
6
+ #include "fundwitnessdialog.h"
7
+ #include <qt/forms/ui_fundwitnessdialog.h>
8
+
9
+ #include <stdexcept>
10
+ #include "wallet/wallet.h"
11
+ #include "gui.h"
12
+ #include "wallet/witness_operations.h"
13
+ #include "units.h"
14
+ #include "witnessutil.h"
15
+ #include "walletmodel.h"
16
+ #include "optionsmodel.h"
17
+ #include "consensus/validation.h"
18
+
19
+ FundWitnessDialog::FundWitnessDialog(CAmount minimumFunding, CAmount lockedAmount_, int durationRemaining, int64_t minimumWeight, WalletModel* walletModel_, const QStyle *_platformStyle, QWidget *parent)
20
+ : QFrame( parent )
21
+ , ui( new Ui::FundWitnessDialog )
22
+ , platformStyle( _platformStyle )
23
+ , walletModel(walletModel_)
24
+ , lockedAmount(lockedAmount_)
25
+ {
26
+ ui->setupUi(this);
27
+
28
+ ui->fundingSelection->setWalletModel(walletModel, minimumFunding);
29
+
30
+ connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));
31
+ connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked()));
32
+ connect(ui->fundButton, SIGNAL(clicked()), this, SLOT(fundClicked()));
33
+ connect(ui->payAmount, SIGNAL(amountChanged()), this, SLOT(amountFieldChanged()));
34
+
35
+ ui->payAmount->setOptionsModel(walletModel->getOptionsModel());
36
+ ui->payAmount->setDisplayMaxButton(false);
37
+ ui->payAmount->setAmount(lockedAmount);
38
+ ui->lockDuration->configure(lockedAmount, durationRemaining, minimumWeight);
39
+ }
40
+
41
+ FundWitnessDialog::FundWitnessDialog(CAmount lockedAmount_, int durationRemaining, int64_t minimumWeight, WalletModel* walletModel_, const QStyle *_platformStyle, QWidget *parent)
42
+ : FundWitnessDialog(1 * COIN, lockedAmount_, durationRemaining, minimumWeight, walletModel_, _platformStyle, parent)
43
+ {
44
+ ui->extendButton->setVisible(true);
45
+ ui->fundButton->setVisible(false);
46
+ ui->labelExtendDescription->setText(tr("Extend a witness to increase amount and/or locking duration. A funding account is needed to provide the transaction fee, even if the amount is not increased."));
47
+ }
48
+
49
+ FundWitnessDialog::FundWitnessDialog(WalletModel* walletModel_, const QStyle *platformStyle, QWidget *parent)
50
+ : FundWitnessDialog(gMinimumWitnessAmount * COIN, 0, 0, 0, walletModel_, platformStyle, parent)
51
+ {
52
+ ui->extendButton->setVisible(false);
53
+ ui->fundButton->setVisible(true);
54
+ ui->labelExtendDescription->setText(tr("Fund your witness to start witnessing and earn rewards."));
55
+
56
+ // Initial funding dialog is shown automatically when an empty witness account is selected and does not need the cancel button
57
+ ui->cancelButton->setVisible(false);
58
+ }
59
+
60
+ FundWitnessDialog::~FundWitnessDialog()
61
+ {
62
+ delete ui;
63
+ }
64
+
65
+ void FundWitnessDialog::cancelClicked()
66
+ {
67
+ LOG_QT_METHOD;
68
+
69
+ Q_EMIT dismiss(this);
70
+ }
71
+
72
+ void FundWitnessDialog::extendClicked()
73
+ {
74
+ LOG_QT_METHOD;
75
+
76
+ // Format confirmation message
77
+ QString questionString = tr("Are you sure you want to extend the witness?");
78
+ questionString.append("<br /><br />");
79
+ int days = ui->lockDuration->duration() / DailyBlocksTarget();
80
+ questionString.append(tr("%1 will be locked for %2 days (%3).")
81
+ .arg(GuldenUnits::formatHtmlWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), ui->payAmount->amount()))
82
+ .arg(days)
83
+ .arg(daysToHuman(days)));
84
+ questionString.append("<br /><br />");
85
+ questionString.append(tr("It will not be possible under any circumstances to spend or move these funds for the duration of the lock period."));
86
+
87
+ if(QDialog::Accepted == GUI::createDialog(this, questionString, tr("Extend witness"), tr("Cancel"), 600, 360, "ExtendWitnessConfirmationDialog")->exec())
88
+ {
89
+ // selected fundingAccount
90
+ CAccount* fundingAccount = ui->fundingSelection->selectedAccount();
91
+ if (!fundingAccount) {
92
+ GUI::createDialog(this, tr("No funding account selected"), tr("Okay"), QString(""), 400, 180)->exec();
93
+ return;
94
+ }
95
+
96
+ pactiveWallet->BeginUnlocked(_("Wallet unlock required to extend witness"), [=](){
97
+
98
+ try {
99
+ LOCK2(cs_main, pactiveWallet->cs_wallet);
100
+ CAccount* witnessAccount = pactiveWallet->activeAccount;
101
+ extendwitnessaccount(pactiveWallet,
102
+ fundingAccount,
103
+ witnessAccount,
104
+ ui->payAmount->amount(),
105
+ ui->lockDuration->duration(),
106
+ nullptr, nullptr); // ignore result params
107
+
108
+ // request dismissal only when succesful
109
+ Q_EMIT dismiss(this);
110
+
111
+ } catch (std::runtime_error& e) {
112
+ GUI::createDialog(this, e.what(), tr("Okay"), QString(""), 400, 180)->exec();
113
+ }
114
+
115
+ pactiveWallet->EndUnlocked();
116
+ });
117
+ }
118
+ }
119
+
120
+ void FundWitnessDialog::fundClicked()
121
+ {
122
+ LOG_QT_METHOD;
123
+
124
+ // Format confirmation message
125
+ QString questionString = tr("Are you sure you want to fund the witness?");
126
+ questionString.append("<br /><br />");
127
+ int days = ui->lockDuration->duration() / DailyBlocksTarget();
128
+ questionString.append(tr("%1 will be locked for %2 days (%3).")
129
+ .arg(GuldenUnits::formatHtmlWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), ui->payAmount->amount()))
130
+ .arg(days)
131
+ .arg(daysToHuman(days)));
132
+ questionString.append("<br /><br />");
133
+ questionString.append(tr("It will not be possible under any circumstances to spend or move these funds for the duration of the lock period."));
134
+
135
+ if(QDialog::Accepted == GUI::createDialog(this, questionString, tr("Fund witness"), tr("Cancel"), 600, 360, "FundWitnessConfirmationDialog")->exec())
136
+ {
137
+ // selected fundingAccount
138
+ CAccount* fundingAccount = ui->fundingSelection->selectedAccount();
139
+ if (!fundingAccount) {
140
+ GUI::createDialog(this, tr("No funding account selected"), tr("Okay"), QString(""), 400, 180)->exec();
141
+ return;
142
+ }
143
+
144
+ pactiveWallet->BeginUnlocked(_("Wallet unlock required to fund witness"), [=](){
145
+
146
+ try
147
+ {
148
+ LOCK2(cs_main, pactiveWallet->cs_wallet);
149
+ CAccount* witnessAccount = pactiveWallet->activeAccount;
150
+ fundwitnessaccount(pactiveWallet,
151
+ fundingAccount,
152
+ witnessAccount,
153
+ ui->payAmount->amount(),
154
+ ui->lockDuration->duration(),
155
+ false,
156
+ nullptr, nullptr); // ignore result params
157
+
158
+ // request dismissal only when succesful
159
+ Q_EMIT dismiss(this);
160
+
161
+ }
162
+ catch (std::runtime_error& e)
163
+ {
164
+ GUI::createDialog(this, e.what(), tr("Okay"), QString(""), 400, 180)->exec();
165
+ }
166
+
167
+ pactiveWallet->EndUnlocked();
168
+ });
169
+ }
170
+ }
171
+
172
+ void FundWitnessDialog::amountFieldChanged()
173
+ {
174
+ CAmount newAmount = ui->payAmount->amount();
175
+ ui->lockDuration->setAmount(newAmount);
176
+ }
pool/shard006/C++/0074189_DescribeTaskSetsResult.cpp ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0.
4
+ */
5
+
6
+ #include <aws/ecs/model/DescribeTaskSetsResult.h>
7
+ #include <aws/core/utils/json/JsonSerializer.h>
8
+ #include <aws/core/AmazonWebServiceResult.h>
9
+ #include <aws/core/utils/StringUtils.h>
10
+ #include <aws/core/utils/UnreferencedParam.h>
11
+
12
+ #include <utility>
13
+
14
+ using namespace Aws::ECS::Model;
15
+ using namespace Aws::Utils::Json;
16
+ using namespace Aws::Utils;
17
+ using namespace Aws;
18
+
19
+ DescribeTaskSetsResult::DescribeTaskSetsResult()
20
+ {
21
+ }
22
+
23
+ DescribeTaskSetsResult::DescribeTaskSetsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
24
+ {
25
+ *this = result;
26
+ }
27
+
28
+ DescribeTaskSetsResult& DescribeTaskSetsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
29
+ {
30
+ JsonView jsonValue = result.GetPayload().View();
31
+ if(jsonValue.ValueExists("taskSets"))
32
+ {
33
+ Array<JsonView> taskSetsJsonList = jsonValue.GetArray("taskSets");
34
+ for(unsigned taskSetsIndex = 0; taskSetsIndex < taskSetsJsonList.GetLength(); ++taskSetsIndex)
35
+ {
36
+ m_taskSets.push_back(taskSetsJsonList[taskSetsIndex].AsObject());
37
+ }
38
+ }
39
+
40
+ if(jsonValue.ValueExists("failures"))
41
+ {
42
+ Array<JsonView> failuresJsonList = jsonValue.GetArray("failures");
43
+ for(unsigned failuresIndex = 0; failuresIndex < failuresJsonList.GetLength(); ++failuresIndex)
44
+ {
45
+ m_failures.push_back(failuresJsonList[failuresIndex].AsObject());
46
+ }
47
+ }
48
+
49
+
50
+
51
+ return *this;
52
+ }