blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ca8cdf68bc08fb4fd6710f1e1a2ddf9d2c9ad481 | C++ | PirateLi/C-Sample | /StudentMIS/StudentMain.cpp | GB18030 | 838 | 2.875 | 3 | [] | no_license | #include <iostream>
#include "Student.h"
using namespace std;
int main()
{
StudentMIS sysu;
StudentBase* pBase;
First* pFirst;
Second* pSecond;
StudentMIS* pMIS;
pFirst=&sysu;
pSecond=&sysu;
pBase=&sysu;
pMIS=&sysu;
int n;
while (1)
{
system("cls");
cout<<"ӭʹѧϢϵͳѡȨޣ"<<endl;
cout<<"1. "<<endl;
cout<<"2. רҵԱ"<<endl;
cout<<"3. רҵԱ"<<endl;
cout<<"4. ѧλ"<<endl;
cout<<"0. ˳ϵͳ"<<endl;
cout<<": ";
while(cin>>n &&( n<0 || n>4)) cout<<"룺 ";
if (n==1) pBase->selectOperation();
if (n==2) pFirst->selectOperation();
if (n==3) pSecond->selectOperation();
if (n==4) pMIS->selectOperation();
if (n==0) break;
}
}
| true |
94cada3b7d32e1d00416a696c96a9ed9e1ca957b | C++ | ITA-Dnipro/BackEndMonitoring | /utils/include/CThreadPool.h | UTF-8 | 1,699 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <future>
#include <queue>
#include <condition_variable>
#include <functional>
#include "CEvent.h"
#include "CThreadSafeVariable.h"
#include "STaskInQueue.h"
#include "Log.h"
class CThreadPool
{
public:
using Task = std::function<void()>;
CThreadPool() = delete;
CThreadPool(std::size_t numThreads, CEvent& stop_event);
CThreadPool(const CThreadPool&) = delete;
CThreadPool(CThreadPool&&) noexcept = delete;
~CThreadPool() noexcept;
CThreadPool& operator= (const CThreadPool&) = delete;
CThreadPool& operator= (CThreadPool&&) noexcept = delete;
template<typename TaskType>
auto Enqueue(TaskType task) -> STaskInQueue<decltype(task( ))>
{
STaskInQueue<decltype(task( ))> future_and_pos;
CLOG_DEBUG_START_FUNCTION( );
CLOG_TRACE_VAR_CREATION(future_and_pos);
auto p_task_wrapper = std::make_shared<std::packaged_task<
decltype(task( ))()>>(std::move(task));
CLOG_TRACE_VAR_CREATION(p_task_wrapper);
{
auto [queue, mtx] = m_tasks_queue.GetAccess( );
CLOG_DEBUG("Obtained queue mutex");
queue.emplace([=]
{
(*p_task_wrapper)();
});
CLOG_DEBUG("Pushed task in queue");
future_and_pos.position = queue.size( );
CLOG_TRACE_VAR_CREATION(future_and_pos.position);
}
m_event.NotifyOne( );
CLOG_DEBUG("Notified one thread that task pushed");
future_and_pos.future = p_task_wrapper->get_future( );
CLOG_TRACE_VAR_CREATION(future_and_pos.future);
CLOG_DEBUG_END_FUNCTION( );
return future_and_pos;
}
private:
void ThreadWork();
void CheckThread( );
private:
CEvent m_event;
CThreadSafeVariable<std::queue<Task>> m_tasks_queue;
std::vector<std::thread> m_threads;
CEvent& m_stop_event;
};
| true |
d77c0ff9b17690d426e001a6cd15545068f3c4dc | C++ | almohamedumar/awesome-coding | /count nodes in complete binary tree2.cpp | UTF-8 | 998 | 3.40625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node *left, *right;
Node(int key)
{
this->key = key;
this->left = this->right = nullptr;
}
};
int countnum(Node *root)
{
if(root == NULL)
{
return 0;
}
int l=0,r=0;
Node*curr = root;
while(curr!= NULL)
{
l++;
curr = curr->left;
}
curr = root;
while(curr!=NULL)
{
r++;
curr= curr->right;
}
if(l==r)
{
int res = pow(2,l)-1;
}
else
{
return 1+ countnum(root->left) + countnum(root->right);
}
}
int main()
{
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(25);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
cout<<countnum(root);
} | true |
e7b969dde0734b428b7d005241467e04edbffe20 | C++ | adanil/CompetitiveProgramming | /Greedy/taskD/main.cpp | UTF-8 | 14,584 | 2.765625 | 3 | [] | no_license | //#include <iostream>
//#include <string>
//#include <vector>
//#include <algorithm>
//
//using namespace std;
//using ll = long long;
//
//struct prnts{
// ll bal;
// ll negPref;
// ll posPost;
// ll id;
//};
//
//vector<string> generetedParenthesis;
//
//
//void generateParenthesis(int n,int bal,string prn) {
// //for (int i = 0;i < n;i++){
// if (bal > 0 && n > 0){
// generateParenthesis(n-1,bal+1,prn + '(');
// generateParenthesis(n,bal-1,prn + ')');
// }
// else if (bal > 0 && n == 0){
// generateParenthesis(n,bal-1,prn + ')');
// }
// else if (bal == 0 && n > 0)
// generateParenthesis(n-1,bal+1,prn + '(');
// else if (bal == 0 && n == 0)
// generetedParenthesis.push_back(prn);
// // }
//}
//
//bool checkParnethesis(string s){
// ll bres = 0;
// for (ll i = 0;i < s.size();i++){
// if (s[i] == '(')
// bres++;
// else
// bres--;
// if (bres < 0){
// return false;
// }
// }
// return true;
//}
//
//bool solution(vector<string> vs){
// vector<prnts> pos;
// vector<prnts> neg;
// vector<prnts> zero;
// for (ll i = 0;i < vs.size();i++){
// ll posPst = 0;
// ll bal = 0;
// ll close = 0;
// bool fl = true;
// for (ll j = 0;j < vs[i].size();j++){
// if (vs[i][j] == '(') {
// fl = false;
// bal++;
// posPst++;
// }
// else {
// bal--;
// posPst = 0;
// }
// if (fl)
// if (bal < 0)
// close = max(close,abs(bal));
// }
// if (bal > 0){
// prnts e;
// e.bal = bal;
// e.negPref = close;
// e.id = i;
// pos.push_back(e);
//
// }
// else if (bal < 0){
// prnts e;
// e.bal = bal;
// e.negPref = close;
// e.posPost = posPst;
// e.id = i;
// neg.push_back(e);
// }
// else{
// prnts e;
// e.bal = 0;
// e.negPref = close;
// e.id = i;
// zero.push_back(e);
// }
// }
//
// string ans;
// vector<ll>ansv;
// sort(pos.begin(),pos.end(),[](prnts a,prnts b){return a.negPref < b.negPref;});
// ll balance = 0;
// for (ll i = 0;i < pos.size();i++){
// if (pos[i].negPref > balance){
//// cout << "NO" << endl;
// return 0;
// }
// ansv.push_back(pos[i].id);
// ans += vs[pos[i].id];
// balance += pos[i].bal;
// }
//
// for (ll i = 0;i < zero.size();i++){
// if (zero[i].negPref > balance){
//// cout << "NO" << endl;
// return 0;
// }
// ansv.push_back(zero[i].id);
// ans += vs[zero[i].id];
// }
//
// sort(neg.begin(),neg.end(),[](prnts a,prnts b){return -a.bal + b.negPref < -b.bal + a.negPref;});
// for (ll i = 0;i < neg.size();i++){
// if (neg[i].negPref > balance){
//// cout << "NO" << endl;
// return 0;
// }
// ansv.push_back(neg[i].id);
// ans += vs[neg[i].id];
// balance += neg[i].bal;
// }
// ll bres = 0;
// for (ll i = 0;i < ans.size();i++){
// if (ans[i] == '(')
// bres++;
// else
// bres--;
// if (bres < 0){
//// cout << "NO" << endl;
// return 0;
// }
// }
// if (bres != 0)
// return 0;
//// cout << "NO" << endl;
// else{
//// cout << "YES" << endl;
//// for (auto &el : ansv)
//// cout << el+1 << ' ';
// return 1;
// cout << ans << endl;
// }
//}
//
//
//
//
//
//
//int main() {
//
// generateParenthesis(10,0,"");
//
//// for (int i = 0;i < generetedParenthesis.size();i++)
//// cout << generetedParenthesis[i] << ' ' << checkParnethesis(generetedParenthesis[i]) << endl;
//
// vector<vector<string>> slicedPr(generetedParenthesis.size());
//
// int needSlice = 6;
//
// for (int i = 0;i < generetedParenthesis.size();i++){
// int sz = generetedParenthesis[i].size()/needSlice;
// int pnt = 0;
// int sliceCount = 0;
// string slice;
// for (int j = 0;j < generetedParenthesis[i].size();j++){
// if (sliceCount < needSlice - 1 && pnt < sz) {
// slice += generetedParenthesis[i][j];
// pnt++;
// }
// else if (sliceCount < needSlice - 1 && pnt >= sz){
// slicedPr[i].push_back(slice);
// sliceCount++;
// pnt = 1;
// slice = generetedParenthesis[i][j];
// }
// else{
// slice += generetedParenthesis[i][j];
// pnt++;
// }
//
// }
// slicedPr[i].push_back(slice);
// }
//
//// for (int i = 0;i < slicedPr.size();i++){
//// for (auto el : slicedPr[i])
//// cout << el << ' ';
//// cout << endl;
//// }
//
// for (int i = 0;i < slicedPr.size();i++){
// cout << "i = " << i << " answer: " << solution(slicedPr[i])<< endl;
// }
//
//
// vector<string> wr;
// wr.push_back("(");
// wr.push_back("(");
// wr.push_back("(");
// wr.push_back(")))((()");
// wr.push_back("))(");
// wr.push_back(")");
//
//
//
//
// cout << solution(wr) << endl;
//
//
////
//// ios_base::sync_with_stdio(false);
//// cin.tie(NULL);
//// ll n;
//// cin >> n;
//// vector<string> vs(n);
//// vector<prnts> pos;
//// vector<prnts> neg;
//// vector<prnts> zero;
//// for (ll i = 0;i < n;i++){
//// ll posPst = 0;
//// cin >> vs[i];
//// ll bal = 0;
//// ll negPr = 0;
// bool fl = true;
// for (ll j = 0;j < vs[i].size();j++){
// if (vs[i][j] == '(') {
// fl = false;
// bal++;
// posPst++;
// }
// else {
// negPr++;
// bal--;
// if (posPst > 0) {
// posPst--;
// negPr--;
// }
//
// }
// }
//// if (bal > 0){
//// prnts e;
//// e.bal = bal;
//// e.negPref = close;
//// e.id = i;
//// pos.push_back(e);
////
//// }
//// else if (bal < 0){
//// prnts e;
//// e.bal = bal;
//// e.negPref = close;
//// e.posPost = posPst;
//// e.id = i;
//// neg.push_back(e);
//// }
//// else{
//// prnts e;
//// e.bal = 0;
//// e.negPref = close;
//// e.id = i;
//// zero.push_back(e);
//// }
//// }
////
//// string ans;
//// vector<ll>ansv;
//// sort(pos.begin(),pos.end(),[](prnts a,prnts b){return a.negPref < b.negPref;});
//// ll balance = 0;
//// for (ll i = 0;i < pos.size();i++){
//// if (pos[i].negPref > balance){
//// cout << "NO" << endl;
//// return 0;
//// }
//// ansv.push_back(pos[i].id);
//// ans += vs[pos[i].id];
//// balance += pos[i].bal;
//// }
////
//// for (ll i = 0;i < zero.size();i++){
//// if (zero[i].negPref > balance){
//// cout << "NO" << endl;
//// return 0;
//// }
//// ansv.push_back(zero[i].id);
//// ans += vs[zero[i].id];
//// }
////
//// sort(neg.begin(),neg.end(),[](prnts a,prnts b){return a.posPost > b.posPost;});
//// for (ll i = 0;i < neg.size();i++){
//// if (neg[i].negPref > balance){
//// cout << "NO" << endl;
//// return 0;
//// }
//// ansv.push_back(neg[i].id);
//// ans += vs[neg[i].id];
//// balance += neg[i].bal;
//// }
//// ll bres = 0;
//// for (ll i = 0;i < ans.size();i++){
//// if (ans[i] == '(')
//// bres++;
//// else
//// bres--;
//// if (bres < 0){
//// cout << "NO" << endl;
//// return 0;
//// }
//// }
//// if (bres != 0)
//// cout << "NO" << endl;
//// else{
//// cout << "YES" << endl;
//// for (auto &el : ansv)
//// cout << el+1 << ' ';
////// cout << ans << endl;
//// }
//
// return 0;
//}
/////
//
//
//#include <iostream>
//#include <string>
//#include <vector>
//#include <algorithm>
//namespace Danil {
// using namespace std;
// using ll = long long;
//
// struct prnts{
// ll bal;
// ll negPref;
// ll posPost;
// ll id;
// };
//
std::string main(const vector<string>& vs) {
const int n = (int)vs.size();
//cin >> n;
//vector<string> vs(n);
vector<prnts> pos;
vector<prnts> neg;
vector<prnts> zero;
for (ll i = 0;i < n;i++){
ll posPst = 0;
//cin >> vs[i];
ll bal = 0;
ll negPr = 0;
bool fl = true;
for (ll j = 0;j < vs[i].size();j++){
if (vs[i][j] == '(') {
fl = false;
bal++;
posPst++;
}
else {
negPr++;
bal--;
if (posPst > 0) {
posPst--;
negPr--;
}
}
}
if (bal > 0){
prnts e;
e.bal = bal;
e.negPref = negPr;
e.id = i;
pos.push_back(e);
}
else if (bal < 0){
prnts e;
e.bal = bal;
e.negPref = negPr;
e.posPost = posPst;
e.id = i;
neg.push_back(e);
}
else{
prnts e;
e.bal = 0;
e.negPref = negPr;
e.id = i;
zero.push_back(e);
}
}
string ans;
vector<ll>ansv;
sort(pos.begin(),pos.end(),[](prnts a,prnts b){return a.negPref < b.negPref;});
ll balance = 0;
for (ll i = 0;i < pos.size();i++){
if (pos[i].negPref > balance){
return "NO";//cout << "NO" << endl;
//return 0;
}
ansv.push_back(pos[i].id);
ans += vs[pos[i].id];
balance += pos[i].bal;
}
for (ll i = 0;i < zero.size();i++){
if (zero[i].negPref > balance){
return "NO"; //cout << "NO" << endl;
//return 0;
}
ansv.push_back(zero[i].id);
ans += vs[zero[i].id];
}
sort(neg.begin(),neg.end(),[](prnts a,prnts b){return a.posPost > b.posPost;});
for (ll i = 0;i < neg.size();i++){
if (neg[i].negPref > balance){
return "NO";//cout << "NO" << endl;
//return 0;
}
ansv.push_back(neg[i].id);
ans += vs[neg[i].id];
balance += neg[i].bal;
}
ll bres = 0;
for (ll i = 0;i < ans.size();i++){
if (ans[i] == '(')
bres++;
else
bres--;
if (bres < 0){
return "NO";//cout << "NO" << endl;
//return 0;
}
}
if (bres != 0)
return "NO";//cout << "NO" << endl;
else{
return "YES";//cout << "YES" << endl;
//for (auto &el : ansv)
// cout << el+1 << ' ';
// cout << ans << endl;
}
}
}
std::string next(std::string s) {
int n = (int) s.length();
std::string ans = "-1";
for (int i=n-1, depth=0; i>=0; --i) {
if (s[i] == '(')
--depth;
else
++depth;
if (s[i] == '(' && depth > 0) {
--depth;
int open = (n-i-1 - depth) / 2;
int close = n-i-1 - open;
ans = s.substr(0,i) + ')' + std::string (open, '(') + std::string (close, ')');
break;
}
}
//assert(ans != "-1");
return ans;
}
int main() {
for (int n = 1; n <= 10; n++) {
std::string seq = std::string(n, '(') + std::string(n, ')');
while (seq != "-1") {
std::vector<std::string> vs;
for (int i = 1; i < 2 * n; i++) {
vs.push_back(seq.substr(0,i));
for (int j = i+1; j < 2 * n; j++) {
vs.push_back(seq.substr(i,j-i));
for (int k = j+1; k < 2 * n; k++) {
vs.push_back(seq.substr(j,k-j));
for (int t = k+1; t < 2 * n; t++) {
vs.push_back(seq.substr(k,t-k));
for (int r = t+1; r < 2 * n; r++) {
vs.push_back(seq.substr(t,r-t));
vs.push_back(seq.substr(r,2*n-r));
auto copy = vs;
#define all(x) (x).begin(),(x).end()
std::sort(all(copy));
if (Danil::main(vs) == "NO") {
std::cout << vs.size() << std::endl;
for (auto &it : vs) {
std::cout << it << std::endl;
}
for (auto el: vs){
std::cout << el << ' ';
}
std::cout << "Wrong" << std::endl;
std::exit(0);
}
vs.pop_back();
vs.pop_back();
}
vs.pop_back();
}
vs.pop_back();
}
vs.pop_back();
}
vs.pop_back();
}
std::cerr << "seq=" << seq << ": OK" << '\n';
seq = next(seq);
}
}
} | true |
eb738fbdc8d3b61784b20ff81286e7796fc89768 | C++ | Noahbrauer/MCMCProj | /BayeSource.cpp | UTF-8 | 2,095 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include "BayesNet.h"
int main()
{
// Creating all net objects
BayesNet net1;
BayesNet net2;
BayesNet net3;
BayesNet net4;
BayesNet net5;
double numTrue[5][10] = { 0 };
double record[5] = { 0 };
// Run 1 storing count in first slice of numTrue
net1.initVars(1);
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 1000; k++)
{
numTrue[0][j] += net1.mcmc();
}
record[0] += numTrue[0][j];
}
// Run 2 storing count in second slice of numTrue
net2.initVars(2);
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 1000; k++)
{
numTrue[1][j] += net1.mcmc();
}
record[1] += numTrue[1][j];
}
// Run 3 storing count in third slice of numTrue
net3.initVars(3);
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 1000; k++)
{
numTrue[2][j] += net1.mcmc();
}
record[2] += numTrue[2][j];
}
// Run 4 storing count in fourth slice of numTrue
net4.initVars(4);
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 1000; k++)
{
numTrue[3][j] += net1.mcmc();
}
record[3] += numTrue[3][j];
}
// Run 5 storing count in fifth slice of numTrue
net5.initVars(5);
for (int j = 0; j < 10; j++)
{
for (int k = 0; k < 1000; k++)
{
numTrue[4][j] += net1.mcmc();
}
record[4] += numTrue[4][j];
}
// Printing values for each run
cout << "Number of B=T for each 1000 chunk " << "Run 1" << setw(8) << "Run 2" << setw(8) << "Run 3" << setw(8) << "Run 4" << setw(8) << "Run 5\n";
for (int j = 0; j < 10; j++) {
cout << "Proportion in" << setw(3) << j + 1 << "000 Instances: " << setw(8) << numTrue[0][j]/1000.0 << setw(8) << numTrue[1][j]/1000.0 << setw(8) << numTrue[2][j]/1000.0 << setw(8) << numTrue[3][j]/1000.0 << setw(8) << numTrue[4][j]/1000.0 << endl;
}
// Printing final result for each iteration inside an array
cout << "\nPr(B|D,G) = [ ";
for (int i = 0; i < 5; i++)
{
if (i == 4)
cout << record[i] / 10000.0 << " ]\n\n";
else cout << record[i] / 10000.0 << " , ";
}
}
| true |
6966c2ffbd02689d9e9daec128a5e0a37114ea6a | C++ | SiChiTong/DosuBot_pkg | /src/dosubot_serial/src/dosubot_serial.cpp | UTF-8 | 2,728 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <ros/ros.h>
#include <serial/serial.h>
#include <std_msgs/String.h>
#include <std_msgs/Empty.h>
#include "sensor_msgs/JointState.h"
#include <string>
#include <sstream>
serial::Serial ros_ser; //声明串口对象
//回调函数
void jointstatesCallback(const sensor_msgs::JointStateConstPtr& msg)
{
std::stringstream str;
str<<"joint1: pos:"<<msg->position[0]<<" vel:"<<msg->velocity[0]
<<" joint2: pos:"<<msg->position[1]<<" vel:"<<msg->velocity[1]
<<" joint3: pos:"<<msg->position[2]<<" vel:"<<msg->velocity[2]
<<" joint4: pos:"<<msg->position[3]<<" vel:"<<msg->velocity[3]
<<" joint5: pos:"<<msg->position[4]<<" vel:"<<msg->velocity[4]<<std::endl;
ROS_INFO_STREAM("Writing to serial port" );
ros_ser.write(str.str()); //发送串口数据
}
/*void callback(const std_msgs::String::ConstPtr& msg)
{
std::stringstream str;
str<<"joint1: pos:"<<1.0<<" vel:"<<2.0<<std::endl;0
ROS_INFO_STREAM("Write to serial port" << msg->data);
ros_ser.write(str.str()); //发送串口数据
}*/
int main (int argc, char** argv){
ros::init(argc, argv, "dosubot_serial_node"); //初始化节点
ros::NodeHandle n; //声明节点句柄
//订阅主题/joint_states,并配置回调函数
ros::Subscriber command_sub = n.subscribe("/dosubot/joint_states", 1000, jointstatesCallback);
//发布主题sensor
ros::Publisher sensor_pub = n.advertise<std_msgs::String>("sensor", 1000);
try
{
//设置串口属性,并打开串口
ros_ser.setPort("/dev/ttyUSB0");
ros_ser.setBaudrate(115200);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
ros_ser.setTimeout(to);
ros_ser.open();
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("Unable to open port ");
return -1;
}
//检测串口是否已经打开,并给出提示信息
if(ros_ser.isOpen()){
ROS_INFO_STREAM("Serial Port opened");
}else{
return -1;
}
//指定循环的频率
ros::Rate loop_rate(10);
while(ros::ok()){
//处理ROS的信息,比如订阅消息,并调用回调函数
ros::spinOnce();
if(ros_ser.available()){
ROS_INFO_STREAM("Reading from serial port");
std_msgs::String serial_data;
//获取串口数据
serial_data.data = ros_ser.read(ros_ser.available());
ROS_INFO_STREAM("Read: " << serial_data.data);
//将串口数据发布到主题sensor
sensor_pub.publish(serial_data);
}
loop_rate.sleep();
}
}
| true |
34abbde746a1c0ebd136cc21df9c3c5f915d0fa5 | C++ | fredericjoanis/Argorha-Pathfinding | /doc/demos/Irrlicht/src/main.cpp | UTF-8 | 11,956 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
In this tutorial, I will show how to collision detection with the Irrlicht Engine.
I will describe 3 methods: Automatic collision detection for moving through 3d worlds
with stair climbing and sliding, manual triangle picking and manual
scene node picking.
To start, we take the program from tutorial 2, which loaded and displayed a quake 3
level. We will use the level to walk in it and to pick triangles from it. In addition
we'll place 3 animated models into it for scene node picking. The following code
starts up the engine and loads
a quake 3 level. I will not explain it, because it should already be known from tutorial
2.
*/
#include "IrrPrePathfindingPhysic.h"
#include <iostream>
#include "Pre/PathfindingPreCompute.h"
#include "IrrPathData.h"
#include "PathfindingPortal.h"
#include "Utilities/Math/IrrAxisAlignedBoxAdapter.h"
#include "Utilities/Math/PathfindingVector3Adapter.h"
#include "Path/PathfindingPathCardinalSpline.h"
#include "PathfindingAStar.h"
using namespace irr;
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
video::IVideoDriver* mDriver;
scene::ISceneManager* mSmgr;
Pathfinding::Actor* mPathActor;
scene::ITriangleSelector* mSelector = 0;
scene::ICameraSceneNode* mCamera;
Pathfinding::Math::Vector3 mStartPos;
Pathfinding::Math::Vector3 mEndPos;
std::vector<Pathfinding::Math::Vector3> mPathPoints;
std::vector<Pathfinding::AStarNode> mAStarNodes;
/*
* Handle the event for the pathfinding calculations
*/
class MyEventReceiver : public IEventReceiver
{
public:
virtual bool OnEvent(const SEvent& event)
{
bool ret = false;
if (event.EventType == EET_MOUSE_INPUT_EVENT && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN )
{
irr::core::vector3df outColl;
irr::core::triangle3df outTri;
core::line3d<f32> lineCollision;
lineCollision.start = mCamera->getPosition();
lineCollision.end = lineCollision.start + (mCamera->getTarget() - lineCollision.start).normalize() * 1000.0f;
if (mSmgr->getSceneCollisionManager()->getCollisionPoint( lineCollision, mSelector, outColl, outTri))
{
if( mStartPos != mEndPos )
{
mStartPos = mEndPos;
mEndPos = PathIrr::PathfindingVector3Adapter(outColl);
mEndPos.y += mPathActor->getSmallVector().y * 0.5f;
Pathfinding::AStar AStar;
mAStarNodes = AStar.getPath(mStartPos, mEndPos, mPathActor->getData(), 0 );
Pathfinding::Path::CardinalSpline path;
path.reCalculatePoints(&mAStarNodes, mPathActor);
Pathfinding::Path::InterpolatePathData dataPath;
dataPath.waypoints = &mAStarNodes;
dataPath.nbPoints = 15;
dataPath.data = mPathActor->getData();
dataPath.hLevel = 0;
mPathPoints = path.interpolateFromWaypoints( &dataPath );
}
else
{
mEndPos = PathIrr::PathfindingVector3Adapter(outColl);
mEndPos += mPathActor->getSmallVector().y * 0.5f;
}
}
ret = true;
}
return ret;
}
};
int main()
{
video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;
printf("(t) Incomplete generation (Small part of the map will be generated)\nor\n(c) Complete pathfinding generation (Might take more than 1 minute)\n");
Pathfinding::Math::AxisAlignedBox zone;
char i = 0;
while( i != 't' && i != 'c' && i != 'd' )
{
std::cin >> i;
switch(i)
{
case 'c': zone = Pathfinding::Math::AxisAlignedBox( -1000, -70, -1200, 1300, 500, 1000 );
break;
case 't': zone = Pathfinding::Math::AxisAlignedBox( -500, -70, -600, 150, 500, 0 );
break;
case 'd': zone = Pathfinding::Math::AxisAlignedBox( 500, 175, 700, 665, 400, 800 );
break;
}
}
// create device
MyEventReceiver receiver;
IrrlichtDevice *device = createDevice(driverType, core::dimension2d<s32>(640, 480), 16, false, false, false, &receiver );
if (device == 0)
return 1; // could not create selected driver.
mDriver = device->getVideoDriver();
mSmgr = device->getSceneManager();
device->getFileSystem()->addZipFileArchive("../media/map-20kdm2.pk3");
scene::IAnimatedMesh* q3levelmesh = mSmgr->getMesh("20kdm2.bsp");
scene::ISceneNode* q3node = 0;
if (q3levelmesh)
{
q3node = mSmgr->addOctTreeSceneNode(q3levelmesh->getMesh(0));
if (q3node)
{
q3node->setPosition(core::vector3df(-1350,-130,-1400));
mSelector = mSmgr->createOctTreeTriangleSelector(q3levelmesh->getMesh(0), q3node, 128);
q3node->setTriangleSelector(mSelector);
}
}
mCamera = mSmgr->addCameraSceneNodeFPS();
//m_camera->setPosition(core::vector3df(500,400,600));
mCamera->setPosition(core::vector3df(60,0,-50));
if (mSelector)
{
scene::ISceneNodeAnimator* anim = mSmgr->createCollisionResponseAnimator( mSelector, mCamera, core::vector3df(30,50,30), core::vector3df(0,-3,0), core::vector3df(0,50,0));
mSelector->drop();
}
// disable mouse cursor
device->getCursorControl()->setVisible(false);
// add billboard
scene::IBillboardSceneNode * bill = mSmgr->addBillboardSceneNode();
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
bill->setMaterialTexture(0, mDriver->getTexture("../media/particle.bmp"));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZBUFFER, false);
bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
// add 3 animated faeries.
video::SMaterial material;
material.setTexture(0, mDriver->getTexture("../media/faerie2.bmp"));
material.Lighting = true;
scene::IAnimatedMeshSceneNode* node = 0;
scene::IAnimatedMesh* faerie = mSmgr->getMesh("../media/faerie.md2");
if (faerie)
{
node = mSmgr->addAnimatedMeshSceneNode(faerie);
node->setPosition(core::vector3df(-70,0,-90));
node->setMD2Animation(scene::EMAT_RUN);
node->getMaterial(0) = material;
node = mSmgr->addAnimatedMeshSceneNode(faerie);
node->setPosition(core::vector3df(-70,0,-30));
node->setMD2Animation(scene::EMAT_SALUTE);
node->getMaterial(0) = material;
node = mSmgr->addAnimatedMeshSceneNode(faerie);
node->setPosition(core::vector3df(-70,0,-60));
node->setMD2Animation(scene::EMAT_JUMP);
node->getMaterial(0) = material;
}
material.setTexture(0, 0);
material.Lighting = false;
// Add a light
mSmgr->addLightSceneNode(0, core::vector3df(-60,100,400), video::SColorf(1.0f,1.0f,1.0f,1.0f), 600.0f);
/*
For not making it to complicated, I'm doing picking inside the drawing loop.
We take two pointers for storing the current and the last selected scene node and
start the loop.
*/
scene::ISceneNode* selectedSceneNode = 0;
scene::ISceneNode* lastSelectedSceneNode = 0;
int lastFPS = -1;
Pathfinding::Pre::Compute compute;
PathIrr::PrePathfindingPhysic phys(mSmgr, mSelector);
PathIrr::IrrPathData* pathData = new PathIrr::IrrPathData();
mPathActor = new Pathfinding::Actor(pathData, Pathfinding::Math::AxisAlignedBox( 0.f, 0.f, 0.f, 30.f, 50.f, 30.f));
gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
wchar_t buffer[50];
swprintf(buffer, L"%d, %d, %d", mCamera->getPosition().X, mCamera->getPosition().Y, mCamera->getPosition().Z);
irr::gui::IGUIStaticText* text = guienv->addStaticText(buffer, core::rect<s32>(10,10,260,22), true,true,0,-1,true);
// Just take all the level
bool bFirstRun = true;
while(device->run())
if (device->isWindowActive())
{
mDriver->beginScene(true, true, 0);
mSmgr->drawAll();
guienv->drawAll();
core::line3d<f32> line;
line.start = mCamera->getPosition();
line.end = line.start + (mCamera->getTarget() - line.start).normalize() * 1000.0f;
swprintf(buffer, L"%d, %d, %d", (int)mCamera->getPosition().X, (int)mCamera->getPosition().Y, (int)mCamera->getPosition().Z);
text->setText(buffer);
core::vector3df intersection;
core::triangle3df tri;
if (mSmgr->getSceneCollisionManager()->getCollisionPoint(line, mSelector, intersection, tri))
{
bill->setPosition(intersection);
mDriver->setTransform(video::ETS_WORLD, core::matrix4());
mDriver->setMaterial(material);
mDriver->draw3DTriangle(tri, video::SColor(0,255,0,0));
}
if( bFirstRun )
{
printf( "Starting pathfinding generation" );
if( i == 'c' )
{
printf( ", might be long ; please wait!" );
}
compute.generateSectorsAndPortals(&phys, mPathActor, &zone, 0 );
bFirstRun = false;
}
for( std::list<Pathfinding::Portal*>::iterator iter = pathData->mListPortal.begin(); iter != pathData->mListPortal.end(); iter++ )
{
mDriver->draw3DBox(PathIrr::IrrAxisAlignedBoxAdapter((*iter)->getBox()),irr::video::SColor(255,0,0,255));
}
for( std::list<Pathfinding::Sector*>::iterator iter = pathData->mListSector.begin(); iter != pathData->mListSector.end(); iter++ )
{
mDriver->draw3DBox(PathIrr::IrrAxisAlignedBoxAdapter((*iter)->getBox()),irr::video::SColor(255,255,0,0));
}
std::vector<Pathfinding::Math::Vector3>::iterator iter = mPathPoints.begin();
while( iter != mPathPoints.end() )
{
iter++;
if( iter != mPathPoints.end() )
{
core::vector3df startPos;
core::vector3df endPos;
startPos = PathIrr::IrrVector3Adapter( *iter );
iter--;
endPos = PathIrr::IrrVector3Adapter( *iter );
iter++;
mDriver->draw3DLine(startPos, endPos,irr::video::SColor(255,0,255,0));
}
}
/*
Another type of picking supported by the Irrlicht Engine is scene node picking
based on bouding boxes. Every scene node has got a bounding box, and because of
that, it's very fast for example to get the scene node which the camera looks
at. Again, we ask the collision manager for this, and if we've got a scene node,
we highlight it by disabling Lighting in its material, if it is not the
billboard or the quake 3 level.
*/
selectedSceneNode = mSmgr->getSceneCollisionManager()->getSceneNodeFromCameraBB(mCamera);
if (lastSelectedSceneNode)
lastSelectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
if (selectedSceneNode == q3node || selectedSceneNode == bill)
selectedSceneNode = 0;
if (selectedSceneNode)
selectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
lastSelectedSceneNode = selectedSceneNode;
/*
That's it, we just have to finish drawing.
*/
mDriver->endScene();
int fps = mDriver->getFPS();
if (lastFPS != fps)
{
core::stringw str = L"Collision detection example - Irrlicht Engine [";
str += mDriver->getName();
str += "] FPS:";
str += fps;
device->setWindowCaption(str.c_str());
lastFPS = fps;
}
}
device->drop();
// m_pathActor also delete m_Data
delete mPathActor;
delete pathData;
return 0;
}
| true |
276aff9a945a9230903e4d8587061d3a7f4f12b7 | C++ | taceroc/Herr | /4-09/holamundo.cpp | UTF-8 | 240 | 2.71875 | 3 | [] | no_license | #include <iostream> //imprimir pantalla
//#using namespace std;: es mejor std:: dentro de std esta cout
int main(void)
{
double x = 1.0e-6;
std::cout<<"Hola Munduo\n";
// std :: cout<<"Hola Mundo"<<endl;
std::cout<<x<<"\n";
return 0;
}
| true |
3c76f2a7d8b24635b092f61cf73511ab41af4bc9 | C++ | tanv1r/cpp_concurrency_in_action | /c3_protect_shared_data/projects/listing_3_2/MutexNotEnough.cpp | UTF-8 | 1,399 | 3.8125 | 4 | [] | no_license | #include <functional>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class ProtectedData
{
public:
ProtectedData(unsigned x)
: data_(x)
{
}
template<typename Function>
void processData(Function func)
{
// Even though we are protecting access to the data through mutex
// that is not enough, the passed in func can steal the memory address
// of the protected data and then freely manipulate bypassing lock.
// We could prevent the stealing by applying the func on a copy.
//
lock_guard<mutex> funcGuard{ dataLock_ };
// deep copy
// auto copy = data_;
func(data_);
// func(copy);
// copy assignment should be a deep copy as well
// data_ = copy;
}
unsigned data()
{
return data_;
}
private:
unsigned data_ = 0;
mutex dataLock_;
};
unsigned * steal;
void badGuy(unsigned & takeit)
{
// steal the memory address of the protected data
steal = &takeit;
}
int main()
{
ProtectedData protectedData(10);
// prints 10
cout << protectedData.data() << endl;
protectedData.processData(badGuy);
++*steal;
// prints 11
cout << protectedData.data() << endl;
}
| true |
e54dcafa91ef75cb1c748be040ca95cd9e3f756c | C++ | AprilAndFriends/april | /include/april/Cursor.h | UTF-8 | 1,216 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | /// @file
/// @version 5.2
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
///
/// @section DESCRIPTION
///
/// Defines a Cursor object.
#ifndef APRIL_CURSOR_H
#define APRIL_CURSOR_H
#include <hltypes/hltypesUtil.h>
#include <hltypes/hstring.h>
#include "aprilExport.h"
namespace april
{
class Window;
/// @brief Defines a cursor object.
class aprilExport Cursor
{
public:
friend class Window;
/// @brief The filename of the cursor file.
HL_DEFINE_GET(hstr, filename, Filename);
protected:
/// @brief The filename of the cursor file.
hstr filename;
/// @brief Whether loaded from a resource file or a normal file.
bool fromResource;
/// @brief Basic constructor.
/// @param[in] fromResource Whether loaded from a resource file or a normal file.
Cursor(bool fromResource);
/// @brief Destructor.
virtual ~Cursor();
/// @brief Creates an internal curosr object from a filename.
/// @param[in] filename The filename to load.
/// @return True if loading was successful.
virtual bool _create(chstr filename);
};
}
#endif
| true |
d7034d3997723caca31a24ed69346513c945a2b9 | C++ | rsotani/AtCoder | /BeginnerContest/020-029/028/C.cpp | UTF-8 | 419 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> abcde(5);
for (int i=0; i<5; i++) cin >> abcde[i];
vector<int> ans;
for (int i=0; i<3; i++){
for (int j=i+1; j<4; j++){
for (int k=j+1; k<5; k++){
int val = abcde[i]+abcde[j]+abcde[k];
//cout << val << endl;
ans.push_back(val);
}
}
}
sort(ans.begin(), ans.end());
cout << ans[7] << endl;
}
| true |
c15d498b6e327be296c7437dce90aaa20da02db2 | C++ | gingteam/ds | /pointer/stack.cpp | UTF-8 | 1,008 | 3.671875 | 4 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
Node *next;
} Node;
typedef struct {
Node *top;
} Stack;
Node *makeNode(int x) {
Node *a = (Node *) malloc(sizeof(Node));
a->data = x;
return a;
}
void init(Stack &s) {
s.top = NULL;
}
int isEmpty(Stack s) {
return (s.top == NULL);
}
void push(Stack &s, int x) {
Node *pre = s.top;
s.top = makeNode(x);
s.top->next = pre;
}
void pop(Stack &s) {
if (isEmpty(s)) {
printf("Danh sach rong\n");
return;
}
Node *pre = s.top->next;
// Giai phong bo nho
free(s.top);
s.top = pre;
}
void peek(Stack s) {
if (isEmpty(s)) {
printf("Danh sach trong\n");
return;
}
Node *tmp = s.top;
do {
printf("%5d", tmp->data);
tmp = tmp->next;
} while(tmp != NULL);
}
int main() {
Stack a;
init(a);
push(a, 5);
push(a, 6);
push(a, 7);
pop(a);
pop(a);
peek(a);
return 0;
}
| true |
e54ba9763c0d07b277fa14841115b4338b5f3f11 | C++ | jae2900/Programing-study-YJ | /BackJoon/1267_핸드폰 요금.cpp | UTF-8 | 712 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int cnt;
vector <int> num_Y,num_M;
cin >> cnt;
for(int i = 0;i<cnt;i++)
{
int x;
cin >> x;
num_Y.push_back(x);
num_M.push_back(x);
}
int ans_Y = 0, ans_M = 0;
for(int i = 0;i<cnt;i++)
{
while(num_Y[i] > 0)
{
num_Y[i] -= 30;
ans_Y += 10;
}
while(num_M[i] > 0)
{
num_M[i] -= 60;
ans_M += 20;
}
}
if(ans_M > ans_Y)
cout << "Y " << ans_Y;
else if(ans_M < ans_Y)
cout << "M " << ans_M;
else
cout << "Y M " << ans_Y;
return 0;
} | true |
c51d395429ec74c5c3dcbaeaea9dc6507610c4d1 | C++ | luozhancheng/leetcode_cpp | /include/n_queens_ii.h | UTF-8 | 869 | 3.03125 | 3 | [] | no_license | //
// Created by lelezi on 2019-05-13.
//
#ifndef LEETCODE_N_QUEENS_II_H
#define LEETCODE_N_QUEENS_II_H
class Solution {
public:
int totalNQueens(int n) {
if (n < 1)
return 0;
dfs(n, 0, 0, 0, 0);
return count;
}
void dfs(int32_t n, int32_t row, int32_t cols, int32_t pie, int32_t na) {
if (row >= n) {
count += 1;
return;
}
// 得到当前所有的空位
int32_t bits = (~(cols | pie | na)) & ((1 << n) - 1);
while (bits) {
// 取得最低位的1
int32_t p = bits & -bits;
dfs(n, row + 1, cols | p, (pie | p) << 1, (na | p) >> 1);
// 去掉最低位的1
bits = bits & (bits - 1);
}
}
int32_t count = {0};
public:
static void run() {
int ret = Solution().totalNQueens(8);
std::cout << "ret = " << ret << std::endl;
}
};
#endif //LEETCODE_N_QUEENS_II_H
| true |
a93b3fd871512bff52b2359cc7c5a27ac61e6ea9 | C++ | JGuissart/Cpp-MySailingWorld | /Lib/Concurrent.cxx | UTF-8 | 3,411 | 3.28125 | 3 | [] | no_license | #include "Concurrent.h"
#include <iostream>
using namespace std;
Concurrent::Concurrent()
{
setNumeroMatricule(0);
setNomConcurrent("defaut");
setNiveauCapacite(0);
setPlace(0);
pos.setX(0);
pos.setY(0);
setNumeroBouee(0);
}
Concurrent::Concurrent(int nM, std::string nC, float lvlC)
{
setNumeroMatricule(nM);
setNomConcurrent(nC);
setNiveauCapacite(lvlC);
setPlace(0);
pos.setX(0);
pos.setY(0);
setNumeroBouee(0);
}
Concurrent::Concurrent(const Concurrent &c)
{
setNumeroMatricule(c.getNumeroMatricule());
setNomConcurrent(c.getNomConcurrent());
setNiveauCapacite(c.getNiveauCapacite());
setPlace(c.getPlace());
setPosition(c.getPosition());
setNumeroBouee(c.getNumeroBouee());
}
Concurrent::~Concurrent()
{
}
/********* Getters *********/
int Concurrent::getNumeroMatricule() const
{
return numMatricule;
}
string Concurrent::getNomConcurrent() const
{
return nomConcurrent;
}
float Concurrent::getNiveauCapacite() const
{
return niveauCapacite;
}
int Concurrent::getPlace() const
{
return place;
}
int Concurrent::getNumeroBouee() const
{
return numBouee;
}
double Concurrent::getPositionX()
{
return pos.getX();
}
double Concurrent::getPositionY()
{
return pos.getY();
}
Point Concurrent::getPosition() const
{
return pos;
}
/********* Setters *********/
void Concurrent::setNumeroMatricule(const int nM)
{
numMatricule = nM;
}
void Concurrent::setNomConcurrent(const string nC)
{
nomConcurrent = nC;
}
void Concurrent::setNiveauCapacite(const float nC)
{
niveauCapacite = nC;
}
void Concurrent::setPlace(const int pl)
{
place = pl;
}
void Concurrent::setNumeroBouee(const int bouee)
{
numBouee = bouee;
}
void Concurrent::setPositionX(const double x)
{
pos.setX(x);
}
void Concurrent::setPositionY(const double y)
{
pos.setY(y);
}
void Concurrent::setPosition(const Point& p)
{
pos = p;
}
/********* Surcharges d'operateurs *********/
bool Concurrent::operator<(const Concurrent &c)
{
if (getNomConcurrent() < c.getNomConcurrent())
return true;
else
return false;
}
bool Concurrent::operator==(const Concurrent& c)
{
if (getNumeroMatricule() == c.getNumeroMatricule())
return true;
else
return false;
}
ostream& operator<<(ostream& o, const Concurrent& c)
{
cout.precision(4); // Permet de définir la précision d'affichage (nombre de chiffres après la virgule) d'un float/double
o << " " << c.getNumeroMatricule() << " \t\t" << c.getNomConcurrent() << "\t\t" << c.getNiveauCapacite() << "\t\t" << c.getPlace() << "\t" << c.pos;
return o;
}
istream& operator>>(istream& i, Concurrent& c)
{
char nC[256];
int choix = 0;
cout << "Entrez le numero de matricule du concurrent: ";
i >> c.numMatricule;
i.ignore();
cout << "Entrez le nom du concurrent: ";
i.getline(nC, 256);
while (choix < 1 || choix > 3)
{
cout << "Choississez un niveau de capacite: " << endl;
cout << "\t1. Moyen (90%)" << endl;
cout << "\t2. Bon (100%)" << endl;
cout << "\t3. Avance (110%)" << endl;
cout << "Votre choix: ";
i >> choix;
}
c.setNomConcurrent(nC);
if (choix == 1)
c.setNiveauCapacite(0.9);
if (choix == 2)
c.setNiveauCapacite(1);
if (choix == 3)
c.setNiveauCapacite(1.1);
c.setPlace(0);
c.setNumeroBouee(0);
return i;
}
/*******************************************/
| true |
a30c81acb6590c968e22b0ce492ca1597dc79dfe | C++ | guilhermeleobas/maratona | /SPOJ/calcula.cpp | UTF-8 | 1,076 | 2.765625 | 3 | [] | no_license | /*
Problema - CALCULA
http://br.spoj.com/problems/CALCULA/
Guilherme Leobas
*/
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <deque>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
#define num(conta) (int)conta-'0';
int main (){
int sum, aux, cnt, i, op, x, test;
string conta;
sum = 0;
aux = 0;
test = 0;
while (true){
cin >> i;
if (i == 0) break;
cin >> conta;
cnt = 0;
sum = 0;
while (conta[cnt] != '+' && conta[cnt] != '-'){
sum = sum*10 + num(conta[cnt++]);
}
int cont = cnt;
while (cont < conta.size()){
if (conta[cont++] == '+') op = 1;
else op = 0;
aux = 0;
while (conta[cont] != '+' && conta[cont] != '-' && cont < conta.size()){
x = num(conta[cont++]);
if (x != 0){
aux = aux*10 + x;
}
else {
aux = aux*10;
}
}
if (op == 1){
sum += aux;
}
else {
sum -= aux;
}
}
cout << "Teste " << ++test << endl << sum << endl << endl;
}
return 0;
} | true |
93c8ed1a1da5ddcf8e26270e81fd926efeb7356f | C++ | Maigo/gea | /gea/libs/gea_math/src/gea/mth_core/type/half.inl | UTF-8 | 1,742 | 2.609375 | 3 | [] | no_license | namespace gea {
namespace mth {
// state functions
inline bool half::is_zero() const {
return (m_bits & ~HALF_SIGN_MASK) == 0;
}
inline bool half::is_finite() const {
uint16_t exp = HALF_EXP_F(m_bits);
return exp < 31;
}
inline bool half::is_negative() const {
return (m_bits & HALF_SIGN_MASK) != 0;
}
inline bool half::is_normalized() const {
uint16_t exp = HALF_EXP_F(m_bits);
return 0 < exp && exp < 31;
}
inline bool half::is_denormalized() const {
uint16_t exp = HALF_EXP_F(m_bits);
uint16_t frac = HALF_FRAC_F(m_bits);
return exp == 0 && frac != 0;
}
inline bool half::is_infinity() const {
uint16_t exp = HALF_EXP_F(m_bits);
uint16_t frac = HALF_FRAC_F(m_bits);
return exp == 31 && frac == 0;
}
inline bool half::is_nan() const {
uint16_t exp = HALF_EXP_F(m_bits);
uint16_t frac = HALF_FRAC_F(m_bits);
return exp == 31 && frac != 0;
}
// internal represenation access functions
inline uint16_t &half::bits() { return m_bits; }
// compression functions
inline bool half::can_pack(const float &f) {
return HALF_MIN <= f && f <= HALF_MAX;
}
// segment access functions
inline const uint16_t half::HALF_SIGN_F(const uint16_t &x) { return ((x & HALF_SIGN_MASK) >> HALF_SIGN_SHIFT); }
inline const uint16_t half::HALF_EXP_F (const uint16_t &x) { return ((x & HALF_EXP_MASK ) >> HALF_EXP_SHIFT ); }
inline const uint16_t half::HALF_FRAC_F(const uint16_t &x) { return ((x & HALF_FRAC_MASK) >> HALF_FRAC_SHIFT); }
inline float half::overflow() const {
volatile float f = 1e10;
for (int i = 0; i < 10; ++i) // this will overflow before
f *= f; // the for-loop terminates
return f;
}
} // namespace mth //
} // namespace gea //
| true |
8405f360567d1913e05cde22802a2d75b6216da3 | C++ | Michael-prog/ExplorerListView | /src/IItemComparator.h | UTF-8 | 1,559 | 3.09375 | 3 | [
"MIT"
] | permissive | //////////////////////////////////////////////////////////////////////
/// \class IItemComparator
/// \author Timo "TimoSoft" Kunze
/// \brief <em>Communication between the \c CompareItems callback method and the object that initiated the sorting</em>
///
/// This interface allows the \c CompareItems callback method to forward the message to the object
/// that initiated the sorting.
///
/// \sa ::CompareItems, ::CompareItemsEx, ExplorerListView::SortItems
//////////////////////////////////////////////////////////////////////
#pragma once
class IItemComparator
{
public:
/// \brief <em>Compares two items by ID</em>
///
/// \param[in] itemID1 The unique ID of the first item to compare.
/// \param[in] itemID2 The unique ID of the second item to compare.
///
/// \return -1 if the first item should precede the second; 0 if the items are equal; 1 if the
/// second item should precede the first.
///
/// \sa CompareItemsEx, ::CompareItems, ExplorerListView::SortItems
virtual int CompareItems(LONG itemID1, LONG itemID2) = 0;
/// \brief <em>Compares two items by index</em>
///
/// \param[in] itemIndex1 The index of the first item to compare.
/// \param[in] itemIndex2 The index of the second item to compare.
///
/// \return -1 if the first item should precede the second; 0 if the items are equal; 1 if the
/// second item should precede the first.
///
/// \sa CompareItems, ::CompareItemsEx, ExplorerListView::SortItems
virtual int CompareItemsEx(int itemIndex1, int itemIndex2) = 0;
}; // IItemComparator | true |
76f63bbce5b3c40145f16e8ebbb5f7e3ef78d635 | C++ | mitchetm/Legacy-Irrlicht-Multiplayer-RPG | /Code/MoveToComponent.cpp | UTF-8 | 607 | 2.703125 | 3 | [] | no_license | #include "MoveToComponent.h"
MoveToComponent::MoveToComponent()
{
}
MoveToComponent::~MoveToComponent()
{
}
MoveToComponent::MoveToComponent(unsigned int id) : GameComponent(MOVE_TO_COMP, id)
{
x = 0;
y = 0;
z = 0;
}
void MoveToComponent::setMoveToX(float value)
{
x = value;
}
float MoveToComponent::getMoveToX(void)
{
return x;
}
void MoveToComponent::setMoveToY(float value)
{
y = value;
}
float MoveToComponent::getMoveToY(void)
{
return y;
}
void MoveToComponent::setMoveToZ(float value)
{
z = value;
}
float MoveToComponent::getMoveToZ(void)
{
return z;
}
| true |
f8555b10dd477342e4012da2bf654c364ad18a42 | C++ | claassen/GalaxySim3D | /GalaxySim3D/Body.h | UTF-8 | 1,107 | 3.046875 | 3 | [] | no_license | #pragma once
class Body
{
public:
int id;
long long mass;
float x, y, z;
float radius;
float dx, dy, dz;
float ax, ay, az;
float r, g, b;
bool markForDeletion;
Body() : id(0) {}
Body(int id, long long mass, float x, float y, float z, float dx, float dy, float dz)
: id(id), mass(mass), x(x), y(y), z(z), dx(dx), dy(dy), dz(dz), ax(0), ay(0), az(0), markForDeletion(false)
{
setRadiusAndColor();
}
Body(int id, long long mass, float x, float y, float z)
: id(id), mass(mass), x(x), y(y), z(z), dx(0), dy(0), dz(0), ax(0), ay(0), az(0), markForDeletion(false)
{
setRadiusAndColor();
}
bool operator==(const Body& rhs) { return rhs.id == id; }
bool operator!=(const Body& rhs) { return !operator==(rhs); }
void setRadiusAndColor();
//Static methods
static float radiusFromMass(long long mass);
static float distance(const Body& b1, const Body& b2);
static float distance(float x1, float y1, float z1, float x2, float y2, float z2);
static float forceOfGravity(const Body& b1, const Body& b2, float distance, float axisValue);
};
| true |
89976114f27ce323b9c5d4bc949506ae2e1a2220 | C++ | ttan6729/PMRC | /src/trail_backup.cpp | UTF-8 | 4,254 | 2.6875 | 3 | [] | no_license | #include "trail.h"
#include <limits>
using namespace std;
void Trail::Run()
{
// printf("test weight matrix\n");
// for(int i = 0; i < n; i++)
// {
// for(int j = 0; j < n; j++)
// printf("%.3f ",w_matrix[i][j]);
// printf("\n");
// }
printf("begin trail, threshold %lf, number of files %d\n",e,n);
int *trail_set = (int *)malloc(sizeof(int) * n);
memset(trail_set,0,n);
float prev_max = 0.0;
int start = 0, current = 1;
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if( w_matrix[i][j] > prev_max )
{
start = i;
current = j;
prev_max = w_matrix[i][j];
}
}
}
trail_set[start] = 1; trail_set[current] = 1;
int start_max = FindMax(start,trail_set);
int cur_max = FindMax(current,trail_set);
//printf("test: %.4f %.4f\n",w_matrix[start][start_max],w_matrix[current][cur_max]);
if ( w_matrix[start][start_max] > w_matrix[current][cur_max] )
{
int buffer = start;
start = current;
current = buffer;
}
group *cur_group = (group *)malloc(sizeof(group));
kv_init(*cur_group);
kv_push(int, *cur_group, start);
kv_push(int, *cur_group, current);
int count = 2;
vector <int> test_result;
test_result.push_back(start);
test_result.push_back(current);
float average_weight = 0.0;
for (int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
average_weight += w_matrix[i][j];
}
w_threshold = 0.5*average_weight/(n*(n-1));
printf("weight: %d,%d,%lf\n",start,current,w_matrix[start][current]);
while (count < n)
{
int next = FindMax(current,trail_set);
//printf("weight: %d,%d,%lf\n",current,next,w_matrix[current][next]);
trail_set[next] = 1;
if( w_matrix[current][next] >= e * (0.9-3/(cur_group->n+9))* prev_max ||
(w_matrix[current][next] > w_threshold && cur_group->n <=4) )
{
//printf("a\n");
kv_push(int, *cur_group, next);
}
else
{
//printf("b\n");
groups.push_back(cur_group);
cur_group = (group *)malloc(sizeof(group));
kv_init(*cur_group);
kv_push(int, *cur_group, next);
}
test_result.push_back(next);
prev_max = w_matrix[current][next];
current = next;
count++;
}
groups.push_back(cur_group);
printf("test result:\n");
for(int i = 0; i < n; i++)
printf("%d ", test_result[i]);
printf("\n");
free(trail_set);
return;
}
int Trail::FindMax(int id, int *trail_set)
{
float max = 0.0;
int result = -1;
for(int i = 0 ; i < n; i++)
{
if( w_matrix[id][i] > max)
{
if( i != id && trail_set[i] != 1 )
{
result = i;
max = dist_matrix[id][i];
}
}
}
return result;
}
int Trail::FindMin(int id, int *trail_set)
{
float min = numeric_limits<float>::max();
int result = -1;
for(int i = 0 ; i < n; i++)
{
if( dist_matrix[id][i] < min)
{
if( i != id && trail_set[i] != 1 )
{
result = i;
min = dist_matrix[id][i];
}
}
}
return result;
}
void Trail::WriteResult(char *file_name)
{
printf("result write to %s\n",file_name);
ofstream fp;
fp.open(file_name);
printf("begin split, number of groups: %d\n", groups.size());
int total = 0;
for(int i = 0; i < groups.size(); i++)
{
total += groups[i]->n;
printf("start %d, group size:%d\n",groups[i]->a[0],groups[i]->n);
float prev_weight = 0.0;
int count = 0, cur_num = 0;
while( count < (groups[i]->n)-2 && groups[i]->n > 3)
{
//printf("step %d ",count);
int cur = groups[i]->a[count], next = groups[i]->a[count+1];
float cur_weight = w_matrix[cur][next];
double threshold = 5/(10-cur_num);
if(cur_num <= 2 && (cur_weight >= threshold * prev_weight || cur_weight > w_threshold))
{
//printf("a, count %d\n",count);
fp << cur << " ";
cur_num++;
}
else
{
//printf("b, count %d\n",count);
fp << "\n" << cur << " ";
cur_num = 1;
}
count++;
prev_weight = w_matrix[cur][next];
if(cur_num >=2 && count >= ((groups[i]->n)-2) )
fp << "\n";
}
for(int j = count; j < groups[i]->n; j++ )
fp << groups[i]->a[j] << " ";
fp << "\n";
}
printf("included file %d\n",total);
fp.close();
return;
}
void Trail::Split(group *g)
{
}
| true |
0288042f918f8a2e43af5b8cdd46dacff2d692f2 | C++ | rbapub/homebk | /src/Partner.cpp | UTF-8 | 521 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Partner.h"
using std::string;
int Partner::nextId = 1;
Partner::Partner(string pName)
{
id = nextId;
nextId++;
name=pName;
}
int Partner::getId() const
{
return id;
}
void Partner::setId(int i)
{
id = i;
}
string Partner::getName() const
{
return name;
}
void Partner::setName(string n)
{
name = n;
}
Partner::~Partner()
{
}
ostream & operator<<(ostream &output, const Partner &p)
{
output << p.getName() << " (id: " << p.getId() << ')';
return output;
}
| true |
c6b954b731ac97169dd8ae307855f118c6d50b18 | C++ | rouman321/code-practice | /0960-deleteColumnsToMakeSortedIII.cpp | UTF-8 | 782 | 3 | 3 | [] | no_license | /*
LeetCode 960. Delete Columns to Make Sorted III
hard
time 78.21%
space 80%
*/
class Solution {
public:
int minDeletionSize(vector<string>& A) {
int len = A[0].size();
vector<int> dp(len,1);
for(int i = len-2;i >= 0;i--){
for(int j = i+1;j < len;j++){
bool flag = true;
for(int x = 0;x < A.size();x++){
if(A[x][i]>A[x][j]){
flag = false;
break;
}
}
if(flag){
dp[i] = max(dp[i],1+dp[j]);
}
}
}
int ret = 0;
for(int i = 0;i < dp.size();i++){
ret = max(ret,dp[i]);
}
return len-ret;
}
}; | true |
7ea02c9e7b2378977eb74f0d4e1267a4546ac123 | C++ | heyterrance/ctrie_map | /ctrie_map.h | UTF-8 | 11,774 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <algorithm>
#include <array>
#include <string_view>
#include <tuple>
#include <utility>
namespace ctrie {
template<typename... Entries> class index_node;
template<typename T, typename IndexTrie> class array_map;
template<char... Ks>
struct insert_key {
template<typename V>
constexpr std::pair<insert_key, V> operator=(V&& value)
{
return std::make_pair(insert_key{}, std::forward<V>(value));
}
};
constexpr struct default_key_t {
template<typename V>
constexpr std::pair<default_key_t, V> operator=(V&& value) const
{
return std::make_pair(default_key_t{}, std::forward<V>(value));
}
} default_key{};
namespace detail {
template<char K, typename Node> class entry;
template<typename FoundEntry, typename... RemainingEntries> struct found_tag { };
struct not_found_tag { };
template<typename... RemainingEntries>
struct find_record {
template<typename Entry>
constexpr find_record<RemainingEntries..., Entry> operator+(Entry) const { return {}; }
template<typename Entry>
static constexpr found_tag<Entry, RemainingEntries...> found(Entry) { return {}; }
};
template<char K, typename... Searched>
constexpr not_found_tag find_entry_impl(find_record<Searched...>) { return {}; }
template<char K, typename Entry, typename... Entries, typename... Searched>
constexpr auto find_entry_impl(find_record<Searched...> rec, Entry e, Entries... es)
{
constexpr auto match = (rec + ... + es).found(e);
constexpr auto recurse = find_entry_impl<K>(rec + e, es...);
return std::conditional_t<e.matches(K), decltype(match), decltype(recurse)>{};
}
template<char K, typename... Entries>
constexpr auto find_entry(Entries... es) { return find_entry_impl<K>(find_record<>{}, es...); }
template<typename>
constexpr int size_until() { return 0; }
template<typename Entry, typename Entry0, typename... Entries>
constexpr int size_until(Entry0, Entries... es)
{
if constexpr (std::is_same_v<Entry, Entry0>) {
return 0;
}
return Entry0::size() + size_until<Entry>(es...);
}
template<typename T, typename IndexTrie, typename ValuesTup, std::size_t... KeyIdxs, std::size_t... ArrayIdxs>
constexpr auto construct_array_map(
ValuesTup&& values,
std::index_sequence<KeyIdxs...>,
std::index_sequence<ArrayIdxs...>)
{
constexpr auto find_key_idx = [](int arr_idx) -> std::size_t {
std::size_t keyIdxs[] = {KeyIdxs...};
for (int i = 0; i != sizeof...(KeyIdxs); ++i) {
if (keyIdxs[i] == arr_idx) {
return i;
}
}
return sizeof...(KeyIdxs);
};
return array_map<T, IndexTrie>{
std::get<find_key_idx(ArrayIdxs)>(std::forward<ValuesTup>(values))...
};
}
template<char K, typename Node>
class entry {
public:
static constexpr bool is_leaf() { return false; }
static constexpr bool is_default() { return false; }
static constexpr auto min_match_length() { return std::size_t{1} + Node::min_match_length(); }
static constexpr auto max_match_length() { return std::size_t{1} + Node::max_match_length(); }
static constexpr bool matches(char c) { return c == K; }
static constexpr int size() { return Node::size(); }
static constexpr int end() { return Node::end(); }
static constexpr int find(std::string_view s)
{
s.remove_prefix(1);
return Node::find(s);
}
static constexpr bool contains(std::string_view s)
{
s.remove_prefix(1);
return Node::contains(s);
}
template<char... Ks>
static constexpr auto insert(insert_key<Ks...> k)
{
auto new_node = Node::insert(k);
return entry<K, decltype(new_node)>{};
}
};
struct null_entry {
static constexpr bool is_leaf() { return false; }
static constexpr bool is_default() { return false; }
static constexpr bool matches(char) { return false; }
static constexpr int find(std::string_view) { return 0; }
static constexpr bool contains(std::string_view) { return false; }
static constexpr int size() { return 0; }
static constexpr int end() { return 0; }
static constexpr auto min_match_length() { return std::numeric_limits<std::size_t>::max(); }
static constexpr auto max_match_length() { return std::numeric_limits<std::size_t>::min(); }
};
struct leaf_node;
struct default_node;
template<>
class entry<0, leaf_node> : public null_entry {
public:
static constexpr bool is_leaf() { return true; }
static constexpr bool contains(std::string_view) { return true; }
static constexpr int size() { return 1; }
static constexpr int end() { return 1; }
};
template<>
class entry<0, default_node> : public null_entry {
public:
static constexpr bool is_default() { return true; }
};
using leaf_entry = entry<0, leaf_node>;
using default_entry = entry<0, default_node>;
} // namespace detail
template<typename... Entries>
class index_node {
public:
static constexpr bool has_leaf() { return (Entries::is_leaf() || ...); }
static constexpr bool has_default() { return (Entries::is_default() || ...); }
static constexpr auto min_match_length() { return std::min<std::size_t>({Entries::min_match_length()..., 0}); }
static constexpr auto max_match_length() { return std::max<std::size_t>({Entries::max_match_length()..., 0}); }
template<char... Ks>
constexpr auto operator<<(insert_key<Ks...> k) const { return insert(k); }
constexpr auto operator<<(default_key_t k) const { return insert(k); }
template<char K, char... Ks>
static constexpr auto insert(insert_key<K, Ks...> k)
{
return insert_impl(k, detail::find_entry<K>(Entries{}...));
}
static constexpr auto insert(insert_key<>)
{
static_assert(!has_leaf(), "Inserted duplicate keys");
return index_node<Entries..., detail::leaf_entry>{};
}
static constexpr auto insert(default_key_t)
{
static_assert(!has_default(), "Inserted multiple defaults");
return index_node<Entries..., detail::default_entry>{};
}
static constexpr int size() { return (Entries::size() + ... + 0); }
static constexpr int capacity() { return size() + static_cast<int>(has_default()); }
static constexpr int end() { return size(); }
static constexpr bool contains(std::string_view s)
{
if (s.empty()) {
return has_leaf();
}
if (s.length() < min_match_length() || s.length() > max_match_length()) {
return false;
}
char c = s.front();
return ((Entries::matches(c) && Entries::contains(s)) || ...);
}
static constexpr int find(std::string_view s)
{
if (s.empty()) {
if constexpr (has_leaf())
return call_find<detail::leaf_entry>({});
return end();
}
if (s.length() < min_match_length() || s.length() > max_match_length()) {
return end();
}
int result{end()};
char c = s.front();
((Entries::matches(c) && (result = call_find<Entries>(s), true)) || ...);
return result;
}
template<char... Ks>
static constexpr int find(insert_key<Ks...>)
{
constexpr char s[] = {Ks...};
return find(std::string_view{s, sizeof...(Ks)});
}
static constexpr int find(default_key_t)
{
static_assert(has_default());
return end();
}
private:
template<typename Entry>
static constexpr int call_find(std::string_view s)
{
if (auto idx = Entry::find(s); idx != Entry::end()) {
return idx + detail::size_until<Entry>(Entries{}...);
}
return end();
}
template<char K, char... Ks, typename Found, typename... Remaining>
static constexpr auto insert_impl(insert_key<K, Ks...>, detail::found_tag<Found, Remaining...>)
{
auto new_entry = Found::insert(insert_key<Ks...>{});
return index_node<Remaining..., decltype(new_entry)>{};
}
template<char K, char... Ks>
static constexpr auto insert_impl(insert_key<K, Ks...>, detail::not_found_tag)
{
auto new_entry = detail::entry<K, index_node<>>::insert(insert_key<Ks...>{});
return index_node<Entries..., decltype(new_entry)>{};
}
};
template<typename T, typename IndexTrie>
class array_map
{
public:
using index_trie_type = IndexTrie;
using array_type = std::array<T, IndexTrie::capacity()>;
using size_type = typename array_type::size_type;
using value_type = typename array_type::value_type;
using reference = typename array_type::reference;
using const_reference = typename array_type::const_reference;
using iterator = typename array_type::iterator;
using const_iterator = typename array_type::const_iterator;
template<typename... Us>
constexpr explicit array_map(Us&&... us) :
_data{{std::forward<Us>(us)...}}
{ }
static constexpr bool empty() { return IndexTrie::size() == 0; }
static constexpr size_type size() { return IndexTrie::size(); }
static constexpr size_type capacity() { return IndexTrie::capacity(); }
static constexpr size_type index_of(std::string_view s) { return IndexTrie::find(s); }
constexpr reference operator[](std::string_view s) { return operator[](index_of(s)); }
constexpr const_reference operator[](std::string_view s) const { return operator[](index_of(s)); }
constexpr reference operator[](size_type pos) { return _data[pos]; }
constexpr const_reference operator[](size_type pos) const { return _data[pos]; }
static constexpr bool contains(std::string_view s) { return IndexTrie::contains(s); }
constexpr iterator find(std::string_view s) { return std::next(std::begin(_data), index_of(s)); }
constexpr const_iterator find(std::string_view s) const { return std::next(std::begin(_data), index_of(s)); }
constexpr iterator begin() { return std::begin(_data); }
constexpr const_iterator begin() const { return std::begin(_data); }
constexpr iterator end() { return std::next(std::begin(_data), size()); }
constexpr const_iterator end() const { return std::next(std::begin(_data), size()); }
static constexpr bool has_default() { return IndexTrie::has_default(); }
constexpr reference get_default() { return _data.back(); }
constexpr const_reference get_default() const { return _data.back(); }
private:
array_type _data;
};
template<typename... InsertKeys>
constexpr auto build_index(InsertKeys... keys) { return (index_node<>{} << ... << keys); }
template<typename T, typename... InsertKeyValues>
constexpr auto build_map(InsertKeyValues... kvs)
{
constexpr auto index_trie = build_index(kvs.first...);
return detail::construct_array_map<T, decltype(index_trie)>(
std::forward_as_tuple(std::forward<typename InsertKeyValues::second_type>(kvs.second)...),
std::index_sequence<index_trie.find(kvs.first)...>{},
std::make_index_sequence<index_trie.capacity()>());
}
template<typename T, char... Ks, typename... InsertKeys>
constexpr auto build_map(insert_key<Ks...> key, InsertKeys... keys)
{
constexpr auto index_trie = build_index(key, keys...);
return array_map<T, decltype(index_trie)>{};
}
namespace literals {
template<typename T, T... Ks>
constexpr insert_key<Ks...> operator""_key() { return {}; }
} // namespace literals
} // namespace ctrie
| true |
18ccc1c5579985719d8da2286bc5963f5f32d7eb | C++ | JHDReis/MetadataStudy | /metadata/metadataStudy1.h | UTF-8 | 3,078 | 2.71875 | 3 | [] | no_license | //
// Created by Joao Henriques David Dos Reis on 01/04/2018.
//
#ifndef METADATASTUDY_METADATASTUDY1_H
#define METADATASTUDY_METADATASTUDY1_H
/*
* https://www.codeproject.com/Articles/3743/A-gentle-introduction-to-Template-Metaprogramming
* https://monoinfinito.wordpress.com/series/introduction-to-c-template-metaprogramming/
* */
template< unsigned char byte > class BITS_SET
{
public:
enum {
B0 = (byte & 0x01) ? 1:0,
B1 = (byte & 0x02) ? 1:0,
B2 = (byte & 0x04) ? 1:0,
B3 = (byte & 0x08) ? 1:0,
B4 = (byte & 0x10) ? 1:0,
B5 = (byte & 0x20) ? 1:0,
B6 = (byte & 0x40) ? 1:0,
B7 = (byte & 0x80) ? 1:0
};
public:
enum{RESULT = B0+B1+B2+B3+B4+B5+B6+B7};
};
// ---------------------------------
// Factorials
// ---------------------------------
template< int i >
class FACTOR{
public:
enum {
RESULT = i * FACTOR<i-1>::RESULT
};
};
//Specialization and end:
template<>
class FACTOR< 1 >{
public:
enum {RESULT = 1};
};
// ---------------------------------
// Fibonacci
// ---------------------------------
template<unsigned long i>
class FIBONACCI {
public:
enum { RESULT = FIBONACCI<i-1>::RESULT + FIBONACCI<i-2>::RESULT};
};
template<>
class FIBONACCI<0> {
public:
enum { RESULT = 0};
};
template<>
class FIBONACCI<1> {
public:
enum { RESULT = 1};
};
//Fractions
template <int N, int D> struct Frak {
static const long Num = N;
static const long Den = D;
};
template <int N, typename X> struct ScalarMultiplication {
//static const long Num = N * X::Num;
//static const long Den = N * X::Den;
typedef Frak<N*X::Num, N*X::Den> result;
};
//Simplification
template <int X, int Y> struct MCD {
static const long result = MCD<Y, X % Y>::result;
};
//partial specialization
template <int X> struct MCD<X, 0> {
static const long result = X;
};
//simple(fraction) = fraction / mcd(fraction)
template <class F> struct Simpl {
static const long mcd = MCD<F::Num, F::Den>::result;
typedef Frak< F::Num / mcd, F::Den / mcd > result;
//static const long new_num = F::Num / mcd;
//static const long new_den = F::Den / mcd;
//typedef Frak<new_num, new_den> New_Frak;
};
template <typename X1, typename Y1> struct SameBase {
typedef typename ScalarMultiplication< Y1::Den, X1>::result X;
typedef typename ScalarMultiplication< X1::Den, Y1>::result Y;
};
template <typename X, typename Y> struct Sum {
typedef SameBase<X, Y> B;
static const long Num = B::X::Num + B::Y::Num;
static const long Den = B::Y::Den; // == B::X::Den
typedef typename Simpl< Frak<Num, Den> >::result result;
};
//Calculating the total result of the factorial e:
// e = S(1/n!) = 1/0! + 1/1! + 1/2! + ...
template <int N> struct E {
static const long Den = FACTOR<N>::RESULT;
typedef Frak< 1, Den > term;
typedef typename E<N-1>::result next_term;
typedef typename Sum< term, next_term >::result result;
};
template <> struct E<0> {
typedef Frak<1, 1> result;
};
#endif //METADATASTUDY_METADATASTUDY1_H
| true |
805dc7f9aa8e57789cee3b75fd33b035edd70e7e | C++ | StevePunak/KanoopCommonQt | /userutil.cpp | UTF-8 | 1,782 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "userutil.h"
#ifndef __WIN32
#include "unistd.h"
gid_t UserUtil::gidFromName(const QString &name)
{
gid_t ret = 0;
struct group* group;
group = getgrnam(name.toLatin1().constData());
if(group != nullptr)
ret = group->gr_gid;
return ret;
}
uid_t UserUtil::uidFromName(const QString &name)
{
uid_t ret = 0;
struct passwd* passwd;
passwd = getpwnam(name.toLatin1().constData());
if(passwd != nullptr)
ret = passwd->pw_uid;
return ret;
}
QString UserUtil::nameFromGid(gid_t gid)
{
QString ret = 0;
struct group* group;
group = getgrgid(gid);
if(group != nullptr)
ret = group->gr_name;
return ret;
}
QString UserUtil::nameFromUid(uid_t uid)
{
QString ret;
struct passwd* passwd;
passwd = getpwuid(uid);
if(passwd != nullptr)
ret = passwd->pw_name;
return ret;
}
uid_t UserUtil::currentUser()
{
return uidFromName(currentUserName());
}
QString UserUtil::currentUserName()
{
char buf[1024];
if(getlogin_r(buf, sizeof(buf)) != 0)
buf[0] = 0;
return QString(buf);
}
QString UserUtil::currentUserFullName()
{
QString result;
struct passwd* passwd;
passwd = getpwnam(currentUserName().toLatin1().constData());
if(passwd != nullptr)
result = passwd->pw_gecos;
return result;
}
bool UserUtil::isUserMemberOfGroup(uid_t uid, gid_t gid)
{
struct passwd* pw = getpwuid(uid);
if(pw == nullptr)
return false;
int ngroups = 0;
getgrouplist(pw->pw_name, pw->pw_gid, nullptr, &ngroups);
gid_t groups[ngroups];
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
for(int i = 0;i < ngroups;i++)
if(groups[i] == gid)
return true;
return false;
}
#endif
| true |
af80f40bc44234e0a71b0fbc8c4ef2aa68c9f8cc | C++ | zachprinz/Snag_Mobile | /Classes/Level.cpp | UTF-8 | 3,520 | 2.859375 | 3 | [] | no_license | #include "Level.h"
#include "NDKHelper/NDKHelper.h"
#include "User.h"
#include <string.h>
#include <iostream>
#include <vector>
#include <algorithm>
Level::Level(){
map["data"] = "<Map></Map>";
uploaded = false;
}
Level::Level(ValueMap map){
setMap(map);
uploaded = true;
}
std::vector<Entity*> Level::getEntities(){
return mapToEntities();
}
void Level::setEntities(std::vector<Entity*> entities){
clear();
entitiesToMap(entities);
}
void Level::save(){
Value parameters = Value(map);
if(uploaded)
sendMessageWithParams("saveLevel", parameters);
else
sendMessageWithParams("newLevel", parameters);
uploaded = true;
}
void Level::clear(){
map.erase("data");
}
void Level::entitiesToMap(std::vector<Entity*> entities){
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement* map = doc.NewElement("Map");
for(int x = 0; x < entities.size(); x++){
if(entities[x] != NULL){
tinyxml2::XMLElement* entity = doc.NewElement("entity");
entity->SetAttribute("type", TAG_TO_TYPE(entities[x]->getTag()));
entity->SetAttribute("x", entities[x]->getPosition().x);
entity->SetAttribute("y", entities[x]->getPosition().y);
entity->SetAttribute("width", entities[x]->getSize().x);
entity->SetAttribute("height", entities[x]->getSize().y);
entity->SetAttribute("xVelocity", entities[x]->getLaunchVelocity().x);
entity->SetAttribute("yVelocity", entities[x]->getLaunchVelocity().y);
map->InsertFirstChild(entity);
}
}
doc.InsertFirstChild(map);
tinyxml2::XMLPrinter printer;
doc.Print(&printer);
this->map["data"] = printer.CStr();
}
std::vector<Entity*> Level::mapToEntities(){
std::vector<Entity*> ents;
tinyxml2::XMLDocument doc;
doc.Parse(map["data"].asString().c_str());
if(doc.ErrorID())
printf("Error Parsing Map from String");
tinyxml2::XMLElement* root = doc.RootElement();
if(root->FirstChildElement() != NULL){
tinyxml2::XMLElement* iterEnt = root->FirstChild()->ToElement();
bool first = true;
do{
if(!first){
iterEnt = iterEnt->NextSiblingElement();
} else {
first = false;
}
Vec2 tempPos(iterEnt->IntAttribute("x"), iterEnt->IntAttribute("y"));
Vec2 tempSize(iterEnt->IntAttribute("width"), iterEnt->IntAttribute("height"));
Vec2 tempVelocity(iterEnt->IntAttribute("xVelocity"), iterEnt->IntAttribute("yVelocity"));
int tempType = iterEnt->IntAttribute("type");
ents.push_back(Entity::createEntity(tempType, tempPos, tempSize, tempVelocity));
} while(iterEnt->NextSiblingElement());
}
return ents;
}
std::string Level::getName(){
return map["name"].asString();
}
std::string Level::getAuthor(){
return map["author"].asString();
}
int Level::getNumFavorites(){
return std::atoi(map["favorites"].asString().c_str());
}
bool Level::getPublic(){
return (map["status"].asString().compare("Public") == 0);
}
void Level::setPublic(bool isPublic){
if(isPublic)
map["status"] = "Public";
else
map["status"] = "Private";
}
bool Level::getIsFavorited(){
if(map["favorited"].asString().compare("true") == 0)
return true;
return false;
}
void Level::setName(std::string n){
map["name"] = n;
}
void Level::setMap(ValueMap map){
this->map = map;
} | true |
20bd278672296205aae0fcd4d0b532138345c203 | C++ | amedeo-giuliani/programming-for-tlc | /lab4/mac-hdr.cpp | UTF-8 | 979 | 2.703125 | 3 | [] | no_license | #include "mac-hdr.h"
#include <cmath>
bool mac_hdr::serialize(char* buffer, size_t& offset) const{
for(int i = 0; i < sn_size; i++){
buffer[(int)std::floor(offset/8)] |= (char) ((sn >> i & 1U) << offset%8);
offset++;
}
for(int i = 0; i < addr_size; i++){
buffer[(int)std::floor(offset/8)] |= (char) ((src >> i & 1U) << offset%8);
offset++;
}
for(int i = 0; i < addr_size; i++){
buffer[(int)std::floor(offset/8)] |= (char) ((dest >> i & 1U) << offset%8);
offset++;
}
return true;
}
bool mac_hdr::deserialize(char* buffer, size_t& offset){
sn = 0; src = 0; dest = 0;
for(int i = 0; i < sn_size; i++){
sn |= (buffer[(int)std::floor(offset/8)] >> offset%8 & 1U) << i;
offset++;
}
for(int i = 0; i < addr_size; i++){
src |= (buffer[(int)std::floor(offset/8)] >> offset%8 & 1U) << i;
offset++;
}
for(int i = 0; i < addr_size; i++){
dest |= (buffer[(int)std::floor(offset/8)] >> offset%8 & 1U) << i;
offset++;
}
return true;
}
| true |
a52e6969781c638cac582cfa65c119e1e50fd74d | C++ | eslam733/c-plus-plus-projects | /sort_array_2d.cpp | UTF-8 | 1,064 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
// Bulbasaur
struct Interval
{
int start, end;
};
bool compareInterval(Interval i1, Interval i2)
{
if((i1.start != i2.start))
return (i1.start > i2.start);
else
{
return (i1.start == i2.start && i1.end < i2.end);
}
}
bool compareInterval2(Interval i1, Interval i2)
{
return (i1.start == i2.start && i1.end < i2.end);
}
int main(void)
{
int n, k; cin >> n >> k;
struct Interval arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i].start;
cin >> arr[i].end;
}
sort(arr, arr+n, compareInterval);
//sort(arr, arr+n, compareInterval2);
// for (int i = 0; i < n; i++)
// {
// cout << arr[i].start << " ";
// cout << arr[i].end << endl;
// }
int cont = 0;
for (int i = 0; i < n; i++)
{
if(arr[k-1].start == arr[i].start && arr[k-1].end == arr[i].end)
cont++;
}
cout << cont;
return 0;
} | true |
56789fa90065adef37628fc3e890c4c560aae5f2 | C++ | BartoszewskiA/PodstawyProgramowaniaST20 | /w04p03.cpp | UTF-8 | 298 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int x;
int tab[32];
cout << "x=";
cin >> x;
int n = 0;
do
{
tab[n] = x % 2;
x = x / 2;
n++;
} while (x > 0);
for (int i = n - 1; i >= 0; i--)
cout << tab[i];
return 0;
} | true |
2af368e96003014b39a64bc40eb04d61ac09d93e | C++ | valerieSergeevna/aistrd | /UnitTest1/list_unittest.cpp | WINDOWS-1251 | 11,644 | 3.234375 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include <stdexcept>
#include "../3/List.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod_size)
{
List<int> list2;
list2.push_back(40);
list2.push_back(10);
list2.push_back(50);
size_t size = 3;
Assert::IsTrue(list2.get_size() == size);
}
TEST_METHOD(TestMethod_size_Empty)
{
List<int> list2;
Assert::IsTrue(list2.get_size() == 0);
}
TEST_METHOD(TestMethod_push_back)
{
List<int> list2;
list2.push_front(40);
list2.push_front(10);
list2.push_back(50);
size_t data = 50;
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_push_back_empty)
{
List<int> list2;
list2.push_back(50);
size_t data = 50;
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_pop_back)
{
List <int>list2;
list2.push_front(40);
list2.push_front(10);
list2.push_back(50);
list2.pop_back();
size_t data = 40;
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_pop_back_one)
{
List<int> list2;
list2.push_front(40);
list2.pop_back();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_push_front)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
size_t data = 10;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_push_front_empty)
{
List<int> list2;
list2.push_front(10);
size_t data = 10;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_pop_front)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.pop_front();
size_t data = 50;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_at)
{
List <int>list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
size_t data = 50;
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_at_front)
{
List <int>list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
size_t data = 10;
Assert::IsTrue(list2.at(0) == data);
}
TEST_METHOD(TestMethod_isEmpty)
{
List<int> list2;
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_isEmpty_one)
{
List<int> list2;
list2.push_front(10);
Assert::IsFalse(list2.isEmpty());
}
TEST_METHOD(TestMethod_set)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.set(1, 9);
size_t data = 9;
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_clear)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.clear();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_clear_one)
{
List<int> list2;
list2.push_front(10);
list2.clear();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_clear_Empty)
{
List<int> list2;
try
{
list2.clear();
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("List is empty", error.what());
}
}
//
// ,
TEST_METHOD(TestMethod_Del)
{
int data = 50;
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.Delete(1);
Assert::AreEqual(list2.at(1), data);
}
TEST_METHOD(TestMethod_Del_front)
{
int data = 50;
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.Delete(0);
Assert::AreEqual(list2.at(0), data);
}
TEST_METHOD(TestMethod_Del_back)
{
int data = 50;
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.Delete(2);
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_Del_One)
{
List<int> list2;
list2.push_back(50);
list2.Delete(0);
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_Del_Empty)
{
List<int> list2;
try
{
list2.Delete(1);
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("List is empty", error.what());
}
}
TEST_METHOD(TestMethod_Insert)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.insert(1, 1);
size_t data = 1;
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_Insert_0)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.insert(1, 0);
size_t data = 1;
Assert::IsTrue(list2.at(0) == data);
}
TEST_METHOD(TestMethod_Insert_to_Empty)
{
List<int> list2;
try
{
list2.insert(1, 0);
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("Index is greater than list size", error.what());
}
}
TEST_METHOD(TestMethod_Insert_end)
{
List<int> list2;
list2.push_back(50);
list2.push_back(40);
list2.push_front(10);
list2.insert(1, 2);
int data = 1;
Assert::AreEqual(list2.at(2), data);
}
//string
TEST_METHOD(TestMethod_size_string)
{
List<string> list2;
list2.push_back("pop");
list2.push_back("nos");
list2.push_back("son");
size_t size = 3;
Assert::IsTrue(list2.get_size() == size);
}
TEST_METHOD(TestMethod_size_Empty_string)
{
List<string> list2;
Assert::IsTrue(list2.get_size() == 0);
}
TEST_METHOD(TestMethod_push_back_string)
{
List<string> list2;
list2.push_front("pop");
list2.push_front("nos");
list2.push_back("son");
string data = "son";
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_push_back_empty_string)
{
List<string> list2;
list2.push_back("son");
string data = "son";
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_pop_back_string)
{
List <string>list2;
list2.push_front("pop");
list2.push_front("nos");
list2.push_back("son");
list2.pop_back();
string data = "pop";
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_pop_back_one_string)
{
List<string> list2;
list2.push_front("pop");
list2.pop_back();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_push_front_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
string data = "nos";
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_push_front_empty_string)
{
List<string> list2;
list2.push_front("nos");
string data = "nos";
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_pop_front_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.pop_front();
string data = "son";
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_at_string)
{
List <string>list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
string data = "son";
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_at_front_string)
{
List <string>list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
string data = "nos";
Assert::IsTrue(list2.at(0) == data);
}
TEST_METHOD(TestMethod_isEmpty_string)
{
List<string> list2;
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_isEmpty_one_string)
{
List<string> list2;
list2.push_front("nos");
Assert::IsFalse(list2.isEmpty());
}
TEST_METHOD(TestMethod_set_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.set(1, "con");
string data = "con";
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_clear_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.clear();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_clear_one_string)
{
List<string> list2;
list2.push_front("nos");
list2.clear();
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_clear_Empty_string)
{
List<string> list2;
try
{
list2.clear();
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("List is empty", error.what());
}
}
TEST_METHOD(TestMethod_Del_string)
{
string data = "son";
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.Delete(1);
Assert::AreEqual(list2.at(1), data);
}
TEST_METHOD(TestMethod_Del_front_string)
{
string data = "son";
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.Delete(0);
Assert::AreEqual(list2.at(0), data);
}
TEST_METHOD(TestMethod_Del_back_string)
{
string data = "son";
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.Delete(2);
Assert::IsTrue(list2.get_back() == data);
}
TEST_METHOD(TestMethod_Del_One_string)
{
List<string> list2;
list2.push_back("son");
list2.Delete(0);
Assert::IsTrue(list2.isEmpty());
}
TEST_METHOD(TestMethod_Del_Empty_string)
{
List<string> list2;
try
{
list2.Delete(1);
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("List is empty", error.what());
}
}
TEST_METHOD(TestMethod_Insert_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.insert("cat", 1);
string data = "cat";
Assert::IsTrue(list2.at(1) == data);
}
TEST_METHOD(TestMethod_Insert_0_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.insert("cat", 0);
string data = "cat";
Assert::IsTrue(list2.at(0) == data);
}
TEST_METHOD(TestMethod_Insert_to_Empty_string)
{
List<string> list2;
try
{
list2.insert("cat", 0);
}
catch (const std::out_of_range& error)
{
Assert::AreEqual("Index is greater than list size", error.what());
}
}
TEST_METHOD(TestMethod_Insert_end_string)
{
List<string> list2;
list2.push_back("son");
list2.push_back("pop");
list2.push_front("nos");
list2.insert("cat", 2);
string data = "cat";
Assert::AreEqual(list2.at(2), data);
}
//double
TEST_METHOD(TestMethod_push_front_double)
{
List<double> list2;
list2.push_back(50);
list2.push_back(0.40);
list2.push_front(10.908);
double data = 10.908;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_push_front_empty_double)
{
List<double> list2;
list2.push_front(0.101);
double data = 0.101;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_pop_front_double)
{
List<double> list2;
list2.push_back(0.50);
list2.push_back(0.140);
list2.push_front(12.10);
list2.pop_front();
double data = 0.50;
Assert::IsTrue(list2.get_front() == data);
}
TEST_METHOD(TestMethod_at_double)
{
List <double>list2;
list2.push_back(0.050);
list2.push_back(0.40);
list2.push_front(10);
double data = 0.050;
Assert::IsTrue(list2.at(1) == data);
}
};
} | true |
e2b0a5d751f954948228c631d8ff421ca9c36c06 | C++ | decoda/clien-server-sync | /client/BufferStream.h | UTF-8 | 659 | 2.90625 | 3 | [] | no_license | #ifndef BufferStream_h__
#define BufferStream_h__
class MySocket;
class BufferStream
{
public:
BufferStream(uint32 bufflen);
~BufferStream(void);
bool Read(void* destination, size_t bytes);
bool Write(const void* data, size_t bytes);
int32 SocketFlush(MySocket *pSocket);
int32 SocketFill(MySocket *pSocket);
uint32 Size() const;
uint32 Space() const;
bool Resize();
void Clear()
{
m_nHead = m_nTail = 0;
}
private:
int32 Recv(SOCKET s, int32 len);
int32 Send(SOCKET s, int32 len);
private:
char *m_buffer;
uint32 m_nBufferLen;
uint32 m_nHead;
uint32 m_nTail;
};
#endif // BufferStream_h__
| true |
acf091e932bab6bc6aa7c67312ee6b5c91bbf4e2 | C++ | flopezv95/Programacion3D | /Practica5/plantilla3d/project/Model.h | UTF-8 | 277 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Entity.h"
#include <iostream>
class Mesh;
class Model : public Entity
{
public:
Model(const std::shared_ptr<Mesh>& mesh);
virtual void draw(float deltaTime, float angle, bool rotateInTime = false) override;
private:
std::shared_ptr<Mesh> myMesh;
}; | true |
aac2ca5fea4b1649dfa154f359b0b2ba71d5fd81 | C++ | geranium12/Programming | /C++/Labs/Labs1Sem/Assembler/5ChainString/strpbrk.cpp | WINDOWS-1251 | 2,694 | 3.640625 | 4 | [] | no_license | /*
. 1 . 7 .
:
strpbrk <cstring>.
:
s1 s1
s2.
s1 .
s2 s1.
:
input output
1 12345 45
45 5
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int STR_LENGTH = 105;
// , s1
//- , s2 ( NULL).
//STRPBRK y s1 , NULL-y,
// s2 s1 .
char* STRPBRK(char *s1, char *s2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int i = 0; int j = 0;
char *c = NULL;
while (i < len1)
{
j = 0;
while (j < len2)
{
if (s2[j] == s1[i])
{
c = &s1[i];
j = -1;
break;
}
j++;
}
if (j == -1)
break;
i++;
}
return c;
}
char* STRPBRK_ASM(char *s1, char *s2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int i = 0, j = 0;
char *c = NULL;
_asm
{
mov ebx, 0
for1: mov c, NULL
cmp ebx, len1
je exit1
mov edi, s1
mov al, [edi + ebx]
inc ebx
mov ecx, len2
mov edi, s2
repne scasb
mov esi, s1
dec ebx
add esi, ebx
inc ebx
mov c, esi
cmp ecx, 0
jne exit1
jmp for1
exit1 :
}
return c;
}
int main()
{
setlocale(LC_ALL, ".1251");
char *str1 = new char[STR_LENGTH];
char *str2 = new char[STR_LENGTH];
cout << "Enter the first string in which we will search symbols from the second string." << endl;
fgets(str1, STR_LENGTH, stdin);
cout << "Enter the second string from which we will search symbols in the first string." << endl;
fgets(str2, STR_LENGTH, stdin);
cout << "Mine implementation // C++ Code:" << endl;
int i = 1;
char *c = strpbrk(str1, str2);
while (c != NULL)
{
cout << i << '\t';
cout << c << endl;
c = strpbrk(c + 1, str2);
i++;
}
cout << endl;
cout << "Mine implementation // Assembly Code:" << endl;
i = 1;
c = STRPBRK_ASM(str1, str2);
while (c != NULL)
{
cout << i << '\t';
cout << c << endl;
c = STRPBRK_ASM(c + 1, str2);
i++;
}
cout << endl;
system("pause");
} | true |
b308efaf1592d429874af56a76d942dc9e873e40 | C++ | tumluliu/hengii | /server/core/trackerenv.h | UTF-8 | 4,878 | 2.5625 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: trackerenv.h
*
* Description: tracker env, contains resources cleanup functionality
*
* Version: 1.0
* Created: 05/21/2012 04:38:14 PM
* Revision: none
* Compiler: gcc
*
* Author: YANG Anran (), 08to09@gmail.com
* Organization:
*
* =====================================================================================
*/
#ifndef TRACKERENV_H_
#define TRACKERENV_H_
/* DESIGN DECISION:
* This class abstract the object runtime env, which will do some cleanup after the
* object die.
* I previously make this a wrapper, and do a lot analysis. But when I reverse the relationship
* and change it to the metaphor of env, everything seems finally get its place. In fact,
* it is a nice journey of this refactoring because the code is less and I remove
* several warnings.
*
* I didn't delete the part of previous analysis below because it is still inspiring,
* especially for item 1. As for item 2, it is nearly deprecated but the conclusion still
* helps, except that it should be now state as:
*
* this design consists of a TYPICAL factory and a less typical but
* rather CLEAR runtime env(the env clean himself just like system clean a object's living
* env. e.g. some index or statistic data)
*
* by YANG Anran @ 2012.5.22
*
* This class exists due to the needs for some cleanups related to
* runtime env. Till now, it is only for lock/unlock data that the tracker consumes.
* There are several methods to do the job. Except for this, the unlock logic can be
* simply put into the tracker's destructor. But on that senario, the tracker's interface is
* polluted and may explode when extra cleanup needs occur.
*
* This class wraps the tracker, which decomples the run&trace logic from cleanup, and the
* cleanup can be easily acheived by a smart pointer to the wrapper class.
*
* some potential worrying and revisons:
* 1. The resource allocate/cleanup are not balanced. Factory consumes resource and
* this class free them
* revision: Resources does NOT have to be balanced in this manner. With an
* unambigious ownership shipping(factory creates a product), the cleanup
* responsibility now falls on the receiver class.
* In fact, the balanced manner may cause some unefficiency due to the imbalance lying in
* the knowledge requirements of create/destroy: in most cases, destroy is far easier.
* (the same in real life, isn't it?) So, it may not be a wise choice to always let the
* creator waiting for long long time only to do little work comparing to the creating
* task. Rather, the creator just transfer ownership and the receiver will do all the
* other work. Further more, it seems factory returning smart pointer, or even GC in
* smarter languages works in this manner.
* 2. I feel bad as if the borrow/return factory is back, now even with a class more
* it seems the borrow/return factory is back.
* revision: I cannot persuade myself fully, but to get back borrow/return factory is
* less clear than this design. Reasons: 1) the borrow/return factory must be held
* too to wait for the returning. Then if it is used as this class, i.e. as a wrapper
* and tracker center simply keeps its smart pointer, the complex building logic seems
* not proper. 2) this design consists of a TYPICAL factory and a less typical but
* rather CLEAR resource ptr(It is like the smart pointer not only manages memory but
* also other resources).
* by YANG Anran @ 2012.5.21 */
#include <memory>
/*-----------------------------------------------------------------------------
* forward declarations to eliminate compiling dependencies
*-----------------------------------------------------------------------------*/
class DataRepo;
/*
* =====================================================================================
* Class: TrackerEnv
* Description: He wrap tracker, do some cleanup when dies
* =====================================================================================
*/
class TrackerEnv
{
public:
/* ==================== LIFECYCLE ======================================= */
TrackerEnv(DataRepo &, int64_t);/* constructor for empty ptr */
~TrackerEnv();
private:
/* ==================== DATA MEMBERS ======================================= */
DataRepo &datarepo_;
int64_t trackerid_;
/* ==================== DISABLED ======================================= */
/* These MUST be disabled because when it is destructed it will free
* resources of its internal tracker, then the copy will leads to too early free
* or even double free! */
TrackerEnv(const TrackerEnv &);
TrackerEnv &operator= (const TrackerEnv &);
}; /* ----- end of class TrackerEnv ----- */
#endif
| true |
80ee9f5cd97c285458d4b219f1cddf31a03f2d4d | C++ | songxinjianqwe/CppPrimerCode | /Charpter10/src/344diy.cpp | GB18030 | 1,404 | 3.765625 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//Ʋ
//Ĭǰ<ؽ
//ûأҪԣԼƣһֶƷǴȽϵĺ
//ע⺯ΪʱҪд()
extern void deDuplication(vector<string> & sVec);
//ϣȰͬİֵ
//ҪȰֵٰճҳ㷨ڳȵԪزıǵĴ
//sortһ汾ܵһν
//νһɵõıʽ䷵ؽһֵ
//һԪνʺͶԪνʣһԪνζֻܵһԪνʽ
//һԪνʲsortν<
bool isShorter(const string & s1,const string & s2){
return s1.size() < s2.size();
}
//
//stable_sort㷨ȶ㷨Ԫصԭ˳
void test12(){
vector<string> sVec = { "the", "quick", "red", "fox", "jumps", "over",
"the", "slow", "red", "turtle" };
deDuplication(sVec);
stable_sort(sVec.begin(),sVec.end(),isShorter);
for(const auto & s:sVec){
cout<<s<<"\t";
}
cout<<endl;
}
| true |
7ad74b043f2662bb512026bdfb3183c6cdc7f122 | C++ | Phirxian/sacred-fractal | /src/sounds/generator/TriangleGenerator.h | UTF-8 | 774 | 2.765625 | 3 | [] | no_license | #ifndef __SACRED_TRIANGLEGENERATOR__
#define __SACRED_TRIANGLEGENERATOR__
/**
* @file TriangleGenerator.h
* @brief Declares the TriangleGenerator class
*
* @author Adrien Grosjean
* @version 1.1
* @date April 27 2017
**/
#include "Generator.h"
namespace sacred
{
namespace sounds
{
/**
* @class TriangleGenerator
* @brief A Generator for triangle waveforms
**/
class TriangleGenerator : public Generator
{
public:
TriangleGenerator(double f=1000.0, double a=1.0, double ph=0.0, bool stereo=true);
virtual const char* getTypeName() const { return "Triangle"; }
protected:
SampleType genSample(double time) override;
};
}
}
#endif
| true |
f961f9902a5c600fc5ae77291a35b634174f1997 | C++ | Hao1Zhang/OOP | /practical-02/main-2-2.cpp | UTF-8 | 358 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
extern int binary_to_number(int (*)[6] , int number_of_digits)
int main()
{
int binary_digits[6] = { 1, 0, 1, 1, 1, 0 };
int number_of_digits=binary_to_number(binary_digits,(sizeof(binary_digits)/sizeof(binary_digits[0])));
cout << "" << binary_to_number(binary_digits,number_of_digits) << endl;
}
| true |
bc60aa6ef61e39cdae6a0f165678636ffbaef231 | C++ | mm-89/edit_uv_sa | /SpreadSheet.cpp | UTF-8 | 2,433 | 2.65625 | 3 | [] | no_license | #include "SpreadSheet.h"
#include <algorithm>
#include "IOCSV.h"
using namespace std;
SpreadSheet::SpreadSheet()
{
type = ST_Count;
for(int i = 0; i < ST_Count; i++)
{
SpreadSheetTypes thisType = (SpreadSheetTypes)i;
if(!isSupported(thisType)) continue;
if(type == ST_Count)
{ type = thisType;
// Add children
children[thisType] = new IOCSV();
}
}
}
SpreadSheet::~SpreadSheet()
{
for(auto it = children.begin(); it != children.end(); it++)
delete it->second;
}
int SpreadSheet::test()
{
return current()->test();
}
#include <QDebug>
int SpreadSheet::init(const char *fileName)
{
std::string ext = fileName;
ext = ext.substr(ext.length() - 3, 3);
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
ext = "*." + ext;
for(auto it = children.begin(); it != children.end(); it++)
if(it->second->extensions().contains(ext.c_str()))
{
type = it->first;
break;
}
return current()->init(fileName);
}
int SpreadSheet::open(const char *fileName)
{
return current()->open(fileName);
}
string SpreadSheet::read(int nRow, int nColumn)
{
return current()->read(nRow, nColumn);
}
Date SpreadSheet::readTimeStamp(int nRow)
{
return current()->readTimeStamp(nRow);
}
int SpreadSheet::searchDateRow(const Date &searchedDate)
{
return current()->searchDateRow(searchedDate);
}
Date *SpreadSheet::getFirstDate()
{
return current()->getFirstDate();
}
Date *SpreadSheet::getLastDate()
{
return current()->getLastDate();
}
int SpreadSheet::getTimeStep()
{
return current()->getTimeStep();
}
QStringList SpreadSheet::extensions() const
{
QStringList res;
for(auto it = children.begin(); it != children.end(); it++)
{
IOSpreadSheet *child = it->second;
QStringList subRes = child->extensions();
for(int j = 0; j < subRes.size(); j++)
res << subRes[j];
}
return res;
}
void SpreadSheet::readTimeData()
{
current()->readTimeData();
}
int SpreadSheet::searchExcelRow(int searchedNumber, int startRow, int column)
{
return current()->searchExcelRow(searchedNumber, startRow, column);
}
IOSpreadSheet *SpreadSheet::current()
{
return children[type];
}
bool SpreadSheet::isSupported(SpreadSheet::SpreadSheetTypes type) const
{
switch(type)
{
case ST_Excel:
return false;
case ST_CSV:
return true;
default:
return false;
}
}
| true |
45ea2caac5e4f717fa9d3ea92c7a7c1151b2c1ae | C++ | koonom/project-euler | /src/prob-077.cpp | UTF-8 | 1,093 | 2.84375 | 3 | [] | no_license | #include <iostream>
const int N = 100;
int k[N + 1][N + 1]; // Enough for k(N, N - 1)
bool composite[N + 1];
int main() {
for (int n = 2; n <= N / 2; ++n)
if (!composite[n])
for (int m = n + n; m <= N; m += n) composite[m] = true;
//--------------------------------------------------
// k(0, n) = k(m, 0) = 0 for all m, n
// k(1, n) = k(m, 1) = 0 for all m, n
//
// k(m, n) = k(m, m - 1) + 1 if n >= m
// = \sum_{j = 1 .. n} k(m - j, j) otherwise
//--------------------------------------------------
for (int i = 0; i <= N; ++i) k[0][i] = k[i][0] = 0;
for (int i = 1; i <= N; ++i) k[1][i] = k[i][1] = 0;
for (int m = 2; m <= N; ++m) {
for (int n = 2; n < m; ++n) // assume k[m][n] set to 0
for (int j = 2; j <= n; ++j)
if (!composite[j]) k[m][n] += k[m - j][j];
int carry = !composite[m];
for (int n = m; n <= N; ++n) k[m][n] = k[m][m - 1] + carry;
}
int n = 2;
for (; n <= N; ++n)
if (k[n][n - 1] >= 5000) break;
std::cout << n << "\n";
return 0;
}
| true |
479786ca451277cf86e31ffba76f010171eafc22 | C++ | noizzEmpresaOficial/sistemas_informacion | /main.cpp | UTF-8 | 333 | 2.9375 | 3 | [] | no_license | //Inicio de esta nueva aventura de programación
#include <iostream>
int main()
{
std::cout << "Hola mundo!" << std::endl;
std::cout << "Este es un gran día para crear una app" << std::endl;
std::cout << "Pero necesito concentrarme para ello, un poco de ruido blanco me vendría bien..." << std::endl;
return 0;
} | true |
3348913d986692b7abf4ee0f73e8fab619696055 | C++ | baibolatovads/work | /Algorithms and Data Structures/Midterm/H.cpp | UTF-8 | 387 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string s;
int main(){
cin >> s;
vector<int> num;
int n = s.size();
for(int i = 0; i < s.size(); i++){
char ch = s[i];
if(ch >= 48 && ch <= 57){
int numb = ch - '0';
num.push_back(numb);
}
}
sort(num.begin(), num.end());
cout << num[0];
for(int i = 1; i < num.size(); i++){
cout << "+" << num[i];
}
return 0;
} | true |
ac3e9efcc105e8922e8b267215dffe74db1d7293 | C++ | zmiksis/SciComp | /21210_Spring2017/SP2017_me/exam/untitled.cpp | UTF-8 | 657 | 3.015625 | 3 | [] | no_license | #ifndef WEATHER_H
#define WEATHER_H
#include <string>
#include <vector>
class Weather{
// Public interface
public:
Weather(std::string country, std::string state, std::string town, std::vector<int> temperature, std::vector<int> rain, int projected);
// Accessors / Getters
std::string get_full_name();
float get_final_grade();
// Mutators / Setters
void set_final_grade();
// Private interface
private:
// Student data
std::string fn; // First Name
std::string ln; // Last Name
std::vector<int> hw; // Homework scores
std::vector<int> ex; // Exam scores
int fin; // Final Exam score
float gp; // Grade percent
};
#endif | true |
3a123bf038aaecbdfb5989a071475132763199c0 | C++ | ydkhub/algorithm | /code/查并集.cpp | GB18030 | 749 | 2.515625 | 3 | [] | no_license | #include<cstdio>
const int maxn=100000001;
int father[maxn];
int isf[maxn];
void init(int n){
for(int i=0;i<n;i++){
father[i]=i;
isf[i]=1;
}
}
//ʼ
int findfather(int x){
int a=x;
while(x!=father[x]){
x=father[x];
}
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
//
void Union(int a,int b){
int faa=findfather(a);
int fab=findfather(b);
if(faa!=fab){
father[faa]=fab;
isf[fab]+=isf[faa];
}
}
//ϲ
int main(){
int n;
int a,b;
while(scanf("%d",&n)!=EOF){
init(maxn);
for(int i=0;i<n;i++){
scanf("%d%d",&a,&b);
Union(a,b);
}
int ans=1;
for(int i=0;i<maxn;i++){
if(isf[i]>ans)
ans=isf[i];
}
printf("%d",ans);
}
return 0;
}
| true |
8867966714d47bbfd59e28e0c99b99e0e508e455 | C++ | HaDriell/Permafrost | /Permafrost/include/Permafrost/Core/CommonTypes.h | UTF-8 | 938 | 2.765625 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <assert.h>
#include <memory>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>
//Unsigned integral types
using u8 = unsigned char;
using u16 = unsigned short;
using u32 = unsigned int;
using u64 = unsigned long long;
//Signed integral types
using i8 = signed char;
using i16 = signed short;
using i32 = signed int;
using i64 = signed long long;
//Floating types
using f32 = float;
using f64 = double;
//Smart Pointer Aliases
template<typename T>
using Scope = std::unique_ptr<T>;
template<typename T, typename ... Args>
constexpr Scope<T> CreateScope(Args&& ... args)
{
return std::make_unique<T>(std::forward<Args>(args)...);
}
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T, typename ... Args>
constexpr Ref<T> CreateRef(Args&& ... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
} | true |
b8a69c28f175ad7918f8702b6a49e104cb21117e | C++ | IlyaSirosh/ATM_client | /cardeater.cpp | UTF-8 | 834 | 2.921875 | 3 | [] | no_license | #include "cardeater.h"
#include <QVBoxLayout>
CardEater::CardEater(QWidget *parent) :
QWidget(parent),
_input(new QLineEdit()),
_submit(new QPushButton()),
_card("")
{
_submit->setText("Вставити картку");
connect(_submit,SIGNAL(clicked()),this,SLOT(submit()));
createLayout();
}
CardEater::~CardEater(){
delete _input;
delete _submit;
}
void CardEater::createLayout(){
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(_input);
layout->addWidget(_submit);
}
void CardEater::submit(){
_card = _input->text();
emit getCard(_card);
}
const QString& CardEater::getCardNumber() const{
return _card;
}
bool CardEater::isInjected()const{
return _card.length()!=0;
}
void CardEater::setInput(const QString& s){
_input->setText(s);
}
| true |
555724351792713992050a74c29f6130657c7cb2 | C++ | mrrranjbar/SixR20GUI | /Model/Robot/TrajectoryPoint.h | UTF-8 | 2,331 | 2.703125 | 3 | [] | no_license | #pragma once
#include <vector>
//#include <deque>
class TrajectoryPoints
{
public:
double* q;
double* v;
double* a;
int TrajLength;
// ULONG dooo(ULONG a);
TrajectoryPoints()
{
q = new double[1000000];
v = new double[1000000];
a = new double[1000000];
}
~TrajectoryPoints()
{
delete q;
delete v;
delete a;
}
void FillTraj(double* qq, double* vv, double* aa, int len) {
q = qq;
v = vv;
a = aa;
TrajLength = len;
}
};
class TrajectoryPoint
{
public:
double Q;
double V;
TrajectoryPoint(double q1, double v1)
{
Q = q1;
V = v1;
}
TrajectoryPoint()
{
Q = V = 0.0;
}
};
template<class T>
class TrajectoryPointList
{
public:
bool init = true;
//deque<T> q;// = new List<T>();
std::vector<T> q;// = new List<T>();
std::vector<T> v;// = new List<T>();
std::vector<T> a;// = new List<T>();
int TrajLength = 0;
TrajectoryPointList()
{
}
~TrajectoryPointList()
{
/*delete q;
delete v;
delete a;*/
}
void AddPoint(T qq, T vv, T aa)
{
//q.push
q.push_back(qq);
v.push_back(vv);
a.push_back(aa);
TrajLength++;
}
void clearAll() {
q.clear();
v.clear();
a.clear();
TrajLength = 0;
}
double getPoint(int i) {
return q.at(i);
//T point = q[0];
//q.erase(q.begin());
//v.erase(v.begin());
//a.erase(a.begin());
//return point;// q.pop_front();
}
double getV(int i) {
return v.at(i);
//T point = q[0];
//q.erase(q.begin());
//v.erase(v.begin());
//a.erase(a.begin());
//return point;// q.pop_front();
}
double getAcc(int i) {
return a.at(i);
//T point = q[0];
//q.erase(q.begin());
//v.erase(v.begin());
//a.erase(a.begin());
//return point;// q.pop_front();
}
void FillTraj(T qq[], T vv[], T aa[], int len)
{
q.erase();
q = std::vector<int> (qq, qq + sizeof qq / sizeof qq[0]);
//q = q.insert(0, sizeof(qq) / sizeof(*qq), qq);
v.erase();
v = std::vector<int>(vv, vv + sizeof vv / sizeof vv[0]);
//v = v.insert(0, sizeof(vv) / sizeof(*vv), vv);
a.erase();
a = std::vector<int>(aa, aa + sizeof aa / sizeof aa[0]);
//a = a.insert(0, sizeof(aa) / sizeof(*aa), aa);
TrajLength = len;
}
};
| true |
cd2de87ccf2b5dbdf3fa296b621851b2be25c083 | C++ | mattwalker101/CIS-040-Cplusplus | /Commission/Commission.cpp | UTF-8 | 1,883 | 3.390625 | 3 | [] | no_license | // Commission.cpp
// member definitions
// Author: Matthew Walker
#include <iostream>
#include <iomanip>
#include <string>
#include "Commission.h"
using namespace std;
Commission::Commission(const string fname, const string lname, const string ssn,
double bSalary, double gSales, double cRate) {
// fname = { "Mary" };
cout << "Constructor called.\n";
firstName = { fname };
lastName = { lname };
SSN = { ssn };
baseSalary = { bSalary };
grossSales = { gSales };
commissionRate = { cRate };
};
string Commission::GetFirstName() const {
return firstName;
};
string Commission::GetLastName() const {
return lastName;
};
string Commission::GetSSN() const {
return SSN;
};
double Commission::GetBaseSalary() const {
// baseSalary = baseSalary++;
return baseSalary;
};
double Commission::GetGrossSales() const {
return grossSales;
};
double Commission::GetCommissionRate() const {
return commissionRate;
};
double Commission::Earnings() {
return baseSalary + commissionRate * grossSales;
};
void Commission::SetBaseSalary(double newsalary) {
if (newsalary < 0.0) {
throw invalid_argument("Salary must be >= 0.0");
}
else
baseSalary = newsalary;
}
void Commission::SetFirstName(const string &f) {
firstName = f;
}
void Commission::SetLastName(const string &l) {
lastName = l;
}
void Commission::SetSSN(const string &s) {
SSN = s;
}
void Commission::Print() {
cout << "Name: " << GetFirstName() << " "
<< GetLastName() << endl;
cout << "SSN: " << GetSSN() << endl;
cout << "Base Salary: $" << fixed << setprecision(2) << showpoint
<< GetBaseSalary() << endl;
cout << "Gross Sales: $" << GetGrossSales() << endl;
cout << "Commission Rate: " << GetCommissionRate() << endl;
cout << "\nEarnings: $" << Earnings() << endl;
cout << "-----------------------\n\n";
}
// destructor
Commission::~Commission() {
cout << "Inside destructor!\n";
}
| true |
7db85d6d7ae27dcf5d7f58cf856d29ad48c6456f | C++ | sraman915/Comptetive-Programming | /Spoj-Solutions/ABA12C-BUYINGAPPLES.cpp | UTF-8 | 654 | 2.515625 | 3 | [] | no_license | /*
ABA12C- BUYING APPLES
SOLUTION BY RAMAN SHARMA
*/
#include<bits/stdc++.h>
using namespace std;
#define inf 10000000
int unknapsc(int val[],int k){
int dp[k+1];
dp[0]=0;
for(int i=1; i<=k; ++i){
dp[i]=inf;
for(int j=1; j<=i; ++j){
if(val[j]!=-1)
dp[i]=min(dp[i],dp[i-j]+val[j]);
}
//for(int i=1; i<=k; ++i)
//cout<<dp[i]<<" ";
//cout<<endl;
}
if(dp[k]==inf)
return -1;
return dp[k];
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,k;
scanf("%d%d",&n,&k);
int val[k+1];
val[0]=-1;
for(int i=1; i<=k; ++i)
scanf("%d",val+i);
printf("%d\n",unknapsc(val,k));
}
return 0;}
| true |
eca606949e47031b1f685249110cef97f7870aaa | C++ | kobe24o/LeetCode | /algorithm/leetcode294.cpp | UTF-8 | 459 | 2.765625 | 3 | [] | no_license | class Solution {
unordered_map<string,bool> m;
public:
bool canWin(string s) {
if(s.size() <= 1) return false;
if(m.count(s)) return m[s];
string t;
for(int i = 0; i < s.size()-1; ++i)
{
if(s[i]=='+' && s[i+1]=='+')
{
t = s;
t[i]=t[i+1]='-';
if(!canWin(t))
{
m[s] = true;
return true;
}
}
}
m[s] = false;
return false;
}
}; | true |
7f2f04d5ec3a7c302c4a4ee76ef96c2878b03aeb | C++ | lineCode/fish | /hx/db/DbThreadPool.cpp | UTF-8 | 1,902 | 2.84375 | 3 | [] | no_license | #include "DbThreadPool.h"
#include "util/Util.h"
#include "util/format.h"
#include <stdio.h>
void DbThreadPool::threadFunc(DbThreadPool::TaskQueue *queue, DbMysql* db) {
for(;;) {
DbTask* task = queue->Get();
if(!task) {
return;
}
task->ThreadDo(db);
}
}
void DbThreadPool::TaskQueue::Close() {
std::lock_guard<std::mutex> guard(this->mtx);
if(!this->closed) {
this->closed = true;
this->cv.notify_all();
}
}
DbTask* DbThreadPool::TaskQueue::Get() {
std::lock_guard<std::mutex> guard(this->mtx);
for( ; ;) {
if(this->closed) {
if(this->tasks.empty()) {
return NULL;
} else {
DbTask* task = this->tasks.front();
this->tasks.pop_front();
return task;
}
} else {
if(this->tasks.empty()) {
++this->watting;
this->cv.wait(this->mtx);
--this->watting;
} else {
DbTask* task = this->tasks.front();
this->tasks.pop_front();
return task;
}
}
}
}
void DbThreadPool::TaskQueue::PostTask(DbTask* task) {
std::lock_guard<std::mutex> guard(this->mtx);
if(this->closed) {
return;
}
this->tasks.push_back(task);
if(this->watting > 0) {
this->cv.notify_one();
}
}
bool DbThreadPool::Init(int threadCount, std::string ip, int port, std::string user, std::string pwd, std::string name) {
if(threadCount <= 0) {
threadCount = 1;
}
for(auto i = 0; i < threadCount; ++i) {
DbMysql* db = new DbMysql(ip, port, user, pwd);
if (db->Attach(name) == false) {
Util::Exit(fmt::format("attach db:{} error", name));
}
dbs_.push_back(db);
}
for(auto i = 0; i < threadCount; ++i) {
threads_.push_back(std::thread(threadFunc,&queue_, dbs_[i]));
}
return true;
}
DbThreadPool::DbThreadPool() {
}
DbThreadPool::~DbThreadPool() {
queue_.Close();
size_t i = 0;
for( ; i < threads_.size(); ++i) {
threads_[i].join();
}
for( i = 0; i < dbs_.size(); ++i) {
DbMysql* db = dbs_[i];
delete db;
}
}
| true |
3a968875ed4856245df68e2dd83214b27b63dbae | C++ | deepakks1995/Practise | /merge_sort.cpp | UTF-8 | 839 | 3.1875 | 3 | [] | no_license |
void merge_sort(long a[], int lo, int hi)
{
if(lo < hi )
{
long mid = lo + (hi-lo)/2;
merge_sort(a,lo,mid);
merge_sort(a,mid+1,hi);
_merge(a,lo,mid,hi);
}
}
void _merge(long a[], int lo, int mid, int hi)
{
long LHS[mid-lo+1];
long RHS[hi-mid];
int i,j;
for(i=0,j=lo; j<=mid; i++,j++)
LHS[i] = a[j];
for(i=0,j=mid+1; j<=hi; i++,j++)
RHS[i] = a[j];
int k=lo;
i=0;
j=0;
while(i<mid-lo+1 && j<hi-mid)
{
if( LHS[i] <= RHS[j] )
a[k] = LHS[i++];
else
a[k] = RHS[j++];
k++;
}
while(i<mid-lo+1)
{
a[k] = LHS[i];
++k;
++i;
}
while(j<hi-mid)
{
a[k] = RHS[j];
++k;
++j;
}
}
| true |
7019a3fc4f4f4b843b75d531658833b04e62bc22 | C++ | liooil/leetcode | /add-and-search-word-data-structure-design.cpp | UTF-8 | 1,364 | 3.453125 | 3 | [] | no_license | #include <string>
#include <vector>
using namespace std;
// =====================================================================================================================
struct Trie {
string str;
vector<Trie*> children;
};
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() :
root{"", {}} {
}
/** Adds a word into the data structure. */
void addWord(string word) {
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
if (word.empty()) return this->Found;
if (word[0] == '.') {
for (WordDictionary* child : this->Child) {
if (child == nullptr) continue;
if (child->search(word.substr(1))) return true;
}
} else {
unsigned int index = static_cast<unsigned int>(word[0] - 'a');
if (this->Child[index] == nullptr) return false;
return this->Child[index]->search(word.substr(1));
}
return false;
}
private:
Trie root;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/ | true |
293dbf75d36278f3b49ef92a35fc9624d0a406c2 | C++ | lineCode/entity_spell_system | /entities/skills/entity_skill_data.cpp | UTF-8 | 1,970 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "entity_skill_data.h"
int EntitySkillData::get_id() {
return _id;
}
void EntitySkillData::set_id(int value) {
_id = value;
}
int EntitySkillData::get_default_value() {
return _default_value;
}
void EntitySkillData::set_default_value(int value) {
_default_value = value;
}
int EntitySkillData::get_max_value() {
return _max_value;
}
void EntitySkillData::set_max_value(int value) {
_max_value = value;
}
String EntitySkillData::get_text_description() {
return _text_description;
}
void EntitySkillData::set_text_description(String value) {
_text_description = value;
}
EntitySkillData::EntitySkillData() {
_id = 0;
_default_value = 0;
_max_value = 0;
}
EntitySkillData::~EntitySkillData() {
}
void EntitySkillData::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_id"), &EntitySkillData::get_id);
ClassDB::bind_method(D_METHOD("set_id", "value"), &EntitySkillData::set_id);
ADD_PROPERTY(PropertyInfo(Variant::INT, "id"), "set_id", "get_id");
ClassDB::bind_method(D_METHOD("get_default_value"), &EntitySkillData::get_default_value);
ClassDB::bind_method(D_METHOD("set_default_value", "value"), &EntitySkillData::set_default_value);
ADD_PROPERTY(PropertyInfo(Variant::INT, "default_value"), "set_default_value", "get_default_value");
ClassDB::bind_method(D_METHOD("get_max_value"), &EntitySkillData::get_max_value);
ClassDB::bind_method(D_METHOD("set_max_value", "value"), &EntitySkillData::set_max_value);
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_value"), "set_max_value", "get_max_value");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text_name"), "set_name", "get_name");
ClassDB::bind_method(D_METHOD("get_text_description"), &EntitySkillData::get_text_description);
ClassDB::bind_method(D_METHOD("set_text_description", "value"), &EntitySkillData::set_text_description);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text_description", PROPERTY_HINT_MULTILINE_TEXT), "set_text_description", "get_text_description");
}
| true |
f24c25b69dd5a5c8e5fb22b7332b85390151f77f | C++ | lucastarche/aotd | /DynamicProgramming/040-01Knapsack.cpp | UTF-8 | 1,462 | 3.625 | 4 | [
"MIT"
] | permissive | //0-1 Knapsack
//Problem: We are given an array of objects, each with a weigth and value, and a knapsack, in which we can fit a certain weigth at most. Determine the maximum value we can carry in the knapsack.
//One of the classical 2D DP problems. The base cases are when we run out of items or weigth, in which the value is 0.
//The name is due to the fact that, for each item, we can choose to either leave it (0) or take it (1).
//Runtime: O(nw) with bottom-up. This can be improved drastically with top-down, given that we only visit the reachable states.
#include <bits/stdc++.h>
using namespace std;
int Knapsack(vector<pair<int, int>>& objects, int w) {
int n = (int)objects.size();
vector<vector<int>> value(n + 1, vector<int>(w + 1, 0));
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= w; j++) {
if (i == 0 || j == 0)
continue;
if (objects[i - 1].first > j)
value[i][j] = value[i - 1][j];
else
value[i][j] = max(
value[i - 1][j - objects[i - 1].first] + objects[i - 1].second,
value[i - 1][j]);
}
}
return value[n][w];
}
int main() {
int n, w;
cin >> n >> w;
vector<pair<int, int>> obj(n);
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
obj[i] = { a, b };
}
cout << "The max possible value is " << Knapsack(obj, w) << '\n';
}
| true |
48b77fbc520d09675f5e77c4732c9673781f338f | C++ | 210183/CP | /Contest & Online Judge/FBHC/2017/Preliminary/loading.cpp | UTF-8 | 723 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int LOWER_BOUND = 50;
int solve(vector<int> v) {
sort(v.begin(), v.end());
for(int i = 0 ; i < v.size() ; i++) {
int iter = 0;
bool ok = 1;
for(int j = i ; j < v.size() ; j++) {
int tot = 1;
while(v[j] * tot < LOWER_BOUND && iter < i) {
iter++;
tot++;
}
if(v[j] * tot < LOWER_BOUND) {
ok = 0;
break;
}
}
if(ok) {
return v.size() - i;
}
}
return 0;
}
int main() {
int t; cin >> t;
for(int tc = 1 ; tc <= t ; tc++) {
int n; cin >> n;
vector<int> v(n);
for(int i = 0 ; i < n ; i++)
cin >> v[i];
cout << "Case #" << tc << ": " << solve(v) << "\n";
}
return 0;
} | true |
f916e80291e1a3274c1062401069167828783db9 | C++ | PMarcL/LaboratoireGIF1003 | /Laboratoire9/EmployeLib/Employe.h | UTF-8 | 907 | 3.125 | 3 | [] | no_license | /**
* \file Employe.h
* \brief Classe de base abstraite Employe
* \author etudiant
* \version 0.1
* \date 2015-03-19
*/
#ifndef EMPLOYE_H_
#define EMPLOYE_H_
#include "Date.h"
#include "ContratException.h"
namespace labo10 {
/**
* \class Employe
* \brief Classe de base
*/
class Employe {
public:
Employe(const std::string& p_nom, const std::string& p_prenom, util::Date p_dateNaissance, int p_codeDepartement);
virtual ~Employe() {
}
;
//Accesseurs
std::string reqPrenom() const;
std::string reqNomFamille() const;
int reqCodeDepartement() const;
util::Date reqDateNaissance() const;
virtual double gains() const = 0;
virtual std::string reqEmployeFormate() const;
bool operator==(const Employe&) const;
private:
void verifieInvariant() const;
std::string m_nomFamille;
std::string m_prenom;
int m_codeDepartement;
util::Date m_dateNaissance;
};
}
#endif /* EMPLOYE_H_ */
| true |
eb7117dd8c5b92ac5f4bf41a470d7564119918d4 | C++ | CameronHosking/recombination | /same-mutations.cpp | UTF-8 | 19,244 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <set>
#include <unordered_map>
#include <vector>
#include <algorithm>
bool startMatches(const std::string &a,const std::string &b)
{
for(uint i = 0 ;i < std::min(a.size(),b.size());++i)
{
if (a[i]!=b[i])
{
return false;
}
}
return true;
}
enum MutationType{Valid, Ignored, Fatal};
std::unordered_map<int,int> ignoredSiteCounts;
MutationType validMutation(const std::string &mutation)
{
//check that the sequence contains no ambiguity characters
uint lastTab = mutation.find_last_of('\t');
std::string site = mutation.substr(lastTab+1);
site = site.substr(0,site.find(':'));
int siteNumber = std::stoi(site);
//the mutation is near the start or end of the sequence
if(siteNumber < 50||siteNumber>29750)
{
ignoredSiteCounts[siteNumber]++;
return Ignored;
}
//the first non Nucleotide character is within the ref/alt columns
//
if(mutation.find_first_not_of("acgtACGT-\t")<lastTab)
{
return Fatal;
}
return Valid;
/*
//if at the start or the end
if(site.substr(0,2)=="1:")
return false;
if(site.find(":29902")!=std::string::npos)
return false;
//check for dissallowed positions
if(startMatches(site,"635:")) return false;
if(startMatches(site,"2091:")) return false;
if(startMatches(site,"2094:")) return false;
if(startMatches(site,"3145:")) return false;
if(startMatches(site,"3564:")) return false;
if(startMatches(site,"4050:")) return false;
if(startMatches(site,"5736:")) return false;
if(startMatches(site,"6869:")) return false;
if(startMatches(site,"8022:")) return false;
if(startMatches(site,"8790:")) return false;
if(startMatches(site,"10129:")) return false;
if(startMatches(site,"11074:")) return false;
if(startMatches(site,"11083:")) return false;
if(startMatches(site,"11535:")) return false;
if(startMatches(site,"13402:")) return false;
if(startMatches(site,"13408:")) return false;
if(startMatches(site,"13476:")) return false;
if(startMatches(site,"13571:")) return false;
if(startMatches(site,"14277:")) return false;
if(startMatches(site,"15922:")) return false;
if(startMatches(site,"16887:")) return false;
if(startMatches(site,"19484:")) return false;
if(startMatches(site,"21575:")) return false;
if(startMatches(site,"22335:")) return false;
if(startMatches(site,"24389:")) return false;
if(startMatches(site,"24390:")) return false;
if(startMatches(site,"24933:")) return false;
if(startMatches(site,"26549:")) return false;
if(startMatches(site,"29037:")) return false;
if(startMatches(site,"29553:")) return false;
*/
}
//counts the number of elements in common, the elements must be sorted
int elementsInCommon(const std::vector<int> &a, const std::vector<int> &b, const std::vector<int> &c)
{
uint i = 0;
uint j = 0;
uint k = 0;
int common = 0;
while(i < a.size() && j < b.size() && k < c.size())
{
if(a[i]==b[j]&&a[i]==c[k])
{
common++;
i++;
j++;
k++;
}
else if(a[i]>b[j])
{
if(c[k]>b[j])
j++;
else
k++;
}
else
{
if(c[k]>a[i])
i++;
else
k++;
}
}
return common;
}
//map of mutation string to mutation ID
std::unordered_map<std::string,int> mutationIDs;
//vector of strains, this ordering represents their numeric key
std::vector<std::string> strains;
//vector of strains by strainID that contain each mutation by mutationID
std::vector<std::vector<int> > strainsContainingMutation;
//vector of the mutations each strain contains
std::vector<std::vector<int> > strainMutations;
std::unordered_map<std::string,std::string> uniqueStrainMutations;
void deleteLastStrainAddedIfStrainIs(const std::string& strain)
{
if(!strains.empty()&&strains.back()==strain)
{
int strainID = strains.size()-1;
//remove the strain from list of strains
strains.pop_back();
//remove this strains from all the mutations that have this strain
for(auto m: strainMutations[strainID])
{
strainsContainingMutation[m].pop_back();
}
//remove this strain and its mutations from the list of strains and their mutations
strainMutations.pop_back();
}
};
int main(int argc, char* argv[])
{
// Check the number of parameters
if (argc < 4) {
// Tell the user how to run the program
std::cerr << "Usage: " << argv[0] << " INPUTFILE OUTPUTFILE DUPLICATESFILE" << std::endl;
/* "Usage messages" are a conventional way of telling the user
* how to run a program if they enter the command incorrectly.
*/
return 1;
}
std::ifstream infile(argv[1]);
std::ofstream duplicatesFile(argv[3]);
duplicatesFile << "Original Duplicate" << std::endl;
std::string line;
std::cout << "reading in mutations from " << argv[1] << std::endl;
std::cout << "writing duplicates to " << argv[3] << std::endl;
//this strain contained ambiguity codes
bool invalidStrain = false;
std::string prevStrain = "";
std::string allMutationsString = "";
while (std::getline(infile, line))
{
int firstTab = line.find('\t');
std::string strain = line.substr(0,firstTab);
if(strain!=prevStrain)
{
if(!invalidStrain)
{
//if this is a new strain chack the last strain to make sure its mutation set was unique
if(uniqueStrainMutations.count(allMutationsString)==0)
{
uniqueStrainMutations[allMutationsString]=prevStrain;
}
else
{
deleteLastStrainAddedIfStrainIs(prevStrain);
duplicatesFile << prevStrain << "\t" << uniqueStrainMutations[allMutationsString] <<std::endl;
}
}
//reset mutation string
allMutationsString = "";
invalidStrain = false;
prevStrain = strain;
}
else
{
//if this strain has had invalid mutations ignore it
if(invalidStrain)
{
continue;
}
}
std::string mutation = line.substr(firstTab+1);
//check that mutation is valid
MutationType mutationType = validMutation(mutation);
if(mutationType==Fatal)
{
invalidStrain = true;
//remove all trace of this strain
deleteLastStrainAddedIfStrainIs(strain);
continue;
}
if(mutationType==Ignored)
continue;
//valid muation is added to this strains all mutations string
allMutationsString += mutation;
//if it is a new strain we add it to the list of strains
if(strains.empty()||strains.back()!=strain)
{
strains.push_back(strain);
strainMutations.push_back(std::vector<int>());
}
int strainID = strains.size()-1;
//if its a new mutation add it to the mutation set
if(mutationIDs.count(mutation)==0)
{
mutationIDs[mutation] = mutationIDs.size();
strainsContainingMutation.push_back(std::vector<int>());
}
int mutationID = mutationIDs[mutation];
//add this strain to the list of strains that have this mutation
strainsContainingMutation[mutationID].push_back(strainID);
//and add this mutation to this strains list of mutations
strainMutations[strainID].push_back(mutationID);
}
duplicatesFile.close();
std::cout << "read in " << mutationIDs.size() << " unique mutations in " << strains.size() << " strains" << std::endl;
// std::vector<std::pair<int,int>> sitesIgnored = std::vector<std::pair<int,int>>(ignoredSiteCounts.begin(),ignoredSiteCounts.end());
// std::cout << sitesIgnored.size() <<std::endl;
// std::sort(sitesIgnored.begin(),sitesIgnored.end());
// for(auto s: sitesIgnored)
// {
// std::cout << s.first << "\t" << s.second << std::endl;
// }
//return 0;
//sort the mutations (this will be useful later when comparing mutations between strains)
for(uint i = 0; i < strains.size();i++)
{
std::sort(strainMutations[i].begin(),strainMutations[i].end());
}
std::cout << "creating common mutatations matrix" << std::endl;
//create commonMutations matrix, initially zeroes
std::vector<std::vector<unsigned char> > commonMutations;
for(uint i = 0; i < strains.size(); ++i)
{
commonMutations.push_back(std::vector<unsigned char>(i+1,0));
}
auto numberOfCommonMutations = [&](int strainA, int strainB) -> unsigned char&
{
//swap strainA and strainB if A is smaller than B, that way
//we only have to fill out and access half of the AB matrix
if(strainA<strainB)
{
std::swap(strainA,strainB);
}
return commonMutations[strainA][strainB];
};
//loop through each mutation, adding one to the count of mutations in common to each strain pair
for(uint i = 0; i < strainsContainingMutation.size(); i++)
{
for(uint s1 = 0; s1 < strainsContainingMutation[i].size(); s1++)
{
int s1ID = strainsContainingMutation[i][s1];
for(uint s2 = 0; s2 <= s1; s2++)
{
int s2ID = strainsContainingMutation[i][s2];
numberOfCommonMutations(s1ID,s2ID)++;
}
}
}
std::cout << "finished creating common mutatations matrix" << std::endl;
int maxInCommon = 0;
for(uint i = 0; i < strains.size(); ++i)
{
for(uint j = 0; j < i; ++j)
{
int inCommon = commonMutations[i][j];
if(inCommon>maxInCommon)
maxInCommon = inCommon;
}
}
//data structure to store strains ordered by similarity
std::vector<std::vector<int> > strainsBySimilarity = std::vector<std::vector<int> >(maxInCommon+1,std::vector<int>());
std::ofstream outfile(argv[2]);
// struct int30{
// int nums[30];
// };
// int30 distancesToNearestParent[60] = {};
// int10 differentParents[60] = {};
for(uint i = 0; i < strains.size(); ++i)
{
if(i<38904) continue;
if(i%100==0)
{
std::cout << "Tested " << i << "/"<< strains.size() <<" sequences" << std:: endl;
}
//check to see if the strain has a direct parent
int iMutations = commonMutations[i][i];
int bestDirectParent = i;
int maxAccountedFor = 0;
bool directParentFound = false;
//int duplicateParents = 0;
for(uint j = 0; j < strains.size(); j++)
{
int jMutations = commonMutations[j][j];
int numijCommonMutations = numberOfCommonMutations(i,j);
//i is completely a subset of j mutations and is hence an ancestor of j (or identical)
if(numijCommonMutations==iMutations)
continue;
//not all of js mutations are in common with i so not a direct parent
if(jMutations != numijCommonMutations)
continue;
//if j has the most mutations in common seen so far but still fewer than i
//it is the new best direct parent
if(numijCommonMutations > maxAccountedFor)
{
//duplicateParents = 0;
bestDirectParent = j;
maxAccountedFor = numijCommonMutations;
//direct parent within distance 2 found
if(numijCommonMutations==iMutations-1||numijCommonMutations==iMutations-2)
{
directParentFound = true;
break;
}
}
// else if(numijCommonMutations == maxAccountedFor)
// {
// duplicateParents++;
// }
}
// int dist = iMutations - maxAccountedFor;
// if(iMutations < 30 && dist < 20)
// distancesToNearestParent[iMutations].nums[dist]++;
// continue;
// if(duplicateParents>9)
// {
// duplicateParents = 9;
// }
// differentParents[iMutations - maxAccountedFor].nums[duplicateParents]++;
// continue;
//don't need to look for recombination events if we've already got a direct parent
if(directParentFound){
continue;
}
//clear the strains by similarity data structure to fill it with the new strain info
for(uint k = 0; k < strainsBySimilarity.size();k++)
{
strainsBySimilarity[k].clear();
}
//fill out the strains by similarity data structure, now strains are sorted by similarity.
int maxSimilarity = 0;
for(uint j = 0; j < strains.size(); j++)
{
int numijCommonMutations = numberOfCommonMutations(i,j);
//if the strains is sufficiently similar but not likely to be a descendant store it
//it could potentially be a parent
if(numijCommonMutations>1 && numijCommonMutations<iMutations-1)
{
maxSimilarity = std::max(maxSimilarity,numijCommonMutations);
strainsBySimilarity[numijCommonMutations].push_back(j);
}
}
//check for recombination events
int minExtraMutations = 0;
int bestP1 = i;
int bestP2 = i;
//int64_t comparisons = 0;
//similarity must be greater than or equal to 3 for it to be possible to have 3 unique
for(int p1Similarity = maxSimilarity;p1Similarity >=3; p1Similarity--)
{
for(auto p1It = strainsBySimilarity[p1Similarity].begin();p1It!=strainsBySimilarity[p1Similarity].end();p1It++)
{
int p1 = *p1It;
int mutationsInP1 = commonMutations[p1][p1];
//keep checking against parents with lower and lower similarity until it's impossible that they could be an improvement
for(int p2Similarity = p1Similarity; p2Similarity+p1Similarity >= maxAccountedFor&&p2Similarity>=3; p2Similarity--)
{
//loop through all strains with similarity p2, if p1 and p2 are the same we only want to loop on sequences after p1 to avoid duplicating work
for(auto p2It = (p1Similarity==p2Similarity) ? p1It+1 : strainsBySimilarity[p2Similarity].begin(); p2It!=strainsBySimilarity[p2Similarity].end();p2It++)
{
//comparisons++;
int p2=*p2It;
//mutations accounted for, assumes parent common mutations are in child
int accountedFor = p1Similarity + p2Similarity - numberOfCommonMutations(p1,p2);
//we have a better parent / parents
if(accountedFor < maxAccountedFor)
continue;
int mutationsInP2 = commonMutations[p2][p2];
int extraMutations = mutationsInP1 - p1Similarity + mutationsInP2 - p2Similarity;
//pick parents with the minimum number of extraneous mutations
if(accountedFor==maxAccountedFor&&extraMutations>minExtraMutations)
continue;
//must have at least 3 unique mutations from each parent, this is to avoid the case where a recombination occurs but we have only sequenced the children
//of the recombinant strain and each selects their sibling as their recombination parent
int p1p2SharedMutations = numberOfCommonMutations(p1,p2);
if(p1Similarity-p1p2SharedMutations < 3 || p2Similarity-p1p2SharedMutations < 3)
continue;
//make sure that the mutations in common between parents are actually present in child
if(elementsInCommon(strainMutations[i],strainMutations[p1],strainMutations[p2])==numberOfCommonMutations(p1,p2))
{
//if we get this far this is our new best guess for parents
maxAccountedFor = accountedFor;
minExtraMutations = extraMutations;
bestP1 = p1;
bestP2 = p2;
}
}
}
}
}
//std::cout << comparisons << std::endl;
//at least 3 better than a direct parent
if(maxAccountedFor-3>=numberOfCommonMutations(i,bestDirectParent))
{
int commonWithP1 = numberOfCommonMutations(i,bestP1);
int commonWithP2 = numberOfCommonMutations(i,bestP2);
//difference between recombination event and direct parent in number of mutations explained
outfile << maxAccountedFor - numberOfCommonMutations(i,bestDirectParent) << '\t';
// //minimum unique
// int minimumUnique = maxAccountedFor - std::max(commonWithP1,commonWithP2);
// if(minimumUnique < 2)
// continue;
// outfile << minimumUnique << '\t';
//direct parent number of mutations explained
outfile << (int) (commonMutations[i][i] - numberOfCommonMutations(i,bestDirectParent)) << '\t';
//distribution of mutations: mutations unique to p1 / number of shared mutations / mutations unique to p2
int shared = numberOfCommonMutations(bestP1,bestP2);
outfile << commonWithP1 - shared << '/' << shared << '/' << commonWithP2 - shared << '\t';
//mutations transfered in event compared to total mutations in strain
outfile << maxAccountedFor << '/' << (int) commonMutations[i][i] <<'\t';
outfile << commonWithP1 << '/' << (int) commonMutations[bestP1][bestP1] << '\t';
outfile << commonWithP2 << '/' << (int) commonMutations[bestP2][bestP2] << '\t';
//actual strain names
outfile << strains[i] << '\t';
outfile << strains[bestP1] << '\t';
outfile << strains[bestP2] << std::endl;
}
}
// for(uint j = 1; j < 30; j++)
// {
// std::cout << '\t' << j;
// }
// std::cout << std::endl;
// for(uint i = 1; i < 30; i++)
// {
// std::cout << i;
// for(uint j = 1; j < 20; j++)
// {
// std::cout << '\t' << distancesToNearestParent[i].nums[j];
// }
// std::cout << std::endl;
// }
return 0;
}
| true |
8c081f138ab9d8a6fdf08ebe6932cd5e418c35ce | C++ | GitBigNoob/lcdlearn | /442.find-all-duplicates-in-an-array.cpp | UTF-8 | 688 | 3 | 3 | [] | no_license | /*
* @lc app=leetcode id=442 lang=cpp
*
* [442] Find All Duplicates in an Array
*/
/*将每个数字,交换到其秩减一的位置重复即找到*/
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ans;
for(int i=0;i<nums.size();i++){
while(nums[i] != i + 1){
int tmp=nums[i];
if(nums[i] == 0)
break;
if(tmp == nums[tmp - 1]){
ans.push_back(tmp);
nums[tmp-1]=0;
}
nums[i]=nums[tmp - 1];
nums[tmp-1]=tmp;
}
}
return ans;
}
};
| true |
8141c6e57e3a5f23d9376b537e0b3e939909d92f | C++ | coolsnowy/leetcode | /031.Next_Permutation.cpp | UTF-8 | 2,356 | 3.8125 | 4 | [] | no_license | /**
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <list>
#include <stack>
#include <queue>
using std::priority_queue;
using std::list;
using std::map;
using std::unordered_map;
using std::cout;
using std::string;
using std::cin;
using std::endl;
using std::vector;
class Solution {
public:
// see the detail https://leetcode.com/problems/next-permutation/solution/
// great algotithm, smart
// brute dorce is time limited
void nextPermutation(std::vector<int>& nums) {
if(nums.size() <2) return;
// int 和size_t之间 不能乱用,后面有i--!!!!,如果是unsigned,将会导致i变成INT_MAX
int i = nums.size() - 2;
// 全排列中后面数字是递减的
// such as
/*
* 1 2 3 4
* 1 2 4 3
* 1 3 2 4
* 1 3 4 2
* 1 4 2 3
* 1 4 3 2
* 2 1 3 4
* 2 1 4 3
*/
// i 指向从尾部开始第一个不是递增的数字
while(i >= 0 && nums[i+1] <= nums[i]) {
i--;
}
if(i >= 0) {
// j指向刚刚好比i大的数字
int j = nums.size() - 1;
while(j >= 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i+1);
}
private:
void reverse(std::vector<int>& nums, int start) {
int i = start, j = nums.size() - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
void swap(vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
};
int main() {
Solution s;
std::vector<int> vec{1,2};
s.nextPermutation(vec);
for(auto i : vec) {
cout<<i<<'\t';
}
}
| true |
5d445619404ed4df4de8a71a0f1150ed8f274647 | C++ | bacchus/bacchuslib | /src/ui/app.h | UTF-8 | 776 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/freeglut.h>
namespace bacchus {
class App {
public:
App(char* app_name) {
mArgc = 1;
mArgv = new char*[1];
mArgv[0] = app_name;
glutInit(&mArgc, mArgv);
}
App(int argc, char** argv)
: mArgc(argc), mArgv(argv)
{
glutInit(&mArgc, mArgv);
}
virtual ~App() {}
virtual void onInit() {}
virtual void onExit() {}
virtual void mainLoop() {
glutMainLoop();
}
void run() {
onInit();
mainLoop();
onExit();
}
int argc() const {
return mArgc;
}
char** argv() const {
return mArgv;
}
private:
int mArgc;
char** mArgv;
};
} // namespace bacchus
| true |
dd1f414a2fcddd76af4c53b4dc4f3be457301ccd | C++ | InfiniteRegen/Baekjoon_Algorithm | /algorithm/1181.cpp | UTF-8 | 471 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <set>
#include <algorithm>
#include <string>
using namespace std;
set<pair<int, string>> p1;
string input[20000];
int main(int argc, char **argv)
{
int N;
cin >> N;
for (int i = 0; i < N; ++i) {
cin >> input[i];
p1.insert(make_pair(input[i].length(), input[i]));
}
set<pair<int, string>>::iterator iter;
for (iter = p1.begin(); iter != p1.end(); ++iter) {
cout << (*iter).second << endl;
}
return 0;
} | true |
e5cf95b8e55ab7d62f430f2b7c88a9369a5ff2df | C++ | zakaria-n/Syntax-Analysis | /Lexer/automate.cpp | UTF-8 | 1,835 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "automate.h"
#include "etat.h"
using namespace std;
Automate::Automate(string chaine) {
Etat0 * etat0 = new Etat0();
pileEtats.push(etat0);
this->lexer = new Lexer(chaine);
}
void Automate::run() {
bool end = false;
while(!end){
this->affichePile();
Symbole * s = lexer->Consulter();
end = pileEtats.top()->transition(*this,s);
}
if(!pileSymboles.top()->estErreur()) {
Expr * expr = (Expr*)(pileSymboles.top());
cout << "Valeur de l'expression : ";
cout << expr->getValeur() << endl;
} else {
this->affichePile();
cout << "Il y'a une erreur dans l'expression. Arrêt de la lecture." << endl;
}
}
void Automate::affichePile() {
cout << "Pile des symboles : " << endl;
stack<Symbole*> copy = pileSymboles;
while(!copy.empty()){
copy.top()->Affiche();
cout << " ";
copy.pop();
}
cout << endl << "Pile des états : " << endl;
stack<Etat*> etats = pileEtats;
while(!etats.empty()){
cout << etats.top()->getName() << " ";
etats.pop();
}
cout << endl << endl;
}
void Automate::decalage(Symbole * s, Etat * e) {
pileSymboles.push(s);
if(e != NULL) {
pileEtats.push(e);
if(s->estTerminal()) {
lexer->Avancer();
}
}
}
void Automate::reduction(int n, Symbole * s) {
for(int i = 0 ; i<n ; i++) {
delete(pileEtats.top());
pileEtats.pop();
}
pileEtats.top()->transition(*this,s);
}
Symbole* Automate::popSymbol() {
Symbole * sym = pileSymboles.top();
if(!pileSymboles.empty()){
pileSymboles.pop();
}
return sym;
}
void Automate::popAndDestroySymbol(){
if(!pileSymboles.empty()){
pileSymboles.pop();
} else {
cout << "EmptySymbolStack";
}
}
| true |
c860ed5739866ac21affdee0b5191f377c12d99a | C++ | vplesko/DungeonsOfPain | /Morph_0_8/src/Object.cpp | UTF-8 | 6,312 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <Morph/Object.h>
#include <Morph/CollMask.h>
#include <Morph/Look.h>
#include <Morph/Room.h>
#include <Morph/Flow.h>
using namespace morph;
Object::Object(int Depth) {
setStartValues(Depth);
}
Object::Object(sf::Vector2f startPosition, int Depth) : position(startPosition) {
setStartValues(Depth);
}
void Object::setStartValues(int Depth) {
owner = 0;
enabled = true;
persistent = false;
depth = Depth;
rendered = true;
l = 0;
m = 0;
checkCollisionsForThis = true;
setReactToDefault();
setOrderedChangesToFalse();
}
void Object::setReactToDefault() {
reactTick = true;
reactKeyPressed = true;
reactKeyReleased = true;
reactMouseButtonPressed = true;
reactMouseButtonReleased = true;
reactTextEntered = true;
reactOther = true;
}
void Object::setReactsToFalse() {
reactTick = false;
reactKeyPressed = false;
reactKeyReleased = false;
reactMouseButtonPressed = false;
reactMouseButtonReleased = false;
reactTextEntered = false;
reactOther = false;
}
void Object::setOrderedChangesToFalse() {
enabledToChange = false;
positionToChange = false;
depthToChange = false;
collMaskToChange = false;
lookToChange = false;
originToChange = false;
}
void Object::commitOrderedChangesToEnabled() {
if (enabledToChange) {
bool realChange = enabled != enabledNext;
enabled = enabledNext;
enabledToChange = false;
if (owner != 0 && realChange) onEnabledChange();
}
}
void Object::commitOrderedChangesToPosition() {
if (positionToChange) {
if (m) m->move(positionNext - position);
if (l) l->move(positionNext - position);
position = positionNext;
positionToChange = false;
}
}
void Object::commitOrderedChangesToOrigin() {
if (originToChange) {
if (m) m->setOrigin(m->getOrigin() + originNext - origin);
if (l) l->setOrigin(l->getOrigin() + originNext - origin);
origin = originNext;
originToChange = false;
}
}
void Object::commitOrderedChangesToDepth() {
if (depthToChange) {
depth = depthNext;
if (owner) owner->replaceForDepth(indexInCont);
depthToChange = false;
}
}
void Object::commitOrderedChangesToCollMask() {
if (collMaskToChange) {
if (m) delete m;
m = nextMask;
if (m) {
m->move(position);
m->setOrigin(m->getOrigin() + origin);
}
collMaskToChange = false;
}
}
void Object::commitOrderedChangesToLook() {
if (lookToChange) {
if (l) delete l;
l = nextLook;
if (l) {
l->move(position);
l->setOrigin(l->getOrigin() + origin);
}
lookToChange = false;
}
}
void Object::commitOrderedChanges() {
commitOrderedChangesToEnabled();
commitOrderedChangesToPosition();
commitOrderedChangesToOrigin();
commitOrderedChangesToDepth();
commitOrderedChangesToCollMask();
commitOrderedChangesToLook();
}
void Object::changeRoom(Room *r) {
owner->changeRoom(r);
}
bool Object::isColliding(const Object *o) const {
if (CollisionMask::canCollide(getType(), o->getType()))
return CollisionMask::areColliding(m, o->m);
else
return false;
}
bool Object::isColliding(const Object *o, morph::ObjType t, bool enabledOnly) {
return o->owner->isColliding(o, t, enabledOnly);
}
bool Object::isColliding(const Object *o, std::vector<morph::ObjType> T, bool enabledOnly) {
return o->owner->isColliding(o, T, enabledOnly);
}
bool Object::wouldCollide(const sf::Vector2f &offset, const Object *other, const sf::Vector2f &otherOffset) const {
return owner->wouldCollide(this, offset, other, otherOffset);
}
bool Object::wouldCollide(const sf::Vector2f &offset, morph::ObjType t, bool enabledOnly) const {
return owner->wouldCollide(this, offset, t, enabledOnly);
}
bool Object::wouldCollide(const sf::Vector2f &offset, std::vector<morph::ObjType> T, bool enabledOnly) const {
return owner->wouldCollide(this, offset, T, enabledOnly);
}
unsigned Object::objCount(morph::ObjType t, bool enabledOnly) const {
return owner->objCount(t, enabledOnly);
}
unsigned Object::objCount(std::vector<morph::ObjType> T, bool enabledOnly) const {
return owner->objCount(T, enabledOnly);
}
void Object::setCollMask(CollisionMask *cm) {
if (collMaskToChange) delete nextMask;
collMaskToChange = true;
nextMask = cm;
if (owner == 0)
commitOrderedChangesToCollMask();
}
void Object::setLook(Look *ol) {
if (lookToChange) delete nextLook;
lookToChange = true;
nextLook = ol;
if (owner == 0)
commitOrderedChangesToLook();
}
bool Object::collMaskContainsPoint(const sf::Vector2f &p) const {
return m ? m->containsPoint(p) : false;
}
bool Object::collMaskContainsPoint(const sf::Event::MouseButtonEvent &e, bool mapViewPixelToCoords) const {
if (mapViewPixelToCoords) {
return collMaskContainsPoint(owner->getFlow()->mapViewPixelToCoords(e));
} else {
return collMaskContainsPoint(sf::Vector2f((float)e.x, (float)e.y));
}
}
void Object::setDepth(int Depth) {
depthNext = Depth;
depthToChange = true;
if (owner == 0)
commitOrderedChangesToDepth();
}
void Object::setEnabled(bool Enabled) {
enabledNext = Enabled;
enabledToChange = true;
if (owner == 0)
commitOrderedChangesToEnabled();
}
void Object::setEnabled(bool enabled, morph::ObjType t, bool affectObjsAboutToBePutIn) {
owner->setEnabled(enabled, t, affectObjsAboutToBePutIn);
}
void Object::setEnabled(bool enabled, std::vector<morph::ObjType> T, bool affectObjsAboutToBePutIn) {
owner->setEnabled(enabled, T, affectObjsAboutToBePutIn);
}
void Object::onTickMaskLookAndObj() {
if (m) m->onTick();
if (l) l->onTick();
onTick();
}
void Object::setPosition(const sf::Vector2f &Coords) {
positionToChange = true;
positionNext = Coords;
if (owner == 0)
commitOrderedChangesToPosition();
}
void Object::move(const sf::Vector2f &offset) {
if (!positionToChange) positionNext = position;
positionToChange = true;
positionNext += offset;
if (owner == 0)
commitOrderedChangesToPosition();
}
void Object::setOrigin(float x, float y) {
originToChange = true;
originNext = sf::Vector2f(x, y);
if (owner == 0)
commitOrderedChangesToOrigin();
}
void Object::draw(sf::RenderTarget& target, sf::RenderStates states) const {
preDraw(target, states);
if (rendered && l) target.draw(*l, states);
postDraw(target, states);
}
void Object::endGame() {
owner->endGame();
}
Object::~Object() {
if (getRoom())
getRoom()->destroyObjNowForObjsDestructor(this);
if (l) delete l;
if (m) delete m;
} | true |
80dbe5ad193700dcb4b805aee70c01259409447b | C++ | RikoOphorst/battleships | /src/memory/pool_allocator.h | UTF-8 | 474 | 2.765625 | 3 | [] | no_license | #pragma once
#include "../memory/allocator.h"
namespace igad
{
namespace memory
{
class PoolAllocator : public Allocator
{
public:
PoolAllocator(void* start, const size_t& size, const size_t& object_size, const uint32_t& object_alignment);
~PoolAllocator();
void* Allocate(const size_t& size, const uint32_t& alignment = 4);
void Deallocate(void* ptr);
private:
size_t object_size_;
uint32_t object_alignment_;
void** free_list_;
};
}
} | true |
a990fbb599d5625e611e30f946802dd3afc1d245 | C++ | HanLab-BME-MTU/extern | /mex/include/wildmagic-5.7/include/Wm5GMatrix.inl | UTF-8 | 21,153 | 2.9375 | 3 | [
"BSD-2-Clause"
] | permissive | // Geometric Tools, LLC
// Copyright (c) 1998-2011
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.4 (2011/07/27)
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>::GMatrix (int numRows, int numColumns)
{
mEntry = 0;
SetSize(numRows, numColumns);
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>::GMatrix (int numRows, int numColumns, const Real* entry)
{
mEntry = 0;
SetMatrix(numRows, numColumns, entry);
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>::GMatrix (int numRows, int numColumns, const Real** matrix)
{
mEntry = 0;
SetMatrix(numRows, numColumns, matrix);
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>::GMatrix (const GMatrix& mat)
{
mNumRows = 0;
mNumColumns = 0;
mNumElements = 0;
mEntry = 0;
*this = mat;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>::~GMatrix ()
{
delete2(mEntry);
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SetSize (int numRows, int numColumns)
{
delete2(mEntry);
if (numRows > 0 && numColumns > 0)
{
mNumRows = numRows;
mNumColumns = numColumns;
mNumElements = mNumRows*mNumColumns;
mEntry = new2<Real>(mNumColumns, mNumRows);
memset(mEntry[0], 0, mNumElements*sizeof(Real));
}
else
{
mNumRows = 0;
mNumColumns = 0;
mNumElements = 0;
mEntry = 0;
}
}
//----------------------------------------------------------------------------
template <typename Real>
inline void GMatrix<Real>::GetSize (int& numRows, int& numColumns) const
{
numRows = mNumRows;
numColumns = mNumColumns;
}
//----------------------------------------------------------------------------
template <typename Real>
inline int GMatrix<Real>::GetNumRows () const
{
return mNumRows;
}
//----------------------------------------------------------------------------
template <typename Real>
inline int GMatrix<Real>::GetNumColumns () const
{
return mNumColumns;
}
//----------------------------------------------------------------------------
template <typename Real>
inline int GMatrix<Real>::GetNumElements () const
{
return mNumElements;
}
//----------------------------------------------------------------------------
template <typename Real>
inline const Real* GMatrix<Real>::GetElements () const
{
return mEntry[0];
}
//----------------------------------------------------------------------------
template <typename Real>
inline Real* GMatrix<Real>::GetElements ()
{
return mEntry[0];
}
//----------------------------------------------------------------------------
template <typename Real>
inline const Real* GMatrix<Real>::operator[] (int row) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows, "Invalid index in operator[]\n");
#endif
return mEntry[row];
}
//----------------------------------------------------------------------------
template <typename Real>
inline Real* GMatrix<Real>::operator[] (int row)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows, "Invalid index in operator[]\n");
#endif
return mEntry[row];
}
//----------------------------------------------------------------------------
template <typename Real>
inline const Real& GMatrix<Real>::operator() (int row, int col) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows && 0 <= col && col <= mNumColumns,
"Invalid index in operator()\n");
#endif
return mEntry[row][col];
}
//----------------------------------------------------------------------------
template <typename Real>
inline Real& GMatrix<Real>::operator() (int row, int col)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows
&& 0 <= col && col <= mNumColumns,
"Invalid index in operator()\n");
#endif
return mEntry[row][col];
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SwapRows (int row0, int row1)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row0 && row0 < mNumRows
&& 0 <= row1 && row1 < mNumRows,
"Invalid index in SwapRows\n");
#endif
if (row0 != row1)
{
for (int c = 0; c < mNumColumns; ++c)
{
Real save = mEntry[row0][c];
mEntry[row0][c] = mEntry[row1][c];
mEntry[row1][c] = save;
}
}
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SwapColumns (int col0, int col1)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= col0 && col0 < mNumColumns
&& 0 <= col1 && col1 < mNumColumns,
"Invalid index in SwapColumns\n");
#endif
if (col0 != col1)
{
for (int r = 0; r < mNumRows; ++r)
{
Real save = mEntry[r][col0];
mEntry[r][col0] = mEntry[r][col1];
mEntry[r][col1] = save;
}
}
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SetRow (int row, const GVector<Real>& vec)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows && vec.GetSize() == mNumColumns,
"Invalid index in SetRow\n");
#endif
for (int c = 0; c < mNumColumns; ++c)
{
mEntry[row][c] = vec[c];
}
}
//----------------------------------------------------------------------------
template <typename Real>
GVector<Real> GMatrix<Real>::GetRow (int row) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= row && row < mNumRows, "Invalid index in GetRow\n");
#endif
GVector<Real> vec(mNumColumns);
for (int c = 0; c < mNumColumns; ++c)
{
vec[c] = mEntry[row][c];
}
return vec;
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SetColumn (int col, const GVector<Real>& vec)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= col && col < mNumColumns && vec.GetSize() == mNumRows,
"Invalid index in SetColumn\n");
#endif
for (int r = 0; r < mNumRows; ++r)
{
mEntry[r][col] = vec[r];
}
}
//----------------------------------------------------------------------------
template <typename Real>
GVector<Real> GMatrix<Real>::GetColumn (int col) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(0 <= col && col < mNumColumns,
"Invalid index in GetColumn\n");
#endif
GVector<Real> vec(mNumRows);
for (int r = 0; r < mNumRows; ++r)
{
vec[r] = mEntry[r][col];
}
return vec;
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SetMatrix (int numRows, int numColumns, const Real* entry)
{
delete2(mEntry);
if (numRows > 0 && numColumns > 0)
{
mNumRows = numRows;
mNumColumns = numColumns;
mNumElements = mNumRows*mNumColumns;
mEntry = new2<Real>(mNumColumns, mNumRows);
memcpy(mEntry[0], entry, mNumElements*sizeof(Real));
}
else
{
mNumRows = 0;
mNumColumns = 0;
mNumElements = 0;
mEntry = 0;
}
}
//----------------------------------------------------------------------------
template <typename Real>
void GMatrix<Real>::SetMatrix (int numRows, int numColumns,
const Real** matrix)
{
delete2(mEntry);
if (numRows > 0 && numColumns > 0)
{
mNumRows = numRows;
mNumColumns = numColumns;
mNumElements = mNumRows*mNumColumns;
mEntry = new2<Real>(mNumColumns, mNumRows);
for (int r = 0; r < mNumRows; ++r)
{
for (int c = 0; c < mNumColumns; ++c)
{
mEntry[r][c] = matrix[r][c];
}
}
}
else
{
mNumRows = 0;
mNumColumns = 0;
mNumElements = 0;
mEntry = 0;
}
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>& GMatrix<Real>::operator= (const GMatrix& mat)
{
if (mat.mNumElements > 0)
{
if (mNumRows != mat.mNumRows || mNumColumns != mat.mNumColumns)
{
delete2(mEntry);
mNumRows = mat.mNumRows;
mNumColumns = mat.mNumColumns;
mNumElements = mat.mNumElements;
mEntry = new2<Real>(mNumColumns, mNumRows);
}
memcpy(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real));
}
else
{
delete2(mEntry);
mNumRows = 0;
mNumColumns = 0;
mNumElements = 0;
mEntry = 0;
}
return *this;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator== (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) == 0;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator!= (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) != 0;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator< (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) < 0;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator<= (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) <= 0;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator> (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) > 0;
}
//----------------------------------------------------------------------------
template <typename Real>
bool GMatrix<Real>::operator>= (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
return memcmp(mEntry[0], mat.mEntry[0], mNumElements*sizeof(Real)) >= 0;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator+ (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
GMatrix<Real> result(mNumRows, mNumColumns);
const Real* srcEntry0 = mEntry[0];
const Real* srcEntry1 = mat.mEntry[0];
Real* trgEntry = result.mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] = srcEntry0[i] + srcEntry1[i];
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator- (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
GMatrix<Real> result(mNumRows, mNumColumns);
const Real* srcEntry0 = mEntry[0];
const Real* srcEntry1 = mat.mEntry[0];
Real* trgEntry = result.mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] = srcEntry0[i] - srcEntry1[i];
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator* (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
// 'this' is RxN, 'M' is NxC, 'product = this*M' is RxC
assertion(mNumColumns == mat.mNumRows, "Mismatch of matrix sizes.\n");
#endif
GMatrix<Real> result(mNumRows, mat.mNumColumns);
for (int r = 0; r < result.mNumRows; ++r)
{
for (int c = 0; c < result.mNumColumns; ++c)
{
for (int m = 0; m < mNumColumns; ++m)
{
result.mEntry[r][c] += mEntry[r][m] * mat.mEntry[m][c];
}
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator* (Real scalar) const
{
GMatrix<Real> result(mNumRows, mNumColumns);
const Real* srcEntry = mEntry[0];
Real* trgEntry = result.mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] = scalar*srcEntry[i];
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator/ (Real scalar) const
{
GMatrix<Real> result(mNumRows, mNumColumns);
Real* trgEntry = result.mEntry[0];
int i;
if (scalar != (Real)0)
{
Real invScalar = ((Real)1)/scalar;
const Real* srcEntry = mEntry[0];
for (i = 0; i < mNumElements; ++i)
{
trgEntry[i] = invScalar*srcEntry[i];
}
}
else
{
for (i = 0; i < mNumElements; ++i)
{
trgEntry[i] = Math<Real>::MAX_REAL;
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::operator- () const
{
GMatrix<Real> result(mNumRows, mNumColumns);
const Real* srcEntry = mEntry[0];
Real* trgEntry = result.mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] = -mEntry[i];
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>& GMatrix<Real>::operator+= (const GMatrix& mat)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
const Real* srcEntry = mat.mEntry[0];
Real* trgEntry = mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] += srcEntry[i];
}
return *this;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>& GMatrix<Real>::operator-= (const GMatrix& mat)
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(mNumRows == mat.mNumRows && mNumColumns == mat.mNumColumns,
"Mismatch of matrix sizes.\n");
#endif
const Real* srcEntry = mat.mEntry[0];
Real* trgEntry = mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] -= srcEntry[i];
}
return *this;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>& GMatrix<Real>::operator*= (Real scalar)
{
Real* trgEntry = mEntry[0];
for (int i = 0; i < mNumElements; ++i)
{
trgEntry[i] *= scalar;
}
return *this;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real>& GMatrix<Real>::operator/= (Real scalar)
{
Real* trgEntry = mEntry[0];
int i;
if (scalar != (Real)0)
{
Real invScalar = ((Real)1)/scalar;
for (i = 0; i < mNumElements; ++i)
{
trgEntry[i] *= invScalar;
}
}
else
{
for (i = 0; i < mNumElements; ++i)
{
trgEntry[i] = Math<Real>::MAX_REAL;
}
}
return *this;
}
//----------------------------------------------------------------------------
template <typename Real>
GVector<Real> GMatrix<Real>::operator* (const GVector<Real>& vec) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(vec.GetSize() == mNumColumns,
"Mismatched sizes in operator*.\n");
#endif
GVector<Real> result(mNumRows);
for (int r = 0; r < mNumRows; ++r)
{
for (int c = 0; c < mNumColumns; ++c)
{
result[r] += mEntry[r][c]*vec[c];
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
Real GMatrix<Real>::QForm (const GVector<Real>& u, const GVector<Real>& v)
const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
assertion(u.GetSize() == mNumRows && v.GetSize() == mNumColumns,
"Mismatched sizes in QForm.\n");
#endif
return u.Dot((*this)*v);
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::Transpose () const
{
GMatrix<Real> result(mNumColumns, mNumRows);
for (int r = 0; r < mNumRows; ++r)
{
for (int c = 0; c < mNumColumns; ++c)
{
result.mEntry[c][r] = mEntry[r][c];
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::TransposeTimes (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
// P = A^T*B, P[r][c] = sum_m A[m][r]*B[m][c]
assertion(mNumRows == mat.mNumRows, "Mismatch in TransposeTimes\n");
#endif
GMatrix<Real> result(mNumColumns, mat.mNumColumns);
for (int r = 0; r < result.mNumRows; ++r)
{
for (int c = 0; c < result.mNumColumns; ++c)
{
for (int m = 0; m < mNumRows; ++m)
{
result.mEntry[r][c] += mEntry[m][r] * mat.mEntry[m][c];
}
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::TimesTranspose (const GMatrix& mat) const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
// P = A*B^T, P[r][c] = sum_m A[r][m]*B[c][m]
assertion(mNumColumns == mat.mNumColumns, "Mismatch in TimesTranspose\n");
#endif
GMatrix<Real> result(mNumRows, mat.mNumRows);
for (int r = 0; r < result.mNumRows; ++r)
{
for (int c = 0; c < result.mNumColumns; ++c)
{
for (int m = 0; m < mNumColumns; ++m)
{
result.mEntry[r][c] += mEntry[r][m] * mat.mEntry[c][m];
}
}
}
return result;
}
//----------------------------------------------------------------------------
template <typename Real>
GMatrix<Real> GMatrix<Real>::TransposeTimesTranspose (const GMatrix& mat)
const
{
#ifdef WM5_ASSERT_GMATRIX_OUT_OF_RANGE
// P = A*B^T, P[r][c] = sum_m A[m][r]*B[c][m]
assertion(mNumColumns == mat.mNumColumns,
"Mismatch in TransposeTimesTranspose\n");
#endif
GMatrix<Real> result(mNumColumns, mat.mNumRows);
for (int r = 0; r < result.mNumRows; ++r)
{
for (int c = 0; c < result.mNumColumns; ++c)
{
for (int m = 0; m < mNumColumns; ++m)
{
result.mEntry[r][c] += mEntry[m][r] * mat.mEntry[c][m];
}
}
}
return result;
}
//----------------------------------------------------------------------------
| true |
7087c1ec3b0816168baec111e8a577165e52ba59 | C++ | DrXlor/pp_2019_autumn | /modules/task_1/rezantsev_s_min_matrix/min_matrix.cpp | UTF-8 | 2,195 | 2.734375 | 3 | [] | no_license | // Copyright 2019 Rezantsev Sergey
#include "../../../modules/task_1/rezantsev_s_min_matrix/min_matrix.h"
#include <mpi.h>
#include <algorithm>
#include <ctime>
#include <iostream>
#include <random>
#include <stdexcept>
#include <vector>
std::vector<int> getRandMatrix(int n, int m) {
std::mt19937 gen;
gen.seed(static_cast<unsigned int>(time(0)));
std::vector<int> matrix(n * m);
for (int i = 0; i < n * m; i++) {
matrix[i] = gen() % 100;
}
return matrix;
}
std::vector<int> getOrdMinOfMatrix(const std::vector<int> &a, int n, int m) {
std::vector<int> x(m, 1000);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
x[i] = std::min(x[i], a[i + j * m]);
}
return x;
}
std::vector<int> getMinOfMatrix(const std::vector<int> &a, int n,
int m) {
int size, rank;
std::vector<int> res(m, 1000);
std::vector<int> tmp(m, 1000);
std::vector<int> temp(m, 1000);
std::vector<int> str(n);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
if (m <= 0) throw std::runtime_error("m <=0");
if (n <= 0) throw std::runtime_error("n <=0");
}
if (rank == 0) {
for (int i = 0; i < m; i++) {
if (i % size) {
for (int j = 0; j < n; j++) str[j] = a[i + j * m];
MPI_Send(&str[0], n, MPI_INT, i % size, 1, MPI_COMM_WORLD);
}
}
}
MPI_Status status;
std::vector<int> b(n);
if (rank == 0) {
for (int i = 0; i < m; i += size) {
for (int j = 0; j < n; j++) str[j] = a[i + j * m];
temp[i] = std::min(*min_element(str.begin(), str.end()), temp[i]);
}
} else {
if (rank < m) {
for (int i = rank; i < m; i += size) {
MPI_Recv(&b[0], n, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
res[i] = std::min(res[i], *min_element(b.begin(), b.end()));
}
MPI_Send(&res[0], m, MPI_INT, 0, 2, MPI_COMM_WORLD);
}
}
if ((rank == 0) && (rank < m) && (m > 1)) {
for (int proc = 1; proc < std::min(size, m); proc++) {
MPI_Recv(&res[0], m, MPI_INT, proc, 2, MPI_COMM_WORLD, &status);
for (int j = proc; j < m; j += size) {
temp[j] = res[j];
}
}
}
return temp;
}
| true |
031f7ad696be436696cd2420605f771300a5725b | C++ | dimritium/Code | /DSprep/treeTr.cpp | UTF-8 | 580 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define fl(a,b,c) for(a=b;a<c;a++)
#define flr(a,b,c) for(a=b-1;a>=0;a--)
#define MOD 10000000007
using namespace std;
struct treeNode
{
int data;
struct treeNode *left;
struct treeNode *right;
};
void preOrtr(struct treeNode *root)
{
if(root)
{
cout<<root->data;
preOrtr(root->left);
preOrtr(root->right);
}
}
int main()
{
treeNode *x=new treeNode();
treeNode *y=new treeNode();
treeNode *z=new treeNode();
x->data=5;
x->left=y;
x->right=z;
y->data=6;
y->left=y->right=NULL;
z->data=7;
z->left=z->right=NULL;
preOrtr(x);
return 0;
} | true |
d9e84b460e9ac43ed0b2d27faa166a693c5bf18e | C++ | jristic/renderland | /source/gui.cpp | UTF-8 | 2,470 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license |
namespace gui {
void DisplayShaderConstants(std::vector<rlf::ConstantBuffer>& CBs, ID3D11ShaderReflection* reflector)
{
D3D11_SHADER_DESC sd;
reflector->GetDesc(&sd);
u32 cb_index = 0;
for (u32 ic = 0 ; ic < sd.ConstantBuffers ; ++ic)
{
D3D11_SHADER_BUFFER_DESC bd;
ID3D11ShaderReflectionConstantBuffer* constBuffer =
reflector->GetConstantBufferByIndex(ic);
constBuffer->GetDesc(&bd);
if (bd.Type != D3D11_CT_CBUFFER)
continue;
const rlf::ConstantBuffer& cb = CBs[cb_index];
// Buffers were not created for the skipped buffer types,
// so we need to advance index used in the rlf data only
// for those not skipped.
++cb_index;
for (u32 j = 0 ; j < bd.Variables ; ++j)
{
ID3D11ShaderReflectionVariable* var = constBuffer->GetVariableByIndex(j);
D3D11_SHADER_VARIABLE_DESC vd;
var->GetDesc(&vd);
ID3D11ShaderReflectionType* ctype = var->GetType();
D3D11_SHADER_TYPE_DESC td;
ctype->GetDesc(&td);
switch (td.Type)
{
case D3D_SVT_BOOL: {
bool val = *(bool*)(cb.BackingMemory+vd.StartOffset);
ImGui::Text("%s: %s", vd.Name, val ? "true" : "false");
break;
}
case D3D_SVT_INT: {
i32 val = *(i32*)(cb.BackingMemory+vd.StartOffset);
ImGui::Text("%s: %d", vd.Name, val);
break;
}
case D3D_SVT_UINT: {
u32 val = *(u32*)(cb.BackingMemory+vd.StartOffset);
ImGui::Text("%s: %u", vd.Name, val);
break;
}
case D3D_SVT_FLOAT: {
float val = *(float*)(cb.BackingMemory+vd.StartOffset);
ImGui::Text("%s: %f", vd.Name, val);
break;
}
default:
Unimplemented();
}
}
}
}
void DisplayShaderPasses(rlf::RenderDescription* rd)
{
std::vector<rlf::Pass> passes = rd->Passes;
for (int i = 0 ; i < passes.size() ; ++i)
{
rlf::Pass& p = passes[i];
static int selected_index = -1;
if (ImGui::Selectable(p.Name ? p.Name : "anon", selected_index == i))
selected_index = i;
ImGui::Indent();
switch (p.Type) {
case rlf::PassType::Dispatch:
DisplayShaderConstants(p.Dispatch->CBs, p.Dispatch->Shader->Common.Reflector);
break;
case rlf::PassType::Draw:
DisplayShaderConstants(p.Draw->VSCBs, p.Draw->VShader->Common.Reflector);
DisplayShaderConstants(p.Draw->PSCBs, p.Draw->PShader->Common.Reflector);
break;
case rlf::PassType::ClearColor:
case rlf::PassType::ClearDepth:
case rlf::PassType::ClearStencil:
case rlf::PassType::Resolve:
break;
default:
Unimplemented();
}
ImGui::Unindent();
}
}
} | true |
8bf09d4b3019bd3cbb94cbefc9ff07624a4814a1 | C++ | Jbok/Baekjoon_Online_Judge | /9600/9663.cpp | UTF-8 | 952 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int leftCross[2][15] = { { 0, }, };
int upCross[30] = { 0, };
int row[15] = { 0, };
int col[15] = { 0, };
void dfs(int n, int depth, int *result)
{
if (depth == n)
{
*result = *result + 1;
return;
}
for (int i = 0; i < n; i++)
{
int k = i - depth;
int p = 0;
if (k < 0)
p = 1;
k = abs(k);
if (row[i] == 0 && col[depth] == 0 && upCross[i+depth] == 0 && leftCross[p][k] == 0)
{
row[i] = 1;
col[depth] = 1;
upCross[i+depth] = 1;
leftCross[p][k] = 1;
dfs(n, depth + 1, result);
row[i] = 0;
col[depth] = 0;
upCross[i+depth] = 0;
leftCross[p][k] = 0;
}
}
}
int main()
{
int n;
cin >> n;
int max = 0;
int *pmax = &max;
dfs(n, 0, pmax);
printf("%d\n", max);
} | true |
fa10ad2b499e3f5b1ab4018b3ceb8232fa2a90a0 | C++ | chromium/chromium | /third_party/abseil-cpp/absl/functional/any_invocable.h | UTF-8 | 12,535 | 2.875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause"
] | permissive | // Copyright 2022 The Abseil 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
//
// https://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.
//
// -----------------------------------------------------------------------------
// File: any_invocable.h
// -----------------------------------------------------------------------------
//
// This header file defines an `absl::AnyInvocable` type that assumes ownership
// and wraps an object of an invocable type. (Invocable types adhere to the
// concept specified in https://en.cppreference.com/w/cpp/concepts/invocable.)
//
// In general, prefer `absl::AnyInvocable` when you need a type-erased
// function parameter that needs to take ownership of the type.
//
// NOTE: `absl::AnyInvocable` is similar to the C++23 `std::move_only_function`
// abstraction, but has a slightly different API and is not designed to be a
// drop-in replacement or C++11-compatible backfill of that type.
//
// Credits to Matt Calabrese (https://github.com/mattcalabrese) for the original
// implementation.
#ifndef ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
#define ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
#include <cstddef>
#include <initializer_list>
#include <type_traits>
#include <utility>
#include "absl/base/config.h"
#include "absl/functional/internal/any_invocable.h"
#include "absl/meta/type_traits.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
// absl::AnyInvocable
//
// `absl::AnyInvocable` is a functional wrapper type, like `std::function`, that
// assumes ownership of an invocable object. Unlike `std::function`, an
// `absl::AnyInvocable` is more type-safe and provides the following additional
// benefits:
//
// * Properly adheres to const correctness of the underlying type
// * Is move-only so avoids concurrency problems with copied invocables and
// unnecessary copies in general.
// * Supports reference qualifiers allowing it to perform unique actions (noted
// below).
//
// `absl::AnyInvocable` is a template, and an `absl::AnyInvocable` instantiation
// may wrap any invocable object with a compatible function signature, e.g.
// having arguments and return types convertible to types matching the
// `absl::AnyInvocable` signature, and also matching any stated reference
// qualifiers, as long as that type is moveable. It therefore provides broad
// type erasure for functional objects.
//
// An `absl::AnyInvocable` is typically used as a type-erased function parameter
// for accepting various functional objects:
//
// // Define a function taking an AnyInvocable parameter.
// void my_func(absl::AnyInvocable<int()> f) {
// ...
// };
//
// // That function can accept any invocable type:
//
// // Accept a function reference. We don't need to move a reference.
// int func1() { return 0; };
// my_func(func1);
//
// // Accept a lambda. We use std::move here because otherwise my_func would
// // copy the lambda.
// auto lambda = []() { return 0; };
// my_func(std::move(lambda));
//
// // Accept a function pointer. We don't need to move a function pointer.
// func2 = &func1;
// my_func(func2);
//
// // Accept an std::function by moving it. Note that the lambda is copyable
// // (satisfying std::function requirements) and moveable (satisfying
// // absl::AnyInvocable requirements).
// std::function<int()> func6 = []() { return 0; };
// my_func(std::move(func6));
//
// `AnyInvocable` also properly respects `const` qualifiers, reference
// qualifiers, and the `noexcept` specification (only in C++ 17 and beyond) as
// part of the user-specified function type (e.g.
// `AnyInvocable<void()&& const noexcept>`). These qualifiers will be applied to
// the `AnyInvocable` object's `operator()`, and the underlying invocable must
// be compatible with those qualifiers.
//
// Comparison of const and non-const function types:
//
// // Store a closure inside of `func` with the function type `int()`.
// // Note that we have made `func` itself `const`.
// const AnyInvocable<int()> func = [](){ return 0; };
//
// func(); // Compile-error: the passed type `int()` isn't `const`.
//
// // Store a closure inside of `const_func` with the function type
// // `int() const`.
// // Note that we have also made `const_func` itself `const`.
// const AnyInvocable<int() const> const_func = [](){ return 0; };
//
// const_func(); // Fine: `int() const` is `const`.
//
// In the above example, the call `func()` would have compiled if
// `std::function` were used even though the types are not const compatible.
// This is a bug, and using `absl::AnyInvocable` properly detects that bug.
//
// In addition to affecting the signature of `operator()`, the `const` and
// reference qualifiers of the function type also appropriately constrain which
// kinds of invocable objects you are allowed to place into the `AnyInvocable`
// instance. If you specify a function type that is const-qualified, then
// anything that you attempt to put into the `AnyInvocable` must be callable on
// a `const` instance of that type.
//
// Constraint example:
//
// // Fine because the lambda is callable when `const`.
// AnyInvocable<int() const> func = [=](){ return 0; };
//
// // This is a compile-error because the lambda isn't callable when `const`.
// AnyInvocable<int() const> error = [=]() mutable { return 0; };
//
// An `&&` qualifier can be used to express that an `absl::AnyInvocable`
// instance should be invoked at most once:
//
// // Invokes `continuation` with the logical result of an operation when
// // that operation completes (common in asynchronous code).
// void CallOnCompletion(AnyInvocable<void(int)&&> continuation) {
// int result_of_foo = foo();
//
// // `std::move` is required because the `operator()` of `continuation` is
// // rvalue-reference qualified.
// std::move(continuation)(result_of_foo);
// }
//
// Attempting to call `absl::AnyInvocable` multiple times in such a case
// results in undefined behavior.
template <class Sig>
class AnyInvocable : private internal_any_invocable::Impl<Sig> {
private:
static_assert(
std::is_function<Sig>::value,
"The template argument of AnyInvocable must be a function type.");
using Impl = internal_any_invocable::Impl<Sig>;
public:
// The return type of Sig
using result_type = typename Impl::result_type;
// Constructors
// Constructs the `AnyInvocable` in an empty state.
AnyInvocable() noexcept = default;
AnyInvocable(std::nullptr_t) noexcept {} // NOLINT
// Constructs the `AnyInvocable` from an existing `AnyInvocable` by a move.
// Note that `f` is not guaranteed to be empty after move-construction,
// although it may be.
AnyInvocable(AnyInvocable&& /*f*/) noexcept = default;
// Constructs an `AnyInvocable` from an invocable object.
//
// Upon construction, `*this` is only empty if `f` is a function pointer or
// member pointer type and is null, or if `f` is an `AnyInvocable` that is
// empty.
template <class F, typename = absl::enable_if_t<
internal_any_invocable::CanConvert<Sig, F>::value>>
AnyInvocable(F&& f) // NOLINT
: Impl(internal_any_invocable::ConversionConstruct(),
std::forward<F>(f)) {}
// Constructs an `AnyInvocable` that holds an invocable object of type `T`,
// which is constructed in-place from the given arguments.
//
// Example:
//
// AnyInvocable<int(int)> func(
// absl::in_place_type<PossiblyImmovableType>, arg1, arg2);
//
template <class T, class... Args,
typename = absl::enable_if_t<
internal_any_invocable::CanEmplace<Sig, T, Args...>::value>>
explicit AnyInvocable(absl::in_place_type_t<T>, Args&&... args)
: Impl(absl::in_place_type<absl::decay_t<T>>,
std::forward<Args>(args)...) {
static_assert(std::is_same<T, absl::decay_t<T>>::value,
"The explicit template argument of in_place_type is required "
"to be an unqualified object type.");
}
// Overload of the above constructor to support list-initialization.
template <class T, class U, class... Args,
typename = absl::enable_if_t<internal_any_invocable::CanEmplace<
Sig, T, std::initializer_list<U>&, Args...>::value>>
explicit AnyInvocable(absl::in_place_type_t<T>,
std::initializer_list<U> ilist, Args&&... args)
: Impl(absl::in_place_type<absl::decay_t<T>>, ilist,
std::forward<Args>(args)...) {
static_assert(std::is_same<T, absl::decay_t<T>>::value,
"The explicit template argument of in_place_type is required "
"to be an unqualified object type.");
}
// Assignment Operators
// Assigns an `AnyInvocable` through move-assignment.
// Note that `f` is not guaranteed to be empty after move-assignment
// although it may be.
AnyInvocable& operator=(AnyInvocable&& /*f*/) noexcept = default;
// Assigns an `AnyInvocable` from a nullptr, clearing the `AnyInvocable`. If
// not empty, destroys the target, putting `*this` into an empty state.
AnyInvocable& operator=(std::nullptr_t) noexcept {
this->Clear();
return *this;
}
// Assigns an `AnyInvocable` from an existing `AnyInvocable` instance.
//
// Upon assignment, `*this` is only empty if `f` is a function pointer or
// member pointer type and is null, or if `f` is an `AnyInvocable` that is
// empty.
template <class F, typename = absl::enable_if_t<
internal_any_invocable::CanAssign<Sig, F>::value>>
AnyInvocable& operator=(F&& f) {
*this = AnyInvocable(std::forward<F>(f));
return *this;
}
// Assigns an `AnyInvocable` from a reference to an invocable object.
// Upon assignment, stores a reference to the invocable object in the
// `AnyInvocable` instance.
template <
class F,
typename = absl::enable_if_t<
internal_any_invocable::CanAssignReferenceWrapper<Sig, F>::value>>
AnyInvocable& operator=(std::reference_wrapper<F> f) noexcept {
*this = AnyInvocable(f);
return *this;
}
// Destructor
// If not empty, destroys the target.
~AnyInvocable() = default;
// absl::AnyInvocable::swap()
//
// Exchanges the targets of `*this` and `other`.
void swap(AnyInvocable& other) noexcept { std::swap(*this, other); }
// absl::AnyInvocable::operator bool()
//
// Returns `true` if `*this` is not empty.
//
// WARNING: An `AnyInvocable` that wraps an empty `std::function` is not
// itself empty. This behavior is consistent with the standard equivalent
// `std::move_only_function`.
//
// In other words:
// std::function<void()> f; // empty
// absl::AnyInvocable<void()> a = std::move(f); // not empty
explicit operator bool() const noexcept { return this->HasValue(); }
// Invokes the target object of `*this`. `*this` must not be empty.
//
// Note: The signature of this function call operator is the same as the
// template parameter `Sig`.
using Impl::operator();
// Equality operators
// Returns `true` if `*this` is empty.
friend bool operator==(const AnyInvocable& f, std::nullptr_t) noexcept {
return !f.HasValue();
}
// Returns `true` if `*this` is empty.
friend bool operator==(std::nullptr_t, const AnyInvocable& f) noexcept {
return !f.HasValue();
}
// Returns `false` if `*this` is empty.
friend bool operator!=(const AnyInvocable& f, std::nullptr_t) noexcept {
return f.HasValue();
}
// Returns `false` if `*this` is empty.
friend bool operator!=(std::nullptr_t, const AnyInvocable& f) noexcept {
return f.HasValue();
}
// swap()
//
// Exchanges the targets of `f1` and `f2`.
friend void swap(AnyInvocable& f1, AnyInvocable& f2) noexcept { f1.swap(f2); }
private:
// Friending other instantiations is necessary for conversions.
template <bool /*SigIsNoexcept*/, class /*ReturnType*/, class... /*P*/>
friend class internal_any_invocable::CoreImpl;
};
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_FUNCTIONAL_ANY_INVOCABLE_H_
| true |
76948d3d030c9b6260181d3cb5c53518198f2202 | C++ | ameerhaider/cpp-programs | /dimond.cpp | UTF-8 | 952 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
cout << "hello"<<endl;
int a = 9;
int spaces=a-3;
if (a % 2 != 0 ){
for (int stars = 0 ; stars < a ;stars = stars+2) {
for(int s = 0; s < spaces; s++) {
cout<<" ";
}
for(int x = 0; x <= stars; x++) {
cout<<"*";
}
cout<<endl;
spaces--;
}
spaces = a-6;
for (int b =1; b < a ; b=b+2){
for (int c=0; c < spaces ; c++ ){
cout <<" ";
}
for ( int s= a-2 ; s>=b;s--){
cout << "*";
}
cout << endl;
spaces ++;
}
} else {
cout << "plz enter an odd number thanks";
}
return 0;
} | true |
73165ddc88a05a3dad86b415f9e3813358c07f04 | C++ | atem11/ITMO_Labs | /1(stack)/f.cpp | UTF-8 | 1,103 | 3.40625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct node
{
int value;
node *next;
node()
{
}
node(int new_value, node *new_next)
{
value = new_value;
next = new_next;
}
};
struct my_stack
{
node *head = NULL;
void push(int new_value)
{
head = new node(new_value, head);
}
int pop()
{
int new_value = head -> value;
node *trash_head = head -> next;
free(head);
head = trash_head;
return new_value;
}
};
int main()
{
freopen("postfix.in", "r", stdin);
freopen("postfix.out", "w", stdout);
my_stack a = my_stack();
char c;
while(scanf("%c ", &c) == 1)
{
if (c != '+' && c != '-' && c != '*') a.push((int)(c - '0'));
else
{
int x, y;
x = a.pop();
y = a.pop();
if (c == '+')
a.push(x + y);
if (c == '-')
a.push(y - x);
if (c == '*')
a.push(x * y);
}
}
printf("%d\n", a.pop());
return 0;
}
| true |
2bb6da0c6c50447bcfd13380c0f1b854b0a5ee4e | C++ | Viv786ek/Cracking-any-interview-Code | /Minimum Swaps to Sort.cpp | UTF-8 | 1,921 | 3.15625 | 3 | [] | no_license |
class Solution {
private:
public:
//Method 1
int minSwaps(vector<int>&nums){
// Code here
int N = nums.size();
pair<int, int> arrPos[N];
for (int i = 0; i < N; i++)
{
arrPos[i].first = nums[i];
arrPos[i].second = i;
}
sort(arrPos, arrPos + N);
vector<bool> visited(N, false);
int ans = 0;
for(int i = 0; i < N; i++)
{
if (visited[i] == true || arrPos[i].second == i)
{
continue;
}
int cycle_size = 0;
int j = i;
while (!visited[j])
{
visited[j] = 1;
j = arrPos[j].second;
cycle_size++;
}
if (cycle_size > 0)
{
ans += (cycle_size - 1);
}
}
return ans;
}
//Method 2
/*
void swap(vector<int> &arr,
int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Return the minimum number
// of swaps required to sort
// the array
int minSwaps(vector<int>arr,
int N)
{
int ans = 0;
vector<int>temp = arr;
// Hashmap which stores the
// indexes of the input array
map <int, int> h;
sort(temp.begin(), temp.end());
for (int i = 0; i < N; i++)
{
h[arr[i]] = i;
}
for (int i = 0; i < N; i++)
{
// This is checking whether
// the current element is
// at the right place or not
if (arr[i] != temp[i])
{
ans++;
int init = arr[i];
// If not, swap this element
// with the index of the
// element which should come here
swap(arr, i, h[temp[i]]);
// Update the indexes in
// the hashmap accordingly
h[init] = h[temp[i]];
h[temp[i]] = i;
}
}
return ans;
}
*/
};
| true |
095662282579afbc17beb4e70a9faf6d958361f0 | C++ | ydk1104/PS | /5575.cpp | UTF-8 | 219 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
int main(void){
for(int i=0; i<3; i++){
int a,b,c,d,e,f;
scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);
d-=a; e-=b; f-=c;
if(f<0) f+=60,e--;
if(e<0) e+=60,d--;
printf("%d %d %d\n",d,e,f);
}
}
| true |
f2c1cadc8ce9d96f1e00f0d570694d959f8272bb | C++ | weixing0909/CppProject | /cv/opencv_base/opencv_08_image_analysis.cpp | UTF-8 | 5,540 | 2.984375 | 3 | [] | no_license | #include "main.h"
void convolveDFT(Mat A, Mat B, Mat& C)
{
// reallocate the output array if needed
C.create(abs(A.rows - B.rows) + 1, abs(A.cols - B.cols) + 1, A.type());
Size dftSize;
// calculate the size of DFT transform
dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
// allocate temporary buffers and initialize them with 0's
Mat tempA(dftSize, A.type(), Scalar::all(0));//initial 0
Mat tempB(dftSize, B.type(), Scalar::all(0));
// copy A and B to the top-left corners of tempA and tempB, respectively
Mat roiA(tempA, Rect(0, 0, A.cols, A.rows));
A.copyTo(roiA);
Mat roiB(tempB, Rect(0, 0, B.cols, B.rows));
B.copyTo(roiB);
// now transform the padded A & B in-place;
// use "nonzeroRows" hint for faster processing
dft(tempA, tempA, 0, A.rows);
dft(tempB, tempB, 0, B.rows);
// multiply the spectrums;
// the function handles packed spectrum representations well
mulSpectrums(tempA, tempB, tempA, DFT_COMPLEX_OUTPUT);
//mulSpectrums(tempA, tempB, tempA, DFT_REAL_OUTPUT);
// transform the product back from the frequency domain.
// Even though all the result rows will be non-zero,
// you need only the first C.rows of them, and thus you
// pass nonzeroRows == C.rows
dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
// now copy the result back to C.
tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
// all the temporary buffers will be deallocated automatically
}
void dft_test()
{
string imagePath = "D:\\dataset\\test_image/lena.jpg";
Mat img = imread(imagePath, 0);
img.convertTo(img, CV_64F);
int64 tt = getTickCount();
Mat dst;
dft(img, dst);
int range = 2;
//dst(Rect(0, 0, dst.cols / 40, dst.rows / 40)).setTo(Scalar(0));
dst(Rect(dst.cols - dst.cols / range, dst.rows - dst.rows / range, dst.cols / range, dst.rows / range)).setTo(Scalar(0));
Mat src;
idft(dst, src);
Mat k = (Mat_<float>(3, 3) << -1, 0, 1, -1, 0, 1, -1, 0, 1);
Mat k2;
dft(k, k2);
Mat floatI = Mat_<float>(img);
Mat filteredI;
convolveDFT(floatI, k, filteredI);
Mat dst2;
dct(img, dst2);
Mat src2;
idct(dst2, src2);
cout << "time: " << (getTickCount() - tt) / getTickFrequency() * 1000 << endl;
cout << endl;
}
void integral_test()
{
string imagePath = "D:\\dataset\\test_image/lena.jpg";
Mat img = imread(imagePath, 0);
Mat dst;
integral(img, dst);
// cv::integral for standard summation integral
// cv::integral for squared summation integral
// cv::integral for tilted summation integral
cout << endl;
}
void canny_test()
{
string imagePath = "D:\\dataset\\test_image/lena.jpg";
Mat img = imread(imagePath, 0);
Mat dst1;
Canny(img, dst1, 15, 45);
Mat dst2;
Canny(img, dst2, 30, 90);
Mat dst3;
Canny(img, dst3, 30, 90, 5);
cout << endl;
}
void hough_test()
{
string imagePath = "D:\\dataset\\test_image/street.jpg";
Mat image = imread(imagePath);
Mat img;
cvtColor(image, img, COLOR_BGR2GRAY);
Mat dst1;
Canny(img, dst1, 50, 200);
vector<Vec2f> lines;
HoughLines(dst1, lines, 1, CV_PI / 180, 300, 0, 0);
// cv::HoughLinesP() the progreassive probabilistic hough transform
Mat img2;
image.copyTo(img2);
for (size_t i = 0; i < lines.size(); i++)
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(img2, pt1, pt2, Scalar(0, 255, 0), 1);
}
string imagePath2 = "D:\\dataset\\test_image/circle.jpg";
Mat image3 = imread(imagePath2);
Mat img3;
cvtColor(image3, img3, COLOR_BGR2GRAY);
cv::GaussianBlur(img3, img3, Size(5, 5), 0, 0);
//Mat dst3;
//Canny(img3, dst3, 40, 60);
vector<Vec3f> circles;
HoughCircles(img3, circles, HOUGH_GRADIENT, 1, img3.rows / 10, 100, 60, 0, 0);
Mat img4;
image3.copyTo(img4);
for (size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
circle(img4, center, 3, Scalar(0, 255, 0), -1, 8, 0);
circle(img4, center, radius, Scalar(0, 0, 255), 3, 8, 0);
}
cout << endl;
}
void segmentation_test()
{
string imagePath = "D:\\dataset\\test_image/star.jpg";
Mat image = imread(imagePath);
Mat imageGray;
cvtColor(image, imageGray, COLOR_BGR2GRAY);
imageGray = ~imageGray;
Mat dst;
distanceTransform(imageGray, dst, DIST_L2, 5);
normalize(dst, dst, 0, 255, NORM_MINMAX);
// cv::floodFill
// cv::watershed
// cv::grabCut
// cv::pyrMeanShiftFiltering
string imagePath2 = "D:\\dataset\\test_image/201907081015.jpg";
Mat image2 = imread(imagePath2);
Mat img3 = image2.clone();
Rect rect;
floodFill(img3, Point(20, 20), Scalar(255, 0, 0), &rect, Scalar(10, 10, 10), Scalar(10, 10, 10));
//Mat mask1(img3.rows + 2, img3.cols + 2, CV_8UC1);
//floodFill(image2, mask1, Point(20, 20), Scalar(255, 0, 0), &rect, Scalar(10, 10, 10), Scalar(10, 10, 10));
Mat img4 = image2.clone();
line(img4, Point(344, 128), Point(438, 224), Scalar(255, 255, 255), 10);
Mat mask2 = Mat(img4.size(), CV_32S);
mask2 = Scalar::all(0);
watershed(image2, mask2);
cout << endl;
}
void opencv_08_image_analysis()
{
cout << "entry opencv_08_image_analysis " << endl;
int index = 4;
switch (index)
{
case 0:dft_test(); break;
case 1:integral_test(); break;
case 2:canny_test(); break;
case 3:hough_test(); break;
case 4:segmentation_test(); break;
default:break;
}
cout << "quit opencv_08_image_analysis " << endl;
} | true |
5ec2103015c1aa73b03a1feb13d9a89f08435084 | C++ | BlitzBurn/Jsontest | /JsonSlave-master/Http/HttpHeader.hpp | UTF-8 | 756 | 2.765625 | 3 | [
"MIT"
] | permissive | //
// Created by Per Andersson on 2018-02-23.
// Copyright (c) 2018 West Coast Code AB. All rights reserved.
//
#ifndef JSONSLAVE_HTTPHEADER_HPP
#define JSONSLAVE_HTTPHEADER_HPP
#include "../Config.hpp"
/**
* Object representing an Http Header
*/
struct HttpHeader
{
HttpHeader(const string& name, const string& value)
: mName(name), mValue(value) {}
explicit HttpHeader(const HttpHeader& rhs)
: mName(rhs.mName), mValue(rhs.mValue) {}
/**
* @return The name of the header
*/
inline const string& GetName() const {
return mName;
}
/**
* @return The headers value
*/
inline const string& GetValue() const {
return mValue;
}
int GetIntValue() const;
private:
string mName;
string mValue;
};
#endif //JSONSLAVE_HTTPHEADER_HPP
| true |
fc09b6dc1ac0bd77a25e806c0dc1ec55cda3512a | C++ | Tuka96/CPP_Program | /July_30/July_30-1/Student.cpp | UTF-8 | 461 | 3.328125 | 3 | [] | no_license | #include"cStudent2.h"
cStudent::cStudent()
{
rollNo = 0;
height = 0;
weight = 0;
}
cStudent::cStudent(int r, float h, float w)
{
rollNo = r;
height = h;
weight = w;
}
void cStudent::display()
{
cout << "\nRoll No::" << rollNo;
cout << "\n Height::" << height;
cout << "\nWeight::" << weight;
}
void cStudent::Accept()
{
cout << "\nEnter roll No::";
cin>>rollNo;
cout << "\n Enter weight::";
cin>>height;
cout << "\nEnter weight::";
cin>>weight;
} | true |
1412d1e69662a19fdd713f0fa3d1fb2b997a63ba | C++ | mduarte-git/DuarteMark_CIS_40402 | /Homework/Assignment_3/Gaddis_9thEd_Chap4_Prob8_Sort_Names/main.cpp | UTF-8 | 895 | 3.484375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Dr. Mark E. Lehr
* Created on January 2, 2019, 12:36 PM
* Purpose: Creation of Template to be used for all
* future projects
*/
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int books_purchased;
cout<<"Book Worm Points\n"<<"Input the number of books purchased this month.\n";
cin>>books_purchased;
cout<<"Books purchased = "<<books_purchased<<endl;
if(books_purchased == 0)
cout<<"Points earned = 0";
else if(books_purchased == 1)
cout<<"Points earned = 5";
else if(books_purchased == 2)
cout<<"Points earned = 15";
else if(books_purchased == 3)
cout<<"Points earned = 30";
else if(books_purchased >= 4)
cout<<"Points earned = 60";
else
{
cout<<"Invalid number";
}
return 0;
} | true |
0761c86107646fb0d5599be8987e2fea1a53a5f8 | C++ | RattleInGlasses/ps_oop | /lab03/2.Rectangles/src/rectanglesTests/RectangleTests.cpp | UTF-8 | 23,889 | 2.84375 | 3 | [] | no_license | #include "stdafx.h";
#include "..\rectangles\Rectangle.h"
BOOST_AUTO_TEST_SUITE(RectangleTests)
// init state
BOOST_AUTO_TEST_CASE(InitialState)
{
CRectangle rect(0, 0, 0, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
BOOST_CHECK_EQUAL(rect.GetRight(), 0);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
BOOST_CHECK_EQUAL(rect.GetBottom(), 0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
BOOST_CHECK_EQUAL(*rect.GetArea(), 0);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), 0);
CRectangle rect2(10, 25, 100, 200);
BOOST_CHECK_EQUAL(rect2.GetLeft(), 10);
BOOST_CHECK_EQUAL(rect2.GetRight(), 110);
BOOST_CHECK_EQUAL(rect2.GetTop(), 25);
BOOST_CHECK_EQUAL(rect2.GetBottom(), 225);
BOOST_CHECK_EQUAL(rect2.GetHeight(), 200);
BOOST_CHECK_EQUAL(rect2.GetWidth(), 100);
BOOST_CHECK_EQUAL(*rect2.GetArea(), 20000);
BOOST_CHECK_EQUAL(*rect2.GetPerimeter(), 600);
CRectangle rect3(10, 25, -100, -200);
BOOST_CHECK_EQUAL(rect3.GetLeft(), 10);
BOOST_CHECK_EQUAL(rect3.GetRight(), 10);
BOOST_CHECK_EQUAL(rect3.GetTop(), 25);
BOOST_CHECK_EQUAL(rect3.GetBottom(), 25);
BOOST_CHECK_EQUAL(rect3.GetHeight(), 0);
BOOST_CHECK_EQUAL(rect3.GetWidth(), 0);
BOOST_CHECK_EQUAL(*rect3.GetArea(), 0);
BOOST_CHECK_EQUAL(*rect3.GetPerimeter(), 0);
}
// properties
//// properties setting
BOOST_AUTO_TEST_CASE(WidthCanBeSet)
{
CRectangle rect(0, 0, 0, 0);
rect.SetWidth(20);
BOOST_CHECK_EQUAL(rect.GetWidth(), 20);
rect.SetWidth(100);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
rect.SetWidth(0);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
}
BOOST_AUTO_TEST_CASE(HeightCanBeSet)
{
CRectangle rect(0, 0, 0, 0);
rect.SetHeight(20);
BOOST_CHECK_EQUAL(rect.GetHeight(), 20);
rect.SetHeight(100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 100);
rect.SetHeight(0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
}
BOOST_AUTO_TEST_CASE(LeftCanBeSet)
{
CRectangle rect(0, 0, 100, 0);
rect.SetLeft(20);
BOOST_CHECK_EQUAL(rect.GetLeft(), 20);
rect.SetLeft(-100);
BOOST_CHECK_EQUAL(rect.GetLeft(), -100);
rect.SetLeft(0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
}
BOOST_AUTO_TEST_CASE(TopCanBeSet)
{
CRectangle rect(0, 0, 0, 100);
rect.SetTop(20);
BOOST_CHECK_EQUAL(rect.GetTop(), 20);
rect.SetTop(-100);
BOOST_CHECK_EQUAL(rect.GetTop(), -100);
rect.SetTop(0);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
}
BOOST_AUTO_TEST_CASE(RightCanBeSet)
{
CRectangle rect(-200, 0, 0, 0);
rect.SetRight(20);
BOOST_CHECK_EQUAL(rect.GetRight(), 20);
rect.SetRight(-100);
BOOST_CHECK_EQUAL(rect.GetRight(), -100);
rect.SetRight(0);
BOOST_CHECK_EQUAL(rect.GetRight(), 0);
}
BOOST_AUTO_TEST_CASE(BottomCanBeSet)
{
CRectangle rect(0, -200, 0, 0);
rect.SetBottom(20);
BOOST_CHECK_EQUAL(rect.GetBottom(), 20);
rect.SetBottom(-100);
BOOST_CHECK_EQUAL(rect.GetBottom(), -100);
rect.SetBottom(0);
BOOST_CHECK_EQUAL(rect.GetBottom(), 0);
}
//// properties relations
BOOST_AUTO_TEST_CASE(SetWidthChangeRight)
{
CRectangle rect(0, 0, 0, 0);
rect.SetWidth(10);
BOOST_CHECK_EQUAL(rect.GetRight(), 10);
rect.SetWidth(222);
BOOST_CHECK_EQUAL(rect.GetRight(), 222);
rect.SetWidth(0);
BOOST_CHECK_EQUAL(rect.GetRight(), 0);
}
BOOST_AUTO_TEST_CASE(SetRightChangeWidth)
{
CRectangle rect(0, 0, 0, 0);
rect.SetRight(10);
BOOST_CHECK_EQUAL(rect.GetWidth(), 10);
rect.SetRight(222);
BOOST_CHECK_EQUAL(rect.GetWidth(), 222);
rect.SetRight(0);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
}
BOOST_AUTO_TEST_CASE(SetLeftChangeWidth)
{
CRectangle rect(0, 0, 0, 0);
rect.SetLeft(-10);
BOOST_CHECK_EQUAL(rect.GetWidth(), 10);
rect.SetLeft(-222);
BOOST_CHECK_EQUAL(rect.GetWidth(), 222);
rect.SetLeft(0);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
}
BOOST_AUTO_TEST_CASE(SetHeightChangeBottom)
{
CRectangle rect(0, 0, 0, 0);
rect.SetHeight(10);
BOOST_CHECK_EQUAL(rect.GetBottom(), 10);
rect.SetHeight(222);
BOOST_CHECK_EQUAL(rect.GetBottom(), 222);
rect.SetHeight(0);
BOOST_CHECK_EQUAL(rect.GetBottom(), 0);
}
BOOST_AUTO_TEST_CASE(SetBottomChangeHeight)
{
CRectangle rect(0, 0, 0, 0);
rect.SetBottom(10);
BOOST_CHECK_EQUAL(rect.GetHeight(), 10);
rect.SetBottom(222);
BOOST_CHECK_EQUAL(rect.GetHeight(), 222);
rect.SetBottom(0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
}
BOOST_AUTO_TEST_CASE(SetTopChangeHeight)
{
CRectangle rect(0, 0, 0, 0);
rect.SetTop(-10);
BOOST_CHECK_EQUAL(rect.GetHeight(), 10);
rect.SetTop(-222);
BOOST_CHECK_EQUAL(rect.GetHeight(), 222);
rect.SetTop(0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
}
BOOST_AUTO_TEST_CASE(ChangeAreaBySettingWidthHeight)
{
CRectangle rect(0, 0, 0, 0);
BOOST_CHECK_EQUAL(*rect.GetArea(), 0);
// zero area
rect.SetWidth(10);
rect.SetHeight(0);
BOOST_CHECK_EQUAL(*rect.GetArea(), 0);
rect.SetWidth(0);
rect.SetHeight(10);
BOOST_CHECK_EQUAL(*rect.GetArea(), 0);
// non-zero area
rect.SetWidth(10);
rect.SetHeight(5);
BOOST_CHECK_EQUAL(*rect.GetArea(), 50);
rect.SetWidth(125);
rect.SetHeight(20);
BOOST_CHECK_EQUAL(*rect.GetArea(), 2500);
}
BOOST_AUTO_TEST_CASE(ChangePerimeterBySettingWidthHeight)
{
CRectangle rect(0, 0, 0, 0);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), 0);
// 1 param check
rect.SetWidth(250);
rect.SetHeight(0);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), 500);
rect.SetWidth(0);
rect.SetHeight(500);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), 1000);
// 2 params check
rect.SetWidth(250);
rect.SetHeight(500);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), 1500);
}
//// properties restrictions
BOOST_AUTO_TEST_CASE(MinMaxLeft)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetLeft(INT_MIN);
BOOST_CHECK_EQUAL(rect.GetLeft(), INT_MIN);
// max value
rect.SetLeft(0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
rect.SetLeft(1);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
rect.SetRight(100);
rect.SetLeft(100);
BOOST_CHECK_EQUAL(rect.GetLeft(), 100);
rect.SetLeft(101);
BOOST_CHECK_EQUAL(rect.GetLeft(), 100);
}
BOOST_AUTO_TEST_CASE(MinMaxRight)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetRight(0);
BOOST_CHECK_EQUAL(rect.GetRight(), 0);
rect.SetRight(-1);
BOOST_CHECK_EQUAL(rect.GetRight(), 0);
rect.SetLeft(-100);
rect.SetRight(-100);
BOOST_CHECK_EQUAL(rect.GetRight(), -100);
rect.SetRight(-101);
BOOST_CHECK_EQUAL(rect.GetRight(), -100);
// max value
rect.SetRight(INT_MAX);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(MinMaxTop)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetTop(INT_MIN);
BOOST_CHECK_EQUAL(rect.GetTop(), INT_MIN);
// max value
rect.SetTop(0);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
rect.SetTop(1);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
rect.SetBottom(100);
rect.SetTop(100);
BOOST_CHECK_EQUAL(rect.GetTop(), 100);
rect.SetTop(101);
BOOST_CHECK_EQUAL(rect.GetTop(), 100);
}
BOOST_AUTO_TEST_CASE(MinMaxBottom)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetBottom(0);
BOOST_CHECK_EQUAL(rect.GetBottom(), 0);
rect.SetBottom(-1);
BOOST_CHECK_EQUAL(rect.GetBottom(), 0);
rect.SetTop(-100);
rect.SetBottom(-100);
BOOST_CHECK_EQUAL(rect.GetBottom(), -100);
rect.SetBottom(-101);
BOOST_CHECK_EQUAL(rect.GetBottom(), -100);
// max value
rect.SetBottom(INT_MAX);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(MinMaxWidth)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetWidth(0);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
rect.SetWidth(-1);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
// max value
rect.SetLeft(INT_MIN);
rect.SetRight(INT_MAX);
BOOST_CHECK_EQUAL(rect.GetWidth(), UINT_MAX);
rect.SetLeft(INT_MIN);
rect.SetRight(0);
rect.SetWidth(UINT_MAX);
BOOST_CHECK_EQUAL(rect.GetWidth(), UINT_MAX);
}
BOOST_AUTO_TEST_CASE(MinMaxHeight)
{
CRectangle rect(0, 0, 0, 0);
// min value
rect.SetHeight(0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
rect.SetHeight(-1);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
// max value
rect.SetTop(INT_MIN);
rect.SetBottom(INT_MAX);
BOOST_CHECK_EQUAL(rect.GetHeight(), UINT_MAX);
rect.SetBottom(0);
rect.SetHeight(UINT_MAX);
BOOST_CHECK_EQUAL(rect.GetHeight(), UINT_MAX);
}
//// properties overflow
BOOST_AUTO_TEST_CASE(RightOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.SetLeft(-23451);
rect.SetWidth(static_cast<unsigned>(23451) + INT_MAX);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
rect.SetWidth(static_cast<unsigned>(23451) + INT_MAX + 1);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(BottomOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.SetTop(-23451);
rect.SetHeight(static_cast<unsigned>(23451) + INT_MAX);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
rect.SetHeight(static_cast<unsigned>(23451) + INT_MAX + 1);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(PerimeterOverflow)
{
CRectangle rect(0, 0, 0, 0);
// max value
rect.SetLeft(INT_MIN);
rect.SetWidth(INT_MAX - 1000);
rect.SetHeight(1000);
BOOST_CHECK_EQUAL(*rect.GetPerimeter(), UINT_MAX - 1);
// overflow
rect.SetLeft(INT_MIN);
rect.SetWidth(INT_MAX - 999);
rect.SetHeight(1000);
BOOST_CHECK(rect.GetPerimeter() == boost::none);
rect.SetWidth(UINT_MAX);
rect.SetHeight(1000);
BOOST_CHECK(rect.GetPerimeter() == boost::none);
}
BOOST_AUTO_TEST_CASE(AreaOverflow)
{
CRectangle rect(0, 0, 0, 0);
// max value
rect.SetLeft(INT_MIN);
rect.SetWidth(UINT_MAX);
rect.SetHeight(1);
BOOST_CHECK_EQUAL(*rect.GetArea(), UINT_MAX);
// oveflow
rect.SetLeft(INT_MIN);
rect.SetWidth(static_cast<unsigned>(INT_MAX) + 1);
rect.SetHeight(2);
BOOST_CHECK(rect.GetArea() == boost::none);
}
// methods
//// move
BOOST_AUTO_TEST_CASE(MoveChangeLeftRight)
{
CRectangle rect(0, 0, 100, 100);
rect.Move(10, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 10);
BOOST_CHECK_EQUAL(rect.GetRight(), 110);
rect.Move(-10, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
BOOST_CHECK_EQUAL(rect.GetRight(), 100);
}
BOOST_AUTO_TEST_CASE(MoveRightOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.Move(100, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 100);
BOOST_CHECK_EQUAL(rect.GetRight(), 100);
// max value after move
rect.Move(INT_MAX, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), INT_MAX);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
// max value before move
rect.Move(1, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), INT_MAX);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(MoveLeftOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.Move(-100, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), -100);
BOOST_CHECK_EQUAL(rect.GetRight(), -100);
// min value after move
rect.Move(INT_MIN, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), INT_MIN);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MIN);
// min value before move
rect.Move(-1, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), INT_MIN);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MIN);
}
BOOST_AUTO_TEST_CASE(MoveChangeTopBottom)
{
CRectangle rect(0, 0, 100, 100);
rect.Move(0, 10);
BOOST_CHECK_EQUAL(rect.GetTop(), 10);
BOOST_CHECK_EQUAL(rect.GetBottom(), 110);
rect.Move(0, -10);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
BOOST_CHECK_EQUAL(rect.GetBottom(), 100);
}
BOOST_AUTO_TEST_CASE(MoveBottomOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.Move(0, 100);
BOOST_CHECK_EQUAL(rect.GetTop(), 100);
BOOST_CHECK_EQUAL(rect.GetBottom(), 100);
// max value after move
rect.Move(0, INT_MAX);
BOOST_CHECK_EQUAL(rect.GetTop(), INT_MAX);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
// max value before move
rect.Move(0, 1);
BOOST_CHECK_EQUAL(rect.GetTop(), INT_MAX);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(MoveTopOverflow)
{
CRectangle rect(0, 0, 0, 0);
rect.Move(0, -100);
BOOST_CHECK_EQUAL(rect.GetTop(), -100);
BOOST_CHECK_EQUAL(rect.GetBottom(), -100);
// min value after move
rect.Move(0, INT_MIN);
BOOST_CHECK_EQUAL(rect.GetTop(), INT_MIN);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MIN);
// min value before move
rect.Move(0, -1);
BOOST_CHECK_EQUAL(rect.GetTop(), INT_MIN);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MIN);
}
BOOST_AUTO_TEST_CASE(MoveChangeLeftRightTopBottom)
{
CRectangle rect(0, 0, 1000, 2000);
rect.Move(100, -100);
BOOST_CHECK_EQUAL(rect.GetLeft(), 100);
BOOST_CHECK_EQUAL(rect.GetRight(), 1100);
BOOST_CHECK_EQUAL(rect.GetTop(), -100);
BOOST_CHECK_EQUAL(rect.GetBottom(), 1900);
}
//// scale
BOOST_AUTO_TEST_CASE(ScaleChangeWidth)
{
CRectangle rect(0, 0, 100, 100);
rect.Scale(2, 1);
BOOST_CHECK_EQUAL(rect.GetWidth(), 200);
rect.Scale(100, 1);
BOOST_CHECK_EQUAL(rect.GetWidth(), 20000);
rect.Scale(0, 1);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
}
BOOST_AUTO_TEST_CASE(ScaleWidthOverflow)
{
CRectangle rect(-2000, 0, 1, 100);
// out of Right bound
rect.Scale(INT_MAX, 1);
rect.Scale(2, 1);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
// out of Width bound
rect.Scale(2, 1);
BOOST_CHECK_EQUAL(rect.GetRight(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(ScaleChangeHeight)
{
CRectangle rect(0, 0, 100, 100);
rect.Scale(1, 2);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 200);
rect.Scale(1, 100);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 20000);
}
BOOST_AUTO_TEST_CASE(ScaleHeightOverflow)
{
CRectangle rect(0, -2000, 100, 1);
// out of Bottom bound
rect.Scale(1, INT_MAX);
rect.Scale(1, 2);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
// out of Height bound
rect.Scale(1, 2);
BOOST_CHECK_EQUAL(rect.GetBottom(), INT_MAX);
}
BOOST_AUTO_TEST_CASE(ScaleChangeWidhtHeight)
{
CRectangle rect(0, 0, 100, 200);
rect.Scale(2, 3);
BOOST_CHECK_EQUAL(rect.GetWidth(), 200);
BOOST_CHECK_EQUAL(rect.GetHeight(), 600);
}
BOOST_AUTO_TEST_CASE(ScaleNotChangeLeftTop)
{
CRectangle rect(0, 0, 100, 100);
rect.Scale(10, 2);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
rect.Scale(0, 0);
BOOST_CHECK_EQUAL(rect.GetLeft(), 0);
BOOST_CHECK_EQUAL(rect.GetTop(), 0);
}
BOOST_AUTO_TEST_CASE(ScaleNotAlwaysChangeWidthHeight)
{
CRectangle rect(0, 0, 100, 100);
// scale by 1, 1
rect.Scale(1, 1);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 100);
// scale by negative number
rect.Scale(5, -10);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 100);
rect.Scale(-5, 10);
BOOST_CHECK_EQUAL(rect.GetWidth(), 100);
BOOST_CHECK_EQUAL(rect.GetHeight(), 100);
// scale zero dimensions rect
rect.SetWidth(0);
rect.SetHeight(0);
rect.Scale(2, 10);
BOOST_CHECK_EQUAL(rect.GetWidth(), 0);
BOOST_CHECK_EQUAL(rect.GetHeight(), 0);
}
//// intersect
////// main properties
BOOST_AUTO_TEST_CASE(IntersectionReturnTrue)
{
CRectangle rect(10, 20, 100, 100);
BOOST_CHECK_EQUAL(rect.Intersect(rect), true);
}
BOOST_AUTO_TEST_CASE(NoIntersectionReturnFalse)
{
CRectangle rect1(10, 20, 100, 100);
CRectangle rect2(1000, 2000, 100, 100);
BOOST_CHECK_EQUAL(rect1.Intersect(rect2), false);
}
BOOST_AUTO_TEST_CASE(NoIntersectionNoMove)
{
CRectangle rect1(10, 20, 100, 100);
CRectangle rect2(1000, 2000, 100, 100);
BOOST_REQUIRE_EQUAL(rect1.Intersect(rect2), false);
BOOST_CHECK_EQUAL(rect1.GetLeft(), 10);
BOOST_CHECK_EQUAL(rect1.GetTop(), 20);
}
BOOST_AUTO_TEST_CASE(NoIntersectionSet0WidthHeight)
{
CRectangle rect1(10, 20, 100, 100);
CRectangle rect2(1000, 2000, 100, 100);
BOOST_REQUIRE_EQUAL(rect1.Intersect(rect2), false);
BOOST_CHECK_EQUAL(rect1.GetWidth(), 0);
BOOST_CHECK_EQUAL(rect1.GetHeight(), 0);
}
////// rects collocations
//////// no intersection
void CheckNoIntersectionWithStandardRect(CRectangle const &rect2)
{
CRectangle rect1(0, 0, 100, 100);
BOOST_CHECK_EQUAL(rect1.Intersect(rect2), false);
}
BOOST_AUTO_TEST_CASE(NoIntersectWithDistanceRect2Upper)
{
CheckNoIntersectionWithStandardRect({ 0, -300, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectWithDistanceRect2Lower)
{
CheckNoIntersectionWithStandardRect({ 0, 300, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectWithDistanceRect2Right)
{
CheckNoIntersectionWithStandardRect({ 300, 0, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectWithDistanceRect2Left)
{
CheckNoIntersectionWithStandardRect({ -300, 0, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectCloseRect2Upper)
{
CheckNoIntersectionWithStandardRect({ 0, -100, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectCloseRect2Lower)
{
CheckNoIntersectionWithStandardRect({ 0, 100, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectCloseRect2Right)
{
CheckNoIntersectionWithStandardRect({ 100, 0, 100, 100 });
}
BOOST_AUTO_TEST_CASE(NoIntersectCloseRect2Left)
{
CheckNoIntersectionWithStandardRect({ -100, 0, 100, 100 });
}
//////// intersect OX projection
BOOST_AUTO_TEST_CASE(XIntersectRect2Inside)
{
CheckNoIntersectionWithStandardRect({ 0, 300, 50, 100 });
}
BOOST_AUTO_TEST_CASE(XIntersectRect2OutSide)
{
CheckNoIntersectionWithStandardRect({ -50, 300, 200, 100 });
}
BOOST_AUTO_TEST_CASE(XIntersectRect2Left)
{
CheckNoIntersectionWithStandardRect({ -50, 300, 100, 100 });
}
BOOST_AUTO_TEST_CASE(XIntersectRect2Right)
{
CheckNoIntersectionWithStandardRect({ 50, 300, 200, 100 });
}
//////// intersect OY projection
BOOST_AUTO_TEST_CASE(YIntersectRect2Inside)
{
CheckNoIntersectionWithStandardRect({ 300, 20, 100, 50 });
}
BOOST_AUTO_TEST_CASE(YIntersectRect2OutSide)
{
CheckNoIntersectionWithStandardRect({ 300, -50, 100, 200 });
}
BOOST_AUTO_TEST_CASE(YIntersectRect2Upper)
{
CheckNoIntersectionWithStandardRect({ 300, -50, 100, 100 });
}
BOOST_AUTO_TEST_CASE(YIntersectRect2Lower)
{
CheckNoIntersectionWithStandardRect({ 300, 50, 100, 100 });
}
//////// real intersection
////////// rect 2 upper
void CheckIntersectionWithStandardRect(CRectangle const &rect2, CRectangle const &expectedResult)
{
CRectangle rect1(0, 0, 100, 100);
BOOST_CHECK_EQUAL(rect1.Intersect(rect2), true);
BOOST_CHECK_EQUAL(rect1.GetLeft(), expectedResult.GetLeft());
BOOST_CHECK_EQUAL(rect1.GetTop(), expectedResult.GetTop());
BOOST_CHECK_EQUAL(rect1.GetWidth(), expectedResult.GetWidth());
BOOST_CHECK_EQUAL(rect1.GetHeight(), expectedResult.GetHeight());
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperLeft)
{
CheckIntersectionWithStandardRect({ -50, -50, 100, 100 }, { 0, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperRight)
{
CheckIntersectionWithStandardRect({ 50, -50, 100, 100 }, { 50, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperInside)
{
CheckIntersectionWithStandardRect({ 20, -50, 50, 100 }, { 20, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperOutside)
{
CheckIntersectionWithStandardRect({ -50, -50, 200, 100 }, { 0, 0, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, -50, 200, 100 }, { 0, 0, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2UpperCloseRight)
{
CheckIntersectionWithStandardRect({ 50, -50, 50, 100 }, { 50, 0, 50, 50 });
}
////////// rect 2 lower
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerLeft)
{
CheckIntersectionWithStandardRect({ -50, 50, 100, 100 }, { 0, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerRight)
{
CheckIntersectionWithStandardRect({ 50, 50, 100, 100 }, { 50, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerInside)
{
CheckIntersectionWithStandardRect({ 20, 50, 50, 100 }, { 20, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerOutside)
{
CheckIntersectionWithStandardRect({ -50, 50, 200, 100 }, { 0, 50, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, 50, 200, 100 }, { 0, 50, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2LowerCloseRight)
{
CheckIntersectionWithStandardRect({ 50, 50, 50, 100 }, { 50, 50, 50, 50 });
}
////////// rect 2 inside
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideLeft)
{
CheckIntersectionWithStandardRect({ -50, 20, 100, 50 }, { 0, 20, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideRight)
{
CheckIntersectionWithStandardRect({ 50, 20, 100, 50 }, { 50, 20, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideInside)
{
CheckIntersectionWithStandardRect({ 20, 20, 50, 50 }, { 20, 20, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideOutside)
{
CheckIntersectionWithStandardRect({ -50, 20, 200, 50 }, { 0, 20, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, 20, 200, 50 }, { 0, 20, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2InsideCloseRight)
{
CheckIntersectionWithStandardRect({ 50, 20, 50, 50 }, { 50, 20, 50, 50 });
}
////////// rect 2 outside
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideLeft)
{
CheckIntersectionWithStandardRect({ -50, -50, 100, 200 }, { 0, 0, 50, 100 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideRight)
{
CheckIntersectionWithStandardRect({ 50, -50, 100, 200 }, { 50, 0, 50, 100 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideInside)
{
CheckIntersectionWithStandardRect({ 20, -50, 50, 200 }, { 20, 0, 50, 100 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideOutside)
{
CheckIntersectionWithStandardRect({ -50, -50, 200, 200 }, { 0, 0, 100, 100 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, -50, 200, 200 }, { 0, 0, 100, 100 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2OutsideCloseRight)
{
CheckIntersectionWithStandardRect({ 50, -50, 50, 200 }, { 50, 0, 50, 100 });
}
////////// rect 2 close top
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopLeft)
{
CheckIntersectionWithStandardRect({ -50, 0, 100, 50 }, { 0, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopRight)
{
CheckIntersectionWithStandardRect({ 50, 0, 100, 50 }, { 50, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopInside)
{
CheckIntersectionWithStandardRect({ 20, 0, 50, 50 }, { 20, 0, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopOutside)
{
CheckIntersectionWithStandardRect({ -50, 0, 200, 50 }, { 0, 0, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, 0, 200, 50 }, { 0, 0, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseTopCloseRight)
{
CheckIntersectionWithStandardRect({ 50, 0, 50, 50 }, { 50, 0, 50, 50 });
}
////////// rect 2 close bottom
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomLeft)
{
CheckIntersectionWithStandardRect({ -50, 50, 100, 50 }, { 0, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomRight)
{
CheckIntersectionWithStandardRect({ 50, 50, 100, 50 }, { 50, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomInside)
{
CheckIntersectionWithStandardRect({ 20, 50, 50, 50 }, { 20, 50, 50, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomOutside)
{
CheckIntersectionWithStandardRect({ -50, 50, 200, 50 }, { 0, 50, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomCloseLeft)
{
CheckIntersectionWithStandardRect({ 0, 50, 200, 50 }, { 0, 50, 100, 50 });
}
BOOST_AUTO_TEST_CASE(RealIntersectRect2CloseBottomCloseRight)
{
CheckIntersectionWithStandardRect({ 50, 50, 50, 50 }, { 50, 50, 50, 50 });
}
BOOST_AUTO_TEST_SUITE_END()
| true |
6fde46a536ea34dd83008591c0bf66210d365f08 | C++ | ototsuyume/poj-solution | /3041.cpp | UTF-8 | 782 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
bool g[510][510],used[510];
int result[510],n,m;
bool augument(int x){
for(int i=0;i<n;++i){
if(!g[x][i]||used[i])continue;
used[i]=true;
if(result[i]==-1||augument(result[i])){
result[i]=x;
return true;
}
}
return false;
}
int solve(){
int ans=0;
memset(result,-1,sizeof(result));
for(int i=0;i<n;++i){
memset(used,0,sizeof(used));
if(augument(i))
++ans;
}
return ans;
}
int main(){
while(cin>>n>>m){
memset(g,0,sizeof(g));
for(int i=0;i<m;++i){
int x,y;
cin>>x>>y;
g[x-1][y-1]=true;
}
cout<<solve()<<endl;
}
return 0;
}
| true |
28c30f92bef2abbb076b7f78e59e798da68f7fd4 | C++ | paulinho-16/MIEIC-PROG | /Ficha 1/Exercício2/Exercício2.9/Exercício2.9/main.cpp | UTF-8 | 2,174 | 3.5625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
char alinea;
cout << "Enter the alinea you want to do: ";
cin >> alinea;
switch (alinea)
{
case 'a':
{
int soma = 0 , minimo = 99999999 , maximo = -99999999 , comprimento = 0 , valor = 1;
double media;
while (valor != 0)
{
cout << "Enter an integer number (0 to end): ";
cin >> valor;
if (valor == 0)
{
cout << "End of sequence." << endl;
break;
}
soma += valor;
if (valor < minimo)
minimo = valor;
if (valor > maximo)
maximo = valor;
comprimento++;
}
media = static_cast<double>(soma) / comprimento;
cout << "The sum of the " << comprimento << " entered numbers is " << soma << ", the minimum is " << minimo << ", the maximum is " << maximo << ", and the mean is " << media << endl;
break;
}
case 'b':
{
int comprimento, soma = 0, minimo = 99999999, maximo = -99999999, valor;
double media;
cout << "Enter the length of the sequence: ";
cin >> comprimento;
for (int i = 1; i <= comprimento; i++)
{
cout << "Enter an integer number: ";
cin >> valor;
soma += valor;
if (valor < minimo)
minimo = valor;
if (valor > maximo)
maximo = valor;
}
media = static_cast<double>(soma) / comprimento;
cout << "The sum of the " << comprimento << " entered numbers is " << soma << ", the minimum is " << minimo << ", the maximum is " << maximo << ", and the mean is " << media << endl;
break;
}
case 'c':
{
int comprimento = 0 , soma = 0, minimo = 99999999, maximo = -99999999, valor;
double media;
while (true)
{
cout << "Enter an integer number (Ctrl + Z to end): ";
cin >> valor;
if (cin.fail())
if (cin.eof())
break;
soma += valor;
if (valor < minimo)
minimo = valor;
if (valor > maximo)
maximo = valor;
comprimento++;
}
media = static_cast<double>(soma) / comprimento;
cout << "The sum of the " << comprimento << " entered numbers is " << soma << ", the minimum is " << minimo << ", the maximum is " << maximo << ", and the mean is " << media << endl;
break;
}
}
system("pause");
return 0;
} | true |
685dad8e3c93f1cb3ddecb6bc79e9f73d72cf6bf | C++ | iCodeIN/leetcode-4 | /PrintWordsVertically.cpp | UTF-8 | 1,288 | 2.890625 | 3 | [] | no_license | class Solution {
public:
vector<string> printVertically(string s) {
int i,len=s.length(),maxlen=0,len1,j;
vector<string>words;
string temp="";
for(i=0;i<len;i++)
{
if(s[i]!=' ')
temp=temp+s[i];
else if(s[i]==' ')
{
if(temp!="")
{
words.push_back(temp);
if(maxlen<temp.length())
maxlen=temp.length();
}
temp="";
}
}
if(temp!="")
{
words.push_back(temp);
if(maxlen<temp.length())
maxlen=temp.length();
}
temp="";
vector<string>res(maxlen);
len=words.size();
for(i=0;i<len;i++)
{
temp=words[i];
len1=temp.length();
for(j=0;j<len1;j++)
{
res[j]=res[j]+temp[j];
}
for(;j<maxlen;j++)
res[j]=res[j]+" ";
}
for(i=0;i<maxlen;i++)
{
temp=res[i];
len1=temp.length();
for(j=len1-1;(j>=0 && temp[j]==' ');j--);
res[i]=temp.substr(0,j+1);
}
return res;
}
};
| true |
9f16adb30f7988a02581b8eecaa5773c48f0de46 | C++ | KamikazeChan/Contest | /CodeLib/Geometry/POJ 3168 Barn Expansion.cpp | UTF-8 | 2,259 | 2.96875 | 3 | [] | no_license | /*
** POJ 3168 Barn Expansion
** Created by Rayn @@ 2014/04/01
*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define MAX 25005
using namespace std;
struct wall{
int id, pos;
int beg, end;
wall(int id=0, int beg=0, int end=0, int pos=0):
id(id), beg(beg), end(end), pos(pos) {}
bool operator < (const wall &a) const {
if(pos == a.pos)
return beg < a.beg;
return pos < a.pos;
};
};
wall vert[MAX*2], hori[MAX*2], tmp[MAX*2];
int sign[MAX];
void Solve(wall *arr, int n)
{
int i, j, k;
for(i=0 ; i<n; i=j)
{
for(j=i; j<n; ++j)
{
if(arr[i].pos != arr[j].pos)
break;
}
int ed = arr[i].end;
for(k=i+1; k<j; ++k)
{
if(arr[k].beg <= ed)
{
sign[arr[k].id] = 1;
sign[arr[k-1].id] = 1;
}
ed = max(ed, arr[k].end);
}
}
}
int main()
{
#ifdef _Rayn
freopen("in.txt", "r", stdin);
#endif
int n, a, b, c, d;
scanf("%d", &n);
for(int i=0; i<n; ++i)
{
scanf("%d%d%d%d", &a, &b, &c, &d);
vert[i*2] = wall(i, b, d, a);
vert[i*2+1] = wall(i, b, d, c);
hori[i*2] = wall(i, a, c, b);
hori[i*2+1] = wall(i, a, c, d);
}
/*test for input
printf(" id pos beg end\n");
for(int i=0; i<n*2; ++i)
printf("%2d%4d%4d%4d\n",vert[i].id, vert[i].pos, vert[i].beg, vert[i].end);
printf("----------------\n");
for(int i=0; i<n*2; ++i)
printf("%2d%4d%4d%4d\n",hori[i].id, hori[i].pos, hori[i].beg, hori[i].end);
//*/
sort(vert, vert + n*2);
sort(hori, hori + n*2);
/*test for sort
printf(" id pos beg end\n");
for(int i=0; i<n*2; ++i)
printf("%2d%4d%4d%4d\n",vert[i].id, vert[i].pos, vert[i].beg, vert[i].end);
printf("----------------\n");
for(int i=0; i<n*2; ++i)
printf("%2d%4d%4d%4d\n",hori[i].id, hori[i].pos, hori[i].beg, hori[i].end);
//*/
memset(sign, 0, sizeof(sign));
Solve(vert, n*2);
Solve(hori, n*2);
int ans = 0;
for(int i=0; i<n; ++i)
{
if(sign[i] == 0)
ans++;
}
printf("%d\n", ans);
return 0;
}
| true |
7ba07aaf630827f0e92dc23058928588a0bf8eb1 | C++ | jinbooooom/coding-for-algorithms | /function/int2str.cpp | UTF-8 | 341 | 3 | 3 | [
"MIT"
] | permissive | void int2str(int n, char *str)
{
int num = n > 0 ? n : -n;
if (str == nullptr)
return;
char buf[10] = " ";
int i = 0, j = 0;
while(num)
{
buf[i++] = num % 10 + '0';
num /= 10;
}
int len = n > 0 ? i : ++i;
str[len] = '\0';
if (n < 0)
{
j = 1;
str[0] = '-';
}
for (; j < len; ++j)
{
str[j] = buf[len - 1 - j];
}
} | true |
bb6231cde3e757466cee54b4160dd06f61fe4731 | C++ | Crawping/JE | /JE/Engine/Common/MathHelper.h | UTF-8 | 10,452 | 2.890625 | 3 | [] | no_license | //***************************************************************************************
// MathHelper.h by Frank Luna (C) 2011 All Rights Reserved.
//
// Helper math class.
//***************************************************************************************
#ifndef MATHHELPER_H
#define MATHHELPER_H
#include <Windows.h>
//#include <xnamath.h>
#include <DirectXMath.h>
#include <cmath>
using namespace DirectX;
XMFLOAT3 operator+ (const XMFLOAT3& val1, const XMFLOAT3& val2);
XMFLOAT3 operator- (const XMFLOAT3& val1, const XMFLOAT3& val2);
XMFLOAT3 operator* (const XMFLOAT3& val1, const XMFLOAT3& val2);
XMFLOAT3 operator* (const FLOAT& val1, const XMFLOAT3& val2);
XMFLOAT3 operator* (const XMFLOAT3& val1, const FLOAT& val2);
XMFLOAT3 operator/ (const XMFLOAT3& val1, const FLOAT& val2);
static const XMVECTOR g_UnitQuaternionEpsilon =
{
1.0e-4f, 1.0e-4f, 1.0e-4f, 1.0e-4f
};
static const XMVECTOR g_UnitVectorEpsilon =
{
1.0e-4f, 1.0e-4f, 1.0e-4f, 1.0e-4f
};
static const XMVECTOR g_UnitPlaneEpsilon =
{
1.0e-4f, 1.0e-4f, 1.0e-4f, 1.0e-4f
};
class MathHelper
{
public:
// Returns random float in [0, 1).
static float RandF()
{
return (float)(rand()) / (float)RAND_MAX;
}
// Returns random float in [a, b).
static float RandF(float a, float b)
{
return a + RandF()*(b-a);
}
//(degree->radian)
static float ConvertToRadians(float fDegrees)
{
return fDegrees * (XM_PI / 180.0f);
}
//(radian->degree)
static float ConvertToDegrees(float fRadians)
{
return fRadians * (180.0f / XM_PI);
}
template<typename T>
static T Min(const T& a, const T& b)
{
return a < b ? a : b;
}
template<typename T>
static T Max(const T& a, const T& b)
{
return a > b ? a : b;
}
template<typename T>
static T Lerp(const T& a, const T& b, float t)
{
return a + (b-a)*t;
}
template<typename T>
static T Clamp(const T& x, const T& low, const T& high)
{
return x < low ? low : (x > high ? high : x);
}
// Returns the polar angle of the point (x,y) in [0, 2*PI).
static float AngleFromXY(float x, float y);
static XMFLOAT3 XMFLOAT3_CROSS(XMFLOAT3 F1, XMFLOAT3 F2)
{
return XMFLOAT3(
(F1.y * F2.z) - (F1.z * F2.y),
(F1.z * F2.x) - (F1.x * F2.z),
(F1.x * F2.y) - (F1.y * F2.x));
}
static float XMFLOAT3_DOT(XMFLOAT3 F1, XMFLOAT3 F2)
{
return float((F1.x * F2.x) + (F1.y * F2.y) + (F1.z * F2.z));
}
static XMFLOAT3 XMFLOAT3_NORMALIZE(XMFLOAT3 F1)
{
float length = sqrt((F1.x*F1.x) + (F1.y * F1.y) + (F1.z * F1.z));
if (length != 0.0f)
{
return XMFLOAT3(F1.x / length, F1.y / length, F1.z / length);
}
return F1;
}
static XMFLOAT3 XMVECTOR_TO_XMFLOAT3(XMVECTOR vector)
{
XMFLOAT3 fvalue;
XMStoreFloat3(&fvalue, vector);
return fvalue;
}
static XMFLOAT4 XMVECTOR_TO_XMFLOAT4(XMVECTOR vector)
{
XMFLOAT4 fvalue;
XMStoreFloat4(&fvalue, vector);
return fvalue;
}
static XMVECTOR XMFLOAT3_TO_XMVECTOR(XMFLOAT3 fvalue, float w)
{
XMVECTOR vector;
return vector = XMLoadFloat4(&XMFLOAT4(fvalue.x, fvalue.y, fvalue.z, w));
}
static XMFLOAT4 XMFLOAT4_MUL_XMFLOAT4X4(XMFLOAT4 fvalue1, XMFLOAT4X4 fvalue2)
{
XMFLOAT4 result;
result.x = fvalue1.x*fvalue2._11 + fvalue1.y*fvalue2._21 + fvalue1.z*fvalue2._31 + fvalue1.w*fvalue2._41;
result.y = fvalue1.x*fvalue2._12 + fvalue1.y*fvalue2._22 + fvalue1.z*fvalue2._32 + fvalue1.w*fvalue2._42;
result.z = fvalue1.x*fvalue2._13 + fvalue1.y*fvalue2._23 + fvalue1.z*fvalue2._33 + fvalue1.w*fvalue2._43;
result.w = fvalue1.x*fvalue2._14 + fvalue1.y*fvalue2._24 + fvalue1.z*fvalue2._34 + fvalue1.w*fvalue2._44;
return result;
}
static XMFLOAT4 XMFLOAT4_MUL_XMFLOAT4X4(XMFLOAT3 fvalue, XMFLOAT4X4 fvalue2)
{
XMFLOAT4 fvalue1 = XMFLOAT4(fvalue.x, fvalue.y, fvalue.z, 1.0f);
XMFLOAT4 result;
result.x = fvalue1.x*fvalue2._11 + fvalue1.y*fvalue2._21 + fvalue1.z*fvalue2._31 + fvalue1.w*fvalue2._41;
result.y = fvalue1.x*fvalue2._12 + fvalue1.y*fvalue2._22 + fvalue1.z*fvalue2._32 + fvalue1.w*fvalue2._42;
result.z = fvalue1.x*fvalue2._13 + fvalue1.y*fvalue2._23 + fvalue1.z*fvalue2._33 + fvalue1.w*fvalue2._43;
result.w = fvalue1.x*fvalue2._14 + fvalue1.y*fvalue2._24 + fvalue1.z*fvalue2._34 + fvalue1.w*fvalue2._44;
return result;
}
static XMFLOAT3 XMFLOAT3_MUL_SCALAR(XMFLOAT3 fvalue, float scalar)
{
return XMFLOAT3(fvalue.x*scalar, fvalue.y*scalar, fvalue.z*scalar);
}
static XMFLOAT4 XMFLOAT3_TO_XMFLOAT4(XMFLOAT3 fvalue, float w)
{
return XMFLOAT4(fvalue.x, fvalue.y, fvalue.z, w);
}
static XMFLOAT3 XMFLOAT4_TO_XMFLOAT3(XMFLOAT4 fvalue)
{
return XMFLOAT3(fvalue.x, fvalue.y, fvalue.z);
}
static XMFLOAT4 XMFLOAT4_DIV_W(XMFLOAT4 fvalue1)
{
fvalue1.x = fvalue1.x / fvalue1.w;
fvalue1.y = fvalue1.y / fvalue1.w;
fvalue1.z = fvalue1.z / fvalue1.w;
fvalue1.w = 1.0f;
return fvalue1;
}
static FLOAT Distance(XMFLOAT3 fvalue1, XMFLOAT3 fvalue2)
{
fvalue1.x = fvalue1.x - fvalue2.x;
fvalue1.x = fvalue1.x*fvalue1.x;
fvalue1.y = fvalue1.y - fvalue2.y;
fvalue1.y = fvalue1.y*fvalue1.y;
fvalue1.z = fvalue1.z - fvalue2.z;
fvalue1.z = fvalue1.z*fvalue1.z;
return sqrt(fvalue1.x + fvalue1.y + fvalue1.z);
}
static XMFLOAT3 QuateriontoEuler(XMFLOAT4 q1) {
XMFLOAT3 Euler;
float test = q1.x*q1.y + q1.z*q1.w;
if (test > 0.499f) { // singularity at north pole
Euler.y = 2.0f * atan2(q1.x, q1.w);
Euler.z = XM_PI / 2.0f;
Euler.x = 0;
return Euler;
}
if (test < -0.499) { // singularity at south pole
Euler.y = -2 * atan2(q1.x, q1.w);
Euler.z = -XM_PI / 2.0f;
Euler.x = 0;
return Euler;
}
float sqx = q1.x*q1.x;
float sqy = q1.y*q1.y;
float sqz = q1.z*q1.z;
Euler.y = atan2(2.0f * q1.y*q1.w - 2.0f * q1.x*q1.z, 1.0f - 2.0f * sqy - 2.0f * sqz);
Euler.z = asin(2.0f * test);
Euler.x = atan2(2.0f * q1.x*q1.w - 2.0f * q1.y*q1.z, 1.0f - 2.0f * sqx - 2.0f * sqz);
return Euler;
}
static void RemoveFloatError(XMFLOAT4X4 *fvalue1)
{
if (abs(fvalue1->_11) < 0.0000001f) fvalue1->_11 = 0.0f;
if (abs(fvalue1->_12) < 0.0000001f) fvalue1->_12 = 0.0f;
if (abs(fvalue1->_13) < 0.0000001f) fvalue1->_13 = 0.0f;
if (abs(fvalue1->_14) < 0.0000001f) fvalue1->_14 = 0.0f;
if (abs(fvalue1->_21) < 0.0000001f) fvalue1->_21 = 0.0f;
if (abs(fvalue1->_22) < 0.0000001f) fvalue1->_22 = 0.0f;
if (abs(fvalue1->_23) < 0.0000001f) fvalue1->_23 = 0.0f;
if (abs(fvalue1->_24) < 0.0000001f) fvalue1->_24 = 0.0f;
if (abs(fvalue1->_31) < 0.0000001f) fvalue1->_31 = 0.0f;
if (abs(fvalue1->_32) < 0.0000001f) fvalue1->_32 = 0.0f;
if (abs(fvalue1->_33) < 0.0000001f) fvalue1->_33 = 0.0f;
if (abs(fvalue1->_34) < 0.0000001f) fvalue1->_34 = 0.0f;
if (abs(fvalue1->_41) < 0.0000001f) fvalue1->_41 = 0.0f;
if (abs(fvalue1->_42) < 0.0000001f) fvalue1->_42 = 0.0f;
if (abs(fvalue1->_43) < 0.0000001f) fvalue1->_43 = 0.0f;
if (abs(fvalue1->_44) < 0.0000001f) fvalue1->_44 = 0.0f;
}
static XMMATRIX InverseTranspose(CXMMATRIX M)
{
// Inverse-transpose is just applied to normals. So zero out
// translation row so that it doesn't get into our inverse-transpose
// calculation--we don't want the inverse-transpose of the translation.
XMMATRIX A = M;
A.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
XMVECTOR det = XMMatrixDeterminant(A);
return XMMatrixTranspose(XMMatrixInverse(&det, A));
}
static XMMATRIX Inverse(CXMMATRIX M)
{
//XMMATRIX A = M;
//A.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
XMVECTOR det = XMMatrixDeterminant(M);
return XMMatrixInverse(&det, M);
}
static XMVECTOR RandUnitVec3();
static XMVECTOR RandHemisphereUnitVec3(XMVECTOR n);
static const float Infinity;
static const float Pi;
//-----------------------------------------------------------------------------
// Return TRUE if the vector is a unit vector (length == 1).
//-----------------------------------------------------------------------------
static inline BOOL XMVector3IsUnit(FXMVECTOR V)
{
XMVECTOR Difference = XMVector3Length(V) - XMVectorSplatOne();
return XMVector4Less(XMVectorAbs(Difference), g_UnitVectorEpsilon);
}
static BOOL IntersectRayTriangle(FXMVECTOR Origin, FXMVECTOR Direction, FXMVECTOR V0, CXMVECTOR V1, CXMVECTOR V2,
FLOAT* pDist)
{
assert(pDist);
assert(XMVector3IsUnit(Direction));
static const XMVECTOR Epsilon =
{
1e-20f, 1e-20f, 1e-20f, 1e-20f
};
XMVECTOR Zero = XMVectorZero();
XMVECTOR e1 = V1 - V0;
XMVECTOR e2 = V2 - V0;
// p = Direction ^ e2;
XMVECTOR p = XMVector3Cross(Direction, e2);
// det = e1 * p;
XMVECTOR det = XMVector3Dot(e1, p);
XMVECTOR u, v, t;
if (XMVector3GreaterOrEqual(det, Epsilon))
{
// Determinate is positive (front side of the triangle).
XMVECTOR s = Origin - V0;
// u = s * p;
u = XMVector3Dot(s, p);
XMVECTOR NoIntersection = XMVectorLess(u, Zero);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorGreater(u, det));
// q = s ^ e1;
XMVECTOR q = XMVector3Cross(s, e1);
// v = Direction * q;
v = XMVector3Dot(Direction, q);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorLess(v, Zero));
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorGreater(u + v, det));
// t = e2 * q;
t = XMVector3Dot(e2, q);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorLess(t, Zero));
if (XMVector4EqualInt(NoIntersection, XMVectorTrueInt()))
return FALSE;
}
else if (XMVector3LessOrEqual(det, -Epsilon))
{
// Determinate is negative (back side of the triangle).
XMVECTOR s = Origin - V0;
// u = s * p;
u = XMVector3Dot(s, p);
XMVECTOR NoIntersection = XMVectorGreater(u, Zero);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorLess(u, det));
// q = s ^ e1;
XMVECTOR q = XMVector3Cross(s, e1);
// v = Direction * q;
v = XMVector3Dot(Direction, q);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorGreater(v, Zero));
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorLess(u + v, det));
// t = e2 * q;
t = XMVector3Dot(e2, q);
NoIntersection = XMVectorOrInt(NoIntersection, XMVectorGreater(t, Zero));
if (XMVector4EqualInt(NoIntersection, XMVectorTrueInt()))
return FALSE;
}
else
{
// Parallel ray.
return FALSE;
}
XMVECTOR inv_det = XMVectorReciprocal(det);
t *= inv_det;
// u * inv_det and v * inv_det are the barycentric cooridinates of the intersection.
// Store the x-component to *pDist
XMStoreFloat(pDist, t);
return TRUE;
}
};
#endif // MATHHELPER_H | true |
2fb59f56aada0bb8a31a4e5daf5e9deada147f08 | C++ | linhphan98/C-_DataStructure | /Stack/infixToPosfix.cpp | UTF-8 | 4,417 | 4.09375 | 4 | [] | no_license | // order of operation
// 1) Parentheses() {} []
// 2) Exponents (right to left)
// 3) Multiplication and division (left to right)
// 4) Addition and subtraction (left to right)
// infix prefix postfix
// 2+3 +2 3 2 3 +
// p-q -p q p q -
// a+b*c +a *b c abc * +
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
string InfixToPostfix(string expression);
int HasHigherPrecedence(char top, char current);
bool IsOperator(char C);
bool IsOperand(char C);
int main(void){
string expression;
cout << "Enter Infix Expression" << endl;
cin >> expression;
string postfix = InfixToPostfix(expression);
cout << "Output = " << postfix << endl;
return 0;
};
string InfixToPostfix(string expression){
stack<char> S;
string postfix = "";
for(int i = 0; i < expression.length(); i++){
// if character is a space or , move on
if(expression[i] == ' ' || expression[i] == ',') continue;
// if character is operator, pop two elements from the stack, perform the operation and push the result
else if(IsOperator(expression[i])){
// stop when the stack is empty or '(' is the next one in stack or the top has higher priority than the current (* > +)
// then pop everything out until '(' or empty or same priority or current is higher
while(!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(), expression[i])){
postfix += S.top();
S.pop();
}
S.push(expression[i]);
}
// else if character is an operand
else if(IsOperand(expression[i])){
postfix += expression[i];
}else if (expression[i] == '('){
S.push(expression[i]);
}else if(expression[i] == ')'){
while(!S.empty() && S.top() != '('){
postfix += S.top();
S.pop();
}
S.pop();
}
}
while(!S.empty()){
postfix += S.top();
S.pop();
}
return postfix;
};
// Verifying whether a character is english letter or numeric digit
bool IsOperand(char C){
if(C >= '0' && C <= '9') return true;
if(C >= 'a' && C <= 'z') return true;
if(C >= 'A' && C <= 'Z') return true;
return false;
};
// Function to verify whether a character is operator symbol or not
bool IsOperator(char C){
if((C == '+') || (C == '-') || (C == '/') || (C == '*') || (C == '$'))
return true;
return false;
};
// Function to verify whether an operator is right associative or not
int IsRightAssociative(char op){
if(op == '$') return true;
return false;
};
// Function to get weight of an operator. An operator with higher weight will have higher priorities
int GetOperatorWeight(char op){
int weight = -1;
switch(op){
case '+':
case '-':
weight = 1;
break;
case '/':
case '*':
weight = 2;
break;
case '$':
weight = 3;
break;
}
return weight;
};
// Function to perform an operation and return output
int HasHigherPrecedence(char top, char current){
int op1Weight = GetOperatorWeight(top);
int op2Weight = GetOperatorWeight(current);
// if operators have equal weight, return true if they are left associative
// return false, if right associative because we are check the top of the stack and current character in the string
// equal weight, the inside the stack should have priority
if(op1Weight == op2Weight){
// IsRightAssociative, I think, always returns false so the function will always return false if they have equal weight
if(IsRightAssociative(top)) return false;
else return true;
}
return op1Weight > op2Weight ? true: false;
}
// Implement this method when there is two number like 12 14 22 as an operand
// else if(IsNumericDigit(expression[i])){
// // Extract the numeric operand from the string
// // Keep incrementing i as long as you are getting a numeric digit.
// int operand = 0;
// while(i<expression.length() && IsNumericDigit(expression[i])) {
// // For a number with more than one digits, as we are scanning from left to right.
// // Everytime , we get a digit towards right, we can multiply current total in operand by 10
// // and add the new digit.
// operand = (operand*10) + (expression[i] - '0');
// i++;
// }
// // Finally, you will come out of while loop with i set to a non-numeric character or end of string
// // decrement i because it will be incremented in increment section of loop once again.
// // We do not want to skip the non-numeric character by incrementing i twice.
// i--;
// // Push operand on stack.
// S.push(operand);
// }
| true |
eb3b08e077336f2d47eed4cf42b0021776a961e9 | C++ | RyanHealy11/practice | /Project4/Source.cpp | UTF-8 | 2,693 | 3.046875 | 3 | [] | no_license | #include <iostream>
int main()
{
/*
int input1 = -1;
std::cout << "Give me a number between 1 and 100 " << std::endl;
std::cin >> input1;
if (input1 < 50)
{
std::cout << "That is a small number" << std::endl;
}
else if (input1 == 50)
{
std::cout << "your number is a balenced number" << std::endl;
}
else
{
std::cout << "That is a large number" << std::endl;
}
*/
/*
int age = -1;
std::cout << "What is your age? " << std::endl;
std::cin >> age;
if (age >= 65)
{
std::cout << "you are eligable for retierment benifits!!!!!!!" << std::endl;
}
else if (age >= 50)
{
std::cout << "you are eligable to join AARP" << std::endl;
}
else if (age >= 18)
{
std::cout << "you are now an adult have fun adulting" << std::endl;
}
else
{
std::cout << "leave this pub now minor " << std::endl;
}
*/
/*
int num1 = -1;
int num2 = -1;
int num3 = -1;
std::cout << "Good sir please give me 3 random numbers" << std::endl;
std::cin >> num1;
std::cin >> num2;
std::cin >> num3;
if ((num1 < num2) and (num1 < num3))
{
std::cout << num1 << std::endl;
}
else if ((num2 < num1) and (num2 < num3))
{
std::cout << num2 << std::endl;
}
else if ((num3 < num1) and (num2 > num3))
{
std::cout << num3 << std::endl;
}
*/
/*
int num = -1;
std::cout << "give me a number " << std::endl;
std::cin >> num;
num = (num % 2);
std::cout << num << std::endl;
if(num == 1)
{
std::cout << "your number is odd" << std::endl;
}
else if(num == 0)
{
std::cout << "your number is even" << std::endl;
}
*/
/*
int clamp = -1;
std::cout << "give me a number " << std::endl;
std::cin >> clamp;
if (clamp < 15)
{
clamp = 15;
std::cout << clamp << std::endl;
}
else if (clamp > 30)
{
clamp = 30;
std::cout << clamp << std::endl;
}
else
{
std::cout << clamp << std::endl;
}
*/
int userscore = 0;
int dinoscore = 0;
int dinostrength = 4;
int userstrength = -1;
int dinopaper = 1;
int userpaper = -1;
int dinobattle = 2;
int userbattle = -1;
std::cout << "How would you rate your strength from 1 to 10?" << std::endl;
std::cin >> userstrength;
if (dinostrength > userstrength)
{
dinoscore++;
}
else if (userstrength > dinostrength)
{
userscore++;
}
std::cout << "which of the following did you take into battle? (1 Rock, 2 Paper, 3 Scissors)" << std::endl;
std::cout << "how many battles have you fought" << std::endl;
std::cin >> userbattle;
if (dinobattle > userbattle)
{
dinoscore++;
}
else if (dinobattle < userbattle)
{
userscore++;
}
std::cout << "Did you get enough sleep?" << std::endl;
std::cout << "How muc Vitamin C do you get everyday?" << std::endl;
return 0;
} | true |
0fb6375abbc2cf17cd2a4fe0ad6c5dc6de8820d0 | C++ | dustin-biser/FluidSim | /external/Synergy/include/Synergy/Graphics/ShaderException.hpp | UTF-8 | 505 | 2.78125 | 3 | [] | no_license | /**
* ShaderException
*/
#pragma once
#include <exception>
#include <string>
namespace Synergy {
using std::string;
class ShaderException : public std::exception {
public:
ShaderException(const string & message)
: errorMessage(message) { }
virtual ~ShaderException() noexcept { }
virtual const char * what() const noexcept {
return errorMessage.c_str();
}
private:
string errorMessage;
};
} // end namespace Synergy
| true |
7a6a7f65566e9b0eac000c88361f2e96d33964e6 | C++ | tonyskjellum/TEPPP | /main/wr_mpi.cpp | UTF-8 | 1,275 | 2.5625 | 3 | [] | no_license | #include "../include/funcs.h"
#include "mpi.h"
using namespace std;
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int num_chains = stoi(argv[3]);
int chain_length = stoi(argv[2]);
int chunk = num_chains / size;
int num;
double **coords = read_coords(argv[1], &num);
double result[chunk];
string fname = to_string(chain_length) + "wrmpiout" + to_string(rank) + ".txt";
ofstream outfile;
outfile.open(fname);
for (int i = rank * chunk; i < (rank + 1) * chunk; i++) {
double **chain1 = new double*[chain_length];
for (int j = 0; j < chain_length; j++) {
chain1[j] = new double[3];
chain1[j][0] = coords[j + (i * chain_length)][0];
chain1[j][1] = coords[j + (i * chain_length)][1];
chain1[j][2] = coords[j + (i * chain_length)][2];
}
double res = wr(chain1, chain_length, false);
outfile << "writhe of chain " << i << ": " << res << "\n";
result[i-(rank*chunk)] = res;
delete_array(chain1, chain_length);
}
delete_array(coords, num_chains);
outfile.close();
MPI_Finalize();
return 0;
} | true |
37cd69f0f3470e1c73a7a5dbb8e3835433a6ea4d | C++ | RizkyKhapidsyah/SK-Lib-cmath-sqrt-Bagian6__CPP | /SK-Lib-cmath-sqrt-Bagian6__CPP/Source.cpp | UTF-8 | 357 | 2.53125 | 3 | [] | no_license | #include <cmath>
#include <iomanip>
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
long long int val1 = 1000000000000000000;
long long int val2 = 999999999999999999;
cout << fixed << setprecision(12) << sqrt(val1) << endl;
cout << fixed << setprecision(12) << sqrt(val2) << endl;
_getch();
return (0);
} | true |
9cf1c9b82003e647eaa25ccd67b3e93d4d34d08b | C++ | edouarda/boost_processes | /boost/processes/scheduler.hpp | UTF-8 | 4,310 | 2.625 | 3 | [] | no_license |
#pragma once
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/thread/mutex.hpp>
namespace boost
{
namespace processes
{
namespace detail
{
template <typename Platform>
class scheduler : public boost::noncopyable
{
private:
typedef boost::container::flat_set<information> processes_set;
typedef scheduler<Platform> this_type;
public:
boost::system::error_code spawn(command_line cmdline, information & info)
{
return spawn(cmdline, input_output(), info);
}
boost::system::error_code spawn(command_line cmdline, input_output io, information & info)
{
info = information(cmdline, io);
boost::system::error_code ec = _platform.run(info);
if (!ec)
{
boost::unique_lock<boost::mutex> lock(_mutex);
// if we have a previous entry with the same id, close it
// nota bene, this is a bug and should never happen
processes_set::iterator it = _processes.find(info);
if (it != _processes.end())
{
_platform.close(it->id);
_processes.erase(it);
}
assert(_processes.find(info) == _processes.end());
_processes.insert(info);
}
return ec;
}
public:
boost::system::error_code terminate(identifier id)
{
boost::system::error_code ec = _platform.terminate(id);
if (!ec)
{
close_process(id);
}
return ec;
}
void terminate_all(void)
{
processes_set copy;
{
// work on a copy to make sure we don't have any deadlock
boost::unique_lock<boost::mutex> lock(_mutex);
copy = _processes;
}
for(processes_set::const_iterator it = copy.begin(); it != copy.end(); ++it)
{
// terminate will remove the entry from _processes
terminate(it->id);
}
}
public:
bool process_info(identifier id, information & info) const
{
bool found = false;
boost::unique_lock<boost::mutex> lock(_mutex);
processes_set::const_iterator it = _processes.find(id.pid);
if (it != _processes.end())
{
info = *it;
found = true;
}
return found;
}
private:
void close_process(const identifier & id)
{
_platform.close(id);
boost::unique_lock<boost::mutex> lock(_mutex);
_processes.erase(id.pid);
}
private:
bool gc_process(const identifier & id)
{
if (_platform.running(id))
{
// process is alive, nothing to do
return false;
}
close_process(id);
return true;
}
public:
bool running(identifier id)
{
return running(id.pid);
}
bool running(pid_type p)
{
boost::unique_lock<boost::mutex> lock(_mutex);
processes_set::const_iterator it = _processes.find(p);
if (it == _processes.end())
{
return false;
}
identifier id = it->id;
lock.unlock();
// attempt to garbage collect the pid, if we can it means it exited
return !gc_process(id);
}
bool any_running(void)
{
processes_set to_gc;
bool result = false;
{
boost::unique_lock<boost::mutex> lock(_mutex);
// in C++ 11 this would be a one-liner :'(
for(processes_set::const_iterator it = _processes.begin(); it != _processes.end(); ++it)
{
if (_platform.running(it->id))
{
result = true;
}
else
{
to_gc.insert(*it);
}
}
}
// let's gc what we found to be no longer running
for(processes_set::const_iterator it = to_gc.begin(); it != to_gc.end(); ++it)
{
gc_process(it->id);
}
return result;
}
public:
// I like spin locks. Don't you?
// the thing is that it's possible on some systems to get a signal when a child exits, while on some others it's not possible
// for now we spin everywhere and will specialize later
void wait(void)
{
while (any_running())
{
boost::this_thread::yield();
}
}
void wait(const identifier & id)
{
while(running(id))
{
boost::this_thread::yield();
}
}
public:
Platform _platform;
mutable boost::mutex _mutex;
processes_set _processes;
};
}
}
}
| true |
9e16209061c125b719ba7d67213427a4bba8a02d | C++ | sudeshpawar008/QtOpenGL | /OpenGL/openglspotlight.cpp | UTF-8 | 879 | 2.96875 | 3 | [] | no_license | #include "openglspotlight.h"
#include <KMath>
OpenGLSpotLight::OpenGLSpotLight() :
m_depth(20.0f)
{
setInnerAngle(15.0f);
setOuterAngle(30.0f);
}
float OpenGLSpotLight::CalculateScalar(int segments)
{
float segArcLength = Karma::Pi / segments;
float yAxisLength = Karma::sec(segArcLength);
return std::abs(yAxisLength);
}
void OpenGLSpotLight::setInnerAngle(float angle)
{
angle /= 2.0f;
float rads = Karma::DegreesToRads(angle);
m_innerAngle = std::cos(rads);
}
void OpenGLSpotLight::setOuterAngle(float angle)
{
angle /= 2.0f;
float rads = Karma::DegreesToRads(angle);
m_outerAngle = std::cos(rads);
m_angleOfInfluence = rads;
}
void OpenGLSpotLight::setDepth(float d)
{
float dz = d * std::tan(m_angleOfInfluence) * CalculateScalar(32);
m_depth = d;
m_transform.setScaleX(dz);
m_transform.setScaleY(dz);
m_transform.setScaleZ(d);
}
| true |
5c516a4e43fa1ce2ac170325d9164fdeb88c36fe | C++ | WhiZTiM/coliru | /Archive2/d6/fb1901dd868be3/main.cpp | UTF-8 | 246 | 2.671875 | 3 | [] | no_license | struct A
{
const A& operator=(const A&){ return A(); }
};
struct B : A
{
const B& operator=(const B&){ return B(); } //What does that function have to do with the function defined in another class (in our case it's A)?
};
int main(){ } | true |
802429337a386afa2cac1ede93ca582444291b30 | C++ | LuuuuuG/MyLeetCode | /Source/232_Implement Queue using Stacks.cpp | UTF-8 | 1,699 | 4.125 | 4 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
/*
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
1.You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
2.Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
3.You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
232. Implement Queue using Stacks: https://leetcode.com/problems/implement-queue-using-stacks/discuss/64206/Short-O(1)-amortized-C++-Java-Ruby
*/
class MyQueue {
stack<int> input, output;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int tmp = peek();
output.pop();
return tmp;
}
/** Get the front element. */
int peek() {
if (output.empty()){
while (input.size())
output.push(input.top()), input.pop();
}
return output.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.empty();
}
}; | true |
475805475f5b6167a0b60ba6fcb01dd8f6a83f47 | C++ | justinmichaud/raytracer | /Main.cpp | UTF-8 | 6,798 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <vector>
#include "Vector.h"
class Camera {
public:
Vec pos = Vec(0,0,0);
Vec up = Vec(0,1,0);
Vec right = Vec(1,0,0);
Vec forward = Vec(0,0,1);
float f = 1;
};
class Sphere {
public:
Vec pos = Vec(0,0,0);
float radius = 0.5;
Vec colour = Vec(1,1,1);
float reflect=0.5;
bool light = false;
Sphere() {}
Sphere(Vec pos, float radius): pos{pos}, radius{radius} {}
Sphere(Vec pos, float radius, Vec colour, bool light):
pos{pos}, radius{radius}, colour{colour}, light{light} {}
Sphere(Vec pos, float radius, Vec colour, float reflect):
pos{pos}, radius{radius}, colour{colour}, reflect{reflect} {}
Vec collision(const Vec& origin, const Vec& direction) const {
float solution = this->solution(origin, direction);
if (solution < 0) return Vec::INFINITE;
return (direction*solution) + origin;
}
Vec objectSpace(Vec x) const {
return x - pos;
}
bool operator ==(const Sphere &b) const {
return this->pos==b.pos && this->radius==b.radius && this->colour==b.colour
&& this->reflect==b.reflect && this->light==b.light;
}
bool operator !=(const Sphere &b) const {
return !(*this==b);
}
friend std::ostream& operator <<(std::ostream& strm, const Sphere& a) {
return strm << "Sphere(" << a.pos << "," << a.radius << ")";
}
private:
float solution(const Vec& o, const Vec& l) const {
//Solve for line-sphere intersection:
// https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
float desc = (l*(o-this->pos))*(l*(o-this->pos))
- (~(o-this->pos))*(~(o-this->pos)) + (this->radius*this->radius);
if (desc < 0) return -1;
desc = sqrt(desc);
float t1 = -(l*(o-this->pos)) + desc;
float t2 = -(l*(o-this->pos)) - desc;
//Discard negative or zero solutions
if (t1 <= 0) t1 = t2;
if (t2 <= 0) t2 = t1;
if (t1 <= 0 && t2 <= 0) return -1;
//Return smallest possible solution
if (t2 <= t1) return t2;
else return t1;
}
};
Vec background(const Vec& pos, const Vec& dir) {
//Find intersection with ground plane
//https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection
float groundPlaneY = 1;
Vec p0(0,groundPlaneY, 0);
Vec n(0,1,0);
float d = (p0 - pos)*n/(dir*n);
Vec intersectionPlane = dir*d;
if (d < 0) intersectionPlane = Vec::INFINITE;
//Find intersection with skysphere
const Sphere backgroundSphere = Sphere(pos, 50);
Vec intersectionSphere = backgroundSphere.collision(pos, dir);
if (intersectionPlane.isinf() && intersectionSphere.isinf()) return Vec(0,0,0);
if (intersectionPlane.isinf() || intersectionSphere.y < groundPlaneY) {
//Determine the sky gradient
Vec obj = backgroundSphere.objectSpace(intersectionSphere)/backgroundSphere.radius;
float h = (-obj.y+1.0)/2.0;
return Vec(h*0.3 + 0.3, h*0.4 + 0.4, h*0.7 + 0.5);
}
else {
//Checkerboard
float scale = 2;
if ((int((intersectionPlane.x+100)*scale)%2==0
|| int((intersectionPlane.z+100)*scale)%2==0)
&& !(int((intersectionPlane.x+100)*scale)%2==0 && int((intersectionPlane.z+100)*scale)%2==0)) return Vec(1,0.1,0.1);
else return Vec(1,1,1);
}
}
const Sphere& traceRay(const Vec& pos, const Vec& dir, const std::vector<Sphere>& world) {
Vec intersection = Vec::INFINITE;
const Sphere* sphere = &world[0];
for (const Sphere& s : world) {
Vec sol = s.collision(pos, dir);
if (sol.isinf()) continue;
if (~(sol - pos) <= ~(intersection - pos)) {
intersection = sol;
sphere = &s;
}
}
return *sphere;
}
Vec sample(Vec pos, Vec dir, const std::vector<Sphere>& world, int recursiveCount) {
if (recursiveCount >= 5) return Vec(0,0,0);
const Sphere& sphere = traceRay(pos, dir, world);
Vec intersection = sphere.collision(pos, dir);
if (intersection.isinf()) return background(pos, dir);
if (sphere.light) return sphere.colour;
Vec normal = !sphere.objectSpace(intersection);
//Fix aliasing when some values are inside the sphere due to rounding
intersection += normal*0.0001;
Vec reflectedDirection = dir + (-2*normal*(normal*dir));
Vec reflectedSample = sample(intersection,
reflectedDirection, world, recursiveCount+1);
//look for lights
Vec lighting = Vec(0,0,0);
for (const Sphere& light : world) {
if (!light.light) continue;
Vec lightDir = !(light.pos - intersection);
const Sphere& closestObject = traceRay(intersection, lightDir, world);
if (closestObject != light) continue; //We are in shaddow of another object
if (light.collision(intersection, lightDir).isinf()) continue; //This is not a real intersection
//the object is illuminated by this light, so use cosine shading
float shading = lightDir*normal;
if (shading < 0) continue;
lighting += light.colour*shading;
}
return 0.5*Vec(sphere.colour.x*lighting.x, sphere.colour.y*lighting.y, sphere.colour.z*lighting.z)
+ sphere.reflect*Vec(sphere.colour.x*reflectedSample.x, sphere.colour.y*reflectedSample.y, sphere.colour.z*reflectedSample.z);
}
int main() {
Camera camera;
camera.pos = Vec(0,0,-2);
std::vector<Sphere> world = {
Sphere(Vec(-1.1,-1.1,0), 0.01, Vec(1,1,1), true),
};
float name[5][5] = {
{1,1,1,1,1},
{0,0,1,0,0},
{0,0,1,0,0},
{1,0,1,0,0},
{1,1,1,0,0},
};
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
if (name[j][i]) world.push_back(Sphere(Vec((i-2)*0.15,(j-2)*0.15,0), 0.1, Vec(1,1,1), 0.7f));
}
}
//Netppm image
int width = 500;
int height = 500;
std::cout << "P3 " << width << " " << height << " 255";
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
float normX = (x/(float) width) - 0.5;
float normY = (y/(float) height) - 0.5;
Vec dir = !Vec(normX, normY, camera.f);
Vec color = (255.0*sample(camera.pos, dir, world, 0)).clamp(0,255.0);
//Convert form [0.0, 1.0] to [0, 255]
std::cout
<< " " << int(color.x)
<< " " << int(color.y)
<< " " << int(color.z);
}
}
return 0;
}
| true |
6be74a3d5cdb1ad7d99ee82d8e08fbe960a84987 | C++ | josephding23/DataAnalysis | /adams2.cpp | UTF-8 | 1,998 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
const int N = 1000;
double Func(double x, double y) {
return y - 2 * x / y;
}
double Solve(double x) {
return sqrt(1 + 2 * x);
}
int main() {
double x0, y0, K1, K2, K3, K4, h, yp, Yp;
double x[N], y[N], Y[N];
int N, n = 4;
cout << "Function: y' = y - 2 * x / y" << endl
<< "Exact solve: y = sqrt(1 + 2 * x)" << endl << endl;
cout << "x0 = ";
cin >> x0;
cout << "y0 = ";
cin >> y0;
cout << "h = ";
cin >> h;
cout << "N = ";
cin >> N;
for(int n = 0; n <= 3; n++) {
x[n] = x0 + h;
K1 = Func(x0, y0);
K2 = Func(x0 + h / 2, y0 + h * K1 / 2);
K3 = Func(x0 + h / 2, y0 + h * K2 / 2);
K4 = Func(x[n], y0 + h * K3);
y[n] = y0 + h * (K1 + 2 * K2 + 2 * K3 + K4) / 6;
Y[n] = Func(x[n], y[n]);
x0 = x[n];
y0 = y[n];
cout << "x" << left << setw(2) << n << " = " << left << setw(12) << x[n] <<
" " <<
"y" << left << setw(2) << n << " = " << left << setw(12) << y[n] <<
"y(x" << left << setw(1) << n << ") = " << left << setw(12) << Solve(x[n]) << endl;
}
for(int n = 4; n <= N; n++) {
x[4] = x[3] + h;
yp = y[3] + h * (55 * Y[3] - 59 * Y[2] + 37 * Y[1] - 9 * Y[0]) / 24;
Yp = Func(x[4], yp);
y[4] = y[3] + h * (9 * Yp + 19 * Y[3] - 5 * Y[2] + Y[1]) / 24;
Y[4] = Func(x[4], y[4]);
cout << "x" << left << setw(2) << n << " = " << left << setw(12) << x[4] <<
"y*" << left << setw(2) << n << " = " << left << setw(12) << yp <<
"y" << left << setw(2) << n << " = " << left << setw(12) << y[4] <<
"y(x" << left << setw(1) << n << ") = " << left << setw(12) << Solve(x[4]) << endl;
x[3] = x[4];
y[3] = y[4];
for(int i = 0; i < 4; i++) {
Y[i] = Y[i + 1];
}
}
return 0;
}
| true |
59429e4c12a3552f0dbbd10a2e99655d3db9ef35 | C++ | mradziwilko/NSCC2019 | /Semester 3/C++/Assignment 2/project.cpp | UTF-8 | 8,374 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//movie struct definition
struct movie {
string name;
string director;
int year;
float rating;
float price;
int views;
int renter;
string dueDate;
};
void addMovie(vector<movie>& movies);
void browseMovies(vector<movie>& movies);
void changeMovie(vector <movie>& mymovies);
void deleteMovie(vector <movie>& mymovies);
void sort(vector <movie>& mymovies);
void searchMovie(vector <movie>& mymovies);
float calculateEarnings(std::vector <movie>& mymovies);
void exitProgram();
void showMainMenu();
int main () {
vector <movie> mymovies;
int choice = 0;
int ch;
FILE *p_file;
float total = 0.00;
choice = 0;
while (choice != 9)
{
showMainMenu();
cin >> choice;
//scanf("%d", &choice);
//int ch;
//while ((ch = getchar()) != '\n' && ch != EOF);
//call function for different options
switch(choice)
{
case 1: addMovie(mymovies); break;
case 2: browseMovies(mymovies); break;
case 3: changeMovie(mymovies); break;
case 4: deleteMovie(mymovies); break;
case 5: sort(mymovies); break;
case 6: searchMovie(mymovies); break;
case 7: total = calculateEarnings(mymovies); printf("\nStore has earned $%.2f\n", total); break;
case 8: exitProgram(); break;
default: cout << "\nError. Choice not found.";
}
}
return 0;
}
void addMovie(vector<movie>& movies) {
// Get Constructor for newMovie.
movie newMovie;
// Fill out Infomration of the movie
cout << "Enter Movie Name: ";
cin >> newMovie.name;
cout << "Enter Movie Director: ";
cin >> newMovie.director;
cout << "Enter Movie year: ";
cin >> newMovie.year;
cout << "Enter Movie Rating: ";
cin >> newMovie.rating;
cout << "Enter Movie Price: ";
cin >> newMovie.price;
cout << "Enter Movie Views: ";
cin >> newMovie.views;
cout << "Enter Movie Renter: ";
cin >> newMovie.renter;
cout << "Enter Movie Date Due: ";
cin >> newMovie.dueDate;
// Add Movie to main Vector.
movies.push_back(newMovie);
}
void browseMovies(vector<movie>& movies) {
//Input variable for choice.
string input;
// Go though the whole vector printing out its contents
for (auto element = movies.cbegin(); element != movies.cend(); ++element) {
cout << "Movie Name: " << element->name << endl;
cout << "Director: " << element->director << endl;
cout << "Year: " << element->year << endl;
cout << "Rating: " << element->rating << endl;
cout << "Price: " << element->price << endl;
cout << "# of Views: " << element->views << endl;
cout << "Renter: " << element->renter << endl;
cout << "Due Date: " << element->dueDate << endl;
// Ask to Continue or go back to main menu.
cout << "(C)ontinue or (B)ack to menu? " << endl;
cin >> input;
// if B or B, go back to main menu, if C or c go to next entry.
if(input == "B" || input == "b") {
break;
}else if(input == "C" || input == "c") {
// Dont break.
} else{
break;
}
}
cout << endl;
}
void changeMovie(vector <movie>& movies) {
// Get Input variables.
string input;
// Set Edit Vector
movie editMovie;
// Count to check where you are in the vector.
int count = 0;
// Ask what movie to edit.
cout << "Search for movie: " << endl;
cin >> input;
for (auto element = movies.cbegin(); element != movies.cend(); ++element) {
// If Element matches input, edit, if not Add to count go to next entry.
if(element->name == input) {
cout << "Enter Movie Name: (" << element->name << "): ";
cin >> editMovie.name;
cout << "Enter Movie Director: (" << element->director << "): ";
cin >> editMovie.director;
cout << "Enter Movie year: (" << element->year << "): ";
cin >> editMovie.year;
cout << "Enter Movie Rating: (" << element->rating << "): ";
cin >> editMovie.rating;
cout << "Enter Movie Price: (" << element->price << "): ";
cin >> editMovie.price;
cout << "Enter Movie Views: (" << element->views << "): ";
cin >> editMovie.views;
cout << "Enter Movie Renter: (" << element->renter << "): ";
cin >> editMovie.renter;
cout << "Enter Movie Date Due: (" << element->dueDate << "): ";
cin >> editMovie.dueDate;
// Erase the Entry at current spot, then add new entry into that spot.
movies.erase(movies.begin() + count);
movies.insert(movies.begin() +count , editMovie);
// Print exit notice
cout << "Movie Edited, Press anykey to go back.";
cin.ignore();
cin.get();
break;
}
count++;
}
cout << endl;
}
void deleteMovie(vector <movie>& movies) {
string input;
int count = 0;
int newcount = 0;
cout << "Remove movie: " << endl;
cin >> input;
for (auto element = movies.cbegin(); element != movies.cend(); ++element) {
count = 1;
if(element->name == input) {
movies.erase(movies.begin() + count);
cout << "Press anykey to go back.";
cout << endl;
cin.ignore();
cin.get();
break;
}
count++;
}
}
// Sort Container by name function
bool sortByName(const movie &lhs, const movie &rhs) { return lhs.name < rhs.name; }
void sort(vector <movie>& movies) {
string input;
// Sort by name and then display. (Using custom Sort by name function.)
sort(movies.begin(), movies.end(), sortByName);
browseMovies(movies);
}
void searchMovie(vector <movie>& movies) {
// Get Input
string input;
cout << "Search for movie: " << endl;
cin >> input;
// Go though loop on vector untill Name = Input
for (auto element = movies.cbegin(); element != movies.cend(); ++element) {
// If Found, Print result, if not found Print message and go bakc to main menu.
if(element->name == input) {
cout << "Movie Name: " << element->name << endl;
cout << "Director: " << element->director << endl;
cout << "Year: " << element->year << endl;
cout << "Rating: " << element->rating << endl;
cout << "Price: " << element->price << endl;
cout << "# of Views: " << element->views << endl;
cout << "Renter: " << element->renter << endl;
cout << "Due Date: " << element->dueDate << endl;
cout << "Press anykey to go back.";
cin.ignore();
cin.get();
}else{
cout << "No Movie found by the name: " << input << endl;
cout << "Press anykey to go back.";
cin.ignore();
cin.get();
}
}
cout << endl;
}
float calculateEarnings(vector <movie>& movies) {
// Number to add to decliration
float numberAdded = 0.0;
// Go though the Vector, Multiply price by # of views and add to number added.
for (auto element = movies.cbegin(); element != movies.cend(); ++element) {
float temp = element->price * element->views;
numberAdded = numberAdded + temp;
}
// Return Number added after complete.
return numberAdded;
}
void showMainMenu() {
// Fixed Darrens Number Mixup after removing couple entries and spelled "Calculate" properly
puts("\nPlease choose an option:");
puts("1. Add new entry");
puts("2. Browse entries");
puts("3. Modify existing entry ");
puts("4. Delete entry");
puts("5. Sort entries");
puts("6. Search for entry");
puts("7. Calculate total");
puts("8. Exit");
}
void exitProgram() {
} | true |
3308635bd85687428ba12393fa974235cd03ab48 | C++ | marco-c/gecko-dev-comments-removed | /third_party/libwebrtc/third_party/abseil-cpp/absl/random/poisson_distribution.h | UTF-8 | 5,611 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Apache-2.0"
] | permissive |
#ifndef ABSL_RANDOM_POISSON_DISTRIBUTION_H_
#define ABSL_RANDOM_POISSON_DISTRIBUTION_H_
#include <cassert>
#include <cmath>
#include <istream>
#include <limits>
#include <ostream>
#include <type_traits>
#include "absl/random/internal/fast_uniform_bits.h"
#include "absl/random/internal/fastmath.h"
#include "absl/random/internal/generate_real.h"
#include "absl/random/internal/iostream_state_saver.h"
#include "absl/random/internal/traits.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
template <typename IntType = int>
class poisson_distribution {
public:
using result_type = IntType;
class param_type {
public:
using distribution_type = poisson_distribution;
explicit param_type(double mean = 1.0);
double mean() const { return mean_; }
friend bool operator==(const param_type& a, const param_type& b) {
return a.mean_ == b.mean_;
}
friend bool operator!=(const param_type& a, const param_type& b) {
return !(a == b);
}
private:
friend class poisson_distribution;
double mean_;
double emu_;
double lmu_;
double s_;
double log_k_;
int split_;
static_assert(random_internal::IsIntegral<IntType>::value,
"Class-template absl::poisson_distribution<> must be "
"parameterized using an integral type.");
};
poisson_distribution() : poisson_distribution(1.0) {}
explicit poisson_distribution(double mean) : param_(mean) {}
explicit poisson_distribution(const param_type& p) : param_(p) {}
void reset() {}
template <typename URBG>
result_type operator()(URBG& g) {
return (*this)(g, param_);
}
template <typename URBG>
result_type operator()(URBG& g,
const param_type& p);
param_type param() const { return param_; }
void param(const param_type& p) { param_ = p; }
result_type(min)() const { return 0; }
result_type(max)() const { return (std::numeric_limits<result_type>::max)(); }
double mean() const { return param_.mean(); }
friend bool operator==(const poisson_distribution& a,
const poisson_distribution& b) {
return a.param_ == b.param_;
}
friend bool operator!=(const poisson_distribution& a,
const poisson_distribution& b) {
return a.param_ != b.param_;
}
private:
param_type param_;
random_internal::FastUniformBits<uint64_t> fast_u64_;
};
template <typename IntType>
poisson_distribution<IntType>::param_type::param_type(double mean)
: mean_(mean), split_(0) {
assert(mean >= 0);
assert(mean <=
static_cast<double>((std::numeric_limits<result_type>::max)()));
assert(mean <= 1e10);
if (mean_ < 10) {
split_ = 1;
emu_ = std::exp(-mean_);
} else if (mean_ <= 50) {
split_ = 1 + static_cast<int>(mean_ / 10.0);
emu_ = std::exp(-mean_ / static_cast<double>(split_));
} else {
constexpr double k2E = 0.7357588823428846;
constexpr double kSA = 0.4494580810294493;
lmu_ = std::log(mean_);
double a = mean_ + 0.5;
s_ = kSA + std::sqrt(k2E * a);
const double mode = std::ceil(mean_) - 1;
log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode);
}
}
template <typename IntType>
template <typename URBG>
typename poisson_distribution<IntType>::result_type
poisson_distribution<IntType>::operator()(
URBG& g,
const param_type& p) {
using random_internal::GeneratePositiveTag;
using random_internal::GenerateRealFromBits;
using random_internal::GenerateSignedTag;
if (p.split_ != 0) {
result_type n = 0;
for (int split = p.split_; split > 0; --split) {
double r = 1.0;
do {
r *= GenerateRealFromBits<double, GeneratePositiveTag, true>(
fast_u64_(g));
++n;
} while (r > p.emu_);
--n;
}
return n;
}
const double a = p.mean_ + 0.5;
for (;;) {
const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>(
fast_u64_(g));
const double v = GenerateRealFromBits<double, GenerateSignedTag, false>(
fast_u64_(g));
const double x = std::floor(p.s_ * v / u + a);
if (x < 0) continue;
const double rhs = x * p.lmu_;
double s = (x <= 1.0) ? 0.0
: (x == 2.0) ? 0.693147180559945
: absl::random_internal::StirlingLogFactorial(x);
const double lhs = 2.0 * std::log(u) + p.log_k_ + s;
if (lhs < rhs) {
return x > static_cast<double>((max)())
? (max)()
: static_cast<result_type>(x);
}
}
}
template <typename CharT, typename Traits, typename IntType>
std::basic_ostream<CharT, Traits>& operator<<(
std::basic_ostream<CharT, Traits>& os,
const poisson_distribution<IntType>& x) {
auto saver = random_internal::make_ostream_state_saver(os);
os.precision(random_internal::stream_precision_helper<double>::kPrecision);
os << x.mean();
return os;
}
template <typename CharT, typename Traits, typename IntType>
std::basic_istream<CharT, Traits>& operator>>(
std::basic_istream<CharT, Traits>& is,
poisson_distribution<IntType>& x) {
using param_type = typename poisson_distribution<IntType>::param_type;
auto saver = random_internal::make_istream_state_saver(is);
double mean = random_internal::read_floating_point<double>(is);
if (!is.fail()) {
x.param(param_type(mean));
}
return is;
}
ABSL_NAMESPACE_END
}
#endif
| true |
af8e65dfbc1c550486c68f6e38e40a033ef12d76 | C++ | seuczk/cpp-primer | /chapter3/3_19.cpp | UTF-8 | 284 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec1(10, 42);
vector<int> ivec2{42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
vector<int> ivec3;
for (int i=0; i < 10; ++i)
ivec3.push_back(42);
//Obviously, the first is the best!
return 0;
}
| true |