blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
42188659a25fcb3111331435d9cde1fdfe3dc874
a5b5f56c37954bd9e6744c33806896856a9975d8
/UDPserver.h
deeac0863d7a1c78074040ec846541f8383f77ac
[ "MIT" ]
permissive
shanilfernando/VRInteraction
3890b9410c5a0c9b2f39e68a203dc72a9c35a2f5
db1f4ffe10059eb6af01ecc12846c3b2bd0a003f
refs/heads/master
2020-12-03T04:02:48.901246
2017-07-11T09:36:41
2017-07-11T09:36:41
95,807,804
26
7
null
null
null
null
UTF-8
C++
false
false
472
h
UDPserver.h
#pragma once #include<stdio.h> #include<winsock2.h> #include <vector> #include <string> #include <sstream> #include <iostream> #include <ctime> #pragma comment(lib,"ws2_32.lib") #define BUFLEN 512 #define PORT 5555 class UDPserver { public: UDPserver(); ~UDPserver(); std::string getBuffer(); private: SOCKET s; struct sockaddr_in server, si_other; int slen, recv_len; char buf[BUFLEN]; WSADATA wsa; void recvData(); };
18cbead82164d02127cd556e385939f7c1f9094b
8ba4c2d8ba65d48ae32f911a8a2c6f16afe5670d
/usb_cam/src/usb_cam/gps/src/agvc_gps/src/agvc_gps_2d_node.cpp
d74fa8ec1522c2814fa52e6b4ce616923fd1f0ae
[]
no_license
Gwylim23/owr_software
6aeda6bf3228225167d3ba0d67843b7c01a9e702
a81562202a47337ff92447c02511eb5449a5e233
refs/heads/master
2021-01-18T03:11:10.053391
2014-08-02T02:36:32
2014-08-02T02:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,913
cpp
agvc_gps_2d_node.cpp
#include <agvc_gps/agvc_gps_2d_node.h> AGVCGPS2DNode::AGVCGPS2DNode() { ros::NodeHandle private_node_handle("~"); // Read in GPS topic to subscribe to. std::string gps_topic("fix"); if (!private_node_handle.getParam("gps_fix_topic", gps_topic)) { ROS_WARN("[AGVC GPS 2D Node] : <gps_fix_topic> not specified, defaulting to %s", gps_topic.c_str()); } else { ROS_INFO("[AGVC GPS 2D Node] : <gps_fix_topic> set to %s", gps_topic.c_str()); } // Subscribe to the topic. gps_sub_ = node_handle_.subscribe(gps_topic, 20, &AGVCGPS2DNode::navSatFixCallback, this); // Read in GPS topic to publish. std::string gps_2d_topic("fix_2d"); if (!private_node_handle.getParam("gps_fix_2d_topic", gps_2d_topic)) { ROS_WARN("[AGVC GPS 2D Node] : <gps_fix_2d_topic> not specified, defaulting to %s", gps_2d_topic.c_str()); } else { ROS_INFO("[AGVC GPS 2D Node] : <gps_fix_2d_topic> set to %s", gps_2d_topic.c_str()); } // Advertise topic. gps_2d_pub_ = node_handle_.advertise<sensor_msgs::NavSatFix>(gps_2d_topic, 20); } void AGVCGPS2DNode::spin() { ros::spin(); } void AGVCGPS2DNode::navSatFixCallback(const sensor_msgs::NavSatFix::ConstPtr & nav_sat_fix) { sensor_msgs::NavSatFix nav_sat_fix_2d; nav_sat_fix_2d.header = nav_sat_fix->header; nav_sat_fix_2d.latitude = nav_sat_fix->latitude; nav_sat_fix_2d.longitude= nav_sat_fix->longitude; // Set altitude to zero. nav_sat_fix_2d.altitude= 0.0f; nav_sat_fix_2d.position_covariance = nav_sat_fix->position_covariance; // Large altitude uncertainty. nav_sat_fix_2d.position_covariance[8] = 1e9; nav_sat_fix_2d.position_covariance_type = nav_sat_fix->position_covariance_type; gps_2d_pub_.publish(nav_sat_fix_2d); } int main(int argc, char ** argv) { ros::init(argc, argv, "agvc_gps_2d_node"); AGVCGPS2DNode agvc_gps_2d_node; agvc_gps_2d_node.spin(); return 0; }
e11904aea9e75ce8bed13e6687285798ece892ea
81940315f6b945c2fab270272630d01785ec0fb1
/red/101_week4_ListsQuiz/main.cpp
82e36e7b53e92b32c7f7e74d6387677b3a02da01
[]
no_license
adogadaev/CourseraYandexCpp
d3361fb6a8707ac2ea406f0cd6a259cde1176732
b5ca2b8288410fbb23f36ee813cd12eb87b11eeb
refs/heads/master
2023-06-22T21:47:57.437530
2021-07-20T12:14:29
2021-07-20T12:14:29
218,399,060
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
main.cpp
#include <iostream> #include <list> using namespace std; int main() { list<int> mylist; // set some initial values: for (int i=1; i<=10; ++i) mylist.push_back(i); for (const auto& el : mylist) cout << el << " "; cout << "\n"; auto it1 = next(mylist.begin(), 2); auto it2 = next(mylist.begin(), 7); cout << *it1 << " " << *it2 << "\n"; auto tmp_it = next(it2); mylist.splice(it1, mylist, it2); mylist.splice(tmp_it, mylist, it1); for (const auto& el : mylist) cout << el << " "; cout << "\n"; cout << *it1 << " " << *it2 << "\n"; }
3172aaad1f0f7518c1b07a8dc2db2922769171f1
b4be6b6d18cb35e8d5cfbf5b7ec04d0bdbab7f79
/test/test_mesh.cpp
89fd6ec25c58200c05b07be462077cef414db3bf
[]
no_license
amorilia/vcache
1eb767a9d0393bbeec3d551a63fcbb3adb8c86fc
0b62a292097844186a9e27acda935ff0c7d2e173
refs/heads/master
2016-09-09T19:29:30.600599
2011-11-20T10:55:18
2011-11-20T10:55:18
1,106,988
1
0
null
null
null
null
UTF-8
C++
false
false
6,409
cpp
test_mesh.cpp
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <ostream> #include "vcache/mesh.hpp" #include "test_helpers.hpp" BOOST_AUTO_TEST_SUITE(mesh_test_suite) BOOST_AUTO_TEST_CASE(declare_test) { // check that declarations work as expected BOOST_CHECK_NO_THROW(Face face(0, 1, 2)); BOOST_CHECK_NO_THROW(Mesh mesh(3)); // degenerate faces BOOST_CHECK_THROW(Face face(30, 0, 30), std::runtime_error); BOOST_CHECK_THROW(Face face(0, 40, 40), std::runtime_error); BOOST_CHECK_THROW(Face face(50, 50, 0), std::runtime_error); BOOST_CHECK_THROW(Face face(7, 7, 7), std::runtime_error); } BOOST_AUTO_TEST_CASE(face_vertex_order_test_0) { Face f(6, 2, 5); BOOST_CHECK_EQUAL(f.v0, 2); BOOST_CHECK_EQUAL(f.v1, 5); BOOST_CHECK_EQUAL(f.v2, 6); } BOOST_AUTO_TEST_CASE(face_vertex_order_test_1) { Face f(2, 5, 6); BOOST_CHECK_EQUAL(f.v0, 2); BOOST_CHECK_EQUAL(f.v1, 5); BOOST_CHECK_EQUAL(f.v2, 6); } BOOST_AUTO_TEST_CASE(face_vertex_order_test_2) { Face f(5, 6, 2); BOOST_CHECK_EQUAL(f.v0, 2); BOOST_CHECK_EQUAL(f.v1, 5); BOOST_CHECK_EQUAL(f.v2, 6); } BOOST_AUTO_TEST_CASE(mesh_add_face_test) { Mesh m(13); // add faces BOOST_CHECK_NO_THROW(m.add_face(0, 1, 2)); BOOST_CHECK_NO_THROW(m.add_face(2, 1, 3)); BOOST_CHECK_NO_THROW(m.add_face(2, 3, 4)); BOOST_CHECK_EQUAL(m.faces.size(), 3); // add duplicate face BOOST_CHECK_NO_THROW(m.add_face(2, 3, 4)); Face const & f0 = m.add_face(10, 11, 12); Face const & f1 = m.add_face(12, 10, 11); Face const & f2 = m.add_face(11, 12, 10); BOOST_CHECK_EQUAL(f0, f1); BOOST_CHECK_EQUAL(f0, f2); // one extra face, four extra vertices BOOST_CHECK_EQUAL(m.faces.size(), 4); } BOOST_AUTO_TEST_CASE(mvertex_mfaces_test_0) { // construct mesh Mesh m(5); Face const & f0 = m.add_face(0, 1, 2); Face const & f1 = m.add_face(1, 3, 2); Face const & f2 = m.add_face(2, 3, 4); // 0->-1 // \ / \ // 2-<-3 // 2->-3 // \ / // 4 // check face vertices BOOST_CHECK_EQUAL(f0.v0, 0); BOOST_CHECK_EQUAL(f0.v1, 1); BOOST_CHECK_EQUAL(f0.v2, 2); BOOST_CHECK_EQUAL(f1.v0, 1); BOOST_CHECK_EQUAL(f1.v1, 3); BOOST_CHECK_EQUAL(f1.v2, 2); BOOST_CHECK_EQUAL(f2.v0, 2); BOOST_CHECK_EQUAL(f2.v1, 3); BOOST_CHECK_EQUAL(f2.v2, 4); // check vertex faces std::set<Face> faces; // vertex 0 faces.clear(); faces.insert(f0); BOOST_CHECK_EQUAL(m.vertex_infos[0].faces, faces); // vertex 1 faces.clear(); faces.insert(f0); faces.insert(f1); BOOST_CHECK_EQUAL(m.vertex_infos[1].faces, faces); // vertex 2 faces.clear(); faces.insert(f0); faces.insert(f1); faces.insert(f2); BOOST_CHECK_EQUAL(m.vertex_infos[2].faces, faces); // vertex 3 faces.clear(); faces.insert(f1); faces.insert(f2); BOOST_CHECK_EQUAL(m.vertex_infos[3].faces, faces); // vertex 4 faces.clear(); faces.insert(f2); BOOST_CHECK_EQUAL(m.vertex_infos[4].faces, faces); } BOOST_AUTO_TEST_CASE(mvertex_faces_test_1) { // construct mesh Mesh m(6); Face const & f0 = m.add_face(0, 1, 2); Face const & f1 = m.add_face(1, 3, 2); Face const & f2 = m.add_face(2, 3, 4); Face const & f3 = m.add_face(2, 3, 5); // check face vertices BOOST_CHECK_EQUAL(f0.v0, 0); BOOST_CHECK_EQUAL(f0.v1, 1); BOOST_CHECK_EQUAL(f0.v2, 2); BOOST_CHECK_EQUAL(f1.v0, 1); BOOST_CHECK_EQUAL(f1.v1, 3); BOOST_CHECK_EQUAL(f1.v2, 2); BOOST_CHECK_EQUAL(f2.v0, 2); BOOST_CHECK_EQUAL(f2.v1, 3); BOOST_CHECK_EQUAL(f2.v2, 4); BOOST_CHECK_EQUAL(f3.v0, 2); BOOST_CHECK_EQUAL(f3.v1, 3); BOOST_CHECK_EQUAL(f3.v2, 5); // check vertex faces std::set<Face> faces; // vertex 0 faces.clear(); faces.insert(f0); BOOST_CHECK_EQUAL(m.vertex_infos[0].faces, faces); // vertex 1 faces.clear(); faces.insert(f0); faces.insert(f1); BOOST_CHECK_EQUAL(m.vertex_infos[1].faces, faces); // vertex 2 faces.clear(); faces.insert(f0); faces.insert(f1); faces.insert(f2); faces.insert(f3); BOOST_CHECK_EQUAL(m.vertex_infos[2].faces, faces); // vertex 3 faces.clear(); faces.insert(f1); faces.insert(f2); faces.insert(f3); BOOST_CHECK_EQUAL(m.vertex_infos[3].faces, faces); // vertex 4 faces.clear(); faces.insert(f2); BOOST_CHECK_EQUAL(m.vertex_infos[4].faces, faces); // vertex 5 faces.clear(); faces.insert(f3); BOOST_CHECK_EQUAL(m.vertex_infos[5].faces, faces); } BOOST_AUTO_TEST_CASE(mvertex_faces_test_2) { // single triangle mesh Mesh m(3); Face const & f = m.add_face(0, 1, 2); // check face vertices BOOST_CHECK_EQUAL(f.v0, 0); BOOST_CHECK_EQUAL(f.v1, 1); BOOST_CHECK_EQUAL(f.v2, 2); // check vertex faces std::set<Face> faces; faces.clear(); faces.insert(f); BOOST_CHECK_EQUAL(m.vertex_infos[0].faces, faces); BOOST_CHECK_EQUAL(m.vertex_infos[1].faces, faces); BOOST_CHECK_EQUAL(m.vertex_infos[2].faces, faces); } BOOST_AUTO_TEST_CASE(score_mesh_empty_test) { VertexScore vertex_score; Mesh m(0); BOOST_CHECK_NO_THROW(m.update_score(Mesh::VertexList(), vertex_score)); } BOOST_AUTO_TEST_CASE(score_mesh_single_test) { VertexScore vertex_score; Mesh m(3); m.add_face(0, 1, 2); Mesh::VertexList vertices; vertices.push_back(0); vertices.push_back(1); vertices.push_back(2); BOOST_CHECK_NO_THROW(m.update_score(vertices, vertex_score)); } BOOST_AUTO_TEST_CASE(score_mesh_double_test) { VertexScore vertex_score; Mesh m(4); m.add_face(0, 1, 2); m.add_face(2, 1, 3); Mesh::VertexList vertices; vertices.push_back(0); vertices.push_back(1); vertices.push_back(2); vertices.push_back(3); BOOST_CHECK_NO_THROW(m.update_score(vertices, vertex_score)); } BOOST_AUTO_TEST_CASE(optimize_mesh_test_1) { VertexScore vertex_score; Mesh m(10); Face const & f0 = m.add_face(0, 1, 2); Face const & f1 = m.add_face(7, 8, 9); Face const & f2 = m.add_face(2, 3, 4); std::list<Face> faces; faces.push_back(f1); faces.push_back(f0); faces.push_back(f2); BOOST_CHECK_EQUAL(faces, m.get_cache_optimized_faces(vertex_score)); } BOOST_AUTO_TEST_SUITE_END()
bb0ff982a7e00247470b7df76c5b712674a550f8
c4f06fda7a887b590e5787422f87f047258765f6
/MightyTCPClient/BufferManage.cpp
34e2ee8e98bb69e153cb4b79b3c10d69fb3fab8f
[]
no_license
wangdy326/CyclonicGameEngine
686e07f5eeb9880635845f0c565af95ef74d0633
566f98c038185934fa0437d74a83f7d89bfec4fc
refs/heads/master
2021-05-26T18:09:50.319170
2011-06-02T05:42:04
2011-06-02T05:42:04
null
0
0
null
null
null
null
GB18030
C++
false
false
1,182
cpp
BufferManage.cpp
//Copyright (c) 2005, 中搜 // //文件名称:BufferManage.cpp //创建:冯立强 //last update 2005-8-31 0:18:20 by 冯立强 #include "StdAfx.h" #include ".\buffermanage.h" CBufferManage::CBufferManage(void) { this->m_count = 0; } CBufferManage::~CBufferManage(void) { } ICE_BUF *CBufferManage::AllocBuffer(int len) { ICE_BUF *pRetValue = new ICE_BUF(len); if ( pRetValue->buffer.len != len ) { delete pRetValue; pRetValue = NULL; } return pRetValue; } void CBufferManage::FreeBuffer(ICE_BUF *pBuffer) { if ( pBuffer != NULL ) delete pBuffer; } ICE_OVERLAPPED_BUF *CBufferManage::AllocOverLappedBuf(int len) { ICE_OVERLAPPED_BUF *pRetValue = new ICE_OVERLAPPED_BUF(len); InterlockedIncrement(&this->m_count); if ( pRetValue->pBuffer == NULL ) { if ( len == 0 ) return pRetValue; delete pRetValue; return NULL; } if ( pRetValue->pBuffer->buffer.len != len ) { delete pRetValue; return NULL; } return pRetValue; } void CBufferManage::FreeOverLappedBuf(ICE_OVERLAPPED_BUF *pOverLappedBuf) { InterlockedDecrement(&this->m_count); K_PRINT("\n缓冲区个数为%d", this->m_count); if ( pOverLappedBuf != NULL ) delete pOverLappedBuf; }
4a98382ce4eaa6154d4637affdbf846ddbb8f5e2
65b02eae4e6ea39beadb67c5efd62e0b429bb43b
/Problems/cccc/L1/L1-029.cpp
aabbdb2114817c49277c4d7638b516db064a466b
[]
no_license
ctuu/acm-icpc
c0a96a347feba414fce28455e9b71546ac1cb08d
7fde619dce94dd2e722465cdcad32c76d30afa16
refs/heads/master
2021-07-08T06:14:57.837572
2018-12-29T04:09:40
2018-12-29T04:09:40
81,524,853
2
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
L1-029.cpp
#include <iostream> #include <iomanip> int main() { double a; std::cin >> a; std::cout << std::setprecision(1) << std::fixed << (a - 100) * 1.8; return 0; }
2117bda29f0594588f3c0e51b13d5aaa45f33fe9
969d14ce44343fb1866261efee01e652e217c35e
/commands.h
90cba69e593473e28b5b1de7d28f6a358af2fb13
[]
no_license
Jkreynin/Anomaly-detecion-server
2c8565c0b84b6de5f77067217944eaf5c4020a7b
db5b966de288bd1e8091ff16a505a79dda5b80d5
refs/heads/master
2023-03-13T09:18:45.042534
2021-03-04T17:06:04
2021-03-04T17:06:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,851
h
commands.h
#ifndef COMMANDS_H_ #define COMMANDS_H_ #include<iostream> #include <cstring> #include <syscall.h> #include <fstream> #include <vector> #include "HybridAnomalyDetector.h" using namespace std; class DefaultIO { public: virtual string read() = 0; virtual void write(string text) = 0; virtual void write(float f) = 0; virtual void read(float *f) = 0; void createFile(const string &fileName) { ofstream file; file.open(fileName); string input; input = this->read(); while (!(input == "done")) { file << input << endl; input = this->read(); } file.close(); } virtual ~DefaultIO() {} // you may add additional methods here }; // you may add here helper classes typedef struct commend_data { TimeSeries *ts1; TimeSeries *ts2; vector<AnomalyReport> reporst; HybridAnomalyDetector *algo = new HybridAnomalyDetector(); } commend_data; // you may edit this class class Command { protected: DefaultIO *dio; string description; commend_data *data; public: Command(DefaultIO *dio) : dio(dio) {} virtual void execute() = 0; virtual void printDescption() { this->dio->write(this->description); } virtual ~Command() {} }; class UploudFile : virtual public Command { public: UploudFile(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "1.upload a time series csv file\n"; } void execute() override { const char *train_file = "anomalyTrain.csv"; const char *test_file = "anomalyTest.csv"; this->dio->write("Please upload your local train CSV file.\n"); this->dio->createFile("anomalyTrain.csv"); data->ts1 = new TimeSeries(train_file); this->dio->write("Upload complete.\n"); this->dio->write("Please upload your local test CSV file.\n"); this->dio->createFile("anomalyTest.csv"); data->ts2 = new TimeSeries(test_file); this->dio->write("Upload complete.\n"); } ~UploudFile() override {} }; class ChengeThreshold : virtual public Command { public: ChengeThreshold(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "2.algorithm settings\n"; } void execute() override { float newThreshold; this->dio->write("The current correlation threshold is "); this->dio->write(data->algo->get_threshold()); this->dio->write("\n"); this->dio->write("Type a new threshold\n"); newThreshold = stof(this->dio->read()); while (!inRange(newThreshold)) { this->dio->write("please choose a value between 0 and 1.\n"); } data->algo->set_threshold(newThreshold); } static bool inRange(float x) { return (x <= 1 && x >= 0); } ~ChengeThreshold() override {} }; class HybridAlgo : public Command { public: explicit HybridAlgo(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "3.detect anomalies\n"; } void execute() override { data->algo->learnNormal(*(data->ts1)); data->reporst = data->algo->detect(*(data->ts2)); this->dio->write("anomaly detection complete.\n"); } }; class ReporstDev : public Command { public: explicit ReporstDev(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "4.display results\n"; } void execute() override { for (const AnomalyReport &a:data->reporst) { string text = to_string(a.timeStep) + "\t" + a.description + "\n"; this->dio->write(text); } this->dio->write("Done.\n"); } }; class AnlayzeData : public Command { public: explicit AnlayzeData(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "5.upload anomalies and analyze results\n"; } void execute() override { this->dio->write("Please upload your local anomalies file.\n"); //init a vector of pair that the first is a number and the second is also a pair - int and bool. vector<pair<int, pair<int, bool>>> timeClient; // the sum of the lines that was a report of dev. int sum = 0; //the lines of report of the client. int counter_line = 0; int first, second; string input = this->dio->read(); // get all the report form the client and keep it inside the vector. while (!(input == "done")) { counter_line++; string part; stringstream stream(input); getline(stream, part, ','); first = stoi(part); getline(stream, part, ','); second = stoi(part); sum += (second + 1) - first; timeClient.emplace_back(first, make_pair(second, false)); input = this->dio->read(); } this->dio->write("Upload complete.\n"); // init another vector to compare the reports from the detect and what the client gave us. vector<pair<long, long>> compare; // start with the first report // string des = this->data->reporst[0].description; long time = this->data->reporst[0].timeStep; long left = time; long right; /* get over the reports and get all the same description and there is one step between one report to the next one, and get them all together. inside the vecotr. */ for (int i = 0; i < this->data->reporst.size() - 1; ++i) { string name1 = this->data->reporst[i].description; string name2 = this->data->reporst[i + 1].description; long step2 = this->data->reporst[i + 1].timeStep; if ((name1 == name2) && (time == step2 - 1)) { right = step2; } else { compare.emplace_back(left, right); right = left = step2; } time = step2; } compare.emplace_back(left, right); //sort the vector to be a up series. sort(compare.begin(), compare.end()); // get the size of the lines. int size_steps = this->data->ts2->getSize(); // the lines of the report from the client. int positive = counter_line; // get the amount of lines that was not a reports above. int negative = size_steps - sum; int is_cros = 0; float TruePositive = 0, TrueNegative = 0, FalsePositive = 0, FalseNegative = 0; bool intersection; for (const pair<long, long> &c:compare) { intersection = false; for (pair<int, pair<int, bool>> &step:timeClient) { // if there is a intersection between the tow if (inRange(step.first, step.second.first, c.first, c.second)) { is_cros += (isMax(step.second.first, c.second) + 1) - isMin(step.first, c.first); intersection = true; // update the bool of the step to be true,because was a intersection. step.second.second = true; } } // if there no intersection. if (!intersection) { FalsePositive++; } } for (const pair<int, pair<int, bool>> &client:timeClient) { if (!client.second.second) { FalseNegative++; } else { TruePositive++; } } TrueNegative = size_steps - (is_cros + FalsePositive + FalseNegative); float True_positive_rate = (floor((TruePositive / float(positive)) * 1000)) / 1000; float False_alarm_rate = (floor((FalsePositive / float(negative)) * 1000)) / 1000; stringstream s; s << True_positive_rate; string text = "True Positive Rate: " + s.str() + "\n"; this->dio->write(text); s.str(string()); s << False_alarm_rate; text = "False Positive Rate: " + s.str() + "\n"; this->dio->write(text); } bool inRange(int x1, int x2, int y1, int y2) { if ((x1 >= y1) && (x1 <= y2) || (x2 >= y1) && (x2 <= y2) || (y1 >= x1) && (y1 <= x2) || (y2 >= x1) && (y2 <= x2)) { return true; } return false; } int isMin(int x1, int x2) { if (x1 < x2) { return x1; } else { return x2; } } int isMax(int x1, int x2) { if (x1 > x2) { return x1; } else { return x2; } } }; class ExitMenu : public Command { public: explicit ExitMenu(DefaultIO *dio, commend_data *commendData) : Command(dio) { this->data = commendData; this->description = "6.exit\n"; } void execute() override { delete this->data->ts1; delete this->data->ts2; delete this->data->algo; } }; class StandartIo : public DefaultIO { public: string read() override { string input; cin >> input; return input; } void write(string text) override { cout << text; } void write(float f) override { cout << f; } void read(float *f) override { cin >> *f; } }; #endif /* COMMANDS_H_ */
f7765dac88086a8d85e936d455306a5c480547de
e28e3c5355b34560b0b2cbdd40e75c6e445fa5b1
/generic_process/ex1/Solution/Deque.h
cf3f3d24966c77288dee18e00b92958dfbe3d823
[]
no_license
cnsuhao/labs
98ed85cca6df21adb3bdb67e0bc273f80a913192
a8ec74e904f7d7144002efa7bfcc52da8efa7b1d
refs/heads/master
2021-05-18T09:15:26.259492
2013-01-29T07:59:10
2013-01-29T07:59:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,391
h
Deque.h
/////////////////////////////////////////////////////////////////////////////// // Copyright 2007 Eric Niebler, David Abrahams. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef DEQUE_H_BOOST_CONSULTING #define DEQUE_H_BOOST_CONSULTING #include <cassert> #include <utility> const int DequeSegmentSize = 5; // DequeSegment: // // ----------------------------------------------------------------------- // | | | | | | | | // | first | last | data[0] | data[1] | data[2] | data[3] | data[4] | // | | | | | | | | // ------------------------------------^-----------------^---------------- // | | / \ / \ // | | | | // | | | | // \---------+--------------------/ | // | | // | | // \--------------------------------------/ // struct DequeSegment { int* first; // pointer to the first element in this segment int* last; // pointer to the last+1 element in this segment int data[DequeSegmentSize]; explicit DequeSegment(int offset) : first(data + offset) , last(first) {} }; // Deque: // // --------------- --------------- // | | | | ---------------...- // | segments |----->| segments[0] |------>| Segment 0 ... | // | | | | ---------------...- // ---------------- --------------- // | | | | ---------------...- // | count | | segments[1] |------>| Segment 1 ... | // | | | | ---------------...- // ---------------- --------------- // | | ---------------...- // | segments[2] |------>| Segment 2 ... | // | | ---------------...- // |---- .... ---| // | | ---------------...- // | segments[N] |------>| Segment 3 ... | // | | ---------------...- // --------------- class Deque { // Pointer to the array of segment pointers. DequeSegment** segments; // Size of the array of segment pointers. int count; public: Deque() : segments(new DequeSegment*[0]) , count(0) {} ~Deque() { for(int i = 0; i < count; ++i) delete segments[i]; delete[] segments; } // Add an element to the back of the Deque. // May need to allocate a new Segment. void PushBack(int value) { // If there are no segments, or if the last segment // is full, add a new segment if(0 == count || segments[count-1]->last == segments[count-1]->data + DequeSegmentSize) { DequeSegment* s = new DequeSegment(0); DequeSegment** segs = new DequeSegment*[count+1], ** tmp; for(int i = 0; i < count; ++i) segs[i] = segments[i]; segs[count++] = s; assert(segs[0]->first); tmp = segments; segments = segs; delete[] tmp; } // Get the last segment DequeSegment* s = segments[count-1]; // Write into the last position, and increment // the last position. *s->last++ = value; } // Remove an element from the front of the Deque. // May deallocate a Segment. void PopFront() { assert(0 != count && segments[0]->first != segments[0]->data + DequeSegmentSize); if(++segments[0]->first == segments[0]->data + DequeSegmentSize) { DequeSegment** segs = new DequeSegment*[count-1], ** tmp; for(int i = 1; i < count; ++i) segs[i-1] = segments[i]; --count; tmp = segments; segments = segs; delete tmp[0]; delete[] tmp; } } int* Transform(int (*pfun)(int), int* out) const { DequeSegment** s = segments, **send = s + count; for(; s != send; ++s) { int* last = (*s)->last; for(int* j = (*s)->first; j != last; ++j) *out++ = pfun(*j); } return out; } int& GetAt(int i) { assert(0 != count); i -= segments[0]->last - segments[0]->first; if(i < 0) return *(segments[0]->last + i); else return *(segments[1+i/DequeSegmentSize]->first + i%DequeSegmentSize); } int* Find(int value) { if(0 == count) return 0; DequeSegment** s = segments, **send = s + count; for(; s != send; ++s) { int* last = (*s)->last; for(int* j = (*s)->first; j != last; ++j) if(value == *j) return j; } return 0; } }; #endif
9ae1ddb601518544f6efcae96bce5093a6b853ec
65ff94add5bec27c4fcf2006809dc9b9b8c788f1
/src/core/router/transports/ssu/packet.cc
ba20de79eba60af5872dcf36b1cdddf271161c5b
[ "BSD-3-Clause" ]
permissive
anonimal/kovri
6e4c8c9b24ab597c783f55b75ffc8e2de6f12df2
3fa695156d287d05924ab29fc33f491e562b3b59
refs/heads/master
2020-04-05T19:26:30.555894
2018-08-05T22:12:24
2018-08-05T22:12:24
50,646,302
0
1
null
2018-07-30T22:16:53
2016-01-29T07:31:37
C++
UTF-8
C++
false
false
16,014
cc
packet.cc
/** * Copyright (c) 2015-2018, The Kovri I2P Router Project * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/router/transports/ssu/packet.h" #include <exception> #include "core/crypto/rand.h" #include "core/router/transports/ssu/data.h" #include "core/util/log.h" #include "core/util/timestamp.h" namespace kovri { namespace core { // TODO(unassigned): move out of unit file std::size_t SSUSessionConfirmedPacket::get_size() const noexcept { // This message must be a multiple of 16 return SSUPacketBuilder::get_padded_size( SSUPacket::get_size() + 3 // Info and identity size + m_RemoteIdentity.GetFullLen() // Identity + m_RemoteIdentity.GetSignatureLen() // Signature + 4); // Time size } /** * * Header processing * */ SSUHeader::SSUHeader() : SSUHeader(SSUPayloadType::Unknown) {} SSUHeader::SSUHeader(const SSUPayloadType type) : SSUHeader(type, nullptr, nullptr, 0) {} SSUHeader::SSUHeader( const SSUPayloadType type, std::uint8_t* mac, std::uint8_t* iv, const std::uint32_t time) : m_MAC(mac), m_IV(iv), m_ExtendedOptions(nullptr), m_Rekey(false), m_Extended(false), m_Time(time), m_PayloadType(type), m_ExtendedOptionsSize(0) {} /** * * Packet parsing implementation * */ SSUPacketParser::SSUPacketParser( std::uint8_t* data, const std::size_t len) : InputByteStream(data, len) {} SSUFragment SSUPacketParser::ParseFragment() { // Patch for #823 so we can keep running with assertions if (gcount() < 4 /* message ID */ + 3 /* fragment info */) throw std::length_error( "SSUPacketParser: invalid packet size, fragment unavailable"); SSUFragment fragment; fragment.set_msg_id(Read<std::uint32_t>()); // TODO(unassigned): we should not setup a 4 byte array to parse 3 bytes // and ByteStream should consider having a std::bitset implementation. std::array<std::uint8_t, 4> info_buf {{}}; memcpy(info_buf.data() + 1, ReadBytes(3), 3); const std::uint32_t fragment_info = Read<std::uint32_t>(info_buf.data()); fragment.set_size(fragment_info & 0x3FFF); // bits 0 - 13 // bits 15-14: unused, set to 0 for compatibility with future uses fragment.set_is_last(fragment_info & 0x010000); // bit 16 fragment.set_num(fragment_info >> 17); // bits 23 - 17 std::uint16_t const frag_size = fragment.get_size(); // End session if fragmented size is greater than buffer size if (frag_size > gcount()) { // TODO(anonimal): invalid size could be an implementation issue rather // than an attack. Reconsider how we mitigate invalid fragment size. throw std::length_error("SSUPacketParser: invalid fragment size"); } // Don't read if purported size is 0 if (frag_size) fragment.set_data(ReadBytes(frag_size)); return fragment; } std::unique_ptr<SSUHeader> SSUPacketParser::ParseHeader() { if (m_Length < SSUSize::HeaderMin) throw std::length_error("SSU header too small"); auto header = std::make_unique<SSUHeader>(); // Set MAC and IV header->set_mac(ReadBytes(SSUSize::MAC)); header->set_iv(ReadBytes(SSUSize::IV)); // Extract information from flag (payload type and rekey/extened options) const std::uint8_t flag = Read<std::uint8_t>(); header->set_rekey(flag & SSUFlag::Rekey); header->set_ext_opts(flag & SSUFlag::ExtendedOptions); header->set_payload_type(flag >> 4); // Extract the time header->set_time(Read<std::uint32_t>()); if (header->has_rekey()) { // TODO(EinMByte): Actually do something with the data // TODO(EinMByte): See issue #119, for some reason some rekey options // are sometimes set? SkipBytes(SSUSize::KeyingMaterial); } if (header->has_ext_opts()) { const std::size_t options_size = Read<std::uint8_t>(); header->set_ext_opts_data(ReadBytes(options_size), options_size); } return header; } std::unique_ptr<SSUPacket> SSUPacketParser::ParsePacket() { m_Header = ParseHeader(); std::unique_ptr<SSUPacket> packet; std::uint8_t* const old_data = m_DataPtr; const std::size_t old_length = m_Length; switch (m_Header->get_payload_type()) { case SSUPayloadType::SessionRequest: packet = ParseSessionRequest(); break; case SSUPayloadType::SessionCreated: packet = ParseSessionCreated(); break; case SSUPayloadType::SessionConfirmed: packet = ParseSessionConfirmed(); break; case SSUPayloadType::RelayRequest: packet = ParseRelayRequest(); break; case SSUPayloadType::RelayResponse: packet = ParseRelayResponse(); break; case SSUPayloadType::RelayIntro: packet = ParseRelayIntro(); break; case SSUPayloadType::Data: packet = ParseData(); break; case SSUPayloadType::PeerTest: packet = ParsePeerTest(); break; case SSUPayloadType::SessionDestroyed: packet = ParseSessionDestroyed(); break; case SSUPayloadType::Unknown: default: throw std::runtime_error("SSUPacketParser: unknown payload type"); } // TODO(EinMByte): Get rid of this packet->m_RawDataLength = old_length; packet->m_RawData = old_data; packet->set_header(std::move(m_Header)); return packet; } std::unique_ptr<SSUSessionRequestPacket> SSUPacketParser::ParseSessionRequest() { auto packet = std::make_unique<SSUSessionRequestPacket>(); packet->set_dh_x(ReadBytes(SSUSize::DHPublic)); std::uint8_t const size = Read<std::uint8_t>(); packet->set_ip(ReadBytes(size), size); return packet; } std::unique_ptr<SSUSessionCreatedPacket> SSUPacketParser::ParseSessionCreated() { auto packet = std::make_unique<SSUSessionCreatedPacket>(); packet->set_dh_y(ReadBytes(SSUSize::DHPublic)); std::uint8_t const address_size = Read<std::uint8_t>(); packet->set_ip(ReadBytes(address_size), address_size); packet->set_port(Read<std::uint16_t>()); packet->set_relay_tag(Read<std::uint32_t>()); packet->set_time(Read<std::uint32_t>()); packet->set_sig(m_DataPtr, m_Length); return packet; } std::unique_ptr<SSUSessionConfirmedPacket> SSUPacketParser::ParseSessionConfirmed() { const std::size_t init_length = m_Length; auto packet = std::make_unique<SSUSessionConfirmedPacket>(); SkipBytes(1); // Info byte std::uint16_t identity_size = Read<std::uint16_t>(); kovri::core::IdentityEx identity; if (!identity.FromBuffer(ReadBytes(identity_size), identity_size)) throw std::length_error("SSUPacketParser: invalid length within identity"); packet->set_remote_ident(identity); packet->set_time(Read<std::uint32_t>()); const std::size_t padding_size = SSUPacketBuilder::get_padding_size( m_Header->get_size() + init_length - m_Length + identity.GetSignatureLen()); SkipBytes(padding_size); // Padding packet->set_sig(m_DataPtr); return packet; } std::unique_ptr<SSURelayRequestPacket> SSUPacketParser::ParseRelayRequest() { auto packet = std::make_unique<SSURelayRequestPacket>(); packet->set_relay_tag(Read<std::uint32_t>()); std::uint8_t const address_size = Read<std::uint8_t>(); packet->set_ip(ReadBytes(address_size), address_size); packet->set_port(Read<std::uint16_t>()); const std::size_t challenge_size = Read<std::uint8_t>(); packet->set_challenge(ReadBytes(challenge_size), challenge_size); packet->set_intro_key(ReadBytes(SSUSize::IntroKey)); packet->set_nonce(Read<std::uint32_t>()); return packet; } std::unique_ptr<SSURelayResponsePacket> SSUPacketParser::ParseRelayResponse() { auto packet = std::make_unique<SSURelayResponsePacket>(); std::uint8_t const charlie_address_size = Read<std::uint8_t>(); packet->set_charlie_ip(ReadBytes(charlie_address_size), charlie_address_size); packet->set_charlie_port(Read<std::uint16_t>()); std::uint8_t const alice_address_size = Read<std::uint8_t>(); packet->set_alice_ip(ReadBytes(alice_address_size), alice_address_size); packet->set_alice_port(Read<std::uint16_t>()); packet->set_nonce(Read<std::uint32_t>()); return packet; } std::unique_ptr<SSURelayIntroPacket> SSUPacketParser::ParseRelayIntro() { auto packet = std::make_unique<SSURelayIntroPacket>(); std::uint8_t const address_size = Read<std::uint8_t>(); packet->set_ip(ReadBytes(address_size), address_size); packet->set_port(Read<std::uint16_t>()); const std::size_t challenge_size = Read<std::uint8_t>(); packet->set_challenge(ReadBytes(challenge_size), challenge_size); return packet; } std::unique_ptr<SSUDataPacket> SSUPacketParser::ParseData() { auto packet = std::make_unique<SSUDataPacket>(); const std::uint8_t flags = Read<std::uint8_t>(); // Read ACKS if (flags & SSUFlag::DataExplicitACKsIncluded) { const std::size_t nb_explicit_ACKs = Read<std::uint8_t>(); for(std::size_t i = 0; i < nb_explicit_ACKs; ++i) packet->AddExplicitACK(Read<std::uint32_t>()); } // Read ACK bifields if (flags & SSUFlag::DataACKBitfieldsIncluded) { const std::size_t nb_ACKs = Read<std::uint8_t>(); // Read message IDs for (std::size_t i = 0; i < nb_ACKs; ++i) packet->AddACK(Read<std::uint32_t>()); // Read bitfields std::uint8_t bitfield; do { bitfield = Read<std::uint8_t>(); packet->AddACKBitfield(bitfield); } while (bitfield & SSUFlag::DataACKBitFieldHasNext); } // Ignore possible extended data if (flags & SSUFlag::DataExtendedIncluded) SkipBytes(Read<std::uint8_t>()); const std::size_t nb_flags = Read<std::uint8_t>(); // Read fragments for(std::size_t i = 0; i < nb_flags; ++i) packet->AddFragment(ParseFragment()); return packet; } std::unique_ptr<SSUPeerTestPacket> SSUPacketParser::ParsePeerTest() { auto packet = std::make_unique<SSUPeerTestPacket>(); packet->set_nonce(Read<std::uint32_t>()); std::uint8_t const size(Read<std::uint8_t>()); if (size) // Bob or Charlie packet->set_ip(core::BytesToAddress(ReadBytes(size), size)); packet->set_ip_size(size); packet->set_port(Read<std::uint16_t>()); packet->set_intro_key(ReadBytes(SSUSize::IntroKey)); return packet; } std::unique_ptr<SSUSessionDestroyedPacket> SSUPacketParser::ParseSessionDestroyed() { auto packet = std::make_unique<SSUSessionDestroyedPacket>(); return packet; } SSUPacketBuilder::SSUPacketBuilder( std::uint8_t* data, const std::size_t len) : OutputByteStream(data, len) {} void SSUPacketBuilder::WriteHeader(SSUHeader* header) { if (header->get_mac()) WriteData(header->get_mac(), SSUSize::MAC); else SkipBytes(SSUSize::MAC); // Write real MAC later WriteData(header->get_iv(), SSUSize::IV); const std::uint8_t flag = (header->get_payload_type() << 4) + (header->has_rekey() << 3) + (header->has_ext_opts() << 2); Write<std::uint8_t>(flag); Write<std::uint32_t>(header->get_time()); if (header->has_ext_opts()) { Write<std::uint8_t>(header->get_ext_opts_size()); WriteData( header->get_ext_opts_data(), header->get_ext_opts_size()); } } void SSUPacketBuilder::WriteSessionRequest(SSUSessionRequestPacket* packet) { WriteData(packet->get_dh_x(), SSUSize::DHPublic); Write<std::uint8_t>(packet->get_ip_size()); WriteData(packet->get_ip(), packet->get_ip_size()); } void SSUPacketBuilder::WriteSessionCreated(SSUSessionCreatedPacket* packet) { WriteData(packet->get_dh_y(), SSUSize::DHPublic); Write<std::uint8_t>(packet->get_ip_size()); WriteData(packet->get_ip(), packet->get_ip_size()); Write<std::uint16_t>(packet->get_port()); Write<std::uint32_t>(packet->get_relay_tag()); Write<std::uint32_t>(packet->get_time()); WriteData(packet->get_sig(), packet->get_sig_size()); } void SSUPacketBuilder::WriteSessionConfirmed( SSUSessionConfirmedPacket* packet) { const std::uint8_t* const begin = tellp(); Write<std::uint8_t>(0x01); // 1 byte info, with 1 fragment const std::size_t identity_size = packet->get_remote_ident().GetFullLen(); Write<std::uint16_t>(identity_size); std::uint8_t* const identity = m_DataPtr; SkipBytes(identity_size); packet->get_remote_ident().ToBuffer(identity, identity_size); Write<std::uint32_t>(packet->get_time()); // Write padding here (rather than later), because it is in the middle of the // message const std::size_t signature_size = packet->get_remote_ident().GetSignatureLen(); const std::size_t padding_size = get_padding_size( packet->get_header()->get_size() + tellp() - begin + signature_size); std::uint8_t* const padding = m_DataPtr; SkipBytes(padding_size); kovri::core::RandBytes(padding, padding_size); WriteData(packet->get_sig(), signature_size); } void SSUPacketBuilder::WriteRelayRequest( SSURelayRequestPacket* /*packet*/) {} void SSUPacketBuilder::WriteRelayResponse( SSURelayResponsePacket* /*packet*/) {} void SSUPacketBuilder::WriteRelayIntro( SSURelayIntroPacket* /*packet*/) {} void SSUPacketBuilder::WriteDataMessage( SSUDataPacket* /*packet*/) {} void SSUPacketBuilder::WritePeerTest( SSUPeerTestPacket* /*packet*/) {} void SSUPacketBuilder::WriteSessionDestroyed( SSUSessionDestroyedPacket* /*packet*/) {} void SSUPacketBuilder::WritePacket(SSUPacket* packet) { switch (packet->get_header()->get_payload_type()) { case SSUPayloadType::SessionRequest: WriteSessionRequest(static_cast<SSUSessionRequestPacket*>(packet)); break; case SSUPayloadType::SessionCreated: WriteSessionCreated(static_cast<SSUSessionCreatedPacket*>(packet)); break; case SSUPayloadType::SessionConfirmed: WriteSessionConfirmed(static_cast<SSUSessionConfirmedPacket*>(packet)); break; case SSUPayloadType::RelayRequest: WriteRelayRequest(static_cast<SSURelayRequestPacket*>(packet)); break; case SSUPayloadType::RelayResponse: WriteRelayResponse(static_cast<SSURelayResponsePacket*>(packet)); break; case SSUPayloadType::RelayIntro: WriteRelayIntro(static_cast<SSURelayIntroPacket*>(packet)); break; case SSUPayloadType::Data: WriteDataMessage(static_cast<SSUDataPacket*>(packet)); break; case SSUPayloadType::PeerTest: WritePeerTest(static_cast<SSUPeerTestPacket*>(packet)); break; case SSUPayloadType::SessionDestroyed: WriteSessionDestroyed(static_cast<SSUSessionDestroyedPacket*>(packet)); break; case SSUPayloadType::Unknown: default: throw std::runtime_error("SSUPacketBuilder: unknown payload type"); } } } // namespace core } // namespace kovri
21378bad63a04199c008fbe1706bfe0a02241f68
6ca029e4b3242d19360a51d6e3941bab31c6163b
/src/vscp/common/udpsrv.h
daa4bb154bc0d1906d14651ed3f42a10263ac418
[ "MIT" ]
permissive
grodansparadis/vscp
d9246e4762f5d9653e5c037dfea854fc64e78fbd
57f7202ff305118db16b5be29424cb69b0b47549
refs/heads/master
2023-07-10T01:40:41.117634
2023-06-27T13:25:36
2023-06-27T13:25:36
5,659,452
42
21
null
2017-12-29T17:18:38
2012-09-03T13:46:36
C
UTF-8
C++
false
false
6,963
h
udpsrv.h
// udpsrv.h // // This file is part of the VSCP (https://www.vscp.org) // // The MIT License (MIT) // // Copyright © 2000-2022 Ake Hedman, the VSCP project // <info@vscp.org> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if !defined(UDPCLIENTTHREAD_H__INCLUDED_) #define UDPCLIENTTHREAD_H__INCLUDED_ #include <guid.h> #include <vscp.h> #include <arpa/inet.h> #include <stdlib.h> #include <syslog.h> #include <unistd.h> #include <string> class CControlObject; class CClientItem; // Prototypes void* udpSrvWorkerThread(void* pData); void* udpClientWorkerThread(void* pData); #define UDP_MAX_PACKAGE 2048 // Remote UDP Client structure. One is defined for each // remote client. class udpRemoteClient { public: /*! CTOR @param Pointer to control object */ udpRemoteClient(); // DTOR ~udpRemoteClient(); /*! Initialize the UDP remote client @param pobj Pointer to control object @param host Host to connect to @param port Port on host to connect to. @param nEncryption Encryption to use. None, AES128, AES192, AES256 @param bBroadcast True to set broadcast bit on sent frame. @return VSCP_ERROR_SUCCESS if all goes well, otherwise error. */ int init(CControlObject* pobj, uint8_t nEncryption = VSCP_ENCRYPTION_NONE, bool bSetBroadcast = false); /*! Start the client worker thread @return True on success, false on failure. */ bool startWorkerThread(void); /*! Send event to UDP remote client */ int sendFrame(void); // Getter/setters void enable(bool bEnable = true) { m_bEnable = bEnable; } void setRemoteAddress(const std::string& remoteAddress) { m_remoteAddress = remoteAddress; } std::string getRemoteAddress(void) { return m_remoteAddress; } void setRemotePort(int16_t remotePort) { m_remotePort = remotePort; } int16_t getRemotePort(void) { return m_remotePort; } void setUser(const std::string& user) { m_user = user; } std::string getUser(void) { return m_user; } void setEncryption(uint8_t encryption = VSCP_ENCRYPTION_NONE) { if (encryption <= VSCP_ENCRYPTION_AES256) m_nEncryption = encryption; }; uint8_t getEncryption(void) { return m_nEncryption; } void SetBroadcastBit(bool enable = true) { m_bSetBroadcast = enable; } bool isBroadCastBitSet(void) { return m_bSetBroadcast; } void setFilter(const vscpEventFilter& filter) { memcpy(&m_filter, &filter, sizeof(vscpEventFilter)); } // Assign control object void setControlObjectPointer(CControlObject* pCtrlObj) { m_pCtrlObj = pCtrlObj; } public: // Client thread will run as long as false bool m_bQuit; // Client we are working as CClientItem* m_pClientItem; // The global control object CControlObject* m_pCtrlObj; public: bool m_bEnable; int m_sockfd; struct sockaddr_in m_clientAddress; // Interface to connect to std::string m_remoteAddress; int16_t m_remotePort; vscpEventFilter m_filter; // Outgoing filter for this remote client. cguid m_guid; // GUID for outgoing channel. std::string m_user; // user the client act as std::string m_password; // Password for user we act as uint8_t m_nEncryption; // Encryption algorithm bool m_bSetBroadcast; // Set broadcast flag MG_F_ENABLE_BROADCAST. uint8_t m_index; // Rolling send index // (only low tree bits used). // The thread that do the actual sending pthread_t m_udpClientWorkerThread; }; /*! This class implement the listen thread for the vscpd connections on the UDP interface */ class udpSrvObj { public: /// Constructor udpSrvObj(); /// Destructor ~udpSrvObj(); /*! Init UDP server object @param pobj Pointer to VSCP daemon control object */ void init(CControlObject* pobj) { m_pCtrlObj = pobj; } /*! * Receive UDP frame * * @param sockfd UDP socket descriptor for listening socket. * @param pClientItem Client item for this user. Normally "UDP" * @return VSCP_ERROR_SUCCESS on success, errorcode on failure. */ int receiveFrame(int sockfd, CClientItem* pClientItem); /*! * Send ACK reply * * @param pkttype Packet type * @param index Running index 0-7 * @return VSCP_ERROR_SUCCESS on success, errorcode on failure. */ int replyAckFrame(struct sockaddr* to, uint8_t pkttype, uint8_t index); /*! * Send NACK reply * * @param pkttype Packet type * @param index Running index 0-7 * @return VSCP_ERROR_SUCCESS on success, errorcode on failure. */ int replyNackFrame(struct sockaddr* to, uint8_t pkttype, uint8_t index); // Assign control object void setControlObjectPointer(CControlObject* pCtrlObj) { m_pCtrlObj = pCtrlObj; } // --- Member variables --- // Mutex that protect the UDP info structure pthread_mutex_t m_mutexUDPInfo; bool m_bQuit; bool m_bEnable; // Enable UDP std::string m_interface; // Interface to bind to "UDP://33333" struct sockaddr_in m_servaddr; // Bind address + port int m_sockfd; // Socket used to send ACK/NACK) bool m_bAllowUnsecure; // Allow un encrypted datagrams bool m_bAck; // ACK received datagram std::string m_user; // User account to use for UDP std::string m_password; // Password for user account cguid m_guid; // GUID to use for server client object vscpEventFilter m_filter; // Filter for incoming events // UDP Client item CClientItem* m_pClientItem; // The global control object CControlObject* m_pCtrlObj; }; #endif
b972ccb3fc0e6d6e08195a2e78fb42a3a65626f0
15dea4de84765fd04efb0367247e94657e76515b
/source/3rdparty/won/Firewall/FirewallAPI.cpp
a48ef8c7b0afae85d12442eba1a10852718db527
[]
no_license
dppereyra/darkreign2
4893a628a89642121d230e6e02aa353636566be8
85c83fdbb4b4e32aa5f816ebfcaf286b5457a11d
refs/heads/master
2020-12-30T13:22:17.657084
2017-01-30T21:20:28
2017-01-30T21:20:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,516
cpp
FirewallAPI.cpp
#include "FirewallAPI.h" #include "Socket/TCPSocket.h" #include "Socket/TMsgSocket.h" #include "msg/Firewall/SMsgFirewallDetect.h" #include "msg/Firewall/SMsgFirewallStatusReply.h" #include <iostream> using namespace WONAPI; using namespace WONMsg; using namespace WONCommon; class DetectFirewallData { public: Error error; TCPSocket listenSocket; TCPSocket tcpSocket; TCPSocket acceptedSocket; TMsgSocket tMsgSocket; TMsgSocket tMsgAcceptedSocket; bool autoDelete; Event doneEvent; bool tempIsBehindFirewall; bool* behindFirewall; long timeout; CompletionContainer<const DetectFirewallResult&> completion; SMsgFirewallDetect msg; CriticalSection crit; int stageCount; DetectFirewallData() : tMsgSocket(&tcpSocket, false, 2), tMsgAcceptedSocket(&acceptedSocket, false, 2), stageCount(0) { } void Done() { if (error != Error_Success) *(behindFirewall) = false; completion.Complete(DetectFirewallResult(error, behindFirewall)); if (autoDelete) delete this; else doneEvent.Set(); } }; void DetectFirewallAcceptedDoneRecv(const TMsgSocket::RecvBaseMsgResult& result, DetectFirewallData* detectFirewallData) { AutoCrit crit(detectFirewallData->crit); if (!result.msg) { if (result.closed) detectFirewallData->error = Error_ConnectionClosed; } else { try { SMsgFirewallStatusReply reply(*(SmallMessage*)(result.msg)); reply.Unpack(); if (reply.GetStatus() == 2100) // StatusFirewallSuccessConnect detectFirewallData->error = Error_Success; else detectFirewallData->error = Error_InvalidMessage; } catch (...) { detectFirewallData->error = Error_InvalidMessage; } delete result.msg; } // Might have gotten this before recving a message on the accepted socket if (detectFirewallData->stageCount == 2) { crit.Leave(); detectFirewallData->Done(); } else { detectFirewallData->stageCount++; detectFirewallData->listenSocket.Close(0); } } void DetectFirewallDoneRecv(const TMsgSocket::RecvBaseMsgResult& result, DetectFirewallData* detectFirewallData) { AutoCrit crit(detectFirewallData->crit); if (!result.msg) { if (!result.closed) detectFirewallData->error = Error_ConnectionClosed; } else { try { SMsgFirewallStatusReply reply(*(SmallMessage*)(result.msg)); reply.Unpack(); if (reply.GetStatus()) // != success *(detectFirewallData->behindFirewall) = true; detectFirewallData->error = Error_Success; } catch (...) { detectFirewallData->error = Error_InvalidMessage; } delete result.msg; } // Might have gotten this before recving a message on the accepted socket if (detectFirewallData->stageCount == 2) { crit.Leave(); detectFirewallData->Done(); } else { detectFirewallData->stageCount++; detectFirewallData->listenSocket.Close(0); } } void DetectFirewallDoneAccept(const WSSocket::AcceptResult& result, DetectFirewallData* detectFirewallData) { AutoCrit crit(detectFirewallData->crit); if (detectFirewallData->acceptedSocket.IsOpen()) { detectFirewallData->stageCount++; detectFirewallData->tMsgAcceptedSocket.RecvBaseMsgEx(NULL, detectFirewallData->timeout, true, DetectFirewallAcceptedDoneRecv, detectFirewallData); } else { *(detectFirewallData->behindFirewall) = true; if (detectFirewallData->stageCount == 1) { // Must have gotten a fail reply, which caused an Accept to complete when the socket closed crit.Leave(); detectFirewallData->Done(); } else { detectFirewallData->stageCount += 2; detectFirewallData->listenSocket.Close(0); } } } void DetectFirewallDoneOpen(const Socket::OpenResult& result, DetectFirewallData* detectFirewallData) { if (result.error != Error_Success) { detectFirewallData->error = result.error; detectFirewallData->Done(); return; } detectFirewallData->listenSocket.AcceptEx(&(detectFirewallData->acceptedSocket), detectFirewallData->timeout, true, DetectFirewallDoneAccept, detectFirewallData); unsigned short port = detectFirewallData->listenSocket.GetLocalAddress().GetPort(); detectFirewallData->msg.SetListenPort(port); detectFirewallData->msg.SetWaitForConnect(true); detectFirewallData->msg.SetMaxConnectTime(0); detectFirewallData->tMsgSocket.SendBaseMsg(detectFirewallData->msg, detectFirewallData->timeout, true); detectFirewallData->tMsgSocket.RecvBaseMsgEx(NULL, detectFirewallData->timeout, true, DetectFirewallDoneRecv, detectFirewallData); } Error WONAPI::DetectFirewall(const IPSocket::Address& firewallDetectionServerAddr, bool* behindFirewall, unsigned short useListenPort, long timeout, bool async, const CompletionContainer<const DetectFirewallResult&>& completion) { bool tmp = false; if (behindFirewall) *behindFirewall = false; DetectFirewallData* detectFirewallData = new DetectFirewallData; if (!detectFirewallData) { completion.Complete(DetectFirewallResult(Error_OutOfMemory, behindFirewall ? behindFirewall : &tmp)); return Error_OutOfMemory; } Error listenErr = detectFirewallData->listenSocket.Listen(useListenPort); if (listenErr != Error_Success) { delete detectFirewallData; completion.Complete(DetectFirewallResult(listenErr, behindFirewall ? behindFirewall : &tmp)); return listenErr; } detectFirewallData->autoDelete = async; detectFirewallData->behindFirewall = behindFirewall ? behindFirewall : &(detectFirewallData->tempIsBehindFirewall); *(detectFirewallData->behindFirewall) = false; detectFirewallData->completion = completion; detectFirewallData->timeout = timeout; detectFirewallData->error = Error_Timeout; detectFirewallData->tcpSocket.OpenEx(&firewallDetectionServerAddr, timeout, true, DetectFirewallDoneOpen, detectFirewallData); Error err = Error_Pending; if (!async) { WSSocket::PumpUntil(detectFirewallData->doneEvent, timeout); //detectFirewallData->doneEvent.WaitFor(); err = detectFirewallData->error; delete detectFirewallData; } return err; } class DetectFirewallFailoverData { public: IPSocket::Address* addrs; unsigned short curAddr; unsigned short numAddrs; bool* behindFirewall; unsigned short useListenPort; long timeout; Event doneEvent; bool autoDel; Error err; CompletionContainer<const DetectFirewallResult&> completion; void Done(const DetectFirewallResult& result) { err = result.error; completion.Complete(result); if (autoDel) delete this; else doneEvent.Set(); } ~DetectFirewallFailoverData() { delete[] addrs; } }; static void DoneDetectFirewallFailover(const DetectFirewallResult& result, DetectFirewallFailoverData* failoverData) { if (result.error != Error_Success) { if (++(failoverData->curAddr) != failoverData->numAddrs) { DetectFirewallEx(failoverData->addrs[failoverData->curAddr], failoverData->behindFirewall, failoverData->useListenPort, failoverData->timeout, true, DoneDetectFirewallFailover, failoverData); return; } } failoverData->Done(result); } Error WONAPI::DetectFirewall(const IPSocket::Address* firewallDetectionServerAddrs, unsigned short numAddrs, bool* behindFirewall, unsigned short useListenPort, long timeout, bool async, const CompletionContainer<const DetectFirewallResult&>& completion) { bool tmp = false; if (behindFirewall) *behindFirewall = false; if (!firewallDetectionServerAddrs || !numAddrs) { completion.Complete(DetectFirewallResult(Error_InvalidParams, behindFirewall ? behindFirewall : &tmp)); return Error_InvalidParams; } IPSocket::Address* addrs = new IPSocket::Address[numAddrs]; if (!addrs) { completion.Complete(DetectFirewallResult(Error_OutOfMemory, behindFirewall ? behindFirewall : &tmp)); return Error_OutOfMemory; } DetectFirewallFailoverData* failoverData = new DetectFirewallFailoverData; if (!failoverData) { delete[] addrs; completion.Complete(DetectFirewallResult(Error_OutOfMemory, behindFirewall ? behindFirewall : &tmp)); return Error_OutOfMemory; } failoverData->addrs = addrs; failoverData->numAddrs = numAddrs; failoverData->behindFirewall = behindFirewall; failoverData->useListenPort = useListenPort; failoverData->timeout = timeout; failoverData->autoDel = async; failoverData->curAddr = 0; failoverData->completion = completion; for (unsigned short s = 0; s < numAddrs; s++) addrs[s] = firewallDetectionServerAddrs[s]; DetectFirewallEx(addrs[0], behindFirewall, useListenPort, timeout, true, DoneDetectFirewallFailover, failoverData); Error err = Error_Pending; if (!async) { WSSocket::PumpUntil(failoverData->doneEvent, timeout); // failoverData->doneEvent.WaitFor(); err = failoverData->err; delete failoverData; } return err; } #include "wondll.h" WONError WONFirewallDetect(const WONIPAddress* firewallDetectorServers, unsigned int numAddrs, BOOL* behindFirewall, unsigned short listenPort, long timeout) { Error err = Error_InvalidParams; if (numAddrs && firewallDetectorServers && behindFirewall) { err = Error_OutOfMemory; IPSocket::Address* srvAddrs = new IPSocket::Address[numAddrs]; if (srvAddrs) { array_auto_ptr<IPSocket::Address> autoSrvAddrs(srvAddrs); for (int i = 0; i < numAddrs; i++) srvAddrs[i].Set(firewallDetectorServers[i]); bool b; err = DetectFirewall(srvAddrs, numAddrs, &b, listenPort, timeout); *behindFirewall = b ? TRUE : FALSE; } } return err; } static void TranslateFirewallDetectCompletion(const WONAPI::DetectFirewallResult& result, std::pair<HWONCOMPLETION, BOOL*> pr) { BOOL* bPtr = pr.second; *bPtr = result.behindFirewall ? TRUE : FALSE; delete result.behindFirewall; WONComplete(pr.first, (void*)result.error); }; void WONFirewallDetectAsync(WON_CONST WONIPAddress* firewallDetectorServers, unsigned int numAddrs, BOOL* behindFirewall, unsigned short listenPort, long timeout, HWONCOMPLETION hCompletion) { Error err = Error_InvalidParams; if (numAddrs && firewallDetectorServers && behindFirewall) { err = Error_OutOfMemory; IPSocket::Address* srvAddrs = new IPSocket::Address[numAddrs]; if (srvAddrs) { array_auto_ptr<IPSocket::Address> autoSrvAddrs(srvAddrs); bool* result = new bool; if (result) { for (int i = 0; i < numAddrs; i++) srvAddrs[i].Set(firewallDetectorServers[i]); err = DetectFirewallEx(srvAddrs, numAddrs, result, listenPort, timeout, true, TranslateFirewallDetectCompletion, std::pair<HWONCOMPLETION, BOOL*>(hCompletion, behindFirewall)); return; } } } WONComplete(hCompletion, (void*)err); }
87c977ddf0936e25c17effd0286ba0cde21dfe06
2623da23ebf4385795543e42a07104e0bc9aa9e0
/src/engine.cpp
beefaf5fb3053bfd0c961e6e2a714e0746a824fb
[]
no_license
tathougies/eva
660e9a877cb04b447ec6f8620ed3824e8f0d51b0
e4d24c4a3f32df003d22e4402026af065619ad85
refs/heads/master
2020-12-31T22:54:05.152176
2020-02-08T03:38:41
2020-02-08T03:38:41
239,063,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
cpp
engine.cpp
#include "engine.hpp" namespace eva { IEngineSubmission::~IEngineSubmission() { } StreamSource::StreamSource(Engine &engine, const interned_string &moduleName) : m_engine(engine), m_submission(engine.registerStreamSource(this)), m_module(moduleName) { } StreamSource::~StreamSource() { } Engine::Engine(Allocator &allocator) : m_allocator(allocator) { } Engine::~Engine() { } void Engine::addEngineObserver(const std::shared_ptr<IEngineObserver> &observer) { boost::upgrade_lock observersLock(m_observersMutex); if ( m_observers.find(observer) == m_observers.end() ) { boost::upgrade_to_unique_lock observersWriteLock(observersLock); m_observers.insert(observer); } } void Engine::removeEngineObserver(const std::shared_ptr<IEngineObserver> &observer) { boost::unique_lock observersLock(m_observersMutex); auto place(m_observers.find(observer)); if ( place != m_observers.end() ) { m_observers.erase(place) } } IEngineSubmission &Engine::registerStreamSource(StreamSource *src) { _ } void Engine::releaseStreamSource(StreamSource *src) { } }
e97d6de80952b11b8883b9fc84486350d3046860
6eeb2ace34ce205bf25cf99993a0972aa38859f3
/Assignments/Assignment_01/Node.h
62b7a1c6584fa90e5cb08240fb47b317fbf436ac
[]
no_license
mattjmoses/DataStructures
05020529bd6432a8d84ee687c01417c782ca623f
f4acbb664a705e3a60e1a3b1530117edfce31958
refs/heads/master
2021-05-13T11:54:45.142914
2018-04-16T23:18:59
2018-04-16T23:18:59
117,143,816
0
0
null
null
null
null
UTF-8
C++
false
false
411
h
Node.h
// // Created by Matt on 2018-01-10. // #ifndef ASSIGNMENT_01_NODE_H #define ASSIGNMENT_01_NODE_H #include<string> using namespace std; //Here's our node class which handles all the data and pointers on the nodes. class Node { public: string nodeData; //This contains the text data in the node. Node *nodePtr; //This node points to the next node in the chain. }; #endif //ASSIGNMENT_01_NODE_H
2fc04875981e76e9f33c9dfce49466dde3b63c9e
24f26275ffcd9324998d7570ea9fda82578eeb9e
/base/task/promise/promise_value.cc
23d501bb00124b099ae5121c5b3fd42ecdb0cd46
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
638
cc
promise_value.cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/task/promise/promise_value.h" #include "base/task/promise/abstract_promise.h" namespace base { namespace internal { // static void PromiseValueInternal::NopMove(PromiseValueInternal* src, PromiseValueInternal* dest) {} // static void PromiseValueInternal::NopDelete(PromiseValueInternal* src) {} constexpr PromiseValueInternal::TypeOps PromiseValueInternal::null_type_; } // namespace internal } // namespace base
294d1b28285c81d6cd891b7edba98ff26ee7d75c
a62153d5ac82729f228e2dc854aea325e3afad6d
/ESTAssemblyC++/Graph.cpp
22d5671396948bcf5a88eb4c9c7dea827f0a43f5
[]
no_license
dhungvi/mytestpjt
17d95a8180be59988cde3e88f2a0694064951b0b
4ede2b72ec28fce9cc909c01b5cf89463b645e03
refs/heads/master
2021-01-01T06:55:18.101041
2010-03-07T17:07:54
2010-03-07T17:07:54
37,358,601
0
0
null
null
null
null
UTF-8
C++
false
false
14,292
cpp
Graph.cpp
#include <math.h> #include <iostream> #include "Graph.h" using namespace std; Graph::Graph(InclusionNodes* in) { numOfLevels = NUMOFLEVELS; inc = in; } vector<SixTuple*> Graph::handleInclusion() { vector<SixTuple*> nodes; int nOfNodes = mst.size(); for (int i=0; i<nOfNodes; i++) { bool flag = true; for (EdgeIterator it=mst[i].begin(); it!=mst[i].end(); it++) { int index = (*it).node; string curSeq = graphNodes[i].getNodeStr(); string comSeq = graphNodes[index].getNodeStr(); vector<int> ovlDis = calDist.searchDistance(i, index); if ((ovlDis[1] == INT_MAX) && (ovlDis[0] == INT_MAX)) { ovlDis = ovl.getOVLDistance(curSeq, comSeq); //add to CalculatedOvlDistance calDist.addDistance(i, index, ovlDis[1], ovlDis[0]); } if (curSeq.length() <= comSeq.length()) { if (ovlDis[1] == INT_MIN) { //has inclusion inc->addNode1(i, index); //get rid of i and put it into inclusion list. flag = false; break; } } } if (flag) { nodes.push_back(new SixTuple(i)); } } return nodes; } /** * Get two closest nodes which is on the left and on the right to every node * from the input minimum spanning tree, and store the data into an array list. * This function removes inclusion nodes from the tree, and then finds parent and * children for all the left nodes, and calculates overlap distance between the node and * others, select the two nodes with minimum left and right overlap distance. * * * @param mst a Minimum Spanning Tree. * @return an array list of SixTuple which stores two closest nodes which is to the left and to the right * respectively for all the nodes in the tree. */ vector<SixTuple*> Graph::get2CloseNodesFromMST() { vector<SixTuple*> alignedNodes = handleInclusion(); int nOfNodes = alignedNodes.size(); for (int i=0; i<nOfNodes; i++) { int curIdx = alignedNodes[i]->curNode; if (inc->containInclusionNode(curIdx)) continue; int leftNode = -1; int rightNode = -1; int maxLeft = INT_MIN; //maximum left distance because left distance is negative int minRight = INT_MAX; //minimum right distance int overlapLeft = 0; int overlapRight = 0; for (EdgeIterator it=mst[curIdx].begin(); it!=mst[curIdx].end(); it++) { int index = (*it).node; if (inc->containInclusionNode(index)) continue; vector<int> ovlDis = calDist.searchDistance(curIdx, index); if ((ovlDis[1] == INT_MAX) && (ovlDis[0] == INT_MAX)) { ovlDis = ovl.getOVLDistance(graphNodes[curIdx].getNodeStr(), graphNodes[index].getNodeStr()); //add to CalculatedOvlDistance calDist.addDistance(curIdx, index, ovlDis[1], ovlDis[0]); } if (ovlDis[1] != INT_MAX) { // there is overlap between them if (ovlDis[0] < 0) { if (ovlDis[1] > maxLeft){ maxLeft = ovlDis[1]; overlapLeft = ovlDis[0]; leftNode = index; } else if (ovlDis[1] == maxLeft) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapLeft)) { overlapLeft = ovlDis[0]; leftNode = index; } } } if (ovlDis[0] > 0) { if (ovlDis[1] < minRight) { minRight = ovlDis[1]; overlapRight = ovlDis[0]; rightNode = index; } else if (ovlDis[1] == minRight) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapRight)) { overlapRight = ovlDis[0]; rightNode = index; } } } } } //leftNode, index of node on the left //overlapLeft, overlap length //maxLeft, overlap distance //rightNode, index of node on the right //overlapRight, overlap length //minRight, overlap distance alignedNodes[i]->setSixTuple(leftNode, overlapLeft, maxLeft, rightNode, overlapRight, minRight, false); } return alignedNodes; } /** * Get two closest nodes which is on the left and on the right to the 'index' node * from the input minimum spanning tree, and store the data into an array. * To get the six-tuple for the node, the function calculates distance from * this node to all the other nodes which are less than or equal to three levels from it. * * * @param mst a Minimum Spanning Tree. * @param index The index of current node in the tree and graph. * @param sixTuple The SixTuple for this node with the index * @return SixTuple for the current node which has the input "index". * the first is the index of node on the left, the second is the overlap length with + or -. * the third is the distance with + or -. * the fourth is the index of node on the right, the fifth is the overlap length with + or -. * the sixth is the distance with + or -. * For the first and fourth one, if no node is found, the value is -1; * For the second and fifth one, if no node is found, the value is 0; * For the third and sixth one, if no node is found, the value is INT_MIN or INT_MAX. */ SixTuple Graph::get2CloseNodesFromGrand(int index, const SixTuple sixTuple) { SixTuple closeNode; int leftNode = -1; int rightNode = -1; int maxLeft = sixTuple.lDis; int minRight = sixTuple.rDis; int overlapLeft = sixTuple.lOvlLen; int overlapRight = sixTuple.rOvlLen; //put all the nodes within three levels from the current node into the stack "allNodes". Do not // include parents and children because they have been processed. stack<int> allNodes; stack<int> partNodes; partNodes.push(index); for (int i=0; i<3; i++) { stack<int> tmpStack; while (!partNodes.empty()) { int tmpIndex = partNodes.top(); partNodes.pop(); for (EdgeIterator it=mst[tmpIndex].begin(); it!=mst[tmpIndex].end(); it++) { int tIndex = (*it).node; tmpStack.push(tIndex); if ((i != 0) && (tIndex != index)){ //Do not include parents and children because they have been processed. allNodes.push(tIndex); } } } partNodes = tmpStack; } //find two closest nodes string s1 = graphNodes[index].getNodeStr(); while (!allNodes.empty()) { int tmpIndex = allNodes.top(); allNodes.pop(); if (inc->containInclusionNode(tmpIndex)) continue; string s2 = graphNodes[tmpIndex].getNodeStr(); vector<int> ovlDis = calDist.searchDistance(index, tmpIndex); if ((ovlDis[1] == INT_MAX) && (ovlDis[0] == INT_MAX)) { ovlDis = ovl.getOVLDistance(s1, s2); //add to CalculatedOvlDistance calDist.addDistance(index, tmpIndex, ovlDis[1], ovlDis[0]); } if (ovlDis[1] == INT_MIN) { // there is inclusion between them if (s1.length() >= s2.length()) { inc->addNode2(tmpIndex, index); } else { inc->addNode2(index, tmpIndex); } } else if (ovlDis[1] != INT_MAX) { // there is overlap between them if (ovlDis[0] < 0) { if (ovlDis[1] > maxLeft){ maxLeft = ovlDis[1]; overlapLeft = ovlDis[0]; leftNode = tmpIndex; } else if (ovlDis[1] == maxLeft) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapLeft)) { overlapLeft = ovlDis[0]; leftNode = tmpIndex; } } } if (ovlDis[0] > 0) { if (ovlDis[1] < minRight) { minRight = ovlDis[1]; overlapRight = ovlDis[0]; rightNode = tmpIndex; } else if (ovlDis[1] == minRight) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapRight)) { overlapRight = ovlDis[0]; rightNode = tmpIndex; } } } } } closeNode.leftNode = leftNode; //index of node on the left closeNode.lOvlLen = overlapLeft; //overlap length closeNode.lDis = maxLeft; //overlap distance closeNode.rightNode = rightNode; //index of node on the right closeNode.rOvlLen = overlapRight; //overlap length closeNode.rDis = minRight; //overlap distance closeNode.isNull = false; return closeNode; } /** * Recalculate 6-tuples for an assumed left end in order to make sure it is a real left end. * Specifically, for the assumed left end,start to calculate from fourth level until meeting one node which * makes six-tuple.leftEnd != -1, or until the level we specified in the property file, then return the six-tuple. * If we fail to find any node, we consider it a real left end and six-tuple.leftEnd will be set to be -1. * * @param mst a Minimum Spanning Tree. * @param index The index of current node in the tree and graph. * @param sixTuple The SixTuple for this node with the index * @return SixTuple which stores two closest nodes which is to the left and to the right if it is not left end; * if it does, six-tuple.leftEnd = -1. */ SixTuple Graph::checkLeftEndFromMST(int index, const SixTuple sixTuple) { if (numOfLevels == 0) { //keep checking until leaves numOfLevels = INT_MAX; } vector<stack<int> > nodes (2); nodes[0].push(index); nodes[1].push(-1); for (int i=0; i<3; i++) { //skip over all the nodes within 3 levels nodes = getNodesFromMST(nodes); } SixTuple closeNode; for (int foundLevel=4; foundLevel<=numOfLevels; foundLevel++) { //start from level 4 nodes = getNodesFromMST(nodes); if (nodes[0].size() == 0) { break; } else { closeNode = findAdjacentNode(nodes[0], index, sixTuple); if (closeNode.leftNode != -1) { closeNode.isNull = false; return closeNode; } } } closeNode.isNull = true; return closeNode; } SixTuple Graph::checkRightEndFromMST(int index, const SixTuple sixTuple) { if (numOfLevels == 0) { //keep checking until leaves numOfLevels = INT_MAX; } vector<stack<int> > nodes (2); nodes[0].push(index); nodes[1].push(-1); for (int i=0; i<3; i++) { //skip over all the nodes within 3 levels nodes = getNodesFromMST(nodes); } SixTuple closeNode; for (int foundLevel=4; foundLevel<=numOfLevels; foundLevel++) { //start from level 4 nodes = getNodesFromMST(nodes); if (nodes[0].size() == 0) { break; } else { closeNode = findAdjacentNode(nodes[0], index, sixTuple); if (closeNode.rightNode != -1) { closeNode.isNull = false; return closeNode; } } } closeNode.isNull = true; return closeNode; } /* * find the most adjacent node to the current node from allNodes. * @param allNodes Store indices of all the nodes which will be compared to the current node. * @param index The index of current node. * @sixTuple The sixTuple for the current node. */ SixTuple Graph::findAdjacentNode(stack<int> nodes, int index, const SixTuple sixTuple) { stack<int> allNodes; //put all the values of nodes into another stack so that we won't change nodes(it's a pointer) because it may be used by the calling method. int stackSize = nodes.size(); vector<int> tmpStack(stackSize); for (int i=stackSize-1; i>=0; i--) { tmpStack[i] = nodes.top(); nodes.pop(); } for (int i=0; i<stackSize; i++) { //get(0) will get the bottom element of the stack allNodes.push(tmpStack[i]); } SixTuple closeNode; int leftNode = -1; int rightNode = -1; int maxLeft = sixTuple.lDis; int minRight = sixTuple.rDis; int overlapLeft = sixTuple.lOvlLen; int overlapRight = sixTuple.rOvlLen; //find two closest nodes string s1 = graphNodes[index].getNodeStr(); while (!allNodes.empty()) { int tmpIndex = allNodes.top(); allNodes.pop(); if (inc->containInclusionNode(tmpIndex)) continue; if (tmpIndex == index) continue; string s2 = graphNodes[tmpIndex].getNodeStr(); vector<int> ovlDis = calDist.searchDistance(index, tmpIndex); if ((ovlDis[1] == INT_MAX) && (ovlDis[0] == INT_MAX)) { ovlDis = ovl.getOVLDistance(s1, s2); //add to CalculatedOvlDistance calDist.addDistance(index, tmpIndex, ovlDis[1], ovlDis[0]); } if (ovlDis[1] == INT_MIN) { // there is inclusion between them if (s1.length() >= s2.length()) { inc->addNode2(tmpIndex, index); } else { inc->addNode2(index, tmpIndex); } } else if (ovlDis[1] != INT_MAX) { // there is overlap between them if (ovlDis[0] < 0) { if (ovlDis[1] > maxLeft) { maxLeft = ovlDis[1]; overlapLeft = ovlDis[0]; leftNode = tmpIndex; } else if (ovlDis[1] == maxLeft) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapLeft)) { overlapLeft = ovlDis[0]; leftNode = tmpIndex; } } } if (ovlDis[0] > 0) { if (ovlDis[1] < minRight) { minRight = ovlDis[1]; overlapRight = ovlDis[0]; rightNode = tmpIndex; } else if (ovlDis[1] == minRight) { //if they are equal, find that one with maximal overlap if (abs(ovlDis[0]) > abs(overlapRight)) { overlapRight = ovlDis[0]; rightNode = tmpIndex; } } } } } closeNode.leftNode = leftNode; //index of node on the left closeNode.lOvlLen = overlapLeft; //overlap length closeNode.lDis = maxLeft; //overlap distance closeNode.rightNode = rightNode; //index of node on the right closeNode.rOvlLen = overlapRight; //overlap length closeNode.rDis = minRight; //overlap distance closeNode.isNull = false; return closeNode; } /** * Get all the children for the input nodes and put them into a stack. * * @param mst a Minimum Spanning Tree. * @param nodes The stack array, nodes[0], the indexes of all the nodes for which we will find their children; * nodes[1], the indexes of the parent node of every element in nodes[0]. * @return a stack array which stores all the found nodes' indexes. ret[0], the indexes of all the found nodes * (that is, the children of input nodes); ret[1], the indexes of the parent node of every element in nodes[0]. */ vector<stack<int> > Graph::getNodesFromMST(vector<stack<int> > nodes) { vector<stack<int> > ret (2); while (!(nodes[0].empty())) { int curIndex = nodes[0].top(); nodes[0].pop(); int parentIndex = nodes[1].top(); nodes[1].pop(); for (EdgeIterator it=mst[curIndex].begin(); it!=mst[curIndex].end(); it++) { int index2 = (*it).node; if (index2 != parentIndex) { ret[0].push(index2); ret[1].push(curIndex); } } } return ret; }
2159c441f6f9782137f3de2f78819d2d35114d75
6ac43269dd6013c6f4e8e1afbb5337e3374dbf74
/Interfaces/MassDiag/inc/ParSLHA.hpp
8b2772a795cd57489a8d0e3bedbb72a7a01d014c
[]
no_license
HEPcodes/FeynRules
e520d30c98bdecb6fd54cfb8507ad39d9a3c8ae8
d3c7ef89542e4101e1379298a0c932bc75d5dcf0
refs/heads/master
2022-05-10T19:46:48.980590
2022-02-08T18:49:35
2022-02-08T18:50:51
18,512,127
8
6
null
2021-05-26T11:34:01
2014-04-07T09:30:58
Mathematica
UTF-8
C++
false
false
857
hpp
ParSLHA.hpp
#ifndef PARSLHA_HPP #define PARSLHA_HPP #include "headers.hpp" //class to store parameters to be used in the SLHABlocks. class ParSLHA { private: /****parameters****/ //the value double value; //the comment to be used in the parametercard string comment; public: /****constructors****/ //default constructor ParSLHA(); //constructor ParSLHA(double v, string c); /****setters*****/ //set the value void setValue(double v) {value = v;} //set the comment void setComment(string c) {comment = c;} /****getters****/ //get the value double getValue() {return value;} //get the comment string getComment() {return comment;} }; #endif
43bf5384f12e0bf224fa5f5cd006049fe6c3715b
64732dfaeb3efb781db6e894bebfe23d627278e7
/LoganEngine/src/lCore/lRenderer/lrRenderer/lGLRenderer/lGLUtils/lrGLRenderUtils.h
dc2b6f8bea2efeeb3f986f3fe80ad477dd6791fa
[ "MIT" ]
permissive
sereslorant/logan_engine
b791f843a36bd19caa4cc97dc4ec102a37cb650a
a596b4128d0a58236be00f93064e276e43484017
refs/heads/master
2020-05-21T19:41:45.676116
2018-01-28T10:25:43
2018-01-28T10:25:43
63,418,341
1
0
null
null
null
null
UTF-8
C++
false
false
2,110
h
lrGLRenderUtils.h
#ifndef LR_GL_RENDER_UTILS_H #define LR_GL_RENDER_UTILS_H #include <lRenderer/lrRenderer/lGLRenderer/lGLExt.h> #include <lRenderer/lrRenderer/lGLRenderer/liGLShaderInterfaces.h> #include <lRenderer/lrRenderer/lGLRenderer/lGL3Renderer/lGL3DCachedLayer/lrGL3SceneCache/lrGLData/lrGLMaterialData.h> #include <lRenderer/lrRenderer/lGLRenderer/lGL3Renderer/lGL3DCachedLayer/lrGL3SceneCache/lrGLData/lrGLTransformArray.h> class lrGLRenderUtils { public: /* static void UploadUniformLight(liGLPointLightShader &shader,const lrGLLightData &light) { glUniform3fv(shader.GetLightPositionLocation(0),1,light.Position); glUniform3fv(shader.GetLightColorLocation(0),1,light.Color); glUniform1f(shader.GetLightIntensityLocation(0),light.Intensity); } *//* static void UploadUniformLight(liGLPointLightShader &shader,const lrGLLightData &light,unsigned int id) { glUniform3fv(shader.GetLightPositionLocation(id),1,light.Position); glUniform3fv(shader.GetLightColorLocation(id),1,light.Color); glUniform1f(shader.GetLightIntensityLocation(id),light.Intensity); } */ static void UploadUniformLightArray(liGLPointLightShader &shader,float *positions,float *colors,float *intensities,unsigned int size) { glUniform1i(shader.GetLightCountLocation(),size); glUniform3fv(shader.GetLightPositionLocation(),size,positions); glUniform3fv(shader.GetLightColorLocation(),size,colors); glUniform1fv(shader.GetLightIntensityLocation(),size,intensities); } static void UploadUniformMaterial(liGLPbMatShader &shader,const lrGLMaterialData &material) { glUniform3fv(shader.GetMatAlbedoLocation(),1,material.Material[0]); glUniform4fv(shader.GetMaterial1Location(),1,material.Material[1]); } static void UploadUniformTransform(liGL3DShader &shader,const lrGLTransform &transform) { glUniformMatrix4fv(shader.GetModelMatrixLocation(),1,GL_FALSE,transform.ModelMatrix[0]); glUniformMatrix3fv(shader.GetNormalMatrixLocation(),1,GL_FALSE,transform.NormalMatrix[0]); glUniformMatrix4fv(shader.GetMvpMatrixLocation(),1,GL_FALSE,transform.MvpMatrix[0]); } }; #endif // LR_GL_RENDER_UTILS_H
1ac0ab00c5d14a0a1966a259161c13e2c1bec1ae
d7632bcbe8385f864752d5765869b09c6ec69303
/MouseController/thread/thread_point.h
debc97d4e5fc1d075c563a4d199bc0bf693de66f
[]
no_license
tigerbobo/public
4aac0f445aac9f06ea3a0d4533bc983b3a537084
4c6bcfe2ad015c95a9c5aaaf4405d04080ca9139
refs/heads/master
2022-11-21T10:14:41.579616
2022-10-21T01:23:04
2022-10-21T01:23:04
228,769,259
0
0
null
null
null
null
UTF-8
C++
false
false
557
h
thread_point.h
#pragma once #include "base_thread.h" #include "..\define\define.h" class CThreadPoint : public CBaseThread { public: CThreadPoint() {}; ~CThreadPoint() {}; protected: virtual unsigned int procedure(void *param) { POINT point; HWND message_wnd = (HWND)param; onstart(0, 0); while (false == m_interrupt) { GetCursorPos(&point); ::SendMessage(message_wnd, WM_POINT_MESSAGE, point.x, point.y); Sleep(10); } onstop(0, 0); CloseHandle(m_handle); m_handle = NULL; _endthreadex(0); return 0; }; };
dff4da9fb397e96120bdb81bf60a1f8d11de9a99
037985edaf61f245644a1b6c4724c2b54174120e
/HW1/main.cpp
6e6701c2eb7060dea907a9805121579507590664
[]
no_license
SANDEEP95890/algorithm-implementations
c41cdaf7c580902a7f637abe2dbb8ad25a9320de
59b82124f8d94ca8234349a4fc370db73ade8343
refs/heads/master
2023-03-17T13:01:51.099683
2020-09-30T22:38:23
2020-09-30T22:38:23
549,698,818
1
0
null
2022-10-11T15:39:28
2022-10-11T15:39:27
null
UTF-8
C++
false
false
1,862
cpp
main.cpp
#include <iostream> #include <cstdlib> #include <vector> #include <chrono> #include <random> using namespace std; void find_duplications(unsigned int *arr, unsigned int arr_length, vector<unsigned int> &dup_vec) { for (unsigned int i = 0; i < arr_length; i++) { for (unsigned int j = i + 1; j < arr_length; j++) { if (arr[i] == arr[j]) { dup_vec.push_back(i); dup_vec.push_back(j); } } } } int main(int argc, char *argv[]) { // (a) unsigned int arr_length; // User will provide the array length and maximum number we can generate arr_length = stoul(argv[1]); unsigned int *random_arr = new unsigned int[arr_length]; // (b) unsigned seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine generator(seed); uniform_int_distribution<int> distribution(1, arr_length); for (unsigned int i = 0; i < arr_length; i++) { random_arr[i] = distribution(generator); // Element i is between 1 and arr_length(included) } // (c) cout << "ARRAY:"; for (unsigned int i = 0; i < arr_length; i++) { if (i % 10 == 0) cout << "\n"; // 10 elements per line cout << random_arr[i] << "\t"; } cout << endl; // (d) cout << "\nEXPECTED NUMBER OF DUPLICATIONS = " << (arr_length - 1) / 2.0 << endl; // (e) vector<unsigned int> dup_vec; find_duplications(random_arr, arr_length, dup_vec); int c = 0; for (auto i = dup_vec.begin(); i != dup_vec.end(); advance(i, 2)) { if (c % 10 == 0) cout << "\n"; // 10 elements per line cout << "(" << *i + 1 << ", " << *(i + 1) + 1 << ") "; c++; } // (f) cout << endl << "\nENCOUNTERED NUMBER OF DUPLICATIONS = " << dup_vec.size() / 2 << endl; delete[] random_arr; return 0; }
e1ff372336207bbcb2d4ad3e31a533e732a2dca9
429cbd00303dc2084344ca5fda79303cb120dd6f
/Assignment2/GeneratedFiles/ui_ReceiverOptions.h
facd54db2bd6fcc547b08acbeaa18e21c5ec4e43
[]
no_license
jctee/TCP-UDP-FileTransfer
0d83a182fc04ee8b6c704827f99150ea09dbf2b6
9484329576ae4500d9780fa1acb013d9810fa5ed
refs/heads/master
2020-03-18T05:47:09.610644
2018-05-22T05:13:35
2018-05-22T05:13:35
134,361,334
0
0
null
null
null
null
UTF-8
C++
false
false
4,083
h
ui_ReceiverOptions.h
/******************************************************************************** ** Form generated from reading UI file 'ReceiverOptions.ui' ** ** Created by: Qt User Interface Compiler version 5.9.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_RECEIVEROPTIONS_H #define UI_RECEIVEROPTIONS_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_ReceiverOptions { public: QWidget *layoutWidget; QHBoxLayout *hboxLayout; QSpacerItem *spacerItem; QPushButton *okButton; QPushButton *cancelButton; QLabel *label_5; QLineEdit *lineReceiverIP; QLabel *label_6; QLineEdit *lineReceiverPort; void setupUi(QDialog *ReceiverOptions) { if (ReceiverOptions->objectName().isEmpty()) ReceiverOptions->setObjectName(QStringLiteral("ReceiverOptions")); ReceiverOptions->resize(846, 320); layoutWidget = new QWidget(ReceiverOptions); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(430, 200, 351, 48)); hboxLayout = new QHBoxLayout(layoutWidget); hboxLayout->setSpacing(6); hboxLayout->setObjectName(QStringLiteral("hboxLayout")); hboxLayout->setContentsMargins(0, 0, 0, 0); spacerItem = new QSpacerItem(131, 31, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout->addItem(spacerItem); okButton = new QPushButton(layoutWidget); okButton->setObjectName(QStringLiteral("okButton")); hboxLayout->addWidget(okButton); cancelButton = new QPushButton(layoutWidget); cancelButton->setObjectName(QStringLiteral("cancelButton")); hboxLayout->addWidget(cancelButton); label_5 = new QLabel(ReceiverOptions); label_5->setObjectName(QStringLiteral("label_5")); label_5->setGeometry(QRect(80, 50, 111, 25)); lineReceiverIP = new QLineEdit(ReceiverOptions); lineReceiverIP->setObjectName(QStringLiteral("lineReceiverIP")); lineReceiverIP->setGeometry(QRect(290, 50, 491, 31)); label_6 = new QLabel(ReceiverOptions); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(100, 120, 89, 25)); lineReceiverPort = new QLineEdit(ReceiverOptions); lineReceiverPort->setObjectName(QStringLiteral("lineReceiverPort")); lineReceiverPort->setGeometry(QRect(290, 120, 491, 31)); retranslateUi(ReceiverOptions); QObject::connect(okButton, SIGNAL(clicked()), ReceiverOptions, SLOT(accept())); QObject::connect(cancelButton, SIGNAL(clicked()), ReceiverOptions, SLOT(reject())); QMetaObject::connectSlotsByName(ReceiverOptions); } // setupUi void retranslateUi(QDialog *ReceiverOptions) { ReceiverOptions->setWindowTitle(QApplication::translate("ReceiverOptions", "Dialog", Q_NULLPTR)); okButton->setText(QApplication::translate("ReceiverOptions", "OK", Q_NULLPTR)); cancelButton->setText(QApplication::translate("ReceiverOptions", "Cancel", Q_NULLPTR)); label_5->setText(QApplication::translate("ReceiverOptions", "IP Address", Q_NULLPTR)); lineReceiverIP->setText(QString()); label_6->setText(QApplication::translate("ReceiverOptions", "Port #", Q_NULLPTR)); lineReceiverPort->setText(QString()); } // retranslateUi }; namespace Ui { class ReceiverOptions: public Ui_ReceiverOptions {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_RECEIVEROPTIONS_H
26b79938cece68f9e502f52805e73aac1f480e20
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/2552.cpp
172829fca33ee3ceebb943f2995c79f22dff9307
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
990
cpp
2552.cpp
#include <iostream> #include <cstring> using namespace std; #define N (int)1e7 int freq[N + 1], n, ans[N + 1]; bool is_prime[N + 1]; int presum[N + 1]; void seive() { for (int i = 2; i <= N; i++) is_prime[i] = 1; for (int i = 2; i*i <= N; i++) if (is_prime[i]) for (int j = i*i; j <= N; j += i) is_prime[j] = 0; } int main() { ios::sync_with_stdio(false); seive(); memset(freq, 0, sizeof(freq)); cin>>n; for (int i = 0; i < n; i++) { int temp; cin>>temp; freq[temp]++; } for (int p = 2; p <= N; p++) if (is_prime[p]) { for (int i = p; i <= N; i += p) ans[p] += freq[i]; } presum[0] = 0; for (int i = 1; i <= N; i++) presum[i] = presum[i - 1] + ans[i]; int q; cin>>q; while (q--) { int l, r; cin>>l>>r; r = min((int)1e7, r); l = min((int)1e7, l); cout<<presum[r] - presum[l - 1]<<endl; } return 0; }
94f949a94e323348b4048c7bbacebd7a2dbcb00d
3acacb08ce68dde28c6b400ec90977b0e7779454
/PacketCommSrv/PacketTool.cpp
ae1120ba844f35138f314ed2dfe75b97e1ed81dd
[]
no_license
mqd520/NetworkCommucation-C-
5d532743f9ce19ee24a6bf7952b0c7f1cfca7ca1
2be895c0864439b1c761b111ee3270e01596f6a7
refs/heads/master
2021-01-22T21:07:46.629692
2019-07-16T09:22:29
2019-07-16T09:22:29
85,392,410
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
PacketTool.cpp
#include "stdafx.h" #include "Include/pck/PacketTool.h" #include "Include/pck/IGPacket.h" #define PCR_PacketPointer(CMD, ClassName) if (cmd == EPacketCmd::CMD){return new ClassName;} namespace pck { PacketTool::PacketTool() { } bool PacketTool::IsCmdValid(EPacketCmd cmd) { if (cmd == EPacketCmd::None) { return false; } bool b = false; for (int i = 0; i < PCR_CmdCount; i++) { if (cmd == _vecPacketCmds[i]) { b = true; break; } } return b; } Packet* PacketTool::GetPacket(EPacketCmd cmd) { PCR_PacketPointer(KeepAlive, KeepAlivePacket) PCR_PacketPointer(LoginSrvRequest, LoginSrvRequestPacket) PCR_PacketPointer(LoginSrvResult, LoginSrvResultPacket) return NULL; } }
0cfc294effb733d8366290574866e3617c4118a6
8ab5aab459348f84db0a11a5e9e289c1c3f4a43b
/rmf_traffic_editor/include/traffic_editor/crowd_sim/crowd_sim_impl.h
619cbf640e7d72f2ee963160f50a9ddfaaa75d5a
[ "Apache-2.0" ]
permissive
xiyuoh/rmf_traffic_editor
2e48d288a63b77564251e0eccc01f617a9b3b6a1
686d7a367f8cb2f7d5fe7221b3fd6873499d7be9
refs/heads/main
2023-08-27T09:10:40.524035
2021-11-08T08:30:56
2021-11-08T08:30:56
395,252,842
0
0
Apache-2.0
2021-08-12T08:43:03
2021-08-12T08:43:02
null
UTF-8
C++
false
false
3,747
h
crowd_sim_impl.h
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef CROWD_SIM_IMPL__H #define CROWD_SIM_IMPL__H #include <string> #include <set> #include <memory> #include <yaml-cpp/yaml.h> #include <traffic_editor/crowd_sim/state.h> #include <traffic_editor/crowd_sim/goal_set.h> #include <traffic_editor/crowd_sim/transition.h> #include <traffic_editor/crowd_sim/agent_profile.h> #include <traffic_editor/crowd_sim/agent_group.h> #include <traffic_editor/crowd_sim/model_type.h> namespace crowd_sim { class CrowdSimImplementation { public: CrowdSimImplementation() : _enable_crowd_sim(false), _update_time_step(0.1) { init_default_configure(); } ~CrowdSimImplementation() {} YAML::Node to_yaml(); bool from_yaml(const YAML::Node& input); void clear(); void init_default_configure(); void set_navmesh_file_name(std::vector<std::string> navmesh_filename) { _navmesh_filename_list = navmesh_filename; } std::vector<std::string> get_navmesh_file_name() const { return _navmesh_filename_list; } void set_enable_crowd_sim(bool is_enable) { _enable_crowd_sim = is_enable; } bool get_enable_crowd_sim() const { return _enable_crowd_sim; } void set_update_time_step(double update_time_step) { _update_time_step = update_time_step; } double get_update_time_step() const { return _update_time_step; } void set_goal_areas(std::set<std::string> goal_areas) { _goal_areas = goal_areas; } std::vector<std::string> get_goal_areas() const { return std::vector<std::string>(_goal_areas.begin(), _goal_areas.end()); } void save_goal_sets(const std::vector<GoalSet>& goal_sets); std::vector<GoalSet> get_goal_sets() const { return _goal_sets; } void save_states(const std::vector<State>& states); std::vector<State> get_states() const { return _states; } void save_transitions(const std::vector<Transition>& transitions); std::vector<Transition> get_transitions() const { return _transitions; } void save_agent_profiles(const std::vector<AgentProfile>& agent_profiles); std::vector<AgentProfile> get_agent_profiles() const { return _agent_profiles; } void save_agent_groups(const std::vector<AgentGroup>& agent_groups); std::vector<AgentGroup> get_agent_groups() const { return _agent_groups; } void save_model_types(const std::vector<ModelType>& model_types); std::vector<ModelType> get_model_types() const { return _model_types; } private: // update from project.building in crowd_sim_table std::set<std::string> _goal_areas; std::vector<std::string> _navmesh_filename_list; // real configurations bool _enable_crowd_sim; double _update_time_step; std::vector<State> _states; std::vector<GoalSet> _goal_sets; std::vector<Transition> _transitions; std::vector<AgentProfile> _agent_profiles; std::vector<AgentGroup> _agent_groups; std::vector<ModelType> _model_types; void _initialize_state(); void _initialize_agent_profile(); void _initialize_agent_group(); void _initialize_model_type(); YAML::Node _output_obstacle_node() const; }; using CrowdSimImplPtr = std::shared_ptr<CrowdSimImplementation>; } //namespace crowd_sim #endif
d6986c4f7452adcf7a06ceb663709ebe21a5698d
1c27c3689fed12f6378562df19f745f54b245fab
/zadanie6/StatekPasazerski.cpp
8e20547f4799bc554503ba45474ef185e512d72c
[]
no_license
reko001/zadanie6
9eda6f0397b533b93912885d6fcce3babb5e1dda
99713d136d08f5768b43e72fef1c85b06a847bae
refs/heads/master
2023-04-27T07:51:43.212001
2021-05-09T13:38:30
2021-05-09T13:38:30
365,612,243
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
StatekPasazerski.cpp
#include "StatekPasazerski.h" int StatekPasazerski::get_pasazerowie() const { return m_pasazerowie; } void StatekPasazerski::set_pasazerowie(int pasazerowie) { m_pasazerowie = pasazerowie; } int StatekPasazerski::liczba_osob() const { return m_pasazerowie + get_zaloga(); } std::ostream& operator<<(std::ostream& strumien, const StatekPasazerski& statek) { strumien << "Kapitan: " << statek.m_kapitan << ", nazwa: " << statek.get_nazwa() << ", liczba zalogi: " << statek.get_zaloga() << " Pasazerowie: " << statek.m_pasazerowie; return strumien; } void StatekPasazerski::oblicz_zywnosc() { set_racje(3 * (get_zaloga() + m_pasazerowie)); } void StatekPasazerski::oblicz_zywnosc(bool desery) { if (desery) { set_racje(4 * (get_zaloga() + m_pasazerowie)); return; } set_racje(3 * (get_zaloga() + m_pasazerowie)); }
8e62c58c70afbd180ba6707875fa7a6c242b37a5
d9b8b19c0723a893856bdd613279e43028a1e757
/FlockingHell/FlockingHell/Source/Private/Player.cpp
91aa1816bd2f1136dec1cbcaaef6985134d37ad2
[ "Apache-2.0" ]
permissive
AliElSaleh/Cosmic-Hell
400c0849340cc0ff4b6a5a51add923c619496966
603ae26c4d1c0e05aad1be98bc98af093369121d
refs/heads/master
2020-04-11T06:29:40.949609
2019-03-19T07:22:11
2019-03-19T07:22:11
161,582,151
16
0
null
null
null
null
UTF-8
C++
false
false
11,990
cpp
Player.cpp
#include "Globals.h" #include "Player.h" #include "Bullet.h" #include "Assets.h" #define ASSETS Assets::Get() #define GetAsset(Name) ASSETS.GetSprite(#Name) void Player::Init() { Sprite = GetAsset(Player); Heart.clear(); Bomb.clear(); for (int i = 0; i < 6; i++) Heart.emplace_back(GetAsset(Heart)); for (int i = 0; i < 2; i++) Bomb.emplace_back(GetAsset(Bomb)); XOffset = 15; YOffset = 50; Location.x = float(GetScreenWidth()-PANEL_WIDTH) / 2 + float(XOffset); Location.y = float(GetScreenHeight()) - 100; BulletSpawnLocation.x = Location.x + float(Sprite.width)/4 - XOffset; BulletSpawnLocation.y = Location.y; BulletXOffset = 5; Hitbox.width = 2; Hitbox.height = 2; Hitbox.x = Location.x + float(Sprite.width)/4 - float(Sprite.width)/4/2 - XOffset + 2; // Offset X by XOffset + 2 pixels Hitbox.y = Location.y + float(Sprite.height)/2 - 5; // Offset Y by 5 pixels Spritebox = {Location.x, Location.y, float(Sprite.width)/4 - 20, float(Sprite.height)}; Health = 6; BombsLeft = unsigned short(Heart.size()); BombsLeft = unsigned short(Bomb.size()); Score = 0; GrazingScore = 0; ShootRate = 0; Deaths = 0; Hits = 0; BombsUsed = 0; Name = "Kratos"; // 8 characters maximum for leaderboard FramesCounter = 0; PlayerSpriteFramesCounter = 0; PlayerHitFramesCounter = 0; PlayerFrameRec.x = 0.0f; PlayerFrameRec.y = 0.0f; PlayerFrameRec.width = float(Sprite.width)/4; // 4 frames PlayerFrameRec.height = float(Sprite.height); Center = {Location.x - float(Sprite.width)/12, Location.y + float(Sprite.height)/2}; // Bullets for (int i = 0; i < MAX_PLAYER_BULLETS; i++) { Bullet[i].Sprite = GetAsset(BlueBullet); Bullet[i].Frames = 4; Bullet[i].Location = Location; Bullet[i].Radius = 3.0f; Bullet[i].Speed = 600.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = false; Bullet[i].InitFrames(); } BulletLevel = 1; BossKilled = 0; EnemiesKilled = 0; HealthRegenTimer = 0; BombRegenTimer = 0; BombCooldownTimer = 0; bWarshipDefeated = false; bWasHit = false; bWasBombUsed = false; bCanUseBomb = true; bChangeMusic = false; bInvincible = false; bIsDead = false; bIsHit = false; bDebug = false; } void Player::Update() { // Update location and animation if not dead if (!bIsDead) { PlayerSpriteFramesCounter++; HealthRegenTimer++; BombRegenTimer++; // Update the player's location and its components Location.x = GetMousePosition().x - XOffset - 2; Location.y = GetMousePosition().y - YOffset; Spritebox = {Location.x, Location.y, float(Sprite.width)/4 - 20, float(Sprite.height)}; Center = {Location.x + float(Sprite.width)/12 - 2.0f, Location.y + float(Sprite.height)/2 - 5.0f}; Hitbox.x = Location.x + float(Sprite.width)/4 - float(Sprite.width)/4/2 - XOffset + 2; // Offset X by XOffset + 2 pixels Hitbox.y = Location.y + float(Sprite.height)/2 - 5; // Offset Y by 5 pixels BulletSpawnLocation.x = Location.x + float(Sprite.width)/4 - XOffset - 3; BulletSpawnLocation.y = Location.y; // Player's invincibility mechanic if (bIsHit) { PlayerHitFramesCounter++; Invincibility(true, 1.0f); } else { PlayerHitFramesCounter = 0; Invincibility(false, 0.0f); } // Bomb mechanic if (bCanUseBomb) { if (IsKeyPressed(KEY_B)) { if (BombsLeft < 1) BombsLeft = 0; else { BombsUsed++; bWasBombUsed = true; bCanUseBomb = false; BombsLeft--; if (!Bomb.empty()) Bomb.pop_back(); } } } else { BombCooldownTimer++; bWasBombUsed = false; if (BombCooldownTimer/360%2) { BombCooldownTimer = 0; bWasBombUsed = false; bCanUseBomb = true; } } // Bomb regeneration/refill if (BombRegenTimer/3600%2) // 30 sec { if (Bomb.size() < 4) { Bomb.emplace_back(GetAsset(Bomb)); if (BombsLeft <= 0) BombsLeft = 1; else BombsLeft++; } BombRegenTimer = 0; } // Health regeneration/refill if (HealthRegenTimer/7200%2) // 60 sec { if (Heart.size() < 6) { Heart.emplace_back(GetAsset(Heart)); HeartsLeft++; Health++; } HealthRegenTimer = 0; } // To prevent negative values if (Score < 0) Score = 0; UpdatePlayerAnimation(); } // Player checks CheckCollisionWithWindow(); CheckHealth(); // Update bullets movement on key press [space] UpdateBullet(); CheckBulletOutsideWindow(); } void Player::Draw() const { // Player sprite if (bIsHit) { if (PlayerHitFramesCounter/10%2) DrawTextureRec(Sprite, PlayerFrameRec, Location, WHITE); // Draw part of the player texture } else DrawTextureRec(Sprite, PlayerFrameRec, Location, WHITE); // Draw part of the player texture if (bDebug) { DrawRectangleLines(int(Spritebox.x), int(Spritebox.y), int(Spritebox.width), int(Spritebox.height), WHITE); // Spritebox for (int i = 0; i < MAX_PLAYER_BULLETS; i++) DrawCircle(int(Bullet[i].Center.x), int(Bullet[i].Center.y), Bullet[i].Radius, RED); // Player Bullets hitbox DrawCircle(int(Center.x), int(Center.y), 3.0f, YELLOW); // Player's center DrawRectangle(int(Hitbox.x), int(Hitbox.y), int(Hitbox.width), int(Hitbox.height), BLUE); // Player hitbox } } void Player::DrawBullets() const { for (int i = 0; i < MAX_PLAYER_BULLETS; i++) Bullet[i].Draw(); } void Player::ResetBullet(const short Index) { Bullet[Index].bActive = false; Bullet[Index].bIsHit = true; Bullet[Index].Location = Location; Bullet[Index].Center = Bullet[Index].Location; ShootRate = 0; } void Player::InitBulletLevel(const signed short Level) { switch (Level) { case 1: ShootRate += 2; // Center of gun for (int i = 0; i < MAX_PLAYER_BULLETS/2; i++) { if (!Bullet[i].bActive && ShootRate % 20 == 0) { Bullet[i].Location = BulletSpawnLocation; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } break; case 2: ShootRate += 3; // Left of gun for (int i = 0; i < MAX_PLAYER_BULLETS/2; i++) { if (!Bullet[i].bActive && ShootRate % 24 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x - BulletXOffset; // Offset to the left by 5 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 700.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } // Right of gun for (int i = 25; i < MAX_PLAYER_BULLETS; i++) { if (!Bullet[i].bActive && ShootRate % 24 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x + BulletXOffset; // Offset to the right by 5 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 700.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } break; case 3: ShootRate += 4; BulletXOffset = 15; // Left of gun - 0 to 24 bullets for (int i = 0; i < MAX_PLAYER_BULLETS/4; i++) { if (!Bullet[i].bActive && ShootRate % 28 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x - BulletXOffset; // Offset to the left by 15 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 800.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } // Middle left of gun - 25 - 49 bullets for (int i = 25; i < MAX_PLAYER_BULLETS/2; i++) { if (!Bullet[i].bActive && ShootRate % 28 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x - BulletXOffset + 10; // Offset to the right by 10 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 800.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } // Middle right of gun - 50 to 74 bullets for (int i = 50; i < MAX_PLAYER_BULLETS - MAX_PLAYER_BULLETS/4; i++) { if (!Bullet[i].bActive && ShootRate % 28 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x + BulletXOffset - 10; // Offset to the right by 10 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 800.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } // Right of gun - 75 to 99 bullets for (int i = 75; i < MAX_PLAYER_BULLETS; i++) { if (!Bullet[i].bActive && ShootRate % 28 == 0) { Bullet[i].Location.x = BulletSpawnLocation.x + BulletXOffset; // Offset to the right by 15 pixels to make room for other half of bullets Bullet[i].Location.y = BulletSpawnLocation.y; Bullet[i].Speed = 800.0f; Bullet[i].Damage = GetRandomValue(10, 15); Bullet[i].bActive = true; break; } } break; default: break; } } void Player::UpdatePlayerAnimation() { // Player sprite animation if (PlayerSpriteFramesCounter >= (GetFPS()/FramesSpeed)) { PlayerSpriteFramesCounter = 0; PlayerCurrentFrame++; if (PlayerCurrentFrame > 4) PlayerCurrentFrame = 0; PlayerFrameRec.x = float(PlayerCurrentFrame)*float(Sprite.width)/4; } } void Player::UpdateBullet() { // Initialise bullets if (IsKeyDown(KEY_SPACE)) { if (!bIsDead) { switch (BulletLevel) { case 1: InitBulletLevel(1); break; case 2: InitBulletLevel(2); break; case 3: InitBulletLevel(3); break; default: InitBulletLevel(1); break; } } } // Apply movement to bullets when they become active for (int i = 0; i < MAX_PLAYER_BULLETS; i++) { if (Bullet[i].bActive) { // Bullet movement Bullet[i].Location.y -= Bullet[i].Speed * GetFrameTime(); // Move the center location with bullet movement Bullet[i].Center.x = Bullet[i].Location.x + float(Bullet[i].Sprite.width)/8; Bullet[i].Center.y = Bullet[i].Location.y + float(Bullet[i].Sprite.height); Bullet[i].UpdateAnimation(); } else Bullet[i].Location = Location; } } void Player::CheckBulletOutsideWindow() { for (int i = 0; i < MAX_PLAYER_BULLETS; i++) if (Bullet[i].Location.y + Bullet[i].Sprite.height < 0) ResetBullet(i); } void Player::CheckCollisionWithWindow() { if (Location.x + float(Sprite.width)/4 > GetScreenWidth()-PANEL_WIDTH) { Location.x = GetScreenWidth()-PANEL_WIDTH - float(Sprite.width)/4; Hitbox.x = GetScreenWidth()-PANEL_WIDTH - float(Sprite.width)/6 - 3.0f; BulletSpawnLocation.x = GetScreenWidth()-PANEL_WIDTH - float(Sprite.width)/6 + 23.0f; } if (Location.y + float(Sprite.height)/2 > GetScreenHeight()) { Location.y = float(GetScreenHeight()) - float(Sprite.height)/2; Hitbox.y = float(GetScreenHeight() - 7.0f); BulletSpawnLocation.y = float(GetScreenHeight()) - float(Sprite.height)/2; } if (Location.x < 0.0f) { Location.x = 0.0f; Hitbox.x = float(Sprite.width)/12 - 3.0f; BulletSpawnLocation.x = float(Sprite.width)/6 + 3.0f; } if (Location.y < 0.0f) { Location.y = 0.0f; Hitbox.y = float(Sprite.height)/2 - 7.0f; } } void Player::CheckHealth() { if (Health <= 0) { // Prevent negative health values Health = 0; Heart.clear(); Bomb.clear(); bIsDead = true; Deaths++; *GameState = DEATH; } } void Player::Invincibility(const bool Mode, const float Seconds) { FramesCounter++; if (Mode && Seconds > 0.0f) { bInvincible = true; if (fmodf(FramesCounter/(GetFPS()*Seconds), 2) == 1) { FramesCounter = 0; bInvincible = false; bIsHit = false; } } else if (Mode && Seconds <= 0.0f) { bInvincible = true; Health = 6; } else if (!Mode && Seconds > 0.0f) { bInvincible = false; if (fmodf(FramesCounter/(GetFPS()*Seconds), 2) == 1) { FramesCounter = 0; bInvincible = true; bIsHit = true; } } else if (!Mode && Seconds <= 0.0f) bInvincible = false; if (FramesCounter > 120*Seconds) FramesCounter = 0; }
fdac34c01fcbfb1fbba5c0c29046dd1c0453ed4a
9cb52fa70eb57fa0cc13bd37b6dd6b5f8b3468a5
/oop/oop/move-constructors/Move.hpp
1c07df072d684a0068d9324413d8ddde2d299ee9
[]
no_license
AybarsAcar/cpp-learning-material
e095ebc006d933506c0f3516131074c6318eb461
c00573dd6080e955aa9997b0e01c2a0ada6a4c4c
refs/heads/master
2023-02-12T21:12:39.103841
2021-01-15T00:27:22
2021-01-15T00:27:22
329,767,628
0
0
null
null
null
null
UTF-8
C++
false
false
531
hpp
Move.hpp
// // Move.hpp // oop // // Created by Aybars Acar on 10/1/21. // #ifndef Move_hpp #define Move_hpp #include <stdio.h> /** * Class that has a move constructor */ class Move { private: int *data; public: Move(int d); // constructor Move(const Move &source); // copy constructor Move(Move &&source) noexcept; // move construcotor ~Move(); // destructor void setData(int d); int getData(); }; #endif /* Move_hpp */
e800745457d6dca5835526380679e834f2a9f32d
e312cfd866411780194e923f7e34c3e849b7545b
/lib/word.cpp
6dd357679b653af60ccc42214ebd7dc184f3e768
[]
no_license
HishamLY/TugasUTSGrafika
d9eafb41a3504006140661abd2f4b4f7bdbdcac0
5615527a41fe65fee63135d2fe1df5e504a177f8
refs/heads/master
2021-09-27T21:46:50.005828
2018-11-11T22:35:18
2018-11-11T22:35:18
125,203,362
0
0
null
null
null
null
UTF-8
C++
false
false
27,767
cpp
word.cpp
#include "word.h" #include <iostream> using namespace std; Word::Word(char _c): c(_c) { start_fill_x = 11; start_fill_y = 8; } Matriks Word::draw() { if (c == 'p' || c == 'P') return drawP(); else if (c == 'y' || c == 'Y') return drawY(); else if (c == 'z' || c == 'Z') return drawZ(); else if (c == 'g' || c == 'G') return drawG(); else if(c == 'n' || c == 'N') return drawN(); else if(c == 'a' || c == 'A') return drawA(); else if(c == 'u' || c == 'U') return drawU(); else if(c == 'h' || c == 'H') return drawh(); else if (c == 'X') return drawParachute(); } Matriks Word::drawParachute() { Matriks map(365,390); int lines[636][4] = { {179, 3, 199, 3}, {164, 4, 213, 4}, {155, 5, 221, 5}, {148, 6, 229, 6}, {142, 7, 234, 7}, {137, 8, 240, 8}, {132, 9, 245, 9}, {128, 10, 249, 10}, {124, 11, 253, 11}, {120, 12, 257, 12}, {116, 13, 261, 13}, {113, 14, 264, 14}, {110, 15, 267, 15}, {107, 16, 271, 16}, {104, 17, 274, 17}, {101, 18, 277, 18}, {98, 19, 279, 19}, {96, 20, 282, 20}, {93, 21, 285, 21}, {91, 22, 288, 22}, {88, 23, 290, 23}, {85, 24, 292, 24}, {83, 25, 295, 25}, {81, 26, 297, 26}, {79, 27, 299, 27}, {76, 28, 302, 28}, {74, 29, 304, 29}, {72, 30, 306, 30}, {70, 31, 308, 31}, {68, 32, 310, 32}, {66, 33, 312, 33}, {64, 34, 314, 34}, {62, 35, 316, 35}, {60, 36, 318, 36}, {59, 37, 320, 37}, {57, 38, 321, 38}, {55, 39, 323, 39}, {53, 40, 325, 40}, {52, 41, 327, 41}, {50, 42, 328, 42}, {48, 43, 330, 43}, {46, 44, 332, 44}, {45, 45, 333, 45}, {43, 46, 335, 46}, {42, 47, 336, 47}, {40, 48, 338, 48}, {38, 49, 339, 49}, {37, 50, 341, 50}, {35, 51, 342, 51}, {34, 52, 344, 52}, {32, 53, 345, 53}, {31, 54, 346, 54}, {29, 55, 348, 55}, {28, 56, 349, 56}, {27, 57, 350, 57}, {25, 58, 351, 58}, {24, 59, 353, 59}, {22, 60, 354, 60}, {21, 61, 355, 61}, {20, 62, 356, 62}, {18, 63, 357, 63}, {17, 64, 358, 64}, {16, 65, 358, 65}, {14, 66, 359, 66}, {9, 67, 11, 67}, {13, 67, 360, 67}, {8, 68, 360, 68}, {8, 69, 360, 69}, {8, 70, 360, 70}, {9, 71, 359, 71}, {10, 72, 357, 72}, {10, 73, 356, 73}, {11, 74, 355, 74}, {12, 75, 355, 75}, {12, 76, 354, 76}, {13, 77, 353, 77}, {14, 78, 352, 78}, {15, 79, 352, 79}, {15, 80, 351, 80}, {16, 81, 350, 81}, {17, 82, 349, 82}, {17, 83, 349, 83}, {18, 84, 348, 84}, {19, 85, 347, 85}, {19, 86, 347, 86}, {20, 87, 346, 87}, {21, 88, 345, 88}, {22, 89, 344, 89}, {22, 90, 344, 90}, {23, 91, 343, 91}, {24, 92, 342, 92}, {24, 93, 341, 93}, {25, 94, 341, 94}, {26, 95, 340, 95}, {27, 96, 339, 96}, {27, 97, 339, 97}, {28, 98, 338, 98}, {29, 99, 337, 99}, {29, 100, 336, 100}, {30, 101, 336, 101}, {31, 102, 335, 102}, {31, 103, 334, 103}, {32, 104, 333, 104}, {33, 105, 333, 105}, {34, 106, 332, 106}, {34, 107, 331, 107}, {35, 108, 331, 108}, {36, 109, 330, 109}, {36, 110, 329, 110}, {37, 111, 328, 111}, {38, 112, 328, 112}, {39, 113, 327, 113}, {39, 114, 326, 114}, {40, 115, 325, 115}, {41, 116, 325, 116}, {41, 117, 324, 117}, {42, 118, 323, 118}, {43, 119, 323, 119}, {44, 120, 322, 120}, {44, 121, 321, 121}, {45, 122, 320, 122}, {46, 123, 320, 123}, {46, 124, 319, 124}, {47, 125, 318, 125}, {48, 126, 317, 126}, {48, 127, 317, 127}, {49, 128, 316, 128}, {50, 129, 315, 129}, {51, 130, 315, 130}, {51, 131, 314, 131}, {52, 132, 313, 132}, {53, 133, 312, 133}, {53, 134, 312, 134}, {54, 135, 311, 135}, {55, 136, 310, 136}, {56, 137, 309, 137}, {56, 138, 309, 138}, {57, 139, 308, 139}, {58, 140, 181, 140}, {203, 140, 307, 140}, {58, 141, 175, 141}, {208, 141, 307, 141}, {59, 142, 171, 142}, {212, 142, 306, 142}, {60, 143, 167, 143}, {215, 143, 305, 143}, {61, 144, 163, 144}, {218, 144, 304, 144}, {61, 145, 160, 145}, {220, 145, 304, 145}, {62, 146, 157, 146}, {223, 146, 303, 146}, {63, 147, 154, 147}, {225, 147, 302, 147}, {63, 148, 151, 148}, {227, 148, 301, 148}, {64, 149, 149, 149}, {230, 149, 301, 149}, {65, 150, 146, 150}, {231, 150, 300, 150}, {65, 151, 143, 151}, {233, 151, 299, 151}, {66, 152, 141, 152}, {235, 152, 299, 152}, {67, 153, 138, 153}, {237, 153, 298, 153}, {68, 154, 136, 154}, {239, 154, 297, 154}, {68, 155, 133, 155}, {241, 155, 296, 155}, {69, 156, 131, 156}, {243, 156, 296, 156}, {70, 157, 129, 157}, {245, 157, 295, 157}, {70, 158, 126, 158}, {246, 158, 294, 158}, {71, 159, 124, 159}, {248, 159, 293, 159}, {72, 160, 121, 160}, {250, 160, 293, 160}, {73, 161, 119, 161}, {252, 161, 292, 161}, {73, 162, 117, 162}, {253, 162, 291, 162}, {74, 163, 115, 163}, {255, 163, 291, 163}, {75, 164, 112, 164}, {257, 164, 290, 164}, {75, 165, 110, 165}, {258, 165, 289, 165}, {76, 166, 108, 166}, {260, 166, 288, 166}, {77, 167, 105, 167}, {262, 167, 288, 167}, {77, 168, 103, 168}, {263, 168, 287, 168}, {78, 169, 101, 169}, {265, 169, 286, 169}, {79, 170, 99, 170}, {266, 170, 285, 170}, {80, 171, 96, 171}, {268, 171, 285, 171}, {80, 172, 94, 172}, {270, 172, 284, 172}, {81, 173, 92, 173}, {271, 173, 283, 173}, {82, 174, 90, 174}, {273, 174, 283, 174}, {82, 175, 87, 175}, {275, 175, 282, 175}, {82, 176, 88, 176}, {276, 176, 282, 176}, {83, 177, 88, 177}, {275, 177, 282, 177}, {84, 178, 89, 178}, {275, 178, 281, 178}, {85, 179, 90, 179}, {275, 179, 280, 179}, {85, 180, 91, 180}, {274, 180, 279, 180}, {86, 181, 92, 181}, {273, 181, 279, 181}, {87, 182, 93, 182}, {272, 182, 278, 182}, {88, 183, 93, 183}, {271, 183, 277, 183}, {89, 184, 94, 184}, {270, 184, 276, 184}, {90, 185, 95, 185}, {269, 185, 275, 185}, {90, 186, 96, 186}, {269, 186, 274, 186}, {91, 187, 97, 187}, {268, 187, 273, 187}, {92, 188, 98, 188}, {267, 188, 273, 188}, {93, 189, 98, 189}, {266, 189, 272, 189}, {94, 190, 99, 190}, {265, 190, 271, 190}, {95, 191, 100, 191}, {264, 191, 270, 191}, {95, 192, 101, 192}, {263, 192, 269, 192}, {96, 193, 102, 193}, {263, 193, 268, 193}, {97, 194, 102, 194}, {262, 194, 267, 194}, {98, 195, 103, 195}, {261, 195, 266, 195}, {99, 196, 104, 196}, {260, 196, 266, 196}, {100, 197, 105, 197}, {259, 197, 265, 197}, {100, 198, 106, 198}, {258, 198, 264, 198}, {101, 199, 107, 199}, {257, 199, 263, 199}, {102, 200, 107, 200}, {256, 200, 262, 200}, {103, 201, 108, 201}, {256, 201, 261, 201}, {104, 202, 109, 202}, {255, 202, 260, 202}, {104, 203, 110, 203}, {254, 203, 260, 203}, {105, 204, 111, 204}, {253, 204, 259, 204}, {106, 205, 112, 205}, {252, 205, 258, 205}, {107, 206, 112, 206}, {251, 206, 257, 206}, {108, 207, 113, 207}, {250, 207, 256, 207}, {109, 208, 114, 208}, {250, 208, 255, 208}, {109, 209, 115, 209}, {249, 209, 254, 209}, {110, 210, 116, 210}, {248, 210, 254, 210}, {111, 211, 117, 211}, {247, 211, 253, 211}, {112, 212, 117, 212}, {246, 212, 252, 212}, {113, 213, 118, 213}, {245, 213, 251, 213}, {114, 214, 119, 214}, {244, 214, 250, 214}, {114, 215, 120, 215}, {244, 215, 249, 215}, {115, 216, 121, 216}, {243, 216, 248, 216}, {116, 217, 122, 217}, {242, 217, 247, 217}, {117, 218, 122, 218}, {241, 218, 247, 218}, {118, 219, 123, 219}, {240, 219, 246, 219}, {119, 220, 124, 220}, {239, 220, 245, 220}, {119, 221, 125, 221}, {238, 221, 244, 221}, {120, 222, 126, 222}, {237, 222, 243, 222}, {121, 223, 127, 223}, {237, 223, 242, 223}, {122, 224, 127, 224}, {236, 224, 241, 224}, {123, 225, 128, 225}, {235, 225, 241, 225}, {124, 226, 129, 226}, {234, 226, 240, 226}, {124, 227, 130, 227}, {233, 227, 239, 227}, {125, 228, 131, 228}, {232, 228, 238, 228}, {126, 229, 131, 229}, {231, 229, 237, 229}, {127, 230, 132, 230}, {231, 230, 236, 230}, {128, 231, 133, 231}, {230, 231, 235, 231}, {129, 232, 134, 232}, {229, 232, 235, 232}, {129, 233, 135, 233}, {228, 233, 234, 233}, {130, 234, 136, 234}, {227, 234, 233, 234}, {131, 235, 136, 235}, {226, 235, 232, 235}, {132, 236, 137, 236}, {225, 236, 231, 236}, {133, 237, 138, 237}, {224, 237, 230, 237}, {134, 238, 139, 238}, {223, 238, 229, 238}, {134, 239, 140, 239}, {223, 239, 228, 239}, {135, 240, 141, 240}, {222, 240, 228, 240}, {136, 241, 141, 241}, {221, 241, 227, 241}, {137, 242, 142, 242}, {221, 242, 226, 242}, {138, 243, 143, 243}, {221, 243, 225, 243}, {138, 244, 144, 244}, {220, 244, 225, 244}, {139, 245, 145, 245}, {148, 245, 150, 245}, {220, 245, 225, 245}, {140, 246, 151, 246}, {219, 246, 224, 246}, {141, 247, 151, 247}, {219, 247, 224, 247}, {142, 248, 152, 248}, {218, 248, 223, 248}, {143, 249, 152, 249}, {218, 249, 223, 249}, {143, 250, 153, 250}, {218, 250, 222, 250}, {144, 251, 153, 251}, {217, 251, 222, 251}, {145, 252, 154, 252}, {217, 252, 221, 252}, {146, 253, 148, 253}, {150, 253, 154, 253}, {216, 253, 221, 253}, {150, 254, 155, 254}, {216, 254, 220, 254}, {150, 255, 155, 255}, {215, 255, 220, 255}, {151, 256, 155, 256}, {215, 256, 219, 256}, {151, 257, 156, 257}, {214, 257, 219, 257}, {152, 258, 156, 258}, {214, 258, 218, 258}, {152, 259, 157, 259}, {213, 259, 218, 259}, {153, 260, 157, 260}, {213, 260, 217, 260}, {153, 261, 158, 261}, {212, 261, 217, 261}, {154, 262, 158, 262}, {212, 262, 216, 262}, {154, 263, 159, 263}, {183, 263, 190, 263}, {211, 263, 216, 263}, {155, 264, 159, 264}, {180, 264, 194, 264}, {211, 264, 216, 264}, {155, 265, 160, 265}, {178, 265, 196, 265}, {210, 265, 215, 265}, {156, 266, 160, 266}, {176, 266, 197, 266}, {210, 266, 215, 266}, {156, 267, 161, 267}, {175, 267, 199, 267}, {209, 267, 214, 267}, {156, 268, 161, 268}, {173, 268, 182, 268}, {191, 268, 200, 268}, {209, 268, 214, 268}, {157, 269, 161, 269}, {172, 269, 180, 269}, {194, 269, 201, 269}, {209, 269, 213, 269}, {157, 270, 162, 270}, {171, 270, 178, 270}, {195, 270, 202, 270}, {208, 270, 213, 270}, {158, 271, 162, 271}, {171, 271, 177, 271}, {197, 271, 202, 271}, {208, 271, 212, 271}, {158, 272, 163, 272}, {170, 272, 175, 272}, {198, 272, 203, 272}, {207, 272, 212, 272}, {159, 273, 163, 273}, {170, 273, 175, 273}, {199, 273, 203, 273}, {207, 273, 211, 273}, {159, 274, 164, 274}, {169, 274, 174, 274}, {199, 274, 204, 274}, {206, 274, 211, 274}, {160, 275, 164, 275}, {169, 275, 173, 275}, {200, 275, 204, 275}, {206, 275, 210, 275}, {160, 276, 165, 276}, {169, 276, 173, 276}, {200, 276, 210, 276}, {161, 277, 165, 277}, {168, 277, 172, 277}, {201, 277, 209, 277}, {161, 278, 166, 278}, {168, 278, 172, 278}, {201, 278, 209, 278}, {162, 279, 166, 279}, {168, 279, 172, 279}, {201, 279, 208, 279}, {162, 280, 172, 280}, {201, 280, 208, 280}, {162, 281, 172, 281}, {201, 281, 207, 281}, {163, 282, 172, 282}, {201, 282, 207, 282}, {163, 283, 172, 283}, {201, 283, 207, 283}, {164, 284, 173, 284}, {200, 284, 206, 284}, {164, 285, 173, 285}, {200, 285, 206, 285}, {165, 286, 174, 286}, {199, 286, 205, 286}, {165, 287, 174, 287}, {199, 287, 205, 287}, {166, 288, 175, 288}, {198, 288, 204, 288}, {166, 289, 176, 289}, {197, 289, 204, 289}, {167, 290, 178, 290}, {184, 290, 189, 290}, {195, 290, 203, 290}, {167, 291, 179, 291}, {182, 291, 191, 291}, {194, 291, 203, 291}, {168, 292, 202, 292}, {168, 293, 202, 293}, {168, 294, 173, 294}, {176, 294, 201, 294}, {169, 295, 173, 295}, {177, 295, 201, 295}, {169, 296, 174, 296}, {178, 296, 200, 296}, {170, 297, 174, 297}, {177, 297, 200, 297}, {170, 298, 181, 298}, {192, 298, 199, 298}, {171, 299, 181, 299}, {193, 299, 197, 299}, {171, 300, 180, 300}, {193, 300, 198, 300}, {172, 301, 180, 301}, {194, 301, 198, 301}, {175, 302, 179, 302}, {194, 302, 198, 302}, {175, 303, 179, 303}, {194, 303, 199, 303}, {174, 304, 178, 304}, {195, 304, 199, 304}, {174, 305, 178, 305}, {195, 305, 199, 305}, {174, 306, 178, 306}, {195, 306, 199, 306}, {174, 307, 178, 307}, {195, 307, 199, 307}, {174, 308, 178, 308}, {196, 308, 200, 308}, {173, 309, 177, 309}, {196, 309, 200, 309}, {173, 310, 177, 310}, {196, 310, 200, 310}, {173, 311, 177, 311}, {196, 311, 200, 311}, {173, 312, 177, 312}, {196, 312, 200, 312}, {173, 313, 177, 313}, {196, 313, 200, 313}, {173, 314, 177, 314}, {196, 314, 200, 314}, {173, 315, 177, 315}, {196, 315, 200, 315}, {173, 316, 177, 316}, {196, 316, 200, 316}, {173, 317, 177, 317}, {196, 317, 200, 317}, {173, 318, 177, 318}, {196, 318, 200, 318}, {173, 319, 177, 319}, {196, 319, 200, 319}, {174, 320, 178, 320}, {196, 320, 200, 320}, {174, 321, 178, 321}, {195, 321, 199, 321}, {174, 322, 178, 322}, {195, 322, 199, 322}, {174, 323, 178, 323}, {195, 323, 199, 323}, {174, 324, 178, 324}, {195, 324, 199, 324}, {175, 325, 179, 325}, {194, 325, 199, 325}, {175, 326, 179, 326}, {194, 326, 198, 326}, {175, 327, 179, 327}, {194, 327, 198, 327}, {176, 328, 180, 328}, {193, 328, 198, 328}, {176, 329, 180, 329}, {193, 329, 197, 329}, {176, 330, 181, 330}, {192, 330, 197, 330}, {177, 331, 182, 331}, {191, 331, 197, 331}, {177, 332, 183, 332}, {190, 332, 198, 332}, {178, 333, 184, 333}, {189, 333, 198, 333}, {179, 334, 199, 334}, {180, 335, 193, 335}, {195, 335, 199, 335}, {181, 336, 192, 336}, {195, 336, 200, 336}, {181, 337, 191, 337}, {196, 337, 200, 337}, {181, 338, 189, 338}, {196, 338, 201, 338}, {180, 339, 185, 339}, {197, 339, 201, 339}, {180, 340, 184, 340}, {197, 340, 202, 340}, {180, 341, 184, 341}, {197, 341, 202, 341}, {179, 342, 184, 342}, {198, 342, 203, 342}, {179, 343, 183, 343}, {198, 343, 203, 343}, {179, 344, 183, 344}, {199, 344, 204, 344}, {178, 345, 183, 345}, {199, 345, 204, 345}, {178, 346, 182, 346}, {200, 346, 204, 346}, {178, 347, 182, 347}, {200, 347, 205, 347}, {177, 348, 182, 348}, {201, 348, 205, 348}, {177, 349, 181, 349}, {201, 349, 206, 349}, {177, 350, 181, 350}, {202, 350, 206, 350}, {176, 351, 181, 351}, {202, 351, 207, 351}, {176, 352, 180, 352}, {203, 352, 207, 352}, {176, 353, 180, 353}, {203, 353, 208, 353}, {175, 354, 180, 354}, {204, 354, 208, 354}, {175, 355, 179, 355}, {204, 355, 209, 355}, {175, 356, 179, 356}, {205, 356, 209, 356}, {174, 357, 179, 357}, {205, 357, 210, 357}, {174, 358, 178, 358}, {206, 358, 210, 358}, {174, 359, 178, 359}, {206, 359, 211, 359}, {173, 360, 178, 360}, {206, 360, 211, 360}, {173, 361, 177, 361}, {207, 361, 212, 361}, {173, 362, 177, 362}, {207, 362, 212, 362}, {172, 363, 177, 363}, {208, 363, 212, 363}, {172, 364, 176, 364}, {208, 364, 213, 364}, {172, 365, 176, 365}, {209, 365, 213, 365}, {171, 366, 176, 366}, {209, 366, 214, 366}, {171, 367, 175, 367}, {210, 367, 214, 367}, {171, 368, 175, 368}, {210, 368, 215, 368}, {170, 369, 175, 369}, {211, 369, 215, 369}, {170, 370, 174, 370}, {211, 370, 215, 370}, {170, 371, 174, 371}, {212, 371, 214, 371}, {170, 372, 174, 372}, {169, 373, 174, 373}, {169, 374, 173, 374}, {169, 375, 173, 375}, {168, 376, 173, 376}, {168, 377, 172, 377}, {168, 378, 172, 378}, {169, 379, 171, 379} }; for (int i = 0; i < 636; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } return map; } Matriks Word::drawP() { // Set points Matriks map(80,80); int lines [10][4] = { {0,0,70,0},{70,0,70,40},{70,40,20,40},{20,40,20,79},{20,79,0,79},{0,79,0,0}, {20,10,60,10},{60,10,60,30},{60,30,20,30},{20,30,20,10} }; for (int i = 0; i < 10; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map,start_fill_x,start_fill_y); return map; } Matriks Word::drawY() { Matriks map(80,80); // Gambar int lines[9][4] = { {0, 0, 20, 0}, {0, 0, 30, 54}, {20, 0, 40, 34}, {49, 54, 79, 0}, {39, 34, 59, 0}, {59, 0, 79, 0}, {30, 54, 30, 79}, {30, 79, 49, 79}, {49, 54, 49, 79} }; for (int i = 0; i < 9; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map,start_fill_x,start_fill_y); return map; } Matriks Word::drawG() { Matriks map(80, 80); // Gambar int lines[12][4] = { {0, 0, 79, 0}, {79, 0, 79, 20}, {0, 0, 0, 79}, {79, 20, 20, 20}, {20, 20, 20, 59}, {20, 59, 59, 59}, {59, 59, 59, 49}, {59, 49, 49, 49}, {49, 49, 49, 29}, {49, 29, 79, 29}, {79, 29, 79, 79}, {79, 79, 0, 79} }; for (int i = 0; i < 12; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map,start_fill_x,start_fill_y); return map; } Matriks Word::drawN() { Matriks map(80, 80); // Gambar int lines[12][4] = { {0, 0, 20, 0}, {0, 0, 0, 79}, {0, 79, 20, 79}, {20, 79, 20, 29}, {20, 29, 59, 79}, {59, 79, 79, 79}, {79, 79, 79, 0}, {79, 0, 59, 0}, {59, 0, 59, 59}, {59, 59, 20, 0} }; for (int i = 0; i < 12; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map,start_fill_x,start_fill_y); return map; } Matriks Word::drawA() { Matriks map(80, 80); // Gambar int lines[12][4] = { {0, 30, 49, 30}, {49, 30, 49, 79}, {49, 79, 0, 79}, {0, 79, 0, 50}, {0, 50, 39, 50}, {39, 50, 39, 40}, {39, 40, 0, 40}, {0, 40, 0, 30}, {39, 69, 10, 69}, {10, 69, 10, 59}, {10, 59, 39, 59}, {39, 59, 39, 69} }; for (int i = 0; i < 12; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map,1,31); return map; } Matriks Word::drawZ() { // Set points Matriks map(80,80); int lines [10][4] = { {1,1,78,1},{78,1,78,8},{78,8,8,70},{8,70,78,70},{78,70,78,78},{78,78,1,78}, {1,78,1,70},{1,70,70,8},{70,8,1,8},{1,8,1,1} }; for (int i = 0; i < 10; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map, 2, 2); return map; } Matriks Word::drawU() { // Set points Matriks map(80,80); int lines [16][4] = { {15, 19, 31, 19}, {31, 19, 31, 63}, {31, 63, 55, 63}, {55, 63, 55, 23}, {55, 23, 47, 23}, {47, 23, 47, 19}, {47, 19, 63, 19}, {63, 19, 63, 63}, {63, 63, 67, 63}, {67, 63, 67, 67}, {67, 67, 63, 71}, {63, 71, 31, 71}, {31, 71, 23, 63}, {23, 63, 23, 23}, {23, 23, 15, 23}, {15, 23, 15, 19} }; for (int i = 0; i < 16; i++) { draw_line(map,lines[i][0],lines[i][1],lines[i][2],lines[i][3]); } floodFill(map, 16, 20); return map; } Matriks Word::drawh() { // Set points Matriks map(50,50); int pixel[2500] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { map.setVal(j, i, pixel[i*50 + j]); } } floodFill(map, 10, 10); return map; } void Word::floodFill(Matriks& m,int s_x, int s_y) { queue<Point> my_q; my_q.push(Point(s_x,s_y)); m.setVal(s_x,s_y,1); while (my_q.size() > 0 ) { int p_x = my_q.front().getX(); int p_y = my_q.front().getY(); if (m.getVal(p_x-1,p_y) == 0) { my_q.push(Point(p_x-1,p_y)); m.setVal(p_x-1,p_y,1); } if (m.getVal(p_x+1,p_y) == 0) { my_q.push(Point(p_x+1,p_y)); m.setVal(p_x+1,p_y,1); } if (m.getVal(p_x,p_y-1) == 0) { my_q.push(Point(p_x,p_y-1)); m.setVal(p_x,p_y-1,1); } if (m.getVal(p_x,p_y+1) == 0) { my_q.push(Point(p_x,p_y+1)); m.setVal(p_x,p_y+1,1); } my_q.pop(); } } void Word::draw_line_low(Matriks &m,int x0,int y0,int x1,int y1) { int dx = x1 - x0; int dy = y1 - y0; int yi = 1; if (dy < 0) { yi = -1; dy = -dy; } int D = 2*dy - dx; int y = y0; for (int x = x0; x <= x1; x++) { m.setVal(x,y,1); if (D > 0) { y += yi; D -= 2*dx; } D += 2*dy; } } void Word::draw_line_high(Matriks &m,int x0,int y0,int x1,int y1) { int dx = x1 - x0; int dy = y1 - y0; int xi = 1; if (dx < 0) { xi = -1; dx = -dx; } int D = 2*dx - dy; int x = x0; for (int y = y0; y <= y1; y++) { m.setVal(x,y,1); if (D > 0) { x += xi; D -= 2*dy; } D += 2*dx; } } void Word::draw_line(Matriks &m,int x0, int y0, int x1, int y1) { if (abs(y1 - y0) < abs(x1 - x0)) if (x0 > x1) draw_line_low(m,x1, y1, x0, y0); else draw_line_low(m,x0, y0, x1, y1); else if (y0 > y1) draw_line_high(m,x1, y1, x0, y0); else draw_line_high(m,x0, y0, x1, y1); }
c918050f1d09fc50bed95f6a1bb05cb6da482ab3
4bf2ee10c6594f70c32feb3bcb50eec186daa9cf
/solutions/2482/2482.cpp14.cpp
4792ba18c6fe363dc48e3ede44b3895032029f4e
[]
no_license
jwvg0425/boj
7674928dc012ba3c404cef3a76aa753828e09761
4b7e7389cbe55270bd0dab546d6e84817477b0f1
refs/heads/master
2020-07-14T02:37:36.658675
2017-07-13T06:11:44
2017-07-13T06:11:44
94,295,654
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
2482.cpp14.cpp
#include <stdio.h> #include <vector> #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <tuple> #include <memory.h> #define MOD 1000000003 int table[1001][1001]; //n개짜리 색상환에서 인접한 거 선택 안 하고 k개 고르는 경우의 수 int solve(int n, int k) { if (n <= 0) { if (k > 0) return 0; else return 1; } if (k == 0) return 1; if (table[n][k] != -1) return table[n][k]; int& res = table[n][k]; res = (solve(n - 2, k - 1) + solve(n - 1, k)) % MOD; return res; } int main() { memset(table, -1, sizeof(table)); int n, k; scanf("%d %d", &n, &k); printf("%d", (solve(n - 3, k - 1) + solve(n - 1, k)) % MOD); return 0; }
29a1469af919431e8aae25a4521e961325263df9
5bddb7782c09facdef854f822f39f7d9aab597de
/Library Management System/onhold.h
996617ce72174796782e9fae8b59c4c1f7748fc7
[]
no_license
jamshaidsohail5/Library-Management-System
2b3f7211f3e0c1e272773c2d1f2b6ff2f2d115cd
f8d8478b6bf4b6ea76bff643877092100b294954
refs/heads/master
2021-04-15T15:16:47.182689
2018-03-26T01:46:57
2018-03-26T01:46:57
126,757,526
0
0
null
null
null
null
UTF-8
C++
false
false
269
h
onhold.h
#ifndef ONHOLD_H #define ONHOLD_H #include"state.h" #include "user.h" #include "libitem.h" #include "date.h" #include "loan.h" class onhold:public State { public: onhold(); void add_loan(user * u,Libitem*li,Date ida,Date rda,loan *l); }; #endif // ONHOLD_H
355110354e9dce2445e5ff535fb1de252062d5e5
6712f8313dd77ae820aaf400a5836a36af003075
/zOrder.h
6b75b840bd0d0848a7ddf0ad02d2b6d8c7490a11
[]
no_license
AdamTT1/bdScript
d83c7c63c2c992e516dca118cfeb34af65955c14
5483f239935ec02ad082666021077cbc74d1790c
refs/heads/master
2021-12-02T22:57:35.846198
2010-08-08T22:32:02
2010-08-08T22:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,001
h
zOrder.h
#ifndef __ZORDER_H__ #define __ZORDER_H__ "$Id: zOrder.h,v 1.3 2006-12-01 18:47:47 tkisky Exp $" /* * zOrder.h * * This header file declares the zOrderMap_t and * zOrderMapStack_t classes, which are used to keep * track of the objects occupying a piece of screen * real estate. * * * Change History : * * $Log: zOrder.h,v $ * Revision 1.3 2006-12-01 18:47:47 tkisky * -friend function definition * * Revision 1.2 2003/11/24 19:08:46 ericn * -modified to check range of inputs to getBox() * * Revision 1.1 2002/11/21 14:09:52 ericn * -Initial import * * * * Copyright Boundary Devices, Inc. 2002 */ #ifndef __BOX_H__ #include "box.h" #endif #include <list> #include <vector> class zOrderMap_t { public: zOrderMap_t( void ); // starts off empty ~zOrderMap_t( void ); box_t *getBox( unsigned short x, unsigned short y ) const ; void addBox( box_t const & ); void removeBox( box_t const & ); private: unsigned short const width_ ; // from frame buffer device unsigned short const height_ ; // " box_t::id_t * const boxes_ ; friend void dumpZMap( zOrderMap_t const &map ); }; class zOrderMapStack_t { public: void addBox( box_t const & ); void removeBox( box_t const & ); zOrderMap_t &top( void ); // // increase the depth of the stack // void push(); // // decrease the depth of the stack // void pop(); // // retrieve a set of box_t's occupying a pixel // set is returned in fore->back order, so getBoxes(0,0)[0] is // the top-most item occupying pixel 0,0 // std::vector<box_t *> getBoxes( unsigned short xPos, unsigned short yPos ) const ; private: zOrderMapStack_t( void ); ~zOrderMapStack_t( void ); typedef std::list<zOrderMap_t *> mapStack_t ; mapStack_t maps_ ; friend zOrderMapStack_t &getZMap(); friend void dumpZMaps( void ); friend void release_ZMap(); }; void release_ZMap(); zOrderMapStack_t &getZMap(); #endif
0b79f6d75535cb33fa8cd41fbb03751ba04ad243
6f635d39c3844633266eb7a23192ec1df2951c51
/src/screens/vrScreenSelectMusic.h
bf72a3c5f5ee688f602c4bd0132868b6a2ddbaac
[]
no_license
mvallebr/VivaRock
4e810fe0660a9fd8d1c39c7a80e050ab2dfc329a
20426c15ec9a44526411e03700d896be24b4ab77
refs/heads/master
2021-01-01T05:51:16.810334
2011-11-20T16:04:49
2011-11-20T16:04:49
2,812,661
0
0
null
null
null
null
UTF-8
C++
false
false
508
h
vrScreenSelectMusic.h
#ifndef VRSCREENSELECTMUSIC_H_ #define VRSCREENSELECTMUSIC_H_ #include <system/vrScreen.h> #include <core/vrPlayer.h> #include <irrlicht.h> using namespace irr; class VRScreenSelectMusic : public VRScreen { private: int selectedMusic; public: VRScreenSelectMusic(string name); virtual ~VRScreenSelectMusic(); virtual void open(); virtual void close(); virtual void render(); virtual void OnInputEvent(int playerNum, int key, bool pressed, bool shiftState); }; #endif /*VRSCREENSELECTMUSIC_H_*/
a7eb8c0435df26c1a78f172104731206df2196de
d205793571b39fe254f513f4437f37c47f4db011
/src/StateVector.cpp
7cc6e6b228869c59f64aea145f5f3eccd0d05287
[]
no_license
memanuel/kepler-sieve
ba996c4008edec3458ac0afbfa3bee95367467cd
9f11f377d82cb941d77159fd7b97ae2300b6ca6a
refs/heads/main
2021-11-22T19:07:13.725263
2021-08-08T20:44:47
2021-08-08T20:44:47
236,581,914
1
0
null
null
null
null
UTF-8
C++
false
false
10,562
cpp
StateVector.cpp
/** @file StateVector.cpp * @brief Implementation of class StateVector. * * @author Michael S. Emanuel * @date 2021-07-02 * */ // ***************************************************************************** // Local dependencies #include "StateVector.hpp" // ***************************************************************************** namespace ks { // ***************************************************************************** // Add two vectors // ***************************************************************************** // ***************************************************************************** Position operator+ (const Position& p1, const Position& p2) { // Add the two positions componentwise return Position { .qx = p1.qx + p2.qx, .qy = p1.qy + p2.qy, .qz = p1.qz + p2.qz }; } // ***************************************************************************** Velocity operator+ (const Velocity& v1, const Velocity& v2) { // Add the two velocities componentwise return Velocity { .vx = v1.vx + v2.vx, .vy = v1.vy + v2.vy, .vz = v1.vz + v2.vz }; } // ***************************************************************************** StateVector operator+ (const StateVector& s1, const StateVector& s2) { // Add the two state vectors componentwise return StateVector { .qx = s1.qx + s2.qx, .qy = s1.qy + s2.qy, .qz = s1.qz + s2.qz, .vx = s1.vx + s2.vx, .vy = s1.vy + s2.vy, .vz = s1.vz + s2.vz }; } // ***************************************************************************** // Subtract two vectors // ***************************************************************************** // ***************************************************************************** Position operator- (const Position& p1, const Position& p2) { // Add the two positions componentwise return Position { .qx = p1.qx - p2.qx, .qy = p1.qy - p2.qy, .qz = p1.qz - p2.qz }; } // ***************************************************************************** Velocity operator- (const Velocity& v1, const Velocity& v2) { // Add the two velocities componentwise return Velocity { .vx = v1.vx - v2.vx, .vy = v1.vy - v2.vy, .vz = v1.vz - v2.vz }; } // ***************************************************************************** StateVector operator- (const StateVector& s1, const StateVector& s2) { // Add the two positions componentwise return StateVector { .qx = s1.qx - s2.qx, .qy = s1.qy - s2.qy, .qz = s1.qz - s2.qz, .vx = s1.vx - s2.vx, .vy = s1.vy - s2.vy, .vz = s1.vz - s2.vz }; } // ***************************************************************************** // Multiply a velocity by a scalar // ***************************************************************************** // ***************************************************************************** Velocity operator* (const Velocity& v, const double alpha) { return Velocity { .vx = v.vx*alpha, .vy = v.vy*alpha, .vz = v.vz*alpha }; } // ***************************************************************************** Velocity operator* (const double alpha, const Velocity& v) { // Multiplication is commutative; delegate to to the previous definition with alpha on the right return operator* (v, alpha); } // ***************************************************************************** // Extract position and velocity from a state vector // ***************************************************************************** // ***************************************************************************** Position sv2pos(const StateVector& s) { return Position {.qx=s.qx, .qy=s.qy, .qz=s.qz}; } // ***************************************************************************** Velocity sv2vel(const StateVector& s) { return Velocity {.vx=s.vx, .vy=s.vy, .vz=s.vz}; } // ***************************************************************************** // Norm and distance of positions, velocities and state vectors // ***************************************************************************** // ***************************************************************************** double norm(const Position& p) { return sqrt(sqr(p.qx) + sqr(p.qy) + sqr(p.qz)); } // ***************************************************************************** double norm(const Velocity& v) { return sqrt(sqr(v.vx) + sqr(v.vy) + sqr(v.vz)); } // ***************************************************************************** double norm(const StateVector& s) { return sqrt(sqr(s.qx) + sqr(s.qy) + sqr(s.qz) + sqr(s.vx) + sqr(s.vy) + sqr(s.vz)); } // ***************************************************************************** double dist(const Position& p1, const Position& p2) {return norm(p2-p1);} // ***************************************************************************** double dist(const Velocity& v1, const Velocity& v2) {return norm(v2-v1);} // ***************************************************************************** double dist(const StateVector& s1, const StateVector& s2) {return norm(s2-s1);} // ***************************************************************************** double dist_dq(const StateVector& s1, const StateVector& s2) {return dist(sv2pos(s1), sv2pos(s2));} // ***************************************************************************** double dist_dv(const StateVector& s1, const StateVector& s2) {return dist(sv2vel(s1), sv2vel(s2));} // ***************************************************************************** double dist(const StateVector& s1, const Position& q2) { // Extract position component Position q1 = sv2pos(s1); return dist(q1, q2); } // ***************************************************************************** double dist(const Position& q1, const StateVector& s2) { // Extract position component Position q2 = sv2pos(s2); return dist(q1, q2); } // ***************************************************************************** double dist(const StateVector& s1, const Velocity& v2) { // Extract velocity component Velocity v1 = sv2vel(s1); return dist(v1, v2); } // ***************************************************************************** double dist(const Velocity& v1, const StateVector& s2) { // Extract velocity component Velocity v2 = sv2vel(s2); return dist(v1, v2); } // ***************************************************************************** // Check if two vectors are close // ***************************************************************************** // ***************************************************************************** bool is_close(const Position& p1, const Position& p2, double tol_dq) {return dist(p1, p2) < tol_dq;} // ***************************************************************************** bool is_close(const Velocity& v1, const Velocity& v2, double tol_dv) {return dist(v1, v2) < tol_dv;} // ***************************************************************************** bool is_close(const StateVector& s1, const StateVector& s2, double tol_dq, double tol_dv) { // Extract position and velocity components Position q1 = sv2pos(s1); Position q2 = sv2pos(s2); Velocity v1 = sv2vel(s1); Velocity v2 = sv2vel(s2); return (dist(q1, q2) < tol_dq) && (dist(v1, v2) < tol_dv); } // ***************************************************************************** bool is_close(const StateVector& s1, const Position& q2, double tol_dq) {return dist(s1, q2) < tol_dq;} // ***************************************************************************** bool is_close(const Position& q1, const StateVector& s2, double tol_dq) {return dist(q1, s2) < tol_dq;}; bool is_equal(const StateVector& s1, const StateVector& s2) {return (s1.qx==s2.qx) && (s1.qy==s2.qy) && (s1.qz==s2.qz) && (s1.vx==s2.vx) && (s1.vy==s2.vy) && (s1.vz==s2.vz);} // ***************************************************************************** // Print a position // ***************************************************************************** // ***************************************************************************** void print_position_headers(const string prefix) {print("{:s}{:10s} : {:10s} : {:10s}\n", prefix, " qx", " qy", " qz");} // ***************************************************************************** void print_position(const Position& p, const string prefix) {print("{:s}{:+10.6f} : {:+10.6f} : {:+10.6f}\n", prefix, p.qx, p.qy, p.qz);} // ***************************************************************************** void print_position_sci(const Position& p, const string prefix) {print("{:s}{:+10.2e} : {:+10.2e} : {:+10.2e}\n", prefix, p.qx, p.qy, p.qz);} // ***************************************************************************** // Print a state vector // ***************************************************************************** // ***************************************************************************** void print_state_vector_headers(const string prefix) {print("{:s}{:10s} : {:10s} : {:10s} : {:10s} : {:10s} : {:10s}\n", prefix, " qx", " qy", " qz", " vx", " vy", " vz");} // ***************************************************************************** void print_state_vector(const StateVector& s, const string prefix) {print("{:s}{:+10.6f} : {:+10.6f} : {:+10.6f} : {:+10.6f} : {:+10.6f} : {:+10.6f}\n", prefix, s.qx, s.qy, s.qz, s.vx, s.vy, s.vz);} // ***************************************************************************** void print_state_vector_sci(const StateVector& s, const string prefix) {print("{:s}{:+10.2e} : {:+10.2e} : {:+10.2e} : {:+10.2e} : {:+10.2e} : {:+10.2e}\n", prefix, s.qx, s.qy, s.qz, s.vx, s.vy, s.vz);} // ***************************************************************************** void print_state_vector_long(const StateVector& s) { print("qx = {:+12.8f}\n", s.qx); print("qy = {:+12.8f}\n", s.qy); print("qz = {:+12.8f}\n", s.qz); print("vx = {:+12.8f}\n", s.vx); print("vy = {:+12.8f}\n", s.vy); print("vz = {:+12.8f}\n", s.vz); } // ***************************************************************************** } // namespace ks
b4ac7d65b3db48261816e973aa3b776eb90709e9
a4736d6be8fe24919dc899ca3ecf0da5ffd40c43
/1133.cpp
797d3505fc7536a972f7ef4a6edbf7058947e75a
[]
no_license
VauP/URI_Judge_SolutionsCPP
4df49b6e8211e40b9c171f249d1983e85c42dfc1
9f0b504e281154aa7389b0b4001620f08c19b20a
refs/heads/master
2023-02-17T13:21:47.868588
2021-01-13T18:15:46
2021-01-13T18:15:46
292,113,263
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
1133.cpp
#include <iostream> using namespace std; int main(){ int x,y,m=0,ma=0; cin>>x; cin>>y; ma=x; if(y>=ma){ma=y;m=x;} else {ma=x; m=y;} for(int i=m+1;i<ma;i++){ if(i%5==2 ||i%5==3){cout<<i<<endl;} } return 0; }
efad82a9b3ae0ccb73002a89b3b52e7e817e4f07
08f258b8a4feec9d148632e2666cb8d030edccbf
/Actions/PlaySoundAction.cpp
7e4f62ead1e20af79a27e5bfad39bef3c64260c9
[]
no_license
alienjon/Escape-
56eab369d8095b4332bed6c0421cd6037056e211
62741ed573b1c01209cd24a5eabc02325bdb4868
refs/heads/master
2020-04-13T20:51:15.526752
2013-06-29T05:25:58
2013-06-29T05:25:58
1,593,887
1
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
PlaySoundAction.cpp
/* * PlaySoundAction.cpp * * Created on: Aug 12, 2009 * Author: alienjon */ #include "PlaySoundAction.hpp" using std::string; PlaySoundAction::PlaySoundAction(const std::string& sound) : mSound(sound) { } void PlaySoundAction::activate(Level& level) { // Play the sound. AudioManager::playSound(mSound); // The action is complete. mPerformed = true; }
f6fa410474ca82195eb2df45394fa00b1107f873
a10bf0c86a5eb0b38fa42a159ac32a460c393cc1
/main.cpp
953fad3dad9eb94263c304b645ade89ce3afcb7a
[]
no_license
oliverxa/yolov3-sort-cpp
ae0fdc156f72ba310812623affb532d69852bc4b
fbf01aea73725b57308a2e8da980d68186b8c093
refs/heads/master
2020-12-11T10:52:53.272023
2020-06-20T05:03:38
2020-06-20T05:03:38
233,829,348
30
4
null
null
null
null
UTF-8
C++
false
false
3,428
cpp
main.cpp
#include <torch/torch.h> #include <opencv2/opencv.hpp> #include <iostream> #include <chrono> #include <string.h> #include "Darknet.h" #include "SORT.h" #include "YOLOv3.h" // global variables for counting #define CNUM 20 //int total_frames = 0; //double total_time = 0.0; int main(int argc, const char* argv[]) { // yolov3 init torch::DeviceType device_type; if (torch::cuda::is_available() ) { device_type = torch::kCUDA; std::cout << "GPU--version"<< std::endl; } else { device_type = torch::kCPU; std::cout << "CPU--version"<< std::endl; } torch::Device device(device_type); // input image size for YOLO v3 int input_image_size = 416; // std::string cfg, weight; // cfg = "../models/yolov3-swim-test.cfg"; // weight = "../models/yolov3-swim_final.weights"; std::cout << "loading configure file..." << std::endl; Darknet net("../models/yolov3-swim-test.cfg", &device); std::map<std::string, std::string> *info = net.get_net_info(); info->operator[]("height") = std::to_string(input_image_size); std::cout << "loading weight model..." << std::endl; net.load_weights("../models/yolov3-swim_final.weights"); //std::cout << "weight loaded ..." << std::endl; net.to(device); torch::NoGradGuard no_grad; net.eval(); std::cout << "loading video ..." << std::endl; cv::VideoCapture capture(argv[1]); if(!capture.isOpened()){ std::cout << "load video Failed" << std::endl; return -1; } int frame_num = capture.get(cv::CAP_PROP_FRAME_COUNT); cv::Mat origin_image; std::cout << "start to inference ..." << std::endl; SORT Sort; YOLOv3 Yolov3; KalmanTracker::kf_count = 0; // tracking id relies on this, so we have to reset it in each video. cv::RNG rng(0xFFFFFFFF); cv::Scalar_<int> randColor[CNUM]; for (int i = 0; i < CNUM; i++) rng.fill(randColor[i], cv::RNG::UNIFORM, 0, 256); for(int fi = 0; fi < frame_num; fi++){ capture >> origin_image; std::vector<std::vector<float>> bbox = Yolov3.yolov3(net, origin_image, device); //std::cout << bbox.size(); /* for(int i = 0; i < bbox.size(); i++){ cv::rectangle(origin_image, cv::Point(bbox[i][0], bbox[i][1]), cv::Point(bbox[i][2], bbox[i][3]), cv::Scalar(0, 0, 255), 1, 1, 0); std::cout << bbox[i][0] << ' ' << bbox[i][1] << ' ' << bbox[i][2] << ' ' << bbox[i][3] << '\n' ; } */ // using sort for tracking //std::vector<Sort::TrackingBox> frameTrackingResult = Sort::Sort(bbox, fi); std::vector<SORT::TrackingBox> frameTrackingResult = Sort.Sortx(bbox, fi); //std::cout << frameTrackingResult.size(); for(auto tb : frameTrackingResult){ cv::rectangle(origin_image, tb.box, randColor[tb.id % CNUM], 6, 8, 0); cv::Point pt = cv::Point(tb.box.x, tb.box.y); cv::Scalar color = cv::Scalar(0, 255, 255); std::string num = std::to_string(tb.id); cv::putText(origin_image, num, pt, cv::FONT_HERSHEY_DUPLEX, 4.0, color, 2); } Size size(800,600); cv::resize(origin_image, origin_image, size); cv::imshow("video test", origin_image); if( cv::waitKey(10) == 27 ) break; } cv::destroyWindow("video test"); capture.release(); std::cout << "Done" << std::endl; return 0; }
e910496702e91d174187d076948b9f6331af2d2e
f806d792bf22bc8306a0926f7b2306c0b3dd4367
/Leetcode/P58 最后一个单词的长度/sl.cpp
5cf21b8a10322af198a5a7d41aaf2d1f83c251ce
[ "MIT" ]
permissive
Wycers/Codelib
d7665476c810ddefd82dd758a4963f6b0e1b7ac1
7d54dce875a69bc998597abb1c2e2c814587c9b8
refs/heads/master
2023-03-05T13:57:44.371292
2022-09-22T02:23:17
2022-09-22T02:23:17
143,575,376
28
4
MIT
2023-03-04T22:05:33
2018-08-05T01:44:34
VHDL
UTF-8
C++
false
false
192
cpp
sl.cpp
class Solution { public: int lengthOfLastWord(string s) { istringstream iss(s); string word; while (iss >> word) ; return word.size(); } };
5ec9d20c9d23002c7ae1453b123210ef0599f018
02ab470d3187e5d3e2800859984a9ee58f9bd3c0
/casmacat/Range.h
48b6fc3e56fccc08b6adc5ae43a81b19e1572169
[]
no_license
PRHLT/CATTI
e128883400b9637768da348205d5083841958969
61cff0de9c9c5dd0e32d9b560139b9e4a9c2c7f5
refs/heads/master
2021-05-01T21:28:14.304219
2018-02-06T11:40:12
2018-02-06T11:40:12
75,202,392
2
0
null
null
null
null
UTF-8
C++
false
false
1,786
h
Range.h
/* * Copyright 2012, valabau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * Range.h * * Created on: 13/09/2012 * Author: valabau */ #ifndef CASMACAT_RANGE_H_ #define CASMACAT_RANGE_H_ namespace casmacat { /** * Structures for manipulating ranges */ class Range { size_t from; size_t to; public: Range(): from(0), to(0) {} Range(size_t _start, size_t _end): from(_start), to(_end) {} std::ostream& print(std::ostream& out) const { return out << "(" << from << "," << to << ")"; } }; std::ostream& operator<<(std::ostream& out, const Range &range) { return range.print(out); } class RangeSequence { std::vector<Range> sequence; public: RangeSequence() {} void addRange(const Range &range) { sequence.push_back(range); } void add(size_t start, size_t end) { sequence.push_back(Range(start, end)); } std::ostream& print(std::ostream& out) const { out << "["; copy(sequence.begin(), sequence.end(), std::ostream_iterator<Range>(out, ";")); out << "]"; return out; } }; std::ostream& operator<<(std::ostream& out, const RangeSequence &range_requence) { return range_requence.print(out); } } #endif /* CASMACAT_RANGE_H_ */
b1662ca4e8308ac7c0acbfbeb75c6fbe4d926bd0
093f6363e7728ea1a98254e75830ca7297b39436
/MayChallenge/week3/PermutationInString.CPP
63853f7922d2e66d3f5ac22262d476b661c38e6b
[]
no_license
srmalkan/Leetcode
33fd50e0083343a2cabe78345cf51cf492913c7f
eee663a74655aa43ac954e26fc1ab25190eb85e3
refs/heads/master
2023-05-30T08:29:52.138428
2021-06-16T16:46:49
2021-06-16T16:46:49
261,119,298
0
0
null
null
null
null
UTF-8
C++
false
false
1,812
cpp
PermutationInString.CPP
class Solution { public: bool compareMaps(map<char,int> &temp, map<char,int> &P){ if(temp.size()!=P.size()){ return false; } for(auto itr=P.begin(),itr2=temp.begin();itr!=P.end();itr++,itr2++){ // cout<<itr->first<<" "<<itr2->first; if(itr->first != itr2->first){ return false; } if(itr->second != itr2->second){ return false; } } return true; } bool checkInclusion(string p, string s) { map<char,int> P; for(char x : p){ P[x]++; } int m=p.length(); int n=s.length(); if(m>n){ return false; } map<char,int> temp; for(int i=0;i<m-1;i++){ temp[s[i]]++; } for(int i=m-1;i<n;i++){ temp[s[i]]++; if(compareMaps(temp,P)){ return true; } // for(auto x:temp){ // cout<<x.first<<" "<<x.second<<"\n"; // } // cout<<endl; if(temp[s[i-(m-1)]]==1){ temp.erase(s[i-(m-1)]); }else{ temp[s[i-(m-1)]]--; } } return false; } }; /* Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Example 1: Input: s1 = "ab" s2 = "eidbaooo" Output: True Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input:s1= "ab" s2 = "eidboaoo" Output: False Constraints: The input strings only contain lower case letters. The length of both given strings is in range [1, 10,000]. */
77fad8ee8dc72a9b2d9cdf744635d3461077d1f9
29871ec191cbbec8fe5ad4dc905dbbcef9484e9f
/C++/04042018/ex6.cpp
24e014011a135e164a92c09912f9d3f5d5930e26
[]
no_license
narosan/Algoritmo-UVA
03b4e37b48a38b5f6e75da659c10bd366d1bda6d
30caf6052c578f6f93aad149f2a463ef56142cd5
refs/heads/master
2020-03-10T14:55:43.362716
2018-06-21T21:07:37
2018-06-21T21:07:37
129,438,303
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
1,325
cpp
ex6.cpp
/* 6) Fazer um programa para que o usuário opte por uma opção de conversão “1 – Celsius 2 – Farenheit”. Após a escolha o usuário deverá informar a temperatura. Criar uma nova função para aplicar a conversão conforme opção escolhida. Fórmulas: C=5*(F-32)/9 F=(9*C/5) + 32 */ #include <stdio.h> #include <stdlib.h> int converteCelsius(float farenheit){ float C; C = 5 * (farenheit-32) / 9; printf("%.1f em graus Farenheit é equivalente a %.1f graus Celsius.", farenheit, C); return 0; } int converteFarenheit(float celsius){ float F; F = (9 * celsius / 5) + 32; printf("\n%.1f em graus Celsius eh equivalente a %.1f graus Farenheit.\n", celsius, F); return 0; } main(){ int menu; float temperatura; printf("====== Programa para converter graus Celsius ou Farenheit ======\n\n"); printf("1 - Celsius\n2 - Farenheit\n:"); scanf("%i", &menu); switch(menu){ case 1: printf("Informe a temperatura em graus Farenheit: "); scanf("%f", &temperatura); converteCelsius(temperatura); break; case 2: printf("Informe a temperatura em graus Celsius: "); scanf("%f", &temperatura); converteFarenheit(temperatura); break; } system("pause"); return 0; }
4ffe9bc95d5535a297e379b1d7fec9d9e10bda5a
b1679be076b6f72da0897fe5b3fc66cbe30fb2b0
/codeforces/265-c.cpp
32eb7116ddd7605029a6293d7536a60e1a01438f
[]
no_license
euyuil/icpc-training-solutions
a86b4a4bf12bd931fa2315683d8ee22dff253930
d40c5b90dbe668ea80d5a7bc55592016a9c3d20d
refs/heads/master
2020-06-04T15:40:52.854240
2013-09-24T03:15:03
2013-09-24T03:15:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
673
cpp
265-c.cpp
#include <iostream> #include <algorithm> using namespace std; const int N = 1000111; int id[N]; int main() { int i = 2, m = 2; char c; id[1] = 1; while (cin >> c) { switch (c) { case 'l': id[i++] = m++; break; case 'r': if (i > 1) { cout << id[i - 1] << endl; id[i - 1] = m++; } else { cout << m++ << endl; } break; default: goto the_end; } } the_end: for (i -= 2; i >= 1; --i) cout << id[i] << endl; return 0; }
80298727aa79c9b5bf3b9a49b18bb7915cc366f0
ab17472543e64365ed23468b19f54a2e0fddb9ce
/scripts/EGammaTrigEff.cc
59751e83586fc70b3a8f69cd1c83d837bcbce098
[]
no_license
JessWYWong/postFWLJMETanalyzer-SS2L
86cae06723f60c9dbe3316837efd71807b07c61b
c35d327fa88f84b1486653d03ea8de01e7af994b
refs/heads/master
2022-06-17T03:16:15.909411
2019-06-24T19:37:03
2019-06-24T19:37:03
224,484,652
0
0
null
2019-11-27T17:35:40
2019-11-27T17:35:39
null
UTF-8
C++
false
false
5,385
cc
EGammaTrigEff.cc
#include <iostream> #include <stdio.h> #include <math.h> #include <sstream> #include <string> #include "TFile.h" #include "TTree.h" #include "TH1.h" #include "TGraphAsymmErrors.h" #include "TCanvas.h" #include "TLegend.h" #include "TLatex.h" #include "TMath.h" #include "Math/ProbFunc.h" using namespace std; TGraphAsymmErrors* getGraph(TFile* f){ TCanvas* c = (TCanvas*) f->Get("GsfElectronToTrigger/EfficiencyBinningSpecification/fit_eff_plots/probe_Ele_pt_PLOT_probe_sc_abseta_bin0"); TGraphAsymmErrors* g = (TGraphAsymmErrors*)c->GetPrimitive("probe_Ele_pt_PLOT_probe_sc_abseta_bin0"); return g; } Double_t erf2(Double_t* x, Double_t* par){ //return par[0]* (ROOT::Math::normal_cdf(x[0]+par[1],par[3]) - ROOT::Math::normal_cdf(x[0]+par[1],par[3]) ) + par[2]; return par[0]* (ROOT::Math::normal_cdf(x[0]-par[1],par[2])); } Double_t erf( Double_t *x, Double_t *par){ //<=========== return par[0]*TMath::Erf(x[0]+par[1]) + par[2]; //<=========== } void printGraph(TGraphAsymmErrors* g,std::string eta, std::string title, std::string pdfname){ TCanvas* c = new TCanvas(); //set up error function TF1 *fitfcn = new TF1("fitfcn",erf,20.0,100.0,3); //<============ TF1 *fitfcn2 = new TF1("fitfcn2",erf2,20.0,100.0,3); //<============ fitfcn->SetParameter(0,0.45); //<============= fitfcn->SetParameter(1,-33); fitfcn->SetParameter(2,0.5); fitfcn2->SetParameter(0,0.95); //<============= fitfcn2->SetParameter(1,33); fitfcn2->SetParameter(2,1.5); //fitfcn2->SetParameter(3,1.5); //some prettifying g->SetTitle(title.c_str()); g->GetXaxis()->SetTitle("p_{T} (GeV)"); g->GetYaxis()->SetTitle("Efficiency"); //c->SetLogx(); g->Draw("ap"); g->GetXaxis()->SetRangeUser(0,100); //g->Draw("ap"); //fit graph g->Fit("fitfcn2","M"); //write plateau efficiency: float eff = 100.0*(fitfcn2->GetParameter(0));//+fitfcn->GetParameter(2)); std::stringstream texstring; texstring<<"#splitline{Plateau Efficiency for}{ "<<eta<<" : "<<eff<<"%}"; TLatex* tex = new TLatex(); tex->DrawLatex(45,.6, (texstring.str()).c_str()); std::cout<<texstring.str()<<std::endl; //get turn on pT std::stringstream ptstring; ptstring<<"p_{T}^{TO}: "<<fitfcn2->GetParameter(1); TLatex* pttex = new TLatex(); pttex->DrawLatex(45,0.4,(ptstring.str()).c_str()); //get resolution std::stringstream sigmastring; sigmastring<<"#sigma_{p_{T}}: "<<fitfcn2->GetParameter(2); TLatex* sigmatex = new TLatex(); sigmatex->DrawLatex(45,0.3,(sigmastring.str()).c_str()); for(int i=0;i<g->GetN();i++){ std::cout<<"bin: "<<i<<" eff: "<<g->GetY()[i]<<std::endl; } //save plot c->Print(pdfname.c_str()); } void EGammaTrigEff(){ TFile* fbin0 = new TFile("efficiency-data-passingHLTEle33_MVATightMiniIso_probeAbsEta0p0-0p8.root"); TFile* fbin1 = new TFile("efficiency-data-passingHLTEle33_MVATightMiniIso_probeAbsEta0p8-1p4.root"); TFile* fbin2 = new TFile("efficiency-data-passingHLTEle33_MVATightMiniIso_probeAbsEta1p5-2p4.root"); TFile* fele27bin0 = new TFile("efficiency-data-passingHLTEle27_MVATightMiniIso_probeAbsEta0p0-0p8.root"); TFile* fele27bin2 = new TFile("efficiency-data-passingHLTEle27_MVATightMiniIso_probeAbsEta1p5-2p4.root"); TFile* fele37bin0 = new TFile("efficiency-data-passingHLTEle37_MVATightMiniIso_probeAbsEta0p0-0p8.root"); TFile* fele37bin1 = new TFile("efficiency-data-passingHLTEle37_MVATightMiniIso_probeAbsEta0p8-1p4.root"); TFile* fele37bin2 = new TFile("efficiency-data-passingHLTEle37_MVATightMiniIso_probeAbsEta1p5-2p4.root"); TGraphAsymmErrors* gbin0 = getGraph(fbin0); TGraphAsymmErrors* gbin1 = getGraph(fbin1); TGraphAsymmErrors* gbin2 = getGraph(fbin2); TGraphAsymmErrors* gele27bin0 = getGraph(fele27bin0); TGraphAsymmErrors* gele27bin2 = getGraph(fele27bin2); TGraphAsymmErrors* gele37bin0 = getGraph(fele37bin0); TGraphAsymmErrors* gele37bin1 = getGraph(fele37bin1); TGraphAsymmErrors* gele37bin2 = getGraph(fele37bin2); TCanvas* can = new TCanvas(); printGraph(gbin0,"0 < #eta < 0.8","Efficiency for passing single leg of HLT_DoubleEle33","Ele33_Efficiency-vs-pT_0p0-0p8.pdf"); printGraph(gbin1,"0.8 < #eta < 1.442","Efficiency for passing single leg of HLT_DoubleEle33","Ele33_Efficiency-vs-pT_0p8-1p4.pdf"); printGraph(gbin2,"1.556 < #eta < 2.4","Efficiency for passing single leg of HLT_DoubleEle33","Ele33_Efficiency-vs-pT_1p5-2p4.pdf"); printGraph(gele27bin0,"0.0 < #eta < 0.8","Efficiency for passing single leg of HLT_Ele27","Ele27_Efficiency-vs-pT_0p0-0p8.pdf"); printGraph(gele27bin2,"1.556 < #eta < 2.4","Efficiency for passing single leg of HLT_Ele27","Ele27_Efficiency-vs-pT_1p5-2p4.pdf"); printGraph(gele37bin0,"0.0 < #eta < 0.8","Efficiency for passing single leg of HLT_Ele37","Ele37_Efficiency-vs-pT_0p0-0p8.pdf"); printGraph(gele37bin1,"0.8 < #eta < 1.4442","Efficiency for passing single leg of HLT_Ele37","Ele37_Efficiency-vs-pT_0p8-1p4.pdf"); printGraph(gele37bin2,"1.556 < #eta < 2.4","Efficiency for passing single leg of HLT_Ele37","Ele37_Efficiency-vs-pT_1p5-2p4.pdf"); //gbin0->SetLineColor(kBlue); //gbin1->SetLineColor(kRed); //gbin2->SetLineColor(kBlack); //TCanvas* can = new TCanvas(); //can->SetLogx(); //gbin0->Draw("ap"); //gbin0->Fit("fitfcn"); //gbin1->Draw("plsame"); //gbin2->Draw("plsame"); //can->Print("Ele33_Efficiency-vs-pT.pdf"); }
aeb7cd55dcc93a2819b03881d27f92f501314176
4d74aa247055ba254a7f3ab305634dffcc656185
/tests/kernel_bundle/has_kernel_bundle_zero_device.h
9149f8cd7d24fb90f4b137b1a88ba645cf56f1ac
[ "Apache-2.0" ]
permissive
KhronosGroup/SYCL-CTS
e2ecc8ffd0f80e90f6f44a2f5e1ce167aff53ba9
cc653d0d88bb40d209e83267b5b91b070d84300a
refs/heads/SYCL-2020
2023-08-31T23:55:36.962775
2023-08-30T14:12:30
2023-08-30T14:12:30
160,528,100
51
60
Apache-2.0
2023-09-14T15:49:21
2018-12-05T14:11:21
C++
UTF-8
C++
false
false
4,169
h
has_kernel_bundle_zero_device.h
/******************************************************************************* // // SYCL 2020 Conformance Test Suite // // Provides common code for zero device test case // *******************************************************************************/ #ifndef __SYCLCTS_TESTS_HAS_KERNEL_BUNDLE_ZERO_DEVICE_H #define __SYCLCTS_TESTS_HAS_KERNEL_BUNDLE_ZERO_DEVICE_H #include "../common/common.h" #include "has_kernel_bundle.h" #include <vector> namespace sycl_cts::tests::has_kernel_bundle::check { /** @brief Call sycl::has_kernel_bundle with sycl::bundle_state, context and * device and verify that exception was thrown * @tparam KernelDescriptorT Kernel descriptor * @tparam BundleState sycl::bundle_state enum's enumeration's field * @param log sycl_cts::util::logger class object * @param ctx sycl::context class object * @param dev sycl::device class object */ template <typename KernelDescriptorT, sycl::bundle_state BundleState> struct zero_device<KernelDescriptorT, BundleState, overload::id::ctx_dev> { void operator()(sycl_cts::util::logger &log, const sycl::context &ctx, const sycl::device &dev) { using kernel_functor = typename KernelDescriptorT::type; auto k_id = sycl::get_kernel_id<kernel_functor>(); bool ex_was_thrown = false; sycl::queue queue{ctx, dev}; std::vector<sycl::device> devs{}; expect_throws<sycl::errc::invalid>( log, TestCaseDescription<BundleState>("<bundle_state>(context, devices)"), [&] { sycl::has_kernel_bundle<BundleState>(ctx, devs); }); kernel_bundle::define_kernel<KernelDescriptorT, BundleState>(queue); } }; /** @brief Call sycl::has_kernel_bundle with sycl::bundle_state, context, device * and kernel_id and verify that exception was thrown * @tparam KernelDescriptorT Kernel descriptor * @tparam BundleState sycl::bundle_state enum's enumeration's field * @param log sycl_cts::util::logger class object * @param ctx sycl::context class object * @param dev sycl::device class object */ template <typename KernelDescriptorT, sycl::bundle_state BundleState> struct zero_device<KernelDescriptorT, BundleState, overload::id::ctx_dev_kid> { void operator()(sycl_cts::util::logger &log, const sycl::context &ctx, const sycl::device &dev) { using kernel_functor = typename KernelDescriptorT::type; auto k_id = sycl::get_kernel_id<kernel_functor>(); bool ex_was_thrown = false; sycl::queue queue{ctx, dev}; std::vector<sycl::device> devs{}; expect_throws<sycl::errc::invalid>( log, TestCaseDescription<BundleState>( "<bundle_state>(context, devices, kernel_ids)"), [&] { sycl::has_kernel_bundle<BundleState>(ctx, devs, {k_id}); }); kernel_bundle::define_kernel<KernelDescriptorT, BundleState>(queue); } }; /** @brief Call sycl::has_kernel_bundle with sycl::bundle_state, context, device * and kernel_name and verify that exception was thrown * @tparam KernelDescriptorT Kernel descriptor * @tparam BundleState sycl::bundle_state enum's enumeration's field * @param log sycl_cts::util::logger class object * @param ctx sycl::context class object * @param dev sycl::device class object */ template <typename KernelDescriptorT, sycl::bundle_state BundleState> struct zero_device<KernelDescriptorT, BundleState, overload::id::ctx_dev_kname> { void operator()(sycl_cts::util::logger &log, const sycl::context &ctx, const sycl::device &dev) { using kernel_functor = typename KernelDescriptorT::type; bool ex_was_thrown = false; sycl::queue queue{ctx, dev}; std::vector<sycl::device> devs{}; expect_throws<sycl::errc::invalid>( log, TestCaseDescription<BundleState>( "<kernel_name, bundle_state>(context, devices)"), [&] { sycl::has_kernel_bundle<kernel_functor, BundleState>(ctx, devs); }); kernel_bundle::define_kernel<KernelDescriptorT, BundleState>(queue); } }; } // namespace sycl_cts::tests::has_kernel_bundle::check #endif // __SYCLCTS_TESTS_HAS_KERNEL_BUNDLE_ZERO_DEVICE_H
f4b8a83e37fe10ce9ca70b80f2ee78dd0024e27f
2dcc8c1fcb0427dbdae0f82c919989dcf2055c44
/Test/sub_hwa.cpp
dc373ea175fbdc58c6c6ca58128282ca32fcca56
[]
no_license
wnflrj123/Test
dd2527933aa71519e4110da6587188455bd93e0a
dfd3381937079141671cbe436045cd61483b5171
refs/heads/jooool2
2020-05-17T04:21:45.631511
2015-08-13T13:08:18
2015-08-13T13:08:18
29,849,217
0
0
null
2015-08-13T13:08:18
2015-01-26T07:05:52
C++
UTF-8
C++
false
false
341
cpp
sub_hwa.cpp
// // main.cpp // Test // // Created by 서듈 on 2014. 10. 14.. // Copyright (c) 2014년 서듈. All rights reserved. // #include <stdio.h> //int main() { // // insert code here... // int sub; // double hwa; // // scanf("%d",&sub); // hwa=9.0/5.0*sub+32; // // printf("%.1f",hwa); // // return 0; //}
66f8f7de76d544b39c75635d74b0b451d70e90cc
6cc9420434eacf18814a033e92fe114e5bbfcf1f
/FinalPrj_NN_Framework/mnist_dataset_helper.h
46d08cdb5e3c601d60defe0ddbcdb18d710a29a2
[ "MIT" ]
permissive
dimant/gpu2021hpc
a043a92c7616fa1bb4b164c77e86be5e9e3f30a0
c6a7dd94df9dc18f475ae4a89452335948de7eb5
refs/heads/main
2023-03-24T10:57:12.381443
2021-03-19T04:56:37
2021-03-19T04:56:37
328,256,637
0
0
null
null
null
null
UTF-8
C++
false
false
3,877
h
mnist_dataset_helper.h
#pragma once // MNIST dataset loading and pre-processing // // full_path strings must be fully-qualified path to a valid MNIST datafile of IDX file format // #include <string> #include <fstream> typedef unsigned char uchar; using namespace std; auto reverseInt = [](int i) { unsigned char c1, c2, c3, c4; c1 = i & 255, c2 = (i >> 8) & 255, c3 = (i >> 16) & 255, c4 = (i >> 24) & 255; return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4; }; // Read MNIST dataset images into contiguous float array and normalize values to range (0,1) // Caller must free( ) returned float array void load_and_preproc_mnist_images(string full_path, float** _dataset, int& number_of_images, int& n_rows, int& n_cols) { ifstream file(full_path, ios::binary); if (file.is_open()) { int magic_number = 0; file.read((char*)&magic_number, sizeof(magic_number)); magic_number = reverseInt(magic_number); if (magic_number != 2051) throw runtime_error("Invalid MNIST image file!"); file.read((char*)&number_of_images, sizeof(number_of_images)); number_of_images = reverseInt(number_of_images); file.read((char*)&n_rows, sizeof(n_rows)); n_rows = reverseInt(n_rows); file.read((char*)&n_cols, sizeof(n_cols)); n_cols = reverseInt(n_cols); uchar* _tmp_data = (uchar*)malloc(number_of_images * n_rows * n_cols * sizeof(uchar)); float* _f32_data = NULL; CURT_CHK(cudaMallocManaged(&_f32_data,(number_of_images * n_rows * n_cols * sizeof(float)))); //uchar** _dataset = new uchar * [number_of_images]; for (int i = 0; i < number_of_images; i++) { file.read((char*)&_tmp_data[i * n_rows * n_cols], n_rows * n_cols); } // convert to float and normalize int total_vals = number_of_images * n_rows * n_cols; for (int i = 0; i < total_vals; ++i) { if (0 == (int)_tmp_data[i]) _f32_data[i] = 0.0f; else { _f32_data[i] = 1.0f / (int)_tmp_data[i]; } } free(_tmp_data); *_dataset = _f32_data; } else { throw runtime_error("Cannot open file `" + full_path + "`!"); } } // Read MNIST dataset labels as one-hot-encoded arrays, placed into contiguous float array // Caller must free( ) returned float array void load_preproc_mnist_labels(string full_path, float** _dataset, int& number_of_labels) { ifstream file(full_path, ios::binary); if (file.is_open()) { int magic_number = 0; file.read((char*)&magic_number, sizeof(magic_number)); magic_number = reverseInt(magic_number); if (magic_number != 2049) throw runtime_error("Invalid MNIST label file!"); file.read((char*)&number_of_labels, sizeof(number_of_labels)); number_of_labels = reverseInt(number_of_labels); int number_of_MNIST_classes = 10; uchar* _tmp_data = (uchar*)malloc(number_of_labels * sizeof(uchar)); float* _f32_data = NULL; CURT_CHK(cudaMallocManaged(&_f32_data, (number_of_labels * number_of_MNIST_classes * sizeof(float)))); for (int i = 0; i < number_of_labels; i++) { file.read((char*)&_tmp_data[i], 1); } // convert to float and one-hot-encoding for (int i = 0; i < number_of_labels; ++i) { for (int j = 0; j < number_of_MNIST_classes; ++j) { if (j == (int)_tmp_data[i]) _f32_data[i * number_of_MNIST_classes + j] = 1.0f; else _f32_data[i * number_of_MNIST_classes + j] = 0.0f; } } free(_tmp_data); *_dataset = _f32_data; } else { throw runtime_error("Unable to open file `" + full_path + "`!"); } }
6ecd597b6b5b5f8715ab7a1edd5154b7282c7f9f
af9c1566c7f8b7e30ee957ef40de647c1d86d17a
/tek2/maths/208chevillettes/Core.hpp
af65eb4c7e7d1c4396f7655c0acf79d058522545
[]
no_license
Vasrek77/epitech-projects
471b7503e189000ad1ab491915c950af4b661c01
6db30340f7accd04d037ba1ea2bc3e3ecd736251
refs/heads/master
2021-01-17T22:41:05.342477
2015-08-12T19:10:24
2015-08-12T19:10:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,161
hpp
Core.hpp
#ifndef CORE_HPP_ # define CORE_HPP_ # include <iostream> # include <iomanip> # include <sstream> # include <fstream> # include <vector> # include <cmath> # include "gmpxx.h" # include "Exception.hpp" using namespace std; class Core { vector<int> _effectifs; vector<double> _ajust; vector<int> _pourcents; vector<vector<double> > _datas; vector<string> _x; vector<double> _ox; vector<double> _tx; double _p; double _s; double _d; int _min; int _max; public: Core() {}; ~Core() {}; void init(int argc, char **argv) { this->_effectifs.resize(9); this->_effectifs.assign(9, 0); this->_ajust.resize(9); this->_ajust.assign(9, 0); this->_pourcents.resize(13); this->_pourcents.assign(13, 0); vector<double> data; data.resize(14); data.assign(14, 0); this->_datas.resize(10); this->_datas.assign(10, data); this->_x.resize(9); this->_x.assign(9, ""); this->_ox.resize(9); this->_ox.assign(9, 0); this->_tx.resize(9); this->_tx.assign(9, 0); for (int i = 1; i < argc; i++) { int number(this->stringToNumber(argv[i])); if (number < 0) { throw Exception("You must enter only positive numbers"); } else { this->_effectifs[i - 1] = number; } } cout << "\033[01mUtilisation des effectifs entier:\033[0m "; for (vector<int>::iterator it = this->_effectifs.begin(); it != this->_effectifs.end(); it++) { cout << *it << " "; } cout << endl << endl; this->fill(); } void run(void) { this->law(); this->binomial(); this->calculate(); this->sum(); this->degre(); this->pourcent(); cout << "\033[4mx |"; for (int i = 0; i < 9; i++) { if (!this->_x[i].empty()) { if (this->_x[i] == "7+") { cout << " " << this->_x[i] << " |"; } else { cout << " " << this->_x[i] << " |"; } } } cout << " total\033[0m" << endl; cout << "Ox |"; for (int i = 0; i < 9; i++) { if (!this->_x[i].empty()) { if (this->_x[i].length() > 2) { cout << " " << this->_ox[i] << " |"; } else { cout << " " << this->_ox[i] << " |"; } } } cout << " 100" << endl; cout << setprecision(1) << fixed; cout << "Tx |"; for (int i = 0; i < 9; i++) { if (!this->_x[i].empty()) { if (this->_x[i].length() > 2) { cout << " " << (this->_tx[i] * 100) << " "; } else { cout << " " << (this->_tx[i] * 100) << " "; } if (this->_tx[i] * 100 < 10) { cout << " |"; } else { cout << "|"; } } } cout << " 100" << endl; cout << endl << endl; cout << setprecision(4) << fixed; cout << "\033[01mLoi choisie:\033[0m\t\t\tB(100, " << this->_p << ")" << endl; cout << setprecision(3) << fixed; cout << "\033[01mSomme des carrés des écarts:\033[0m\tX2 = " << this->_s << endl; cout << setprecision(0) << fixed; cout << "\033[01mDegrés de liberté:\033[0m\t\tv = " << this->_d << endl; cout << "\033[01mValidité de l’ajustement:\033[0m\t" << this->_min << "% < P < " << this->_max << "%" << endl; } void end(void) { this->_effectifs.clear(); } void law(void) { for (int i = 0; i < 9; i++) { this->_p += i * this->_effectifs[i]; } this->_p /= 10000; } void binomial(void) { int n(100); for (int k = 0; k < 51; k++) { double coef(coefficient(n, k)); coef = (coef * (pow(this->_p, k)) * (pow((1 - this->_p), (n - k)))); if (k < 8) { this->_ajust[k] += coef; } else { this->_ajust[8] += coef; } } } void calculate(void) { stringstream stream; for (int i = 0; i < 7; i++) { double ox(this->_effectifs[i]); double tx(this->_ajust[i]); stream.str(""); stream.clear(); if (this->_effectifs[i] < 10) { if (this->_effectifs[i] + this->_effectifs[i + 1] < 10) { this->_ox[i] = this->_effectifs[i] + this->_effectifs[i + 1] + this->_effectifs[i + 2]; this->_tx[i] = this->_ajust[i] + this->_ajust[i + 1] + this->_ajust[i + 2]; stream << i << "-" << i + 2; this->_x[i] = stream.str(); } else { this->_ox[i] = this->_effectifs[i] + this->_effectifs[i + 1]; this->_tx[i] = this->_ajust[i] + this->_ajust[i + 1]; stream << i << "-" << i + 1; this->_x[i] = stream.str(); } i++; } else { this->_ox[i] = ox; this->_tx[i] = tx; stream << i; this->_x[i] = stream.str(); } } if (this->_effectifs[7] < 10 or this->_effectifs[8] < 10) { this->_ox[7] = this->_effectifs[7] + this->_effectifs[8]; this->_tx[7] = this->_ajust[7] + this->_ajust[8]; this->_x[7] = "7+"; } else { this->_ox[7] = this->_effectifs[7]; this->_tx[7] = this->_ajust[7]; this->_x[7] = "7"; this->_ox[8] = this->_effectifs[8]; this->_tx[8] = this->_ajust[8]; this->_x[8] = "8"; } } void sum(void) { for (int i = 0; i < 9; i++) { if (!this->_x[i].empty() and this->_tx[i] != 0) { this->_s += pow(this->_ox[i] - (this->_tx[i] * 100), 2) / (this->_tx[i] * 100); } } } void degre(void) { for (int i = 0; i < 9; i++) { if (!this->_x[i].empty()) { this->_d += 1; } } this->_d -= 2; } void pourcent(void) { for (int i = 1; i < 14; i++) { if (this->_s < this->_datas[this->_d - 1][i]) { this->_min = this->_pourcents[i - 1]; this->_max = this->_pourcents[i - 2]; break; } } } double coefficient(double firstValue, double secondValue) { mpz_t b, tmp, tmp2, tmp3, i, k, n; double k2, j = 0; mpz_init_set_d(b, 1); mpz_init_set_d(i, 1); mpz_init_set_d(n, firstValue); mpz_init_set_d(tmp, 1); mpz_init_set_d(tmp2, 1); mpz_init_set_d(tmp3, 1); if (secondValue < 0 or secondValue > firstValue) { mpz_set_d(b, 0); } else { k2 = min(secondValue, (firstValue - secondValue)); mpz_init_set_d(k, k2); j = 1; while (j <= k2) { mpz_sub(tmp, n, i); mpz_add_ui(tmp2, tmp, 1); mpz_mul(tmp3, b, tmp2); mpz_div(b, tmp3, i); mpz_add_ui(i, i, 1); j++; } } mpz_class res(b); return res.get_d(); } void fill(void) { fstream file; file.open("data.xml"); int i(0); if (file) { string line; while (getline(file, line)) { if (line.find("line") != line.npos and line.find("pourcent") != line.npos) { int j(0); while (getline(file, line) and line.find("cell") != line.npos) { istringstream cell(line); string value; cell >> value; cell >> value; this->_pourcents[j] = stringToNumber(value); j++; } } else if (line.find("line") != line.npos) { int j(0); while (getline(file, line) and line.find("cell") != line.npos) { istringstream cell(line); string value; cell >> value; cell >> value; this->_datas[i][j] = stringToNumber(value); j++; } i++; } } } else { throw Exception("Can't open data.xml file"); } } double stringToNumber(const std::string &value) { stringstream stream; double number(0); stream << value; stream >> number; return number; } }; #endif /* CORE_HPP_ */
914c5175bb17bf6f32d9dd2bb55296ba75849901
2d3cb2f9ac1028e81abe725692f8e34d259da3f4
/2nd year rahul sirc++/Inheritance/InheritData.cpp
984055bc53018beb8a2157575d20d58271cd2c01
[]
no_license
satinder147/c_plus_plus
f1c5f7c9b2b79871bea7b33a364d64d2e535d602
041e38803825c7b65c2b6ce78d5b5fb231ed8adc
refs/heads/master
2021-07-08T07:14:31.096467
2020-08-13T15:11:37
2020-08-13T15:11:37
149,191,459
1
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
InheritData.cpp
//Program to study :Inheritance of Data //See : InheritData.png //Refer : Inheritance.txt #include <iostream> using namespace std; class A { private: int x; protected: int y; public : int z; A(); int getX(); ~A(); }; A :: A() { cout<<"\n A()"; x = 10; y = 20; z = 30; } int A :: getX() { return x; } A:: ~A() { cout<<"\n ~A()"; } class B : public A { protected: int sum; public: B(); void display(); ~B(); }; B :: B() { cout<<"\n B()"; sum = getX() +y+z; } void B ::display() { cout<<"\n"<<getX()<<" + "<<y <<" + "<<z<<" = "<<sum; } B :: ~B() { cout<<"\n ~B()"; } int main() { B objB; objB.display(); return 0; }
f1478c18c6781e5b8ed6ed2dee8599ae274205a7
f66ca7e6d96638d129c73e4dab57223ee57bd7fe
/p552/p552_2.cpp
9b149d399bb17b1fdcda735f6e98f538eb0f3f7f
[ "MIT" ]
permissive
suzyz/leetcode_practice
e4a5ab30b60318dc087452daef7dab51727d396a
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
refs/heads/master
2021-01-19T01:17:49.194902
2019-01-12T13:27:56
2019-01-12T13:27:56
95,619,304
1
0
null
null
null
null
UTF-8
C++
false
false
1,055
cpp
p552_2.cpp
// Based on version 1. // DP + enumerate A's position. // And a little space optimization. const int maxn = 100002; class Solution { public: int f[3][2]; long long g[maxn]; const int mo = 1e9 + 7; int checkRecord(int n) { f[1][0] = f[1][1] = 1; f[2][0] = f[2][1] = 2; g[0] = 1; g[1] = 2; g[2] = 4; int cur = 0; for (int i = 3; i <= n; ++i) { int p1 = getPre(cur, 1), p2 = getPre(cur, 2); f[cur][0] = addMod(f[p1][1], f[p2][1]); f[cur][1] = addMod(f[p1][0], f[p1][1]); g[i] = addMod(f[cur][0], f[cur][1]); cur = (cur+1)%3; } long long ans = g[n]; for (int i = 1; i <= n; ++i) ans = addMod(ans, g[i-1] * g[n-i] % mo); return ans; } int addMod(int a, int b) { a += b; if (a >= mo) a -= mo; return a; } int getPre(int cur, int offset) { int res = cur - offset; if (res < 0) res += 3; return res; } };
0fb2225232e22769a0cd33029e76ff02e6211e77
ce96b51f9becc72a63093edcc3bbc0188866e182
/src/trialmanager.cpp
f985f7251c30499dfca00bb4a1797743efa5fdef
[]
no_license
magicphotos/magicphotos-bb10
086962883b9a49d09bb963335c3cf1ed62960083
8782983ee66cb0e26b71bf49a0b18d03ebf1e076
refs/heads/master
2020-05-19T04:31:53.524285
2018-05-30T20:51:48
2018-05-30T20:51:48
184,828,067
1
1
null
null
null
null
UTF-8
C++
false
false
239
cpp
trialmanager.cpp
#include "trialmanager.h" TrialManager::TrialManager(QObject *parent) : QObject(parent) { } TrialManager::~TrialManager() { } bool TrialManager::trialMode() const { #ifdef TRIAL_VERSION return true; #else return false; #endif }
dd1772e1756dbb70c1a3fee0f5284aa516bb21c5
3ca798d7c32019742bce89ba11d52c4b470ad872
/Spoj/Maximum profit.cpp
3b5c768cb4f9e829d3c542555228e3be3bba4e2f
[]
no_license
prakhar3agrwal/Online-Programming-Codes
8537248d13d70ac118a475e531818e304539a979
ed67b9ade7bbca463d9143757903191f7b0c3fba
refs/heads/master
2023-08-06T08:03:19.175740
2023-08-01T09:46:52
2023-08-01T09:46:52
41,192,466
5
1
null
null
null
null
UTF-8
C++
false
false
955
cpp
Maximum profit.cpp
#include<stdio.h> main() { unsigned long long int n,m,i,j,s,t,x,mx; scanf("%llu",&t); while(t--) { scanf("%llu%llu",&n,&m); unsigned long long int a[n][m],b[n][m],c[n][m]; for(i=0;i<n;i++) for(j=0;j<m;j++) scanf("%llu",&a[i][j]); for(i=0;i<n;i++) for(j=0;j<m;j++) scanf("%llu",&b[i][j]); for(i=0;i<n;i++) for(j=0;j<m;j++) scanf("%llu",&c[i][j]); s=0; for(i=0;i<n;i++) { mx=0; for(j=0;j<m;j++) { x=a[i][j]>b[i][j]?b[i][j]:a[i][j]; x=(x*c[i][j]); if(x>mx) mx=x; } s+=mx; } printf("%llu\n",s); } }
05df4b14a065c4f616a4b0ead03c0b6c1e801031
a9e4c398451c8b0d1711d3dffb3fc19ab4a6eb8c
/C++/include/Poly3D.h
19303dea5750bc3f62fd329a284f5a0271fde7a1
[ "LicenseRef-scancode-us-govt-public-domain" ]
permissive
supriyantomaftuh/icarous
df0ef8c5571672f65e3baadb3b6ec1d50d919876
b0d2262a89f5783bcad5664991d80b73be316b64
refs/heads/master
2017-12-07T15:16:49.563140
2017-03-10T04:37:26
2017-03-10T04:37:26
69,625,426
0
1
null
null
null
null
UTF-8
C++
false
false
980
h
Poly3D.h
/* * Poly3D.h * * Copyright (c) 2011-2016 United States Government as represented by * the National Aeronautics and Space Administration. No copyright * is claimed in the United States under Title 17, U.S.Code. All Other * Rights Reserved. */ #ifndef POLY3D_H_ #define POLY3D_H_ #include <vector> #include "Poly2D.h" #include "Vect2.h" #include "Vect3.h" namespace larcfm { class Poly3D { private: Poly2D p2d; double top; double bottom; ; public: void calcCentroid() ; Poly3D(); Poly3D(const Poly2D& v, double b, double t); // Poly3D(const Vect3& v); Poly3D(const Poly3D& p); Poly2D poly2D() const; void addVertex(const Vect2& v); Vect2 getVertex(int i) const ; int size() const; double getTop() const ; void setTop(double t); double getBottom()const ; void setBottom(double b) ; Vect3 centroid() const ; Vect3 averagePoint() const ; std::string toString() ; bool contains(const Vect3& v) const; }; } #endif /* Poly3D_H_ */
7dd66c892d2a582fae932f62ad714e4049b40716
bf2c42a581639c94138d6ec465f17ebfd73f3c29
/customgauge.h
cc40375be68af44f57ce1615b44b63d42114776c
[]
no_license
wahello/CustomGauge
5101c3c2ead58583050e10d4a6e3d5ea11d83178
423e2c1c9b2d7dc1d1db13a33e58b3a038d7a448
refs/heads/master
2023-03-20T01:01:30.121014
2017-05-25T15:56:25
2017-05-25T15:56:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,732
h
customgauge.h
/************************************************* * Name: customgauge.h * Purpose: CustomGauge class definition * Author: DJ_Kovrik (djkovrik at gmail.com) * Created: 2013-01-23 * Source: https://github.com/djkovrik *************************************************/ #ifndef CUSTOMGAUGE_H_INCLUDED #define CUSTOMGAUGE_H_INCLUDED #include <wx/panel.h> #include <wx/dcclient.h> class wxBrush; class wxPen; class wxSizeEvent; class wxColour; class wxFont; class CustomGauge { public: CustomGauge() : m_panel(NULL), m_position(0), m_range(100), m_label(true) { InitialInit(); } CustomGauge(wxPanel* parent, int pos = 0, int range = 100, bool f = false) : m_panel(parent), m_position(pos), m_range(range), m_label(f) { InitialInit(); } ~CustomGauge(); void RedrawNow(); // Setters & Getters int GetValue() const { return m_position; } int GetRange() const { return m_range; } void SetValue(int pos); void SetRange(int range); // Settings void ShowPercents(bool flag) { m_label = flag; } void SetBackgroundBrush (const wxColour& col) { m_backFill.SetColour(col); } void SetForegroundBrush (const wxColour& col) { m_foreFill.SetColour(col); } void SetPen (const wxPen& pen) { m_pen = pen; } void SetFont (const wxFont &font) { m_font = font; } void SetTextForeground (const wxColour &colour) { m_font_col = colour; } private: wxPanel* m_panel; // Panel pointer (canvas) int m_position; // Current position int m_range; // Overall range bool m_label; // If true, then add percents value label wxBrush m_backFill; // Gauge background brush wxBrush m_foreFill; // Gauge bar brush wxPen m_pen; // For gauge border drawing wxFont m_font; // Text font wxColour m_font_col; // Text colour // Brushes and pen init void InitialInit(); // Resize event handler void OnPanelResize(wxSizeEvent& event); }; #endif // CUSTOMGAUGE_H_INCLUDED /************************************************************** * SetBackgroundBrush, SetForegroundBrush, * SetPenColour and SetTextForeground methods can get * RGB values or colour names. * * Example: * my_gauge->SetForegroundBrush("RED"); * my_gauge->SetBackgroundBrush(wxColour(0,255,0)); * * Available colour names: * http://docs.wxwidgets.org/trunk/classwx_colour_database.html * *************************************************************/
b3a1d9674c28962e7798b71f0036ff6b806601d9
1f77f63fc4bcf538fc892f6a5ba54058367ed0e5
/src/base/foundation/EquationInitializer.hpp
2426add04a57df558ee11960cf151dc63886bd54
[ "Apache-2.0" ]
permissive
ChristopherRabotin/GMAT
5f8211051b620562947443796fa85c80aed5a7cf
829b7c2c3c7ea73d759c338e7051f92f4f2f6f43
refs/heads/GMAT-2020a
2022-05-21T07:01:48.435641
2022-05-09T17:28:07
2022-05-09T17:28:07
84,392,259
24
10
Apache-2.0
2022-05-11T03:48:44
2017-03-09T03:09:20
C++
UTF-8
C++
false
false
2,703
hpp
EquationInitializer.hpp
//------------------------------------------------------------------------------ // EquationInitializer //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // CSALT: Collocation Stand Alone Library and Toolkit // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under Purchase // Order NNG16LD52P // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: Jul 19, 2018 /** * Initializer for equations */ //------------------------------------------------------------------------------ #ifndef EquationInitializer_hpp #define EquationInitializer_hpp #include "gmatdefs.hpp" class SolarSystem; class CoordinateSystem; /** * Initializer for equations in objects in a Sandbox */ class GMAT_API EquationInitializer { public: EquationInitializer(SolarSystem *solSys, ObjectMap *objMap, ObjectMap *globalObjMap, CoordinateSystem* intCS/*, bool useGOS = false, bool fromFunction = false*/); virtual ~EquationInitializer(); bool PrepareEquationsForMapObjects(); // // Placeholder for moving equations from commands (i.e. from Assignment) // bool PrepareEquations(GmatCommand *cmd); protected: /// The solar system in use SolarSystem *theSolarSystem; /// Mapping of (local) objects in the Sandbox ObjectMap *theLocalObjectStore; /// Mapping of (global) objects in the Sandbox ObjectMap *theGlobalObjectStore; /// The current reference coordinate system CoordinateSystem *theInternalCS; // Moderator *theModerator; // Publisher *thePublisher; // bool includeGOS; // bool registerSubscribers; // bool inFunction; bool PrepareEquations(GmatBase *forObj); // Don't allow these this week EquationInitializer(const EquationInitializer &eqi); EquationInitializer operator=(const EquationInitializer &eqi); }; #endif /* EquationInitializer_hpp */
c0d1cf66f64ce5777d5de396957d49cc3fe009b4
1a66a14a627ea0863a9feee8357df204b4dddb9a
/Gustavo_Bazan_pila.cpp
4ac7204e871bb9453cffc178fa9f3f3d7e37588a
[]
no_license
gssbzn/taller_3_alg_prog_2_ordenamiento
0076f33fc6962e98b3d5d930e5199467a40a4c80
ed8b8245462bacf4edcabe1dd8d6749cb9b9ce8b
refs/heads/master
2016-08-04T17:53:42.460244
2012-06-19T00:25:17
2012-06-19T00:25:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,400
cpp
Gustavo_Bazan_pila.cpp
#ifndef __GUSTAVO_BAZAN_PILA_CPP__ #define __GUSTAVO_BAZAN_PILA_CPP__ #include "Gustavo_Bazan_lib.h" /********************************PILAS*******************************/ //Constructor pila :: pila () : lista(){ } //Destructor pila :: ~pila (void){ ptr_nodo aux; while(!es_vacia()){ desempilar(); } } void pila :: vacia(){ while(!es_vacia()){ desempilar(); } return; } bool pila :: es_vacia(){ if (ultimo == 0) return(true); else return(false); } void pila :: empilar (elemento e){ insertar(0, e); return; } void pila :: desempilar (){ resto(); } elemento pila :: tope(){ elemento e=primero(); return(e); } // operador friend << sobrecargado ostream& operator << (ostream& co, const pila &pil){ elemento e; ptr_nodo act; act=pil.ptr; for(int i=0; i < pil.ultimo; i++){ e=act->get_elemento(); co << e << " "; act=act->get_ptr(); } return co; } elemento get_menor(pila *P){ pila P2, ord; elemento e, a, menor=100001; while(!P->es_vacia()){ e=P->tope(); P->desempilar(); if(e < menor){ if(!ord.es_vacia()){ a.set_elemento(ord.tope()); P2.empilar(a); ord.desempilar(); } menor=e; ord.empilar(e); } else{ P2.empilar(e); } } while(!P2.es_vacia()){ e=P2.tope(); P2.desempilar(); P->empilar(e); } return(menor); } #endif
03b1ceeb37d853533268ae522f1c63e03819d771
90517ce1375e290f539748716fb8ef02aa60823b
/solved/i-k/intersection-between-circle-and-rectangle/make_graph.cpp
fdd9c96e29e1472e84651827498fb0455570e7b7
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
Code4fun4ever/pc-code
23e4b677cffa57c758deeb655fd4f71b36807281
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
refs/heads/master
2021-01-15T08:15:00.681534
2014-09-08T05:28:39
2014-09-08T05:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,180
cpp
make_graph.cpp
#include <cstdio> template <typename T> struct _Point { T x, y; _Point(): x(0), y(0) {} _Point(T X, T Y) : x(X), y(Y) {} T distance(const _Point &p) const { T dx = p.x - x, dy = p.y - y; return sqrt(dx*dx + dy*dy); } bool operator<(const _Point &p) const { return x < p.x || (x == p.x && y < p.y); } bool operator==(const _Point &p) const { return x == p.x && y == p.y; } _Point operator-(const _Point &b) const { return _Point(x - b.x, y - b.y); } bool collinear(const _Point &b, const _Point &c) const { return (b.y - y) * (c.x - x) == (c.y - y) * (b.x - x); } bool in_box(const _Point &a, const _Point &b) const { T lox = min(a.x, b.x), hix = max(a.x, b.x); T loy = min(a.y, b.y), hiy = max(a.y, b.y); return x >= lox && x <= hix && y >= loy && y <= hiy; } // cross product magnitude of axb, relative to this T cross(const _Point &a, const _Point &b) const { return (a.x-x)*(b.y-y) - (a.y-y)*(b.x-x); } }; typedef _Point<int> Point; Point circ; int r; Point rect[4]; const char *outfile = "graph.tex"; FILE *out; void tikz_header() { out = fopen(outfile, "w"); fprintf(out, "\\documentclass[10pt]{article}\n" "\\usepackage[paperwidth=15cm,paperheight=15cm]{geometry}\n" "\\usepackage{tikz}\n" "\\begin{document}\n"); } int tikn = 0; void tikz_case() { fprintf(out, "\n\\pagebreak\n" "Case %d:\\\\\n" "\\begin{tikzpicture}[scale=.3]\n" " \\draw[style=help lines] (0,0) grid (30, 30);\n" " \\draw[style=very thick] ", ++tikn); for (int i = 0; i < 4; ++i) fprintf(out, "(%d,%d) -- ", rect[i].x, rect[i].y); fprintf(out, "cycle;\n" " \\draw[style=very thick] (%d,%d) circle(%d);\n" "\\end{tikzpicture}\n", circ.x, circ.y, r); } void tikz_footer() { fprintf(out, "\\end{document}\n" ); fclose(out); } void solve() { rect[1] = Point(rect[2].x, rect[0].y); rect[3] = Point(rect[0].x, rect[2].y); tikz_case(); } int main() { int T; scanf("%d", &T); tikz_header(); while (T--) { scanf("%d%d%d %d%d%d%d", &circ.x, &circ.y, &r, &rect[0].x, &rect[0].y, &rect[2].x, &rect[2].y); solve(); } tikz_footer(); return 0; }
61f1a2d6da54258a8415152dcee43b0dcc716812
a95dafa235db297cd4bd768f193de9854c3d91cd
/game/foe.cc
2a4409238c378807a0ed483e80da5e2519c17fe7
[]
no_license
mpersano/not-qix
e53096f609ab5e462d32dd5b6e2a1c39a16c6760
3de0407a5c22e1ed6016e54ca74b88bdc0eba77c
refs/heads/master
2020-04-06T03:40:26.109747
2016-02-13T15:46:55
2016-02-13T15:46:55
40,371,969
3
0
null
null
null
null
UTF-8
C++
false
false
2,394
cc
foe.cc
#include <cmath> #include <ggl/vec2_util.h> #include "game.h" #include "foe.h" foe::foe(game& g, const vec2f& pos, float radius) : entity { g } , pos_ { pos } , dir_ { 1, 0 } , speed_ { 0 } , radius_ { radius } { } void foe::update_position() { // update position pos_ += speed_*dir_; // collide against border const auto& border = game_.border; const int height = game_.grid_rows*CELL_SIZE; const int width = game_.grid_cols*CELL_SIZE; bool collided; do { collided = false; for (size_t i = 0; i < border.size(); i++) { const vec2f v0 = border[i]*CELL_SIZE; const vec2f v1 = border[(i + 1)%border.size()]*CELL_SIZE; if (collide_against_edge(v0, v1)) collided = true; } if (collide_against_edge({ 0, 0 }, { 0, height })) collided = true; if (collide_against_edge({ 0, height }, { width, height })) collided = true; if (collide_against_edge({ width, height }, { width, 0 })) collided = true; if (collide_against_edge({ width, 0 }, { 0, 0 })) collided = true; } while (collided); } bool foe::collide_against_edge(const vec2f& v0, const vec2f& v1) { vec2f c = seg_closest_point(v0, v1, pos_); vec2f d = pos_ - c; float dist = length(d); if (dist < radius_) { static const float FUDGE = 2.; pos_ += ((radius_ - dist) + FUDGE)*normalized(d); vec2f n = normalized(pos_ - c); dir_ -= 2.f*dot(dir_, n)*n; return true; } return false; } void foe::rotate_to_player() { vec2f n { -dir_.y, dir_.x }; float da = .025f*dot(n, normalized(vec2f(game_.get_player_world_position()) - pos_)); const float c = cosf(da); const float s = sinf(da); vec2f next_dir { dot(dir_, vec2f { c, -s }), dot(dir_, vec2f { s, c }) }; dir_ = next_dir; } void foe::rotate(float a) { dir_ = dir_.rotate(a); } void foe::set_direction(const vec2f& dir) { dir_ = normalized(dir); } vec2f foe::get_direction() const { return dir_; } void foe::set_speed(float speed) { speed_ = speed; } float foe::get_speed() const { return speed_; } bool foe::intersects(const vec2i& from, const vec2i& to) const { return length(pos_ - seg_closest_point(vec2f(from), vec2f(to), pos_)) < radius_ || intersects_children(from, to); } bool foe::intersects(const vec2i& center, float radius) const { return length(pos_ - vec2f(center)) < radius_ + radius || intersects_children(center, radius); } vec2f foe::get_position() const { return pos_; }
25a8e6e566bd08b79274629d9235fcb2e6a15d08
9e1dbea3884c259f472e197d12f0c35846bfca68
/patern/dimand.cpp
efcfd912348f4669bbd8b3778914561f8741646e
[]
no_license
shrimansoft/Cpp
f1667e0664435784aa1cdd444eb100514ed9a228
1b6f51ca99b3228f1a61dea6b830825f3faaab32
refs/heads/master
2021-07-06T08:41:22.801290
2019-03-27T13:29:07
2019-03-27T13:29:07
143,712,326
0
3
null
2019-01-19T09:56:30
2018-08-06T10:21:27
C++
UTF-8
C++
false
false
2,328
cpp
dimand.cpp
/* This program is to printing paterns of different types. */ #include<iostream> using namespace std; //--------------*** hollow square star pattern ***---------------- void pro_1(int n){ for( int i=0;i<n*n;i++){ cout<<((i/n>n/2?n-i/n-1:i/n)*(i%n>n/2?n-i%n-1:i%n)?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //-------------*** hollow square star pattern with diagonal ***------- void pro_2(int n){ for( int i=0;i<n*n;i++){ cout<<(((i/n>n/2?n-i/n-1:i/n)*(i%n>n/2?n-i%n-1:i%n))&&((i/n>n/2?n-i/n-1:i/n)!=(i%n>n/2?n-i%n-1:i%n))?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //---------*** Hollow Right Triangle Star Pattern ***------------- void pro_3(int n){ for( int i=0;i<n*n;i++){ cout<<(((i/n)!=(n-1))*(i%n)&&((i/n)!=(i%n))?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //--------*** Mirrored Right Triangle Star Pattern ***------------- void pro_4(int n){ for( int i=0;i<n*n;i++){ cout<<((i/n+i%n)<(n-1)?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //-------*** 11.Hollow Mirrored Right Triangle Star Pattern ***------- void pro_5(int n){ for( int i=0;i<n*n;i++){ cout<<((i/n+i%n-n+1)*((i/n)-n+1)*((i%n)-n+1)?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //-----*** 15.Hollow Inverted Mirrored Right Triangle Star Pattern ***----- void pro_6(int n){ for( int i=0;i<n*n;i++){ cout<<((i/n-i%n)*(i/n)*((i%n)-n+1)?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //-----*** 16.Pyramid Star Pattern ***--------- void pro_7(int i){ int n=i*2+1; for( int i=0;i<n*(n/2);i++){ cout<<((i%n>n/2?n-i%n-1:i%n)+(i/n)<n/2?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //----*** 21.Mirrored Half Diamond Star Pattern ***------- void pro_8(int i){ int n=i*2+1; for( int i=0;i<n*n;i++){ cout<<((i/n>n/2?n-i/n-1:i/n)+(i%n>n/2?-1:i%n)<n/2?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //----*** 23.Hollow Diamond Star Pattern ***--------- void pro_9(int i){ int n=i*2+1; for( int i=0;i<n*n;i++){ cout<<((i/n>n/2?n-i/n-1:i/n)+(i%n>n/2?n-i%n-1:i%n)>n/2?' ':'*'); if(i%n==(n-1)) cout<<endl; } } //-----*** 21.Diamond Star Pattern ***------ void pro_10(int i){ int n=i*2+1; for( int i=0;i<n*n;i++){ cout<<((i/n>n/2?n-i/n-1:i/n)+(i%n>n/2?n-i%n-1:i%n)<n/2?' ':'*'); if(i%n==(n-1)) cout<<endl; } } int main() { int n; cout<<"Enter a number : "; cin >> n; mhdsp(n); return 0; }
e1e7ea66c5e7c8e42c61baf505f768ece55d0de6
0337c1df871a431c6a8b03ad871d396826d7e210
/src/musikcube/cursespp/Win32Util.cpp
897179a358a51aa93316940b77e766ef370bd7ec
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
clangen/musikcube
be1ad8c1567c9e3cfbf71e1f595ede9aa0152a97
64485978ea2e4483499996a8e2304ce5566573d9
refs/heads/master
2023-08-28T00:52:06.905519
2023-08-02T02:47:41
2023-08-02T02:47:41
32,483,164
4,049
370
BSD-3-Clause
2023-09-08T05:05:44
2015-03-18T20:41:57
C++
UTF-8
C++
false
false
11,464
cpp
Win32Util.cpp
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2023 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include <stdafx.h> #include <cursespp/Win32Util.h> #include <Windows.h> #include <Commctrl.h> #include <shellapi.h> #ifdef WIN32 using namespace winrt::Windows::UI::ViewManagement; #define WM_TRAYICON (WM_USER + 2000) #define WM_SHOW_OTHER_INSTANCE (WM_USER + 2001) static std::basic_string<TCHAR> className = L"Curses_App"; static HWND mainWindow = nullptr; static WNDPROC oldWndProc = nullptr; static std::unique_ptr<NOTIFYICONDATA> trayIcon; static bool minimizeToTray = false, minimizedToTray = false; static std::string appTitle; static HICON icon16 = nullptr, icon32 = nullptr; static std::string runingMutexName; static HANDLE runningMutex; static DWORD runningMutexLastError = 0; static HWND findThisProcessMainWindow() { static TCHAR buffer[256]; if (mainWindow == nullptr) { DWORD dwProcID = GetCurrentProcessId(); HWND hWnd = GetTopWindow(GetDesktopWindow()); while (hWnd) { DWORD dwWndProcID = 0; GetWindowThreadProcessId(hWnd, &dwWndProcID); if (dwWndProcID == dwProcID) { GetClassName(hWnd, buffer, sizeof(buffer)); if (className == std::basic_string<TCHAR>(buffer)) { mainWindow = hWnd; return hWnd; } } hWnd = GetNextWindow(hWnd, GW_HWNDNEXT); } } return nullptr; } static HWND findOtherProcessMainWindow(const std::string& title) { static TCHAR buffer[256]; DWORD dwProcID = GetCurrentProcessId(); HWND hWnd = GetTopWindow(GetDesktopWindow()); while (hWnd) { DWORD dwWndProcID = 0; GetWindowThreadProcessId(hWnd, &dwWndProcID); if (dwWndProcID != dwProcID) { /* not in this process */ GetClassName(hWnd, buffer, sizeof(buffer)); if (className == std::basic_string<TCHAR>(buffer)) { ::GetWindowText(hWnd, buffer, sizeof(buffer)); if (title == u16to8(buffer)) { /* title must match*/ return hWnd; } } } hWnd = GetNextWindow(hWnd, GW_HWNDNEXT); } return nullptr; } static HICON loadIcon(int resourceId, int size) { return (HICON) ::LoadImageA( GetModuleHandle(nullptr), MAKEINTRESOURCEA(resourceId), IMAGE_ICON, size, size, 0); } static void initTrayIcon(HWND hwnd) { if (!trayIcon) { trayIcon.reset(new NOTIFYICONDATA()); SecureZeroMemory(trayIcon.get(), sizeof(*trayIcon)); trayIcon->hWnd = hwnd; trayIcon->uID = 0; trayIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; trayIcon->uCallbackMessage = WM_TRAYICON; trayIcon->hIcon = icon16; std::wstring title = u8to16(appTitle); ::wcscpy_s(trayIcon->szTip, 255, title.c_str()); } } static void restoreFromTray(HWND hwnd) { Shell_NotifyIcon(NIM_DELETE, trayIcon.get()); minimizedToTray = false; ShowWindow(hwnd, SW_SHOWNORMAL); } static void resetMutex() { CloseHandle(runningMutex); runningMutex = nullptr; runningMutexLastError = 0; } static LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, UINT_PTR id, DWORD_PTR data) { if (minimizeToTray) { if ((msg == WM_SIZE && wparam == SIZE_MINIMIZED) || (msg == WM_SYSCOMMAND && wparam == SC_MINIMIZE)) { if (!minimizedToTray) { initTrayIcon(hwnd); minimizedToTray = (Shell_NotifyIcon(NIM_ADD, trayIcon.get()) != 0); if (minimizedToTray) { ShowWindow(hwnd, SW_HIDE); trayIcon->uVersion = NOTIFYICON_VERSION; ::Shell_NotifyIcon(NIM_SETVERSION, trayIcon.get()); return 1; } } } } if (msg == WM_TRAYICON) { if (LOWORD(lparam) == WM_LBUTTONUP) { restoreFromTray(hwnd); return 1; } } if (msg == WM_SHOW_OTHER_INSTANCE) { cursespp::win32::ShowMainWindow(); restoreFromTray(hwnd); return 1; } if (msg == WM_QUIT) { resetMutex(); } if (msg == WM_SETTINGCHANGE) { if (lparam && !lstrcmp(LPCTSTR(lparam), L"ImmersiveColorSet")) { cursespp::win32::ConfigureThemeAwareness(); } } return DefSubclassProc(hwnd, msg, wparam, lparam); } namespace cursespp { namespace win32 { void ShowMainWindow() { findThisProcessMainWindow(); if (mainWindow) { ShowWindow(mainWindow, SW_SHOWNORMAL); } } void HideMainWindow() { findThisProcessMainWindow(); if (mainWindow) { ShowWindow(mainWindow, SW_HIDE); } } void Minimize() { findThisProcessMainWindow(); if (mainWindow) { ShowWindow(mainWindow, SW_SHOWMINIMIZED); } } HWND GetMainWindow() { findThisProcessMainWindow(); return mainWindow; } void SetIcon(int resourceId) { const HWND hwnd = GetMainWindow(); icon16 = loadIcon(resourceId, 16); icon32 = loadIcon(resourceId, 48); PostMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM) icon16); PostMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM) icon32); } void InterceptWndProc() { HWND hwnd = GetMainWindow(); if (hwnd) { SetWindowSubclass(hwnd, wndProc, 1001, 0); } } void SetMinimizeToTray(bool enabled) { minimizeToTray = enabled; } void SetAppTitle(const std::string& title) { appTitle = title; } bool AlreadyRunning() { return !IsDebuggerPresent() && (runningMutexLastError == ERROR_ALREADY_EXISTS); } void ShowOtherInstance(const std::string& title) { HWND otherHwnd = findOtherProcessMainWindow(title); if (otherHwnd) { SendMessage(otherHwnd, WM_SHOW_OTHER_INSTANCE, 0, 0); ::SetForegroundWindow(otherHwnd); } } void EnableSingleInstance(const std::string& uniqueId) { if (!uniqueId.size()) { resetMutex(); return; } std::string mutexName = "cursespp::" + uniqueId; if (mutexName != runingMutexName) { resetMutex(); runingMutexName = mutexName; runningMutex = CreateMutexA(nullptr, false, runingMutexName.c_str()); runningMutexLastError = GetLastError(); } } static bool IsWine() { HMODULE ntdll = LoadLibrary(L"ntdll.dll"); bool result = ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; FreeLibrary(ntdll); return result; } void ConfigureDpiAwareness() { typedef HRESULT(__stdcall *SetProcessDpiAwarenessProc)(int); static const int ADJUST_DPI_PER_MONITOR = 2; HMODULE shcoreDll = LoadLibrary(L"shcore.dll"); if (shcoreDll) { SetProcessDpiAwarenessProc setDpiAwareness = (SetProcessDpiAwarenessProc) GetProcAddress(shcoreDll, "SetProcessDpiAwareness"); if (setDpiAwareness) { setDpiAwareness(ADJUST_DPI_PER_MONITOR); } FreeLibrary(shcoreDll); } } void ConfigureThemeAwareness() { if (IsWine()) { return; } typedef HRESULT(__stdcall* DwmSetWindowAttributeProc)(HWND, DWORD, LPCVOID, DWORD); static const DWORD DWMWA_USE_IMMERSIVE_DARK_MODE = 20; HMODULE dwmapiDll = LoadLibrary(L"dwmapi.dll"); if (dwmapiDll) { DwmSetWindowAttributeProc dwmSetWindowAttribute = (DwmSetWindowAttributeProc) GetProcAddress(dwmapiDll, "DwmSetWindowAttribute"); if (dwmSetWindowAttribute) { const auto settings = UISettings(); const auto foreground = settings.GetColorValue(UIColorType::Foreground); const BOOL isDarkMode = (((5 * foreground.G) + (2 * foreground.R) + foreground.B) > (8 * 128)); HWND mainHwnd = GetMainWindow(); dwmSetWindowAttribute(mainHwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &isDarkMode, sizeof(isDarkMode)); /* on some versions of Windows this doesn't redraw immediately; this hack very slightly resizes the window to force a repaint... no amount of UpdateWindow/RedrawWindow/etc would do the trick */ RECT rect = { 0 }; GetWindowRect(mainWindow, &rect); SetWindowPos( mainWindow, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top + 1, SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED); } FreeLibrary(dwmapiDll); } } int RegisterFont(const std::string& filename) { return AddFontResourceEx(u8to16(filename).c_str(), FR_PRIVATE, 0); } int UnregisterFont(const std::string& filename) { return RemoveFontResourceEx(u8to16(filename).c_str(), FR_PRIVATE, 0); } } } #endif
0caa9bbf1b431729a51c157d7bb8a5219235bd4d
3eb87c6badf4bbf2d0bef74029afd9d2dec51a9f
/src/js/jit/C1Spewer.h
002125e1d37d419afe07206f11a94e23b7e54b15
[ "MPL-2.0", "MIT" ]
permissive
zief/blazefox
9da726fc6662976b5648ebae985ab1cd84bd9c56
d8687161a2483f1fb27cce2f2928b67604fca4ca
refs/heads/master
2020-04-16T06:27:57.210311
2019-01-12T01:31:07
2019-01-12T01:31:07
165,347,964
1
0
MIT
2019-01-12T04:53:25
2019-01-12T04:53:25
null
UTF-8
C++
false
false
1,282
h
C1Spewer.h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef jit_C1Spewer_h #define jit_C1Spewer_h #ifdef JS_JITSPEW #include "NamespaceImports.h" #include "js/RootingAPI.h" #include "vm/Printer.h" namespace js { namespace jit { class BacktrackingAllocator; class MBasicBlock; class MIRGraph; class LNode; class C1Spewer { MIRGraph* graph; GenericPrinter& out_; public: explicit C1Spewer(GenericPrinter& out) : graph(nullptr), out_(out) { } void beginFunction(MIRGraph* graph, JSScript* script); void spewPass(const char* pass); void spewRanges(const char* pass, BacktrackingAllocator* regalloc); void endFunction(); private: void spewPass(GenericPrinter& out, MBasicBlock* block); void spewRanges(GenericPrinter& out, BacktrackingAllocator* regalloc, LNode* ins); void spewRanges(GenericPrinter& out, MBasicBlock* block, BacktrackingAllocator* regalloc); }; } // namespace jit } // namespace js #endif /* JS_JITSPEW */ #endif /* jit_C1Spewer_h */
90b92027a29bb28718b5c512772a6232851e6b63
4e4f15207f538847de1e1b8d9215531c7f858ec5
/DynamicRandomVar.h
f1f406031d3ecd9f0381a7e5970aaf875d207e63
[ "MIT" ]
permissive
aekul/aether
d896445c9b3d3e398ae62a6f4a9e8f081cb3a5b4
1e882f898561eaa92492de018bd2c09f71ba4c93
refs/heads/master
2019-07-09T01:01:43.118756
2018-11-05T13:43:13
2019-05-05T16:19:32
99,071,911
51
6
MIT
2019-05-05T16:19:34
2017-08-02T04:24:53
C++
UTF-8
C++
false
false
4,986
h
DynamicRandomVar.h
#ifndef DYNAMIC_RANDOM_VAR_H #define DYNAMIC_RANDOM_VAR_H #include <vector> #include <numeric> #include "aether/fwd/Math.h" namespace aether { template <typename T> struct pdf_value_pair { Real pdf; T value; }; template <typename T> auto make_pdf_value_pair(Real pdf, T&& value) { return pdf_value_pair<std::decay_t<T>>{pdf, std::forward<T>(value)}; } template <typename T> struct discrete_random_var_dynamic { using value_t = T; struct discrete_array_struct { T value; Real pdf; Real cdf; }; discrete_random_var_dynamic(int N) : data(N) { for (int i = 0; i < N; i++) { data[i].value = i; data[i].pdf = Real(1.0) / N; data[i].cdf = Real(i + 1) / N; } } discrete_random_var_dynamic(const T *values, const Real *weights, const std::size_t N) : data(N) { if (N >= 1) { data[0].value = values[0]; data[0].pdf = data[0].cdf = weights[0]; for (size_t i = 1; i < N; i++) { data[i].value = values[i]; data[i].pdf = weights[i]; data[i].cdf = data[i - 1].cdf + weights[i]; } Real invNorm = Real(1) / data[N - 1].cdf; for (size_t i = 0; i < N; i++) { data[i].pdf *= invNorm; data[i].cdf *= invNorm; } } } discrete_random_var_dynamic(const T *values, const std::size_t N) : data(N) { for (int i = 0; i < N; i++) { data[i].value = values[i]; data[i].pdf = Real(1.0) / N; data[i].cdf = Real(i + 1) / N; } } discrete_random_var_dynamic(const pdf_value_pair<T> *pairs, const std::size_t N) : data(N) { if (N >= 1) { data[0].value = pairs[0].value; data[0].pdf = data[0].cdf = pairs[0].pdf; for (size_t i = 1; i < N; i++) { data[i].value = pairs[i].value; data[i].pdf = pairs[i].pdf; data[i].cdf = data[i - 1].cdf + pairs[i].pdf; } Real invNorm = Real(1) / data[N - 1].cdf; for (size_t i = 0; i < N; i++) { data[i].pdf *= invNorm; data[i].cdf *= invNorm; } } } std::size_t Size() const { return data.size(); } value_t Value(std::size_t i) const { return data[i].value; } value_t Sample(Real u) const { std::size_t N = data.size(); for (std::size_t i = 0; i < N; ++i) { if (u < data[i].cdf) { return data[i].value; } } return data[N - 1].value; } Real Pdf(const value_t& value) const { std::size_t N = data.size(); Real ret(0); for (std::size_t i = 0; i < N; ++i) { if (data[i].value == value) { ret += data[i].pdf; } } return ret; } std::vector<discrete_array_struct> data; }; template <typename T> constexpr auto discrete_dynamic(const std::vector<T>& values) { return discrete_random_var_dynamic<T>{values.data(), values.size()}; } template <typename T> constexpr auto discrete_dynamic(const T *values, const std::size_t N) { return discrete_random_var_dynamic<T>{values, N}; } template <typename T> constexpr auto discrete_dynamic(const std::vector<T>& values, const std::vector<Real>& weights) { return discrete_random_var_dynamic<T>{values.data(), weights.data(), values.size()}; } template <typename T> constexpr auto discrete_dynamic(const T *values, const Real *weights, const std::size_t N) { return discrete_random_var_dynamic<T>{values, weights, N}; } inline auto discrete_dynamic(int N) { return discrete_random_var_dynamic<int>{N}; } template <typename T> struct discrete_random_var_2d { using value_t = T; template <typename C> discrete_random_var_2d(const C& grid) : dist(Init(grid)) { } template <typename C> auto Init(const C& grid) { auto num_rows = grid.size(); std::vector<Real> rows(num_rows); std::vector<pdf_value_pair<discrete_random_var_dynamic<T>>> dists; Real total = Real(0); for (int i = 0; i < num_rows; ++i) { rows[i] = Sum(grid[i]); total += rows[i]; } for (int i = 0; i < num_rows; ++i) { rows[i] /= total; dists.push_back(make_pdf_value_pair(rows[i], discrete_dynamic<T>(grid[i]))); } return discrete_dynamic<discrete_random_var_dynamic<T>>(dists); } template <typename C> Real Sum(const C& c) { Real sum = Real(0); for (auto v : c) { sum += v; } return sum; } value_t Sample(Real u, Real v) const { return (dist.Sample(u)).Sample(v); } discrete_random_var_dynamic<discrete_random_var_dynamic<T>> dist; }; template <typename A, typename B> constexpr auto discrete_2d(A&& a, B&& b) { return discrete_random_var_2d<std::decay_t<A>>{std::forward<A>(a), std::forward<B>(b)}; } template <typename T, typename A> constexpr auto discrete_dynamic_2d(A&& a) { return discrete_random_var_2d<T>{std::forward<A>(a)}; } template <typename A, typename B> constexpr auto discrete(A&& a, B&& b) { return discrete_2d(discrete(std::forward<A>(a)), discrete(std::forward<B>(b))); } } // end namespace aether #endif
15840835f481cb5f490e01fc9be8dac8d40bda68
4d9ea3a81c9249aa41a02731488b1a109258d29d
/src/arduino-station/WindSpeedProvider.cpp
cdec9ff970fe43895b2d538437fb3c8975205bf3
[]
no_license
kowalej/AnemIO
552f319838c98c5c1196ac09eb27f43dc2c30258
d0f5f6d22cd931b549bfb267c15268dda5aab02d
refs/heads/master
2022-09-20T15:06:33.300628
2020-06-04T04:41:49
2020-06-04T04:41:49
198,953,824
0
0
null
null
null
null
UTF-8
C++
false
false
1,956
cpp
WindSpeedProvider.cpp
#include "WindSpeedProvider.h" WindSpeedProvider::WindSpeedProvider() { } bool WindSpeedProvider::setup() { pinMode(WIND_SPEED_SENSOR_SPEED_INPUT_PIN, INPUT); pinMode(WIND_SPEED_SENSOR_TEMPERATURE_INPUT_PIN, INPUT); _isOnline = true; return _isOnline; } float WindSpeedProvider::getWindSpeedRaw() { float total = 0; for (int i = 0; i < WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; i++) { total += analogRead(WIND_SPEED_SENSOR_SPEED_INPUT_PIN); } float sampledAvg = total / WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; // From Modern Device: // Wind formula derived from a wind tunnel data, annemometer and some fancy Excel regressions. return pow((((float)sampledAvg - 264.0f) / 85.6814f), 3.36814f) * 0.8689758250f; // The last multiplication converts from MPH to knots. } float WindSpeedProvider::getWindSensorTemperature() { float total = 0; for (int i = 0; i < WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; i++) { total += analogRead(WIND_SPEED_SENSOR_TEMPERATURE_INPUT_PIN); } float sampledAvg = total / WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; // From Modern Device: // Convert to volts then use formula from datatsheet // Vout = ( TempC * .0195 ) + .400 // tempC = (Vout - V0c) / TC see the MCP9701 datasheet for V0c and TC float voltage = sampledAvg * (5.0f / 1024.0f); return (voltage - 0.400f) / 0.0195f; } float WindSpeedProvider::getCorrectedWindSpeed(float temperature) { float total = 0; for (int i = 0; i < WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; i++) { total += analogRead(WIND_SPEED_SENSOR_SPEED_INPUT_PIN); } float sampledAvg = total / WIND_SPEED_ANALOG_READ_SAMPLE_COUNT; // Get our voltage value back from the ADC value. float voltage = sampledAvg * (5.0 / 1024.0f); // See https://moderndevice.com/news/calibrating-rev-p-wind-sensor-new-regression/#more-19365. float windSpeed = pow((((voltage - WIND_SPEED_SENSOR_ZERO_WIND_VOLTAGE) / (3.038517 * pow(temperature, 0.115157))) / 0.087288), 3.009364); return windSpeed; }
cd002b0fb795bfa8b16fee54df672fd9a38a204f
1885ce333f6980ab6aad764b3f8caf42094d9f7d
/test/e2e/test_input/ObjectArxHeaders/AcValue.h
5e316e6535444e3f4586121eb11e9701a6cd9699
[ "MIT" ]
permissive
satya-das/cppparser
1dbccdeed4287c36c61edc30190c82de447e415b
f9a4cfac1a3af7286332056d7c661d86b6c35eb3
refs/heads/master
2023-07-06T00:55:23.382303
2022-10-03T19:40:05
2022-10-03T19:40:05
16,642,636
194
26
MIT
2023-06-26T13:44:32
2014-02-08T12:20:01
C++
UTF-8
C++
false
false
12,413
h
AcValue.h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2018 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // Name: AcValue.h // // Description: ////////////////////////////////////////////////////////////////////////////// #pragma once #include "adesk.h" #include "AdAChar.h" #include "AcArray.h" class AcDbEvalVariant; typedef struct tagVARIANT VARIANT; typedef struct _SYSTEMTIME SYSTEMTIME; class AcDbObjectId; class AcGePoint2d; class AcGePoint3d; class AcCmColor; struct resbuf; class AcDbDwgFiler; class AcDbDxfFiler; //************************************************************************* // AcValue //************************************************************************* class AcValue : public AcRxObject { public: enum DataType { kUnknown = 0, kLong = (0x1 << 0), kDouble = (0x1 << 1), kString = (0x1 << 2), kDate = (0x1 << 3), kPoint = (0x1 << 4), k3dPoint = (0x1 << 5), kObjectId = (0x1 << 6), kBuffer = (0x1 << 7), kResbuf = (0x1 << 8), kGeneral = (0x1 << 9), kColor = (0x1 << 10), }; enum UnitType { kUnitless = 0, kDistance = (0x1 << 0), kAngle = (0x1 << 1), kArea = (0x1 << 2), kVolume = (0x1 << 3), kCurrency = (0x1 << 4), kPercentage = (0x1 << 5), kAngleNotTransformed = (0x1 << 16), }; enum ParseOption { kParseOptionNone = 0, kSetDefaultFormat = (0x1 << 0), kPreserveMtextFormat = (0x1 << 1), kConvertTextToValue = (0x1 << 2), kChangeDataType = (0x1 << 3), kParseTextForFieldCode = (0x1 << 4), }; enum FormatOption { kFormatOptionNone = 0, kForEditing = (0x1 << 0), kForExpression = (0x1 << 1), kUseMaximumPrecision = (0x1 << 2), kIgnoreMtextFormat = (0x1 << 3), }; public: static ACDB_PORT bool isValidDataType (const VARIANT& var); public: ACRX_DECLARE_MEMBERS(AcValue); ACDBCORE2D_PORT AcValue(void); ACDBCORE2D_PORT AcValue(AcValue::DataType nDataType); ACDBCORE2D_PORT AcValue(const AcValue& value); ACDBCORE2D_PORT AcValue(AcValue && value); ACDBCORE2D_PORT AcValue(const ACHAR * pszValue); explicit ACDBCORE2D_PORT AcValue(Adesk::Int32 lValue); ACDBCORE2D_PORT AcValue(double fValue); explicit ACDBCORE2D_PORT AcValue(const Adesk::Time64& date); ACDB_PORT AcValue(const SYSTEMTIME& date); ACDBCORE2D_PORT AcValue(const std::tm& date); ACDBCORE2D_PORT AcValue(const AcGePoint2d& pt); ACDBCORE2D_PORT AcValue(double x, double y); ACDBCORE2D_PORT AcValue(const AcGePoint3d& pt); ACDBCORE2D_PORT AcValue(double x, double y, double z); ACDBCORE2D_PORT AcValue(const AcDbObjectId& id); ACDBCORE2D_PORT AcValue(const resbuf& rb); ACDBCORE2D_PORT AcValue(const AcDbEvalVariant& evalVar); ACDB_PORT AcValue(const VARIANT& var); ACDBCORE2D_PORT AcValue(const AcCmColor& var); ACDBCORE2D_PORT AcValue(const void* pBuf, uint32_t dwBufSize); ACDBCORE2D_PORT ~AcValue(void); ACDBCORE2D_PORT bool reset (void); ACDBCORE2D_PORT bool reset (AcValue::DataType nDataType); ACDBCORE2D_PORT bool resetValue (void); ACDBCORE2D_PORT AcValue::DataType dataType (void) const; ACDBCORE2D_PORT AcValue::UnitType unitType (void) const; ACDBCORE2D_PORT bool setUnitType (AcValue::UnitType nUnitType); ACDBCORE2D_PORT const ACHAR* getFormat (void) const; ACDBCORE2D_PORT bool setFormat (const ACHAR* pszFormat); ACDBCORE2D_PORT bool isValid (void) const; ACDBCORE2D_PORT operator const ACHAR * (void) const; ACDBCORE2D_PORT operator Adesk::Int32 (void) const; ACDBCORE2D_PORT operator double (void) const; explicit ACDBCORE2D_PORT operator Adesk::Time64 (void) const; ACDBCORE2D_PORT operator AcGePoint2d (void) const; ACDBCORE2D_PORT operator AcGePoint3d (void) const; ACDBCORE2D_PORT operator AcDbObjectId (void) const; ACDBCORE2D_PORT AcValue& operator= (const AcValue& value); ACDBCORE2D_PORT AcValue& operator= (AcValue && value); ACDBCORE2D_PORT AcValue& operator= (const ACHAR * pszValue); ACDBCORE2D_PORT AcValue& operator= (Adesk::Int32 lValue); ACDBCORE2D_PORT AcValue& operator= (double fValue); ACDBCORE2D_PORT AcValue& operator= (Adesk::Time64 date); ACDBCORE2D_PORT AcValue& operator= (const AcGePoint2d& pt); ACDBCORE2D_PORT AcValue& operator= (const AcGePoint3d& pt); ACDBCORE2D_PORT AcValue& operator= (const AcDbObjectId& objId); ACDBCORE2D_PORT AcValue& operator= (const resbuf& rb); ACDBCORE2D_PORT AcValue& operator= (const AcDbEvalVariant& evalVar); ACDB_PORT AcValue& operator= (const VARIANT& var); ACDBCORE2D_PORT AcValue& operator= (const AcCmColor& clr); ACDBCORE2D_PORT bool operator== (const AcValue& val) const; ACDBCORE2D_PORT bool operator!= (const AcValue& val) const; Adesk::Boolean isEqualTo (const AcRxObject* pOther) const override; ACDBCORE2D_PORT bool get (const ACHAR *& pszValue) const; ACDBCORE2D_PORT bool get (AcString & sValue) const; bool get (ACHAR *& pszValue) const; // deprecated inline ACDBCORE2D_PORT bool get (Adesk::Int32& lValue) const; ACDBCORE2D_PORT bool get (double& fValue) const; ACDBCORE2D_PORT bool get (Adesk::Time64& date) const; ACDBCORE2D_PORT bool get (std::tm& date) const; ACDB_PORT bool get (SYSTEMTIME& date) const; ACDBCORE2D_PORT bool get (AcGePoint2d& pt) const; ACDBCORE2D_PORT bool get (double& x, double& y) const; ACDBCORE2D_PORT bool get (AcGePoint3d& pt) const; ACDBCORE2D_PORT bool get (double& x, double& y, double& z) const; ACDBCORE2D_PORT bool get (AcDbObjectId& objId) const; ACDBCORE2D_PORT bool get (resbuf** pRb) const; ACDBCORE2D_PORT bool get (AcDbEvalVariant& evalVar) const; ACDB_PORT bool get (VARIANT& var) const; ACDBCORE2D_PORT bool get (AcCmColor& clr) const; ACDBCORE2D_PORT bool get (void*& pBuf, uint32_t& dwBufSize) const; ACDBCORE2D_PORT bool set (const AcValue& value); ACDBCORE2D_PORT bool set (const ACHAR* pszValue); ACDBCORE2D_PORT bool set (AcValue::DataType nDataType, const ACHAR* pszValue); ACDBCORE2D_PORT bool set (Adesk::Int32 lValue); ACDBCORE2D_PORT bool set (double fValue); ACDBCORE2D_PORT bool set (const Adesk::Time64& date); ACDB_PORT bool set (const SYSTEMTIME& date); ACDBCORE2D_PORT bool set (const std::tm& date); ACDBCORE2D_PORT bool set (const AcGePoint2d& pt); ACDBCORE2D_PORT bool set (double x, double y); ACDBCORE2D_PORT bool set (const AcGePoint3d& pt); ACDBCORE2D_PORT bool set (double x, double y, double z); ACDBCORE2D_PORT bool set (const AcDbObjectId& objId); ACDBCORE2D_PORT bool set (const resbuf& rb); ACDBCORE2D_PORT bool set (const AcDbEvalVariant& evalVar); ACDB_PORT bool set (const VARIANT& var); ACDBCORE2D_PORT bool set (const AcCmColor& clr); ACDBCORE2D_PORT bool set (const void* pBuf, uint32_t dwBufSize); ACDBCORE2D_PORT bool parse (const ACHAR* pszText, AcValue::DataType nDataType, AcValue::UnitType nUnitType, const ACHAR* pszFormat, AcValue::ParseOption nOption, const AcDbObjectId* pTextStyleId); ACDBCORE2D_PORT const ACHAR* format (void) const; ACDBCORE2D_PORT AcString format (const ACHAR* pszFormat) const; ACDBCORE2D_PORT bool format (AcString & sValue) const; bool format (ACHAR*& pszValue) const; // deprecated inline ACDBCORE2D_PORT bool format (const ACHAR* pszFormat, AcString & sValue) const; bool format (const ACHAR* pszFormat, ACHAR*& pszValue) const; // deprecated inline ACDBCORE2D_PORT AcString format (AcValue::FormatOption nOption); ACDBCORE2D_PORT AcString format (const ACHAR* pszFormat, AcValue::FormatOption nOption); ACDBCORE2D_PORT bool convertTo (AcValue::DataType nDataType, AcValue::UnitType nUnitType); ACDBCORE2D_PORT bool convertTo (AcValue::DataType nDataType, AcValue::UnitType nUnitType, bool bResetIfIncompatible); Acad::ErrorStatus dwgInFields (AcDbDwgFiler* pFiler); Acad::ErrorStatus dwgOutFields (AcDbDwgFiler* pFiler) const; Acad::ErrorStatus dxfInFields (AcDbDxfFiler* pFiler); Acad::ErrorStatus dxfOutFields (AcDbDxfFiler* pFiler) const; protected: void * mpImpObj; private: friend class AcSystemInternals; // Helper method for the inlines below static bool ACharAllocHelper(const AcString & sValue, ACHAR *& pszValue, bool bRet) { pszValue = nullptr; if (bRet) ::acutNewString(sValue.kwszPtr(), pszValue); return bRet; } }; Acad::ErrorStatus acutNewString(const ACHAR* pInput, ACHAR*& pOutput); // This overload is deprecated. Please use the overload taking AcString & arg instead inline bool AcValue::get(ACHAR *& pszValue) const { AcString sValue; return ACharAllocHelper(sValue, pszValue, this->get(sValue)); } // This overload is deprecated. Please use the overload taking AcString & arg instead inline bool AcValue::format(ACHAR*& pszValue) const { AcString sValue; return ACharAllocHelper(sValue, pszValue, this->format(sValue)); } // This overload is deprecated. Please use the overload taking AcString & arg instead inline bool AcValue::format(const ACHAR* pszFormat, ACHAR*& pszValue) const { AcString sValue; return ACharAllocHelper(sValue, pszValue, this->format(pszFormat, sValue)); } typedef AcArray<AcValue, AcArrayObjectCopyReallocator<AcValue> > AcValueArray;
a6682f72e94f0666bdc06e5373eb2fb3751a6c52
150936abf1a4ba3c9862631bbe45259256027d76
/BDHSGQG - Da Lat 2019/Day 4 - Mr. Thuan/KhanhHoa/BALLOON.cpp
6fe435229e03248eb068aca7060adcedb6e5399e
[]
no_license
btdat2506/IT.CLA.K18---CP---btdat2506
4a6242c637b28b6126e294f5cb1802b7ea4ea850
3adc76eebf81c799e5f82dfb946752cb65866a55
refs/heads/master
2021-07-04T21:48:13.054696
2020-12-01T15:18:46
2020-12-01T15:18:46
205,774,038
1
1
null
2019-09-05T02:13:13
2019-09-02T04:01:48
C++
UTF-8
C++
false
false
1,116
cpp
BALLOON.cpp
#include <bits/stdc++.h> using namespace std; const int N = 205, oo = 1e9; int memo[4][N][N][N]; int col[200]; string s; int calc(int c, int d, int l, int r) { if (l == r) { if (d == 1) return -oo; else return d * d; } if (memo[c][d][l][r] != -1) return memo[c][d][l][r]; if (col[s[l]] == c) { if (l == r - 1) return (d + 1) * (d + 1); return memo[c][d][l][r] = calc(c, d + 1, l + 1, r); } else { int cur = -oo; for (int k = l + 2; k <= r; ++k) cur = max(cur, calc(col[s[l]], 1, l + 1, k) + calc(c, d, k, r)); return memo[c][d][l][r] = cur; } } void solve() { cin >> s; int n = s.size(); for (int i = 0; i < 4; ++i) { for (int j = 1; j <= n; ++j) { for (int l = 1; l <= n; ++l) { for (int r = l; r <= n; ++r) memo[i][j][l][r] = -1; } } } cout << max(0, calc(col[s[0]], 1, 1, s.size())) << '\n'; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); // freopen("BALLOON.INP", "r", stdin); // freopen("BALLOON.OUT", "w", stdout); col['R'] = 0; col['B'] = 1; col['G'] = 2; col['Y'] = 3; int tc; cin >> tc; while (tc--) { solve(); } return 0; }
fb9b82faba080c8f0f0830a1e6712227c049ccb8
0c3eb56b60841be2ac30c8cdeb674b2414afb682
/Codeforces/Nastya Is Playing Computer Games.cpp
658f054c0e92a30781085fac682a421878bd10bf
[]
no_license
Akashkarmokar/Online-Judge-Solution
baf680adcfd1c1da0d8f07f961bf797b309f56d4
63fbe4a1cfdc4530e04bb3339ec722efe1a825cc
refs/heads/master
2021-06-04T12:29:40.575281
2020-04-20T01:24:50
2020-04-20T01:24:50
141,269,981
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
Nastya Is Playing Computer Games.cpp
/* Problem Solved By : Akash Karmokar Department of Computer Science and Technology Metropolitan University,sylhet,Bangladesh. */ #include<bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); #endif int n,k; cin>>n>>k; cout<<3*n+min(n-k,k-1)<<endl; return 0; }
63e3006cb9c4c853fdeb06ff1db24e29ce2687dd
e4d601b0750bd9dcc0e580f1f765f343855e6f7a
/kaldi-wangke/src/chainbin/nnet3-chain-acc-lda-stats.cc
b195f5ba1fbd5c8b93b187dff196f339dd7d00a0
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
PeiwenWu/Adaptation-Interspeech18
01b426cd6d6a2d7a896aacaf4ad01eb3251151f7
576206abf8d1305e4a86891868ad97ddfb2bbf84
refs/heads/master
2021-03-03T04:16:43.146100
2019-11-25T05:44:27
2019-11-25T05:44:27
245,930,967
1
0
MIT
2020-03-09T02:57:58
2020-03-09T02:57:57
null
UTF-8
C++
false
false
7,297
cc
nnet3-chain-acc-lda-stats.cc
// nnet3bin/nnet3-chain-acc-lda-stats.cc // Copyright 2015 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "hmm/transition-model.h" #include "lat/lattice-functions.h" #include "nnet3/nnet-nnet.h" #include "nnet3/nnet-chain-example.h" #include "nnet3/nnet-compute.h" #include "nnet3/nnet-optimize.h" #include "transform/lda-estimate.h" namespace kaldi { namespace nnet3 { class NnetChainLdaStatsAccumulator { public: NnetChainLdaStatsAccumulator(BaseFloat rand_prune, const Nnet &nnet): rand_prune_(rand_prune), nnet_(nnet), compiler_(nnet) { } void AccStats(const NnetChainExample &eg) { ComputationRequest request; bool need_backprop = false, store_stats = false, need_xent = false, need_xent_deriv = false; GetChainComputationRequest(nnet_, eg, need_backprop, store_stats, need_xent, need_xent_deriv, &request); const NnetComputation &computation = *(compiler_.Compile(request)); NnetComputeOptions options; if (GetVerboseLevel() >= 3) options.debug = true; NnetComputer computer(options, computation, nnet_, NULL); computer.AcceptInputs(nnet_, eg.inputs); computer.Run(); const CuMatrixBase<BaseFloat> &nnet_output = computer.GetOutput("output"); AccStatsFromOutput(eg, nnet_output); } void WriteStats(const std::string &stats_wxfilename, bool binary) { if (lda_stats_.TotCount() == 0) { KALDI_ERR << "Accumulated no stats."; } else { WriteKaldiObject(lda_stats_, stats_wxfilename, binary); KALDI_LOG << "Accumulated stats, soft frame count = " << lda_stats_.TotCount() << ". Wrote to " << stats_wxfilename; } } private: void AccStatsFromOutput(const NnetChainExample &eg, const CuMatrixBase<BaseFloat> &nnet_output) { BaseFloat rand_prune = rand_prune_; if (eg.outputs.size() != 1 || eg.outputs[0].name != "output") KALDI_ERR << "Expecting the example to have one output named 'output'."; const chain::Supervision &supervision = eg.outputs[0].supervision; // handling the one-sequence-per-eg case is easier so we just do that. KALDI_ASSERT(supervision.num_sequences == 1 && "This program expects one sequence per eg."); int32 num_frames = supervision.frames_per_sequence, num_pdfs = supervision.label_dim; KALDI_ASSERT(num_frames == nnet_output.NumRows()); const fst::StdVectorFst &fst = supervision.fst; Lattice lat; // convert the FST to a lattice, putting all the weight on // the graph weight. This is to save us having to implement the // forward-backward on FSTs. ConvertFstToLattice(fst, &lat); Posterior post; LatticeForwardBackward(lat, &post); KALDI_ASSERT(post.size() == static_cast<size_t>(num_frames)); // Subtract one, to convert the (pdf-id + 1) which appears in the // supervision FST, to a pdf-id. for (size_t i = 0; i < post.size(); i++) for (size_t j = 0; j < post[i].size(); j++) post[i][j].first--; if (lda_stats_.Dim() == 0) lda_stats_.Init(num_pdfs, nnet_output.NumCols()); for (int32 t = 0; t < num_frames; t++) { // the following, transferring row by row to CPU, would be wasteful if we // actually were using a GPU, but we don't anticipate using a GPU in this // program. CuSubVector<BaseFloat> cu_row(nnet_output, t); // "row" is actually just a redudant copy, since we're likely on CPU, // but we're about to do an outer product, so this doesn't dominate. Vector<BaseFloat> row(cu_row); std::vector<std::pair<int32,BaseFloat> >::const_iterator iter = post[t].begin(), end = post[t].end(); for (; iter != end; ++iter) { int32 pdf = iter->first; BaseFloat weight = iter->second; BaseFloat pruned_weight = RandPrune(weight, rand_prune); if (pruned_weight != 0.0) lda_stats_.Accumulate(row, pdf, pruned_weight); } } } BaseFloat rand_prune_; const Nnet &nnet_; CachingOptimizingCompiler compiler_; LdaEstimate lda_stats_; }; } } int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::nnet3; typedef kaldi::int32 int32; typedef kaldi::int64 int64; const char *usage = "Accumulate statistics in the same format as acc-lda (i.e. stats for\n" "estimation of LDA and similar types of transform), starting from nnet+chain\n" "training examples. This program puts the features through the network,\n" "and the network output will be the features; the supervision in the\n" "training examples is used for the class labels. Used in obtaining\n" "feature transforms that help nnet training work better.\n" "Note: the time boundaries it gets from the chain supervision will be\n" "a little fuzzy (which is not ideal), but it should not matter much in\n" "this situation\n" "\n" "Usage: nnet3-chain-acc-lda-stats [options] <raw-nnet-in> <training-examples-in> <lda-stats-out>\n" "e.g.:\n" "nnet3-chain-acc-lda-stats 0.raw ark:1.cegs 1.acc\n" "See also: nnet-get-feature-transform\n"; bool binary_write = true; BaseFloat rand_prune = 0.0; ParseOptions po(usage); po.Register("binary", &binary_write, "Write output in binary mode"); po.Register("rand-prune", &rand_prune, "Randomized pruning threshold for posteriors"); po.Read(argc, argv); if (po.NumArgs() != 3) { po.PrintUsage(); exit(1); } std::string nnet_rxfilename = po.GetArg(1), examples_rspecifier = po.GetArg(2), lda_accs_wxfilename = po.GetArg(3); // Note: this neural net is probably just splicing the features at this // point. Nnet nnet; ReadKaldiObject(nnet_rxfilename, &nnet); NnetChainLdaStatsAccumulator accumulator(rand_prune, nnet); int64 num_egs = 0; SequentialNnetChainExampleReader example_reader(examples_rspecifier); for (; !example_reader.Done(); example_reader.Next(), num_egs++) accumulator.AccStats(example_reader.Value()); KALDI_LOG << "Processed " << num_egs << " examples."; // the next command will die if we accumulated no stats. accumulator.WriteStats(lda_accs_wxfilename, binary_write); return 0; } catch(const std::exception &e) { std::cerr << e.what() << '\n'; return -1; } }
d070958c712dbae32f4161f61ca02b3c42f50412
e026b9a2c8fca6d20c8e7412df686f02b2445465
/utilities.cpp
67073ed3b10cf1381fb6334cde06db66dc74e400
[]
no_license
williamshiwenhao/jpeg_coder
2016b042760351f971c7442866d13c274842e96c
137327bffbd6ed7af1c2cbfe2eabcd2ab7510e96
refs/heads/master
2020-05-27T08:00:22.447583
2019-06-19T01:21:25
2019-06-19T01:21:25
188,538,485
1
0
null
null
null
null
UTF-8
C++
false
false
2,506
cpp
utilities.cpp
#include "utilities.h" Img<Yuv> ImgRgb2YCbCr(const Img<Rgb> imgrgb) { Img<Yuv> imgy; imgy.w = imgrgb.w; imgy.h = imgrgb.h; imgy.data = new Yuv[imgy.w * imgy.h]; for (int i = 0; i < imgy.w * imgy.h; ++i) { imgy.data[i] = Rgb2YCbCr(imgrgb.data[i]); } return imgy; } Img<Rgb> ImgYCbCr2Rgb(const Img<Yuv> imgy) { Img<Rgb> imgrgb; imgrgb.w = imgy.w; imgrgb.h = imgy.h; imgrgb.data = new Rgb[imgy.w * imgy.h]; for (int i = 0; i < imgy.w * imgy.h; ++i) { imgrgb.data[i] = YCbCr2Rgb(imgy.data[i]); } return imgrgb; } inline Yuv Rgb2YCbCr(const Rgb rgb) { Yuv y; y.y = ColorCast(0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b); y.cb = ColorCast(-0.168 * rgb.r - 0.3313 * rgb.g + 0.5 * rgb.b + 128); y.cr = ColorCast(0.5 * rgb.r - 0.4187 * rgb.g - 0.0813 * rgb.b + 128); return y; } inline Rgb YCbCr2Rgb(const Yuv y) { Rgb r; r.r = ColorCast(y.y + 1.402 * (y.cr - 128)); r.g = ColorCast(y.y - 0.34414 * (y.cb - 128) - 0.71414 * (y.cr - 128)); r.b = ColorCast(y.y + 1.772 * (y.cb - 128)); return r; } template<class T> inline uint8_t ColorCast(const T& dc) { if (dc < 0) return 0; if (dc > 255) return 255; return static_cast<uint8_t>(dc); } static const double dctBase = 128; ImgBlock<double> Img2Block(Img<Yuv> img) { int wb = (img.w >> 3) + ((img.w % 8 > 0) ? 1 : 0); int hb = (img.h >> 3) + ((img.h % 8 > 0) ? 1 : 0); ImgBlock<double> block; block.w = img.w; block.h = img.h; block.wb = wb; block.hb = hb; block.data = std::vector<Block<double>>(wb * hb); for (int i = 0; i < img.w * img.h; ++i) { int x = i % img.w; int y = i / img.w; int xb = x / 8; int yb = y / 8; int blkId = yb * wb + xb; int xIn = x % 8; int yIn = y % 8; int inId = yIn * 8 + xIn; block.data[blkId].y[inId] = img.data[i].y - dctBase; block.data[blkId].u[inId] = img.data[i].cb - dctBase; block.data[blkId].v[inId] = img.data[i].cr - dctBase; } return block; } Img<Yuv> Block2Img(ImgBlock<double>& block) { int &wb = block.wb; int &hb = block.hb; Img<Yuv> img; img.w = block.w; img.h = block.h; img.data = new Yuv[img.w * img.h]; for (int i = 0; i < img.w * img.h; ++i) { int x = i % img.w; int y = i / img.w; int xb = x / 8; int yb = y / 8; int blkId = yb * wb + xb; int xIn = x % 8; int yIn = y % 8; int inId = yIn * 8 + xIn; img.data[i].y = ColorCast(block.data[blkId].y[inId] + dctBase); img.data[i].cb = ColorCast(block.data[blkId].u[inId] + dctBase); img.data[i].cr = ColorCast(block.data[blkId].v[inId] + dctBase); } return img; }
9f1686ebc5c1d9058a20a7946d02d56fd689e761
f3105aa4b43a618f59e662c6907082dd782ea024
/acmicpc.net/1107_리모컨.cpp
9a5d09848736bd00637247b5bc82857ee419c293
[]
no_license
inchoel/DailyCoding
b23b2524d7d5a45ea42c036727661bd759875e39
9d1291586ab8afea9866237002c3c64aedf8e855
refs/heads/master
2021-06-01T16:19:08.999296
2020-08-24T08:22:00
2020-08-24T08:22:13
109,554,116
1
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
1107_리모컨.cpp
#include <cstdio> #include <cstring> #include <bitset> using namespace std; // 100->500000 으로 증가하여 도달하거나, 999900 -> 500000 감소하여 도달하는 경우가 있다. // 그러므로 MAX의 범위는 약 2배로 설정하여, 완전탐색을 하면 된다. #define MAX (500000*2) int main() { int channel; scanf (" %d", &channel); bitset<10> remote; remote.set(); int broken, num; scanf (" %d", &broken); for (int i=0; i<broken; i++) { scanf (" %d", &num); remote.set(num, 0); } int ans = abs (channel - 100); // +, - 로 이동하는 경우 int dist, digitSize; bool valid; for (int i=0; i<MAX; i++) { // 리모컨숫자키와 +, - 로 이동하는 경우 valid = true; num = i; digitSize = 0; while (num) { if (remote.test(num%10) == false) valid = false; num = num / 10; digitSize++; // 99를 100에서 감소하는 경우에 자리수를 체크하기 위해서. } if (i == 0) { if (remote.test(0) == false) valid = false; digitSize++; } if (valid) { dist = abs(channel-i) + digitSize; if (ans > dist) ans = dist; } } printf("%d\n", ans); return 0; }
ec3316218f102f6f23871e51d9dcfc73ba47a175
4dcc7fb1758e91fac49cddbb0e15f354e0a9355e
/LeetCode/cpp/3.longest-substring-without-repeating-characters.cpp
ef77fcfb388abc60b1a7b1e8d2ba48b20ce0896e
[]
no_license
Galibier/AlgoPractise
ac0d6c1b201f637e11bf683fa6197417f52aaf46
e6138de6276e6b999da1ec44ec18effb13801a71
refs/heads/master
2021-07-18T16:11:12.665258
2021-05-18T17:53:57
2021-05-18T17:53:57
249,162,340
0
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
3.longest-substring-without-repeating-characters.cpp
/* * @lc app=leetcode id=3 lang=cpp * * [3] Longest Substring Without Repeating Characters */ class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> dp(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dp[s[i]] > start) start = dp[s[i]]; dp[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen; } };
0caaaf46245f36b55457f2f4189a59a84c4bd699
54b9ee00bcd582d56853ddb90be5cfeb0c29ba29
/src/utils/tera_zk_adapter.cc
9c960eee387b7cf38bca2a73d449d3d9af00233c
[ "BSD-3-Clause" ]
permissive
pengdu/bubblefs
8f4deb8668831496bb0cd8b7d9895900b1442ff1
9b27e191a287b3a1d012adfd3bab6a30629a5f33
refs/heads/master
2020-04-04T19:32:11.311925
2018-05-02T11:20:18
2018-05-02T11:20:18
156,210,664
2
0
null
2018-11-05T11:57:22
2018-11-05T11:57:21
null
UTF-8
C++
false
false
40,162
cc
tera_zk_adapter.cc
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: likang01(com@baidu.com) // tera/src/zk/zk_adapter.cc #include "utils/tera_zk_adapter.h" #include <errno.h> #include <functional> #include "platform/base_error.h" #include "utils/bdcom_this_thread.h" namespace bubblefs { namespace mytera { namespace zk { const int32_t kMaxNodeDataLen = 10240; FILE* ZooKeeperAdapter::lib_log_output_ = NULL; port::Mutex ZooKeeperAdapter::lib_log_mutex_; struct ZooKeeperWatch { pthread_mutex_t mutex; bool watch_value; bool watch_exist; bool watch_child; ZooKeeperWatch() : watch_value(false), watch_exist(false), watch_child(false) { pthread_mutex_init(&mutex, NULL); } ~ZooKeeperWatch() { pthread_mutex_destroy(&mutex); } }; ZooKeeperAdapter::ZooKeeperAdapter() : handle_(NULL), state_(ZS_DISCONN), session_id_(-1), state_cond_(&state_mutex_), session_timeout_(0), session_timer_id_(0), thread_pool_(1) { } ZooKeeperAdapter::~ZooKeeperAdapter() { Finalize(); } bool ZooKeeperAdapter::Init(const std::string& server_list, const std::string& root_path, uint32_t session_timeout, const std::string& id, int* zk_errno) { MutexLock mutex(&state_mutex_); if (NULL != handle_) { SetZkAdapterCode(ZE_INITED, zk_errno); return false; } server_list_ = server_list; root_path_ = root_path; if (*root_path_.end() == '/') { root_path_.resize(root_path_.size() - 1); } id_ = id; handle_ = zookeeper_init((server_list_ + root_path_).c_str(), EventCallBack, session_timeout, NULL, this, 0); if (NULL == handle_) { PRINTF_ERROR("zookeeper_init fail : %s\n", zerror(errno)); SetZkAdapterCode(ZE_SESSION, zk_errno); return false; } while (state_ == ZS_DISCONN || state_ == ZS_CONNECTING) { state_cond_.Wait(); } int code = ZE_OK; // succe if (state_ == ZS_CONNECTED) { pthread_rwlock_init(&watcher_lock_, NULL); pthread_rwlock_init(&locks_lock_, NULL); PRINTF_INFO("zookeeper_init success\n"); SetZkAdapterCode(code, zk_errno); return true; } // fail if (state_ == ZS_TIMEOUT) { code = ZE_SESSION; } else if (state_ == ZS_AUTH) { code = ZE_AUTH; } else { code = ZE_UNKNOWN; } zookeeper_close(handle_); handle_ = NULL; state_ = ZS_DISCONN; PRINTF_ERROR("zookeeper_init fail : %s\n", ZkErrnoToString(code).c_str()); SetZkAdapterCode(code, zk_errno); return false; } void ZooKeeperAdapter::Finalize() { zhandle_t* old_handle; { MutexLock mutex(&state_mutex_); if (NULL == handle_) { return; } old_handle = handle_; handle_ = NULL; } int ret = zookeeper_close(old_handle); if (ret == ZOK) { PRINTF_INFO("zookeeper_close success\n"); } else { PRINTF_ERROR("zookeeper_close fail : %s\n", zerror(ret)); } { MutexLock mutex(&state_mutex_); pthread_rwlock_destroy(&locks_lock_); pthread_rwlock_destroy(&watcher_lock_); locks_.clear(); watchers_.clear(); state_ = ZS_DISCONN; thread_pool_.CancelTask(session_timer_id_); session_timer_id_ = 0; PRINTF_INFO("zookeeper_session_timeout_timer has gone, safe to finalize.\n"); } } bool ZooKeeperAdapter::CreatePersistentNode(const std::string& path, const std::string& value, int* zk_errno) { MutexLock mutex(&state_mutex_); return Create(path, value, 0, NULL, zk_errno); } bool ZooKeeperAdapter::CreateEphemeralNode(const std::string& path, const std::string& value, int* zk_errno) { MutexLock mutex(&state_mutex_); return Create(path, value, ZOO_EPHEMERAL, NULL, zk_errno); } bool ZooKeeperAdapter::CreateSequentialEphemeralNode(const std::string& path, const std::string& value, std::string* ret_path, int* zk_errno) { MutexLock mutex(&state_mutex_); return Create(path, value, ZOO_EPHEMERAL | ZOO_SEQUENCE, ret_path, zk_errno); } bool ZooKeeperAdapter::Create(const std::string& path, const std::string& value, int flag, std::string* ret_path, int* zk_errno) { state_mutex_.AssertHeld(); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int value_len = value.size(); if (value_len == 0) { value_len = -1; } size_t root_path_len = root_path_.size(); size_t path_len = path.size(); char * ret_path_buf = NULL; size_t ret_path_size = 0; if (ret_path != NULL) { ret_path_size = root_path_len + path_len + 11; ret_path_buf = new char[ret_path_size]; } int ret = zoo_create(handle_, path.c_str(), value.c_str(), value_len, &ZOO_OPEN_ACL_UNSAFE, flag, ret_path_buf, ret_path_size); if (ZOK == ret) { if (NULL != ret_path) { size_t ret_path_len = strlen(ret_path_buf); if (((flag & ZOO_SEQUENCE) == 1 && ret_path_len == root_path_len + path_len + 10) || ((flag & ZOO_SEQUENCE) == 0 && ret_path_len == root_path_len + path_len)) { // compatible to zk 3.3.x *ret_path = ret_path_buf + root_path_len; } else { *ret_path = ret_path_buf; } } PRINTF_INFO("zoo_create success\n"); } else { PRINTF_WARN("zoo_create fail : %s\n", zerror(ret)); } if (NULL != ret_path_buf) { delete[] ret_path_buf; } switch (ret) { case ZOK: SetZkAdapterCode(ZE_OK, zk_errno); return true; case ZNONODE: SetZkAdapterCode(ZE_NO_PARENT, zk_errno); return false; case ZNODEEXISTS: SetZkAdapterCode(ZE_EXIST, zk_errno); return false; case ZNOAUTH: SetZkAdapterCode(ZE_AUTH, zk_errno); return false; case ZNOCHILDRENFOREPHEMERALS: SetZkAdapterCode(ZE_ENTITY_PARENT, zk_errno); return false; case ZBADARGUMENTS: SetZkAdapterCode(ZE_ARG, zk_errno); return false; case ZINVALIDSTATE: SetZkAdapterCode(ZE_SESSION, zk_errno); return false; case ZMARSHALLINGERROR: SetZkAdapterCode(ZE_SYSTEM, zk_errno); return false; default: SetZkAdapterCode(ZE_UNKNOWN, zk_errno); return false; } } bool ZooKeeperAdapter::DeleteNode(const std::string& path, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = zoo_delete(handle_, path.c_str(), -1); if (ZOK == ret) { PRINTF_INFO("zoo_delete success\n"); } else { PRINTF_WARN("zoo_delete fail : %s\n", zerror(ret)); } switch (ret) { case ZOK: SetZkAdapterCode(ZE_OK, zk_errno); return true; case ZNONODE: SetZkAdapterCode(ZE_NOT_EXIST, zk_errno); return false; case ZNOAUTH: SetZkAdapterCode(ZE_AUTH, zk_errno); return false; case ZBADVERSION: // impossible SetZkAdapterCode(ZE_UNKNOWN, zk_errno); return false; case ZNOTEMPTY: SetZkAdapterCode(ZE_HAS_CHILD, zk_errno); return false; case ZBADARGUMENTS: SetZkAdapterCode(ZE_ARG, zk_errno); return false; case ZINVALIDSTATE: SetZkAdapterCode(ZE_SESSION, zk_errno); return false; case ZMARSHALLINGERROR: SetZkAdapterCode(ZE_SYSTEM, zk_errno); return false; default: SetZkAdapterCode(ZE_UNKNOWN, zk_errno); return false; } } bool ZooKeeperAdapter::ReadNode(const std::string& path, std::string* value, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = GetWrapper(path, false, value); SetZkAdapterCode(ret, zk_errno); return (ZE_OK == ret); } bool ZooKeeperAdapter::ReadAndWatchNode(const std::string& path, std::string* value, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } pthread_rwlock_wrlock(&watcher_lock_); std::pair<WatcherMap::iterator, bool> insert_ret = watchers_.insert( std::pair<std::string, ZooKeeperWatch*>(path, NULL)); struct ZooKeeperWatch*& watch = insert_ret.first->second; if (NULL == watch) { watch = new ZooKeeperWatch; } pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); bool is_watch = false; if (!watch->watch_value) { is_watch = true; } else { pthread_mutex_unlock(&watch->mutex); PRINTF_INFO("watch has been set before\n"); } int ret = GetWrapper(path, is_watch, value); if (ZE_OK == ret) { if (is_watch) { watch->watch_value = true; pthread_mutex_unlock(&watch->mutex); } SetZkAdapterCode(ZE_OK, zk_errno); return true; } else { if (is_watch) { pthread_mutex_unlock(&watch->mutex); } SetZkAdapterCode(ret, zk_errno); return false; } } bool ZooKeeperAdapter::ListChildren(const std::string& path, std::vector<std::string>* child_list, std::vector<std::string>* value_list, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = GetChildrenWrapper(path, false, child_list, value_list); SetZkAdapterCode(ret, zk_errno); return (ZE_OK == ret); } bool ZooKeeperAdapter::ListAndWatchChildren(const std::string& path, std::vector<std::string>* child_list, std::vector<std::string>* value_list, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } pthread_rwlock_wrlock(&watcher_lock_); std::pair<WatcherMap::iterator, bool> insert_ret = watchers_.insert( std::pair<std::string, ZooKeeperWatch*>(path, NULL)); struct ZooKeeperWatch*& watch = insert_ret.first->second; if (NULL == watch) { watch = new ZooKeeperWatch; } pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); bool is_watch = false; if (!watch->watch_child) { is_watch = true; } else { pthread_mutex_unlock(&watch->mutex); PRINTF_INFO("is_watch has been set before\n"); } int ret = GetChildrenWrapper(path, is_watch, child_list, value_list); if (ZE_OK == ret) { if (is_watch) { watch->watch_child = true; pthread_mutex_unlock(&watch->mutex); } SetZkAdapterCode(ret, zk_errno); return true; } else { if (is_watch) { pthread_mutex_unlock(&watch->mutex); } SetZkAdapterCode(ret, zk_errno); return false; } } bool ZooKeeperAdapter::CheckExist(const std::string&path, bool* is_exist, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = ExistsWrapper(path, false, is_exist); SetZkAdapterCode(ret, zk_errno); return (ZE_OK == ret); } bool ZooKeeperAdapter::CheckAndWatchExist(const std::string& path, bool* is_exist, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } bool is_watch = false; pthread_rwlock_wrlock(&watcher_lock_); std::pair<WatcherMap::iterator, bool> insert_ret = watchers_.insert( std::pair<std::string, ZooKeeperWatch*>(path, NULL)); struct ZooKeeperWatch*& watch = insert_ret.first->second; if (NULL == watch) { watch = new ZooKeeperWatch; } pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); if (!watch->watch_exist) { is_watch = true; } else { pthread_mutex_unlock(&watch->mutex); PRINTF_INFO("is_watch has been set before\n"); } int ret = ExistsWrapper(path, is_watch, is_exist); if (ZE_OK == ret) { if (is_watch) { watch->watch_exist = true; pthread_mutex_unlock(&watch->mutex); } } else { if (is_watch) { pthread_mutex_unlock(&watch->mutex); } } SetZkAdapterCode(ret, zk_errno); return (ZE_OK == ret); } bool ZooKeeperAdapter::CheckAndWatchExistForLock(const std::string& path, bool* is_exist, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = ExistsWrapperForLock(path, is_exist); SetZkAdapterCode(ret, zk_errno); return (ZE_OK == ret); } bool ZooKeeperAdapter::WriteNode(const std::string& path, const std::string& value, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } int ret = zoo_set(handle_, path.c_str(), value.c_str(), value.size(), -1); if (ZOK == ret) { PRINTF_INFO("zoo_set success\n"); } else { PRINTF_WARN("zoo_set fail : %s\n", zerror(ret)); } switch (ret) { case ZOK: SetZkAdapterCode(ZE_OK, zk_errno); return true; case ZNONODE: SetZkAdapterCode(ZE_NOT_EXIST, zk_errno); return false; case ZNOAUTH: SetZkAdapterCode(ZE_AUTH, zk_errno); return false; case ZBADVERSION: // impossible SetZkAdapterCode(ZE_UNKNOWN, zk_errno); return false; case ZBADARGUMENTS: SetZkAdapterCode(ZE_ARG, zk_errno); return false; case ZINVALIDSTATE: SetZkAdapterCode(ZE_SESSION, zk_errno); return false; case ZMARSHALLINGERROR: SetZkAdapterCode(ZE_SYSTEM, zk_errno); return false; default: SetZkAdapterCode(ZE_UNKNOWN, zk_errno); return false; } } void ZooKeeperAdapter::EventCallBack(zhandle_t * zh, int type, int state, const char * node_path, void * watch_ctx) { PRINTF_INFO("recv event: type=%s, state=%s, path=%s\n", ZooTypeToString(type).c_str(), ZooStateToString(state).c_str(), node_path); if (NULL == watch_ctx) { return; } ZooKeeperAdapter* zk_adapter = (ZooKeeperAdapter*)watch_ctx; MutexLock mutex(&zk_adapter->state_mutex_); if (zh != zk_adapter->handle_) { PRINTF_WARN("zhandle not match\n"); return; } // handle_ is guaranteed (by zk lib) to be valid within callback func. // no need to check it. if (ZOO_SESSION_EVENT == type) { zk_adapter->SessionEventCallBack(state); return; } if (NULL == node_path) { PRINTF_WARN("path is missing\n"); return; } std::string path = node_path; if (!ZooKeeperUtil::IsValidPath(path)) { PRINTF_WARN("path is invalid\n"); return; } if (ZOO_CREATED_EVENT == type) { zk_adapter->CreateEventCallBack(path); } else if (ZOO_DELETED_EVENT == type) { zk_adapter->DeleteEventCallBack(path); } else if (ZOO_CHANGED_EVENT == type) { zk_adapter->ChangeEventCallBack(path); } else if (ZOO_CHILD_EVENT == type) { zk_adapter->ChildEventCallBack(path); } else if (ZOO_NOTWATCHING_EVENT == type) { zk_adapter->WatchLostEventCallBack(state, path); } else { PRINTF_WARN("unknown event type: %d\n", type); } } void ZooKeeperAdapter::CreateEventCallBack(std::string path) { PRINTF_INFO("CreateEventCallBack: path=[%s]\n", path.c_str()); pthread_rwlock_wrlock(&watcher_lock_); WatcherMap::iterator itor = watchers_.find(path); if (itor == watchers_.end()) { pthread_rwlock_unlock(&watcher_lock_); PRINTF_INFO("watch not match\n"); return; } ZooKeeperWatch * watch = itor->second; pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); if (!watch->watch_exist) { pthread_mutex_unlock(&watch->mutex); PRINTF_WARN("watch not match\n"); return; } bool is_exist; int ret = ExistsWrapper(path, true, &is_exist); if (ZE_OK == ret) { pthread_mutex_unlock(&watch->mutex); state_mutex_.Unlock(); OnNodeCreated(path); if (!is_exist) { OnNodeDeleted(path); } state_mutex_.Lock(); } else { watch->watch_exist = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnWatchFailed(path, ZT_WATCH_EXIST, ret); state_mutex_.Lock(); } } void ZooKeeperAdapter::DeleteEventCallBack(std::string path) { PRINTF_INFO("DeleteEventCallBack: path=[%s]\n", path.c_str()); pthread_rwlock_wrlock(&watcher_lock_); WatcherMap::iterator itor = watchers_.find(path); if (itor == watchers_.end()) { pthread_rwlock_unlock(&watcher_lock_); PRINTF_INFO("watch not match\n"); return; } ZooKeeperWatch * watch = itor->second; pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); if (!watch->watch_exist && !watch->watch_value && !watch->watch_child) { pthread_mutex_unlock(&watch->mutex); PRINTF_WARN("watch not match\n"); return; } bool is_watch_exist = watch->watch_exist; bool is_exist; int ret = ExistsWrapper(path, true, &is_exist); if (ZE_OK == ret) { watch->watch_value = false; watch->watch_child = false; pthread_mutex_unlock(&watch->mutex); if (!is_watch_exist) { TryCleanWatch(path); } state_mutex_.Unlock(); OnNodeDeleted(path); if (is_exist && is_watch_exist) { OnNodeCreated(path); } state_mutex_.Lock(); } else { watch->watch_exist = false; watch->watch_value = false; watch->watch_child = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnNodeDeleted(path); if (is_watch_exist) { OnWatchFailed(path, ZT_WATCH_EXIST, ret); } state_mutex_.Lock(); } } void ZooKeeperAdapter::ChangeEventCallBack(std::string path) { PRINTF_INFO("ChangeEventCallBack: path=[%s]\n", path.c_str()); pthread_rwlock_wrlock(&watcher_lock_); WatcherMap::iterator itor = watchers_.find(path); if (itor == watchers_.end()) { pthread_rwlock_unlock(&watcher_lock_); PRINTF_INFO("watch not match\n"); return; } ZooKeeperWatch * watch = itor->second; pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); if (!watch->watch_value) { pthread_mutex_unlock(&watch->mutex); PRINTF_WARN("watch not match\n"); return; } std::string value; int ret = GetWrapper(path, true, &value); if (ZE_OK == ret) { pthread_mutex_unlock(&watch->mutex); state_mutex_.Unlock(); OnNodeValueChanged(path, value); state_mutex_.Lock(); } else if (ZE_NOT_EXIST == ret) { watch->watch_value = false; watch->watch_child = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnNodeDeleted(path); state_mutex_.Lock(); } else { watch->watch_value = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnWatchFailed(path, ZT_WATCH_VALUE, ret); state_mutex_.Lock(); } } void ZooKeeperAdapter::ChildEventCallBack(std::string path) { PRINTF_INFO("ChildEventCallBack: path=[%s]\n", path.c_str()); pthread_rwlock_wrlock(&watcher_lock_); WatcherMap::iterator itor = watchers_.find(path); if (itor == watchers_.end()) { pthread_rwlock_unlock(&watcher_lock_); PRINTF_INFO("watch not match\n"); return; } ZooKeeperWatch * watch = itor->second; pthread_mutex_lock(&watch->mutex); pthread_rwlock_unlock(&watcher_lock_); if (!watch->watch_child) { pthread_mutex_unlock(&watch->mutex); PRINTF_WARN("watch not match\n"); return; } std::vector<std::string> child_list; std::vector<std::string> value_list; int ret = GetChildrenWrapper(path, true, &child_list, &value_list); if (ZE_OK == ret) { pthread_mutex_unlock(&watch->mutex); state_mutex_.Unlock(); OnChildrenChanged(path, child_list, value_list); state_mutex_.Lock(); } else if (ZE_NOT_EXIST == ret) { watch->watch_child = false; watch->watch_value = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnNodeDeleted(path); state_mutex_.Lock(); } else { watch->watch_child = false; pthread_mutex_unlock(&watch->mutex); TryCleanWatch(path); state_mutex_.Unlock(); OnWatchFailed(path, ZT_WATCH_CHILD, ret); state_mutex_.Lock(); } } void ZooKeeperAdapter::SessionTimeoutWrapper() { this->OnSessionTimeout(); MutexLock mutex(&state_mutex_); session_timer_id_ = 0; } void ZooKeeperAdapter::SessionEventCallBack(int state) { if (ZOO_CONNECTED_STATE == state) { if (ZS_CONNECTING == state_) { if (!thread_pool_.CancelTask(session_timer_id_)) { PRINTF_WARN("session timeout timer is triggered\n"); return; } session_timer_id_ = 0; } const clientid_t *cid = zoo_client_id(handle_); if (cid == NULL) { PRINTF_WARN("zoo_client_id fail\n"); return; } session_id_ = cid->client_id; state_ = ZS_CONNECTED; state_cond_.Signal(); session_timeout_ = zoo_recv_timeout(handle_); PRINTF_INFO("connected to zk server, session timeout: %d ms\n", session_timeout_); } else if (ZOO_CONNECTING_STATE == state || ZOO_ASSOCIATING_STATE == state) { if (ZS_CONNECTED == state_) { PRINTF_INFO("disconnect from zk server, enable timer: %d ms\n", session_timeout_); mybdcom::ThreadPool::Task task = std::bind(&ZooKeeperAdapter::SessionTimeoutWrapper, this); session_timer_id_ = thread_pool_.DelayTask(session_timeout_, task); } session_id_ = -1; state_ = ZS_CONNECTING; state_cond_.Signal(); } else if (ZOO_AUTH_FAILED_STATE == state) { session_id_ = -1; state_ = ZS_AUTH; state_cond_.Signal(); } else if (ZOO_EXPIRED_SESSION_STATE == state) { session_id_ = -1; state_ = ZS_TIMEOUT; state_cond_.Signal(); state_mutex_.Unlock(); OnSessionTimeout(); state_mutex_.Lock(); } } void ZooKeeperAdapter::WatchLostEventCallBack(int state, std::string path) { // shit... } bool ZooKeeperAdapter::SyncLock(const std::string& path, int* zk_errno, int32_t timeout) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } bool ret_val; pthread_rwlock_wrlock(&locks_lock_); std::pair<LockMap::iterator, bool> insert_ret = locks_.insert( std::pair<std::string, ZooKeeperLock*>(path, NULL)); if (!insert_ret.second) { ZooKeeperLock * lock = insert_ret.first->second; if (lock == NULL || !lock->IsAcquired()) { PRINTF_INFO("lock exists but is not acquired\n"); } else { PRINTF_INFO("lock has been acquired\n"); } pthread_rwlock_unlock(&locks_lock_); SetZkAdapterCode(ZE_LOCK_EXIST, zk_errno); return false; } pthread_rwlock_unlock(&locks_lock_); timeval start_time, end_time; gettimeofday(&start_time, NULL); end_time.tv_sec = start_time.tv_sec + timeout; end_time.tv_usec = start_time.tv_usec; LockCompletion * callback_param = new LockCompletion(); ZooKeeperLock * lock = new ZooKeeperLock(this, path, SyncLockCallback, callback_param); callback_param->SetLock(lock); state_mutex_.Unlock(); if (!lock->BeginLock(zk_errno)) { state_mutex_.Lock(); delete callback_param; delete lock; pthread_rwlock_wrlock(&locks_lock_); locks_.erase(path); pthread_rwlock_unlock(&locks_lock_); return false; } state_mutex_.Lock(); pthread_rwlock_wrlock(&locks_lock_); locks_[path] = lock; pthread_rwlock_unlock(&locks_lock_); timeval now_time; gettimeofday(&now_time, NULL); if (timeout > 0 && (now_time.tv_sec > end_time.tv_sec || (now_time.tv_sec == end_time.tv_sec && now_time.tv_usec > end_time.tv_usec))) { if (lock->IsAcquired()) { SetZkAdapterCode(ZE_OK, zk_errno); return true; } else { SetZkAdapterCode(ZE_LOCK_TIMEOUT, zk_errno); return false; } } state_mutex_.Unlock(); if (timeout > 0) { ret_val = callback_param->Wait(zk_errno, &end_time); } else { ret_val = callback_param->Wait(zk_errno); } state_mutex_.Lock(); return ret_val; } bool ZooKeeperAdapter::AsyncLock(const std::string& path, LOCK_CALLBACK callback_func, void * callback_param, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } pthread_rwlock_wrlock(&locks_lock_); std::pair<LockMap::iterator, bool> insert_ret = locks_.insert( std::pair<std::string, ZooKeeperLock*>(path, NULL)); if (!insert_ret.second) { ZooKeeperLock * lock = insert_ret.first->second; if (lock == NULL || !lock->IsAcquired()) { PRINTF_INFO("lock exists but is not acquired\n"); } else { PRINTF_INFO("lock has been acquired\n"); } pthread_rwlock_unlock(&locks_lock_); SetZkAdapterCode(ZE_LOCK_EXIST, zk_errno); return false; } pthread_rwlock_unlock(&locks_lock_); ZooKeeperLock * lock = new ZooKeeperLock(this, path, callback_func, callback_param); state_mutex_.Unlock(); if (!lock->BeginLock(zk_errno)) { state_mutex_.Lock(); pthread_rwlock_wrlock(&locks_lock_); locks_.erase(path); pthread_rwlock_unlock(&locks_lock_); delete lock; return false; } else { state_mutex_.Lock(); pthread_rwlock_wrlock(&locks_lock_); locks_[path] = lock; pthread_rwlock_unlock(&locks_lock_); return true; } } void ZooKeeperAdapter::SyncLockCallback(const std::string& path, int err, void * param) { LockCompletion * comp = (LockCompletion *) param; comp->Signal(err); } bool ZooKeeperAdapter::CancelLock(const std::string& path, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } pthread_rwlock_wrlock(&locks_lock_); LockMap::iterator itor = locks_.find(path); if (itor == locks_.end()) { pthread_rwlock_unlock(&locks_lock_); PRINTF_WARN("lock not exist\n"); SetZkAdapterCode(ZE_LOCK_NOT_EXIST, zk_errno); return false; } ZooKeeperLock * lock = itor->second; state_mutex_.Unlock(); if (!lock->CancelLock(zk_errno)) { state_mutex_.Lock(); delete lock; locks_.erase(itor); pthread_rwlock_unlock(&locks_lock_); return false; } else { state_mutex_.Lock(); pthread_rwlock_unlock(&locks_lock_); return true; } } bool ZooKeeperAdapter::Unlock(const std::string& path, int* zk_errno) { MutexLock mutex(&state_mutex_); if (!ZooKeeperUtil::IsValidPath(path)) { SetZkAdapterCode(ZE_ARG, zk_errno); return false; } if (NULL == handle_) { SetZkAdapterCode(ZE_NOT_INIT, zk_errno); return false; } pthread_rwlock_wrlock(&locks_lock_); LockMap::iterator itor = locks_.find(path); if (itor == locks_.end() || itor->second == NULL) { pthread_rwlock_unlock(&locks_lock_); PRINTF_WARN("lock not exist\n"); SetZkAdapterCode(ZE_LOCK_NOT_EXIST, zk_errno); return false; } ZooKeeperLock * lock = itor->second; state_mutex_.Unlock(); if (lock->Unlock(zk_errno)) { state_mutex_.Lock(); delete lock; locks_.erase(itor); pthread_rwlock_unlock(&locks_lock_); return true; } else { state_mutex_.Lock(); pthread_rwlock_unlock(&locks_lock_); return false; } } void ZooKeeperAdapter::GetId(std::string* id) { MutexLock mutex(&state_mutex_); *id = id_; } void ZooKeeperAdapter::TryCleanWatch(const std::string& path) { state_mutex_.AssertHeld(); pthread_rwlock_wrlock(&watcher_lock_); WatcherMap::iterator itor = watchers_.find(path); if (itor == watchers_.end()) { pthread_rwlock_unlock(&watcher_lock_); return; } ZooKeeperWatch * watch = itor->second; pthread_mutex_lock(&watch->mutex); if (!watch->watch_child && !watch->watch_exist && !watch->watch_value) { pthread_mutex_unlock(&watch->mutex); delete watch; watchers_.erase(itor); } else { pthread_mutex_unlock(&watch->mutex); } pthread_rwlock_unlock(&watcher_lock_); } void ZooKeeperAdapter::LockEventCallBack(zhandle_t * zh, int type, int state, const char * node_path, void * watch_ctx) { PRINTF_INFO("recv lock event: type=%s, state=%s, path=[%s]\n", ZooTypeToString(type).c_str(), ZooStateToString(state).c_str(), node_path); if (ZOO_DELETED_EVENT != type) { PRINTF_WARN("only allow DELETE_EVENT for lock\n"); return; } if (NULL == watch_ctx) { return; } ZooKeeperAdapter* zk_adapter = (ZooKeeperAdapter*)watch_ctx; { MutexLock mutex(&zk_adapter->state_mutex_); if (zh != zk_adapter->handle_) { PRINTF_WARN("zhandle not match\n"); return; } } if (NULL == node_path) { PRINTF_WARN("path is missing\n"); return; } std::string path = node_path; if (!ZooKeeperUtil::IsValidPath(path)) { PRINTF_WARN("path is invalid\n"); return; } zk_adapter->LockEventCallBack(path); } void ZooKeeperAdapter::LockEventCallBack(std::string path) { PRINTF_INFO("LockEventCallBack: path=[%s]\n", path.c_str()); MutexLock mutex(&state_mutex_); std::string lock_path; ZooKeeperUtil::GetParentPath(path, &lock_path); pthread_rwlock_wrlock(&locks_lock_); LockMap::iterator itor = locks_.find(lock_path); if (itor == locks_.end()) { pthread_rwlock_unlock(&locks_lock_); PRINTF_WARN("lock [%s] not exist\n", lock_path.c_str()); return; } ZooKeeperLock* lock = itor->second; if (lock == NULL) { pthread_rwlock_unlock(&locks_lock_); return; } state_mutex_.Unlock(); lock->OnWatchNodeDeleted(path); state_mutex_.Lock(); pthread_rwlock_unlock(&locks_lock_); } bool ZooKeeperAdapter::GetSessionId(int64_t* session_id, int* zk_errno) { MutexLock mutex(&state_mutex_); if (ZS_CONNECTED == state_) { *session_id = session_id_; SetZkAdapterCode(ZE_OK, zk_errno); return true; } SetZkAdapterCode(ZE_SESSION, zk_errno); return false; } bool ZooKeeperAdapter::SetLibraryLogOutput(const std::string& file) { MutexLock mutex(&lib_log_mutex_); FILE* new_log = fopen(file.c_str(), "a"); if (NULL == new_log) { PRINTF_WARN("fail to open file [%s]:%s\n", file.c_str(), strerror(errno)); return false; } zoo_set_log_stream(new_log); if (NULL != lib_log_output_) { fclose(lib_log_output_); } lib_log_output_ = new_log; return true; } int ZooKeeperAdapter::ExistsWrapper(const std::string& path, bool is_watch, bool* is_exist) { state_mutex_.AssertHeld(); struct Stat stat; int ret = zoo_exists(handle_, path.c_str(), is_watch, &stat); if (ZOK == ret) { *is_exist = true; PRINTF_INFO("zoo_exists success\n"); } else if (ZNONODE == ret) { *is_exist = false; PRINTF_INFO("zoo_exists success\n"); } else { PRINTF_WARN("zoo_exists fail: %s\n", zerror(ret)); } switch (ret) { case ZOK: case ZNONODE: return ZE_OK; case ZNOAUTH: return ZE_AUTH; case ZBADARGUMENTS: return ZE_ARG; case ZINVALIDSTATE: return ZE_SESSION; case ZMARSHALLINGERROR: return ZE_SYSTEM; default: return ZE_UNKNOWN; } } int ZooKeeperAdapter::ExistsWrapperForLock(const std::string& path, bool* is_exist) { state_mutex_.AssertHeld(); struct Stat stat; int ret = zoo_wexists(handle_, path.c_str(), LockEventCallBack, this, &stat); if (ZOK == ret) { *is_exist = true; PRINTF_INFO("zoo_exists success\n"); } else if (ZNONODE == ret) { *is_exist = false; PRINTF_INFO("zoo_exists success\n"); } else { PRINTF_WARN("zoo_exists fail: %s\n", zerror(ret)); } switch (ret) { case ZOK: case ZNONODE: return ZE_OK; case ZNOAUTH: return ZE_AUTH; case ZBADARGUMENTS: return ZE_ARG; case ZINVALIDSTATE: return ZE_SESSION; case ZMARSHALLINGERROR: return ZE_SYSTEM; default: return ZE_UNKNOWN; } } int ZooKeeperAdapter::GetWrapper(const std::string& path, bool is_watch, std::string* value) { state_mutex_.AssertHeld(); char* buffer = new char[kMaxNodeDataLen]; int buffer_len = kMaxNodeDataLen; int ret = zoo_get(handle_, path.c_str(), is_watch, buffer, &buffer_len, NULL); if (ZOK == ret) { if (buffer_len < 0) { buffer_len = 0; } else if (buffer_len >= kMaxNodeDataLen) { buffer_len = kMaxNodeDataLen - 1; } buffer[buffer_len] = '\0'; *value = buffer; PRINTF_INFO("zoo_get success\n"); } else { PRINTF_WARN("zoo_get fail: %s\n", zerror(ret)); } delete[] buffer; switch (ret) { case ZOK: return ZE_OK; case ZNONODE: return ZE_NOT_EXIST; case ZNOAUTH: return ZE_AUTH; case ZBADARGUMENTS: return ZE_ARG; case ZINVALIDSTATE: return ZE_SESSION; case ZMARSHALLINGERROR: return ZE_SYSTEM; default: return ZE_UNKNOWN; } } int ZooKeeperAdapter::GetChildrenWrapper(const std::string& path, bool is_watch, std::vector<std::string>* child_list, std::vector<std::string>* value_list) { state_mutex_.AssertHeld(); struct String_vector str_vec; allocate_String_vector(&str_vec, 0); int ret = zoo_get_children(handle_, path.c_str(), is_watch, &str_vec); if (ZOK == ret) { child_list->clear(); value_list->clear(); for (int i = 0; i < str_vec.count; i++) { child_list->push_back(str_vec.data[i]); std::string child_path = path + '/' + str_vec.data[i]; std::string value; int ret2 = GetWrapper(child_path, false, &value); if (ZE_OK != ret2) { value = ""; PRINTF_WARN("read node fail: %d\n", ret2); } value_list->push_back(value); } PRINTF_INFO("zoo_get_children success\n"); } else { PRINTF_WARN("zoo_get_children fail: %s\n", zerror(ret)); } deallocate_String_vector(&str_vec); switch (ret) { case ZOK: return ZE_OK; case ZNONODE: return ZE_NOT_EXIST; case ZNOAUTH: return ZE_AUTH; case ZBADARGUMENTS: return ZE_ARG; case ZINVALIDSTATE: return ZE_SESSION; case ZMARSHALLINGERROR: return ZE_SYSTEM; default: return ZE_UNKNOWN; } } } // namespace zk } // namespace mytera } // namespace bubblefs
b7fe308e4ba1e496d4c17c7020a30be72bcb55cd
0ffe7f555733c8a8ba997518c36771e92c4caa3a
/C++/upload_file.cpp
7c1d0e836cdcb46f493a287796897296b2d18790
[]
no_license
9176324/authentication-samples
67b94bf676bc942d2e88910747a16dd1043e2ad3
bcfdf621bbf716b7a0ce8b561d374c7b6ebc0443
refs/heads/master
2020-07-04T03:32:41.705599
2016-03-28T12:20:13
2016-03-28T12:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,223
cpp
upload_file.cpp
#include "cpprest/http_client.h" #include <iterator> #include <fstream> #include <iostream> #include <string> #include "stdlib.h" using std::cerr; using std::copy; using std::endl; using std::ifstream; using std::ios; using std::istreambuf_iterator; using std::string; using std::vector; using utility::string_t; using web::http::client::http_client; using web::http::http_request; using web::http::http_response; using web::http::methods; using web::http::uri_builder; namespace { const string CRLF = "\r\n"; const string BOUNDARY = "xxxtXGddonlfOoyaEOLpXFia8LqV10PqzCTVJ8Fh5igxxx"; const string FILENAME_MARK = "<<<FILENAME>>>"; const string PREFIX = CRLF + "--" + BOUNDARY + CRLF + "Content-Disposition: form-data;" + " name=\"file\"; filename=\"" + FILENAME_MARK + "\"" + CRLF + "Content-Type: octet/stream" + CRLF + CRLF; const string SUFFIX = CRLF + CRLF + "--" + BOUNDARY + CRLF + "Content-Disposition: form-data; name=\"unzip\"" + CRLF + CRLF + "false" + CRLF + "--" + BOUNDARY + CRLF + "Content-Disposition: form-data; name=\"public\"" + CRLF + CRLF + "true" + CRLF + "--" + BOUNDARY + "--" + CRLF; }; void upload_file(const string_t& access_token, const string_t& path) { ucerr << "Using file: " << path << endl; ucerr << "Using token: Bearer " << access_token << endl; // Manually build up an HTTP request with header and request URI. uri_builder builder; builder .set_scheme(U("https")) .set_host(U("sandbox.spark.autodesk.com")); http_request request(methods::POST); request.set_request_uri(U("api/v1/files/upload")); //Setting access token request.headers().add(U("Authorization"), U("Bearer ") + access_token); request.headers().set_content_type(utility::conversions::to_string_t("multipart/form-data; boundary=" + BOUNDARY)); //Parsing filename auto string_path = utility::conversions::to_utf8string(path); string basename = string_path.substr(string_path.find_last_of("/\\") + 1); ifstream inputFile(path, ios::binary); string modifiedPrefix = PREFIX; //Setting the actual filename modifiedPrefix.replace(modifiedPrefix.find(FILENAME_MARK), FILENAME_MARK.size(), basename); vector<unsigned char> body; copy(modifiedPrefix.begin(), modifiedPrefix.end(), back_inserter(body)); copy(istreambuf_iterator<char>(inputFile), istreambuf_iterator<char>(), back_inserter(body)); copy(SUFFIX.begin(), SUFFIX.end(), back_inserter(body)); request.set_body(body); // Create http_client to send the request. http_client client(builder.to_uri()); // This example uses the task::wait method to ensure that async operations complete before the app exits. // In most apps, you typically don't wait for async operations to complete. client.request(request).then([=](http_response response) { ucerr << "Response:\n" << response.to_string() << endl; }).wait(); } #ifdef _WIN32 int wmain(int argc, wchar_t *argv[]) #else int main(int argc, char *argv[]) #endif { if (argc < 3) { cerr << "Not enough arguments. Usage: " << argv[0] << "<Access-Token> <filename(full file path with file extension)>" << endl; exit(1); } upload_file(argv[1], argv[2]); return 0; }
54e256386020c4244f9bf886b055a3e721835185
4520caea6e0871433a20612103ca61de04d76bd8
/src/simplifier.cpp
bf6ff487d1fecd5a355aa3c8de5086661cd1bbce
[ "BSL-1.0", "MIT" ]
permissive
JervenBolleman/vg
094e5c7181b4f3beea7abcd440843ed3f2b78e28
054473dfb31b75e67e0ab544e1b7c02b5571acca
refs/heads/master
2020-04-05T22:50:12.773343
2017-09-15T00:54:56
2017-09-15T00:54:56
42,646,990
2
0
null
2015-09-17T09:19:54
2015-09-17T09:19:54
null
UTF-8
C++
false
false
34,393
cpp
simplifier.cpp
#include "simplifier.hpp" namespace vg { using namespace std; Simplifier::Simplifier(VG& graph) : Progressive(), graph(graph), traversal_finder(graph) { // create a SnarlManager using Cactus CactusUltrabubbleFinder site_finder(graph, "", true); site_manager = site_finder.find_snarls(); } pair<size_t, size_t> Simplifier::simplify_once(size_t iteration) { // Set up the deleted node and edge counts pair<size_t, size_t> to_return {0, 0}; auto& deleted_nodes = to_return.first; auto& deleted_edges = to_return.second; if(!graph.is_valid(true, true, true, true)) { // Make sure the graph is valid and not missing nodes or edges cerr << "error:[vg::Simplifier] Invalid graph on iteration " << iteration << endl; exit(1); } // Make a list of leaf sites list<const Snarl*> leaves; if (show_progress) { cerr << "Iteration " << iteration << ": Scanning " << graph.node_count() << " nodes and " << graph.edge_count() << " edges for sites..." << endl; } for (const Snarl* top_level_site : site_manager.top_level_snarls()) { list<const Snarl*> queue {top_level_site}; while (queue.size()) { const Snarl* site = queue.front(); queue.pop_front(); if (site_manager.is_leaf(site)) { leaves.push_back(site); } else { for (const Snarl* child_site : site_manager.children_of(site)) { queue.push_back(child_site); } } } } if (show_progress) { cerr << "Found " << leaves.size() << " leaves" << endl; } // Index all the graph paths map<string, unique_ptr<PathIndex>> path_indexes; graph.paths.for_each_name([&](const string& name) { // For every path name, go index it and put it in this collection path_indexes.insert(make_pair(name, move(unique_ptr<PathIndex>(new PathIndex(graph, name))))); }); // Now we have a list of all the leaf sites. create_progress("simplifying leaves", leaves.size()); // We can't use the SnarlManager after we modify the graph, so we load the // contents of all the leaves we're going to modify first. map<const Snarl*, pair<unordered_set<Node*>, unordered_set<Edge*>>> leaf_contents; // How big is each leaf in bp map<const Snarl*, size_t> leaf_sizes; // We also need to pre-calculate the traversals for the snarls that are the // right size, since the traversal finder uses the snarl manager amd might // not work if we modify the graph. map<const Snarl*, vector<SnarlTraversal>> leaf_traversals; for (const Snarl* leaf : leaves) { // Look at all the leaves // Get the contents of the bubble, excluding the boundary nodes leaf_contents[leaf] = site_manager.deep_contents(leaf, graph, false); // For each leaf, calculate its total size. unordered_set<Node*>& nodes = leaf_contents[leaf].first; size_t& total_size = leaf_sizes[leaf]; for (Node* node : nodes) { // For each node include it in the size figure total_size += node->sequence().size(); } if (total_size == 0) { // This site is just the start and end nodes, so it doesn't make // sense to try and remove it. continue; } if (total_size >= min_size) { // This site is too big to remove continue; } // Identify the replacement traversal for the bubble if it's the right size. // We can't necessarily do this after we've modified the graph. vector<SnarlTraversal>& traversals = leaf_traversals[leaf]; traversals = traversal_finder.find_traversals(*leaf); } for (const Snarl* leaf : leaves) { // Look at all the leaves // Get the contents of the bubble, excluding the boundary nodes unordered_set<Node*>& nodes = leaf_contents[leaf].first; unordered_set<Edge*>& edges = leaf_contents[leaf].second; // For each leaf, grab its total size. size_t& total_size = leaf_sizes[leaf]; if (total_size == 0) { // This site is just the start and end nodes, so it doesn't make // sense to try and remove it. continue; } if (total_size >= min_size) { // This site is too big to remove continue; } #ifdef debug cerr << "Found " << total_size << " bp leaf" << endl; for (auto* node : nodes) { cerr << "\t" << node->id() << ": " << node->sequence() << endl; } #endif // Otherwise we want to simplify this site away // Grab the replacement traversal for the bubble vector<SnarlTraversal>& traversals = leaf_traversals[leaf]; if (traversals.empty()) { // We couldn't find any paths through the site. continue; } // Get the traversal out of the vector SnarlTraversal& traversal = traversals.front(); // Determine the length of the new traversal size_t new_site_length = 0; for (size_t i = 1; i < traversal.visits_size() - 1; i++) { // For every non-anchoring node const Visit& visit = traversal.visits(i); // Total up the lengths of all the nodes that are newly visited. assert(visit.node_id()); new_site_length += graph.get_node(visit.node_id())->sequence().size(); } #ifdef debug cerr << "Chosen traversal is " << new_site_length << " bp" << endl; #endif // Now we have to rewrite paths that visit nodes/edges not on this // traversal, or in a different order, or whatever. To be safe we'll // just rewrite all paths. // Find all the paths that traverse this region. // We start at the start node. Copy out all the mapping pointers on that // node, so we can go through them while tampering with them. map<string, set<Mapping*> > mappings_by_path = graph.paths.get_node_mapping(graph.get_node(leaf->start().node_id())); // It's possible a path can enter the site through the end node and // never hit the start. So we're going to trim those back before we delete nodes and edges. map<string, set<Mapping*> > end_mappings_by_path = graph.paths.get_node_mapping(graph.get_node(leaf->end().node_id())); if (!drop_hairpin_paths) { // We shouldn't drop paths if they hairpin and can't be represented // in a simplified bubble. So we instead have to not simplify // bubbles that would have that problem. bool found_hairpin = false; for (auto& kv : mappings_by_path) { // For each path that hits the start node if (found_hairpin) { // We only care if there are 1 or more hairpins, not how many break; } // Unpack the name auto& path_name = kv.first; for (Mapping* start_mapping : kv.second) { // For each visit to the start node if (found_hairpin) { // We only care if there are 1 or more hairpins, not how many break; } // Determine what orientation we're going to scan in bool backward = start_mapping->position().is_reverse(); // Start at the start node Mapping* here = start_mapping; while (here) { // Until we hit the start/end of the path or the mapping we want if (here->position().node_id() == leaf->end().node_id() && here->position().is_reverse() == (leaf->end().backward() != backward)) { // We made it out. // Stop scanning! break; } if (here->position().node_id() == leaf->start().node_id() && here->position().is_reverse() != (leaf->start().backward() != backward)) { // We have encountered the start node with an incorrect orientation. cerr << "warning:[vg simplify] Path " << path_name << " doubles back through start of site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << "; skipping site!" << endl; found_hairpin = true; break; } // Scan left along ther path if we found the site start backwards, and right if we found it forwards. here = backward ? graph.paths.traverse_left(here) : graph.paths.traverse_right(here); } } } for (auto& kv : end_mappings_by_path) { // For each path that hits the end node if (found_hairpin) { // We only care if there are 1 or more hairpins, not how many break; } // Unpack the name auto& path_name = kv.first; for (Mapping* end_mapping : kv.second) { if (found_hairpin) { // We only care if there are 1 or more hairpins, not how many break; } // Determine what orientation we're going to scan in bool backward = end_mapping->position().is_reverse(); // Start at the end Mapping* here = end_mapping; while (here) { if (here->position().node_id() == leaf->start().node_id() && here->position().is_reverse() == (leaf->start().backward() != backward)) { // We made it out. // Stop scanning! break; } if (here->position().node_id() == leaf->end().node_id() && here->position().is_reverse() != (leaf->end().backward() != backward)) { // We have encountered the end node with an incorrect orientation. cerr << "warning:[vg simplify] Path " << path_name << " doubles back through end of site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << "; dropping site!" << endl; found_hairpin = true; break; } // Scan right along the path if we found the site end backwards, and left if we found it forwards. here = backward ? graph.paths.traverse_right(here) : graph.paths.traverse_left(here); } } } if (found_hairpin) { // We found a hairpin, so we want to skip the site. cerr << "warning:[vg simplify] Site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << " skipped due to hairpin path." << endl; continue; } } // We'll keep a set of the end mappings we managed to find, starting from the start set<Mapping*> found_end_mappings; for (auto& kv : mappings_by_path) { // For each path that hits the start node // Unpack the name auto& path_name = kv.first; // If a path can't be represented after a bubble is popped // (because the path reversed and came out the same side as it // went in), we just clobber the path entirely. TODO: handle // out-the-same-side traversals as valid genotypes somehow.. bool kill_path = false; for (Mapping* start_mapping : kv.second) { // For each visit to the start node // Determine what orientation we're going to scan in bool backward = start_mapping->position().is_reverse(); // We're going to fill this list with the mappings we need to // remove and replace in this path for this traversal. Initially // runs from start of site to end of site, but later gets // flipped into path-local orientation. list<Mapping*> existing_mappings; // Tracing along forward/backward from each as appropriate, see // if the end of the site is found in the expected orientation // (or if the path ends first). bool found_end = false; Mapping* here = start_mapping; // We want to remember the end mapping when we find it Mapping* end_mapping = nullptr; #ifdef debug cerr << "Scanning " << path_name << " from " << pb2json(*here) << " for " << to_node_traversal(leaf->end(), graph) << " orientation " << backward << endl; #endif while (here) { // Until we hit the start/end of the path or the mapping we want #ifdef debug cerr << "\tat " << pb2json(*here) << endl; #endif if (here->position().node_id() == leaf->end().node_id() && here->position().is_reverse() == (leaf->end().backward() != backward)) { // We have encountered the end of the site in the // orientation we expect, given the orientation we saw // for the start. found_end = true; end_mapping = here; // Know we got to this mapping at the end from the // start, so we don't need to clobber everything // before it. found_end_mappings.insert(here); // Stop scanning! break; } if (here->position().node_id() == leaf->start().node_id() && here->position().is_reverse() != (leaf->start().backward() != backward)) { // We have encountered the start node with an incorrect orientation. cerr << "warning:[vg simplify] Path " << path_name << " doubles back through start of site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << "; dropping!" << endl; assert(drop_hairpin_paths); kill_path = true; break; } if (!nodes.count(graph.get_node(here->position().node_id()))) { // We really should stay inside the site! cerr << "error:[vg simplify] Path " << path_name << " somehow escapes site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << endl; exit(1); } if (here != start_mapping) { // Remember the mappings that aren't to the start or // end of the site, so we can remove them later. existing_mappings.push_back(here); } // Scan left along ther path if we found the site start backwards, and right if we found it forwards. Mapping* next = backward ? graph.paths.traverse_left(here) : graph.paths.traverse_right(here); if (next == nullptr) { // We hit the end of the path without finding the end of the site. // We've found all the existing mappings, so we can stop. break; } // Make into NodeTraversals NodeTraversal here_traversal(graph.get_node(here->position().node_id()), here->position().is_reverse()); NodeTraversal next_traversal(graph.get_node(next->position().node_id()), next->position().is_reverse()); if (backward) { // We're scanning the other way std::swap(here_traversal, next_traversal); } // Make sure we have an edge so we can traverse this node and then the node we're going to. if(graph.get_edge(here_traversal, next_traversal) == nullptr) { cerr << "error:[vg::Simplifier] No edge " << here_traversal << " to " << next_traversal << endl; exit(1); } here = next; } if (kill_path) { // This path can't exist after we pop this bubble. break; } if (!found_end) { // This path only partly traverses the site, and is // anchored at the start. Remove the part inside the site. // TODO: let it stay if it matches the one true traversal. for(auto* mapping : existing_mappings) { // Trim the path out of the site graph.paths.remove_mapping(mapping); } // TODO: update feature positions if we trim off the start of a path // Maybe the next time the path visits the site it will go // all the way through. continue; } // If we found the end, remove all the mappings encountered, in // order so that the last one removed is the last one along the // path. if (backward) { // Make sure the last mapping in the list is the last // mapping to occur along the path. existing_mappings.reverse(); } // Where does the variable region of the site start for this // traversal of the path? If there are no existing mappings, // it's the start mapping's position if we traverse the site // backwards and the end mapping's position if we traverse // the site forwards. If there are existing mappings, it's // the first existing mapping's position in the path. TODO: // This is super ugly. Can we view the site in path // coordinates or something? PathIndex& path_index = *path_indexes.at(path_name).get(); Mapping* mapping_after_first = existing_mappings.empty() ? (backward ? start_mapping : end_mapping) : existing_mappings.front(); assert(path_index.mapping_positions.count(mapping_after_first)); size_t variable_start = path_index.mapping_positions.at(mapping_after_first); // Determine the total length of the old traversal of the site size_t old_site_length = 0; for (auto* mapping : existing_mappings) { // Add in the lengths of all the mappings that will get // removed. old_site_length += mapping_from_length(*mapping); } #ifdef debug cerr << "Replacing " << old_site_length << " bp at " << variable_start << " with " << new_site_length << " bp" << endl; #endif // Actually update any BED features features.on_path_edit(path_name, variable_start, old_site_length, new_site_length); // Where will we insert the new site traversal into the path? list<Mapping>::iterator insert_position; if (!existing_mappings.empty()) { // If there are existing internal mappings, we'll insert right where they were for (auto* mapping : existing_mappings) { // Remove each mapping from left to right along the // path, saving the position after the mapping we just // removed. At the end we'll have the position of the // mapping to the end of the site. #ifdef debug cerr << path_name << ": Drop mapping " << pb2json(*mapping) << endl; #endif insert_position = graph.paths.remove_mapping(mapping); } } else { // Otherwise we'll insert right before the mapping to // the start or end of the site (whichever occurs last // along the path) insert_position = graph.paths.find_mapping(backward ? start_mapping : here); } // Make sure we're going to insert starting from the correct end of the site. if (backward) { assert(insert_position->position().node_id() == leaf->start().node_id()); } else { assert(insert_position->position().node_id() == leaf->end().node_id()); } // Loop through the internal visits in the canonical // traversal backwards along the path we are splicing. If // it's a forward path this is just right to left, but if // it's a reverse path it has to be left to right. for (size_t i = 0; i < traversal.visits_size(); i++) { // Find the visit we need next, as a function of which // way we need to insert this run of visits. Normally we // go through the visits right to left, but when we have // a backward path we go left to right. const Visit& visit = backward ? traversal.visits(i) : traversal.visits(traversal.visits_size() - i - 1); // Make a Mapping to represent it Mapping new_mapping; new_mapping.mutable_position()->set_node_id(visit.node_id()); // We hit this node backward if it's backward along the // traversal, xor if we are traversing the traversal // backward new_mapping.mutable_position()->set_is_reverse(visit.backward() != backward); // Add an edit Edit* edit = new_mapping.add_edit(); size_t node_seq_length = graph.get_node(visit.node_id())->sequence().size(); edit->set_from_length(node_seq_length); edit->set_to_length(node_seq_length); #ifdef debug cerr << path_name << ": Add mapping " << pb2json(new_mapping) << endl; #endif // Insert the mapping in the path, moving right to left insert_position = graph.paths.insert_mapping(insert_position, path_name, new_mapping); } // Now we've corrected this site on this path. Update its index. // TODO: right now this means retracing the entire path. path_indexes[path_name].get()->update_mapping_positions(graph, path_name); } if (kill_path) { // Destroy the path completely, because it needs to reverse // inside a site that we have popped. graph.paths.remove_path(path_name); } } for (auto& kv : end_mappings_by_path) { // Now we handle the end mappings not reachable from the start. For each path that touches the end... // Unpack the name auto& path_name = kv.first; // We might have to kill the path, if it reverses inside a // bubble we're popping bool kill_path = false; for (Mapping* end_mapping : kv.second) { if (found_end_mappings.count(end_mapping)) { // Skip the traversals of the site that we handled. continue; } // Now we're left with paths that leave the site but don't // enter. We're going to clobber everything before the path // leaves the site. // Determine what orientation we're going to scan in bool backward = end_mapping->position().is_reverse(); // Start at the end Mapping* here = end_mapping; // Keep a list of mappings we need to remove list<Mapping*> to_remove; while (here) { if (here->position().node_id() == leaf->end().node_id() && here->position().is_reverse() != (leaf->end().backward() != backward)) { // We have encountered the end node with an incorrect orientation. cerr << "warning:[vg simplify] Path " << path_name << " doubles back through end of site " << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << "; dropping!" << endl; assert(drop_hairpin_paths); kill_path = true; break; } // Say we should remove the mapping. to_remove.push_back(here); // Scan right along the path if we found the site end backwards, and left if we found it forwards. here = backward ? graph.paths.traverse_right(here) : graph.paths.traverse_left(here); // Eventually we should hit the end of the path, or the // end of the site, since we don't hit the start. } if (kill_path) { // Just go kill the whole path break; } for (auto* mapping: to_remove) { // Get rid of all the mappings once we're done tracing them out. graph.paths.remove_mapping(mapping); } } if (kill_path) { // Destroy the path completely, because it needs to reverse // inside a site that we have popped. graph.paths.remove_path(path_name); } } // Now delete all edges that aren't connecting adjacent nodes on the // blessed traversal (before we delete their nodes). set<Edge*> blessed_edges; for (int i = 0; i < traversal.visits_size() - 1; ++i) { // For each node and the next node (which won't be the end) const Visit visit = traversal.visits(i); const Visit next = traversal.visits(i); // Find the edge between them NodeTraversal here(graph.get_node(visit.node_id()), visit.backward()); NodeTraversal next_traversal(graph.get_node(next.node_id()), next.backward()); Edge* edge = graph.get_edge(here, next_traversal); assert(edge != nullptr); // Remember we need it blessed_edges.insert(edge); } // Also get the edges from the boundary nodes into the traversal if (traversal.visits_size() > 0) { NodeTraversal first_visit = to_node_traversal(traversal.visits(0), graph); NodeTraversal last_visit = to_node_traversal(traversal.visits(traversal.visits_size() - 1), graph); blessed_edges.insert(graph.get_edge(to_node_traversal(leaf->start(), graph), first_visit)); blessed_edges.insert(graph.get_edge(last_visit, to_node_traversal(leaf->end(), graph))); } else { // This is a deletion traversal, so get the edge from the start to end of the site blessed_edges.insert(graph.get_edge(to_node_traversal(leaf->start(), graph), to_node_traversal(leaf->end(), graph))); } for (auto* edge : edges) { if (!blessed_edges.count(edge)) { // Get rid of all the edges not needed for the one true traversal #ifdef debug cerr << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << ": Delete edge: " << pb2json(*edge) << endl; #endif graph.destroy_edge(edge); deleted_edges++; } } // Now delete all the nodes that aren't on the blessed traversal. // What nodes are on it? set<Node*> blessed_nodes; for (int i = 0; i < traversal.visits_size(); i++) { const Visit& visit = traversal.visits(i); blessed_nodes.insert(graph.get_node(visit.node_id())); } for (auto* node : nodes) { // For every node in the site if (!blessed_nodes.count(node)) { // If we don't need it for the chosen path, destroy it #ifdef debug cerr << to_node_traversal(leaf->start(), graph) << " - " << to_node_traversal(leaf->end(), graph) << ": Delete node: " << pb2json(*node) << endl; #endif // There may be paths still touching this node, if they // managed to get into the site without touching the start // node. We'll delete those paths. set<string> paths_to_kill; for (auto& kv : graph.paths.get_node_mapping(node)) { if (mappings_by_path.count(kv.first)) { // We've already actually updated this path; the // node_mapping data is just out of date. continue; } paths_to_kill.insert(kv.first); } for (auto& path : paths_to_kill) { graph.paths.remove_path(path); cerr << "warning:[vg simplify] Path " << path << " removed" << endl; } graph.destroy_node(node); deleted_nodes++; } } // OK we finished a leaf increment_progress(); } destroy_progress(); // Reset the ranks in the graph, since we rewrote paths graph.paths.clear_mapping_ranks(); // Return the statistics. return to_return; } void Simplifier::simplify() { for (size_t i = 0; i < max_iterations; i++) { // Try up to the max number of iterations auto deleted_elements = simplify_once(i); if (show_progress) { cerr << "Iteration " << i << ": deleted " << deleted_elements.first << " nodes and " << deleted_elements.second << " edges" << endl; } if (deleted_elements.first == 0 && deleted_elements.second == 0) { // If nothing gets deleted, stop because trying again won't change // things break; } } } }
21a294a049c57560c6334891877da394f644b72a
4a41e5b7e93d39386055ce8648e6c3354f97c61e
/cppDemo/boostDemo/logs/file/log.cpp
6d89e306175f57068180d6dd9da53d117ead689f
[]
no_license
lianaipeng/demos
52c78eed35f7921b2c425dc6c8443478d80a3061
6692aa6537ab56f56e5b6e374d16654dc17091c1
refs/heads/master
2021-01-17T12:00:12.192250
2017-07-19T09:12:37
2017-07-19T09:12:37
47,742,913
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
log.cpp
#include "log.h" void log_init(const std::string& prefix, const log_level& level){ logging::add_file_log( keywords::file_name = prefix+"_%Y-%m-%d.log", keywords::open_mode = (std::ios::out | std::ios::app), keywords::rotation_size = 10 * 1024 * 1024, keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), keywords::format = "[%TimeStamp%]:%Message%", keywords::auto_flush = true ); logging::core::get()->set_filter( /*logging::trivial::severity >= logging::trivial::info*/ logging::trivial::severity >= level ); logging::add_common_attributes(); std::cout << "###################" << std::endl; }
424b0dc06a8fb6512fe1ce8d23121dde8d084eb1
72a8340645e585ba2d49875723e2cc493399fe8e
/HW2/tests/client_test.cpp
61583ffa986376c34b8f956adb8fa5395537ef9e
[]
no_license
jamesrcounts/CS537
ee0bffdf5706e9c78a494fde0ef483e6b8cf7331
207e6b9a8795a442ad83508dd131a3868378e04d
refs/heads/master
2020-04-06T04:31:12.927032
2013-05-08T20:11:48
2013-05-08T20:11:48
7,839,056
1
0
null
null
null
null
UTF-8
C++
false
false
3,700
cpp
client_test.cpp
/*test.cpp*/ #include <arpa/inet.h> #include <igloo/igloo.h> #include <netdb.h> #include <signal.h> #include <stdio.h> #include <sys/socket.h> #include <unistd.h> #include "../TcpSocket.h" #include "../TcpListeningSocket.h" using namespace igloo; void *caseServer( void *state ); void *pong( void *state ); Context( DescribeAClientSocket ) { Spec( ItHasAnAddressItWantsToConnectTo ) { TcpSocket is( "127.0.0.1", 3490 ); struct sockaddr_in it = is.getAddress(); char *address = new char[INET_ADDRSTRLEN]; inet_ntop( AF_INET, &it.sin_addr.s_addr, address, sizeof( sockaddr_in ) ); Assert::That( address , Equals( "127.0.0.1" ) ); delete[] address; Assert::That( ntohs( it.sin_port ), Equals( 3490 ) ); } Spec( ItHasAFileDescriptor ) { TcpSocket ts( "127.0.0.1", 3490 ); Assert::That( ts.getDescriptor(), IsGreaterThan( -1 ) ); } Spec( ItThrowsAnExceptionWhenItCantConnect ) { TcpSocket ts( "127.0.0.1", 80 ); AssertThrows( InternetSocketException, ts.initiateConnection() ); Assert::That( LastException<InternetSocketException>().what(), Equals( "Connection refused" ) ); } Spec( ItCanConnectToListeningSockets ) { try { TcpSocket ts( "144.37.12.45", 80 ); SocketConnection s = ts.initiateConnection(); Assert::That( s.getDescriptor(), IsGreaterThan( -1 ) ); } catch ( exception &e ) { cout << e.what() << endl; } } }; Context( DescribeASocketConnection ) { Spec( ItCanRecieveAMessage ) { pthread_t tid; pthread_create( &tid, NULL, &pong, ( void * )NULL ); for ( int i = 0; i < 10; ++i ) { sleep( 1 ); try { TcpSocket ts( "127.0.0.1", 3490 ); SocketConnection s = ts.initiateConnection(); string response = s.readMessage(); Assert::That( response, Equals( "Hello, world!" ) ); break; } catch ( InternetSocketException &e ) { cout << e.what() << endl; } } } Spec( ItCanSendAMessage ) { pthread_t tid; pthread_create( &tid, NULL, &caseServer, ( void * )NULL ); for ( int i = 0; i < 10; ++i ) { sleep( 1 ); try { TcpSocket ts( "127.0.0.1", 3490 ); SocketConnection s = ts.initiateConnection(); s.sendMessage( "ok" ); string response = s.readMessage(); Assert::That( response, Equals( "OK" ) ); break; } catch ( InternetSocketException &e ) { cout << e.what() << endl; } } } }; void *caseServer( void *state ) { TcpListeningSocket t( 4, "127.0.0.1", 3490 ); SocketConnection s = t.acceptConnection(); string str = s.readMessage(); transform( str.begin(), str.end(), str.begin(), ::toupper ); s.sendMessage( str ); return NULL; } void *pong( void *state ) { TcpListeningSocket t( 4, "127.0.0.1", 3490 ); SocketConnection s = t.acceptConnection(); s.sendMessage( "Hello, world!" ); return NULL; } int main( int argc, char const *argv[] ) { return TestRunner::RunAllTests(); }
59cb638c6598b07e21ed194e8ee4e6f7f2036238
0bb8e42162e6cbb77abcf59d3721e74bcfc3df2b
/code/day04/src/BlinnPhongRenderer.h
bdb9a874b7fd4109fe765ed517024c1a23ad7f82
[]
no_license
kato-toranosuke/advanced-cg-2021
744b20d86a82317a2bbe9adbc9c34de3dff10efa
f41fd1b35c4fc09dcfc12d613af892e60e47a6eb
refs/heads/master
2023-05-08T14:20:26.312892
2021-06-05T21:14:57
2021-06-05T21:14:57
357,054,724
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
BlinnPhongRenderer.h
#pragma once #include "AbstractRenderer.h" class BlinnPhongRenderer : public AbstractRenderer { public: static void Init(); static AbstractRenderer* Create() { return new BlinnPhongRenderer(); } static void ImGui(); void render(const PolygonMesh& mesh) const; private: static GLSLProgramObject* s_pShader; static float s_Shininess; static glm::vec3 s_DiffuseCoeff; static glm::vec3 s_AmbientColor; };
fc6b4edce15a131f8cae00f054381ad6de7e1391
3f984937a1c186990a3e2174fa3facf9730e66fe
/Unsorted/Matrix/Functions_Basic.ino
26d082c3d1a4154fa1806d5cccdb1990b299df15
[]
no_license
LatvianModder/ProjArduino
3fb52a446660269a52c02464280c3782ae8295a8
a3cbbc2d78d57eeecc3bbc19fe43422b83e08c3e
refs/heads/master
2021-01-20T01:53:38.564991
2015-11-27T10:50:12
2015-11-27T10:50:12
31,860,596
1
0
null
null
null
null
UTF-8
C++
false
false
219
ino
Functions_Basic.ino
void write(int data) { Serial.print(data, BYTE); } boolean read(int data) { if(Serial.read() == data) { return true; } else { return false; } } void digiW(int data1, int data2) { digitalWrite(data1, data2); }
82efc046b00e40e6717b06f91066ff37806b8b51
56a3df7f18d06005b6185152bd7941add18edfa9
/bcos-sdk/tests/unittests/amop/TopicManagerTest.cpp
339a0af660ddbdaa6640484fdcb40ee26756ccc6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
FISCO-BCOS/FISCO-BCOS
bac8b40f12315e043f006fac8152af93662f3444
3014f5be43fe93ddb455d277d30837ab5ba8c14f
refs/heads/master
2023-08-31T20:28:49.049631
2023-08-14T09:01:07
2023-08-14T09:01:07
113,932,055
2,413
829
Apache-2.0
2023-09-14T12:01:28
2017-12-12T02:17:31
Shell
UTF-8
C++
false
false
4,880
cpp
TopicManagerTest.cpp
/** * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @brief test for TopicManager * @file TopicManagerTest.cpp * @author: octopus * @date 2021-09-22 */ #include <bcos-cpp-sdk/amop/AMOPRequest.h> #include <bcos-cpp-sdk/amop/TopicManager.h> #include <bcos-utilities/testutils/TestPromptFixture.h> #include <boost/beast/websocket/rfc6455.hpp> #include <boost/test/tools/old/interface.hpp> #include <boost/test/unit_test.hpp> using namespace bcos; using namespace bcos::cppsdk::amop; using namespace bcos::test; using namespace bcos::protocol; BOOST_FIXTURE_TEST_SUITE(TopicManagerTest, TestPromptFixture) BOOST_AUTO_TEST_CASE(test_AMOPRequestEncodeDecode) { auto amopRequestFactory = std::make_shared<AMOPRequestFactory>(); std::string dataStr = "testAMOPRequest"; auto request = amopRequestFactory->buildRequest(); request->setData(bcos::bytesConstRef((byte*)dataStr.data(), dataStr.size())); request->setVersion(10023); std::string topic = "testAMOPRequest+-@topic"; request->setTopic(topic); BOOST_CHECK(request->version() == 10023); BOOST_CHECK(request->topic() == topic); BOOST_CHECK(*(request->data().data()) == *(dataStr.data())); // encode bytes encodedData; request->encode(encodedData); // decode auto decodedRequest = amopRequestFactory->buildRequest(ref(encodedData)); BOOST_CHECK(decodedRequest->version() == request->version()); BOOST_CHECK(decodedRequest->topic() == request->topic()); BOOST_CHECK(*(decodedRequest->data().data()) == *(request->data().data())); } BOOST_AUTO_TEST_CASE(test_TopicManager) { { auto topicManager = std::make_shared<TopicManager>(); auto topics = topicManager->topics(); BOOST_CHECK(topics.size() == 0); std::string topic1 = "a"; std::string topic2 = "a"; std::string topic3 = "a"; auto r = topicManager->addTopic(topic1); BOOST_CHECK(r); r = topicManager->addTopic(topic1); BOOST_CHECK(!r); r = topicManager->addTopic(topic2); BOOST_CHECK(!r); r = topicManager->addTopic(topic3); BOOST_CHECK(!r); topics = topicManager->topics(); BOOST_CHECK(topics.size() == 1); r = topicManager->removeTopic(topic1); BOOST_CHECK(r); r = topicManager->removeTopic(topic1); BOOST_CHECK(!r); topics = topicManager->topics(); BOOST_CHECK(topics.size() == 0); BOOST_CHECK(!topicManager->toJson().empty()); } { auto topicManager = std::make_shared<TopicManager>(); BOOST_CHECK(topicManager->topics().size() == 0); std::string topic1 = "a"; std::string topic2 = "b"; std::string topic3 = "c"; std::set<std::string> topics{topic1, topic2, topic3}; auto r = topicManager->addTopics(topics); BOOST_CHECK(r); r = topicManager->addTopics(topics); BOOST_CHECK(!r); BOOST_CHECK(topics.size() == topics.size()); r = topicManager->removeTopics(topics); BOOST_CHECK(r); r = topicManager->removeTopics(topics); BOOST_CHECK(!r); topics = topicManager->topics(); BOOST_CHECK(topics.size() == 0); BOOST_CHECK(!topicManager->toJson().empty()); } { auto topicManager = std::make_shared<TopicManager>(); BOOST_CHECK(topicManager->topics().size() == 0); std::string topic1 = "a"; std::string topic2 = "a"; std::string topic3 = "a"; std::set<std::string> topics{topic1, topic2, topic3}; auto r = topicManager->addTopics(topics); BOOST_CHECK(r); r = topicManager->addTopics(topics); BOOST_CHECK(!r); topics = topicManager->topics(); BOOST_CHECK(topics.size() == topics.size()); r = topicManager->removeTopic(topic1); BOOST_CHECK(r); r = topicManager->removeTopic(topic2); BOOST_CHECK(!r); r = topicManager->removeTopic(topic3); BOOST_CHECK(!r); r = topicManager->removeTopics(topics); BOOST_CHECK(!r); topics = topicManager->topics(); BOOST_CHECK(topics.size() == 0); BOOST_CHECK(!topicManager->toJson().empty()); } } BOOST_AUTO_TEST_SUITE_END()
6d74ac2e5dfb201657b8949cd62fe780e26bdf05
ee6944de205f6ac8ef8b2873d99edf30cabea477
/cplusplus/chap6/14_array_params_constant_params.cpp
76ea400fe58fd6d9b8921458dd2233a2f7c9282e
[]
no_license
stareque-atlassian/cplusplus-learn
6bfbda2ec0b6ddcf1f47c89fe361a5ea24408951
cb81573f23d52f1c532c7fb19c605ffb76208685
refs/heads/main
2023-07-14T09:26:11.180328
2021-08-18T05:46:04
2021-08-18T05:46:04
397,440,415
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
14_array_params_constant_params.cpp
// // main.cpp // cplusplus // // Created by Shehab Tareque on 17/8/21. // #include <iostream> void fillArray(int list[], int listSize) { int index; cout<<"Enter "<<listSize<<" integers"<<endl; for (index = 0; index < listSize; index++) cin >> list[index]; } void printArray(int list[], int listSize) { int index; for (index = 0; index < listSize; index++) cout << list[index] << " "; cout<<endl; } void copyArray(int list1[], int src, int list2[], int tar, int numOfElements) { for (int index = tar; index < tar + numOfElements; index++) { list2[index] = list1[src]; src++; } } int main() { int myList[5]; int yourList[5]= {0}; fillArray(myList,5); cout<<"After calling fillArray function"<<endl; printArray(myList,5); copyArray(myList,1,yourList,2,3); cout<<"After calling copyArray function"<<endl; printArray(yourList,5); } void swap(int , int &); void printArray(int list[], int); int main() { int myList[5] = {2,4,6,8,10}; swap(myList[0],myList[3]); cout<<"After calling swap function"<<endl; printArray(myList,5); } void swap(int x, int &y) { int tmp = x; x = y; y = tmp; } void printArray(int list[], int listSize) { int index; for (index = 0; index < listSize; index++) cout << list[index] << " "; cout<<endl; } void printArray(const int list[], int listSize) { int index; for (index = 0; index < listSize; index++) cout << list[index] << " "; cout<<endl; } int sumArray(const int list[], int listSize) { int index; int sum = 0; for (index = 0; index < listSize; index++) sum = sum + list[index]; return sum; } int main() { int myList[5]={3,5,7,8,4}; printArray(myList,5); cout<<"Sum = "<<sumArray(myList,5)<<endl; }
1b7b0e55904f4c4ece736fa4ef6fb9d6b091983d
acdde1143c79084f33bd00e0b1c49f7364540662
/src/import/chips/p9/procedures/hwp/memory/lib/freq/sync.H
4f86248901fa9722109720547e3224fcd596df3a
[ "Apache-2.0" ]
permissive
dongshijiang/hostboot
1329be9424dbd23325064cb89f659d7e636fb1ff
f1746c417531b1264be23a8dcf1284ae204f6153
refs/heads/master
2023-06-15T16:05:09.961450
2021-06-29T21:04:03
2021-07-06T20:33:51
385,787,842
0
0
NOASSERTION
2021-07-14T02:13:08
2021-07-14T02:13:08
null
UTF-8
C++
false
false
6,433
h
sync.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/freq/sync.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file synch.H /// @brief Synchronous function implementations /// // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_SYNC_H_ #define _MSS_SYNC_H_ #include <map> #include <vector> #include <fapi2.H> #include <generic/memory/lib/utils/shared/mss_generic_consts.H> #include <lib/shared/mss_const.H> #include <generic/memory/lib/utils/freq/mss_freq_scoreboard.H> #include <generic/memory/lib/utils/c_str.H> namespace mss { // List of the nest frequencies for nimbus // Note: these need to be sorted so binary search works static const std::vector<uint64_t> NIMBUS_NEST_FREQS = { fapi2::ENUM_ATTR_FREQ_PB_MHZ_1600, fapi2::ENUM_ATTR_FREQ_PB_MHZ_1866, fapi2::ENUM_ATTR_FREQ_PB_MHZ_2000, fapi2::ENUM_ATTR_FREQ_PB_MHZ_2133, fapi2::ENUM_ATTR_FREQ_PB_MHZ_2400 }; /// /// @brief Checks to see if a passed in value could be a valid nest frequency /// @param[in] i_proposed_freq a frequency value that is to be checked /// @return boolean true, false whether the value is a valid nest frequency /// inline bool is_nest_freq_valid (const uint64_t i_proposed_freq) { return ( std::binary_search(NIMBUS_NEST_FREQS.begin(), NIMBUS_NEST_FREQS.end(), i_proposed_freq) ); } /// /// @brief Retrieves a mapping of MSS frequency values per mcbist target /// @param[in] i_targets vector of controller targets /// @param[out] o_freq_map dimm speed map <key, value> = (mcbist target, frequency) /// @param[out] o_is_speed_equal holds whether map dimm speed is equal /// @return FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode dimm_speed_map(const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCBIST> >& i_targets, std::map< fapi2::Target<fapi2::TARGET_TYPE_MCBIST>, uint64_t >& o_freq_map, speed_equality& o_is_speed_equal); /// /// @brief Helper function to deconfigure MCS targets connected to MCBIST /// @param[in] i_target the controller target /// @param[in] i_dimm_speed dimm speed in MT/s /// @param[in] i_nest_freq nest freq in MHz /// @return true if hardware was deconfigured /// bool deconfigure(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, const uint64_t i_dimm_speed, const uint32_t i_nest_freq); /// /// @brief Selects synchronous mode and performs requirements enforced by ATTR_REQUIRED_SYNCH_MODE /// @param[in] i_freq_map dimm speed mapping /// @param[in] i_equal_dimm_speed tracks whether map has equal dimm speeds /// @param[in] i_nest_freq nest frequency /// @param[in] i_required_sync_mode system policy to enforce synchronous mode /// @param[out] o_selected_sync_mode final synchronous mode /// @param[out] o_selected_freq final freq selected, only valid if final sync mode is in-sync /// @return FAPI2_RC_SUCCESS iff successful /// fapi2::ReturnCode select_sync_mode(const std::map< fapi2::Target<fapi2::TARGET_TYPE_MCBIST>, uint64_t >& i_freq_map, const speed_equality i_equal_dimm_speed, const uint32_t i_nest_freq, const uint8_t i_required_sync_mode, uint8_t& o_selected_sync_mode, uint64_t& o_selected_freq); /// /// @brief Update supported frequency scoreboard according to whether the processor is in sync mode or not /// @param[in] i_target processor frequency domain /// @param[in,out] io_scoreboard scoreboard of port targets supporting each frequency /// @return FAPI2_RC_SUCCESS iff ok /// @note the attributes which drive this are read-only so they're hard to change when /// testing. So this helper allows us to use the attributes for the main path but /// have a path for testing /// inline fapi2::ReturnCode limit_freq_by_processor(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, const bool i_sync_mode, freq_scoreboard& io_scoreboard) { // If we're not in sync mode, just exit if(!i_sync_mode) { FAPI_INF("%s is not in sync mode, skipping the sync mode check", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // Loop through all potential ports for(uint64_t l_port_pos = 0; l_port_pos < PORTS_PER_MCBIST; ++l_port_pos) { FAPI_TRY(io_scoreboard.remove_freqs_not_on_list(l_port_pos, NIMBUS_NEST_FREQS)); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } }// mss #endif
a653693670461162ce96f522a0d2615d90df8a15
0154f04e7f2a20dc85fb933c9e0b518186f01ef4
/include/common/path_reader.h
6cfdad111c91fd35fe537c26cc7715b256ec326b
[]
no_license
julian1/shell
c6ca07da5f73ee3ddedecf682536c18f0cc6df82
57745384c2f7f50ef0e124949bac28cc193123e1
refs/heads/master
2020-04-28T02:37:49.343022
2014-04-17T13:05:31
2014-04-17T13:05:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
path_reader.h
#pragma once /* this class is used, because agg_path_storage includes and iterator. therefore even if we have a basically const operation (just iterating the vertices using), it means we cannot pass agg_path_storage with const . therefore use, this class as an adaptor to a const path_storage it also makes the dependencies of operations, like geom transform or rendering clearer. */ #include <agg_path_storage.h> template< class VC> struct path_reader_base { typedef VC container_type; const container_type & m_vertices; unsigned m_iterator; path_reader_base( const agg::path_storage & path ) : m_vertices( path.vertices() ) { rewind( 0); } path_reader_base( const container_type & m_vertices) : m_vertices( m_vertices) { rewind( 0); } inline void rewind(unsigned path_id) { m_iterator = path_id; } //------------------------------------------------------------------------ inline unsigned vertex(double* x, double* y) { if(m_iterator >= m_vertices.total_vertices()) return agg::path_cmd_stop; return m_vertices.vertex(m_iterator++, x, y); } }; typedef path_reader_base< agg::vertex_block_storage<double> > path_reader;
854c8817dfd063429a5cf54bbb720181ba73d72b
cc63612e896bb05a8d5345c3525d4aa6d0e75265
/Pow(x, n).cpp
d52fa04cac1411175df56a777254ec71dfe85269
[]
no_license
avotaliff/tg_mpei_course
5ed5f7c99037d19c8afd789e5f4956e2c74d98a8
4eedc6bcce0641f0062ffa23383e2974ed76b3c0
refs/heads/master
2020-07-19T09:35:58.094975
2020-01-11T11:43:31
2020-01-11T11:43:31
206,421,161
1
0
null
null
null
null
UTF-8
C++
false
false
281
cpp
Pow(x, n).cpp
//https://leetcode.com/problems/powx-n/ class Solution { public: double myPow(double x, long long n) { if (n<0) return 1/myPow(x,-n); if (n==0) return 1; if (n % 2 ==1) return x* myPow(x,n-1); double u=myPow(x,n/2); return u*u; } };
fa04a440bfb258d23ea7dc312179cd6f3c594629
66e293057b7e0cd54b2b45f49174e3cdd5433a59
/src/biser/src/main.cpp
bae1097e126508f3f5bdf9c6f60f1fa329824290
[]
no_license
nick9bkru/UI
c068dd0598e297235e0d4dbec36988b123736c3c
b5fce7951d91d990eb95162d95a0f589056780b1
refs/heads/master
2016-09-15T22:22:59.757179
2015-10-20T07:33:27
2015-10-20T07:33:27
39,785,658
0
1
null
null
null
null
UTF-8
C++
false
false
3,423
cpp
main.cpp
#include <memory> #include <signal.h> #include <functional> #include "LogSingleton.h" #include "util.h" #include "nsdManage.h" #include "TCPClientManage.h" #include "TCPServerManage.h" #include "Database.h" #include "BDReadConf.h" using namespace std; ///< Экземпляр класса для журналирования. SKLib::Log *Log; ///< PID главного потока. int mainThreadPid; ///< Функция запускаемая в потоке void *pthreadTcpMng (void * ); ///< класс следит за подключением к УИ UIservice::TCPManage *TcpMng; ///< класс опроса всех УИ nsdManage * NsdMng; /** \brief функция вызывающаяся при перехвате сигнала */ void sig_handler(int signum) { TcpMng->stop(); NsdMng->stop(); UNUSED(signum); if (mainThreadPid != getpid()) { Log->log("----- hello! I'am thread. -----"); pthread_exit(NULL); return; } } /** \brief функция вызывающаяся устанавливаем перехватчик сигналов */ void setSignal() { signal(SIGHUP, sig_handler); signal(SIGINT, sig_handler); signal(SIGQUIT, sig_handler); signal(SIGABRT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGPIPE, SIG_IGN); sigset_t sigs_to_block; sigemptyset(&sigs_to_block); sigaddset(&sigs_to_block, SIGPIPE); pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL); } /** \brief Основная функция. Запуск всех потоков, открытие каналов к БД. \param argc - число аргументов командной строки. \param argv - массив аргументов командной строки. */ int main(int argc, char **argv) { UNUSED(*argv); pthread_t pidPthreadTcmMng; if (argc == 1) daemon(0, 0); mainThreadPid = getpid(); //Логирующий класс Log = &SKLib::LogSingleton::getInstance( "/tmp/biser.log"); Log->setDebugMode(argc > 1 ? SKLib::Log::DebugToUserScreen : SKLib::Log::DebugToFile); //настраиваем ловушки сигналов) setSignal(); // цепляемся к БД std::auto_ptr< Database > db ( new Database( "127.0.0.1","frag_pgdb" ) ); ///< Указатель на объект, связанный с БД. while ( !db->isReady() ) { Log->log("Error !! Database not started !!"); sleep (1); db.reset ( new Database( "127.0.0.1","frag_pgdb" ) ); } Log->log("Database is start!!"); // Log->log("Sleeep 5 sec .... "); //поставил задержку // sleep (5); try { TcpMng = new UIservice::TCPServerManage(4001); ///< Идентификаторы потока pthread_create(&pidPthreadTcmMng, NULL, pthreadTcpMng, NULL); NsdMng = new nsdManage ( db.get()); NsdMng->init(); UIservice::TCPManage::UiVec vec = NsdMng->getUiVec(); for ( UIservice::TCPManage::UiVec::iterator it=vec.begin(); it!=vec.end(); it++) { TcpMng->addUi(*it); } NsdMng->start(); } catch ( std::string e) { Log->log("!!!! ERROR == :" + e); sig_handler(1); } pthread_join(pidPthreadTcmMng, NULL); return 0; }; void *pthreadTcpMng (void * unused ) { UNUSED ( unused ); Log->log("pthreadTcpMng is start!!"); TcpMng->start(); return NULL; };
c39dc4190bcc0a69cd00adbea17b2f799039a457
bc93833a9a2606dd051738dd06d6d17c18cbdcae
/3rdparty/libSGM/src/stereo_sgm.cpp
c6e6b75e9b773b7d9c2278ef12022c9bb803646a
[ "MIT", "Apache-2.0" ]
permissive
Wizapply/OvrvisionPro
f0552626f22d6fe96824034310a4f08ab874b62e
41680a1f9cfd617a9d33f1df9d9a91e8ffd4dc4b
refs/heads/master
2021-11-11T02:37:23.840617
2021-05-06T03:00:48
2021-05-06T03:00:48
43,277,465
30
32
NOASSERTION
2019-12-25T14:07:27
2015-09-28T03:17:23
C
UTF-8
C++
false
false
8,314
cpp
stereo_sgm.cpp
/* Copyright 2016 fixstars Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include <nppi.h> #include <libsgm.h> #include "internal.h" namespace sgm { static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; } static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; } struct CudaStereoSGMResources { void* d_src_left; void* d_src_right; void* d_left; void* d_right; void* d_scost; void* d_matching_cost; void* d_left_disp; void* d_right_disp; void* d_tmp_left_disp; void* d_tmp_right_disp; cudaStream_t cuda_streams[8]; Npp32u median_buffer_size; void* d_median_filter_buffer; void* d_output_16bit_buffer; uint16_t* h_output_16bit_buffer; CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) { if (is_cuda_input(inout_type_)) { this->d_src_left = NULL; this->d_src_right = NULL; } else { CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_)); } CudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamCreate(&this->cuda_streams[i])); } NppiSize roi = { width_, height_ }; NppiSize mask = { 3, 3 }; // width, height NppStatus status; status = nppiFilterMedianGetBufferSize_16u_C1R(roi, mask, &this->median_buffer_size); if (status != 0) { throw std::runtime_error("nppi error"); } CudaSafeCall(cudaMalloc(&this->d_median_filter_buffer, this->median_buffer_size)); // create temporary buffer when dst type is 8bit host pointer if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { this->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_); } else { this->h_output_16bit_buffer = NULL; } } ~CudaStereoSGMResources() { CudaSafeCall(cudaFree(this->d_src_left)); CudaSafeCall(cudaFree(this->d_src_right)); CudaSafeCall(cudaFree(this->d_left)); CudaSafeCall(cudaFree(this->d_right)); CudaSafeCall(cudaFree(this->d_matching_cost)); CudaSafeCall(cudaFree(this->d_scost)); CudaSafeCall(cudaFree(this->d_left_disp)); CudaSafeCall(cudaFree(this->d_right_disp)); CudaSafeCall(cudaFree(this->d_tmp_left_disp)); CudaSafeCall(cudaFree(this->d_tmp_right_disp)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamDestroy(this->cuda_streams[i])); } CudaSafeCall(cudaFree(this->d_median_filter_buffer)); free(h_output_16bit_buffer); } }; StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) : width_(width), height_(height), disparity_size_(disparity_size), input_depth_bits_(input_depth_bits), output_depth_bits_(output_depth_bits), inout_type_(inout_type), cu_res_(NULL) { // check values if (width_ % 2 != 0 || height_ % 2 != 0) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("width and height must be even"); } if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("depth bits must be 8 or 16"); } if (disparity_size_ != 64 && disparity_size_ != 128) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("disparity size must be 64 or 128"); } cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_); } StereoSGM::~StereoSGM() { if (cu_res_) { delete cu_res_; } } void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) { const void *d_input_left, *d_input_right; if (is_cuda_input(inout_type_)) { d_input_left = left_pixels; d_input_right = right_pixels; } else { CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); d_input_left = cu_res_->d_src_left; d_input_right = cu_res_->d_src_right; } sgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]); sgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]); CudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4])); sgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_); sgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams); cudaStreamSynchronize(cu_res_->cuda_streams[2]); cudaStreamSynchronize(cu_res_->cuda_streams[3]); sgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_); sgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, cu_res_->d_median_filter_buffer, width_, height_); sgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, cu_res_->d_median_filter_buffer, width_, height_); sgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_); // output disparity image void* disparity_image = cu_res_->d_tmp_left_disp; if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) { CudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) { *dst = disparity_image; // optimize! no-copy! } else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { CudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); for (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; } } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) { sgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_); } else { std::cerr << "not impl" << std::endl; } } }
def8ef5eae663d2c015a5c360a66dcc5dfccb83e
dbf490d69ed3318e4eaade31cf6bd47f9b38b666
/week-01/day-03/favnumb/main.cpp
c9473cd39fb0ee9891845863c5cd56bdee0e3387
[]
no_license
green-fox-academy/Boritse
138d30c80afc65988f29bd47fbdbc3f816598113
95458e3a71bddb865865f4a8ced52ec2da7bb36b
refs/heads/master
2020-04-16T18:52:02.747715
2019-04-09T06:11:38
2019-04-09T06:11:38
165,837,942
0
0
null
null
null
null
UTF-8
C++
false
false
168
cpp
main.cpp
#include <iostream> int main(int argc, char* args[]) { int favnumb=7; std::cout << "My favourite number is: " << favnumb << "." << std::endl; return 0; }
d3d5245d9f07da6b67533958936e9e5728eadf0a
060850028c6e112f3abfb76a1d0238ef86b2f188
/examples/c++/publication_recon_dataset.cpp
bd77ad46a52e62a13aa5f03a9600cc0058380334
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
welcheb/ISMRMrd_old
911cdea59e8c9a4f3225e9c0d28b66f87e07bbc5
b6dedcaf7fad6be0787391b290cb6a41766f28c4
refs/heads/master
2020-05-20T05:59:55.080741
2014-02-04T10:06:53
2014-02-04T10:06:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,524
cpp
publication_recon_dataset.cpp
/* * test_recon_dataset.cpp * * Created on: Sep 6, 2012 * Author: Michael S. Hansen (michael.hansen@nih.gov) * */ #include <iostream> #include "ismrmrd.h" #include "ismrmrd.hxx" #include "ismrmrd_hdf5.h" #include "fftw3.h" //Helper function for the FFTW library template<typename TI, typename TO> void circshift(TO *out, const TI *in, int xdim, int ydim, int xshift, int yshift) { for (int i =0; i < ydim; i++) { int ii = (i + yshift) % ydim; for (int j = 0; j < xdim; j++) { int jj = (j + xshift) % xdim; out[ii * xdim + jj] = in[i * xdim + j]; } } } #define fftshift(out, in, x, y) circshift(out, in, x, y, (x/2), (y/2)) void print_usage(const char* application) { std::cout << "Usage:" << std::endl; std::cout << " - " << application << " <HDF5_FILENAME> " << "<SCHEMA_FILENAME>" << std::endl; } /* MAIN APPLICATION */ int main(int argc, char** argv) { if (argc < 3) { print_usage(argv[0]); return -1; } std::string datafile(argv[1]); std::string schemafile(argv[2]); std::cout << "Simple ISMRMRD Reconstruction program" << std::endl; std::cout << " - filename: " << datafile << std::endl; std::cout << " - schema : " << schemafile << std::endl; //Let's open the dataset ISMRMRD::IsmrmrdDataset d(datafile.c_str(),"dataset"); //We will start by getting the header and turning it into a C++ class //In order to do true validation of the XML, we will use the XML schema xml_schema::properties props; props.schema_location ("http://www.ismrm.org/ISMRMRD", schemafile); boost::shared_ptr<std::string> xml = d.readHeader(); std::istringstream str_stream(*xml, std::stringstream::in); boost::shared_ptr<ISMRMRD::ismrmrdHeader> cfg; try { cfg = boost::shared_ptr<ISMRMRD::ismrmrdHeader>(ISMRMRD::ismrmrdHeader_ (str_stream,0,props)); } catch (const xml_schema::exception& e) { std::cout << "Failed to parse XML Parameters: " << e.what() << std::endl; } //Let's print some information from the header ISMRMRD::ismrmrdHeader::encoding_sequence e_seq = cfg->encoding(); if (e_seq.size() != 1) { std::cout << "Number of encoding spaces: " << e_seq.size() << std::endl; std::cout << "This simple reconstruction application only supports one encoding space" << std::endl; return -1; } ISMRMRD::encodingSpaceType e_space = (*e_seq.begin()).encodedSpace(); ISMRMRD::encodingSpaceType r_space = (*e_seq.begin()).reconSpace(); ISMRMRD::encodingLimitsType e_limits = (*e_seq.begin()).encodingLimits(); unsigned int slices = e_limits.slice().present() ? e_limits.slice().get().maximum() + 1 : 1; boost::shared_ptr<ISMRMRD::Acquisition> acq = d.readAcquisition(0); unsigned int channels = acq->getActiveChannels(); std::cout << "Encoding Matrix Size : [" << e_space.matrixSize().x() << ", " << e_space.matrixSize().y() << ", " << e_space.matrixSize().z() << "]" << std::endl; std::cout << "Reconstruction Matrix Size : [" << r_space.matrixSize().x() << ", " << r_space.matrixSize().y() << ", " << r_space.matrixSize().z() << "]" << std::endl; std::cout << "Number of channels : " << channels << std::endl; std::cout << "Number of slices : " << slices << std::endl; std::cout << "Number of acquisitions : " << d.getNumberOfAcquisitions() << std::endl; if (e_space.matrixSize().z() != 1) { std::cout << "This simple reconstruction application only supports 2D encoding spaces" << std::endl; return -1; } //Allocate a buffer for the data std::vector<unsigned int> buffer_dimensions; buffer_dimensions.push_back(e_space.matrixSize().x()); buffer_dimensions.push_back(e_space.matrixSize().y()); buffer_dimensions.push_back(channels); buffer_dimensions.push_back(slices); ISMRMRD::NDArrayContainer< std::complex<float> > buffer(buffer_dimensions); //Now loop through and copy data unsigned int number_of_acquisitions = d.getNumberOfAcquisitions(); std::map<unsigned, ISMRMRD::AcquisitionHeader> slice_heads; for (unsigned int i = 0; i < number_of_acquisitions; i++) { //Read one acquisition at a time boost::shared_ptr<ISMRMRD::Acquisition> acq = d.readAcquisition(i); if (acq->isFlagSet(ISMRMRD::FlagBit(ISMRMRD::ACQ_FIRST_IN_SLICE))) { slice_heads[acq->getIdx().slice] = acq->getHead(); } for (unsigned int c = 0; c < channels; c++) { unsigned int offset = acq->getIdx().slice*buffer.dimensions_[0]*buffer.dimensions_[1]*buffer.dimensions_[2] + c * buffer.dimensions_[0]*buffer.dimensions_[1] + acq->getIdx().kspace_encode_step_1*buffer.dimensions_[0]; memcpy(&buffer[offset],&acq->getData()[0]+c*buffer.dimensions_[0]*2,sizeof(float)*2*buffer.dimensions_[0]); } } //Let's FFT the k-space to image for (unsigned int s = 0; s < slices; s++) { for (unsigned int c = 0; c < channels; c++) { fftwf_complex* tmp = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex)*buffer.dimensions_[0]*buffer.dimensions_[1]); if (!tmp) { std::cout << "Error allocating temporary storage for FFTW" << std::endl; return -1; } unsigned int offset = s*buffer.dimensions_[0]*buffer.dimensions_[1]*buffer.dimensions_[2] + c * buffer.dimensions_[0]*buffer.dimensions_[1]; fftshift(reinterpret_cast<std::complex<float>*>(tmp),&buffer.data_[0]+offset,buffer.dimensions_[0],buffer.dimensions_[1]); //Create the FFTW plan fftwf_plan p = fftwf_plan_dft_2d(buffer.dimensions_[1], buffer.dimensions_[0], tmp,tmp, FFTW_BACKWARD, FFTW_ESTIMATE); fftwf_execute(p); fftshift(&buffer.data_[0]+offset,reinterpret_cast<std::complex<float>*>(tmp),buffer.dimensions_[0],buffer.dimensions_[1]); //Clean up. fftwf_destroy_plan(p); fftwf_free(tmp); } } //Now, let's remove the oversampling in the readout and take the magnitude //Allocate a buffer for the data for (unsigned int s = 0; s < slices; s++) { ISMRMRD::NDArrayContainer< float > img; img.dimensions_.push_back(r_space.matrixSize().x()); img.dimensions_.push_back(r_space.matrixSize().y()); img.data_.resize(r_space.matrixSize().x()*r_space.matrixSize().y(), 0.0); for (unsigned int y = 0; y < img.dimensions_[1]; y++) { for (unsigned int x = 0; x < img.dimensions_[0]; x++) { for (unsigned int c = 0; c < channels; c++) { float m = std::abs(buffer.data_[s*buffer.dimensions_[0]*buffer.dimensions_[1]*buffer.dimensions_[2] + c*buffer.dimensions_[0]*buffer.dimensions_[1] + y*buffer.dimensions_[0] + x + ((e_space.matrixSize().x()-r_space.matrixSize().x())>>1)]); img.data_[y*img.dimensions_[0]+x] += m*m; } } } for (unsigned int i = 0; i < img.elements(); i++) img[i] = std::sqrt(img[i]); //Let's write the reconstructed image straight in the same data file ISMRMRD::ImageHeader img_h; img_h.channels = 1; img_h.image_data_type = ISMRMRD::DATA_FLOAT; //This is actually just guidance img_h.image_type = ISMRMRD::TYPE_REAL; //This is actually just guidance img_h.slice = s; memcpy(img_h.position, slice_heads[s].position, sizeof(float)*3); memcpy(img_h.read_dir, slice_heads[s].read_dir, sizeof(float)*3); memcpy(img_h.phase_dir, slice_heads[s].phase_dir, sizeof(float)*3); memcpy(img_h.slice_dir, slice_heads[s].slice_dir, sizeof(float)*3); memcpy(img_h.patient_table_position, slice_heads[s].patient_table_position, sizeof(float)*3); //And so on //Now append, we will append image and header separately (in two different datasets) d.appendImageHeader(img_h,"myimage.head"); d.appendArray(img,"myimage.img"); } return 0; }
12ebb3d1b7d3580532be8e5b090b61958284fcee
cf617bbeaab3328813a61b3e103d6d6e2b9d3d67
/node/src/node/node.cpp
63a39e8a5262861ad261d053d8e589680749f96e
[ "MIT" ]
permissive
OAkyildiz/src_capstone
a77b1b6a0f01b45a970f0a5d49bab609adff9e8a
4253962d7c01985c15f440cd4eab37d5c45f7af6
refs/heads/master
2020-12-26T02:22:06.281172
2016-12-16T04:45:11
2016-12-16T04:45:11
68,628,342
0
0
null
2016-12-02T22:15:34
2016-09-19T17:16:30
C++
UTF-8
C++
false
false
1,553
cpp
node.cpp
/* * node.cpp * * Created on: Oct 24, 2016 * Author: oakyildiz, Ozan Akyıldız * Email: oakyildiz@wpi.edu * */ #include "node/node.h" double RATE = 60; Node::Node(int argc, char** argv): nh_(0), pnh_(0), init_argc(argc), init_argv(argv) {} Node::~Node() { if(ros::isStarted()) { ros::shutdown(); // explicitly needed since we use ros::start(); ros::waitForShutdown(); } delete nh_; delete pnh_; wait(); } bool Node::init(const std::string &name) { ros::init(init_argc, init_argv, name); if ( ! ros::master::check() ) { ROS_ERROR("Cannot communicate with the ROSMASTER!"); return false; } setup(); return true; } bool Node::init(const std::string &name, const std::string &master_url, const std::string &host_url) { std::map<std::string,std::string> remappings; remappings["__master"] = master_url; remappings["__hostname"] = host_url; ros::init(remappings,name); if ( ! ros::master::check() ) { ROS_ERROR("Cannot communicate with the ROSMASTER!"); return false; } setup(); return true; } bool Node::setup() { nh_ = new ros::NodeHandle(); pnh_ = new ros::NodeHandle("~"); pnh_->param<double>("rate", RATE, 30); setupParams(); setupCustom(); /*subs and pubs*/ return true; } void Node::run() { ros::Rate node_rate(RATE); //talk about redundancy // Startup ROS spinner in background ros::AsyncSpinner spinner(2); spinner.start(); int l=0; while( ros::ok( )){ ros::spinOnce(); node_rate.sleep(); operation(); l++; ROS_DEBUG("node spinning"); } }
b3ee6a8c1d3ea08d2ee05289485ae533ca3f7b20
1b3688fb1fced72b358429c30be0afdee79fe27b
/data/molecular_dynamics/experimental_salts/PPY.TF2.298.comremoved.Cp
f1ca2142d2c697a571a0fe266cb5d69ca371d3fa
[ "MIT" ]
permissive
wesleybeckner/adaptive_learning_salts
25661b292fcebfe0395ce2d0a0761552519015ca
51cc1cf74cef14d45592e5e2894c0b89304a3e8c
refs/heads/master
2020-04-07T01:09:20.803206
2019-03-27T13:09:43
2019-03-27T13:09:43
157,932,653
1
2
null
null
null
null
UTF-8
C++
false
false
40
cp
PPY.TF2.298.comremoved.Cp
559.134 572.214 550.939 557.914 553.233
b080c2109e5db0c0255f2bec410d8942d5aa9e56
7dadbd48949e6a1f216fa90e2d7ff8f7426bab90
/src/cuda/api/multi_wrapper_impls/stream.hpp
ed2cc65aa21b8c88fd8b8419f3d303afad120400
[ "BSD-3-Clause" ]
permissive
eyalroz/cuda-api-wrappers
b87b968acc032338d102e334a51cbdd5a2ae159d
1833895b6a6ce905b6d3ac38226de6e0a030f09e
refs/heads/master
2023-09-04T01:23:10.874145
2023-07-08T09:55:38
2023-07-08T10:48:12
73,505,627
656
90
BSD-3-Clause
2023-03-24T21:32:14
2016-11-11T19:31:08
C++
UTF-8
C++
false
false
5,272
hpp
stream.hpp
/** * @file * * @brief Implementations requiring the definitions of multiple CUDA entity proxy classes, * and which regard streams. Specifically: * * 1. Functions in the `cuda::stream` namespace. * 2. Methods of @ref `cuda::stream_t` and possibly some relates classes. */ #pragma once #ifndef MULTI_WRAPPER_IMPLS_STREAM_HPP_ #define MULTI_WRAPPER_IMPLS_STREAM_HPP_ #include "../array.hpp" #include "../device.hpp" #include "../event.hpp" #include "../kernel_launch.hpp" #include "../pointer.hpp" #include "../stream.hpp" #include "../primary_context.hpp" #include "../kernel.hpp" #include "../current_context.hpp" #include "../current_device.hpp" namespace cuda { namespace stream { namespace detail_ { inline ::std::string identify(const stream_t& stream) { return identify(stream.handle(), stream.context().handle(), stream.device().id()); } #if CUDA_VERSION >= 9020 inline device::id_t device_id_of(stream::handle_t stream_handle) { return context::detail_::get_device_id(context_handle_of(stream_handle)); } #endif // CUDA_VERSION >= 9020 inline void record_event_in_current_context( device::id_t current_device_id, context::handle_t current_context_handle_, stream::handle_t stream_handle, event::handle_t event_handle) { auto status = cuEventRecord(event_handle, stream_handle); throw_if_error_lazy(status, "Failed scheduling " + event::detail_::identify(event_handle) + " on " + stream::detail_::identify(stream_handle, current_context_handle_, current_device_id)); } } // namespace detail_ inline stream_t create( const device_t& device, bool synchronizes_with_default_stream, priority_t priority) { auto pc = device.primary_context(do_not_hold_primary_context_refcount_unit); device::primary_context::detail_::increase_refcount(device.id()); return create(pc, synchronizes_with_default_stream, priority, do_hold_primary_context_refcount_unit); } inline stream_t create( const context_t& context, bool synchronizes_with_default_stream, priority_t priority, bool hold_pc_refcount_unit) { return detail_::create( context.device_id(), context.handle(), synchronizes_with_default_stream, priority, hold_pc_refcount_unit); } } // namespace stream inline void stream_t::enqueue_t::wait(const event_t& event_) const { CAW_SET_SCOPE_CONTEXT(associated_stream.context_handle_); // Required by the CUDA runtime API; the flags value is currently unused static constexpr const unsigned int flags = 0; auto status = cuStreamWaitEvent(associated_stream.handle_, event_.handle(), flags); throw_if_error_lazy(status, "Failed scheduling a wait for " + event::detail_::identify(event_.handle()) + " on " + stream::detail_::identify(associated_stream)); } inline event_t& stream_t::enqueue_t::event(event_t& existing_event) const { auto device_id = associated_stream.device_id_; auto context_handle = associated_stream.context_handle_; auto stream_context_handle_ = associated_stream.context_handle_; if (existing_event.context_handle() != stream_context_handle_) { throw ::std::invalid_argument( "Attempt to enqueue " + event::detail_::identify(existing_event) + " on a stream in a different context: " + stream::detail_::identify(associated_stream)); } context::current::detail_::scoped_ensurer_t ensure_a_context{context_handle}; stream::detail_::record_event_in_current_context( device_id, context_handle, associated_stream.handle_,existing_event.handle()); return existing_event; } inline event_t stream_t::enqueue_t::event( bool uses_blocking_sync, bool records_timing, bool interprocess) const { auto context_handle = associated_stream.context_handle_; CAW_SET_SCOPE_CONTEXT(context_handle); // Note that even if this stream is in the primary context, the created event auto ev = event::detail_::create_in_current_context( associated_stream.device_id_, context_handle, do_not_hold_primary_context_refcount_unit, uses_blocking_sync, records_timing, interprocess); // will not extend the context's life. If the user wants that extension, they // should have the _stream_ hold a reference to the primary context. this->event(ev); return ev; } inline device_t stream_t::device() const noexcept { return cuda::device::wrap(device_id_); } inline context_t stream_t::context() const noexcept { static constexpr const bool dont_take_ownership { false }; return context::wrap(device_id_, context_handle_, dont_take_ownership); } #if CUDA_VERSION >= 11000 inline void copy_attributes(const stream_t &dest, const stream_t &src) { #ifndef NDEBUG if (dest.device() != src.device()) { throw ::std::invalid_argument("Attempt to copy attributes between streams on different devices"); } if (dest.context() != src.context()) { throw ::std::invalid_argument("Attempt to copy attributes between streams on different contexts"); } #endif CAW_SET_SCOPE_CONTEXT(dest.context_handle()); auto status = cuStreamCopyAttributes(dest.handle(), src.handle()); throw_if_error_lazy(status, "Copying attributes from " + stream::detail_::identify(src) + " to " + stream::detail_::identify(src)); } #endif // CUDA_VERSION >= 11000 } // namespace cuda #endif // MULTI_WRAPPER_IMPLS_STREAM_HPP_
da4070097641004d5d0b96e859e5af6838691a34
d2a9836887261aaf3de0a4bd03ee0b3fadeefbd1
/main.cpp
2c180d1e5fb19f675c7bb72f6bc8e7286ccd1738
[]
no_license
shadykdc/Enigma_Machine
f46cbc90c0808a1c2a091896c735e5ac2abe8e33
d188003562aae38499b1365ec6a3c1d483f289f1
refs/heads/master
2021-01-20T20:09:06.043709
2016-06-23T14:10:09
2016-06-23T14:10:09
61,751,585
0
0
null
null
null
null
UTF-8
C++
false
false
4,484
cpp
main.cpp
// Integrated Programming Laboratory // Exercise 2, The Enigma Machine // Kathryn Shea, November 23, 2015 #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include "classes.h" #include "errors.h" #include "helpers.h" #include "checks.h" using namespace std; int main(int argc, char **argv) { /* count how many parts and rotors there are */ int rotor_count = argc-4; // = -1 if there are no rotors int part_count = count_parts(rotor_count); /* check the number of configuration files */ if(argc < 3 || argc == 4){ cerr << "Insufficient number of configuration parameters: "; cerr << argc-1 << ". (Please enter 2 or 4 or more)." << endl; return INSUFFICIENT_NUMBER_OF_PARAMETERS; } /* create plugboard and check plugboard file */ ifstream ins; int error = check_plugboard(argv[1], ins); if(error > 0){ return(error);} Plugboard pb; ins.open(argv[1]); if (!pb.assign_values(ins)){ cerr << "Configuration file: " << argv[1] << endl; return IMPOSSIBLE_PLUGBOARD_CONFIGURATION; } ins.close(); /* create reflector and check reflector file */ error = check_reflector(argv[2], ins); if(error > 0){ return(error);} Reflector ref; ins.open(argv[2]); if (!ref.assign_values(ins)){ cerr << "Configuration file: " << argv[2] << endl; return INVALID_REFLECTOR_MAPPING; } ins.close(); /* check rotor files */ if(rotor_count > 0){ for(int i = 3; i < argc-1; i++){ error = check_rotor(argv[i], ins); if(error > 0){ return(error);} } error = check_position(argv[argc-1], ins, rotor_count); if(error > 0){ return(error);} } Rotor *rotors[rotor_count]; if(rotor_count > 0){ /* create an array of pointers to rotors */ for (int i = 0; i < rotor_count; i++){ rotors[i] = new Rotor(); } /* create rotors */ for (int i = 0; i < rotor_count; i++){ if (!(rotors[i])->assign_values(argv[part_count-i])){ return(INVALID_ROTOR_MAPPING); } } /* import rotor positions */ ins.open(argv[part_count+1]); int num; int i = 0; while (i < rotor_count && ins >> ws >> num){ rotors[rotor_count-i-1]->assign_position(num); i++; } ins.close(); } /* get input from user */ char input; while(cin >> ws >> input) { int enigma_in = input - 65; if(enigma_in > 25 || enigma_in < 0){ cerr << input << " is not a valid input character (input characters"; cerr << " must be upper case letters A-Z)!" << endl; /* delete rotors array */ for (int i = 0; i < rotor_count; i++){ delete rotors[i]; } return(INVALID_INPUT_CHARACTER); } if (rotor_count > 0){ /* rotate the rotors */ rotors[0]->rotate(); int i = 0; bool keep_going = true; while(keep_going && i < rotor_count-1){ if(rotors[i]->is_a_notch(rotors[i]->get_position())){ rotors[i+1]->rotate(); } else { keep_going = false; } if (!(rotors[i+1]->is_a_notch(rotors[i+1]->get_position()))){ keep_going = false; } i++; } } /* run the plugboard */ int letter = pb.swap(enigma_in); if(rotor_count < 0){ /* if there are no rotors, run the plugboard and reflector and print */ letter = ref.swap(letter); letter = pb.swap(letter); char output = letter+65; cout << output; } else { /* run the rotors */ letter = letter + rotors[0]->get_position(); letter = fix_input(letter); letter = rotors[0]->swap_fwd(letter); for(int i = 1; i < rotor_count; i++){ letter = letter + rotors[i]->get_position() - rotors[i-1]->get_position(); letter = fix_input(letter); letter = rotors[i]->swap_fwd(letter); } /* run the reflector */ letter = letter - rotors[rotor_count-1]->get_position(); letter = fix_input(letter); letter = ref.swap(letter) + rotors[rotor_count-1]->get_position(); letter = fix_input(letter); /* run the rotors in reverse */ for(int i = rotor_count-1; i > 0; i--){ letter = rotors[i]->swap_rev(letter) - rotors[i]->get_position() + rotors[i-1]->get_position(); letter = fix_input(letter); } letter = rotors[0]->swap_rev(letter) - rotors[0]->get_position(); letter = fix_input(letter); /* run the plugboard */ letter = pb.swap(letter); letter = fix_input(letter); /* print the output */ char output = letter+65; cout << output; } // if / else bracket } // while loop bracket -- didn't want my code to be really narrow /* delete rotors array */ for (int i = 0; i < rotor_count; i++){ delete rotors[i]; } /* we're done here */ return NO_ERROR; }
9259a90f76257407955158816f72bb20f22db711
5db5ddf10fb0b71f1fd19cb93f874f7e539e33eb
/Tech/src/foundation/stream/poutputstream.cpp
f8e0b105c3921aa630ce2bb73236abf0edb28ced
[]
no_license
softwarekid/FutureInterface
13b290435c552a3feca0f97ecd930aa05fa2fb25
55583a58297a5e265953c36c72f41ccb8bac3015
refs/heads/master
2020-04-08T04:42:21.041081
2014-07-25T01:14:34
2014-07-25T01:14:34
22,280,531
0
1
null
null
null
null
UTF-8
C++
false
false
5,558
cpp
poutputstream.cpp
// poutputstream.cpp // Write to file/memory/other. // // Copyright 2012 - 2014 Future Interface. // This software is licensed under the terms of the MIT license. // // Hongwei Li lihw81@gmail.com // // #include "poutputstream.h" #include <PFoundation/pnew.h> #include <PFoundation/plog.h> #include <PFoundation/passert.h> #include "pstreamobject_private.h" POutputStream::POutputStream() : PAbstractStream() { m_writtenBytes = 0; } POutputStream::~POutputStream() { } pbool POutputStream::createFromFile(const pchar *filePath, PStreamEndianessEnum endianness) { PASSERT(m_object == P_NULL); if (m_object != P_NULL) { PLOG_ERROR("Unable to reopen the stream for writing"); return false; } m_object = PNEW(PStreamFile(filePath, true)); m_object->open(); m_endianness = endianness; return true; } pbool POutputStream::createFromMemory(puint8 *buffer, puint32 size, PStreamEndianessEnum endianness) { PASSERT(m_object == P_NULL); if (m_object != P_NULL) { PLOG_ERROR("Unable to reopen the stream for writing"); return false; } m_object = PNEW(PStreamMemory(buffer, size)); m_object->open(); m_endianness = endianness; return true; } pbool POutputStream::writeBytes(puint32 nbytes, const puint8* buffer) { PASSERT(m_object != P_NULL); if (m_object == P_NULL) { PLOG_ERROR("Output stream is unavailable"); return false; } puint32 bytesWritten; if (!m_object->write(nbytes, bytesWritten, buffer)) { return false; } if (bytesWritten != nbytes) { PLOG_WARNING("The written data is less than expected"); m_writtenBytes = bytesWritten; return false; } m_writtenBytes += bytesWritten; return true; } pbool POutputStream::write(puint32 nbytes, puint32& bytesWritten, const puint8* buffer) { return m_object->write(nbytes, bytesWritten, buffer); } pbool POutputStream::writeUint8(puint8 value) { return writeBytes(1, &value); } pbool POutputStream::writeInt8(pint8 value) { puint8 buffer[1] = {value}; return writeBytes(1, buffer); } pbool POutputStream::writeUint16(puint16 value) { puint8 buffer[2]; switch (m_endianness) { case P_STREAM_ENDIANNESS_BIG: buffer[0] = (puint8)(value); buffer[1] = (puint8)(value >> 8); break; case P_STREAM_ENDIANNESS_LITTLE: buffer[0] = (puint8)(value >> 8); buffer[1] = (puint8)(value); break; case P_STREAM_ENDIANNESS_PLATFORM: { puint8* valueBuffer = (puint8*)&value; buffer[0] = valueBuffer[0]; buffer[1] = valueBuffer[1]; } break; default: PLOG_ERROR("Invalid endianness"); return false; } if (!writeBytes(2, buffer)) { return false; } return true; } pbool POutputStream::writeInt16(pint16 value) { puint16 v = (puint16)value; if (!writeUint16(v)) { return false; } return true; } pbool POutputStream::writeUint32(puint32 value) { puint8 buffer[4]; switch (m_endianness) { case P_STREAM_ENDIANNESS_BIG: buffer[0] = (puint8)(value >> 24); buffer[1] = (puint8)(value >> 16); buffer[2] = (puint8)(value >> 8); buffer[3] = (puint8)value; break; case P_STREAM_ENDIANNESS_LITTLE: buffer[0] = (puint8)value; buffer[1] = (puint8)(value >> 8); buffer[2] = (puint8)(value >> 16); buffer[3] = (puint8)(value >> 24); break; case P_STREAM_ENDIANNESS_PLATFORM: { puint8* valueBuffer = (puint8*)&value; buffer[0] = valueBuffer[0]; buffer[1] = valueBuffer[1]; buffer[2] = valueBuffer[2]; buffer[3] = valueBuffer[3]; } break; default: PLOG_ERROR("Invalid endianness"); return false; } if (!writeBytes(4, buffer)) { return false; } return true; } pbool POutputStream::writeInt32(pint32 value) { puint32 v; v = (puint32)value; if (!writeUint32(v)) { return false; } return true; } pbool POutputStream::writeFloat32(pfloat32 value) { puint32 v = *(puint32*)&value; return writeUint32(v); } pbool POutputStream::writeBoolean(pbool value) { puint8 buffer[1]; if (value) { buffer[0] = 1; } else { buffer[0] = 0; } return writeBytes(1, buffer); } pbool POutputStream::writeString(const PString& value) { return writeBytes(value.length(), (const puint8*)value.c_str()) && writeUint8(0); } pbool POutputStream::writeString(const pchar* value) { const pchar* p = value; do { if (!writeInt8(*p)) { return false; } p++; } while (*p != 0); return true; } void POutputStream::flush() { PASSERT(m_object != P_NULL); if (m_object == P_NULL) { PLOG_ERROR("Output stream is unavailable"); return ; } m_object->flush(); } void POutputStream::skipBytes(puint32 nbytes) { PASSERT(m_object != P_NULL); if (m_object == P_NULL) { PLOG_ERROR("Output stream is unavailable"); return ; } m_object->skip(nbytes); m_writtenBytes += nbytes; }
218ba608464db0bb07197b8f7420723ca1286ef7
5dd63addadcec9ffadaa0c5b8f6aad2eb12c6d9e
/server/session.h
6bc8cc77d257a2e0a54a1861b45ecaa20adec424
[]
no_license
AlexisVaBel/otus-cpp-hw_13
1c73e26789f509390dc1f33d411367d204639f48
985607d388d71c5db758520fe76c6adedbc658b2
refs/heads/master
2020-07-29T08:26:09.352848
2019-09-26T06:24:35
2019-09-26T06:24:35
209,729,978
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
h
session.h
#ifndef SESSION_H #define SESSION_H #include <iostream> #include <set> #include <boost/bind.hpp> #include <boost/asio.hpp> #include "../threader/threadpool.h" #include "../db_struct/basicdb.h" #include "../cmds/dbprocessor.h" using boost::asio::ip::tcp; class Session: public std::enable_shared_from_this<Session> { public: Session(boost::shared_ptr<boost::asio::io_service> ioService, std::shared_ptr<ThreadPool> threadPool, std::shared_ptr<BasicDB> db); ~Session(); tcp::socket &socket(); void start(); void stop(); void handle_read(const boost::system::error_code &ecode, size_t bytes); void handle_write(const boost::system::error_code &ecode, size_t bytes); private: boost::shared_ptr<boost::asio::io_service> m_ioService; std::shared_ptr<tcp::socket> m_socket; enum { max_length = 1024}; char m_data[max_length]; std::shared_ptr<ThreadPool> m_threadPool; std::shared_ptr<BasicDB> m_db; std::shared_ptr<DBProcessor> m_procsDB; boost::asio::streambuf write_buffer; void on_command(); }; #endif // SESSION_H
261fa884e6ec238329e4ac61ad97f63cdb8aa8bd
7f53982a8b84a05d63e3e3b2f57c379da02d762a
/jsc/JavaScriptCore_cc153d71/unified-sources/UnifiedSource7.cpp
7eecf2eb3dc731f727c525f7eecc192ba9e5a885
[]
no_license
ufwt/browser-exploitation
4f9a6a1efe6bf654b4bf78e43fe2bccaa60d7974
768e4751a42a2cb27238542bc5bfbae140a848cf
refs/heads/master
2023-07-07T23:49:10.319022
2021-08-08T13:46:34
2021-08-08T13:46:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
UnifiedSource7.cpp
#include "assembler/MacroAssemblerMIPS.cpp" #include "assembler/MacroAssemblerPrinter.cpp" #include "assembler/MacroAssemblerX86Common.cpp" #include "assembler/PerfLog.cpp" #include "assembler/Printer.cpp" #include "assembler/ProbeContext.cpp" #include "assembler/ProbeStack.cpp"
e253e6ed834fe32c54b4f1432162de92c9ff15b0
6a3ad56a2c029ec12fad89fab21bacb64df01289
/SHOOTER.CPP
a3607a043f7520a2ec0b6287ea20ad6bf61e3429
[]
no_license
yashdhing/C-Projects-Before-standardization-
eb28a630c2d6f10cf84c128b53421c5ed833e381
5dac0292c3875f1e6aa45d4a2d1886b02de079ad
refs/heads/master
2020-04-14T03:26:13.358124
2018-12-30T18:18:08
2018-12-30T18:18:08
163,607,820
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
cpp
SHOOTER.CPP
#include<iostream.h> #include<graphics.h> #include<conio.h> #include<dos.h> #include<stdlib.h> void main() //Yash's upgraded version {randomize(); int gdriver=DETECT,gmode; initgraph(&gdriver,&gmode,"D:\\bgi"); int k=5,t=5,i=0,Ly,midx=200,score=0,midy=0,Px=15,Py=244,rad=10; setbkcolor(2); for( ;t>0 ;midy+=5) { for(Ly=40;Ly<=220;Ly+=10) line(3,Ly,7,Ly); outtextxy(8,38,"40"); outtextxy(8,78,"80"); outtextxy(8,118,"120"); outtextxy(8,158,"160"); outtextxy(8,198,"200"); setcolor(1); setfillstyle(SOLID_FILL,4); circle(midx,midy,rad); line(midx,midy+10,midx,midy+17); floodfill(midx,midy,1); setcolor(1); setfillstyle(1,8); rectangle(0,240,15,247); floodfill(6,246,1); rectangle(0,247,5,254); floodfill(4,248,1); pieslice(5,247,270,360,3); rectangle(550,15,630,75); outtextxy(565,22,"SCORE : "); gotoxy(74,3); cout<<score; gotoxy(72,4); ////////////////////////////////////////////// for(k=t;k>0;k--) cout<<(char)3; if(midy==400) { t--; b: getch(); Px=15; midy=0; midx=200+random(400); } if(kbhit()) { for(i=-1;i<2;i++) { putpixel(Px+i,Py,1); putpixel(Px,Py+i,1); putpixel(Px+i,Py+i,1); } if(Px>midx-10&&Px<midx+10&&Py>midy-10&&Py<midy+10) { for(i=5;i<=10;i++) { setcolor(i); setfillstyle(7+random(6),4); circle(midx,midy,rad+i) ; floodfill(midx,midy,i); delay(175); cleardevice(); } delay(100); score+=10; goto b; } Px+=15; } delay(100); cleardevice(); } closegraph(); }
00c6bebbe9f412d4930967d37b9c9f2eb0fadc52
d34f07b5399ec91bf0998a94c55e69f3da45f5ae
/stree/builder.hpp
b0a16dcfab3ef01df5012b98954b436e3978fd05
[]
no_license
mngr777/stree
ad093e7df922b752912fdf6221a038d6604b9902
49f372dffaf60f714eabfdaf844931e92bbcd98e
refs/heads/master
2022-04-27T05:30:31.669423
2022-03-13T21:55:38
2022-03-13T21:55:38
91,375,024
0
0
null
null
null
null
UTF-8
C++
false
false
858
hpp
builder.hpp
#ifndef STREE_BUILDER_HPP_ #define STREE_BUILDER_HPP_ #include <stack> #include <stree/environment.hpp> #include <stree/tree.hpp> namespace stree { class Builder { public: Builder(Environment& env); void set(const std::string& name); void set(const SymbolPtr& symbol); void set(const Value& value); void up(unsigned n = 1); void down(unsigned n); void reset(); bool is_valid() const; Id root() { return root_; } Environment& env() { return env_; } private: struct StackItem { StackItem(const Id& id, unsigned n) : id(id), n(n) {} Id id; unsigned n; }; using Stack = std::stack<StackItem>; Id root_; void set_id(const Id& id); void set_root(const Id& id); Environment& env_; Stack stack_; }; } #endif
017a978169b39aabd1297fc9ffc530baf952c322
4613c0fd08530adf61cbae5e425b9f9e1d302588
/test/geometry/testaabb.cpp
31fe620e7704d620a6bb407d33412e7b18588cff
[]
no_license
xchrdw/voxellancer
b0e39a883cc7d9a6607985e72267c205aae23b20
9d468a79c0c96a12170061958a4f06a8f8a9b197
refs/heads/master
2021-04-29T17:55:47.628442
2014-08-24T21:14:02
2014-08-24T21:14:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,016
cpp
testaabb.cpp
#include <bandit/bandit.h> #include <iostream> #include "geometry/aabb.h" #include "../bandit_extension/vec3helper.h" #include "property/propertymanager.h" using namespace bandit; go_bandit([](){ describe("AABB", [](){ PropertyManager::instance()->reset(); PropertyManager::instance()->load("data/config.ini"); PropertyManager::instance()->load("data/voxels.ini", "voxels"); before_each([&](){ }); it("has correct bounds", [&]() { AABB a(glm::vec3(3, -2, 1), glm::vec3(8, 5, 3)); AssertThat(a.extent(XAxis), Equals(5)); AssertThat(a.extent(YAxis), Equals(7)); AssertThat(a.extent(ZAxis), Equals(2)); AssertThat(a.axisMin(XAxis), Equals(3)); AssertThat(a.axisMax(XAxis), Equals(8)); AssertThat(a.axisMin(ZAxis), Equals(1)); AssertThat(a.axisMax(ZAxis), Equals(3)); AssertThat(a.axisMax(YAxis), Equals(5)); AssertThat(a.axisMin(YAxis), Equals(-2)); }); it("intersects", [&](){ AABB a(glm::vec3(0, 0, 0), glm::vec3(1, 1, 1)); AABB b(glm::vec3(0, 0, 0), glm::vec3(1, 1, 1)); AssertThat(a.intersects(b) && b.intersects(a), Equals(true)); a.move(XAxis, 1); AssertThat(!(a.intersects(b) && b.intersects(a)), Equals(true)); b.move(XAxis, 0.2f); AssertThat(a.intersects(b) && b.intersects(a), Equals(true)); a.move(glm::vec3(-1.5, -0.8, -0.8)); b.move(glm::vec3(-0.2, 0, 0)); AssertThat(a.intersects(b) && b.intersects(a), Equals(true)); }); it("contains", [&](){ AABB a(glm::vec3(0, 0, 0), glm::vec3(1, 1, 1)); AABB b(glm::vec3(0, 0, 0), glm::vec3(1, 1, 1)); AABB c(glm::vec3(0, 0, 0), glm::vec3(0.3, 0.4, 1.5)); AABB d(glm::vec3(0, 0, 0), glm::vec3(0.3, 0.4, 0.5)); AABB e(glm::vec3(-1, 0.2, 0.2), glm::vec3(0.3, 0.4, 0.5)); AssertThat(a.contains(b) && b.contains(a), Equals(true)); AssertThat(!a.contains(c), Equals(true)); AssertThat(!a.contains(e), Equals(true)); AssertThat(a.contains(d), Equals(true)); a.move(XAxis, 0.1f); AssertThat(!(a.contains(b) && b.contains(a)), Equals(true)); d.move(glm::vec3(0.2, 0.4, 0.1)); AssertThat(a.contains(d), Equals(true)); d.move(XAxis, 0.7f); AssertThat(!a.contains(d), Equals(true)); a.move(XAxis, 0.3f); AssertThat(a.contains(d), Equals(true)); }); it("splits", [&](){ AABB a(glm::vec3(2, 3, 5), glm::vec3(12, 100, 25)); AABB b, c; AABB d, e; for(int _axis = 0; _axis < 3; _axis++) { Axis axis = (Axis)_axis; a.split(b, c, axis); AssertThat(a.contains(b) && a.contains(c), Equals(true)); AssertThat(b.extent(XAxis), Equals(c.extent(XAxis))); AssertThat(b.extent(YAxis), Equals(c.extent(YAxis))); AssertThat(b.extent(ZAxis), Equals(c.extent(ZAxis))); AssertThat(b.extent(axis) + c.extent(axis) , EqualsWithDelta(a.extent(axis), 0.1f)); AssertThat(b.axisMin(axis) + b.extent(axis) , EqualsWithDelta(c.axisMin(axis), 0.1f)); } }); it("recursiveSplits", [&]() { AABB a(glm::vec3(2, 3, 5), glm::vec3(10, 67, 37)); std::list<AABB> splitted = a.recursiveSplit(2, XAxis); AssertThat(splitted.size(), Equals(8)); std::vector<AABB> splittedv(splitted.begin(), splitted.end()); for(int b = 0; b < 8; b++) { AssertThat(splittedv[b].extent(XAxis), Equals(4)); AssertThat(splittedv[b].extent(YAxis), Equals(32)); AssertThat(splittedv[b].extent(ZAxis), Equals(16)); } }); }); });
dd59109857ed547290b4e04670852758692a0395
27408150237ea8838f2ca442fcf987cf8287d224
/src/exp_smoothing.cpp
e3aa769730a4dbb4d36c1d3ba5291879e695f19f
[]
no_license
dcmde/filters
8f5fca0e5db73bfc7149639a5b7122acbea6519b
037114e55f7ec00ada52489c8e5b1cfddf1ce9d2
refs/heads/main
2023-04-16T03:35:19.565367
2021-04-12T13:11:49
2021-04-12T13:11:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
857
cpp
exp_smoothing.cpp
#include <iostream> #include <fstream> #include "ExpSmoothing.hpp" int main(int argc, char *argv[]) { double alpha, x0, temp; std::string line; if (argc != 4) { std::cout << "Enter : file_name alpha init_value" << std::endl; return 0; } alpha = std::stod(argv[2]); x0 = std::stod(argv[3]); std::ifstream ifstream(argv[1]); std::ofstream ofstream("exp_smt.txt"); if (!ifstream.is_open()) { std::cout << "Cannot open file" << std::endl; return 0; } ExpSmoothing expSmoothing(alpha, x0); ofstream << expSmoothing.get() << std::endl; while (std::getline(ifstream, line)) { temp = std::stod(line); ofstream << expSmoothing.update(temp) << std::endl; } std::cout << "Done : exp_smt.txt" << std::endl; ifstream.close(); ofstream.close(); }
9422071bf7f0ba62b4bbefa8ab16b923a65b066e
0f0ef090f5e9c15745f9550a084f270d796a4e82
/postmidsem/hashing/udbhavhashing/hashwithoutclass.cpp
c55e0f0a93e178e3641fd05fd0b01ebc19292450
[]
no_license
udbhav-chugh/CS210-DataStructuresLab
ea97f58f3ff2959d515de59e909197711108b081
fa7d68040c78b6cafe5a33e5424da086d757ff3c
refs/heads/master
2020-04-17T14:54:29.566133
2019-05-27T23:02:06
2019-05-27T23:02:06
166,677,003
0
0
null
null
null
null
UTF-8
C++
false
false
2,603
cpp
hashwithoutclass.cpp
#include<bits/stdc++.h> using namespace std; int hashfunc(int val,int n) { return val%n; } struct node { int data; node* next; node(int d) { data=d; next=NULL; } }; struct hashtab { int bucketsize; node* *arr; hashtab(int size); void insert(int val); int search(int val); int del(int val); void ptable(); }; hashtab:: hashtab(int size) { bucketsize=size; arr=new node*[size]; } void hashtab:: insert(int val) { int hashval=hashfunc(val,bucketsize); node* temp=new node(val); node * t=arr[hashval]; arr[hashval]=temp; temp->next=t; } int hashtab:: search(int val) { int hashval=hashfunc(val,bucketsize); node * temp=arr[hashval]; while(temp!=NULL) { if(temp->data==val) return hashval; temp=temp->next ; } return -1; } int hashtab:: del(int val) { int hashval=hashfunc(val,bucketsize); node * temp=arr[hashval]; node * prev=NULL; while(temp!=NULL) { if(temp->data==val) { if(prev==NULL) { arr[hashval]=temp->next; delete temp; return 1; } else { prev->next=temp->next; delete temp; return 1; } } prev=temp; temp=temp->next; } return 0; } void hashtab:: ptable() { for(int i=0;i<bucketsize;i++) { node * temp=arr[i]; cout<<"BUCKET "<<i<<": "; while(temp!=NULL) { cout<<temp->data<<" "; temp=temp->next; } cout<<endl; } } int main() { int n; int val,option; hashtab *h=NULL; do { cout<<"\nSelect option:\n1)Create hashtabtable\n2)Insert\n3)Search value\n4)Delete value\n5)Print table\nAny other value to Exit\n"; cin>>option; switch(option) { case 1: { cout<<"Enter number of buckets: "; cin>>n; h=new hashtab(n); break; } case 2: { if(h==NULL) { cout<<"create table first\n"; break; } cout<<"Enter value: "; cin>>val; h->insert(val); break; } case 3: { if(h==NULL) { cout<<"create table first\n"; break; } cout<<"Enter value: "; cin>>val; int temp=h->search(val); if(temp==-1) cout<<val<<" not found\n"; else cout<<val<<" found at bucket number: "<<temp<<endl; break; } case 4: { if(h==NULL) { cout<<"create table first\n"; break; } cout<<"Enter value: "; cin>>val; int temp=h->del(val); if(temp==0) cout<<val<<" not found\n"; else cout<<val<<" deleted.\n"; break; } case 5: { if(h==NULL) { cout<<"create table first\n"; break; } h->ptable(); break; } default: { return 0; } } }while(1); }
9096825572e39ac52fd9d927c97539cde13d635c
55eaef34ac69f69625bfcf86359de2cc056d4a71
/Source for linux/pawn.h
40d0f1865e6a38c52db688f77d04c44041e23b29
[]
no_license
prototype2904/StetskevichChulanov2381
bdd057d8827934fe99adfbe5e6a83625b1282cbf
5cae416398aeed72f1e2bb1c15e5152e4162f772
refs/heads/master
2021-01-23T13:18:11.068654
2015-05-25T16:44:09
2015-05-25T16:44:09
30,931,336
2
0
null
null
null
null
UTF-8
C++
false
false
596
h
pawn.h
#ifndef PAWN_H #define PAWN_H #include "square.h" //class of pawn. class Pawn : public Figure { private: Square* nextMove;//next Move directly bool firstMove; //is it first move? void setNextMove(); void evolution(); void specialAttackFunction(Square *newSquare); public: Pawn(); vector<Square *> findAttackForMark(); vector<Square *> findAttack(); Pawn(Square *sq, Square* nextMove, int color); vector<Square *> findMoves(); void setPNext(Square *pNext); void moveFigure(Square *newSquare); void setPFirst(bool first); }; #endif // PAWN_H
516af6a263abfb7e3b75087e27431fff17551a6d
20ce5cf0fca6a7e0db7827cf112cbe4d7d8cf704
/arrayList.cpp
d042bf3cbbb7156ac50827023b34997e0514ec17
[]
no_license
aamirk2244/code-CPP
e7751459bd1afdf3c75c39de736e8da405394cb6
c0e45123818d2360b66d9b0181e179c5a0c56a91
refs/heads/master
2023-04-10T08:58:32.086152
2023-03-28T14:05:36
2023-03-28T14:05:36
242,528,530
1
0
null
null
null
null
UTF-8
C++
false
false
5,501
cpp
arrayList.cpp
#include<iostream> #define size 10 using namespace std; class List{ int *list; // will get the list array int *t; // temporary pointer we will use this later. int length; // will count the total length public: void insertElement(int val); bool deleteElement(int x, int* p); // List(int length){this->length = length; list = new list(this->length); }; List(); bool is_empty(); bool is_full(); void printList(); int searchElement(int x); void insertElementAT(int x, int pos); void emptyList(); int totalLength(){return length;} void copyList( List &fromThis ); int* getList(){return list;}; ~List(){cout << "Distructor is called " << endl;} // checking our distructor void sort(); void reverseList(); }; // 1,2,3 void List::printList() { int *p = list; t = list + this->length; cout << "[ "; while (p != t) { cout << *p << " "; p++; } cout << "]" << endl; } int List::searchElement(int x) { int *p = list; t = list + this->length; while (p!= t) { if(x == *p)return *p; p++; } cout << "Value not found" << endl; return -1; // means value not found } void List::insertElementAT(int x, int pos) // position will starts from zero { if (pos >= length+1 || pos < 0 || pos == size) //i.e if three length then should be max pos contain 3, 4 is not valid { cout << "Invalid position, maybe the list is full or your input is incorrect" << endl; return; } if (pos+1 == length ){*(this->list + pos) = x;return; } // no arrangement needed // 1 2 3 4 5 , if pos = 1, and x = 23, the list should be 1, 23, 2, 3, 4, 5 int swap; for(int i = this->length ; i > pos; i--) { swap = *(this->list + (i-1)); *(this->list + (i-1)) = *(this->list + i); // sending this deleted value to last position *(this->list + i) = swap; } *(this->list + pos) = x; cout << "Value inserted successfully " << endl; this->length++; } bool List::is_empty() { if(this->length == size) { return false; } return true; } bool List::is_full() { if (this->length == size) { return true; } return false; } List::List() { cout << "constructor called " << endl; this->list= new int[size]; t = NULL; length = 0; } //1,2,3 void List::insertElement(int val) { if(is_full()) { cout << "list is full" << endl; return; } t = list + this->length; *t = val; length++; } bool List::deleteElement(int x, int* p = NULL) { if (p == NULL) { t = list + this->length; // t will be present at garbage value, i.e after the last p = list; } if (p == t)return false; // means value not found if(x == *p) { length--; *p = -1; return true; } if(deleteElement(x, p+1) == true) // recursive call to find the element { cout << "element " << x << " is deleted succesfully" << endl; if (p+1 == t) return true; // it is last element no need to arrange list else { p += 1; while(p != t) { *p = *(p + 1); // sending this deleted value to last position p++; } } } return false; } void List::emptyList() { length = 0; t = list = NULL; cout<<"The list is now empty" << endl; } void List::copyList(List &fromThis ) { int *cp = fromThis.getList(); // returning whole list for (int i = 0 ; i < fromThis.totalLength(); i++) { this->insertElement(*(cp + i)); } this->length = fromThis.totalLength(); cout << "\nList copies successfully" << endl; } bool compare(List &l1, List &l2) { if (l1.totalLength() != l2.totalLength())return false; // if list are not same int *a1 = l1.getList(); // getting list array int *a2 = l1.getList(); for (int i = 0 ; i < l1.totalLength(); i++) { if (*(a1 + i) != *(a2 + i))return false; } return true; // it means lists are same } void List::sort() { int *l = this->getList(); int swap; for (int i = 0 ; i < this->totalLength(); i++) { for (int j = i; j < this->totalLength(); j++) { if (*(l + i) > *(l + j)) { swap = *(l + j); *(l + j) = *(l + i); *(l + i) = swap; } } } cout << "List sorted successfully" << endl; } void List::reverseList() { int left= -1; int swap; for (int right = this->length-1; right > int(this->length/2)-1; right--) // i dit /2 to handle even and odd length list , swapping last with first and so on { left++; if (this->list + left == this->list + right) // moving right to right side and left to left side { break; } swap = *(this->list + right); *(this->list + right) = *(this->list + left); *(this->list + left) = swap; } cout << "list reversed successfully" << endl; } // isinstance int main() { List s; List s2; s.insertElement(23); s.insertElement(4); s.insertElement(7); s.insertElement(8); s.printList(); s2.copyList(s); // copy s to s2 s2.printList(); cout << compare(s, s2) << endl; // compare takes 2 list objects s2.sort(); s2.printList(); s2.insertElementAT(100, 1); // inserting 100 at index 1, index starts from 0 s2.printList(); s2.reverseList(); s2.printList(); s2.deleteElement(7); s2.printList(); s2.reverseList(); s2.printList(); cout << s.searchElement(7) << endl; }
cd64abb7fc28b51b8a0c6579766fc095bac3c59b
d9c77e90be679cf9846fa76950e893e33ad9a414
/player/sources/pixlButton/PixelButton.cpp
697b3df1846100529c53673fd0c49f8a4b0e2cba
[]
no_license
jackdevelop/JEngin
607d690505f120cfd7a718a25c64e746861abee1
2e08d32cd654cf0570d7f81f1e551b0c625985e9
refs/heads/master
2016-09-06T11:44:14.775480
2014-01-18T07:24:58
2014-01-18T07:24:58
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,588
cpp
PixelButton.cpp
#include "PixelButton.h" //#include "CCScale9Sprite.h" using namespace std; using namespace cocos2d; USING_NS_CC_EXT; bool PixelButton::init() { if(CCControlButton::init()) { m_src = ""; setTouchEnabled(true); setAnchorPoint(CCPointZero); return true; } return false; } PixelButton* PixelButton::create(std::string normalSprite,std::string selectedSprite , std::string disabledSprite) { PixelButton* m_PixelButton = (PixelButton*)PixelButton::create(); m_PixelButton->m_src = normalSprite; m_PixelButton->setBackgroundSpriteForState(CCScale9Sprite::create(normalSprite.c_str()) , CCControlStateNormal); m_PixelButton->setBackgroundSpriteForState(CCScale9Sprite::create(selectedSprite.c_str()) , CCControlStateHighlighted); m_PixelButton->setBackgroundSpriteForState(CCScale9Sprite::create(disabledSprite.c_str()) , CCControlStateDisabled); return m_PixelButton; } PixelButton* PixelButton::create(std::string normalSprite,std::string selectedSprite , std::string disabledSprite , bool isZoomOnTouchDown) { PixelButton* m_PixelButton = PixelButton::create(normalSprite , selectedSprite , disabledSprite); m_PixelButton->setZoomOnTouchDown(isZoomOnTouchDown); return m_PixelButton; } PixelButton* PixelButton::create(std::string srcName , bool isZoomOnTouchDown) { string normalSprite = srcName; string selectedSprite = srcName; string disabledSprite = srcName; return PixelButton::create(normalSprite.append("_normal.png") , selectedSprite.append("_selector.png") , disabledSprite.append("_selector.png") , isZoomOnTouchDown); } void PixelButton::onEnter() { CCControlButton::onEnter(); } void PixelButton::onExit() { CCControlButton::onExit(); } bool PixelButton::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { CCSize cSize = this->getContentSize(); CCPoint point = this->getAnchorPointInPoints(); CCRect cRect = CCRectMake(-point.x, -point.y, cSize.width,cSize.height); if (!cRect.containsPoint(convertTouchToNodeSpaceAR(pTouch))) { return false; } ccColor4B c = {0, 0, 0, 0}; CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCPoint touchPoint = pTouch->getLocationInView(); point = ccp(cSize.width - point.x,cSize.height- point.y); CCPoint pos(this->getPositionX() - point.x,winSize.height-this->getPositionY()- point.y); CCPoint localPoint = ccp(touchPoint.x - pos.x,touchPoint.y -pos.y); unsigned int x = localPoint.x, y = localPoint.y; clickX=x,clickY=y; CCImage * img = new CCImage(); //CCLog("touch×ø±ê %d - %d", touchPoint.x, touchPoint.y); //CCLog("ת»¯×ø±ê %d - %d", pos.x, pos.y); CCLog("%d - %d" , x , y); img->initWithImageFileThreadSafe(CCFileUtils::sharedFileUtils()->fullPathForFilename(m_src.c_str()).c_str()); unsigned char *data_ = img->getData(); unsigned int *pixel = (unsigned int *)data_; pixel = pixel + (y * (int)this->getContentSize().width)* 1 + x * 1; if (!pixel) { CCLog("------------------error---------------"); return false; } c.r = *pixel & 0xff; c.g = (*pixel >> 8) & 0xff; c.b = (*pixel >> 16) & 0xff; c.a = (*pixel >> 24) & 0xff; if (c.a = (*pixel >> 24) & 0xff) { CCControlButton::ccTouchBegan(pTouch , pEvent); //clickX=x; //clickY=y; return true; }else { return false; } } void PixelButton::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { CCControlButton::ccTouchMoved(pTouch , pEvent); } void PixelButton::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { CCControlButton::ccTouchEnded(pTouch , pEvent); } void PixelButton::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { CCControlButton::ccTouchCancelled(pTouch , pEvent); }
095cf8256896db1f264167f6f1e25a26a0355199
d4a813ce8157670e08f0b17a2a8b5af75d6cc4d2
/R-package/src/gbtorch.cpp
8bd99dd2430dc1e506d5c093dd78c2832919d441
[ "MIT" ]
permissive
yafee123/gbtorch
a3de45fb68edffec43cdee00386fff4607c8b7c2
7e53a1c8d4159a83930863eb994531a8dcdad079
refs/heads/master
2020-08-01T21:24:59.105467
2019-09-24T18:20:03
2019-09-24T18:20:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,061
cpp
gbtorch.cpp
/* * gbtorch: Adaptive and automatic gradient boosting computations. * Berent Lunde * 07.09.2019 */ #include "gbtorch.hpp" //' @export ENSEMBLE class ENSEMBLE { public: double initialPred; double learning_rate; double initial_score; GBTREE* first_tree; Rcpp::List param; // constructors ENSEMBLE(); ENSEMBLE(double learning_rate_); // Functions void set_param(Rcpp::List par_list); Rcpp::List get_param(); double initial_prediction(Tvec<double> &y, std::string loss_function); void train(Tvec<double> &y, Tmat<double> &X, bool verbose, bool greedy_complexities); Tvec<double> predict(Tmat<double> &X); Tvec<double> predict2(Tmat<double> &X, int num_trees); double get_ensemble_bias(int num_trees); int get_num_trees(); }; // ---------------- ENSEMBLE ---------------- ENSEMBLE::ENSEMBLE(){ this->learning_rate=0.01; this->param = Rcpp::List::create( Named("learning_rate") = 0.01, Named("loss_function") = "mse", Named("nrounds") = 5000 ); } ENSEMBLE::ENSEMBLE(double learning_rate_){ this->first_tree = NULL; this->learning_rate = learning_rate_; this->param = Rcpp::List::create( Named("learning_rate") = learning_rate_, Named("loss_function") = "mse", Named("nrounds") = 5000 ); } void ENSEMBLE::set_param(Rcpp::List par_list){ this->param = par_list; this->learning_rate = par_list["learning_rate"]; } Rcpp::List ENSEMBLE::get_param(){ return this->param; } double ENSEMBLE::initial_prediction(Tvec<double> &y, std::string loss_function){ double pred=0; int n = y.size(); if(loss_function=="mse"){ pred = y.sum() / n; }else if(loss_function=="logloss"){ double pred_g_transform = y.sum()/n; // naive probability pred = log(pred_g_transform) - log(1 - pred_g_transform); } return pred; } void ENSEMBLE::train(Tvec<double> &y, Tmat<double> &X, bool verbose, bool greedy_complexities){ // Set init -- mean int MAXITER = param["nrounds"]; int n = y.size(); //int m = X.size(); double EPS = -1E-12; double expected_loss; double learning_rate_set = this->learning_rate; Tvec<double> pred(n), g(n), h(n); // MSE -- FIX FOR OTHER LOSS FUNCTIONS this->initialPred = this->initial_prediction(y, param["loss_function"]); //y.sum()/n; pred.setConstant(this->initialPred); this->initial_score = loss(y, pred, param["loss_function"]); //(y - pred).squaredNorm() / n; // First tree g = dloss(y, pred, param["loss_function"]); h = ddloss(y, pred, param["loss_function"]); this->first_tree = new GBTREE; this->first_tree->train(g, h, X, greedy_complexities, learning_rate_set); GBTREE* current_tree = this->first_tree; pred = pred + learning_rate * (this->first_tree->predict_data(X)); // POSSIBLY SCALED expected_loss = (current_tree->getTreeScore()) * (-2)*learning_rate_set*(learning_rate_set/2 - 1) + learning_rate_set * current_tree->getTreeBiasFullEXM(); if(verbose){ std::cout << std::setprecision(4) << "iter: " << 1 << " | reduction tr: " << (current_tree->getTreeScore()) * (-2)*learning_rate_set*(learning_rate_set/2 - 1) << " | reduction gen: " << expected_loss << " | tr loss: " << loss(y, pred, param["loss_function"]) << " | gen loss: " << this->get_ensemble_bias(1) << std::endl; } for(int i=2; i<(MAXITER+1); i++){ // TRAINING GBTREE* new_tree = new GBTREE(); g = dloss(y, pred, param["loss_function"]); h = ddloss(y, pred, param["loss_function"]); new_tree->train(g, h, X, greedy_complexities, learning_rate_set); // EXPECTED LOSS expected_loss = (new_tree->getTreeScore()) * (-2)*learning_rate_set*(learning_rate_set/2 - 1) + learning_rate_set * new_tree->getTreeBiasFullEXM(); // Update preds -- if should not be updated for last iter, it does not matter much computationally pred = pred + learning_rate * (current_tree->predict_data(X)); // iter: i | num leaves: T | iter train loss: itl | iter generalization loss: igl | mod train loss: mtl | mod gen loss: mgl "\n" if(verbose){ std::cout << std::setprecision(4) << "it: " << i << " | n-leaves: " << current_tree->getNumLeaves() << " | reduct tr: " << (current_tree->getTreeScore()) * (-2)*learning_rate_set*(learning_rate_set/2 - 1) << " | reduct gen: " << expected_loss << " | tr loss: " << loss(y, pred, param["loss_function"]) << " | gen loss: " << this->get_ensemble_bias(i-1) + expected_loss << std::endl; } if(expected_loss < EPS){ // && NUM_BINTREE_CONSECUTIVE < MAX_NUM_BINTREE_CONSECUTIVE){ current_tree->next_tree = new_tree; current_tree = new_tree; }else{ break; } } } Tvec<double> ENSEMBLE::predict(Tmat<double> &X){ int n = X.rows(); Tvec<double> pred(n); pred.setConstant(this->initialPred); GBTREE* current = this->first_tree; while(current != NULL){ pred = pred + (this->learning_rate) * (current->predict_data(X)); current = current->next_tree; } return pred; } Tvec<double> ENSEMBLE::predict2(Tmat<double> &X, int num_trees){ int n = X.rows(); int tree_num = 1; Tvec<double> pred(n); pred.setConstant(this->initialPred); GBTREE* current = this->first_tree; if(num_trees < 1){ while(current != NULL){ pred = pred + (this->learning_rate) * (current->predict_data(X)); current = current->next_tree; } }else{ while(current != NULL){ pred = pred + (this->learning_rate) * (current->predict_data(X)); current = current->next_tree; tree_num++; if(tree_num > num_trees) break; } } return pred; } double ENSEMBLE::get_ensemble_bias(int num_trees){ int tree_num = 1; double total_observed_reduction = 0.0; double total_optimism = 0.0; double learning_rate = this->learning_rate; GBTREE* current = this->first_tree; if(num_trees<1){ while(current != NULL){ total_observed_reduction += current->getTreeScore(); total_optimism += current->getTreeBiasFullEXM(); current = current->next_tree; } }else{ while(current != NULL){ total_observed_reduction += current->getTreeScore(); total_optimism += current->getTreeBiasFullEXM(); current = current->next_tree; tree_num++; if(tree_num > num_trees) break; } } //std::cout<< (this->initial_score) << std::endl; return (this->initial_score) + total_observed_reduction * (-2)*learning_rate*(learning_rate/2 - 1) + learning_rate * total_optimism; } int ENSEMBLE::get_num_trees(){ int num_trees = 0; GBTREE* current = this->first_tree; while(current != NULL){ num_trees++; current = current->next_tree; } return num_trees; } // Expose the classes RCPP_MODULE(MyModule) { using namespace Rcpp; class_<ENSEMBLE>("ENSEMBLE") .default_constructor("Default constructor") .constructor<double>() .field("initialPred", &ENSEMBLE::initialPred) .method("set_param", &ENSEMBLE::set_param) .method("get_param", &ENSEMBLE::get_param) .method("train", &ENSEMBLE::train) .method("predict", &ENSEMBLE::predict) .method("predict2", &ENSEMBLE::predict2) .method("get_ensemble_bias", &ENSEMBLE::get_ensemble_bias) .method("get_num_trees", &ENSEMBLE::get_num_trees) ; }
eb61ad0cb22350b23e29923124c6e046e2d905b0
2b5b1354b01cd71cc77837d5a54e86b08e536487
/course 1/lab5/I/I/main.cpp
ccf199d6117c8362975cfd968f8cb4c29659c70f
[]
no_license
vi34/Discrete-Math-Labs
98b0ca266069bf0bb33a43d22ec16c1693aa5673
1250cdb8ae55feb9e6a86900eafd9863b1cc62e4
refs/heads/master
2021-01-21T04:59:46.010712
2016-06-04T07:23:07
2016-06-04T07:23:07
36,805,817
0
0
null
null
null
null
UTF-8
C++
false
false
1,326
cpp
main.cpp
#include <string> #include <cstdio> #include <iostream> #include <vector> #include <queue> #include <algorithm> #define NAME "salesman" #define mp make_pair #define pb push_back #define rep0(i, n) for(int i = 0; i < n; i++) using namespace std; long long INF = 10000000000; vector< vector<pair<int, int> > > g; vector <vector<long long > > d; int n, m; int mask; long long rec(int mask, int curr) { if(d[mask][curr] != INF) return d[mask][curr]; rep0(i, g[curr].size()) { int v = g[curr][i].first; int w = g[curr][i].second; if(mask & (1 << v)) { d[mask][curr] = min(d[mask][curr], rec(mask - (1 << v),v) + w); } } return d[mask][curr]; } int main () { freopen(NAME".in", "r", stdin); freopen(NAME".out", "w", stdout); cin >> n >> m; g.resize(n); rep0(i, m) { int v, u, w; cin >> v >> u >> w; g[v - 1].pb(mp(u - 1,w)); g[u - 1].pb(mp(v - 1,w)); } long long answ = INF; rep0(i, n) { mask = (1 << (n)) - 1; mask -= (1 << i); d.resize(mask + 1, vector<long long>(n , INF)); d[0][i] = 0; answ = min(answ, rec(mask, i)); } if(answ == INF) cout << -1; else cout << answ; return 0; }