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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
439197f57fc991acd02c37a1e2f90cfedd1037b7 | C++ | sandmn/point_offer | /point_offer/Quit_repeat_in_order_array.cpp | UTF-8 | 583 | 3.5 | 4 | [] | no_license | #include<iostream>
using namespace std;
//有序数组进行去重
int Quit_Repeat(int arr[],int n)
{
if(arr == NULL || n <= 1)
{
return n;
}
int i = 0;
int index = 0;
for(i = 1;i < n;i++)
{
if(arr[index] != arr[i])
{
arr[++index] = arr[i];
}
}
return index + 1;
}
int main()
{
int arr[] = {1,2,2,2,3,4,4,6};
int n = sizeof(arr)/sizeof(arr[0]);
int ret = Quit_Repeat(arr,n);
int i = 0;
for(i = 0;i < ret;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
35ac873abca21bdb5e61f8ddc1770f9e14f5e4d2 | C++ | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut | /src/homework/tic_tac_toe/tic_tac_toe_data.cpp | UTF-8 | 1,129 | 3.234375 | 3 | [
"MIT"
] | permissive | #include "tic_tac_toe.h"
#include "tic_tac_toe_data.h"
#include "tic_tac_toe_3.h"
#include "tic_tac_toe_4.h"
//cpp
void TicTacToeData::save_games(const vector<unique_ptr<TicTacToe>>& games)
{
ofstream file_out(file_name, ios_base::trunc);
for (auto& game : games)
{
for (auto peg : game->get_pegs())
{
file_out << peg;
}
file_out << game->get_winner();
file_out << "\n";
}
file_out.close();
}
vector<unique_ptr<TicTacToe>> TicTacToeData::get_games()
{
vector<unique_ptr<TicTacToe>> games;
ifstream read_file(file_name);
//vector<string> pegs;
//string line;
if (read_file.is_open())
{
vector<string> pegs;
string line;
while (getline(read_file, line))
{
for (int i{ 0 }; i < line.size() - 1; i++)
{
string chstr(1, line[i]);
pegs.push_back(chstr);
}
string winner = pegs[-1];
unique_ptr<TicTacToe>game;
if (pegs.size() == 9)
{
game = make_unique<TicTacToe3>(pegs, winner);
}
else if (pegs.size() == 16)
{
game = make_unique<TicTacToe4>(pegs, winner);
}
games.push_back(move(game));
}
read_file.close();
}
return games;
}
| true |
aa1520cf19e2d02476a7b03e59d9a999d25f5e11 | C++ | Johnny-Martin/toys | /Test/Test/Test.cpp | GB18030 | 15,764 | 2.890625 | 3 | [] | no_license | // Test.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include "Test.h"
#include <map>
#include<cctype>
#include<iostream>
#include <sstream>
#include <fstream>
#include<map>
#include<stack>
#include<string>
#include <regex>
using namespace std;
enum Token_value {
NAME, NUMBER, END, PLUS = '+', MINUS = '-', MUL = '*', DIV = '/', PRINT = ';', ASSIGN = '=', LP = '(', RP = ')'
};
Token_value curr_tok = PRINT;
map<string, double> table;
double number_value;
string string_value;
int no_of_errors;
double expr(bool get);
double term(bool get);
double prim(bool get);
Token_value get_token();
double error(const string& s)
{
no_of_errors++;
cerr << "error:" << s << endl;
return 1;
}
Token_value get_token()
{
char ch = 0;
cin >> ch;
switch (ch) {
case 0:
return curr_tok = END;
case ';':case '*':case '/':case '+':case '-':case '(':case ')':case '=':
return curr_tok = Token_value(ch);
case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':case '.':
cin.putback(ch);
cin >> number_value;
return curr_tok = NUMBER;
default:
if (isalpha(ch)) {
cin.putback(ch);
cin >> string_value;
return curr_tok = NAME;
}
error("bad token");
return curr_tok = PRINT;
}
}
double prim(bool get)
{
if (get) get_token();
switch (curr_tok) {
case NUMBER:
{ double v = number_value;
get_token();
return v;
}
case NAME:
{ double& v = table[string_value];
if (get_token() == ASSIGN) v = expr(true);
return v;
}
case MINUS:
return -prim(true);
case LP:
{ double e = expr(true);
if (curr_tok != RP) return error(") expected");
get_token();
return e;
}
default:
return error("primary expected");
}
}
double term(bool get)
{
double left = prim(get);
for (;;)
switch (curr_tok) {
case MUL:
left *= prim(true);
break;
case DIV:
if (double d = prim(true)) {
left /= d;
break;
}
return error("divide by 0");
default:
return left;
}
}
double expr(bool get)
{
double left = term(get);
for (;;)
switch (curr_tok) {
case PLUS:
left += term(true);
break;
case MINUS:
left -= term(true);
break;
default:
return left;
}
}
/*
int main()
{
table["pi"] = 3.1415926535897932385;
table["e"] = 2.718284590452354;
while (cin) {
get_token();
if (curr_tok == END) break;
if (curr_tok == PRINT) continue;
cout << expr(false) << endl;
}
return no_of_errors;
}
*/
#define SSEXP "[0-9\\+\\-\\*\\(\\)/\\\s*]*"
#define SSCMD "((#mid)*(#height)*(#width)*)*"
//֧+-/*()ֲ,sExpгֲַ֮
//ָ֧(0-)֧С(÷ʾ)
double TestCalcExp(const string& sExp)
{
if (sExp.empty()) return 0.0;
stack<double> outputStack;
stack<char> operatorStack;
auto IsNumber = [](const char& test) { return test >= '0' && test <= '9'; };
auto PushToOutputStack = [&IsNumber, &outputStack](const string& originalExp, string::size_type begin) {
string::size_type end = begin;
while (end < originalExp.size() && IsNumber(originalExp[end])) { ++end; };
--end;
string strOperand = originalExp.substr(begin, end - begin + 1);
_ASSERT(!strOperand.empty());
int iOperand = atoi(strOperand.c_str());
outputStack.push(iOperand);
//صǰĩβڴеλ
return end;
};
auto StackSafeTop = [](auto& paramStack) {
if (paramStack.empty()) throw false;
return paramStack.top();
};
auto StackSafePop = [](auto& paramStack) {
if (paramStack.empty()) throw false;
paramStack.pop();
};
auto CalcOutputStack = [&](const char& op) {
if (outputStack.size() < 2) {
//ERR("CalcOutputStack error: outputStack size: error.");
throw false;
}
int rightOp = StackSafeTop(outputStack);
StackSafePop(outputStack);
int leftOp = StackSafeTop(outputStack);
StackSafePop(outputStack);
switch (op){
case '+':
outputStack.push(leftOp + rightOp);
break;
case '-':
outputStack.push(leftOp - rightOp);
break;
case '*':
outputStack.push(leftOp * rightOp);
break;
case '/':
//0쳣㲶
outputStack.push(leftOp / rightOp);
break;
//default:8
//ERR("CalcOutputStack error: unsupported operator: {}", op);
//throw false;
}
return true;
};
for (string::size_type i = 0; i < sExp.size(); ++i) {
//ˣѹջ
if (IsNumber(sExp[i])) {
i = PushToOutputStack(sExp, i);
continue;
}
char curOperator = sExp[i];
//*/ţֻҪһַ֣ͿԼԼջ
if (curOperator == '*' || curOperator == '/') {
if (IsNumber(sExp[i + 1])) {
//һҳջȻ
i = PushToOutputStack(sExp, i + 1);
CalcOutputStack(curOperator);
continue;
}
operatorStack.push(curOperator);
}else if (curOperator == '+' || curOperator == '-') {
//+-ţֻҪջա'(', ȼջţٽԼջ
if (operatorStack.empty() || StackSafeTop(operatorStack) == '(') {
operatorStack.push(curOperator);
continue;
}
CalcOutputStack(StackSafeTop(operatorStack));
StackSafePop(operatorStack);
operatorStack.push(curOperator);
}else if (curOperator == '(') {
//,ֱջ
operatorStack.push(sExp[i]);
}else if (curOperator == ')') {
//ߴ㣬ջе()֮һֻһ
CalcOutputStack(StackSafeTop(operatorStack));
StackSafePop(operatorStack);
_ASSERT(StackSafeTop(operatorStack) == '(');
StackSafePop(operatorStack);
}
}
if (!operatorStack.empty()) {
cout << "operatorStack size: " << operatorStack.size() << endl;
CalcOutputStack(StackSafeTop(operatorStack));
StackSafePop(operatorStack);
}
return StackSafeTop(outputStack);
}
class UIObject
{
public:
UIObject(int z):m_z(z){}
public:
int GetAttrValue(const string& sname) {
return m_z;
}
private:
int m_z;
};
typedef pair<string, UIObject*> PAIR;
class CmpByZorder {
public:
bool operator()(const PAIR& k1, const PAIR& k2) {
return k1.second->GetAttrValue("") < k2.second->GetAttrValue("");
}
};
void TestMapSort()
{
map<string, UIObject*> childrenMap;
childrenMap["111"] = new UIObject(1);
childrenMap["11"] = new UIObject(5);
childrenMap["22"] = new UIObject(6);
childrenMap["33"] = new UIObject(9);
childrenMap["44"] = new UIObject(11);
string a = "21";
string b = "100";
cout << (a > b) << endl;
vector<PAIR> childrenVec(childrenMap.begin(), childrenMap.end());
sort(childrenVec.begin(), childrenVec.end(), CmpByZorder());
cout << ":" << endl;
for (int i = 0; i != childrenVec.size(); ++i) {
//ڴ˶value֮в
cout<< childrenVec[i].first <<" "<< childrenVec[i].second->GetAttrValue("") << endl;
}
}
void MultiLineTextToSingleLine(const string& inFilePath, const string& outFilePath)
{
auto ReplaceAll = [](string& src, const string& tarSubStr, const string& dstSubStr) {
std::size_t posBegin = src.find(tarSubStr);
while (posBegin != std::string::npos){
src = src.replace(posBegin, tarSubStr.length(), dstSubStr);
posBegin = src.find("\n", posBegin + tarSubStr.length());
}
};
ifstream inFile(inFilePath.c_str());
stringstream buffer;
buffer << inFile.rdbuf();
string allLines(buffer.str());
ReplaceAll(allLines, "\n", "\\n");
ReplaceAll(allLines, "\r", "\\r");
ofstream outFile(outFilePath);
outFile << allLines;
}
class Node
{
public:
~Node() {
cout << "destructor node" << endl;
}
};
void TestVec() {
vector<Node*> vec;
for (auto i = 0; i < 4; ++i) {
auto item = new Node();
vec.push_back(item);
}
}
int main()
{
TestCMF obj;
auto getRet = CallMemberFunction(&obj, &TestCMF::Add, 10, 11);
auto lambda = GetLambda(&obj, &TestCMF::Add);
auto getRet2 = lambda(15, 16);
TestVec();
auto ret = TMAX(5.5, 8.5, 4.5,1.5,3.5);
ret = ret;
MultiLineTextToSingleLine("xmlTemp.xml", "xmlTemp2.xml");
return 0;
TestMapSort();
regex colorPattern("([0-9a-fA-F]*)");
//bool colorRet1 = regex_match("AAFF00", colorPattern);
//string value1 = regex_replace("AAFF00", colorPattern, string("$0"));
//bool colorRet2 = regex_match("AAFF00FF", colorPattern);
//string value2 = regex_replace("AAFF00FF", colorPattern, string("$0"));
//bool colorRet3 = regex_match("AAff00F", colorPattern);
//string value3 = regex_replace("AAff00F", colorPattern, string("$0"));
//bool colorRet4 = regex_match("AAFF00FX", colorPattern);
//string value4 = regex_replace("AAFF00FX", colorPattern, string("$0"));
try {
}
catch (...) {
cout << "catch exception" << endl;
}
try {
auto retDouble1 = TestCalcExp("19-4*2");
auto retDouble2 = TestCalcExp("19-4*2+21");
auto retDouble3 = TestCalcExp("(19-4)))*2+21");
auto retDouble4 = TestCalcExp("100");
auto retDouble5 = TestCalcExp("");
}
catch (...) {
cout << "catch exception" << endl;
}
try {
int* pInt;
pInt = (int*)0x00001234;
*pInt = 6;
}
catch (...) {
cout << "catch exception" << endl;
}
auto eraseSpace = [](string& str) {
for (string::iterator it = str.end(); it != str.begin();) {
--it;
if ((*it) == ' ' || (*it) == '\t') {
str.erase(it);
}
}
};
auto I2Str = [](auto param)->string {
stringstream strStream;
string ret;
strStream << param;
strStream >> ret;
return ret;
};
string strParentWidth = I2Str(unsigned int(155));
string strParentHeight = I2Str(unsigned int(693355));
//ȥ·˵Ŀհ
auto EraseEndsSpace = [](string& str) {
//ȥͷհ
for (string::iterator it = str.begin(); it != str.end(); ) {
if ((*it) == ' ' || (*it) == '\t' || (*it) == '\n' || (*it) == '\r') {
str.erase(it);
it = str.begin();
continue;
}
break;
}
//ȥβհ
for (string::iterator it = str.end(); it != str.begin();) {
--it;
if ((*it) == ' ' || (*it) == '\t' || (*it) == '\n' || (*it) == '\r') {
str.erase(it);
it = str.end();
continue;
}
break;
}
};
regex midPattern("#mid");
string width = "#width/2";
string height = "#height/2";
string midExp = "((#width) - (" + width + "))/2";
auto strRet = regex_replace("5-#mid+#mid2", midPattern, "qq");
regex funcPattern("([^=>]*)(=>)?([^=>\.]*)");
auto funcRet1 = regex_match(".\\ File\\test.lua=>OnWindowCreate", funcPattern);
string file = regex_replace(".\\Program File\\test.lua=>OnWindowCreate", funcPattern, string("$1"));
string fname = regex_replace(".\\Program File\\test.lua=>OnWindowCreate", funcPattern, string("$3"));
auto funcRet2 = regex_match(" .\\Program File\\test.lua => OnWindowCreate", funcPattern);
file = regex_replace(" .\\Program File\\test.lua => OnWindowCreate", funcPattern, string("$1"));
fname = regex_replace(" .\\Program File\\test.lua => OnWindowCreate ", funcPattern, string("$3"));
EraseEndsSpace(file);
EraseEndsSpace(fname);
auto funcRet3 = regex_match("OnWindowCreate", funcPattern);
file = regex_replace("OnWindowCreate", funcPattern, string("$1"));
fname = regex_replace("OnWindowCreate", funcPattern, string("$3"));
file = regex_replace(".\\Program File\\test.lua", funcPattern, string("$1"));
fname = regex_replace(".\\Program File\\test.lua", funcPattern, string("$3"));
auto funcRet4 = regex_match("InputBox.bkg", funcPattern);
auto funcRet5 = regex_match("", funcPattern);
regex boolPattern("[01]");
auto boolRet1 = regex_match("0", boolPattern);
auto boolRet2 = regex_match("1", boolPattern);
auto boolRet3 = regex_match(" ", boolPattern);
auto boolRet4 = regex_match("", boolPattern);
auto boolRet5 = regex_match("01", boolPattern);
auto boolRet6 = regex_match("5", boolPattern);
regex intPattern("[0-9]+");
auto intRet1 = regex_match("0", intPattern);
auto intRet2 = regex_match("6", intPattern);
auto intRet3 = regex_match("255", intPattern);
auto intRet4 = regex_match("0.9", intPattern);
auto intRet5 = regex_match("", intPattern);
auto intRet6 = regex_match(" ", intPattern);
string sPattern = "(([0-9heigtwdm\\+\\-\\*/#\\\s*]*),([0-9heigtwdm\\+\\-\\*/#\\\s*]*),([0-9heigtwdm\\+\\-\\*/#\\\s*]*),([0-9heigtwdm\\+\\-\\*/#\\\s*]*))*";
regex pattern(sPattern.c_str());
string pos = " , #height / 2 - 50, 200, 100 ";
//pos = "";
//eraseSpace(pos);
if (regex_match(pos, pattern)) {
cout << "match success" << endl;
string left = regex_replace(pos, pattern, string("$2"));
string top = regex_replace(pos, pattern, string("$3"));
string width = regex_replace(pos, pattern, string("$4"));
string height = regex_replace(pos, pattern, string("$5"));
cout << "left: " << left<< " top: " << top << " width: " << width << " height: " << height << endl;
}else {
cout << "match failed" << endl;
}
auto posRet1 = regex_match(",,,", pattern);
auto posRet2 = regex_match(",2,3,#mid", pattern);
auto posRet3 = regex_match("1,,3,#mid", pattern);
auto posRet4 = regex_match("2,3,#mid", pattern);
auto posRet5 = regex_match("#height/2-50,,,", pattern);
auto posRet6 = regex_match("#height/2-50,#height/2-50,#height/2-50,#height/2-50", pattern);
auto posRet7 = regex_match("1,,3,#mkd", pattern);
auto posRet8 = regex_match("1,,3,#mId", pattern);
auto posRet9 = regex_match(",,", pattern);
auto posRet10 = regex_match("", pattern);
regex pattern2("([0-9heigtwd\\+\\-\\*\\(\\)/#]+).([0-9heigtwd\\+\\-\\*/#]+)");
string str = "(#height-100)/2.width";
if (regex_match(str, pattern2)) {
cout << "match success" << endl;
}
string sExp = "[0-9\\+\\-\\*\\(\\)/\\\s*]*";
string sCmd = "((#mid)*(#height)*(#width)*)*";
//regex patternAll("(" + sExp + sCmd + sExp + ")*");
regex patternAll("(" SSEXP SSCMD SSEXP ")*");
regex pattern3("([0-9\\+\\-\\*\\(\\)/]*((#mid)*(#height)*(#width)*)*)"); //(".*#hello.*");//
string str3 = "10+#heigh";// (#height - 100) / 2.width";
auto ret1 = regex_match(" #mid", patternAll);
auto ret2 = regex_match("#height ", patternAll);
auto ret3 = regex_match(" #width ", patternAll);
auto ret4 = regex_match("#width+1", patternAll);
auto ret5 = regex_match("2-#mid", patternAll);
auto ret6 = regex_match("10+#height-9", patternAll);
auto ret7 = regex_match("(#height-#width) / 2", patternAll);
auto ret8 = regex_match("(#height-#width) / 2 -#mid", patternAll);
auto ret9 = regex_match("10+ #heght-9", patternAll);
auto ret10 = regex_match("#mqd", patternAll);
auto ret11 = regex_match("(#height-#widwth)/2-#mid", patternAll);
auto ret12 = regex_match("5+(#height-#width)/2-#mid", patternAll);
if (regex_match(str3, pattern3)) {
cout << "match success" << endl;
}
UIBase base;
const string name = base.GetObjectID_1();
cout << name << endl; //Чʵ͡m_attrMap["id"]=>nameһο죬return name->nameһ
const string& rname = base.GetObjectID_2(); //Чʵ
//const string* pName = base.GetObjectID_3();//GetObjeIDصǾֲĵַ
//cout << *pName << endl; //˴ڴ쳣ΪpNameַָѾ
//const string* pName2 = base.GetObjectID_4(); //GetObjeID2صIJǾֲĵַmapijԱĵַ
//cout << *pName2 << endl; //
//delete pName2; //ˣmapijԱ
auto spName = base.GetObjectID_7();
if(!spName->empty())
cout << *spName << endl;
//(*spName)[0] = '4';
cout << *spName << endl;
int a = 10;
map<string, string> testMap;
testMap.insert(pair<string, string>("A", "AAA"));
string pA = testMap["A"];
pA = testMap["B"];
if (testMap.end() != testMap.find("B"))
cout << "what the fuck";
return 0;
}
| true |
6d29d1363e5397817cbaacc59e9e5be9edc99ca4 | C++ | long-gong/leetcode | /test/data-structures-linked-list/445_add_numbers_II_test.cpp | UTF-8 | 1,280 | 2.765625 | 3 | [] | no_license | //
// Created by saber on 8/21/18.
//
#include <src/data-structures-linked-list/445_add_numbers_II.hh>
#include <gtest/gtest.h>
TEST(AddNumbersIITest, Solution01Case01)
{
auto l1 = ListNode::create({7,2,4,3});
auto l2 = ListNode::create({5,6,4});
AddNumbersII01 an201;
EXPECT_TRUE(ListNode::compare({7, 8,0,7}, an201(l1, l2)));
ListNode::delete_me(l1);
ListNode::delete_me(l2);
}
TEST(AddNumbersIITest, Solution01Case02)
{
auto l1 = ListNode::create({9,9});
auto l2 = ListNode::create({1});
AddNumbersII01 an201;
EXPECT_TRUE(ListNode::compare({1,0,0}, an201(l1, l2)));
ListNode::delete_me(l1);
ListNode::delete_me(l2);
}
TEST(AddNumbersIITest, Solution01Case03)
{
auto l1 = ListNode::create({1});
auto l2 = ListNode::create({9,9});
AddNumbersII01 an201;
EXPECT_TRUE(ListNode::compare({1,0,0}, an201(l1, l2)));
ListNode::delete_me(l1);
ListNode::delete_me(l2);
}
TEST(AddNumbersIITest, Solution02Case01)
{
auto l1 = ListNode::create({7,2,4,3});
auto l2 = ListNode::create({5,6,4});
AddNumbersII02 an201;
EXPECT_TRUE(ListNode::compare({7, 8,0,7}, an201(l1, l2)));
ListNode::delete_me(l1);
ListNode::delete_me(l2);
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | true |
14af5ea3d644fa5be50f0d8e7995a4fe880927bf | C++ | hatv/QTowerDefense | /code/Cockroach.h | UTF-8 | 848 | 3.0625 | 3 | [] | no_license | #ifndef COCKROACH_H
#define COCKROACH_H
#include <QtGui>
#include "Enemy.h"
/**
* \class Cockroach
* \image html img/cafard.png
* \brief Représente un cafard
*
* Le cafard est un insecte (et hérite donc de la classe Enemy).
*
* Il a la spécificité de donner naissance à deux cafards de taille inférieure lorsqu'il est tué.
*/
class Cockroach : public Enemy {
public:
/**
* Crée un cafard en passant par le constructeur de sa classe mère : Enemy
* \param map La carte sur laquelle évoluera le cafard
* \param size La taille du cafard
*/
Cockroach (Map* map, int size):
Enemy (map, size , 10 * size * size, false, 5 * size * size, 2) {
this->appendPixmap("cafard1.png");
this->appendPixmap("cafard2.png");
this->appendPixmap("cafard3.png");
this->appendPixmap("cafard2.png");
}
};
#endif
| true |
55d24c269bed2e746a4fc3ab2c0ab38bc80d8723 | C++ | patelpreet422/cipherschools | /minimize_the_max_adjacent_diff.cpp | UTF-8 | 925 | 2.90625 | 3 | [] | no_license | #ifdef DEBUG
#include <LeetcodeHelper.h>
#include <prettyprint.hpp>
#endif
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<int> find_max_of_k_size_window(vector<int> &v, int k) {
vector<int> r;
deque<int> q;
int n = v.size();
for (int i = 0; i < n; ++i) {
while (!q.empty() and q.front() <= i - k) {
q.pop_front();
}
while (!q.empty() and v[q.back()] < v[i]) {
q.pop_back();
}
q.push_back(i);
if (i >= k - 1) {
r.push_back(v[q.front()]);
}
}
return r;
}
int min_max_diff(vector<int> &v, int k) {
int n = v.size();
vector<int> diff(n - 1, 0);
for (int i = 0; i < n - 1; ++i) {
diff[i] = v[i + 1] - v[i];
}
vector<int> a = find_max_of_k_size_window(diff, n - k - 1);
return *min_element(begin(a), end(a));
}
int main() {
int k = 2;
vector<int> v{3, 7, 8, 10, 14};
cout << min_max_diff(v, k) << '\n';
return 0;
}
| true |
25cb3d7165d2175977803bb95cfe9f6cc43e8696 | C++ | PazerOP/StatusSpec | /src/modules/filesystemtools.cpp | UTF-8 | 1,841 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* filesystemtools.cpp
* StatusSpec project
*
* Copyright (c) 2014-2015 Forward Command Post
* BSD 2-Clause License
* http://opensource.org/licenses/BSD-2-Clause
*
*/
#include "filesystemtools.h"
#include "convar.h"
#include "filesystem.h"
FilesystemTools::FilesystemTools() {
searchpath_add = new ConCommand("statusspec_filesystemtools_searchpath_add", [](const CCommand &command) { g_ModuleManager->GetModule<FilesystemTools>()->AddSearchPath(command); }, "add a filesystem search path", FCVAR_NONE);
searchpath_remove = new ConCommand("statusspec_filesystemtools_searchpath_remove", [](const CCommand &command) { g_ModuleManager->GetModule<FilesystemTools>()->RemoveSearchPath(command); }, "remove a filesystem search path", FCVAR_NONE);
}
bool FilesystemTools::CheckDependencies() {
bool ready = true;
if (!g_pFullFileSystem) {
PRINT_TAG();
Warning("Required interface IFileSystem for module %s not available!\n", g_ModuleManager->GetModuleName<FilesystemTools>().c_str());
ready = false;
}
return ready;
}
void FilesystemTools::AddSearchPath(const CCommand &command) {
if (command.ArgC() >= 3) {
SearchPathAdd_t location = PATH_ADD_TO_TAIL;
if (command.ArgC() >= 4) {
if (V_stricmp(command.Arg(3), "head") == 0) {
location = PATH_ADD_TO_HEAD;
}
else if (V_stricmp(command.Arg(3), "tail") == 0) {
location = PATH_ADD_TO_TAIL;
}
}
g_pFullFileSystem->AddSearchPath(command.Arg(1), command.Arg(2), location);
}
else {
Warning("Usage: statusspec_filesystemtools_searchpath_add <path> <id> [location]\n");
}
}
void FilesystemTools::RemoveSearchPath(const CCommand &command) {
if (command.ArgC() >= 3) {
g_pFullFileSystem->RemoveSearchPath(command.Arg(1), command.Arg(2));
}
else {
Warning("Usage: statusspec_filesystemtools_searchpath_remove <path> <id>\n");
}
} | true |
e5b211dc60def531ae9024beea35edebf73136df | C++ | moaiweishui/leetcode | /26. Remove Duplicates from Sorted Array/src.cpp | UTF-8 | 673 | 2.984375 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0)
return 0;
else if(nums.size() == 1)
return 1;
vector<int>::iterator it1 = nums.begin();
while (it1 != nums.end())
{
vector<int>::iterator it2;
for (it2 = it1 + 1; it2 != nums.end();)
{
if (*it2 == *it1)
{
it2 = nums.erase(it2);
}
else
{
break;
}
}
it1++;
}
return nums.size();
}
};
| true |
490a49985bc07ad18acc6fbb62869df58e1006c1 | C++ | jtlai0921/XB1939_-_- | /ch09/CH09_15.cpp | BIG5 | 869 | 3.890625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
class Circle
{
private:
const static double PI;
static int counter;
int radius;
public:
Circle(int r)
{
radius = r;
counter++;
}
double Area(){ return PI*radius*radius; }
int getCounter(){ return counter; }
};
const double Circle::PI = 3.1415926535;//bO~]w`PI
int Circle::counter = 0; //bO~]wRAƦcounter
int main()
{
Circle c1(3);
cout<<"[c1n] = "<<c1.Area()<<endl;
Circle c2(5);
cout<<"[c2n] = "<<c2.Area()<<endl;
cout<<"[c1Xcounter]@ "<<c1.getCounter()<<" Ӷ"<<endl;
cout<<"[c2Xcounter]@ "<<c2.getCounter()<<" Ӷ"<<endl;
return 0;
}
| true |
3d8c73f5038cc2c68fcbfae05ea9e7fa38046e8b | C++ | Knabin/AlgorithmQ | /Chapter2/main_37.cpp | UTF-8 | 864 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int s, n, i, j, temp, idx;
cin >> s;
cin >> n;
vector<int> vSize(s);
vector<int> vNumber(n);
for (i = 0; i < n; ++i)
{
cin >> vNumber[i];
idx = 0;
temp = 0;
for (j = 0; j < s; ++j)
{
if (vNumber[i] != vSize[j]) continue;
idx = j;
temp = vSize[j];
break;
}
// 현재 vSize에 있는지 체크, 해당 인덱스 가지고 있어야 함
if(idx != 0)
{
// 맨앞으로 꺼내오기
for (j = idx - 1; j >= 0; --j)
{
vSize[j + 1] = vSize[j];
}
vSize[j + 1] = temp;
}
// 없다면
else
{
// 맨 앞에 추가하고 한칸씩 밀기
for (j = s - 1; j > 0; --j)
{
vSize[j] = vSize[j - 1];
}
vSize[0] = vNumber[i];
}
}
for (i = 0; i < s; ++i)
cout << vSize[i] << " ";
return 0;
}
| true |
749395645d2cebc4ff80832658752b74f264ec6f | C++ | thirdeye18/CS162a | /Module 9/Lab 9/Lab 9/PalindromeStack.hpp | UTF-8 | 801 | 3.078125 | 3 | [] | no_license | /*********************************************************************
** Program name: Lab 9
** Filename: PalindromeStack.hpp
** Author: Justin Hammel
** Date: 6/4/2017
** Description: Implementation for the PalindromeStack class.
*********************************************************************/
#ifndef PALINDROME_STACK_HPP
#define PALINDROME_STACK_HPP
#include <string>
#include <stack>
#include <iostream>
using std::string;
using std::stack;
using std::cout;
using std::endl;
class PalindromeStack
{
private:
string palindromeString;
stack <char> palindrome;
stack <char> printStack;
public:
PalindromeStack();
~PalindromeStack();
void add2Stack(string userStringIn);
void add2String();
void printPalindromeString();
void printPalindromeStack();
};
#endif // !PALINDROME_STACK_HPP | true |
c53bdd67aecabcc86bbb4c5423a683763003f21c | C++ | DirectX-Vulkan/DirectX11 | /DirectX/Logger.cpp | UTF-8 | 1,696 | 2.984375 | 3 | [] | no_license | #include "Logger.h"
#include <filesystem>
#include <fstream>
#include <iostream>
using namespace std;
Logger::Logger(string pcId, string renderEngine, string objectName, TimeType timeType, char separator)
{
m_pcId = pcId;
m_renderEngine = renderEngine;
m_objectName = objectName;
m_logs = vector<Log>();
m_timeType = timeType;
m_separator = separator;
}
Logger::~Logger()
{
}
void Logger::ExportLogFile()
{
#pragma region create folder
//create folder if it doesn't exist yet
filesystem::create_directory("data");
#pragma endregion
ofstream file;
file.open("data\\" + getTimeTypeName(m_timeType) + "-data-" + m_pcId + "-" + m_renderEngine + "-" + m_objectName + ".csv");
#pragma region --- csv header ---
file << "timestamp" << m_separator
<< "pc-id" << m_separator
<< "engine" << m_separator
<< "object" << m_separator;
switch (m_timeType)
{
case TimeType::rt:
file << "fps";
break;
case TimeType::nrt:
file << "spf";
break;
default:
throw runtime_error("unhandled time type");
break;
}
file << m_separator << "cpu";
#pragma endregion
//skip first logs as it's always inaccurate as the program will be in the process of booting up
//by the time the logs are kept it should've stabilised
for (size_t i = 0; i < m_logs.size(); i++)
{
if (m_logs[i].m_cpuUsage > 0 && m_logs[i].m_frames > 0)
{
file << '\n';
file << m_logs[i].m_timestamp << m_separator
<< m_logs[i].m_pcId << m_separator
<< m_logs[i].m_renderEngine << m_separator
<< m_logs[i].m_objectName << m_separator
<< m_logs[i].m_frames << m_separator
<< m_logs[i].m_cpuUsage;
}
}
file.close();
}
void Logger::AddLog(Log log)
{
m_logs.push_back(log);
}
| true |
67f38ee0fb65e5796ef072bc53e9deb2487adeb1 | C++ | xswxq/C-Primer-Plus | /chapter12/src/String2.cpp | GB18030 | 3,240 | 3.015625 | 3 | [] | no_license | /*ߣlu
ڣ
Ȩ
*/ #include "String2.h"
int String2::num_strings = 0;
int String2::HowMany()
{
return num_strings;
};
String2::String2()
{
len = 4;
str = new char[1];
str[0] = '\0';
num_strings++;
};
String2::String2(const char *s)
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
num_strings++;
}
String2::String2(const String2 &st)
{
num_strings++;
len = st.len;
str = new char[len+1];
strcpy(str,st.str);
}
void String2::Stringlow()
{
for(int i = 0; i<len; ++i)
{
if(isupper(str[i]))
{
str[i] = tolower(str[i]);
}
}
}
void String2::Stringup()
{
for(int i = 0; i<len; ++i)
{
if(islower(str[i]))
{
str[i] = toupper(str[i]);
}
}
}
int String2::has(char ch) const
{
int sum,i;
for(sum = i =0; i<len; ++i)
{
if(str[i] == ch)
sum++;
}
return sum;
}
String2 & String2::operator = (const String2 &st)
{
if(this == &st)
{
return *this;
}
delete [] str;
len = st.len;
str = new char[len+1];
strcpy(str,st.str);
return *this;
}
String2 & String2::operator = (const char *s)
{
delete [] str;
len = strlen(s);
str = new char [len+1];
strcpy(str,s);
return *this;
}
char & String2::operator [](int i)
{
return str[i];
}
const char & String2::operator[](int i) const
{
return str[i];
}
String2::~String2() // necessary destructor
{
--num_strings; // required
delete [] str; // required
}
bool operator<(const String2 & st,const String2 & st2)
{
cout << "run <: ";
return (strcmp(st.str,st2.str)<0);
}
bool operator<=(const String2 & st,const String2 & st2)
{
return (strcmp(st.str,st2.str)<= 0);
}
bool operator>(const String2 & st,const String2 & st2)
{
return st2 < st;
}
bool operator>=(const String2 & st,const String2 & st2)
{
return st2 <= st;
}
bool operator==(const String2 & st,const String2 & st2)
{
return (strcmp(st.str,st2.str) == 0);
}
ostream & operator << (ostream & os,const String2 & st)
{
os << st.str;
return os;
}
istream & operator >>(istream & is,const String2 & st)
{
is >> st.str;
return is;
}
String2 String2::operator +(const String2 & s) const
{
cout <<"run string2 &s : ";
int len = strlen(str) + strlen(s.str);
char *str_sum = new char[len+1];
strcpy(str_sum,str);
strcat(str_sum,s.str);
String2 tr_new = str_sum;
delete [] str_sum;
return tr_new;
}
String2 String2::operator+(const char * s) const
{
cout <<"run char *s: ";
String2 temp = s;
String2 sum = *this + temp;
return sum;
// int len = strlen(str) + strlen(s);
// char *str_sum = new char[len+1];
// strcpy(str_sum,str);
// strcat(str_sum,s);
// String2 tr_new = str_sum;
// delete [] str_sum;
// return tr_new;
}
String2 operator+(const char *st1,const String2 & st2)
{
cout <<"run st1 + st2: ";
return (st2+st1);
}
| true |
87b4ea832ab9693efebf47b925eac30f0187231f | C++ | webclinic017/Potts-Portfolio | /computer_science/cpp_lists/LinkedNode.h | UTF-8 | 554 | 3.046875 | 3 | [] | no_license | //
// Created by Toby Dragon on 10/24/16.
//
// Completed by Kenneth Potts as course project work
//
#ifndef LINKEDNODE_H
#define LINKEDNODE_H
class LinkedNode {
private:
int item;
LinkedNode* next;
public:
LinkedNode(int item){
this->item = item;
next = nullptr;
}
int getItem(){
return item;
}
LinkedNode* getNext(){
return next;
}
void setItem(int newItem){
item = newItem;
}
void setNext(LinkedNode* newNext){
next = newNext;
}
};
#endif //LINKEDNODE_H
| true |
a3675727e6c1392321e7b39e575f2e339cb5ad10 | C++ | alexisv318/CPSC301Assignment4 | /balance.cpp | UTF-8 | 2,084 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
using namespace std;
struct PERSON{
char Name[20];
float Balance;};
void Display(PERSON(&person)[10], int &nPeople){
for (int i = 0; i < nPeople; i++) {
cout << person[i].Name << " " << person[i].Balance << endl;
}
}
void findRichest (PERSON (&personF)[10], int &nPeople){
float tmp = personF[0].Balance;
int counter = 0;
string name1;
while (counter < nPeople) {
while (tmp < personF[counter].Balance){
tmp = personF[counter].Balance;
name1 = personF[counter].Name;
}
counter++;
}
cout << "The customer with maximum balance is " << name1 << endl << endl;
}
void Deposit(string name2, PERSON (&personF)[10], int &nPeople){
int i = 0;
float temp;
cout << name2 << ", how much would you like to deposit?" << endl;
cin >> temp;
while (i < nPeople){
if (name2 == personF[i].Name) {
personF[i].Balance += temp;
cout << "Now your new balance is " << personF[i].Balance << endl;
}
i++;
}
}
void NewCopy(string namefile, PERSON (&person)[10], int &nPeople){
ofstream output_file;
output_file.open(namefile);
if (output_file.is_open()){
for (int i = 0; i < nPeople; i++){
output_file << person[i].Name << " " << person[i].Balance << endl;
}
output_file.close();
}
}
int main(){
int counter = 0;
string fName;
string lName;
string fullname;
string customer;
int nPeople = 6;
float pay;
string filename = "data.txt";
ifstream file;
PERSON person[10];
file.open(filename.c_str());
if (file.is_open()) {
while(file.eof() == false) {
file >> fName >> lName >> pay;
person[counter].Balance = pay;
fullname = (fName + " " + lName);
strcpy(person[counter].Name, fullname.c_str());
++counter;
}
}
else {
cout << "file not open!" << endl;
}
Display(person, nPeople);
findRichest(person, nPeople);
cout << "Enter your full name to deposit money " << endl;
getline(cin, customer);
Deposit(customer, person, nPeople);
NewCopy(filename, person, nPeople);
return 0;
}
| true |
7ffec6486086d1655637b6455b222a63259fa3a2 | C++ | PuppyRush/lesson | /main.h | UTF-8 | 288 | 2.65625 | 3 | [] | no_license | #pragma once
#include "ctor_dtor.h"
#include <string>
using namespace std;
int main()
{
Animal animal;
Animal* animal_ptr = new Animal{};
Animal& animal_ref = animal;
animal_ref.SetName(new string{ "abc" });
string str;
animal_ptr->SetName(str);
animal_ptr->SetName(&str);
} | true |
5efe895aabb02643bdfb81609ae2b16d63596b1f | C++ | changqing16/LeetCode | /0101-0150/138.cpp | UTF-8 | 872 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
class Node
{
public:
int val;
Node *next;
Node *random;
Node() {}
Node(int _val, Node *_next, Node *_random)
{
val = _val;
next = _next;
random = _random;
}
};
Node *copyRandomList(Node *head)
{
if (head == NULL)
return NULL;
Node *cur = head;
vector<Node *> nodes;
int c = 0;
while (cur != NULL)
{
nodes.push_back(new Node(cur->val, NULL, NULL));
cur->val = c;
c++;
cur = cur->next;
}
nodes.push_back(NULL);
cur = head;
c = 0;
while (cur != NULL)
{
if (cur->random != NULL)
nodes[c]->random = nodes[cur->random->val];
nodes[c]->next = nodes[c + 1];
c++;
cur = cur->next;
}
return nodes[0];
} | true |
1b023d304a47da0863497e9a09aea4aef92854c4 | C++ | vintagewang/fuxedo | /src/svcrepo.h | UTF-8 | 2,278 | 2.546875 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | // This file is part of Fuxedo
// Copyright (C) 2017 Aivars Kalvans <aivars.kalvans@gmail.com>
#include <map>
#include "mib.h"
#include "misc.h"
struct queue_entry {
int grpno;
int msqid;
};
struct service_entry {
std::vector<queue_entry> queues;
size_t current_queue;
uint64_t cached_revision;
uint64_t *mib_revision;
size_t mib_service;
service_entry() : current_queue(0) {}
};
class service_repository {
public:
service_repository(mib &m) : m_(m) {}
int get_queue(int grpno, const char *svc) {
auto &entry = get_entry(svc);
refresh(entry);
return load_balance(entry, grpno);
}
private:
service_entry &get_entry(const char *service_name) {
auto it = services_.find(service_name);
if (it == services_.end()) {
auto lock = m_.data_lock();
service_entry entry;
entry.mib_service = m_.find_service(service_name);
if (entry.mib_service == m_.badoff) {
throw std::out_of_range(service_name);
}
entry.mib_revision = &(m_.services().at(entry.mib_service).revision);
entry.cached_revision = 0;
it = services_.insert(std::make_pair(service_name, entry)).first;
}
return it->second;
}
void refresh(service_entry &entry) {
if (entry.cached_revision != *(entry.mib_revision)) {
entry.queues.clear();
auto lock = m_.data_lock();
auto adv = m_.advertisements();
for (size_t i = 0; i < adv->len; i++) {
auto &a = adv.at(i);
if (a.service == entry.mib_service) {
auto msqid = m_.queues().at(a.queue).msqid;
auto grpno = m_.servers().at(a.server).grpno;
entry.queues.push_back({grpno, msqid});
}
}
entry.cached_revision = *(entry.mib_revision);
}
}
int load_balance(service_entry &entry, int grpno) {
if (entry.queues.empty()) {
throw std::out_of_range("no queue");
}
if (grpno == -1) {
entry.current_queue = (entry.current_queue + 1) % entry.queues.size();
return entry.queues[entry.current_queue].msqid;
} else {
for (auto &e : entry.queues) {
if (e.grpno == grpno) {
return e.msqid;
}
}
}
throw std::out_of_range("no queue");
}
mib &m_;
std::map<std::string, service_entry, std::less<void>> services_;
};
| true |
d4da0988706aa83e2114978bc87106902287d41d | C++ | NicoKNL/coding-problems | /problems/kattis/relocation/sol.cpp | UTF-8 | 442 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int N, Q;
cin >> N >> Q;
unordered_map<int, int> M;
for (int i = 1; i <= N; ++i)
cin >> M[i];
while (Q--)
{
int OPT, A, B;
cin >> OPT >> A >> B;
if (OPT == 1)
M[A] = B;
if (OPT == 2)
{
int dist = abs(M[A] - M[B]);
cout << dist << endl;
}
}
return 0;
} | true |
b11e988e3b1c0d97a8ae264f2dd24ae7ed679f81 | C++ | pobortsevv/cpp_intro | /day04/ex01/SuperMutant.cpp | UTF-8 | 812 | 2.78125 | 3 | [] | no_license | /*
* ===================================================================
*
* Filename: SuperMutant.cpp
*
* Version: 1.0
* Created: 06/17/2021 10:13:08
* Compiler: clang++
*
* Author: sabra
*
* ===================================================================
*/
#include "SuperMutant.hpp"
SuperMutant::SuperMutant(void) : Enemy(170, "Super Mutant")
{
std::cout << "Gaaah. Me want smash heads!" << std::endl;
}
SuperMutant::SuperMutant(SuperMutant const & obj) :
Enemy(obj.getHP(), obj.getType())
{
std::cout << "Gaaah. Me want smash heads!" << std::endl;
}
SuperMutant::~SuperMutant(void)
{
std::cout << "Aaargh..." << std::endl;
}
void SuperMutant::takeDamage(int damage)
{
damage = damage > 3 ? damage - 3 : damage;
Enemy::takeDamage(damage);
}
| true |
df2003d69cf9ca79dca8769f872d27c50472e274 | C++ | zhajee/Academic-Spring-2020 | /Calculate Course Grades/calculateScores.cpp | UTF-8 | 1,524 | 3.171875 | 3 | [] | no_license | #include "students.hpp"
//calculate total score based on rawscores, points, and weights for each artifact
void updateTotalScores(Student* student_info, int* points, int* weights, int num_students, int num_artif) {
for (int i = 0; i < num_students; i++) {
double sum = 0;
for (int j = 0; j < num_artif; j++) {
double score = ((double)student_info[i].rawscores[j] / (double)points[j]) * (double)weights[j];
sum += score;
}
student_info[i].totalscore = sum;
//delete[] student_info[i].rawscores;
}
}
void updateLetterGrades(Student* student_info, double* cutpoints, int num_students) {
//calculate letter grade based on cutpoints
for (int i = 0; i < num_students; i++) {
Student student = student_info[i];
std::string letters[4] = {"A", "B", "C", "D"};
std::string letter = "F";
//move backwards from cutpoints aligned with letter grade
for (int j = 3; j >= 0; j--) {
if (student_info[i].totalscore >= cutpoints[j]) {
letter = letters[j];
}
}
student_info[i].lettergrade = letter;
//assign Pass / No Pass based on letter grade calculated above
if (student.gradeop == "P") {
if (letter == "D" or letter == "F") {
student_info[i].lettergrade = "NP";
}
else {
student_info[i].lettergrade = "P";
}
}
}
}
| true |
9343596c3a5527440910a8a8afa2649b532c3de3 | C++ | orlov-dm/qt-chat | /ChatServer/core/connection.h | UTF-8 | 348 | 2.546875 | 3 | [] | no_license | #ifndef CONNECTION_H
#define CONNECTION_H
#include <QTcpSocket>
class Connection : public QTcpSocket
{
Q_OBJECT
public:
Connection(QObject *parent);
void setClientName(const QString &name) { _clientName = name; }
QString getClientName() const { return _clientName; }
private:
QString _clientName;
};
#endif // CONNECTION_H
| true |
a6c84b12fae05f5d45ee77c4d4bad0beb21135b9 | C++ | MachineMitch21/CodeGalore | /RendererStuff/src/VertexBufferLayout.h | UTF-8 | 993 | 3.140625 | 3 | [] | no_license |
#ifndef VERTEXBUFFERLAYOUT_H
#define VERTEXBUFFERLAYOUT_H
#include <GL/glew.h>
#include <vector>
struct VertexBufferElement
{
unsigned int type;
unsigned int count;
unsigned char normalized;
static unsigned int SizeOfGLType(unsigned int type)
{
switch(type)
{
case GL_FLOAT: return 4;
case GL_UNSIGNED_INT: return 4;
case GL_UNSIGNED_BYTE: return 1;
default: return 0;
}
}
};
class VertexBufferLayout
{
public:
VertexBufferLayout();
~VertexBufferLayout();
void Push(unsigned int type, unsigned int count, unsigned char normalized = GL_FALSE);
inline const std::vector<VertexBufferElement>& GetElements() const { return _elements; };
inline unsigned int GetStride() const { return _stride; };
private:
std::vector<VertexBufferElement> _elements;
unsigned int _stride;
};
#endif // VERTEXBUFFERLAYOUT_H | true |
eaa160c6f0ea828733b81f6351c79685d530720b | C++ | dongxiaorui/OJ | /SLCUPC-OJ/1877【函数】求最大公约数——递归.cpp | UTF-8 | 241 | 2.6875 | 3 | [] | no_license | #include "stdio.h"
int Gcd(int n,int m){
if(m<=n&&n%m==0) return m;
else if(n<m) return Gcd(m,n);
else Gcd(m,n%m);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
printf("%d\n",Gcd(n,m));
return 0;
}
| true |
018972a4ba7ce6fbfe3633b6273736af0c2c7390 | C++ | webstorage119/document-scanner-1 | /abstractpapersheetdetector.cpp | UTF-8 | 3,038 | 2.90625 | 3 | [] | no_license | #include "abstractpapersheetdetector.h"
#include <opencv2/imgproc.hpp>
//constexpr AbstractPaperSheetDetector::AbstractPaperSheetDetector(double minAreaPct, double maxAreaPct, double approxAccuracyPct)
// : minAreaPct(minAreaPct>=0 && minAreaPct<=1 ? minAreaPct : throw std::invalid_argument("Min area percentage must be in range 0..1."))
// , maxAreaPct(maxAreaPct>=minAreaPct && maxAreaPct<=1 ? maxAreaPct : throw std::invalid_argument("Max area percentage must be in range <min area percentage>..1"))
// , approxAccuracyPct(approxAccuracyPct>=0 ? approxAccuracyPct : throw std::invalid_argument("Approximation accuracy percentage can't be negative."))
//{
//}
std::vector<std::vector<cv::Point>> AbstractPaperSheetDetector::refineContours(const std::vector<std::vector<cv::Point>>& contours, const cv::Mat &image) const
{
const double imageArea = 1.0 * image.cols * image.rows;
std::vector<std::vector<cv::Point>> refinedContours;
for (const auto& contour : contours)
{
std::vector<cv::Point> contourApprox;
cv::approxPolyDP(contour, contourApprox, this->approxAccuracyPct * cv::arcLength(contour, true), true);
if (contourApprox.size() != 4 || !cv::isContourConvex(contourApprox))
continue;
double approxArea = cv::contourArea(contourApprox, false);
//if (approxArea < 0.5*imageArea || approxArea > 0.99*imageArea)
if (approxArea < this->minAreaPct*imageArea || approxArea > this->maxAreaPct*imageArea)
continue;
refinedContours.push_back(std::move(contourApprox));
} // for each contour
return refinedContours;
}
std::vector<cv::Point> AbstractPaperSheetDetector::selectBestCandidate(const std::vector<std::vector<cv::Point>>& candidates) const
{
if (candidates.empty())
throw std::runtime_error("The list of candidates is empty.");
for (int i = 1; i < candidates.size(); ++i)
if (candidates[i].size() != candidates[i-1].size())
throw std::runtime_error("The candidates have different number of vertices.");
std::vector<double> rank(candidates.size(), 0);
int bestCandIdx = 0;
for (int i = 0; i < candidates.size(); ++i)
{
for (int j = 0; j < candidates.size(); ++j)
{
if (i == j)
continue;
double maxDist = 0;
for (int v = 0; v < candidates[i].size(); ++v)
{
double d = cv::norm(candidates[j][v] - candidates[i][v]);
maxDist = std::max(d, maxDist);
} // v
rank[i] += std::exp(-maxDist);
} // j
if (rank[i] > rank[bestCandIdx])
bestCandIdx = i;
} // i
// Another working option
/*
std::vector<int> rank(candidates.size(), 0);
int bestCandIdx = 0;
for (int i = 0; i < candidates.size(); ++i)
{
for (int j = 0; j < candidates.size(); ++j)
{
if (i == j)
continue;
double maxDist = 0;
for (int v = 0; v<4; ++v)
{
double d = cv::norm(candidates[j][v] - candidates[i][v]);
maxDist = std::max(d, maxDist);
} // v
if (maxDist < 10)
{
++rank[i];
if (rank[i] > rank[bestCandIdx])
bestCandIdx = i;
}
} // j
} // i
*/
return candidates[bestCandIdx];
} // selectBestCandidate
| true |
a4e55fa61d26e3f4f91a6f95ffadd552b7eeeb9b | C++ | strengthen/LeetCode | /C++/682.cpp | UTF-8 | 2,555 | 2.828125 | 3 | [
"MIT"
] | permissive | __________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
int calPoints(vector<string>& ops) {
std::stack<int> opS;
int sum {0};
for (const auto& op : ops) {
if (op == "C") {
if (!opS.empty()) {
int top = opS.top();
sum -= top;
opS.pop();
}
} else if (op == "D") {
if (!opS.empty()) {
int top = opS.top();
opS.push(top*2);
sum += (opS.top());
}
} else if (op == "+") {
int top0 {0}, top0Flag {0};
int top1 {0}, top1Flag {0};
if (!opS.empty()) {
top0 = opS.top();
top0Flag = 1;
opS.pop();
}
if (!opS.empty()) {
top1 = opS.top();
top1Flag = 1;
opS.pop();
}
if (top1Flag == 1) {
opS.push(top1);
}
if (top0Flag == 1) {
opS.push(top0);
}
opS.push(top0 + top1);
sum += opS.top();
} else {
int opV = std::stoi(op);
sum += opV;
opS.push(opV);
}
}
return sum;
}
};
static int _ = [](){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cerr.tie(0);
return 0;
}();
__________________________________________________________________________________________________
sample 9316 kb submission
class Solution {
public:
int calPoints(vector<string>& ops) {
int n=ops.size();
int arr[n];
int top=-1;
for(int i=0;i<n;i++)
{
if(ops[i]=="C")
top--;
else if(ops[i]=="D")
{
arr[top+1]=2*arr[top];
top++;
}
else if(ops[i]=="+")
{
arr[top+1]=arr[top]+arr[top-1];
top++;
}
else
arr[++top]=stoi(ops[i]);
}
int sum=0;
for(int i=0;i<=top;i++)
{
sum+=arr[i];
}
return sum;
}
};
__________________________________________________________________________________________________
| true |
3c138a0a7c77356bec8178de7ddfc57633978f2d | C++ | dom380/IMAT3606-Coursework-2 | /include/Graphics/ModelComponent.h | UTF-8 | 3,241 | 2.6875 | 3 | [
"MIT",
"CC-BY-2.0",
"Zlib",
"CC-BY-3.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | #pragma once
#ifndef MODELCOMPONENT_H
#define MODELCOMPONENT_H
#include "Graphics\stb_image.h"
#include "Graphics\Bitmap.h"
#include "Graphics\Texture.h"
#include <Camera\Camera.h>
#include "utils\ObjReader.h"
#include "Renderers\Graphics.h"
#include "GL\glm\glm\glm.hpp"
#include "Shader.h"
#include "Graphics\Transform.h"
#include <vector>
using std::vector;
#include "AssetManager.h"
#include <Graphics\Material.h>
#include "Components\Component.h"
#include "Components\RenderMessage.h"
#include "GameObject.h"
/*
Component representing a GameObject's model and texture.
*/
class ModelComponent : public Component {
public:
/*
Constructor.
shared_ptr<Graphics>& graphics, Pointer to the Graphics system.
std::weak_ptr<GameObject> owner, Weak Pointer to the GameObject that owns this model.
*/
ModelComponent(shared_ptr<Graphics>& graphics, std::weak_ptr<GameObject> owner);
~ModelComponent();
/*
Method to load the model data and texture if supplied.
const char* objFile, The relative path to the model data file from the 'modelLocation' property defined in configuration.
const char* textureFile, The relative path to the texture file from the 'textureLocation' property defined in configuration. NULL is interprated as not having a texture file.
*/
void init(const char* objFile, const char* textureFile, string id = "");
/*
Empty implementation of Component::update()
*/
void update(double dt);
/*
Calls to the graphics system to render this model if the MessageType is RENDER. Ignores all others.
If the MessageType is RENDER it must be safely castable to a RenderMessage pointer.
Message* msg, The message to handle.
*/
void RecieveMessage(Message* msg);
/*
Returns a pointer to the models texture. Can be null.
*/
shared_ptr<Texture> getTexture();
/*
Returns the ID of the VertexArrayObject containing this models data on the GPU.
If the VertexArrayObject has not been created at this point it will be build and returned here.
*/
unsigned int getVertArray();
/*
Returns the number of indices of this model.
*/
size_t getIndexSize();
/*
Returns the models material.
*/
Material getMaterial();
/*
Returns a pointer to the models Transform object.
*/
shared_ptr<Transform> transform;
string getId();
/*
Toggles the drawing flag to enable and disable rendering of this model.
*/
void toggleDrawing();
/*
Returns true if drawing enabled.
*/
bool isDrawing();
private:
//Private Methods
//Calls to Graphics system to render this model. Parameters supplied by RENDER messages. (see RecieveMessage())
void render(shared_ptr<Camera>& camera);
void render(shared_ptr<Camera>& camera, vector<Light> lights);
void render(shared_ptr<Camera>& camera, unsigned int lightingBuffer, unsigned int lightingBlockId);
//Private members
bool initalised = false;
shared_ptr<Graphics> graphics;
std::weak_ptr<GameObject> owner;
unsigned int verticesId;
unsigned int texCoordsId;
unsigned int normalsId;
unsigned int indexId;
unsigned int textureId;
size_t indexSize;
vector<unsigned int> vboHandles;
unsigned int vaoHandle = 0;
shared_ptr<Shader> shader;
shared_ptr<Texture> texture;
Material material;
string id;
bool drawing = true;
};
#endif // !MODEL_H
| true |
f7e010863755c94e1f35120c3164d3b55fb980f6 | C++ | lsmmay322/BaekJoon | /9465.cpp | UTF-8 | 657 | 2.515625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define MAX(a, b) (a > b) ? a : b
int dp[2][100001];
int main()
{
int t, n;
int res = 0;
scanf("%d", &t);
for (int i = 0; i < t; i++)
{
scanf("%d", &n);
for (int j = 0; j <= 1; j++)
{
for (int k = 0; k < n; k++)
scanf("%d", &dp[j][k]);
}
dp[0][1] += dp[1][0];
dp[1][1] += dp[0][0];
for (int j = 2; j < n; j++)
{
for (int k = 0; k < 2; k++)
{
if (k == 0)
dp[k][j] += MAX(dp[k + 1][j - 1], dp[k + 1][j - 2]);
if (k == 1)
dp[k][j] += MAX(dp[k - 1][j - 1], dp[k - 1][j - 2]);
}
}
res = MAX(dp[0][n - 1], dp[1][n - 1]);
cout << res << endl;
}
return 0;
}
| true |
4cf57cb8fddfe32e1f5a01a0960e9670d51ff552 | C++ | hanhiver/mycpp11 | /Concurrency/promise/promise.cpp | UTF-8 | 792 | 3.6875 | 4 | [] | no_license | #include <iostream> // std::cout, std::endl;
#include <thread> // std::thread
#include <string> // std::string
#include <future> // std::promise, std::future
#include <chrono> // seconds
void read(std::future<std::string> *future)
{
// Future will block untill its value set.
std::cout << future->get() << std::endl;
}
int main()
{
// Promise is a producer here.
std::promise<std::string> promise;
// Future is a consumer here.
std::future<std::string> future = promise.get_future();
// Start the read thread.
std::thread thread(read, &future);
// Wait for a while.
std::this_thread::sleep_for(std::chrono::seconds(1));
// Set the promise value.
promise.set_value("Hello future! \n");
thread.join();
return 0;
} | true |
86ddf2e8097d086b9d3945f690fe151a2c544f19 | C++ | windystrife/UnrealEngine_NVIDIAGameWorks | /Engine/Source/Runtime/MovieScene/Public/Evaluation/PersistentEvaluationData.h | UTF-8 | 9,336 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Stats/Stats.h"
#include "MovieSceneFwd.h"
#include "Evaluation/MovieSceneEvaluationKey.h"
#include "Evaluation/MovieSceneEvaluationOperand.h"
/**
* Unique identifier for shared persistent data entries (see FSharedPersistentDataKey)
*/
struct FMovieSceneSharedDataId
{
/**
* Allocate a new unique identifier
*/
static MOVIESCENE_API FMovieSceneSharedDataId Allocate();
FMovieSceneSharedDataId(const FMovieSceneSharedDataId&) = default;
FMovieSceneSharedDataId& operator=(const FMovieSceneSharedDataId&) = default;
friend bool operator==(FMovieSceneSharedDataId A, FMovieSceneSharedDataId B) { return A.UniqueId == B.UniqueId; }
friend uint32 GetTypeHash(FMovieSceneSharedDataId In) { return GetTypeHash(In.UniqueId); }
private:
FMovieSceneSharedDataId() {}
uint32 UniqueId;
};
/**
* A key to a piece of data that is potentially shared between multiple tracks
*/
struct FSharedPersistentDataKey
{
/**
* Construction from a shared data ID, and an operand
*/
FSharedPersistentDataKey(FMovieSceneSharedDataId InUniqueId, const FMovieSceneEvaluationOperand& InOperand)
: UniqueId(InUniqueId)
, Operand(InOperand)
{}
friend bool operator==(const FSharedPersistentDataKey& A, const FSharedPersistentDataKey& B)
{
return A.UniqueId == B.UniqueId && A.Operand == B.Operand;
}
friend uint32 GetTypeHash(const FSharedPersistentDataKey& In)
{
return HashCombine(GetTypeHash(In.Operand), GetTypeHash(In.UniqueId));
}
/** The actual shared ID */
FMovieSceneSharedDataId UniqueId;
/** The operand that this key relates to (may be invalid where the data pertains to master tracks) */
FMovieSceneEvaluationOperand Operand;
};
/**
* Interface that must be used for all persistent data objects
*/
struct IPersistentEvaluationData
{
virtual ~IPersistentEvaluationData(){}
};
DECLARE_CYCLE_STAT(TEXT("Persistent Data Access"), MovieSceneEval_PersistentData_Access, STATGROUP_MovieSceneEval);
/**
* Structure that stores persistent data that track templates may need during evaluation.
* Such data can be thought of as a cache which exists as long as the track is being evaluated.
* The cache can store any abstract data provided it implements IPersistentEvaluationData.
* Data is stored in buckets that is keyed on either the track (ie, accessible from all child templates/sections), or section (only accessible within the section)
* Type-safety (through the templated methods) is the responsibility of the user. There should only ever be 1 type of data for each section/track association.
*/
struct FPersistentEvaluationData
{
/**
* Proxy constructor from 2 externally owned maps for entity, and shared data
*/
FPersistentEvaluationData(TMap<FMovieSceneEvaluationKey, TUniquePtr<IPersistentEvaluationData>>& InEntityData, TMap<FSharedPersistentDataKey, TUniquePtr<IPersistentEvaluationData>>& InSharedData)
: EntityData(InEntityData)
, SharedData(InSharedData)
{}
FPersistentEvaluationData(const FPersistentEvaluationData&) = delete;
FPersistentEvaluationData& operator=(const FPersistentEvaluationData&) = delete;
public:
/**
* User accessor functions for persistent data relating to the current track
*/
template<typename T> T& GetOrAddTrackData() { return GetOrAdd<T>(TrackKey); }
template<typename T> T& AddTrackData() { return Add<T>(TrackKey); }
template<typename T> T& GetTrackData() { return Get<T>(TrackKey); }
template<typename T> T* FindTrackData() { return Find<T>(TrackKey); }
/**~ Section data access is considered const as it can only ever be accessed from a single template (it can do whatever it likes with its own data) */
template<typename T> T& GetTrackData() const { return Get<T>(TrackKey); }
template<typename T> T* FindTrackData() const { return Find<T>(TrackKey); }
void ResetTrackData() { Reset(TrackKey); }
/**
* User accessor functions for persistent data relating to the current section
*/
template<typename T> T& GetOrAddSectionData() { return GetOrAdd<T>(SectionKey); }
template<typename T> T& AddSectionData() { return Add<T>(SectionKey); }
/**~ Section data access is considered const as it can only ever be accessed from a single template (it can do whatever it likes with its own data) */
template<typename T> T& GetSectionData() const { return Get<T>(SectionKey); }
template<typename T> T* FindSectionData() const { return Find<T>(SectionKey); }
void ResetSectionData() { Reset(SectionKey); }
public:
/**
* Get the currently set track key (ie the track we're currently evaluating)
*/
const FMovieSceneEvaluationKey& GetTrackKey() const
{
return TrackKey;
}
/**
* Get the currently set section key (ie the section we're currently evaluating)
*/
const FMovieSceneEvaluationKey& GetSectionKey() const
{
return SectionKey;
}
/**
* Set the current track
*/
void SetTrackKey(const FMovieSceneEvaluationKey& Key) const
{
TrackKey = Key;
}
/**
* Set the current section
*/
void SetSectionKey(const FMovieSceneEvaluationKey& Key) const
{
SectionKey = Key;
}
/**
* Set the current section based off the current track with the specified section identifier
*/
const FMovieSceneEvaluationKey& DeriveSectionKey(uint32 InSectionIdentifier) const
{
SectionKey = TrackKey.AsSection(InSectionIdentifier);
return SectionKey;
}
public:
/**
* User accessor functions for shared data keys
*/
template<typename T>
T& GetOrAdd(const FSharedPersistentDataKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
if (TUniquePtr<IPersistentEvaluationData>* Existing = SharedData.Find(InKey))
{
return static_cast<T&>(*Existing->Get());
}
return Add<T>(InKey);
}
template<typename T>
T& Add(const FSharedPersistentDataKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
T* Ptr = new T;
SharedData.Add(InKey, TUniquePtr<IPersistentEvaluationData>(Ptr));
return *Ptr;
}
template<typename T>
T* Find(const FSharedPersistentDataKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
TUniquePtr<IPersistentEvaluationData>* Existing = SharedData.Find(InKey);
return Existing ? static_cast<T*>(Existing->Get()) : nullptr;
}
template<typename T>
const T* Find(const FSharedPersistentDataKey& InKey) const
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
const TUniquePtr<IPersistentEvaluationData>* Existing = SharedData.Find(InKey);
return Existing ? static_cast<const T*>(Existing->Get()) : nullptr;
}
template<typename T>
T& Get(const FSharedPersistentDataKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
T* Ptr = Find<T>(InKey);
check(Ptr);
return *Ptr;
}
template<typename T>
const T& Get(const FSharedPersistentDataKey& InKey) const
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
const T* Ptr = Find<T>(InKey);
check(Ptr);
return *Ptr;
}
void Reset(const FSharedPersistentDataKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
SharedData.Remove(InKey);
}
private:
/** Implementation methods */
template<typename T>
T& GetOrAdd(const FMovieSceneEvaluationKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
if (TUniquePtr<IPersistentEvaluationData>* Existing = EntityData.Find(InKey))
{
return static_cast<T&>(*Existing->Get());
}
return Add<T>(InKey);
}
template<typename T>
T& Add(const FMovieSceneEvaluationKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
T* Ptr = new T;
EntityData.Add(InKey, TUniquePtr<IPersistentEvaluationData>(Ptr));
return *Ptr;
}
template<typename T>
T* Find(const FMovieSceneEvaluationKey& InKey) const
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
const TUniquePtr<IPersistentEvaluationData>* Existing = EntityData.Find(InKey);
return Existing ? static_cast<T*>(Existing->Get()) : nullptr;
}
template<typename T>
T& Get(const FMovieSceneEvaluationKey& InKey) const
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
T* Ptr = Find<T>(InKey);
check(Ptr);
return *Ptr;
}
void Reset(const FMovieSceneEvaluationKey& InKey)
{
MOVIESCENE_DETAILED_SCOPE_CYCLE_COUNTER(MovieSceneEval_PersistentData_Access)
EntityData.Remove(InKey);
}
private:
/** Persistent data that's associated with a template entity (such as a track or a section) */
TMap<FMovieSceneEvaluationKey, TUniquePtr<IPersistentEvaluationData>>& EntityData;
/** Persistent data that's shared across multiple template entities */
TMap<FSharedPersistentDataKey, TUniquePtr<IPersistentEvaluationData>>& SharedData;
// The keys themselves are mutable since this a proxy representation of the data above.
// For a const FPersistentEvaluationData& we can change the ptr to the persistent data, but we can't change the data itself (as with a const T*)
mutable FMovieSceneEvaluationKey TrackKey;
mutable FMovieSceneEvaluationKey SectionKey;
};
| true |
3853a4d53b8d1442d9437f7d0da5147733f0dcea | C++ | SinnerA/difftool | /diffstdout/diffstdout.cpp | UTF-8 | 2,934 | 2.765625 | 3 | [] | no_license | // diffstdout.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Templates.h"
#include "FilePartition.h"
#include "DiffEngine.h"
// helper
//
// purpose:tells us whether the file exists
BOOL FileExists(CString &szFilename)
{
BOOL bFound = FALSE;
WIN32_FIND_DATA findFile;
HANDLE hContext;
hContext=::FindFirstFile(szFilename.GetBuffer(0), &findFile);
if ( hContext != INVALID_HANDLE_VALUE )
{
::FindClose(hContext);
bFound = TRUE;
}
return bFound;
}
BOOL IsAFolder(CString &szFilename)
{
if (!FileExists(szFilename)) return FALSE;
BOOL bIsADirectory = FALSE;
WIN32_FIND_DATA findFile;
HANDLE hContext;
hContext=::FindFirstFile(szFilename.GetBuffer(0), &findFile);
if ( hContext != INVALID_HANDLE_VALUE )
{
if (findFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
bIsADirectory = TRUE;
::FindClose(hContext);
}
return bIsADirectory;
}
int main(int argc, char* argv[])
{
CString szFile1, szFile2, szOutfile;
if (argc<3)
{
printf( _T("usage: diffstdout.exe [-c] [-i] <file1> <file2> [<outfilename>]\r\nexample diffstdout.exe bookshop.4.xml bookshop.5.xml diff.html") );
return 0;
}
BOOL bCaseOption = TRUE;
BOOL bIndentOption = TRUE;
// get cmdline parameters
int iStart = 0;
for (int i = 1; i < argc; i++)
{
LPTSTR pszParam = argv[i];
if (stricmp(pszParam,"-c")==0)
{
bCaseOption = FALSE;
iStart++;
}
else if (stricmp(pszParam,"-i")==0)
{
bIndentOption = FALSE;
iStart++;
}
else
{
switch (i-iStart)
{
case 1 : szFile1 = pszParam; break;
case 2 : szFile2 = pszParam; break;
case 3 : szOutfile = pszParam; break;
}
}
}
// make sure those files exist
if ( !FileExists(szFile1) )
{
printf(_T("%s does not exist."), szFile1.GetBuffer(0) );
return FALSE;
}
if ( !FileExists(szFile2) )
{
printf(_T("%s does not exist."), szFile2.GetBuffer(0) );
return FALSE;
}
// process files
CFileOptions o;
if (!bCaseOption) o.SetOption( CString("case"), CString("no") );
if (!bIndentOption) o.SetOption( CString("indent"), CString("no") );
CFilePartition f1;
CFilePartition f2;
BOOL bFile1IsAFolder = IsAFolder(szFile1);
BOOL bFile2IsAFolder = IsAFolder(szFile2);
if ( bFile1IsAFolder && bFile2IsAFolder )
{
// process folders
f1.PreProcessFolder( szFile1, o );
f2.PreProcessFolder( szFile2, o );
}
else if ( !bFile1IsAFolder && !bFile2IsAFolder)
{
// process files
f1.PreProcess( szFile1, o );
f2.PreProcess( szFile2, o );
}
else
{
// error (folder and a file cannot match, anyway)
printf(_T("%s cannot be compared with %s."), szFile1.GetBuffer(0), szFile2.GetBuffer(0) );
return 0;
}
CFilePartition f1_bis, f2_bis;
CDiffEngine d;
d.Diff(f1,f2,f1_bis,f2_bis);
if ( szOutfile.IsEmpty() ) // default output
d.ExportAsStdout( d.Serialize(f1_bis, f2_bis) );
else
d.ExportAsHtml(szOutfile, d.Serialize(f1_bis, f2_bis) );
return 0;
}
| true |
13813e59717fc84865ac60ea416dbb017d931ef4 | C++ | Gleeber/ebml_parser | /main.cpp | UTF-8 | 9,579 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <bitset>
#include <vector>
#include <array>
#include <chrono>
#include <iomanip>
#include <unistd.h> // requires unix
#include <time.h>
using std::cout;
using std::string;
using std::endl;
using std::hex;
using std::ostream;
using std::array;
using std::bitset;
using std::dec;
using std::fixed;
using std::time_t;
using std::strcmp;
#define BUFSIZE 1048576 // 1MB = 1024^2
enum ebml_element_type { // posible data types
MASTER, // other EBL sub-elemnts of next lower level
UINT, // unsigned integer, 1 to 8 bytes
INT, // signed integer, 1 to 8 bytes
STRING, // ASCII characters 0x20 to 0x7E
UTF8, // unicode, padded with zeros
BINARY, // not parsed
FLOAT, // big-endian, 4 and 8 bytes (32 or 64 bits)
DATE // signed 8 byte integer in nanoseconds
};
class simple_vint{
public:
uint8_t width;
uint8_t data[8];
bool is_all_ones(){ // check if data is 255 (0xFF )
for(int i = 1; i < width - 1; i++){
if(data[i] != 255){
return false;
}
}
return true;
}
uint64_t get_uint(){ // convert data to unsigned into - big endian
uint64_t value = 0;
value = data[width - 1];
for(int i = width - 1; i > 0; --i){
value += ((uint64_t)data[i - 1] << ((width - i) * 8));
}
return value;
}
};
class ebml_element{ // ebml element defined using data from spec.cpp
public:
string name;
array<uint8_t, 4> id;
enum ebml_element_type type;
ebml_element(string name, array<uint8_t, 4> const& id, enum ebml_element_type type)
:name(name), id(id), type(type){}
};
const int SPEC_LEN = 250; // number of types of ebml elements
#include "spec.cpp" // include embl element data strcture
// compares data to spec.cpp to find which ebml element the data is
ebml_element* get_element(array<uint8_t, 4> id, uint8_t level){
bool found;
for(int i = 0; i < SPEC_LEN; ++i){
found = true;
for(int j = 0; j < level; ++j){ // check for matching id
if(ebml_spec[i]->id[j] != id[j]){
found = false;
break;
}
}
if(found){ // if found return the element info
return ebml_spec[i];
}
}
return 0;
}
// logging stuff
// if verbose = true then prints bits of data
bool verbose = false;
typedef ostream& (*manip) (ostream&);
class verbose_log{};
template <class T> verbose_log& operator<< (verbose_log& l, const T& x){
if(verbose)
cout << x;
return l;
}
verbose_log& operator<< (verbose_log& l, manip manipulator){
if(verbose)
cout << manipulator;
return l;
}
verbose_log vlog;
class ebml_parser{
public:
void parse(int fd){
int len, mask, pos = 0;
uint8_t buffer[BUFSIZE];
bitset<8> bits;
while(1){
// Get EBML Element ID first byte.
if((len = read(fd, buffer, 1)) < 0){ // check if read length is less than zero
cout << "Uh oh, read first id byte error!\n"; // exit if so
break;
}else if(len == 0){ // check if read length is zero
cout << "DONE!" << endl; // reached end of file
break;
}
pos++; // increment pos
if(buffer[0] == 0){ // skip until buffer is non zero
cout << "Read '0' byte..." << endl;
continue;
}
bits = bitset<8>(buffer[0]);
vlog << "Element ID First Byte: " << bits << endl;
simple_vint id;
id.width = 1;
mask = 0x80;
// Get EBML Element ID vint width.
while(!(buffer[0] & mask)){
mask >>= 1;
id.width++;
}
id.data[0] = buffer[0];
// Get EBML Element ID vint data.
if((len = read(fd, buffer, id.width - 1)) != id.width - 1){
cout << "Uh oh, read id data error!\n";
break;
}
pos += id.width - 1;
vlog << "Element ID Bytes: " << bits;
// Get EBML Element ID.
for(int i = 1; i < id.width; ++i){
id.data[i] = buffer[i - 1];
bits = bitset<8>(buffer[i]);
vlog << ' ' << bits;
}
vlog << endl;
if(verbose){
vlog << "Element ID: 0x";
for(int i = 0; i < id.width; ++i){
vlog << hex << (int)id.data[i];
}
vlog << endl;
}
// Get EBML Element Size first byte.
if((len = read(fd, buffer, 1)) != 1){
cout << "Uh oh, read first size byte error!\n";
break;
}
pos++;
bits = bitset<8>(buffer[0]);
vlog << "Element Size First Byte: " << bits << endl;
simple_vint size;
size.width = 1;
mask = 0x80;
// Get EBML Element Size vint width.
while(!(buffer[0] & mask)){
mask >>= 1;
size.width++;
}
buffer[0] ^= mask;
size.data[0] = buffer[0];
// Get EBML Element Size vint data.
if((len = read(fd, buffer, size.width - 1)) != size.width - 1){
cout << "Uh oh, read id data error!\n";
break;
}
pos += size.width - 1;
bits = bitset<8>(size.data[0]);
vlog << "Element Size Bytes: " << bits;
// Get EBML Element Size.
for(int i = 1; i < size.width; ++i){
size.data[i] = buffer[i - 1];
bits = bitset<8>(buffer[i]);
vlog << ' ' << bits;
}
vlog << endl;
vlog << "Element Size: " << dec << size.get_uint() << endl;
// Specification for ID lookup.
ebml_element* e = get_element(
{{id.data[0], id.data[1], id.data[2], id.data[3]}},
id.width);
vlog << "--------------------------------------------------------" << endl; // after this line the parser prints
// the data based on the ebml element type
if(e != 0){
if(e->type != MASTER){
// Get EBML Element Data, parse it.
uint64_t data_len = size.get_uint();
if((len = read(fd, buffer, data_len) != data_len)){
cout << "Uh oh, could not read all the data!" << endl;
cout << "Wanted " << data_len << " found " << len << endl;
break;
}
pos += data_len;
cout << '(' << dec << pos << ") " << e->name << ": ";
if(e->type == STRING || e->type == UTF8){
for(int i = 0; i < data_len; ++i){
cout << buffer[i];
}
cout << endl;
}else if(e->type == BINARY){
for(int i = 0; i < data_len; ++i){
// I'll only care about the first 32 binary bytes.
if(i == 32 && !verbose){
cout << "...";
break;
}
cout << hex << (int)buffer[i];
}
cout << endl;
if(e->name == "SimpleBlock" || e->name == "Block"){
bits = bitset<8>(buffer[0]);
vlog << "Block First Byte: " << bits << endl;
simple_vint track_number;
track_number.width = 1;
mask = 0x80;
while(!(buffer[0] & mask)){
mask >>= 1;
track_number.width++;
}
buffer[0] ^= mask;
vlog << "Block Track Number Bytes: " << endl;
for(int i = 0; i < track_number.width; ++i){
bits = bitset<8>(buffer[i]);
vlog << bits << ' ';
track_number.data[i] = buffer[i];
}
cout << "Track Number: " << dec << (int)track_number.get_uint() << endl;
int16_t timecode = (int16_t)(((uint16_t)buffer[track_number.width] << 8) | buffer[track_number.width + 1]);
cout << "Timecode: " << dec << (int)timecode << endl;
}
}else if(e->type == UINT){
simple_vint data;
data.width = 0;
for(int i = 0; i < data_len; ++i){
data.data[i] = buffer[i];
data.width++;
}
uint64_t val = data.get_uint();
cout << dec << val;
if(e->id[0] == 0x83){
if(val == 1){
cout << " (video)";
}else if(val == 2){
cout << " (audio)";
}else if(val == 3){
cout << " (complex)";
}
}
cout << endl;
}else if(e->type == FLOAT){
simple_vint data;
data.width = 0;
for(int i = 0; i < data_len; ++i){
data.data[i] = buffer[i];
data.width++;
}
int64_t int_val = int64_t(data.get_uint());
if(data.width == 4){
float float_val;
memcpy(&float_val, &int_val, 4);
cout << fixed << dec << float_val;
}else if(data.width == 8){
double double_val;
memcpy(&double_val, &int_val, 8);
cout << fixed << dec << double_val;
}else{
cout << "Bad float width:: " << dec << (int)data.width;
}
cout << endl;
}else if(e->type == DATE){
simple_vint data;
data.width = 0;
for(int i = 0; i < data_len; ++i){
data.data[i] = buffer[i];
data.width++;
}
// This is a time_t struct composed of:
// time point 0 (Jan 1 1970)
// nanoseconds to millenium (Jan 1 2001)
// nanoseconds to date file was created.
time_t date_val = std::chrono::system_clock::to_time_t(std::chrono::system_clock::time_point::time_point() + std::chrono::nanoseconds(978307200000000000) + std::chrono::nanoseconds(int64_t(data.get_uint())));
// This is the local time; PST in San Francisco, -7h or something.)
//cout << ctime(&date_val);
// This is the UTC time.
cout << asctime(gmtime(&date_val));
}else if(e->type == INT){
simple_vint data;
data.width = 0;
for(int i = 0; i < data_len; ++i){
data.data[i] = buffer[i];
data.width++;
}
cout << dec << int64_t(data.get_uint()) << endl;
}else{
for(int i = 0; i < data_len; ++i){
cout << hex << (int)buffer[i];
}
cout << endl;
}
}else{
// Master data is actually just more elements, continue.
cout << '(' << dec << pos << ')' << " ----- " << e->name << " [";
if(size.is_all_ones()){
cout << "Unknown";
}else{
cout << size.get_uint();
}
cout << ']' << endl;
}
}else{
cout << "UNKNOWN ELEMENT!" << endl;
}
vlog << "--------------------------------------------------------" << endl;
}
}
};
int main(int argc, char** argv){
for(int i = 0; i < argc; i++){
if(strcmp(argv[i], "-v") == 0){
verbose = true;
}
}
ebml_parser p;
p.parse(STDIN_FILENO);
return 0;
} | true |
5e82883f4ec7e506861fad779aac8df60a3bb7b9 | C++ | sgzwiz/xbox_leak_may_2020 | /xbox_leak_may_2020/xbox trunk/xbox/private/atg/samples/misc/sectionload/sectionload.cpp | UTF-8 | 9,757 | 2.625 | 3 | [] | no_license | //-----------------------------------------------------------------------------
// File: SectionLoad.cpp
//
// Desc: Illustrates loading and unloading of sections.
//
// Note: This was a somewhat difficult sample to write. Especially because
// samples are by definition very small bits of code meant only to
// illustrate one particular part of the system.
//
// Section loading and unloading is something that will be used
// primarily in large projects where memory restrictions prevent you
// from having all code and data loaded simultaneously. Furthermore,
// flagging a section as NOPRELOAD only works if that section cannot
// be squeezed into a preloaded section. Thus, when I tried to write
// a couple of small routines that were loaded and unloaded, they were
// squeezed in to the end of a preloaded section and the code would
// always execute (as they were always in memory).
//
// As a result, this sample shows that section loading and unloading
// work properly by doing the following: If the data section is
// loaded, write access to the data area will work just fine and
// the sample shows the time of the last successful access.
// If the data section is not loaded, accessing the data area will
// generate an exception.
//
// This is not the best behaviour for a sample, I know. But it was
// the only way to verify that unloaded sections did not work. Note
// that you should only run this in DEBUG mode so you can see what
// is going on!
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include <XBApp.h>
#include <XBFont.h>
#include <XBHelp.h>
#include <XBMesh.h>
#include "resource.h"
//-----------------------------------------------------------------------------
// ASCII names for the resources used by the app
//-----------------------------------------------------------------------------
XBRESOURCE g_ResourceNames[] =
{
{ "Wings.bmp", resource_Wings_OFFSET },
{ "BiHull.bmp", resource_BiHull_OFFSET },
{ NULL, 0 },
};
//-----------------------------------------------------------------------------
// Help screen definitions
//-----------------------------------------------------------------------------
XBHELP_CALLOUT g_HelpCallouts[] =
{
{ XBHELP_BACK_BUTTON, XBHELP_PLACEMENT_1, L"Display\nhelp" },
{ XBHELP_A_BUTTON, XBHELP_PLACEMENT_1, L"Toggle DataSeg\nLoaded" },
{ XBHELP_B_BUTTON, XBHELP_PLACEMENT_1, L"Attempt DataSeg\nAccess" },
};
#define NUM_HELP_CALLOUTS 3
//-----------------------------------------------------------------------------
// put some data in another section
// note that uninitialize sections will always be flagged as preload
//-----------------------------------------------------------------------------
#define BUFSIZE (32*1024)
#pragma data_seg("dataseg1")
BYTE g_Seg1Data[BUFSIZE] = {0};
BYTE g_Seg1Data1[BUFSIZE] = {0};
BYTE g_Seg1Data2[BUFSIZE] = {0};
#pragma data_seg()
//-----------------------------------------------------------------------------
// Name: class CXBoxSample
// Desc: Main class to run this application. Most functionality is inherited
// from the CXBApplication base class.
//-----------------------------------------------------------------------------
class CXBoxSample : public CXBApplication
{
CXBFont m_Font;
CXBHelp m_Help;
BOOL m_bDrawHelp;
CXBPackedResource m_xprResource;
CXBMesh *m_pPlaneMesh;
BOOL m_bDataSegLoaded;
float m_fDataSegAccessTime;
public:
HRESULT Initialize();
HRESULT FrameMove();
HRESULT Render();
CXBoxSample();
};
//-----------------------------------------------------------------------------
// Name: main()
// Desc: Entry point to the program.
//-----------------------------------------------------------------------------
VOID __cdecl main()
{
CXBoxSample xbApp;
if( FAILED( xbApp.Create() ) )
return;
xbApp.Run();
}
//-----------------------------------------------------------------------------
// Name: CXBoxSample()
// Desc: Constructor
//-----------------------------------------------------------------------------
CXBoxSample::CXBoxSample()
:CXBApplication()
{
// initialize our stuff
m_bDrawHelp = FALSE;
m_bDataSegLoaded = FALSE;
m_fDataSegAccessTime = 0.0f;
}
//-----------------------------------------------------------------------------
// Name: Initialize()
// Desc: Initialize device-dependant objects.
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::Initialize()
{
D3DXMATRIX matProj, matView;
// Create a font
if( FAILED( m_Font.Create( m_pd3dDevice, "Font.xpr" ) ) )
return XBAPPERR_MEDIANOTFOUND;
// Initialize the help system
if( FAILED( m_Help.Create( m_pd3dDevice, "Gamepad.xpr" ) ) )
return XBAPPERR_MEDIANOTFOUND;
// Set projection transform
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 640.0f/480.0f, 0.1f, 100.0f );
m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
// Set view position
D3DXMatrixTranslation( &matView, 0.0f, 0.0f, 60.0f);
m_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
// Create the resources
if( FAILED( m_xprResource.Create( m_pd3dDevice, "Resource.xpr",
resource_NUM_RESOURCES, g_ResourceNames ) ) )
return XBAPPERR_MEDIANOTFOUND;
// initialize the airplanes
m_pPlaneMesh = new CXBMesh;
m_pPlaneMesh ->Create(g_pd3dDevice, "models\\airplane.xbg", &m_xprResource );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FrameMove()
// Desc: Called once per frame, the call is the entry point for animating
// the scene.
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::FrameMove()
{
D3DXMATRIX matWorld, m;
static float fYRot = 0.0f;
float x, z;
VOID *loc;
DWORD i, d;
// Toggle help
if( m_DefaultGamepad.wPressedButtons&XINPUT_GAMEPAD_BACK )
m_bDrawHelp = !m_bDrawHelp;
if(m_bDrawHelp)
return S_OK;
// Toggle dataseg load
if( m_DefaultGamepad.bPressedAnalogButtons[XINPUT_GAMEPAD_A])
{
// if not loaded, do the load
if(!m_bDataSegLoaded)
{
loc = XLoadSection("dataseg1");
if(loc!=NULL)
m_bDataSegLoaded = TRUE;
}
else // otherwise, free it up
{
XFreeSection("dataseg1");
m_bDataSegLoaded = FALSE;
}
}
// attempt dataseg read
if( m_DefaultGamepad.bPressedAnalogButtons[XINPUT_GAMEPAD_B])
{
for(i=0; i<BUFSIZE; i++)
{
d = g_Seg1Data[i];
d = g_Seg1Data1[i];
d = g_Seg1Data2[i];
}
m_fDataSegAccessTime = m_fTime;
}
// move plane
fYRot += 1.57f*m_fElapsedTime;
D3DXMatrixRotationY(&matWorld, fYRot);
x = 20.0f * (float)cos(fYRot);
z = -20.0f * (float)sin(fYRot);
D3DXMatrixTranslation(&m, x, 0.0f, z);
D3DXMatrixMultiply(&matWorld, &matWorld, &m);
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Called once per frame, the call is the entry point for 3d
// rendering. This function sets up render states, clears the
// viewport, and renders the scene.
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::Render()
{
// Clear the viewport
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
0x00400000, 1.0f, 0L );
// Restore state that text clobbers
m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
m_pPlaneMesh->Render(0);
// Show title, frame rate, and help
if( m_bDrawHelp )
m_Help.Render( &m_Font, g_HelpCallouts, NUM_HELP_CALLOUTS );
else
{
m_Font.Begin();
m_Font.DrawText( 64, 50, 0xffffffff, L"SectionLoad" );
m_Font.DrawText( 450, 50, 0xffffff00, m_strFrameRate );
m_Font.DrawText( 64, 70, 0xffffff00, L"Press A to toggle DataSeg loaded" );
m_Font.DrawText( 64, 90, 0xffffff00, L"Press B to access DataSeg" );
if(m_bDataSegLoaded)
m_Font.DrawText( 64, 110, 0xff00ff00, L"DataSeg Loaded" );
else
m_Font.DrawText( 64, 110, 0xffff0000, L"DataSeg NOT Loaded" );
if(m_fDataSegAccessTime!=0.0f)
{
WCHAR s[80];
swprintf(s, L"Last successful DataSeg access time: %3.2f, %3.2f", m_fDataSegAccessTime, m_fTime);
m_Font.DrawText( 64, 130, 0xffffff00, s);
}
m_Font.End();
}
// Present the scene
m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
return S_OK;
}
| true |
2bee64fd1e2c1c62c04414612f3ddc11a8c89751 | C++ | Banderi/GodotNeuralNetworkTests | /CLion/src/main.cpp | UTF-8 | 13,229 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <gdnative_api_struct.gen.h>
#include <cstring>
#include "main.h"
#include "NN/neural_network.h"
const char *p_class_name = "NNClass";
const godot_gdnative_core_api_struct *API = nullptr;
const godot_gdnative_ext_nativescript_api_struct *nativescript_API = nullptr;
typedef struct {
char data[256];
} globals_struct;
void *init_globals() {
auto global_data = (globals_struct*)API->godot_alloc(sizeof(globals_struct));
strcpy(global_data->data, "World from GDNative!");
return (void*)global_data;
}
///////// function overrides for default args
void register_method(const char *p_name, GDCALLINGCONV godot_variant (*method)(godot_object *, void *, void *, int, godot_variant **)) {
return register_method(p_name, method, GODOT_METHOD_RPC_MODE_DISABLED);
}
// empty objects
godot_variant empty_variant() {
godot_variant ret;
return ret;
}
godot_array empty_array() {
godot_array arr;
API->godot_array_new(&arr);
return arr;
}
void free(godot_variant a) {
API->godot_variant_destroy(&a);
}
void free(godot_array a) {
API->godot_array_destroy(&a);
}
void free(godot_string a) {
API->godot_string_destroy(&a);
}
void free(godot_object *a) {
API->godot_object_destroy(&a);
}
int to_int(godot_variant a, bool dealloc = true) {
auto ret = API->godot_variant_as_int(&a);
if (dealloc)
free(a);
return ret;
}
int to_bool(godot_variant a, bool dealloc = true) {
auto ret = API->godot_variant_as_bool(&a);
if (dealloc)
free(a);
return ret;
}
int to_double(godot_variant a, bool dealloc = true) {
auto ret = API->godot_variant_as_real(&a);
if (dealloc)
free(a);
return ret;
}
// these are simple variable types. they don't require deallocation
godot_variant to_variant(int a) {
godot_variant ret;
API->godot_variant_new_int(&ret, a);
return ret;
}
godot_variant to_variant(bool a) {
godot_variant ret;
API->godot_variant_new_bool(&ret, a);
return ret;
}
godot_variant to_variant(double a) {
godot_variant ret;
API->godot_variant_new_real(&ret, a);
return ret;
}
// these are complex variant/object types -- they REQUIRE deallocation!!
godot_variant to_variant_unsafe(godot_string a, bool dealloc = true) {
godot_variant ret;
API->godot_variant_new_string(&ret, &a);
if (dealloc)
free(a);
return ret;
}
godot_variant to_variant_unsafe(const char *a) {
// first, declare, initialize and fill a string object
godot_string str;
API->godot_string_new(&str);
API->godot_string_parse_utf8(&str, a);
// then, transfer to variant
godot_variant ret;
API->godot_variant_new_string(&ret, &str);
// remember to deallocate the object!
// if (dealloc)
free(str);
return ret;
}
godot_variant to_variant_unsafe(godot_array a, bool dealloc = true) {
godot_variant ret;
API->godot_variant_new_array(&ret, &a);
if (dealloc)
free(a);
return ret;
}
godot_variant to_variant_obj(godot_object *a, bool dealloc = true) {
godot_variant ret;
API->godot_variant_new_object(&ret, a);
if (dealloc)
free(a);
return ret;
}
godot_array to_array(godot_variant a) {
return API->godot_variant_as_array(&a);
}
void array_push_back(godot_array *arr, const godot_variant a, bool dealloc = true) {
API->godot_array_push_back(arr, &a);
if (dealloc)
free(a);
}
godot_variant debug_line_text(const char *text, int num) {
godot_array arr = empty_array();
array_push_back(&arr, to_variant_unsafe(text));
array_push_back(&arr, to_variant(num));
return to_variant_unsafe(arr);
}
godot_array constr_godot_array(godot_variant variants[], int num) {
godot_array arr;
API->godot_array_new(&arr);
for (int i = 0; i < num; ++i)
API->godot_array_push_back(&arr, &variants[i]);
return arr;
}
godot_array constr_godot_array(godot_variant **variants, int num) {
godot_array arr;
API->godot_array_new(&arr);
for (int i = 0; i < num; ++i)
API->godot_array_push_back(&arr, variants[i]);
return arr;
}
godot_variant get_param(int param, godot_variant **p_args, int p_num_args) {
godot_variant ret;
if (p_num_args == 0) // no parameters!
return ret;
godot_array arr = constr_godot_array(p_args, p_num_args);
ret = API->godot_array_get(&arr, param);
free(arr);
return ret;
}
//////////// NATIVESCRIPT CLASS MEMBER FUNCTIONS
godot_variant get_test_string(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
godot_string data;
godot_variant ret;
API->godot_string_new(&data);
API->godot_string_parse_utf8(&data, "test");
API->godot_variant_new_string(&ret, &data);
API->godot_string_destroy(&data);
return ret;
// return to_variant(((globals_struct *)(p_globals))->data);
}
godot_variant get_two(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
// this DOES NOT create a leak...
// godot_string data;
// godot_variant ret;
//
// API->godot_string_new(&data);
// API->godot_string_parse_utf8(&data, "test");
// API->godot_variant_new_string(&ret, &data);
// API->godot_string_destroy(&data);
// return ret;
// .....................
// this DOES NOT create a leak...
// godot_variant ret;
// for (int i = 0; i < 20; ++i) {
// godot_string data;
// API->godot_string_new(&data); // <--- this leaves behind a "phantom" string, but we already destroy it at the end of each loop.
// API->godot_string_parse_utf8(&data, "test");
//
// if (i > 0) // only destroy after the first loop - you can not destroy uninitialized objects!
// API->godot_variant_destroy(&ret); // DESTROY the variant first if already initialized!!!!
// API->godot_variant_new_string(&ret, &data); // <--- this leaves behind a "phantom" variant, so it needs to be destroyed!!
//
// API->godot_string_destroy(&data);
// }
// .....................
// this DOES NOT create a leak...
auto arr = empty_array();
for (int i = 0; i < 20; ++i) {
auto b = empty_array();
array_push_back(&b, to_variant(i));
array_push_back(&arr, to_variant_unsafe(b));
}
return to_variant_unsafe(arr);
}
godot_variant get_heartbeat(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
godot_array arr = constr_godot_array(p_args, p_num_args);
return to_variant_unsafe(arr);
}
godot_variant load_neuron_values(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
godot_array data = to_array(get_param(0, p_args, p_num_args));
if (API->godot_array_size(&data) == 0) // empty!
return debug_line_text("no data!!", 0);
// for each layer...
int layers_count = API->godot_array_size(&data);
NN.layers_count = layers_count;
for (int i = 0; i < layers_count; ++i) {
const godot_array layer = to_array(API->godot_array_get(&data, i));
int neurons_this_layer = API->godot_array_size(&layer); // layer size (num. of neurons in it)
// calculate number of weights (neurons in the next layer & prev layer)
int neurons_next_layer = 0;
if (i + 1 < layers_count) {
const godot_array next_layer = to_array(API->godot_array_get(&data, i + 1));
neurons_next_layer = API->godot_array_size(&next_layer); // layer size (num. of neurons in it)
free(next_layer);
}
int neurons_prev_layer = 0;
if (i > 0) {
const godot_array prev_layer = to_array(API->godot_array_get(&data, i - 1));
neurons_prev_layer = API->godot_array_size(&prev_layer); // layer size (num. of neurons in it)
free(prev_layer);
}
// allocate layer memory if necessary
NN.allocate_memory(i, neurons_this_layer, neurons_next_layer, neurons_prev_layer);
// for each neuron in the layer...
for (int j = 0; j < neurons_this_layer; ++j) {
const godot_array neuron = to_array(API->godot_array_get(&layer, j));
const int neuron_arr_size_safety_check = API->godot_array_size(&neuron);
if (neuron_arr_size_safety_check > 0) {
const godot_variant activation = API->godot_array_get(&neuron, 0);
NN.set_activation(i, j, API->godot_variant_as_real(&activation));
}
if (neuron_arr_size_safety_check > 1) {
const godot_variant bias = API->godot_array_get(&neuron, 1);
NN.set_bias(i, j, API->godot_variant_as_real(&bias));
}
if (neuron_arr_size_safety_check > 2 && !NN.allocated) {
const godot_array weights = to_array(API->godot_array_get(&neuron, 2));
int weights_per_neuron_this_layer = API->godot_array_size(&weights);
// for each synapses' weight in the layer...
for (int k = 0; k < weights_per_neuron_this_layer; ++k) {
const godot_variant weight = API->godot_array_get(&weights, k);
NN.set_weight(i, j, k, API->godot_variant_as_real(&weight));
free(weight);
}
}
// free(neuron);
// free(activation);
// free(bias);
// free(weights);
}
free(layer);
}
free(data);
// set up synapse caches!
NN.update_dendrites();
NN.allocated = true;
return empty_variant();
// return debug_line_text("neurons_done:", NN.neuron_total_count);
}
godot_variant fetch_single_neuron(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
int l = to_int(get_param(0, p_args, p_num_args));
int n = to_int(get_param(1, p_args, p_num_args));
auto neuron = NN.get_neuron(l, n);
auto arr_n = empty_array();
array_push_back(&arr_n, to_variant(neuron->activation));
array_push_back(&arr_n, to_variant(neuron->bias));
array_push_back(&arr_n, to_variant(neuron->activation_GOAL_GRADIENT));
return to_variant_unsafe(arr_n);
}
godot_variant fetch_neuron_synapse_weights(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
int l = to_int(get_param(0, p_args, p_num_args));
int n = to_int(get_param(1, p_args, p_num_args));
auto neuron = NN.get_neuron(l, n);
auto arr_s = empty_array();
for (int s = 0; s < neuron->synapses_total_count; ++s)
array_push_back(&arr_s, to_variant(neuron->synapses[s].weight));
return to_variant_unsafe(arr_s);
}
godot_variant fetch_neuron_synapse_single(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
int l = to_int(get_param(0, p_args, p_num_args));
int n = to_int(get_param(1, p_args, p_num_args));
int s = to_int(get_param(2, p_args, p_num_args));
auto neuron = NN.get_neuron(l, n);
return to_variant(neuron->synapses[s].weight);
}
godot_variant update(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
bool success = NN.update_network();
return to_variant(success);
}
godot_variant update_backpropagation(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
auto favorable_results = to_array(get_param(0, p_args, p_num_args)); // <---- this is an ARRAY containing favorable values for the final layer
// update activation_GOAL_FAVORABLE values for the last layer (outputs)
for (int i = 0; i < API->godot_array_size(&favorable_results); ++i) {
double value = to_double(API->godot_array_get(&favorable_results, i));
NN.outputs()->neurons[i].activation_FINAL_DEMAND = value;
// NN.outputs()->neurons[i].activation_GOAL_GRADIENT_COUNTS = 1;
}
bool success = NN.update_backpropagation();
return to_variant(success);
}
godot_variant get_answer_digit(godot_object *p_instance, void *p_method_data, void *p_globals, int p_num_args, godot_variant **p_args) {
int answer = NN.get_answer_digit();
double cost = NN.get_result_cost();
auto arr = empty_array();
array_push_back(&arr, to_variant(answer));
array_push_back(&arr, to_variant(cost));
return to_variant_unsafe(arr);
}
void init_nativescript_methods() {
// register methods
register_method("get_test_string", &get_test_string);
register_method("get_two", &get_two);
register_method("get_heartbeat", &get_heartbeat);
//
register_method("load_neuron_values", &load_neuron_values);
register_method("fetch_single_neuron", &fetch_single_neuron);
register_method("fetch_neuron_synapse_weights", &fetch_neuron_synapse_weights);
register_method("fetch_neuron_synapse_single", &fetch_neuron_synapse_single);
register_method("update", &update);
register_method("update_backpropagation", &update_backpropagation);
//
register_method("get_answer_digit", &get_answer_digit);
} | true |
35672555872060a6a59cea68e5911ff1396ad901 | C++ | georgiosdoumas/ProgrammingCplusplus- | /CplusplusPrimer_5thEd_2012/chapter03/Exercise3.02.cpp | UTF-8 | 793 | 3.703125 | 4 | [] | no_license | /* Exercise 3.2: Write a program to read the standard input a line at a time.
Modify your program to read a word at a time */
#include <iostream>
#include <string>
using std::cin; using std::cout; using std::endl;
int main()
{
cout << "Type text, line by line , and I will output it line-by-line (finish by giving ENTER on an empty line):" << endl;
std::string line_current;
while (getline(cin, line_current))
if (!line_current.empty()) cout << line_current << endl;
else {
cout << "Now you will type text, line by line , and I will output it word by word (finish with Ctrl+d)" << endl;
std::string words;
while (cin >> words ) cout << words << endl;
}
return 0;
}
// g++ -Wall -std=c++11 -o Exercise3.2 Exercise3.2.cpp
| true |
7aededa33d0e4f8cd27e7cab728d46a65e1d0310 | C++ | ginkgo/AMP-LockFreeSkipList | /test/sssp/Simple/SimpleSssp.h | UTF-8 | 1,797 | 2.625 | 3 | [] | no_license | /*
* SimpleSssp.h
*
* Created on: Jul 16, 2012
* Author: Martin Wimmer
* License: Boost Software License 1.0
*/
#ifndef SIMPLESSSP_H_
#define SIMPLESSSP_H_
#include "../sssp_graph_helpers.h"
#include "SimpleSsspPerformanceCounters.h"
namespace pheet {
template <class Pheet>
class SimpleSssp : public Pheet::Task {
public:
typedef SimpleSssp<Pheet> Self;
typedef SimpleSsspPerformanceCounters<Pheet> PerformanceCounters;
SimpleSssp(SsspGraphVertex* graph, size_t size, PerformanceCounters& pc)
:graph(graph), node(0), distance(0), pc(pc) {}
SimpleSssp(SsspGraphVertex* graph, size_t node, size_t distance, PerformanceCounters& pc)
:graph(graph), node(node), distance(distance), pc(pc) {}
virtual ~SimpleSssp() {}
virtual void operator()() {
size_t d = graph[node].distance.load(std::memory_order_relaxed);
if(d != distance) {
pc.num_dead_tasks.incr();
// Distance has already been improved in the meantime
// No need to check again
return;
}
pc.num_actual_tasks.incr();
for(size_t i = 0; i < graph[node].num_edges; ++i) {
size_t new_d = d + graph[node].edges[i].weight;
size_t target = graph[node].edges[i].target;
size_t old_d = graph[target].distance.load(std::memory_order_relaxed);
while(old_d > new_d) {
if(graph[target].distance.compare_exchange_strong(old_d, new_d, std::memory_order_relaxed)) {
Pheet::template
spawn<Self>(graph, target, new_d, pc);
break;
}
}
}
}
static void set_k(size_t k) {}
static void print_name() {
std::cout << name;
}
static char const name[];
private:
SsspGraphVertex* graph;
size_t node;
size_t distance;
PerformanceCounters pc;
};
template <class Pheet>
char const SimpleSssp<Pheet>::name[] = "Simple Sssp";
} /* namespace pheet */
#endif /* SIMPLESSSP_H_ */
| true |
46d0ae37ed19ace90587e084031a83cd2424e356 | C++ | Aftermath863/my-code | /C++project4/C++project4.cpp | UTF-8 | 4,410 | 3.328125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iomanip>
#include <exception>
#include <typeinfo>
#include <string.h>
#include<iostream>
using namespace std;
template <typename T>
class MAT {
T* const e; //指向所有整型矩阵元素的指针
const int r, c; //矩阵的行r和列c大小
public:
MAT(int r, int c) :MAT::r(r), MAT::c(c),e(new T[r*c]){}; //矩阵定义
MAT(const MAT& a) :r(a.r), c(a.c), e(NULL) {
T* arr = new T[r * c];
for (int i = 0; i < r * c; i++)
arr[i] = a.e[i];
*(T**)&e = arr;
}; //深拷贝构造
MAT(MAT&& a)noexcept :r(a.r), c(a.c), e(a.e) {
*(int*)&(a.c) = 0;
*(int*)&(a.r) = 0;
*(T**)&(a.e) = NULL;
}; //移动构造
virtual ~MAT()noexcept {
delete[]e;
*(T**)&e = NULL;
*(int*)&c = 0;
*(int*)&r= 0;
};
virtual T* const operator[](int r) {
if (r > this->r-1||r<0 )
throw "error";
else
return &e[r * c ];
} ;//取矩阵r行的第一个元素地址,r越界抛异常
virtual MAT operator+(const MAT& a)const {
T* arr = new T[r * c];
MAT R(r, c);
*(T**)&R.e = arr;
if (r != a.r || c != a.c)
throw "error";
else {
memset(arr, 0, r * c);
for (int i = 0; i < r * c; i++)
arr[i]=e[i] + a.e[i];
}
return R;
}; //矩阵加法,不能加抛异常
virtual MAT operator-(const MAT& a)const {
T* arr = new T[r * c];
MAT R(r, c);
*(T**)&R.e = arr;
if (r != a.r || c != a.c)
throw "error";
else {
memset(arr, 0, r * c);
for (int i = 0; i < r * c; i++)
arr[i]=e[i] - a.e[i];
}
return R;
}; //矩阵减法,不能减抛异常
virtual MAT operator*(const MAT& a)const {
T* arr = new T[r * a.c];
memset(arr, 0, sizeof(T)*r * a.c);
MAT<T> R(r, a.c );
*(T**)&R.e = arr;
if (c != a.r || !e || !a.e)
throw "error";
else
{
for (int i = 0; i < r; i++)
for (int j = 0; j < a.c; j++) {
for (int k = 0; k < c; k++)
arr[i * a.c + j] += e[i * c + k] * a.e[k * a.c + j];
}
}
return R;
}; //矩阵乘法,不能乘抛异常
virtual MAT operator~()const {
MAT M(c, r);
for (int i = 0; i < c; i++)
for (int j = 0; j < r; j++)
M.e[i * r + j] = e[j * c + i];
return M;
}; //矩阵转置
virtual MAT& operator=(const MAT& a){
if (e == a.e) return *this;
if (e != NULL) *(T**)&e = NULL;
T* arr = new T[r * c];
for (int i = 0; i < r * c; i++)
arr[i] = a.e[i];
*(T**)&e = arr;
*(int*)&r = a.r;
*(int*)&c = a.c;
return *this;
}; //深拷贝赋值运算
virtual MAT& operator=(MAT&& a)noexcept{
if (e == a.e) return *this;
if (e != NULL) *(T**)&e = NULL;
*(int*)&r = a.r;
*(int*)&c = a.c;
*(T**)&e = a.e;
*(int*)&(a.c) = 0;
*(int*)&(a.r) = 0;
*(T**)&(a.e) = NULL;
}; //移动赋值运算
virtual MAT& operator+=(const MAT& a) {
if (r != a.r || c != a.c)
throw "error";
else
for (int i = 0; i < r * c; i++)
e[i] += a.e[i];
return *this;
}; //“+=”运算
virtual MAT& operator-=(const MAT& a) {
if (r != a.r || c != a.c)
throw "error";
else
for (int i = 0; i < r * c; i++)
e[i] -= a.e[i];
return *this;
}; //“-=”运算
virtual MAT& operator*=(const MAT& a) {
T* arr = new T[r * a.c];
memset(arr, 0, sizeof(T)*r*a.c);
if (c != a.r || !e || !a.e)
throw "error";
else
{
for (int i = 0; i < r; i++)
for (int j = 0; j < a.c; j++) {
for (int k = 0; k < c; k++)
arr[i * a.c + j] += e[i * c + k] * a.e[k * a.c + j];
}
*(int*)&c = a.c;
*(T**)&e = arr;
}
return *this;
}; //“*=”运算
//print输出至s并返回s:列用空格隔开,行用回车结束
virtual char* print(char* s)const noexcept {
s[0] = '\0';
for (int i = 0; i < r * c; i++) {
char* ss = s + strlen(s);
if (typeid(e) == typeid(int*))
sprintf(ss, "%6ld ", e[i]);
else
if(typeid(e) == typeid(long long*))
sprintf(ss, "%8d ", e[i]);
if ((i + 1) % c == 0) {
ss = s + strlen(s);
sprintf(ss, "\n");
}
}
return s;
};
};
template MAT<int>; //用于实验四
template MAT<long long>; //用于实验四
extern const char* TestMAT(int& s); //用于实验四
int main(int argc, char* argv[]) //请扩展main()测试其他运算
{
const char* e;
int s;
e = TestMAT(s);
cout << e << endl;
cout << s << endl;
return 0;
}
| true |
e0bd8bf361d271558391529c6f42b80c3bad0cac | C++ | mt-revolution/Competition | /Atcoder/JOI2013finalA.cpp | UTF-8 | 729 | 2.78125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int tmp = 0;
vector<int> light(N+1);
// 交互列の長さをカウント
vector<int> sequence;
sequence.push_back(0);
cin >> light[1];
tmp = 1;
for (int i = 2; i <= N; i++) {
cin >> light[i];
if (light[i] != light[i-1]) {
tmp += 1;
} else {
sequence.push_back(tmp);
tmp = 1;
}
}
sequence.push_back(tmp);
sequence.push_back(0);
int answer = 0;
for (int i = 0; i < sequence.size() - 2; i++) {
answer = max(answer, sequence[i] + sequence[i+1] + sequence[i+2]);
}
cout << answer << endl;
return 0;
} | true |
153fbd35b10e21ab7576187062634818e354d28d | C++ | southernEast/SEU_553 | /2014/4/Date.cpp | GB18030 | 1,060 | 3.59375 | 4 | [] | no_license | #include "Date.h"
#include <iostream>
using namespace std;
Date::Date(unsigned y, unsigned m, unsigned d) {
setDate(y, m, d);
}
void Date::setDate(unsigned y, unsigned m, unsigned d) {
static unsigned days[2][13] = {
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // ÿµ
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // һάȡ1
};
if (y < 2900)
year = y;
else {
cerr << "The year is out of range.";
exit(EXIT_FAILURE);
}
if (m >= 1 && m <= 12)
month = m;
else {
cerr << "The month is out of range.";
exit(EXIT_FAILURE);
}
if (d >= 1 && d <= days[isLeapyear()][month])
day = d;
else {
cerr << "The day is out of range.";
exit(EXIT_FAILURE);
}
}
int Date::isLeapyear() const {
return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
void Date::display() const {
cout << year << "." << month << "." << day;
}
unsigned Date::getYear() const {
return year;
}
unsigned Date::getMonth() const {
return month;
}
unsigned Date::getDay() const {
return day;
} | true |
b0afbc579c55255633103ace13c83b01b00a1688 | C++ | VolodymyrShkrynda/4.6 | /4.6/Source.cpp | UTF-8 | 1,662 | 3.5 | 4 | [] | no_license | // Lab_03_4.cpp
// < Шкринда Володимир
// Лабораторна робота № 4.6
// Табуляція функції, заданої формулою: функція з параметрами
// Варіант 22
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double P,P1, P2;
int n, k;
k = 1;
P2 = 1;
while (k<=20)
{
P1 = 1;
n = 1;
while (n<=25-k)
{
P1 *= ((k*1.00 - n) / (k*1.00 + n) + 1);//перший добуток
n++;
}
P2 *= P1*1.00;// другий добуток
k++;
}
P = P1 * P2;// добуток першого і другого
cout << "1) P1 = " << P1 << endl;
cout << "1) P2 = " << P2 << endl;
cout << "1) P = " << P << endl;
cout << "_____________________" << endl;
P2 = 1;
k = 1;
do
{
P1 = 1;
n = 1;
do
{
P1 *= ((k * 1.00 - n) / (k * 1.00 + n) + 1);
n++;
} while (n <= 25 - k);
P2 *= P1;
k++;
} while (k <= 20);
P = P1 * P2;
cout << "2) P1 = " << P1 << endl;
cout << "2) P2 = " << P2 << endl;
cout << "2) P = " << P << endl;
cout << "_____________________" << endl;
P2 = 1;
for (k = 1; k <= 20; k++)
{
P1 = 1;
for (n = 1; n <= 25-k; n++)
{
P1 *= ((k * 1.00 - n) / (k * 1.00 + n) + 1);
}
P2 *=P1;
}
P = P1 * P2;
cout << "3) P1 = " << P1 << endl;
cout << "3) P2 = " << P2 << endl;
cout << "3) P = " << P << endl;
cout << "_____________________" << endl;
// for (k = 1; k <= 20; k++)
//
// {
// P1 = 1;
// for (n = 1; n <= 25-k; n++)
//
// {
// P1 *= ((k * 1.00 - n) / (k * 1.00 + n) + 1);
//
// }
// P *= P1;
//
// }
// cout << "3) P1 = " << P1 << endl;
// cout << "3) P = " << P << endl;
cin.get();
return 0;
}
| true |
7220cf3f00f4ce713931b4c250f4351a04cf4e95 | C++ | kimdy003/AlgorithmStudy | /Study/3_week/2_1464.cpp | UTF-8 | 341 | 2.75 | 3 | [] | no_license | //분할정복
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
string str, temp;
cin >> str;
for(int i=1; i<str.length(); i++){
if(str[i] > str[i-1]){
temp = str[i];
str.erase(i,1);
str = temp + str;
}
}
cout << str;
} | true |
9f570cbd6c670f232318c43fd627b46acfa0bffb | C++ | angelalim1010/Cybersecurity-labs | /program1.cpp | UTF-8 | 753 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include <climits>
using namespace std;
int main(){
int i ;
int j ;
int result;
cout << "For this compiler: integers are: " << sizeof(int) << " bytes" << endl;
cout << "The largest integer is: " << INT_MAX << endl;
cout << "The smallest integer is: " << INT_MIN << endl;
cout << "Input two integer values: " << endl;
cin >> i >> j;
//cin >> j >> endl;
cout << "The integers your displayed are: " << i << "," << j << endl;
//part 2
result = i * 10;
cout << "Your number times ten is " << result << endl;
result = i + j;
cout << "The sum of your numbers is " << result << endl;
result = i*j;
cout << "The product of your numbers is " << result << endl;
return 0;
}
| true |
08165e280be049e3d133295de84adede78f48317 | C++ | alexandraback/datacollection | /solutions_5630113748090880_0/C++/mooncalf/b.cpp | UTF-8 | 417 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
int t, n, h;
cin >> t;
for (int i = 0; i < t; ++i){
cin >> n;
int nums = (2*n-1)*n;
int heights[2501] = {0};
for (int j = 0; j < nums; ++j) {
cin >> h;
++heights[h];
}
cout << "Case #" << i + 1 << ": ";
for (int j = 1; j < 2501; ++j) {
if (heights[j] % 2) cout << j << " ";
}
cout << endl;
}
return 0;
}
| true |
490141a40f4fa90970c4e2fece818889026ecf3b | C++ | StevensDeptECE/CPE390 | /old/2020F/session03/byvalue.cc | UTF-8 | 872 | 3.921875 | 4 | [] | no_license | #include <iostream>
using namespace std;
void f(int x) { // pass by value
cout << x << '\n';
x = 99;
}
void g(int& x) { //pass by reference (we have a pointer to where the parameter lives)
cout << x << '\n';
x = 22;
}
void h(int* x) { // x is a pointer to where the number lives
cout << x << '\n';
cout << *x << '\n'; // *x is what the pointer is pointing to (dereference)
*x = 33;
}
//pass by value (make a copy)
//pass by reference
int main() {
int a = 3;
f(a); // f is pass by value
cout << a << '\n'; // what is the value of a?
f(a);
g(a); // g is pass by reference it is completely unobvious that this changes a.
g(a); // the only way to know is to look at the function prototype of g
h(&a); // pass the ADDRESS of a (a pointer) to the function
h(&a); // pass the ADDRESS of a (a pointer) to the function
} | true |
01440c67bd457ad649e442bf368579abf857f1dd | C++ | teodoraalexandra/Data-Structures-And-Algorithms | /DSALAB7/BSTNode.h | UTF-8 | 758 | 2.859375 | 3 | [] | no_license | //
// Created by Teodora Dan on 2019-05-28.
//
#ifndef DSALAB7_BSTNODE_H
#define DSALAB7_BSTNODE_H
#include "utility"
typedef int TKey;
typedef int TValue;
typedef std::pair<TKey, TValue> TElem;
class BSTNode {
private:
TElem value;
BSTNode *leftChild;
BSTNode *rightChild;
public:
BSTNode(std::pair<TKey, TValue> value, BSTNode *leftChild = nullptr, BSTNode *rightChild = nullptr);
TKey getKey() const;
void setKey(TKey key);
TValue getValue() const;
void setValue(TValue value);
BSTNode *getLeftChild() const;
void setLeftChild(BSTNode *leftSon);
BSTNode *getRightChild() const;
void setRightChild(BSTNode *rightSon);
bool isLeaf(); //Leaf means that it has no children
};
#endif //DSALAB7_BSTNODE_H
| true |
b282aeee9aab5c9b9ee73990abb4c419519f8590 | C++ | jinq0123/rpcz | /src/rpcz/connection_info_zmq.hpp | UTF-8 | 1,217 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | // Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
// Read and write connection_info through zmq.
#ifndef RPCZ_CONNECTION_INFO_ZMQ_HPP
#define RPCZ_CONNECTION_INFO_ZMQ_HPP
#include <zmq.hpp>
#include <rpcz/connection_info.hpp>
#include <rpcz/zmq_utils.hpp> // for send_uint64()
namespace rpcz {
inline void read_connection_info(
message_iterator& iter,
connection_info* info) {
BOOST_ASSERT(info);
BOOST_ASSERT(iter.has_more());
char is_router(interpret_message<char>(iter.next()));
BOOST_ASSERT(iter.has_more());
info->is_router = (0 != is_router);
info->index = interpret_message<uint64>(iter.next());
if (!is_router) return;
BOOST_ASSERT(iter.has_more());
info->sender = message_to_string(iter.next());
}
inline void write_connection_info(
zmq::socket_t* socket,
const connection_info& info,
int flags=0) {
BOOST_ASSERT(socket);
send_char(socket, info.is_router, ZMQ_SNDMORE);
if (info.is_router) {
send_uint64(socket, info.index, ZMQ_SNDMORE);
send_string(socket, info.sender, flags);
return;
}
send_uint64(socket, info.index, flags);
}
} // namesapce rpcz
#endif // RPCZ_CONNECTION_INFO_ZMQ_HPP
| true |
5700412e1aae3c14bd1952d9f713b16f290d3398 | C++ | AnotherSuperIntensiveMinecraftPlayer/ATACS | /src/POSET.cc | UTF-8 | 26,978 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | //////////////////////////////////////////////////////////////////////////
// @name POSET.cc => Code to implement POSET class defined in bap.h
// @version 0.1 alpha
//
// (c)opyright 2001 by Eric G. Mercer
//
// @author Eric G. Mercer
//////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iomanip>
#include "bap.h"
#include "error.h"
#include "limits.h"
// ERIC: This does not work either, see pab_c4_2.csp
//#define __TOTAL__
//////////////////////////////////////////////////////////////////////////
//
const POSET::bound_type POSET::_UNBOUNDED_ = INT_MAX - 1;
const POSET::bound_type POSET::_MARKED_ = INT_MAX;
void POSET::floyds(){
size_type size_dbm = get_size();
index_type i, j, k;
for ( k = 0 ; k < size_dbm ; ++k ) {
for ( i = 0 ; i < size_dbm ; ++i ) {
for ( j = 0 ; j < size_dbm ; ++j ) {
if ( dbm[i][k] != _UNBOUNDED_ &&
dbm[k][j] != _UNBOUNDED_ &&
dbm[i][j] > dbm[i][k] + dbm[k][j] )
dbm[i][j] = dbm[i][k] + dbm[k][j];
}
}
}
}
// NOTE: This can only be called if a single event has been added to the
// POSET. If more than 1 event has been added since the last
// canonicalization, then the full floyds must be used.
// NOTE: This assumes that size_dbm-1 is the index of the newly added event.
void POSET::incremental_floyds( size_type size_dbm ) {
index_type e = size_dbm - 1;
index_type i, j, k;
for( k = 0 ; k < size_dbm ; k++ ){
for( i = 0 ; i < size_dbm ; i++ ){
if( dbm[i][k] != _UNBOUNDED_ &&
dbm[k][e] != _UNBOUNDED_ &&
dbm[i][e] > dbm[i][k] + dbm[k][e] ) {
dbm[i][e]= dbm[i][k] + dbm[k][e];
}
}
for( j = 0 ; j < size_dbm ; j++ ) {
if( dbm[e][k] != _UNBOUNDED_ &&
dbm[k][j] != _UNBOUNDED_ &&
dbm[e][j] > dbm[e][k] + dbm[k][j] ){
dbm[e][j] = dbm[e][k] + dbm[k][j];
}
}
}
for( i = 0 ; i < size_dbm ; i++ ){
for( j = 0 ; j < size_dbm ; j++ ){
if( dbm[i][e]!=_UNBOUNDED_ &&
dbm[e][j]!=_UNBOUNDED_ &&
dbm[i][j] > dbm[i][e] + dbm[e][j] ){
dbm[i][j] = dbm[i][e] + dbm[e][j];
}
}
}
}
void POSET::delete_dbm( bound_type** p, size_type size ) {
if ( p == NULL ) return;
for ( unsigned int i = 0 ; i < size ; ++i ) {
delete [] dbm[i];
}
delete [] dbm;
}
POSET::bound_type**
POSET::copy_shrink_dbm( bound_type** p, size_type size_p,
size_type size_new ) {
if ( size_new > size_p ) {
string errorStr = "ERROR: bad size_new in copy_expand_dbm";
throw( new error( errorStr ) );
}
bound_type** tmp = new bound_type*[size_new];
if ( tmp == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
index_type i_p = 0, i_tmp = 0;
index_type j_p = 0, j_tmp = 0;
while ( i_p < size_p ) {
// If this event is not _MARKED_, then this row is included.
if ( p[i_p][i_p] != _MARKED_ ) {
tmp[i_tmp] = new bound_type[size_new];
if ( tmp[i_tmp] == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
j_p = 0, j_tmp = 0;
while( j_p < size_p ) {
// If this event is not _MARKED_, then copy in its column entry.
if ( p[j_p][j_p] != _MARKED_ ) {
tmp[i_tmp][j_tmp++] = p[i_p][j_p];
}
++j_p;
}
++i_tmp;
}
++i_p;
}
return( tmp );
}
POSET::bound_type**
POSET::copy_expand_dbm( bound_type** p, size_type size_p,
size_type size_new ) {
if ( size_new < size_p ) {
string errorStr = "ERROR: bad size_new in copy_expand_dbm";
throw( new error( errorStr ) );
}
bound_type** tmp = new bound_type*[size_new];
if ( tmp == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type i = 0 ; i < size_new ; ++i ) {
tmp[i] = new bound_type[size_new];
if ( tmp[i] == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type j = 0 ; j < size_new ; ++j ) {
if ( j < size_p && i < size_p )
tmp[i][j] = p[i][j];
else if ( i == j )
tmp[i][j] = 0;
else
tmp[i][j] = _UNBOUNDED_;
}
}
return( tmp );
}
POSET::bound_type**
POSET::copy_expand_dbm2( bound_type** p, size_type size_p,
size_type size_new ) {
if ( size_new < size_p ) {
string errorStr = "ERROR: bad size_new in copy_expand_dbm";
throw( new error( errorStr ) );
}
bound_type** tmp = new bound_type*[size_new];
if ( tmp == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type i = 0 ; i < size_new ; ++i ) {
tmp[i] = new bound_type[size_new];
if ( tmp[i] == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type j = 0 ; j < size_new ; ++j ) {
if ( j < size_p && i < size_p )
tmp[i][j] = p[i][j];
else if ( i == j )
tmp[i][j] = 0;
else if ( j >= size_p && i < size_p )
tmp[i][j] = 0;
else
tmp[i][j] = _UNBOUNDED_;
}
}
return( tmp );
}
POSET::bound_type**
POSET::copy_dbm( bound_type** p, size_type size ) const{
bound_type** tmp = new bound_type*[size];
if ( tmp == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type i = 0 ; i < size ; ++i ) {
tmp[i] = new bound_type[size];
if ( tmp[i] == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type j = 0 ; j < size ; ++j ) {
tmp[i][j] = p[i][j];
}
}
return( tmp );
}
unsigned int POSET::max_length( const tel& t ) const {
unsigned int max = 0;
for ( event_map::const_iterator i = ptr_map->begin() ;
i != ptr_map->end() ;
++i ) {
unsigned int j = strlen( t.get_event( *i ) );
if ( j > max ) {
max = j;
}
}
return( max );
}
//////////////////////////////////////////////////////////////////////////
// This function adds events to Ekill if the events are not in E
//////////////////////////////////////////////////////////////////////////
template<class inserter>
void POSET::build_not_in_set( const event_set& E,
inserter Ekill ) const {
typedef event_map::const_iterator iterator;
for ( iterator i = ptr_map->begin() ; i != ptr_map->end() ; ++i ) {
if ( E.find( *i ) == E.end() ) {
*Ekill++ = *i;
}
}
}
template<class inserter>
void POSET::build_duplicate_set( inserter Edup ) const {
typedef event_map::iterator iterator;
for ( iterator i = ptr_map->begin() ; i != ptr_map->end() ; ++i ) {
iterator j = i;
if ( find( ++j, ptr_map->end(), *i ) != ptr_map->end() ) {
*Edup++ = *i;
}
}
}
// ---------------------------------------------POSETS::get_causal_indexes
// ASSUMPTION: index_i is set to the oldest instance of an event;
// index_j is set to the most recent instance of an event.
//
// If i==j and there is only a single instance of i in the matrix, then
// get_indexes will return false. The fact that i==j implies that there
// are 2 instances of the event to be found in the POSET, i will be the
// oldest instance, and j will be the newest instance.
//------------------------------------------------------------------------
bool POSET::get_causal_indexes( index_type& index_i,
index_type& index_j,
const event_type& i,
const event_type& j ) const {
bool set_i = false, set_j = false;
size_type size_dbm = get_size();
for ( index_type k = 0 ; k < size_dbm ; ++k ) {
event_type event = get_event( k );
// NOTE: I want to match and only match the first i! Thus,
// if i is duplicated in the POSET, this with return the
// the index of the first (oldest) i.
if ( !set_i && event == i ) {
index_i = k;
set_i = true;
continue;
}
// NOTE: If a duplicate j event exists, then I always want
// to find the most recent j. Thus, this will match every
// time event==j, and the last match will be the most recent
// j in the POSET.
if ( event == j ) {
index_j = k;
set_j = true;
continue;
}
}
if ( set_i && set_j && index_i != index_j ) return( true );
return( false );
}
//------------------------------------------------------------------------
//--------------------------------------bool POSET::get_separation_indexes
// ASSUMPTION: I want the most recent instance of i and j. Thus, this will
// return the index of those most recent entries (i.e., the entries nearest
// to the end of the marix.
//------------------------------------------------------------------------
bool POSET::get_separation_indexes( index_type& index_i,
index_type& index_j,
const event_type& i,
const event_type& j ) const {
bool set_i = false, set_j = false;
size_type size_dbm = get_size();
// NOTE: If a duplicate i or j event exists, then I always want
// to find the most recent i and j. Thus, this will match every
// time event==j or event==i, and the last match will be the most recent
// i or j in the POSET.
for ( index_type k = 0 ; k < size_dbm ; ++k ) {
event_type event = get_event( k );
if ( event == i ) {
index_i = k;
set_i = true;
continue;
}
if ( event == j ) {
index_j = k;
set_j = true;
continue;
}
}
if ( set_i && set_j && index_i != index_j ) return( true );
return( false );
}
//------------------------------------------------------------------------
//------------------------------------------------------get_freshest_index
// Returns the index of the most recent version of event i if multiple
// instances exist in the POSET
//------------------------------------------------------------------------
bool POSET::get_freshest_index( index_type& index_i,
const event_type& i ) const {
bool set_i = false;
size_type size_dbm = get_size();
// NOTE: If a duplicate i or j event exists, then I always want
// to find the most recent i and j. Thus, this will match every
// time event==j or event==i, and the last match will be the most recent
// i or j in the POSET.
for ( index_type k = 0 ; k < size_dbm ; ++k ) {
event_type event = get_event( k );
if ( event == i ) {
index_i = k;
set_i = true;
continue;
}
}
if ( set_i ) return( true );
return( false );
};
//------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////
// Removed events from the index_map that are found in Enotin or Edup.
// NOTE: I only want to remove the first duplicated instance of the
// event.
//////////////////////////////////////////////////////////////////////////
void POSET::update_and_mark_dbm( event_map* ptr_new_map,
const event_set& Enotin,
event_set& Edup ) {
index_type j = 0;
event_set::iterator pos;
size_type size_dbm = get_size();
for ( index_type i = 0 ; i < size_dbm ; ++i ) {
event_type e = (*ptr_map)[i];
if ( Enotin.find( e ) != Enotin.end() ) {
dbm[i][i] = _MARKED_;
}
// NOTE: I erase the event from Edup once it is matched
// so that I only remove the first copy of the event.
else if ( ( pos = Edup.find( e ) ) != Edup.end() ) {
dbm[i][i] = _MARKED_;
Edup.erase( pos );
}
else {
(*ptr_new_map)[j++] = e;
}
}
}
POSET::POSET( const untimed_state& untimed_st, const tel& t ) :
ptr_map( NULL ), dbm( NULL ) {
event_set E;
for ( int i = 0 ; i < t.marking_size() ; ++i ) {
int e( t.enabling(i) );
if ( untimed_st.is_marked( i ) )
E.insert( e );
else if ( !(t.is_dummy_event( e ) ) ) {
int s( t.get_signal( e ) );
if (s >= 0) {
if ( ( t.is_rising_event( e ) && untimed_st.is_high( s ) ) ||
( t.is_falling_event( e ) && untimed_st.is_low( s ) ) )
E.insert( e );
}
}
}
//for ( int i = 1 ; i < t.number_events() ; i++ ) {
// E.insert( i );
//}
ptr_map = new event_map( E.begin(), E.end() );
if ( ptr_map == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
dbm = new bound_type*[ptr_map->size()];
if ( dbm == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type i = 0 ; i < ptr_map->size() ; ++i ) {
dbm[i] = new bound_type[ptr_map->size()];
if ( dbm[i] == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type j = 0 ; j < ptr_map->size() ; ++j ) {
dbm[i][j] = 0;
}
}
}
POSET::POSET( const POSET& p ) : ptr_map( NULL ), dbm( NULL ) {
ptr_map = new event_map( *(p.ptr_map) );
if ( ptr_map == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
dbm = copy_dbm( p.get_dbm(), get_size() );
}
POSET::~POSET() {
delete_dbm( dbm, get_size() );
if ( ptr_map == NULL ) return;
delete ptr_map;
}
POSET& POSET::operator=( const POSET& p ) {
if ( this == &p ) return( *this );
ptr_map = new event_map( *(p.ptr_map) );
if ( ptr_map == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
if ( get_size() != 0 ) {
dbm = copy_dbm( p.get_dbm(), get_size() );
}
else {
dbm = NULL;
}
return( *this );
}
void POSET::constrain_lower_bounds( const tel& t, const rule_set& Rb,
event_type enabled ) {
event_type causal = 0;
bound_type lower_bound = 0;
for ( rule_set::const_iterator r = Rb.begin(); r != Rb.end() ; ++r ) {
// NOTE: For levels, this will need to have enabling, as well as
// causal. The seperation on every potentially causal event must
// meet the lower bounds on its associated rule.
causal = t.enabling( *r );
lower_bound = (bound_type)t.lower_bound( causal, enabled );
//cout << "Constrain " << t.get_event(causal) << " -> "
// << t.get_event(enabled) << " l = " << lower_bound << endl;
set_min_separation( causal, enabled, lower_bound );
}
}
void POSET::constrain_lower_bounds( const tel& t, const rule_set& Rb,
event_type enabled,
const enabled_set& Een ) {
event_type causal = 0;
bound_type lower_bound = 0;
for ( rule_set::const_iterator r = Rb.begin(); r != Rb.end() ; ++r ) {
// NOTE: For levels, this will need to have enabling, as well as
// causal. The seperation on every potentially causal event must
// meet the lower bounds on its associated rule.
causal = t.enabling( *r );
// Skip over this causal event if it refers to a previous instance of
// a causal event that is no longer in the POSET, but the next instance
// is in the enabled set.
// NOTE: What happens if the old instance is still in the POSET?
if ( find_if( Een.begin(), Een.end(),
bind2nd( compare( t ), causal ) ) != Een.end() ) continue;
lower_bound = (bound_type)t.lower_bound( causal, enabled );
set_min_separation( causal, enabled, lower_bound );
}
}
void POSET::add( const enabled_set& Een, const tel& t ) {
unsigned int size_new = get_size() + Een.size();
// ERIC: NOT SURE WHY THIS DOES NOT WORK, SEE circ4.csp for example.
#ifdef __TOTAL__
bound_type** tmp = copy_expand_dbm2( dbm, get_size(), size_new );
#else
bound_type** tmp = copy_expand_dbm( dbm, get_size(), size_new );
#endif
delete_dbm( dbm, get_size() );
dbm = tmp;
ptr_map->reserve( size_new );
for ( enabled_set::const_iterator i = Een.begin() ;
i != Een.end() ;
++i ) {
// NOTE: order is important here. The enabled event must be added
// to the ptr_map before you contrain_lower_bounds on causal events,
// otherwise the enabled event will not be found in the ptr_map.
event_type enabled = get_enabled( *i, t );
ptr_map->push_back( enabled );
constrain_lower_bounds( t, *i, enabled, Een );
}
}
void POSET::add( const rule_set& Rb, const tel& t ) {
size_type old_size_dbm = get_size();
// Reserve memory for the new entry in the map
ptr_map->reserve( old_size_dbm + 1 );
// Get the enabled event and push it into the map
event_type enabled = get_enabled( Rb, t );
ptr_map->push_back( enabled );
// Expand the dbm to accomodate the new entry;
#ifdef __TOTAL__
bound_type** tmp = copy_expand_dbm2( dbm, old_size_dbm, get_size() );
#else
bound_type** tmp = copy_expand_dbm( dbm, old_size_dbm, get_size() );
#endif
delete_dbm( dbm, old_size_dbm );
dbm = tmp;
constrain_lower_bounds( t, Rb, enabled );
}
POSET::size_type POSET::get_size() const {
return( ptr_map->size() );
}
// NOTE: 0 is reserved for system reset, but this assumes that
// reset event will be an enabled event!
POSET::event_type POSET::get_event( index_type i ) const {
if ( i >= ptr_map->size() ) return( 0 );
return( (*ptr_map)[i] );
}
void POSET::set_min_separation( event_type e, event_type f, bound_type v ) {
index_type index_e = 0, index_f = 0;
if ( !( get_causal_indexes( index_e, index_f, e, f ) ) ) return;
// INFIN has the same meaning as _UNBOUNED_ in this scope.
// However, the value of _UNBOUNDED_ may be different than the value
// of INFIN.
if ( v == INFIN ) {
v = _UNBOUNDED_;
}
// t(e) - t(f) < -v -> Think in terms of a rule <e,f,l,u>
dbm[index_e][index_f] = -1 * v;
}
void POSET::set_max_separation( event_type e, event_type f, bound_type v ) {
index_type index_e = 0, index_f = 0;
if ( !( get_causal_indexes( index_e, index_f, e, f ) ) ) return;
// INFIN has the same meaning as _UNBOUNED_ in this scope.
// However, the value of _UNBOUNDED_ may be different than the value
// of INFIN.
if ( v == INFIN ) {
v = _UNBOUNDED_;
}
// t(f) - t(e) < v -> Think in terms of a rule <e,f,l,u>
dbm[index_f][index_e] = v;
}
//////////////////////////////////////////////////////////////////////////
// get_value should NOT be called with i == j. If it is called with
// i == j, then it will look for 2 instances of the event i to be in
// the dbm and return that separation. If only 1 instance of i exists.
// then it will return _UNBOUNDED_
//
// NOTE: The only place that will check a diagonal is is_consistent, and
// then it only checks that it is non-zero!
//////////////////////////////////////////////////////////////////////////
POSET::bound_type
POSET::get_causal_separation( event_type e, event_type f ) const {
index_type index_e = 0, index_f = 0;
if ( !( get_causal_indexes( index_e, index_f, e, f ) ) )
return( _UNBOUNDED_ );
return( dbm[index_e][index_f] );
}
POSET::bound_type
POSET::get_separation( event_type i, event_type j ) const {
index_type index_i = 0, index_j = 0;
if ( !( get_separation_indexes( index_i, index_j, i, j ) ) )
return( _UNBOUNDED_ );
return( dbm[index_i][index_j] );
}
POSET::bound_type** POSET::get_dbm() const {
return( dbm );
}
clockkeyADT POSET::make_clockkey() const {
if ( get_size() == 0 ) {
return( NULL );
}
size_type size_dbm = get_size();
clockkeyADT tmp = new clockkey[size_dbm];
if ( tmp == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
for ( index_type i = 0 ; i < size_dbm ; ++i ) {
tmp[i].enabled = (*ptr_map)[i];
tmp[i].enabling = 0;
tmp[i].eventk_num = 0;
tmp[i].causal = 0;
tmp[i].anti = NULL;
}
return( tmp );
}
bool POSET::is_consistent( unsigned int added ) {
index_type size_dbm = get_size();
index_type start_of_new_events = size_dbm - added;
// Incrementally recanonicalize the dbm by pretending
// to add a single event at a time into the dbm.
// NOTE: incremental_floyd's assumes that the added event
// is located at size_dbm-1 and size_dbm is the size of the dbm.
for ( index_type i = start_of_new_events + 1 ; i <= size_dbm ; ++i ) {
incremental_floyds( i );
}
// If any non-zero values are found on the diagonal, then
// this dbm is not consistent because this not an assignment
// of values that will satisfy all of the inequalities
// represented by the dbm.
for ( index_type i = 0 ; i < size_dbm ; ++i ) {
if ( dbm[i][i] != 0 ) return( false );
}
// The value added represents the number of newly added events
// before this call to is_consistent. If after canonicalization
// the dbm shows that any of these newly added events must
// fire BEFORE events already in the dbm, then this dbm
// is not consistent. It is not consistent because if an event is
// already in the dbm, than that event has already have fired!
// Thus, a newly added event could not have fired before an event
// already in the dbm.
for ( index_type i = start_of_new_events ; i < size_dbm ; ++i ) {
for ( index_type j = 0 ; j < start_of_new_events ; ++j ) {
if ( dbm[i][j] < 0 ) return( false );
}
}
return( true );
}
void POSET::remove_duplicates() {
if ( ptr_map == NULL || dbm == NULL ) return;
// Build the "duplicated in index_map" list
event_set Edup;
build_duplicate_set( insert_iterator<event_set>( Edup, Edup.begin() ) );
// Compute the new size of the POSET and allocate its memory.
size_type new_size = get_size() - Edup.size();
//size_type new_size = get_size() - Edup.size();
if ( new_size == get_size() ) return;
event_map* ptr_new_map = new event_map( new_size );
if ( ptr_new_map == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
// Mark events that should be deleted and remove those events
// from the index map
event_set Enotin;
update_and_mark_dbm( ptr_new_map, Enotin, Edup );
// copy and shrink the dbm according the marked entries from
// the update_and_mark_dbm function.
size_type old_size = get_size();
bound_type** new_dbm = copy_shrink_dbm( dbm, old_size, new_size );
// Delete and reassign the dbm and ptr_map
delete_dbm( dbm, old_size );
delete ptr_map;
dbm = new_dbm;
ptr_map = ptr_new_map;
}
void POSET::remove_non_causal( const event_set& E ) {
if ( ptr_map == NULL || dbm == NULL ) return;
// Build the "not in E" list
event_set Enotin;
build_not_in_set( E, insert_iterator<event_set>( Enotin, Enotin.begin() ) );
// Build the "duplicated in index_map" list
event_set Edup;
build_duplicate_set( insert_iterator<event_set>( Edup, Edup.begin() ) );
// Compute the new size of the POSET and allocate its memory.
size_type new_size = get_size() - Enotin.size() - Edup.size();
//size_type new_size = get_size() - Edup.size();
if ( new_size == get_size() ) return;
event_map* ptr_new_map = new event_map( new_size );
if ( ptr_new_map == NULL ) {
string errorStr = "ERROR: out of memory";
throw( new error( errorStr ) );
}
// Mark events that should be deleted and remove those events
// from the index mar
update_and_mark_dbm( ptr_new_map, Enotin, Edup );
// copy and shrink the dbm according the marked entries from
// the update_and_mark_dbm function.
size_type old_size = get_size();
bound_type** new_dbm = copy_shrink_dbm( dbm, old_size, new_size );
// Delete and reassign the dbm and ptr_map
delete_dbm( dbm, old_size );
delete ptr_map;
dbm = new_dbm;
ptr_map = ptr_new_map;
}
void POSET::clear_separations_on_rows( unsigned int added ) {
index_type size_dbm = get_size();
index_type start_of_new_events = size_dbm - added;
for ( index_type i = start_of_new_events ; i < size_dbm ; ++i ) {
for ( index_type j = 0 ; j < size_dbm ; ++j ) {
if ( i == j ) continue;
dbm[i][j] = _UNBOUNDED_;
}
}
}
//---------------------------------------------------void POSET::set_order
// Adds a relation to the POSET constraining e to always fire before f
// (i.e., dbm[e][f] = 0 or t(e) - t(f) <= 0).
//------------------------------------------------------------------------
void POSET::set_order( event_type e, event_type f ) {
index_type index_e = 0, index_f = 0;
if ( !( get_separation_indexes( index_e, index_f, e, f ) ) ) return;
// t(e) - t(f) < v -> Think in terms of a rule <e,f,l,u>
// MEANING: event e will always happen before event f
if (dbm[index_e][index_f] > 0)
dbm[index_e][index_f] = 0;
}
//------------------------------------------------------------------------
//------------------------------------------bound_type POSET::get_max_over
// Returns the maximum allowed separation between e and any events
// in the POSET from the index 'added' to the end of the POSET.
//------------------------------------------------------------------------
POSET::bound_type POSET::get_max_over( event_type e,
unsigned int added ) {
index_type index_e = 0;
if ( !( get_freshest_index( index_e, e ) ) ) {
return( _UNBOUNDED_ );
}
index_type size_dbm = get_size();
index_type start_of_new_events = size_dbm - added;
POSET::bound_type max_bound = 0;
for ( index_type i = start_of_new_events ; i < size_dbm ; ++i ) {
bound_type tmp = dbm[i][index_e];
if ( tmp > max_bound ) {
max_bound = tmp;
}
}
return( max_bound );
}
//------------------------------------------------------------------------
//--------------------------------------------------------bool is_in_POSET
bool POSET::is_in_POSET( event_type e ) const {
size_type size_dbm = get_size();
for ( index_type k = 0 ; k < size_dbm ; ++k )
if ( e == get_event( k ) )
return( true );
return( false );
}
//------------------------------------------------------------------------
//--------------------------------------------------------bool is_in_POSET
bool POSET::is_in_POSET( event_type e, unsigned added ) const {
size_type size_dbm = get_size() - added;
for ( index_type k = 0 ; k < size_dbm ; ++k )
if ( e == get_event( k ) )
return( true );
return( false );
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
ostream& POSET::dump( ostream& s, const tel& t ) const {
if ( ptr_map->size() == 0 ) {
return( s );
}
size_type w = max_length( t ) + 1;
// Output the column labels
s << setw( w+1 ) << " ";
for ( event_map::const_iterator i = ptr_map->begin() ;
i != ptr_map->end() ;
++i ) {
s << setw( w ) << t.get_event( *i );
}
s << endl << setw( w+1 ) << " ";
for ( index_type i = 0 ; i < ptr_map->size() ; ++i ) {
s << setw( w ) << setfill( '-' ) << "-" << setfill( ' ' );
}
// Print the matrix with Row identifiers.
s << endl;
event_map::const_iterator name = ptr_map->begin();
for ( index_type i = 0 ; i < ptr_map->size() ; ++i, ++name ) {
if ( i ) s << endl;
s << setw( w ) << t.get_event( *name ) << "|";
for ( index_type j = 0 ; j < ptr_map->size() ; ++j ) {
if ( dbm[i][j] == _UNBOUNDED_ ) {
s << setw( w ) << "U";
}
else {
s << setw( w ) << dbm[i][j];
}
}
}
s << endl;
return( s );
}
//------------------------------------------------------------------------
//
//////////////////////////////////////////////////////////////////////////
| true |
4bb463812771252cfa76c8257e48ead3c58a730a | C++ | myevan/el.lua | /Sources/Delegate.h | UTF-8 | 4,139 | 3.34375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <memory>
#include <functional>
#include <cassert>
namespace EL
{
class HandleManager
{
public:
uint32_t AllocHandle()
{
uint32_t handle;
if (m_freeIndices.empty())
{
handle = GenerateHandle(m_totalHandles.size());
m_totalHandles.push_back(handle);
}
else
{
handle = GenerateHandle(m_freeIndices.back());
m_freeIndices.pop_back();
}
return handle;
}
bool TryFreeHandle(uint32_t handle, uint32_t& outIndex)
{
outIndex = GetHandleIndex(handle);
if (m_totalHandles[outIndex] == handle)
{
m_totalHandles[outIndex] = 0;
m_freeIndices.push_back(outIndex);
return true;
}
else
{
return false;
}
}
uint32_t GetHandleIndex(uint32_t handle)
{
return handle & 0xffffff;
}
private:
uint32_t GenerateHandle(size_t index)
{
static uint32_t s_seq = 1;
uint32_t handle = (s_seq << 24) | (index & 0xffffff);
s_seq += 2;
s_seq &= 0xff;
return handle;
}
private:
std::vector<uint32_t> m_totalHandles;
std::vector<uint32_t> m_freeIndices;
};
class DelegateHelper
{
public:
template<typename Func>
static uint32_t Add(HandleManager& handleManager, std::vector<Func>& funcs, Func func)
{
uint32_t handle = handleManager.AllocHandle();
uint32_t index = handleManager.GetHandleIndex(handle);
if (index < funcs.size())
{
funcs[index] = func;
}
else
{
funcs.push_back(func);
}
return handle;
}
template<typename Func>
static bool Remove(HandleManager& handleManager, std::vector<Func>& funcs, uint32_t handle)
{
uint32_t index;
if (handleManager.TryFreeHandle(handle, index))
{
assert(index < funcs.size());
funcs[index] = nullptr;
return true;
}
else
{
return false;
}
}
};
template<typename ... ArgTypes>
class Delegate
{
public:
using Func = std::function<void(ArgTypes...)>;
public:
uint32_t Add(Func func)
{
return DelegateHelper::Add(m_handleManager, m_funcs, func);
}
void Remove(uint32_t handle)
{
return DelegateHelper::Remove(m_handleManager, m_funcs, handle);
}
void Run(ArgTypes... args)
{
for (const Func& func : m_funcs)
{
if (func != nullptr)
{
func(args...);
}
}
}
public:
template<typename T>
void operator()(ArgTypes... args)
{
Run(args...);
}
private:
HandleManager m_handleManager;
private:
std::vector<Func> m_funcs;
};
template<>
class Delegate<void>
{
public:
using Func = std::function<void(void)>;
public:
uint32_t Add(Func func)
{
return DelegateHelper::Add(m_handleManager, m_funcs, func);
}
bool Remove(uint32_t handle)
{
return DelegateHelper::Remove(m_handleManager, m_funcs, handle);
}
void Run()
{
for (const Func& func : m_funcs)
{
if (func != nullptr)
{
func();
}
}
}
public:
void operator()()
{
Run();
}
private:
HandleManager m_handleManager;
private:
std::vector<Func> m_funcs;
};
}
| true |
7edb9edcfc820b67b8572fd2d14504b5d4252b2f | C++ | vaibhavdangayachvd/CPP-Programming | /Practise/Design Patterns/Factory Design/main.cpp | UTF-8 | 351 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<conio.h>
#include "implementation\\factory.cpp"
int main()
{
toy *ptr;
while(true)
{
system("cls");
ptr=factory::create_toy();
if(ptr)
ptr->show_product();
else
std::cout<<"\nProduct not found !!";
getch();
}
return 0;
}
| true |
ddafd05cd461a936978f97da7bba856ca96d0529 | C++ | taronegeorage/AlgorithmTraining | /Dynamic Programming/8.Burst Balloons/solution.cpp | UTF-8 | 560 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
vector<int> newnum(n+2, 1);
for(int i = 1; i <= n; i++) newnum[i] = nums[i-1];
vector<vector<int> > c(n+2, vector<int>(n+2, 0));
for(int l = 1; l <= n; ++l)
for(int i = 1; i <= n-l+1; ++i) {
int j = i+l-1;
for(int k = i; k <= j; ++k)
c[i][j] = max(c[i][j], c[i][k-1]+newnum[i-1]*newnum[k]*newnum[j+1]+c[k+1][j]);
}
return c[1][n];
}
};
| true |
e9bde4e99f07b6ced5d9c6c78eb8feec69467576 | C++ | Solairseir/StereoVisionRobotMM1 | /Robot Vision Windows/Robot Vision Windows/Headers/IMUCommunication.h | UTF-8 | 1,486 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "SerialPorts.h"
namespace RobotVisionWindows {
public ref class IMUCommunication
{
private:
SerialPorts IMUPort;
float Yaw;
float Pitch;
float Roll;
public:
bool Initialize(System::String^ Portname,int BuadRate){
return IMUPort.PortOpen(Portname,BuadRate);
}
//********************************
bool ClosePort(){
return IMUPort.PortClose();
}
//********************************
bool PortIsOpen(){
return IMUPort.PortIsOpen();
}
//********************************
std::pair<int,std::pair<int,int>> ReadData(void){
std::pair<int,std::pair<int,int>> Output;
IMUPort.PortWriteLine("#f");
System::String^ Message=IMUPort.PortRead();
analyzeData(Message);
Output.first = (int)Yaw;
Output.second.first = (int)Pitch;
Output.second.second = (int)Roll;
return Output;
}
//********************************
void analyzeData(System::String^ inputstr){
try{
if(!System::String::Compare(inputstr->Substring(0,5),"#YPR=",true)){
inputstr = inputstr->Substring(5);
int pos = inputstr->IndexOf(',');
Yaw = float::Parse(inputstr->Substring(0,pos));
Yaw +=90;
inputstr = inputstr->Substring(pos+1);
pos = inputstr->IndexOf(',');
Pitch = float::Parse(inputstr->Substring(0,pos));
inputstr = inputstr->Substring(pos+1);
Roll = float::Parse(inputstr);}
}
catch(...){
Yaw = 0;
Pitch = 0;
Roll = 0;}
}
//********************************
};
} | true |
9428228329a65634f942b8671949ca89ac3b0aff | C++ | BFriedrichs/uni | /Programming/friedrichs_3003421_ex12/task02/queue.tpp | UTF-8 | 1,766 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include "queue.hpp"
/**
* @brief Queue Constructor
*/
template<class T>
Queue<T>::Queue() {
this->list = new List<T>;
}
/**
* @brief Queue Destructor
*/
template<class T>
Queue<T>::~Queue() {
delete this->list;
}
/**
* @brief Add an item to back of the queue
*
* @param T, item to be added to back
*/
template<class T>
void Queue<T>::add(const T &value) {
this->list->add(value);
}
/**
* @brief Removes an item from the front of the queue and returns it
*
* @return T, item that got deleted
*/
template<class T>
T Queue<T>::remove() {
return this->list->remove_front();
}
/**
* @brief Returns true if queue is empty
*
* @return bool, is the list empty?
*/
template<class T>
bool Queue<T>::isEmpty() {
return this->list->isEmpty();
}
/**
* @brief Checks if the supplied item is already in the queue
*
* @param T, item to be checked
* @return bool, item in the queue?
*/
template<class T>
bool Queue<T>::contains(const T &obj) {
return this->list->contains(obj);
}
/**
* @brief Removes every item from the queue
*/
template<class T>
void Queue<T>::clear() {
this->list->clear();
}
/**
* @brief returns size of the queue
*
* @return int, item count
*/
template<class T>
int Queue<T>::getSize() {
return this->list->getSize();
}
/**
* @brief returns an iterator at front of queue
*
* @return QueueIterator
*/
template<class T>
QueueIterator<T> Queue<T>::begin() {
QueueIterator<T> it(this->list->getFirst());
return it;
}
/**
* @brief returns an iterator at end of queue
*
* @return QueueIterator
*/
template<class T>
QueueIterator<T> Queue<T>::end() {
QueueIterator<T> it(this->list->getFirst());
for(int i = 0; i < this->getSize(); ++it, i++);
return it;
}
| true |
9b3f7ea6deb8adcd9d9573c5cd0a216553fd8b81 | C++ | DouglassValenzuela/Programacion2 | /Determinar Numero/main.cpp | UTF-8 | 435 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include<stdlib.h>
//ingresar un numero y determinar si es positivo, negativo o cero
using namespace std;
int numero;
int main()
{
cout<<"Ingresar un numero";
cin>> numero;
if (numero>0)
{
cout<<"Es positivo";
}
else if (numero<0)
{
cout<<"Es Negativo";
}
else
{
cout<<"es cero";
}
cout<<"\n";
system("PAUSE");
}
| true |
52d64215464e315bf75a34cc1366e4c15564c769 | C++ | SunInTeo/ImageEditor-Parser | /Header Files/Command.h | UTF-8 | 1,608 | 3.84375 | 4 | [] | no_license | /** @file Command.h
* @brief
*
* Class Command helps with processing given commands.
*
* @author Teodor Karushkov
* @bug No known bugs.
*/
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
class Command
{
private:
std::string rawString;
std::vector<std::string> arrString;
public:
/** @brief Constructor. Receives a raw string of commands and
* divides them into different ones and
* puts them in a container(the vector of commands).
* @param string raw string which is parsed into different commands
*/
Command(std::string);
/** @brief When called returns the raw string that was first handed.
* @return the original string passed to the constructor
*/
std::string getCommand();
/** @brief When called returns the size of the vector(the container).
* @return int value
*/
int getSize() const;
/** @brief Prints commands.
* Used in unite tests only.
* @return Void.
*/
void print();
/** @brief Returns the string that is at the given position in the vector.
*
* @param pos the position of the command we are looking for
* @return command as a string
*/
std::string &operator[](size_t pos);
/** @brief Returns the string that is at the given position in the vector.
* But wurks for const.
* @param pos the position of the command we are looking for
* @return command as a string
*/
const std::string &operator[](size_t pos) const;
};
| true |
67a0b70a3addcefa3879a656a1368ac79b329374 | C++ | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/agc026/A/4634370.cpp | UTF-8 | 847 | 2.609375 | 3 | [] | no_license | #include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
typedef long long int ll;
int main(int argc, char const *argv[]) {
int N;
cin >> N;
vector<int> a(N);
for (size_t i = 0; i < a.size(); i++) {
cin >> a[i];
}
vector<int> a_continuity;
for (size_t i = 1; i < a.size(); i++) {
if (a[i - 1] == a[i]) {
if (a_continuity.empty()) {
a_continuity.push_back(2);
} else {
a_continuity.back()++;
}
} else {
a_continuity.push_back(1);
}
//cout << "debug;" << a_continuity[i] << endl;
}
int ans = 0;
for (size_t i = 0; i < a_continuity.size(); i++) {
ans += a_continuity[i] / 2;
// cout << a_continuity[i] << endl;
}
cout << ans << endl;
return 0;
} | true |
bdf9108f711516c7fa63c176d84f310af0d52825 | C++ | HGD-CodeMe/c_or_cpp | /My Procedure/c++/39.cpp | UTF-8 | 301 | 2.796875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void swap(int a[10])
{
int i,j,t;
for(j=0;j<10;j++)
for(i=0;i<9-j;i++)
if(a[i]>a[i+1])
{
t=a[i+1];
a[i+1]=a[i];
a[i]=t;
}
for(i=0;i<10;i++)
cout<<a[i];
}
main()
{
int x[10];
int i;
for(i=0;i<10;i++)
cin>>x[i];
swap(x);
}
| true |
1269d852af519122f8c4199ec4f45d18306de343 | C++ | cmarcario/FieaGameEngine | /ActionIncrement.h | UTF-8 | 2,391 | 3.03125 | 3 | [] | no_license | #pragma once
#include "Action.h"
#include "Factory.h"
#include "Signature.h"
namespace FieaGameEngine
{
/// <summary>
/// ActionIncrement class
/// increments a set target (float) by the step
/// </summary>
class ActionIncrement : public Action
{
RTTI_DECLARATIONS(ActionIncrement, Action);
public:
/// <summary>
/// action increment constructor
/// </summary>
ActionIncrement();
/// <summary>
/// action increment default copy constructor
/// </summary>
ActionIncrement(const ActionIncrement&) = default;
/// <summary>
/// action increment default move constructor
/// </summary>
ActionIncrement(ActionIncrement&&) = default;
/// <summary>
/// actionIncrement default destructor
/// </summary>
~ActionIncrement() = default;
/// <summary>
/// returns the key of target to be incremented
/// </summary>
/// <returns>the key of target to be incremented</returns>
const std::string& Target() const;
/// <summary>
/// sets the target to be incremented
/// </summary>
/// <param name="target">the key of the target to be incremented</param>
void SetTarget(const std::string& target);
/// <summary>
/// returns the step to increment the target by
/// </summary>
/// <returns>the step to increment the target by</returns>
float Step() const;
/// <summary>
/// sets the step to increment the target by
/// </summary>
/// <param name="step">the new step</param>
void SetStep(float step);
/// <summary>
/// returns a heap allocated copy of itself
/// </summary>
/// <returns>a heap allocated copy of itself</returns>
ActionIncrement* Clone() override;
/// <summary>
/// goes to the target and increments it by the step
/// </summary>
/// <param name="worldState">the worldstate to increment the target by</param>
void Update(WorldState& worldState) override;
/// <summary>
/// signatures for actionincrement
/// </summary>
/// <returns>signatures for actionincrement</returns>
static const Vector<Signature> Signatures();
private:
/// <summary>
/// helper function that increments the target
/// </summary>
void IncrementTarget();
/// <summary>
/// the target to increment
/// </summary>
std::string m_Target;
/// <summary>
/// the step to increment the target by
/// </summary>
float m_Step = 1.0f;
};
ConcreteFactory(ActionIncrement, Scope);
}
| true |
3771b1527281010cd9a8481108a5c16a92e3269a | C++ | iiison/technical-interview-prep | /LeetCode/Previous-Permutation-with-One-Swap.cpp | UTF-8 | 934 | 3.828125 | 4 | [] | no_license | /* Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot be done, then return the same array.
Example 1:
Input: [3,2,1]
Output: [3,1,2]
Explanation: Swapping 2 and 1.
Example 2:
Input: [1,1,5]
Output: [1,1,5]
Explanation: This is already the smallest permutation.
Example 3:
Input: [1,9,4,6,7]
Output: [1,7,4,6,9]
Explanation: Swapping 9 and 7.
Example 4:
Input: [3,1,1,3]
Output: [1,3,1,3]
Explanation: Swapping 1 and 3. */
vector<int> prevPermOpt1(vector<int>& A) {
int n = A.size(), left = n - 2, right = n - 1;
while (left >= 0 && A[left] <= A[left + 1]) left--;
if (left < 0) return A;
while (A[left] <= A[right]) right--;
while (A[right - 1] == A[right]) right--;
swap(A[left], A[right]);
return A;
}
| true |
72bf1acb08d98fafb467fdee82356714e1a847df | C++ | RoboSherlock/robosherlock | /robosherlock/src/segmentation/symmetrysegmentation/include/robosherlock/NonLinearOptimization/Functor.hpp | UTF-8 | 6,061 | 2.5625 | 3 | [] | no_license | /**
* Copyright 2014 University of Bremen, Institute for Artificial Intelligence
* Author(s): Ferenc Balint-Benczedi <balintbe@cs.uni-bremen.de>
* Thiemo Wiedemeyer <wiedemeyer@cs.uni-bremen.de>
* Jan-Hendrik Worch <jworch@cs.uni-bremen.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __FUNCTOR_HPP__
#define __FUNCTOR_HPP__
#include <unsupported/Eigen/NonLinearOptimization>
#include <robosherlock/symmetrysegmentation/RotationalSymmetry.hpp>
#include <robosherlock/symmetrysegmentation/BilateralSymmetry.hpp>
#include <robosherlock/mapping/DistanceMap.hpp>
#include <pcl/registration/correspondence_rejection_one_to_one.h>
/** \brief This supper struct (functor) was implemented for compatible use of Eigen NonLinearOptimization module.
* Each model of non linear optimization must be overrived its own operator() as a child of this class, based on choosen Scalar*/
template <typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>
struct OptimizationFunctor
{
/** \brief Type for compatible purpose with Eigen::NumericalDiff class. It represents type of variable for optimization (float, symmetries, etc) */
typedef _Scalar Scalar;
enum
{
InputsAtCompileTime = NX,
ValuesAtCompileTime = NY
};
typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;
typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;
typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;
int m_inputs, m_outputs;
OptimizationFunctor() : m_inputs(InputsAtCompileTime), m_outputs(ValuesAtCompileTime) {}
OptimizationFunctor(int inputs, int outputs) : m_inputs(inputs), m_outputs(outputs) {}
int inputs() const { return m_inputs; }
int values() const { return m_outputs; }
};
/** \brief Child struct (functor) of OptimizationFunctor, it is the model for optimizing RotationalSymmetry poses.
* Given 3D pointcloud with normals and an initial 3D rotational symmetry axis refine the symmetry axis such that
* it minimizes the error of fit between the symmetry and the points.
* \note The result optimizing may have non-unit normals
*/
template<typename PointT>
struct RotSymOptimizeFunctor : OptimizationFunctor<float>
{
/** \brief input cloud. */
typename pcl::PointCloud<PointT>::Ptr cloud;
/** \brief input normals. */
typename pcl::PointCloud<pcl::Normal>::Ptr normals;
/** \brief max fit error of symmetry and point normal. */
float max_fit_angle;
/** \brief Default constructor. */
RotSymOptimizeFunctor() : max_fit_angle(1.0f) {}
/** \brief overrived method of optimization for RotationalSymmetry, it it minimizes the error of fit between the symmetry and the points */
int operator()(const Eigen::VectorXf &x, Eigen::VectorXf &fvec) const
{
RotationalSymmetry symmetry(x.head(3), x.tail(3));
for(size_t it = 0; it < cloud->points.size(); it++)
{
Eigen::Vector3f point = cloud->points[it].getVector3fMap();
Eigen::Vector3f normal( normals->points[it].normal_x, normals->points[it].normal_y, normals->points[it].normal_z);
float angle = getRotSymFitError(point, normal, symmetry);
fvec(it) = std::min(angle, max_fit_angle);
}
return 0;
}
/** \brief Dimension of input parameter, in this case: 6 for position and orientation of RotationalSymmetry. */
int inputs() const { return 6; }
/** \brief Cloud point size. */
int values() const { return this->cloud->points.size(); }
};
/** \brief A dumb struct interfaces with Eigen::NonLinearOptimization */
template <typename PointT>
struct RotSymOptimizeFunctorDiff : Eigen::NumericalDiff< RotSymOptimizeFunctor<PointT> > {};
/** \brief Child struct (functor) of OptimizationFunctor, it is the model for optimizing BilateralSymmetry poses.
* Given 3D original cloud and downsampled cloud with normals and an initial 3D bilateral symmetry, refine the symmetry normal such that
* it minimizes the error of distance between downsampled point to plane of reflected original point and normal.
* \note The result optimizing may have non-unit normals
*/
template<typename PointT>
struct BilSymOptimizeFunctor : OptimizationFunctor<float>
{
typename pcl::PointCloud<PointT>::Ptr cloud;
typename pcl::PointCloud<pcl::Normal>::Ptr normals;
typename pcl::PointCloud<PointT>::Ptr dsCloud;
pcl::Correspondences correspondences;
BilSymOptimizeFunctor() {};
int inputs() const { return 6; }
int values() const { return this->correspondences.size(); }
int operator()(const Eigen::VectorXf &x, Eigen::VectorXf &fvec) const
{
BilateralSymmetry symmetry(x.head(3), x.tail(3));
for(size_t it = 0; it < this->correspondences.size(); it++)
{
int srcPointId = correspondences[it].index_query;
int tgtPointId = correspondences[it].index_match;
Eigen::Vector3f srcPoint = dsCloud->points[srcPointId].getVector3fMap();
Eigen::Vector3f tgtPoint = cloud->points[tgtPointId].getVector3fMap();
Eigen::Vector3f tgtNormal(normals->points[tgtPointId].normal_x, normals->points[tgtPointId].normal_y, normals->points[tgtPointId].normal_z);
Eigen::Vector3f reflectedTgtPoint = symmetry.reflectPoint(tgtPoint);
Eigen::Vector3f reflectedTgtNormal = symmetry.reflectPoint(tgtNormal);
fvec(it) = std::abs(pointToPlaneSignedNorm<float>(srcPoint, reflectedTgtPoint, reflectedTgtNormal));
}
return 0;
}
};
/** \brief A dumb struct interfaces with Eigen::NonLinearOptimization */
template <typename PointT>
struct BilSymOptimizeFunctorDiff : Eigen::NumericalDiff< BilSymOptimizeFunctor<PointT> > {};
#endif // __FUNCTOR_HPP__
| true |
0c8d269f4035297b59d01a35250f28d48389ab5a | C++ | Cesea/Portfolio | /Hunter/ApplicationTimer.h | UTF-8 | 798 | 2.515625 | 3 | [] | no_license | #ifndef APPLICATION_TIMER_H
#define APPLICATION_TIMER_H
#include "SingletonBase.h"
class ApplicationTimer : public SingletonBase<ApplicationTimer>
{
public :
ApplicationTimer();
~ApplicationTimer();
void Initialize(int32 targetMS);
void Tick();
inline float GetDeltaTime() { return (float)_currentDeltaSecond; }
inline int32 GetDeltaMS() { return _currentDeltaMS; }
inline float GetTargetTime() { return _targetFramePerMS / 1000.0f; }
float GetTotalTimeElapsed();
private :
LARGE_INTEGER _prevCounter;
LARGE_INTEGER _currentCounter;
LARGE_INTEGER _startCounter;
double _timeScale;
LARGE_INTEGER _frequency;
int32 _currentDeltaMS;
double _currentDeltaSecond;
double _targetFrameSecond;
int32 _targetFramePerMS;
};
#define APPTIMER ApplicationTimer::GetInstance()
#endif | true |
00f655b8e386c25c0921e8965cefdf1caf9e0e22 | C++ | arifkhan1990/Competitive-Programming | /Data Structure/Stack/implementation/stack.cpp | UTF-8 | 603 | 3.21875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int stk[10001];
int top = -1;
void push(int data, int n)
{
if(top != n-1) {
stk[++top] = data;
}
}
bool empty()
{
return (top == -1)? 1:0;
}
void pop()
{
if(!empty()) top--;
}
int size()
{
return top+1;
}
int topData()
{
return stk[top];
}
int main()
{
int n,m;
cin >> n;
for(int i =0; i < n; i++) {
cin >> m;
push(m,n);
}
cout << "Size of Stack : " << size() << endl;
while(!empty()) {
cout << topData() << " ";
pop();
}
cout << endl;
return 0;
}
| true |
222ab856a4c0b4e93ec6c27a346a906b30f78632 | C++ | zh7314/drogon_test | /third_party/drogon/orm_lib/src/ArrayParser.cc | UTF-8 | 7,602 | 3 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | /** Handling of SQL arrays.
*
* Copyright (c) 2018, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
// Taken from libpqxx and modified
/**
*
* ArrayParser.cc
* An Tao
*
* Copyright 2018, An Tao. All rights reserved.
* https://github.com/an-tao/drogon
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Drogon
*
*/
#include <cassert>
#include <cstddef>
#include <cstring>
#include <utility>
#include <drogon/orm/ArrayParser.h>
#include <drogon/orm/Exception.h>
using namespace drogon::orm;
namespace
{
/// Find the end of a single-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
* This is used for array parsing, where the database may send us strings
* stored in the array, in a quoted and escaped format.
*
* Returns the address of the first character after the closing quote.
*/
const char *scan_single_quoted_string(const char begin[])
{
const char *here = begin;
assert(*here == '\'');
for (here++; *here; here++)
{
switch (*here)
{
case '\'':
// Escaped quote, or closing quote.
here++;
// If the next character is a quote, we've got a double single
// quote. That's how SQL escapes embedded quotes in a string.
// Terrible idea, but it's what we have.
if (*here != '\'')
return here;
// Otherwise, we've found the end of the string. Return the
// address of the very next byte.
break;
case '\\':
// Backslash escape. Skip ahead by one more character.
here++;
if (!*here)
throw ArgumentError("SQL string ends in escape: " +
std::string(begin));
break;
}
}
throw ArgumentError("Null byte in SQL string: " + std::string(begin));
}
/// Parse a single-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
*/
std::string parse_single_quoted_string(const char begin[], const char end[])
{
// There have to be at least 2 characters: the opening and closing quotes.
assert(begin + 1 < end);
assert(*begin == '\'');
assert(*(end - 1) == '\'');
std::string output;
// Maximum output size is same as the input size, minus the opening and
// closing quotes. In the worst case, the real number could be half that.
// Usually it'll be a pretty close estimate.
output.reserve(std::size_t(end - begin - 2));
for (const char *here = begin + 1; here < end - 1; here++)
{
auto c = *here;
// Skip escapes.
if (c == '\'' || c == '\\')
here++;
output.push_back(c);
}
return output;
}
/// Find the end of a double-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
*/
const char *scan_double_quoted_string(const char begin[])
{
const char *here = begin;
assert(*here == '"');
for (here++; *here; here++)
{
switch (*here)
{
case '\\':
// Backslash escape. Skip ahead by one more character.
here++;
if (!*here)
throw ArgumentError("SQL string ends in escape: " +
std::string(begin));
break;
case '"':
return here + 1;
}
}
throw ArgumentError("Null byte in SQL string: " + std::string(begin));
}
/// Parse a double-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
*/
std::string parse_double_quoted_string(const char begin[], const char end[])
{
// There have to be at least 2 characters: the opening and closing quotes.
assert(begin + 1 < end);
assert(*begin == '"');
assert(*(end - 1) == '"');
std::string output;
// Maximum output size is same as the input size, minus the opening and
// closing quotes. In the worst case, the real number could be half that.
// Usually it'll be a pretty close estimate.
output.reserve(std::size_t(end - begin - 2));
for (const char *here = begin + 1; here < end - 1; here++)
{
auto c = *here;
// Skip escapes.
if (c == '\\')
here++;
output.push_back(c);
}
return output;
}
/// Find the end of an unquoted string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
*/
const char *scan_unquoted_string(const char begin[])
{
assert(*begin != '\'');
assert(*begin != '"');
const char *p;
for (p = begin; *p != ',' && *p != ';' && *p != '}'; p++)
;
return p;
}
/// Parse an unquoted SQL string.
/** Here, the special unquoted value NULL means a null value, not a string
* that happens to spell "NULL".
*/
std::string parse_unquoted_string(const char begin[], const char end[])
{
return std::string(begin, end);
}
} // namespace
ArrayParser::ArrayParser(const char input[]) : pos_(input)
{
}
std::pair<ArrayParser::juncture, std::string> ArrayParser::getNext()
{
ArrayParser::juncture found;
std::string value;
const char *end;
if (pos_ == nullptr)
{
found = juncture::done;
end = nullptr;
}
else
switch (*pos_)
{
case '\0':
found = juncture::done;
end = pos_;
break;
case '{':
found = juncture::row_start;
end = pos_ + 1;
break;
case '}':
found = juncture::row_end;
end = pos_ + 1;
break;
case '\'':
found = juncture::string_value;
end = scan_single_quoted_string(pos_);
value = parse_single_quoted_string(pos_, end);
break;
case '"':
found = juncture::string_value;
end = scan_double_quoted_string(pos_);
value = parse_double_quoted_string(pos_, end);
break;
default:
end = scan_unquoted_string(pos_);
value = parse_unquoted_string(pos_, end);
if (value == "NULL")
{
// In this one situation, as a special case, NULL means a
// null field, not a string that happens to spell "NULL".
value.clear();
found = juncture::null_value;
}
else
{
// The normal case: we just parsed an unquoted string. The
// value is what we need.
found = juncture::string_value;
}
break;
}
// Skip a field separator following a string (or null).
if (end != nullptr && (*end == ',' || *end == ';'))
end++;
pos_ = end;
return std::make_pair(found, value);
}
| true |
df8879c4fa85cb77239a8781901c93755453f487 | C++ | aryansj/data-structures- | /bfs.cpp | UTF-8 | 1,423 | 3.609375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void addEdge(int x, int y, vector <int> *adj){ // function to add an edge from node x to node y
adj[x].push_back(y);
}
void bfs(int start, int n, vector <int> *adj){
bool visited[n]; // create an array of boolean to check if a node is visited
int i;
for(i = 0; i < n; i++)
visited[i] = false;
vector <int> v;
visited[start] = true;
v.push_back(start);
while( v.size() != 0 ){
int temp = v.front();
cout << temp << " ";
v.erase(v.begin());
for(i = 0; i < adj[temp].size(); i++){ // iterate through all unvisited neighbours of the front element and push them in the vector
if(!visited[adj[temp][i]]){
visited[adj[temp][i]] = true;
v.push_back(adj[temp][i]);
}
}
}
}
int main() {
int size;
cin >> size;
vector <int> adj[size];
addEdge(1, 2, adj);
addEdge(2, 1, adj);
addEdge(2, 5, adj);
addEdge(5, 2, adj);
addEdge(1, 3, adj);
addEdge(3, 1, adj);
addEdge(3, 6, adj);
addEdge(6, 3, adj);
addEdge(4, 1, adj);
addEdge(1, 4, adj);
addEdge(4, 7, adj);
addEdge(7, 4, adj);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 1) \n";
bfs(1, size, adj);
return 0;
} | true |
e6dceaab9e0e2a9a1e54716203bfd5478856a483 | C++ | tectronics/cvekas | /source/VertexFormat.cpp | UTF-8 | 3,931 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "VertexFormat.h"
namespace Cvekas {
VertexFormat::VertexFormat()
:
has_position(false),
number_of_uvs(0),
has_normal(false),
has_binormal(false),
has_tangent(false),
has_color(false),
needs_rebuild(false),
declaration(NULL)
{
}
VertexFormat::VertexFormat(bool position, uint UVs, bool normal, bool binormal, bool tangent, bool color)
:
has_position(position),
number_of_uvs(UVs),
has_normal(normal),
has_binormal(binormal),
has_tangent(tangent),
has_color(color),
needs_rebuild(true),
declaration(NULL)
{
}
VertexFormat::~VertexFormat()
{
safeRelease(declaration);
}
uint VertexFormat::getSize() const
{
int size = 0;
size += has_position ? 12 : 0;
size += number_of_uvs * 8;
size += has_normal ? 12 : 0;
size += has_binormal ? 12 : 0;
size += has_tangent ? 12 : 0;
size += has_color ? 4 : 0;
return size;
}
uint VertexFormat::getNumberOfElements() const
{
int n = 0;
if(has_position) n++;
n += number_of_uvs;
if(has_normal) n++;
if(has_binormal) n++;
if(has_tangent) n++;
if(has_color) n++;
return n;
}
IDirect3DVertexDeclaration9* VertexFormat::getD3DVertexDeclaration(D3DDevicePtr device, uint stream)
{
if(last_device != device)
{
needs_rebuild = true;
last_device = device;
}
if(needs_rebuild)
{
safeRelease(declaration);
D3DVERTEXELEMENT9* elements = new D3DVERTEXELEMENT9[getNumberOfElements() + 1];
int idx = 0;
int pos = 0;
if(has_position)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_FLOAT3;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_POSITION;
elements[idx].UsageIndex = 0;
idx++;
pos += 12;
}
else
{
LOG("Vertex declaration has no position. Is this intentional?");
}
if(has_normal)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_FLOAT3;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_NORMAL;
elements[idx].UsageIndex = 0;
idx++;
pos += 12;
}
if(has_binormal)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_FLOAT3;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_BINORMAL;
elements[idx].UsageIndex = 0;
idx++;
pos += 12;
}
if(has_tangent)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_FLOAT3;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_TANGENT;
elements[idx].UsageIndex = 0;
idx++;
pos += 12;
}
if(number_of_uvs > 0 && number_of_uvs <= 8)
{
for(uint i = 0; i < number_of_uvs; ++i)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_FLOAT2;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_TEXCOORD;
elements[idx].UsageIndex = i;
idx++;
pos += 8;
}
}
else
{
if(number_of_uvs != 0)
LOG("Number of UVs must be between 0 and 8");
}
if(has_color)
{
elements[idx].Stream = stream;
elements[idx].Offset = pos;
elements[idx].Type = D3DDECLTYPE_D3DCOLOR;
elements[idx].Method = D3DDECLMETHOD_DEFAULT;
elements[idx].Usage = D3DDECLUSAGE_COLOR;
elements[idx].UsageIndex = 0;
idx++;
pos += 4;
}
elements[idx].Stream = 0xff;
elements[idx].Offset = 0;
elements[idx].Type = D3DDECLTYPE_UNUSED;
elements[idx].Method = 0;
elements[idx].Usage = 0;
elements[idx].UsageIndex = 0;
E_E(device->CreateVertexDeclaration(elements, &declaration));
delete[] elements;
needs_rebuild = false;
}
return declaration;
}
} // namespace | true |
287163ef076468e41b4ecd27c616c0b77407e6c7 | C++ | doniaGhazy/tera_sort | /TeraSortItem.hpp | UTF-8 | 5,843 | 3.15625 | 3 | [] | no_license | #ifndef TeraSortItem_H
#define TeraSortItem_H
#include <string.h>
#include <algorithm>
#include <cstdint>
#include <inttypes.h>
typedef unsigned __int128 uint128_t;
using namespace std;
class Sortable
{
private:
public:
//pure virtual methods to be inherited to all child classes
Sortable(){}
Sortable(Sortable &sortable){}
virtual uint128_t key() = 0;
//virtual void swap(TeraSortItem *p_sortable) = 0;
virtual bool operator>(Sortable *p_sortable) = 0;
virtual bool operator<(Sortable *p_sortable) = 0;
virtual bool operator>=(Sortable *p_sortable) = 0;
virtual bool operator<=(Sortable *p_sortable) = 0;
virtual bool operator==(Sortable *p_sortable) = 0;
virtual bool operator!=(Sortable *p_sortable) = 0;
virtual ~Sortable(){}
};
typedef struct
{ //struct to read the file
uint8_t key[10];
uint8_t b1[2];
char rowid[32];
uint8_t b2[4];
uint8_t filler[48];
uint8_t b3[4];
} teraitem_r;
class TeraSortItem : public Sortable
{
private:
teraitem_r *teraitem; //pointer to tera data item
public:
static uint128_t calckey(uint8_t * ky); //calc key fn
TeraSortItem(); // default constructor
//TeraSortItem::TeraSortItem(TeraSortItem &&teraSortItem);
TeraSortItem(TeraSortItem &teraSortItem); // copy constractor
TeraSortItem(teraitem_r *p_teraitem); //overloaded constructor
uint128_t key(); //to calc the key
void swap(TeraSortItem *p_sortable); //sn to swap two objects
void operator=(TeraSortItem *teraSortItem); //overloaded = operator
void * operator new(size_t size) ; //overload new operator
bool operator>(Sortable *p_sortable); //overloaded > operator
bool operator<(Sortable *p_sortable); //overloaded < operator
bool operator>=(Sortable *p_sortable); //overloaded >= operator
bool operator<=(Sortable *p_sortable); //overloaded <= operator
bool operator==(Sortable *p_sortable); //overloaded == operator
bool operator!=(Sortable *p_sortable); //overloaded != operator
~TeraSortItem(); //deconstructor
};
TeraSortItem::TeraSortItem()
{
}
TeraSortItem::TeraSortItem(TeraSortItem &teraSortItem) // copy constractor
{
teraitem = new teraitem_r;
*teraitem = *teraSortItem.teraitem;
memcpy(teraitem,teraSortItem.teraitem,100);
}
TeraSortItem::TeraSortItem(teraitem_r *p_teraitem)//overloading constructor
{
teraitem = p_teraitem;
}
void TeraSortItem::swap(TeraSortItem *p_sortable)
{
std::swap(this->teraitem,p_sortable->teraitem);
}
void TeraSortItem:: operator=(TeraSortItem *teraSortItem)
{
memcpy(teraitem, teraSortItem->teraitem, sizeof(teraitem_r)); //memcpy fn to move data from one obkect to another
}
void * TeraSortItem:: operator new(size_t size) //overloading new operator
{
void * p = malloc(size); //allocate a new place in memory
// TeraSortItem()
return p;
}
bool TeraSortItem:: operator>(Sortable *p_sortable) //overloading > operator
{
//check if the key of the existing item is greater than the key of the incomming item
//so return true and false otherwise
if (this->key()>p_sortable->key())
return true;
else
return false;
}
bool TeraSortItem:: operator<(Sortable *p_sortable) //overloading < operator
{
//check if the key of the existing item is less than the key of the incomming item
//so return true and false otherwise
if (this->key()<p_sortable->key())
return true;
else
return false;
}
bool TeraSortItem:: operator>=(Sortable *p_sortable) //overloading >= operator
{
//check if the key of the existing item is greater than or equal the key of the incomming item
//so return true and false otherwise
if (this->key()>=p_sortable->key())
return true;
else
return false;
}
bool TeraSortItem:: operator <= (Sortable * p_sortable)//overloading <= operator
{
//check if the key of the existing item is less than or equal the key of the incomming item
//so return true and false otherwise
if (this->key()<=p_sortable->key())
return true;
else
return false;
}
bool TeraSortItem::operator == (Sortable * p_sortable) //overloading == operator
{
//check if the key of the existing item is equal to the key of the incomming item
//so return true and false otherwis
if (this->key()==p_sortable->key())
return true;
else
return false;
}
bool TeraSortItem::operator != (Sortable * p_sortable) //overloading != operator
{
//check if the key of the existing item is not equal to the key of the incomming item
//so return true and false otherwise
if (this->key()!=p_sortable->key())
return true;
else
return false;
}
uint128_t TeraSortItem::key() // to calc value of key
{
//exchange the value of the key of type 8byte into 128 byte but with revere order
//then return the value of the k i 128byte
uint8_t *v = teraitem->key;
uint128_t k = 0;
uint8_t *c = (uint8_t *)&k;
c[0] = v[9];
c[1] = v[8];
c[2] = v[7];
c[3] = v[6];
c[4] = v[5];
c[5] = v[4];
c[6] = v[3];
c[7] = v[2];
c[8] = v[1];
c[9] = v[0];
return k;
}
uint128_t TeraSortItem::calckey(uint8_t * ky) // to calc the key value into unit128
{
//cast the value of 128 byte into 8 byte and then return its value
uint8_t *v = ky;
uint128_t k = 0;
uint8_t *c = (uint8_t *)&k;
c[0] = v[9];
c[1] = v[8];
c[2] = v[7];
c[3] = v[6];
c[4] = v[5];
c[5] = v[4];
c[6] = v[3];
c[7] = v[2];
c[8] = v[1];
c[9] = v[0];
return k;
}
TeraSortItem ::~TeraSortItem() // deconstructor
{
}
#endif
| true |
de9b0a13cf97ed6bc06261547de2ccd7e7abb4ab | C++ | frovedis/frovedis | /test/core/test2.5.2/test.cc | UTF-8 | 1,487 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | #include <frovedis.hpp>
#include <boost/algorithm/string.hpp>
#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>
using namespace frovedis;
using namespace std;
std::vector<std::string> splitter(const std::string& line) {
std::vector<std::string> wordvec;
boost::split(wordvec, line, boost::is_space());
return wordvec;
}
std::pair<std::string, int> counter(const std::string& v) {
return std::make_pair(v, 1);
}
int sum(int a, int b){return a + b;}
BOOST_AUTO_TEST_CASE( frovedis_test )
{
int argc = 1;
char** argv = NULL;
use_frovedis use(argc, argv);
// testing for string counter
auto d1 = frovedis::make_dvector_loadline("./sample.txt");
auto d2 = d1.flat_map(splitter).map(counter).reduce_by_key<std::string,int>(sum);
auto r = d2.as_dvector().sort().gather();
// filling expected output vector
std::vector<std::pair<std::string,int>> ref_out;
ref_out.push_back(std::make_pair("Is", 2));
ref_out.push_back(std::make_pair("Yes", 2));
ref_out.push_back(std::make_pair("a", 3));
ref_out.push_back(std::make_pair("is", 1));
ref_out.push_back(std::make_pair("is!", 1));
ref_out.push_back(std::make_pair("it", 1));
ref_out.push_back(std::make_pair("really", 1));
ref_out.push_back(std::make_pair("test.", 1));
ref_out.push_back(std::make_pair("test?", 2));
ref_out.push_back(std::make_pair("this", 3));
BOOST_CHECK(r == ref_out);
//for(auto& i: r) std::cout << i.first << ": " << i.second << std::endl;
}
| true |
bb2198983823b18e9074120268c13a3b800f992a | C++ | pieisland/2021-coding-test-preparing | /백준/1912. 연속합(210225).cpp | UTF-8 | 942 | 2.984375 | 3 | [] | no_license | #include<cstdio>
#include<stdio.h>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int n;
int arr[100000];
int dp[100000];
//n개의 정수로 이루어진 임의의 수열이 주어지는데 연속된 몇 개의 수를 선택해 구할 수 있는 합 중 가장 큰 합 구하기.
//수는 한 개 이상 선택해야한다.
//순간, 나를 포함을 안해도 되는 거 아닌가? 라고 생각해는데
//그거는 어차피 dp[i-1]에 있는거고
//i번째를 선택했을 때의 최대값이라고 생각하면 되겠지..?
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> arr[i];
dp[0] = arr[0];
for (int i = 1; i < n; i++) {
dp[i] = max(dp[i - 1] + arr[i], arr[i]);
}
int ans = dp[0];
for (int i = 1; i < n; i++) ans = max(dp[i], ans);
cout << ans;
return 0;
}
| true |
f0fe95f10b83490cf3acbfa2f557c929ba0da55b | C++ | AmandaPrasetiyoN/stack_dengan_linkedlist | /stack_linkedlist.cpp | UTF-8 | 2,002 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
struct Node{
int no;
char nama[50];
char posisi[50];
Node *next;
};
Node *top;
class stack{
public:
void push(int n,char pos[],char name[]);
void pop();
void display();
};
void push(int n,char pos [],char name[])
{
struct Node *newNode=new Node;
newNode->no=n;
strcpy(newNode->nama,name);
strcpy(newNode->posisi,pos);
newNode->next=top;
top=newNode;
}
void pop()
{
if(top==NULL){
cout<<"data kosong!"<<endl;
return;
}
top=top->next;
}
void display()
{
if(top==NULL){
cout<<"stack kosong"<<endl;
return;
}
cout<<"isi stack"<<endl;
struct Node *temp=top;
while(temp!=NULL){
cout<<temp->no<<" -> ";
cout<<temp->nama<<" -> ";
cout<<temp->posisi;
cout<<endl;
temp=temp=temp->next;
}
cout<<endl;
}
int main(){
stack s;
int ch;
do{
int n;
cout<<endl;
cout<<"===================================================="<<endl;
cout<<"\t\tSTACK MENGGUNAKAN LINKED LIST"<<endl;
cout<<endl;
cout<<"1.PUSH \n2.POP \n3.TAMPIL \n4.EXIT"<<endl;
cout<<endl;
cout<<"Pilih (1-4) : ";cin>>ch;
switch(ch){
case 1:
Node n;
cout<<"Data Pemain Bola \n";
cout<<"===================\n";
cout<<"No Punggung : ";
cin>>n.no;
cout<<"Nama : ";
fflush(stdin);gets(n.nama);
cout<<"Posisi : ";
fflush(stdin);gets(n.posisi);
push(n.no,n.nama,n.posisi);
break;
case 2 :
pop();
break;
case 3 :
display();
break;
case 4:
break;
default :
cout<<"error\n";
break;
}
}while(ch!=4);
return 0;
}
| true |
3d995b0a56d8d43f01fded748bf64855b6fa0c1d | C++ | shailendra-singh-dev/ProgrammingChallenges | /Caribbean Online Judge COJ/1676 - Let us help George.cpp | UTF-8 | 558 | 2.953125 | 3 | [] | no_license | #include <cstdio>
#define FOR(i, a, b, c) for(i = a ; i <= b ; i += c)
using namespace std;
unsigned long long int N, i, diamonds, temp;
int main()
{
while(scanf("%llu", &N) != EOF)
{
if(!N) break;
if(N == 1)
printf("Case %llu:\nn = %llu, diamonds = %d\n", N, N, 1);
else if(N == 2)
printf("Case %llu:\nn = %llu, diamonds = %d\n", N, N, 5);
else
{
temp = 0, diamonds = 0;
FOR(i, 2, N, 1)
{
temp = i * i;
diamonds += temp;
}
printf("Case %llu:\nn = %llu, diamonds = %llu\n", N, N, diamonds + 1);
}
}
return 0;
} | true |
3bf3fdc2925f0b0d21a571145f296f2463b3799d | C++ | wonny-Jo/algorithm | /알고리즘 문제 풀이/BOJ/단계별 기초 연습/동적 계획법 1/2565_전깃줄/2565.cpp | UTF-8 | 549 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int N; cin >> N;
int num[501] = { 0 };
int a;
for (int i = 0; i < N; ++i)
{
cin >> a;
cin >> num[a];
}
int cache[101] = { 0 };
int size = 0;
for (int i = 1; i <= 500; ++i)
{
if (num[i] == 0)
continue;
if (cache[size] < num[i])
{
++size;
cache[size] = num[i];
}
else
{
int index = lower_bound(cache + 1, cache + 1 + size, num[i])-cache;
cache[index] = num[i];
}
}
cout << N - size;
return 0;
} | true |
cdfdc8916ea9e5f8004c5408015e1d83f22cee5e | C++ | lkramer37/CS302-Data-Structures | /PA06/Project/PA06.2/ExpressionTree.cpp | UTF-8 | 4,850 | 3.6875 | 4 | [] | no_license | /*In this laboratory, you construct an expression tree from the prefix form of an arithmetic expression.
*
*
*
*/
#include <iostream>
#include "ExpressionTree.h"
using namespace std;
template<typename DataType>
ExprTree<DataType>::ExprTree()
{
root = NULL;
}
template<typename DataType>
ExprTree<DataType>::ExprTree(const ExprTree &source)
{
}
template<typename DataType>
ExprTree<DataType>& ExprTree<DataType>::operator=(const ExprTree& sources)
{
}
template<typename DataType>
ExprTree<DataType>::~ExprTree()
{
}
template<typename DataType>
void ExprTree<DataType>::build()
{
buildHelper(root);
//Reads an arithmetic expression in prefix form from the keyboard and builds the corresponding expression tree.
//Read the next arithmetic operator or numeric value
//Create a node containing the operator or numeric value
//If the node contains an operator
//Recursively build the subtree that correspond to the operator's operands
//else the node is a leaf node
}
template<typename DataType>
void ExprTree<DataType>::buildHelper(ExprTreeNode*& node)
{
char temp;
cin >> temp;
switch (temp) {
case '+':
new ExprTreeNode(temp, NULL, NULL);
break;
case '-':
new ExprTreeNode(temp, NULL, NULL);
break;
case '*':
new ExprTreeNode(temp, NULL, NULL);
break;
case '/':
new ExprTreeNode(temp, NULL, NULL);
break;
case '0':
new ExprTreeNode(temp, NULL, NULL);
break;
case '1':
new ExprTreeNode(temp, NULL, NULL);
break;
case '2':
new ExprTreeNode(temp, NULL, NULL);
break;
case '3':
new ExprTreeNode(temp, NULL, NULL);
break;
case '4':
new ExprTreeNode(temp, NULL, NULL);
break;
case '5':
new ExprTreeNode(temp, NULL, NULL);
break;
case '6':
new ExprTreeNode(temp, NULL, NULL);
break;
case '7':
new ExprTreeNode(temp, NULL, NULL);
break;
case '8':
new ExprTreeNode(temp, NULL, NULL);
break;
case '9':
new ExprTreeNode(temp, NULL, NULL);
break;
}
buildHelper(left);
buildHelper(right);
//Create Node at pointer (
// "*&" means a reference to a pointer
//Call Build helper by root by reference
//if digit - Done and return
//If Operator - do work, call buildHelper
//Switch Statement?
}
template<typename DataType>
void ExprTree<DataType>::expression() const
{
//Outputs the expression corresponding to the value of the tree in fully parenthesized infix form
//prints with parentheses
//infix notation with parentheses
//in order traversal
}
template<typename DataType>
DataType ExprTree<DataType>:: evaluate() const throw(logic_error)
{
//Returns the value of the corresponding arithmetic expression
/*
switch(node->data)
{
case '+': return (evaluateHelper(node->left) + evalHelper(node->right))
}
*/
}
template<typename DataType>
void ExprTree<DataType>::clear()
{
//Removes all the ata items in the expression tree
//post traversal
}
template<typename DataType>
void ExprTree<DataType>::commute()
{
//Commutes the operands for every arithmetic operator in the expression
// a + b = b + a -> Should only be used for '+' and '*'
}
template<typename DataType>
bool ExprTree<DataType>::isEquivalent(const ExprTree &source) const
{
//compares the expression tree to another expression tree for equivalence.
//If the two trees are equivalent, then returns true. Otherwise, returns false
//Two trees are equivalent if
// the corresponding nodes are leaves with the same value
// they have the same operator and equivalent subtrees as operands
// they have the same commutable operator with equivalent, but commuted subtrees as operands
}
template<typename DataType>
ExprTree<DataType>::ExprTreeNode::ExprTreeNode(char elem, ExprTreeNode *leftPtr, ExprTreeNode *rightPtr)
{
dataItem = elem;
left=leftPtr;
right=rightPtr;
}
template<typename DataType>
bool ExprTree<DataType>::isEmpty()const
{
if (root == NULL)
{ return true; }
return false;
}
template<typename DataType>
void ExprTree<DataType>::evalHelper(ExprTreeNode* nodePtr) const
{
//Called with root
//pass node pointer
//evaluate helper left
//evaluate helper right
//check for digit or operator
//if digit, returns value
//change from char to int in this function
}
template<typename DataType>
void ExprTree<DataType>::expressionHelper()
{
} | true |
5c4e9d614669c56102cb7a89185301432cd190f1 | C++ | lijinpei/clang-json-gen | /RecordInfo.hpp | UTF-8 | 4,214 | 2.625 | 3 | [] | no_license | #pragma once
#include "Directive.hpp"
#include "clang/AST/DeclCXX.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
class FieldDecl;
class CXXRecordDecl;
class CXXBaseSpecifier;
} // namespace clang
// the information needed by codegen functions
struct CodegenContext {
std::string indent;
std::string self; // the source code used to access yourself
std::string start_state; // the source code for the start state
std::string expact_key_state; // the source code for the expect-key state
std::string prefix; // the prefix that should be append to your state's name
};
struct Field {
const clang::FieldDecl *field;
FieldDirective directive;
Field(const clang::FieldDecl *field, FieldDirective directive)
: field(field), directive(directive) {}
};
// this class doesn't record whether this is a virtual base
struct SubClass {
const clang::CXXBaseSpecifier *base;
bool omit : 1;
SubClass(const clang::CXXBaseSpecifier *base) : base(base) {}
};
class RecordInfo {
// bases means non virtual bases
std::vector<SubClass> bases;
// vbases means virtual bases
std::vector<SubClass> vbases;
std::vector<Field> fields;
RecordDirective record_directive;
clang::CXXRecordDecl *type;
struct VisitContext {
std::string state_name;
std::string self;
std::string parent;
};
// class CB {
// public:
// // handle the specified field, no matter it is a
// // base-field/vbase-field/field
// bool handleField(const VisitContext&, const Field&);
// };
template <bool VisitBase = true, bool VisitVBase = true,
bool VisitField = true, typename CB>
bool Visit(const CodegenContext &, CB &cb);
// codegen functions
// the following codegen functions only generate code for non-virtual bases
bool generateEnumBody(llvm::raw_ostream &, const CodegenContext &);
bool generateNullBody(llvm::raw_ostream &, const CodegenContext &);
bool generateBoolBody(llvm::raw_ostream &, const CodegenContext &);
bool generateIntBody(llvm::raw_ostream &, const CodegenContext &);
bool generateUintBody(llvm::raw_ostream &, const CodegenContext &);
bool generateInt64Body(llvm::raw_ostream &, const CodegenContext &);
bool generateUint64Body(llvm::raw_ostream &, const CodegenContext &);
bool generateDoubleBody(llvm::raw_ostream &, const CodegenContext &);
bool generateStringBody(llvm::raw_ostream &, const CodegenContext &);
bool generateKeyBody(llvm::raw_ostream &, const CodegenContext &);
bool generateStartArrayBody(llvm::raw_ostream &, const CodegenContext &);
bool generateEndArrayBody(llvm::raw_ostream &, const CodegenContext &);
bool generateRawNumberBody(llvm::raw_ostream &, const CodegenContext &);
void emitFieldCheck(llvm::raw_ostream &os, const CodegenContext &cc,
const VisitContext &vc, const Field &f) {
if (!f.directive.is_required) {
return;
}
std::string check_name = vc.state_name + "_check";
os << cc.indent << "if (" << check_name << ") {\n";
os << cc.indent << " return false\n";
os << cc.indent << "} else {\n";
os << cc.indent << " " << check_name << " = false;\n";
os << cc.indent << "}\n";
}
public:
void setDirective(RecordDirective rd) { record_directive = rd; }
bool addMember(const Field &f) {
fields.push_back(f);
return true;
}
bool addMember(Field &&f) {
fields.push_back(f);
return true;
}
bool emplaceMember(const clang::FieldDecl *field, FieldDirective fd) {
fields.emplace_back(field, fd);
return true;
}
bool addBase(const SubClass &b) {
bases.push_back(b);
return true;
}
bool addBase(SubClass &&b) {
bases.push_back(b);
return true;
}
bool emplaceBase(const clang::CXXBaseSpecifier *base) {
bases.emplace_back(base);
return true;
}
bool addVBase(const SubClass &b) {
vbases.push_back(b);
return true;
}
bool addVBase(SubClass &&b) {
vbases.push_back(b);
return true;
}
bool emplaceVBase(const clang::CXXBaseSpecifier *vbase) {
vbases.emplace_back(vbase);
return true;
}
void emitCode(llvm::raw_ostream &);
};
RecordInfo *getRecordInfoFromDecl(const clang::CXXRecordDecl *);
| true |
36de5b016135709b4a250be194f5f908dccd04fc | C++ | a1d4c7/Betriebssysteme | /src/thread/ActivityScheduler.cc | UTF-8 | 4,062 | 2.75 | 3 | [] | no_license | #include "thread/ActivityScheduler.h"
#include "thread/Activity.h"
#include "interrupts/IntLock.h"
#include "device/Clock.h"
#include "lib/Debugger.h"
/* Suspendieren des aktiven Prozesses
* Der korrekte Ausfuehrungszustand ist zu setzen
* und danach der naechste lauffaehige Prozess zu aktivieren.
*/
void ActivityScheduler::suspend()
{
IntLock lock;
Activity* running = (Activity*) active();
running->changeTo(Activity::BLOCKED);
scheduler.reschedule();
}
/* Explizites Terminieren des angegebenen Prozesses
* Der Prozesszustand ist korrekt zu setzen
* und der Prozess aus der Ready-Liste des Schedulers
* zu entfernen. Falls der aktive Prozess zerstoert wird,
* ist dem naechsten lauffaehigen Prozess die CPU
* zuzuteilen.
*/
void ActivityScheduler::kill(Activity* a)
{
IntLock lock;
a->changeTo(Activity::ZOMBIE);
Activity* running = (Activity*) active();
if (a == running)
{
scheduler.reschedule();
}
else
{
scheduler.remove(a);
}
}
/* Terminieren des aktiven Prozesses,
* und Wechsel zum naechsten lauffaehigen Prozess
*/
void ActivityScheduler::exit()
{
//IntLock lock; //keine Statusaenderung, keine gemeinsame Daten
Activity* running = (Activity*) active();
this->kill(running);
}
/* Der aktive Prozess ist, sofern er sich nicht im Zustand
* Blocked oder Zombie befindet, wieder auf die Ready-Liste
* zu setzen. Danach ist "to" mittels dispatch die Kontrolle
* zu �bergeben.
*/
void ActivityScheduler::activate(Schedulable* to)
{
//IntLock lock;
Activity* run = (Activity*) active();
if (!(run->isBlocked() || run->isZombie()))
{
if (run->isRunning()) run->changeTo(Activity::READY);
if (to == 0)
{
to = run;
}
else
{
scheduler.schedule(run);
}
}
//wenn to = 0 ist dann ist readyliste leer
//falls readyliste leer ist, auf naechste activity warten
if (to == 0)
{
isEmpty = true;
while (isEmpty)
{
{
IntLock lock;
CPU::enableInterrupts();
CPU::halt();
}
//interrupts wieder sperren da sie vorher ja aus waren durch reschedule
//und um dequeue zu schuetzen
to = (Schedulable*) readylist.dequeue();
if (to != 0)
{
isEmpty = false;
}
}
}
//falls activate durch checkslice -> reschedule aufgerufen dann doppelt zurueckgesetzt
//aber wichtig wenn geyielded wird
clock.resetTicks();
((Activity*) to)->changeTo(Activity::RUNNING);
dispatch((Activity*) to);
}
/* Ueberprueft ob die Zeitscheibe des aktuell laufenden
* Prozesses abgelaufen ist. Wenn ja, soll ein
* Rescheduling veranlast werden.
*/
void ActivityScheduler::checkSlice()
{
IntLock lock;
if (isEmpty) return;
Activity* running = (Activity*) active();
//running kann null sein da wir in activate den while loop interrupts zulassen
//dadurch kann checkslice auf einen null pointer aufgerufen werden
//sollte aber doch nicht der fall sein, da running nie auf einen null prozess gesetzt werden kann
//der alte prozess steht immer noch in running obwohl er ja garnicht mehr wirklich running ist
if (running != 0)
{
if (clock.ticks() >= running->quantum())
{
clock.resetTicks();
reschedule();
}
}
else
{
clock.resetTicks();
reschedule();
}
} | true |
c5fbc390451614936d958dd3fd4458fb5d5bd02a | C++ | 1InfinityDoesExist/Sigmoid | /Q5.cpp | UTF-8 | 1,749 | 3.6875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
Node(int val) : data(val), next(NULL){}
};
class Solution
{
private:
public:
Solution();
struct Node *mergeSortedLinkedsList(struct Node *head1, struct Node *head2);
};
Solution::Solution(){}
struct Node *Solution::mergeSortedLinkedsList(struct Node *head1, struct Node *head2)
{
if(head1 == NULL)
{
return head2;
}
if(head2 == NULL)
{
return head1;
}
if(head1->data < head2->data)
{
head1->next = mergeSortedLinkedsList(head1->next, head2);
return head1;
}
else
{
head2->next = mergeSortedLinkedsList(head1, head2->next);
return head2;
}
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
Solution sol;
struct Node *head1 = new Node(2);
head1->next = new Node(4);
head1->next->next = new Node(14);
head1->next->next->next = new Node(24);
head1->next->next->next->next = new Node(34);
head1->next->next->next->next->next = new Node(54);
head1->next->next->next->next->next->next = new Node(64);
head1->next->next->next->next->next->next->next = new Node(100);
struct Node *head2 = new Node(20);
head2->next = new Node(44);
head2->next->next = new Node(47);
head2->next->next->next = new Node(54);
head2->next->next->next->next = new Node(64);
head2->next->next->next->next->next = new Node(84);
struct Node *ptr = sol.mergeSortedLinkedsList(head1, head2);
while(ptr != NULL)
{
cout << ptr->data <<" ";
ptr = ptr->next;
}
cout << endl;
return 0;
}
| true |
994a33411550646b64d7652e3c1a650c8e7fe910 | C++ | NathanBhamra/IMAT2908 | /TeapotAD/TeapotAD/scenediffuse.cpp | UTF-8 | 4,951 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include "defines.h"
#include "scenediffuse.h"
#include <gtc/matrix_transform.hpp>
#include <gtx/transform2.hpp>
using std::cerr;
using std::endl;
using glm::vec3;
//This struct is setting the lighting intensity
struct S_Light
{
//Diffusion
vec3 Ld;
//Ambient
vec3 La;
//Specular
vec3 Ls;
} light_Bright;
namespace imat2908
{
//This is the contructor for the SceneDiffuse class
SceneDiffuse::SceneDiffuse()
{
}
//Intialising the scene
void SceneDiffuse::initScene(QuatCamera camera)
{
//Compile and link the shader
compileAndLinkShader();
gl::Enable(gl::DEPTH_TEST);
light_Bright.La.x = 8.0; // set light brightness to 8 on the x
light_Bright.La.y = 8.0; // set light brightness to 8 on the y
light_Bright.La.z = 8.0; // set light brightness to 8 on the z
//Set up the lighting
setLightParams(camera);
//Create the plane to represent the ground
plane = new VBOPlane(100.0,100.0,100,100);
//A matrix to move the teapot lid upwards
glm::mat4 lid = glm::mat4(1.0);
//lid *= glm::translate(vec3(0.0,1.0,0.0));
//Create the teapot with translated lid
teapot = new VBOTeapot(16,lid);
}
void SceneDiffuse::update( float t )
{
}
void SceneDiffuse::setLightParams(QuatCamera camera)
{
vec3 worldLight = vec3(10.0f,10.0f,10.0f);
//Diffuse
prog.setUniform("light.Ld", 0.9f, 0.9f, 0.9f);
//Specular
prog.setUniform("light.La", light_Bright.La.x, light_Bright.La.y, light_Bright.La.z);
//Ambient
prog.setUniform("light.Ls", 0.3f, 0.3f, 0.3f);
prog.setUniform("LightPosition", worldLight );
//Constant Parameter
prog.setUniform("light.atten_constant", 0.5f);
//Linear Parameter
prog.setUniform("light.atten_linear", 0.08f);
//Quadratic Parameter
prog.setUniform("light.atten_quad", 0.09f);
}
void SceneDiffuse::lightChange(float Incre) // light change by "incre" ammount
{
if (light_Bright.La.x <= 26.0 || light_Bright.La.x >= 0.0)
{
light_Bright.La = vec3(light_Bright.La.x + Incre, light_Bright.La.y + Incre, light_Bright.La.z + Incre); // Increase / decrease the the light by the incre at x,y and z
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Render the scene
/////////////////////////////////////////////////////////////////////////////////////////////
void SceneDiffuse::render(QuatCamera camera)
{
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
//First deal with the plane to represent the ground
//Initialise the model matrix for the plane
model = mat4(1.0f);
//Set the matrices for the plane although it is only the model matrix that changes so could be made more efficient
setMatrices(camera);
//Set the plane's material properties in the shader and render
prog.setUniform("matterial.Kd", 0.51f, 1.0f, 0.49f);
prog.setUniform("matterial.Ka", 0.51f, 1.0f, 0.49f);
prog.setUniform("matterial.Ks", 0.1f, 0.1f, 0.1f);
plane->render();
//Now set up the teapot
model = mat4(1.0f);
setMatrices(camera);
//Set the Teapot material properties in the shader and render
prog.setUniform("matterial.Kd", 0.46f, 0.29f, 0.0f);
prog.setUniform("matterial.Ka", 0.46f, 0.29f, 0.0f);
prog.setUniform("matterial.Ks", 0.29f, 0.29f, 0.29f);
teapot->render(); // render the teapot
}
/////////////////////////////////////////////////////////////////////////////////////////////
//Send the MVP matrices to the GPU
/////////////////////////////////////////////////////////////////////////////////////////////
void SceneDiffuse::setMatrices(QuatCamera camera)
{
mat4 mv = camera.view() * model;
prog.setUniform("ModelViewMatrix", mv);
prog.setUniform("NormalMatrix", mat3( vec3(mv[0]), vec3(mv[1]), vec3(mv[2]) ));
prog.setUniform("MVP", camera.projection() * mv);
mat3 normMat = glm::transpose(glm::inverse(mat3(model)));// What does this line do?
prog.setUniform("M", model);
prog.setUniform("V", camera.view() );
prog.setUniform("P", camera.projection() );
prog.setUniform("viewPos", camera.position());
}
/////////////////////////////////////////////////////////////////////////////////////////////
// resize the viewport
/////////////////////////////////////////////////////////////////////////////////////////////
void SceneDiffuse::resize(QuatCamera camera,int w, int h)
{
gl::Viewport(0,0,w,h);
width = w;
height = h;
camera.setAspectRatio((float)w/h);
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Compile and link the shader
/////////////////////////////////////////////////////////////////////////////////////////////
void SceneDiffuse::compileAndLinkShader()
{
try {
prog.compileShader("Shaders/phong.vert");
prog.compileShader("Shaders/phong.frag");
prog.link();
prog.validate();
prog.use();
} catch(GLSLProgramException & e) {
cerr << e.what() << endl;
exit( EXIT_FAILURE );
}
}
}
| true |
fd2c7ace4d438a7279f5fda9b39d0f43184c801f | C++ | BrandonColbert/Geon | /src/tilemap.cpp | UTF-8 | 2,155 | 3.109375 | 3 | [] | no_license | #include "generation/tilemap.h"
#include <cmath>
#include <iostream>
#include <sstream>
#include "actor.h"
#include "components/collider.h"
#include "components/rect.h"
#include "components/sprite.h"
#include "structures/texture.h"
#include "utils/format.h"
#include "console.h"
using namespace std;
using namespace Format;
using Tile = Tilemap::Tile;
Tilemap::Tilemap(Grid<Tile> tiles) : tiles(tiles) {}
Tilemap::Tilemap() {}
Vector2 Tilemap::tileToWorld(Point point) {
auto halfWidth = tiles.getWidth() / 2;
auto halfHeight = tiles.getHeight() / 2;
return {
(point.x - halfWidth) * tileSize,
(halfHeight - point.y) * tileSize
};
}
Point Tilemap::worldToTile(Vector2 position) {
auto halfWidth = tiles.getWidth() / 2;
auto halfHeight = tiles.getHeight() / 2;
return {
(int)round(position.x / tileSize + halfWidth),
(int)round(halfHeight - position.y / tileSize)
};
}
void Tilemap::actualize() {
tiles.forEach([&](int i, int j) {
if(tiles(i, j) == Tile::None)
return;
auto &tile = Actor::spawn(format("Tile(%, %)", i, j));
tile.add(new Rect(
tileToWorld(Point(i, j)),
{tileSize, tileSize}
));
switch(tiles(i, j)) {
case Tile::None:
tile.add(new Sprite(Texture("./resources/tiles/background.png")));
break;
case Tile::Floor:
tile.add(new Sprite(Texture("./resources/tiles/floor.png")));
break;
case Tile::Path:
tile.add(new Sprite(Texture("./resources/tiles/floor.png")));
tile.get<Sprite>().tint = Color(0.9, 0.9, 0.9);
break;
case Tile::Wall:
tile.add(new Sprite(Texture("./resources/tiles/wall.png")));
tile.add(new Collider({tileSize, tileSize}));
break;
case Tile::Plank:
tile.add(new Sprite(Texture("./resources/tiles/plank.png")));
tile.add(new Collider({tileSize, tileSize}));
break;
default:
break;
}
});
}
void Tilemap::visualize() {
cout << tiles.toString([](Tile v) {
switch(v) {
case Tile::None:
return ".";
case Tile::Floor:
return "o";
case Tile::Wall:
return "-";
case Tile::Path:
return "#";
default:
return "?";
}
});
}
Grid<Tile>& Tilemap::getTiles() {
return tiles;
} | true |
cdfa3be23a0c08c7272c43b55f75bcbcbbd3841a | C++ | DmitryKholodok/Osisp-2 | /Lab4/Lab4/ThreadPool.cpp | UTF-8 | 1,813 | 2.875 | 3 | [] | no_license | #include "stdafx.h"
#include "ThreadPool.h"
ThreadPool::ThreadPool(int threadCount)
{
InitializeCriticalSectionAndSpinCount(&threadPoolCritSection, 4000);
InitializeConditionVariable(&threadPoolCondVar);
this->threadCount = threadCount;
this->closed = false;
threads = new HANDLE[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = CreateThread(NULL, 0, threadProcessing, this, 0, NULL);
}
}
DWORD _stdcall ThreadPool::threadProcessing(LPVOID param)
{
ThreadPool* threadPool = (ThreadPool*)param;
while (true)
{
TaskStruct* taskStruct = threadPool->dequeueTask();
if (!taskStruct)
{
break;
}
else
{
taskStruct->func(taskStruct->param);
}
}
return 0;
}
void ThreadPool::enqueueTask(TaskStruct* taskStruct)
{
EnterCriticalSection(&threadPoolCritSection);
tasks.push(taskStruct);
WakeConditionVariable(&threadPoolCondVar);
LeaveCriticalSection(&threadPoolCritSection);
}
TaskStruct* ThreadPool::dequeueTask()
{
EnterCriticalSection(&threadPoolCritSection);
while (tasks.size() == 0 && !closed)
{
SleepConditionVariableCS(&threadPoolCondVar, &threadPoolCritSection, INFINITE);
}
TaskStruct* taskStruct = NULL;
if (tasks.size() != 0)
{
taskStruct = tasks.front();
tasks.pop();
}
LeaveCriticalSection(&threadPoolCritSection);
return taskStruct;
}
void ThreadPool::close()
{
if (!closed)
{
EnterCriticalSection(&threadPoolCritSection);
closed = true;
WakeAllConditionVariable(&threadPoolCondVar);
LeaveCriticalSection(&threadPoolCritSection);
}
for (int i = 0; i < threadCount; i++)
{
WaitForSingleObject(threads[i], INFINITE);
CloseHandle(threads[i]);
}
delete[] threads;
}
ThreadPool::~ThreadPool()
{
if (!closed)
{
close();
}
}
| true |
15710517caa4e4fe662caec2c7f0afa9bb865e6a | C++ | orihehe/BOJ | /Graph/17182번_우주 탐사선.cpp | UTF-8 | 918 | 2.609375 | 3 | [] | no_license | /*
BOJ 17182 - 우주 탐사선
https://www.acmicpc.net/problem/17182
플로이드로 i->j의 최단거리를 구해둔 뒤 완탐
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#define INF 987654321
using namespace std;
/* 🐣🐥 */
int arr[11][11];
int dp[11][1 << 10];
int n, k;
int dfs(int cur, int mm) {
if (mm == (1 << n) - 1)
return 0;
if (dp[cur][mm] != -1) return dp[cur][mm];
int ret = INF;
for (int i = 0; i < n; i++) {
if ((mm & (1 << i)) == 0)
ret = min(ret, dfs(i, mm + (1 << i)) + arr[cur][i]);
}
return dp[cur][mm] = ret;
}
int main() {
memset(dp, -1, sizeof(dp));
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
arr[i][j] = min(arr[i][j], arr[i][k] + arr[k][j]);
printf("%d", dfs(k, 1 << k));
return 0;
} | true |
13687fc8bb93a5dae5069ad92aa9c356106dcf45 | C++ | omwalhekar/arduino | /Binary/Binary.ino | UTF-8 | 1,109 | 2.75 | 3 | [] | no_license | int pin1 = 11;
int pin2 = 12;
int pin3 = 13;
int interval = 1000;
void setup() {
// put your setup code here, to run once:
pinMode(pin3,OUTPUT);
pinMode(pin2,OUTPUT);
pinMode(pin1,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
//0
digitalWrite(pin3,LOW);
digitalWrite(pin2,LOW);
digitalWrite(pin1,LOW);
delay(interval);
//1
digitalWrite(pin3,LOW);
digitalWrite(pin2,LOW);
digitalWrite(pin1,HIGH);
delay(interval);
//2
digitalWrite(pin3,LOW);
digitalWrite(pin2,HIGH);
digitalWrite(pin1,LOW);
delay(interval);
//3
digitalWrite(pin3,LOW);
digitalWrite(pin2,HIGH);
digitalWrite(pin1,HIGH);
delay(interval);
//4
digitalWrite(pin3,HIGH);
digitalWrite(pin2,LOW);
digitalWrite(pin1,LOW);
delay(interval);
//5
digitalWrite(pin3,HIGH);
digitalWrite(pin2,LOW);
digitalWrite(pin1,HIGH);
delay(interval);
//6
digitalWrite(pin3,HIGH);
digitalWrite(pin2,HIGH);
digitalWrite(pin1,LOW);
delay(interval);
//7
digitalWrite(pin3,HIGH);
digitalWrite(pin2,HIGH);
digitalWrite(pin1,HIGH);
delay(interval);
}
| true |
015007ccd467834b0bdb9656802181d625f66cac | C++ | CameronJMurphy/AI-Repo | /Dinosaur Sim/IdleDecision.cpp | UTF-8 | 367 | 2.671875 | 3 | [] | no_license | #include "IdleDecision.h"
void IdleDecision::makeDecision(Agent* agent, float deltaTime)
{
vector2 agentSpeed = agent->GetVelocity(); //get speed
//start to slow the agent down
float slowAmount = 1.001f;
if (agentSpeed.x != 0)
{
agentSpeed.x /= slowAmount;
}
if (agentSpeed.y != 0)
{
agentSpeed.y /= slowAmount;
}
agent->SetVelocity(agentSpeed);
};
| true |
9a1d027c2a859a96126ec24c7e4308f30cabf4cf | C++ | Aditya-013/Hackerrank-Stuff | /Trials/Longest Common Substring/Print_shortest_common_SuperSequence.cpp | UTF-8 | 1,890 | 2.921875 | 3 | [] | no_license | #include <bits/stdc++.h>
int main(){
char w[] = "acbcf";
char q[] = "abcdaf";
std::string temp;
int n = sizeof(w);
int m = sizeof(q);
int t[n][m];
memset(t, 0, sizeof(t));
for(int i=1; i<n; i++){
for(int j=1; j<m; j++){
if(w[i-1] == q[j-1]){
t[i][j] = t[i-1][j-1] + 1;
}
else{
t[i][j] = std::max(t[i-1][j], t[i][j-1]);
}
}
}
std::cout<<"String 1::"<<w<<"\n";
std::cout<<"String 2::"<<q<<"\n";
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
std::cout<<t[i][j]<<"\t";
}
std::cout<<"\n";
}
int i = n-1;
int j = m-1;
std::string temp2;
while(i > 0 && j>0){
if(w[i-1] == q[j-1]){
temp.push_back(w[i-1]);
temp2.push_back(w[i-1]);
i--;
j--;
}
else if(t[i-1][j] > t[i][j-1]){
temp2.push_back(w[i-1]);
i--;
}
else{
temp2.push_back(q[j-1]);
j--;
}
}
reverse(temp2.begin(), temp2.end());
std::cout<<"\n"<<temp2;
std::cout<<std::endl;
reverse(temp.begin(), temp.end());
i=0;
j=0;
int k=0;
while(i<n-1 || j<m-1){
if(temp[k]==w[i] && temp[k]==q[j]){
std::cout<<temp[k];
k++;
i++;
j++;
}
else if(temp[k]!=w[i] && temp[k]!=q[j]){
std::cout<<w[i];
std::cout<<q[j];
i++;
j++;
}
else if(temp[k]!=w[i] && temp[k]==q[j]){
std::cout<<w[i];
i++;
}
else if(temp[k]==w[i] && temp[k]!=q[j]){
std::cout<<q[j];
j++;
}
}
std::cout<<"\nLength of the LCS ::"<<t[n-1][m-1]<<"\n";
return 0;
} | true |
3df36c363a283e3a63c59807f2a4562db1facad2 | C++ | destmaxi/ibrdtn | /ibrdtn/daemon/src/core/EventDispatcher.h | UTF-8 | 2,956 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | /*
* EventDispatcher.h
*
* Created on: 06.12.2012
* Author: morgenro
*/
#ifndef EVENTDISPATCHER_H_
#define EVENTDISPATCHER_H_
#include "core/Event.h"
#include "core/EventSwitch.h"
#include "core/EventReceiver.h"
#include <ibrcommon/thread/RWMutex.h>
#include <ibrcommon/thread/RWLock.h>
#include <ibrcommon/thread/MutexLock.h>
#include <list>
namespace dtn
{
namespace core
{
template<class E>
class EventDispatcher {
private:
/**
* never create a dispatcher
*/
EventDispatcher() : _processor(*this), _stat_count(0)
{ };
class EventProcessorImpl : public EventProcessor {
public:
EventProcessorImpl(EventDispatcher<E> &dispatcher)
: _dispatcher(dispatcher) { };
virtual ~EventProcessorImpl() { };
void process(const Event *evt)
{
ibrcommon::MutexLock l(_dispatcher._dispatch_lock);
for (typename std::list<EventReceiver<E>*>::iterator iter = _dispatcher._receivers.begin();
iter != _dispatcher._receivers.end(); ++iter)
{
EventReceiver<E> &receiver = (**iter);
receiver.raiseEvent(static_cast<const E&>(*evt));
}
_dispatcher._stat_count++;
}
EventDispatcher<E> &_dispatcher;
};
void _reset() {
ibrcommon::RWLock l(_dispatch_lock);
_stat_count = 0;
}
/**
* Directly deliver this event to all subscribers
*/
void _raise(E *evt)
{
_processor.process(evt);
delete evt;
}
/**
* Queue the event for later delivery
*/
void _queue(E *evt)
{
// raise the new event
dtn::core::EventSwitch::queue( _processor, evt );
}
void _add(EventReceiver<E> *receiver) {
ibrcommon::RWLock l(_dispatch_lock);
_receivers.push_back(receiver);
}
void _remove(const EventReceiver<E> *receiver) {
ibrcommon::RWLock l(_dispatch_lock);
for (typename std::list<EventReceiver<E>*>::iterator iter = _receivers.begin(); iter != _receivers.end(); ++iter)
{
if ((*iter) == receiver)
{
_receivers.erase(iter);
break;
}
}
}
static EventDispatcher<E>& instance() {
static EventDispatcher<E> i;
return i;
}
public:
virtual ~EventDispatcher() { };
/**
* Directly deliver this event to all subscribers
*/
static void raise(E *evt) {
instance()._raise(evt);
}
/**
* Queue the event for later delivery
*/
static void queue(E *evt) {
instance()._queue(evt);
}
static void add(EventReceiver<E> *receiver) {
instance()._add(receiver);
}
static void remove(const EventReceiver<E> *receiver) {
instance()._remove(receiver);
}
static void resetCounter() {
instance()._reset();
}
static size_t getCounter() {
return instance()._stat_count;
}
private:
ibrcommon::RWMutex _dispatch_lock;
std::list<EventReceiver<E>*> _receivers;
EventProcessorImpl _processor;
size_t _stat_count;
};
}
}
#endif /* EVENTDISPATCHER_H_ */
| true |
35d5733cf3f29e85c32b72f7a5f57e9e7bbb3cf7 | C++ | Annerley/Images | /PNGImage.h | WINDOWS-1251 | 360 | 2.5625 | 3 | [] | no_license | #pragma once
#include <string>
#include"AbstractImage.h"
class PNGImage final : public AbstractImage // final ,
{
public:
PNGImage(const std::string& fileName);
void save(const std::string& outputName) override;
std::string stringType() const override;
};
| true |
7c87697a7b342eda9d8df5ce7ddb0c50d68aae4f | C++ | causelovem/2-course | /c++/2_matrix_calculator/main.cpp | UTF-8 | 2,072 | 2.78125 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <climits>
#include "class_Exception.hpp"
#include "class_Big_int.hpp"
#include "class_Rational_number.hpp"
#include "class_Vector.hpp"
#include "class_Matrix.hpp"
#include "generator.hpp"
using namespace std;
int main ()
{
try
{
srand((unsigned int)time(0));
double x,y;
x=(float)clock();
Matrix mat1("mat_file1"), mat2("mat_file2"), mat3("mat_file3"), mat4;
Big_int num1("1314"), num2("5612");
Rational_number rat1("1"), rat2, rat3(num1);
long int sum = 0;
Row_position rp1(1), rp2(2), rp3(3);
Col_position cp1(1), cp2(2), cp3(3);
mat4 = mat2[cp2] * mat3[rp2];
mat4.show(stdout);
y=(float)clock();
x=(float)(y-x)/CLOCKS_PER_SEC;
cout << x << endl;
}
catch(Exception &err)
{
err.show(stdout);
return -1;
}
catch(Exception_vector_border &err)
{
err.show(stdout);
return -1;
}
catch(Exception_bigtoshort &err)
{
err.show(stdout);
return -1;
}
catch(Exception_bigtoint &err)
{
err.show(stdout);
return -1;
}
catch(Exception_bigtolong &err)
{
err.show(stdout);
return -1;
}
catch(Exception_rattoshort &err)
{
err.show(stdout);
return -1;
}
catch(Exception_rattoint &err)
{
err.show(stdout);
return -1;
}
catch(Exception_rattolong &err)
{
err.show(stdout);
return -1;
}
catch(Exception_file_name &err)
{
err.show(stdout);
return -1;
}
catch(Exception_matrix_border &err)
{
err.show(stdout);
return -1;
}
catch(Exception_matrix_sizes &err)
{
err.show(stdout);
return -1;
}
catch(...)
{
fprintf(stdout, ">Something unknown catched...\n");
return -1;
}
return 0;
} | true |
06d242ffa010498560e861c4186305213e8d5643 | C++ | the-paulus/old-skool-code | /C++/ch11ptest2.cpp | UTF-8 | 912 | 2.90625 | 3 | [] | no_license | #include<iostream.h>
#include<fstream.h>
#include<string.h>
ofstream OUTFILE;
ifstream INFILE;
char StudentName[25], ch;
int main()
{
OUTFILE.open("OUT.DAT",ios::out);
do
{
cout << "\nEnter student's name and hit 'END' when finished: ";
cin.get(StudentName,25);
cin.ignore(80,'\n');
OUTFILE << StudentName << '\n';
}while(strcmp(StudentName,"END")==true);
OUTFILE.close();
INFILE.open("OUT.DAT",ios::in);
INFILE.unsetf(ios::skipws);
while(!INFILE.eof())
{
INFILE >> StudentName;
if(!INFILE.eof())
{
cout << StudentName << endl;
}
}
INFILE.close();
OUTFILE.open("OUT.DAT",ios::app);
cout << "\nEnter one more student: ";
cin.get(StudentName,25);
cin.ignore(80,'\n');
OUTFILE << StudentName << '\n';
OUTFILE.close();
INFILE.open("OUT.DAT",ios::in);
while(!INFILE.eof())
{
INFILE >> StudentName;
cout << StudentName << '\n';
}
INFILE.close();
return 0;
} | true |
b1881186545b29ed7ebaa560238e643598781e12 | C++ | cavallo5/cpp_scripts | /src/Lettura e stampa matrice.cpp | UTF-8 | 626 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
const int maxrango=10;
typedef int matrice[maxrango][maxrango];
matrice a;
int n;
cout<<"Inserire la dimensione della matrice"<<endl;
cin>>n;
for (int i=0;i<n;i++)
for (int j=0; j<n;j++)
{
cout<<"Inserire il valore "<<i<<","<<j<<": ";
cin>>a[i][j];
}
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout.width(4);
cout<<a[i][j];
}
cout<<endl;
}
system("PAUSE");
return 0;
}
| true |
6da6e9e79e7a6b1aac59595b67c5e5d034f4b3d3 | C++ | kizato1018/computer-programming | /NTNU/NM/matrix.cpp | UTF-8 | 8,790 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include "matrix.h"
using namespace std;
// class Matrix {
// public:
// Matrix() : row_(0), col_(0), v_(nullptr) {};
// Matrix(int, int);
// Matrix(const Matrix&);
// // Matrix(int r, int c, vector<vector<double> > val) : row_(r), col_(c), v(val) {};
// Matrix& operator=(const Matrix&);
// Matrix operator+(const Matrix&) const;
// Matrix operator*(const Matrix&) const;
// Matrix operator*(int) const;
// Matrix operator-(const Matrix&) const;
// const double* operator[] (int i) const { return v_[i]; }
// double* operator[] (int i) { return const_cast<double*> (static_cast<const Matrix &>(*this)[i]); }
// bool operator==(const Matrix&) const;
// bool operator!=(const Matrix& M) const {return !(*this==M);}
// int Row() const {return row_;}
// int Col() const {return col_;}
// Matrix& Append(const Matrix&);
// Matrix Subtract(int);
// void Input();
// void Show();
// private:
// int row_;
// int col_;
// double **v_;
// };
Matrix::Matrix(int r, int c) : row_(r), col_(c) {
v_ = new double*[row_];
for(int i = 0; i < row_; ++i) {
v_[i] = new double[col_];
for(int j = 0; j < col_; ++j) {
v_[i][j] = 0;
}
}
}
Matrix::Matrix(const Matrix& M) : row_(M.row_), col_(M.col_) {
v_ = new double*[row_];
for(int i = 0; i < row_; ++i) {
v_[i] = new double[col_];
for(int j = 0; j < col_; ++j)
v_[i][j] = M[i][j];
}
}
Matrix& Matrix::operator=(const Matrix& M) {
for(int i = 0; i < row_; ++i) {
delete [] v_[i];
}
delete [] v_;
row_ = M.row_;
col_ = M.col_;
v_ = new double*[row_];
for(int i = 0; i < row_; ++i) {
v_[i] = new double[col_];
for(int j = 0; j < col_; ++j)
v_[i][j] = M[i][j];
}
return *this;
}
Matrix Matrix::operator+(const Matrix& M) const {
Matrix tmp(*this);
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < col_; ++j) {
tmp[i][j] += M[i][j];
}
}
return tmp;
}
Matrix Matrix::operator*(const Matrix& M) const {
Matrix tmp(row_, M.col_);
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < M.col_; ++j) {
tmp[i][j] = 0;
for(int k = 0; k < col_; ++k) {
tmp[i][j] += (*this)[i][k] * M[k][j];
}
// printf("[%d][%d]=%lf\n", i, j, sum);
}
}
return tmp;
}
Matrix Matrix::operator*(int c) const {
Matrix tmp(*this);
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < col_; ++j) {
tmp[i][j] *= c;
}
}
return tmp;
}
Matrix Matrix::operator-(const Matrix& M) const{
Matrix tmp(*this), M1(M);
// tmp = tmp + M1;
tmp = tmp + (M * -1);
return tmp;
}
bool Matrix::operator==(const Matrix& M) const {
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < col_; ++j) {
if(abs((*this)[i][j] - M[i][j]) >= 0.00001)
return false;
}
}
return true;
}
Matrix& Matrix::Append(const Matrix& M) {
int offset = col_;
col_ += M.col_;
for(int i = 0; i < row_; ++i) {
double *tmp = new double[col_];
for(int j = 0; j < offset; ++j)
tmp[j] = (*this)[i][j];
for(int j = 0; j < M.Col(); ++j)
tmp[j+offset] = M[i][j];
delete [] v_[i];
v_[i] = tmp;
}
return *this;
}
Matrix Matrix::Subtract(int c) {
if(c < 0) c = col_ + c;
int row = row_, col = col_ - c;
Matrix tmp(row, col);
for(int i = 0; i < row; ++i) {
for(int j = 0; j < col; ++j) {
tmp[i][j] = (*this)[i][j+c];
}
v_[i] = (double*)realloc(v_[i], c * sizeof(double*));
}
return tmp;
}
Matrix Matrix::Inverse() const {
Matrix tmp(*this);
tmp.Append(In(row_));
return tmp;
}
Matrix Matrix::Transpose() const {
Matrix tmp(col_, row_);
for(int i = 0; i < tmp.Row(); ++i) {
for(int j = 0; j < tmp.Col(); ++j) {
tmp[i][j] = (*this)[j][i];
}
}
return tmp;
}
Matrix& Matrix::Input() {
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < col_; ++j) {
cin >> (*this)[i][j];
}
}
return *this;
}
void Matrix::Show() const {
for(int i = 0; i < row_; ++i) {
for(int j = 0; j < col_; ++j) {
printf("%.4lf ", (*this)[i][j]);
}
puts("");
}
}
Matrix Matrix::Vector(int col) const {
Matrix tmp(row_, 1);
for(int i = 0; i < row_; ++i) {
tmp[i][0] = (*this)[i][col];
}
return tmp;
}
double Matrix::length(int col) const {
double l = 0;
for(int i = 0; i < row_; ++i) {
l += pow((*this)[i][col],2);
}
l = sqrt(l);
return l;
}
Matrix In(int n) {
Matrix In(n, n);
for(int i = 0; i < n; ++i)
In[i][i] = 1;
return In;
}
Matrix D_Inv(Matrix& D) {
Matrix D_inv(D);
for(int i = 0; i < D.Row(); ++i) {
D_inv[i][i] = 1 / D[i][i];
}
return D_inv;
}
Matrix Jacobi(Matrix A, Matrix b) {
int r = A.Row(), c = A.Col();
Matrix D(r, c), L(r, c), U(r, c), D_inv(r, c), pre_x(r, 1), x(r, 1);
pre_x = x;
for(int i = 0; i < r; ++i) {
D[i][i] = A[i][i];
for(int j = 0; j < i; ++j) {
L[i][j] = A[i][j];
U[j][i] = A[j][i];
}
}
D_inv = D_Inv(D);
cout << "D_inv:" << endl;
D_inv.Show();
cout << "L:" << endl;
L.Show();
cout << "U:" << endl;
U.Show();
cout << endl;
int cnt = 0;
do{
printf("cnt=%d\n", ++cnt);
cout << "prex: " << endl;
pre_x.Show();
pre_x = x;
x = D_inv * (b - (L + U) * pre_x);
cout << "x: " << endl;
x.Show();
if(cnt == 5) break;
}while(x != pre_x);
return x;
}
Matrix NewMatrix () {
int r, c;
printf("enter (row col): ");
cin >> r >> c;
Matrix tmp(r, c);
printf("enter matrix:\n");
tmp.Input();
return tmp;
}
Matrix Elimination(Matrix M, Matrix& L, Matrix& U, Matrix& P, Matrix& c) {
int N = M.Row();
P = In(N);
L = In(N);
for(int i = 0; i < N; ++i) {
int max = i;
for(int j = i+1; j < N; ++j) {
if(abs(M[max][i]) < abs(M[j][i]))
max = j;
}
// Show(M);
if(max != i) {
for(int j = 0; j < N; ++j) {
swap(P[max][j], P[i][j]);
swap(M[max][j], M[i][j]);
}
swap(c[max][0], c[i][0]);
// cout << "i: " << i << endl;
// cout << "max: " << max << endl;
// Show(M);
// Show(P);
}
for(int j = i+1; j < N; ++j) {
double d = M[j][i] / M[i][i];
L[j][i] = d;
for(int k = i; k < N; ++k) {
M[j][k] -= M[i][k]*d;
}
c[j][0] -= c[i][0]*d;
// cout << "El:" << endl;
// Matrix tmp(M);
// tmp.Append(c).Show();
// cout << endl;
}
if(max != i) {
for(int j = 0; j < max && j < i; ++j) {
swap(L[max][j], L[i][j]);
}
}
}
U = M;
return M;
}
Matrix Elimination(Matrix M, Matrix& L, Matrix& U, Matrix& c) {
Matrix P;
return Elimination(M, L, U, P, c);
}
Matrix Elimination(Matrix M) {
Matrix L, U, P, c;
return Elimination(M, L, U, P, c);
}
Matrix Gaussian(Matrix M, Matrix c) {
int N = M.Row();
Matrix L, U, ans(N, 1);
M = Elimination(M, L, U, c);
M.Append(c);
// Show(M);
for(int i = N-1; i >= 0; --i) {
for(int j = i; j < N; ++j) {
M[i][N] -= (M[i][j] * ans[j][0]);
}
ans[i][0] = M[i][N] / M[i][i];
}
return ans;
}
bool equal(Matrix a, Matrix b) {
for(int i = 0; i < a.Row(); ++i) {
for(int j = 0; j < a.Col(); ++j) {
if(abs(a[i][j]-b[i][j]) > 0.0001) return false;
}
}
return true;
}
// int main() {
// Matrix A, b, x;
// A = NewMatrix();
// b = NewMatrix();
// cout << "A:" << endl;
// A.Show();
// cout << "b:" << endl;
// b.Show();
// // x = Jacobi(A, b);
// cout << "A append B:" << endl;
// A.Append(b);
// A.Show();
// x = A.Subtract(-1);
// cout << "x:" << endl;
// x.Show();
// }
/*
10 10
3 -1 0 0 0 0 0 0 0 0
-1 3 -1 0 0 0 0 0 0 0
0 -1 3 -1 0 0 0 0 0 0
0 0 -1 3 -1 0 0 0 0 0
0 0 0 -1 3 -1 0 0 0 0
0 0 0 0 -1 3 -1 0 0 0
0 0 0 0 0 -1 3 -1 0 0
0 0 0 0 0 0 -1 3 -1 0
0 0 0 0 0 0 0 -1 3 -1
0 0 0 0 0 0 0 0 -1 3
10 1
2 1 1 1 1 1 1 1 1 2
2 2
3 1
1 2
2 1
5 5
*/ | true |
e696ccf4c42fa33018ba16860041cb5813cc453a | C++ | scorpio-su/zerojudge | /c++/d559.cpp | UTF-8 | 264 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
while (cin >> n){
cout <<"\'C\' can use printf(\"%d\",n); to show integer like "<<n << endl;
}
return 0;
}
| true |
9309719e5b0fd3026d1002f373dcd5b3deeff48e | C++ | mtiganik/Arduino-projects | /Exercise08.2 - OOP_version/JoystickController.cpp | UTF-8 | 5,206 | 2.78125 | 3 | [] | no_license | /// FILE NAME: JoystickController.cpp
/// AUTHOR: Mihkel Tiganik
/// CREATED: 02.08.2018
/// MODIFIED: 03.08.2018
#include "JoystickController.h"
JoystickController::JoystickController(Joystick* joystick,
ConfigController* configController,
MainDisplayController* mainDisplayController,
RecorderController* recorderController )
{
this -> _joystick = joystick;
this -> _configController = configController;
this -> _mainDisplayController = mainDisplayController;
this -> _recorderController = recorderController;
}
void JoystickController::updateMenu(){
if(_joystick -> getUpReleased()){
switch(_currentState){
case (States::config):
_configController->onUpButtonPress();
break;
case (States::mainDisplay):
_mainDisplayController->onUpButtonPress();
break;
default:
Serial.println("Currenstate enum working");
break;
}
}
if(_joystick -> getDownReleased()){
switch(_currentState)
{
case (States::config):
_configController->onDownButtonPress();
break;
case (States::mainDisplay):
_mainDisplayController->onDownButtonPress();
break;
default:
Serial.println("default");
break;
}
}
}
void JoystickController::getNewActionMethod()
{
if(_joystick -> getLeftReleased()){
switch(_currentState){
case (States::config):
this->_currentState = _configController -> onLeftButtonPress();
break;
case (States::mainDisplay):
this->_currentState = _mainDisplayController -> onLeftButtonPress();
break;
default:
Serial.println("Currenstate enum working");
break;
}
}
if(_joystick -> getRightReleased()){
switch(_currentState)
{
case (States::config):
this->_currentState = _configController -> onRightButtonPress();
break;
case (States::mainDisplay):
this->_currentState = _mainDisplayController -> onRightButtonPress();
break;
default:
Serial.println("default");
break;
}
}
}
void JoystickController::updateNewActionMethod()
{
switch(_currentState){
case(States::config):
_configController -> ConfigIndex();
break;
case(States::mainDisplay):
_mainDisplayController -> MainIndex();
break;
case(States::newGraph):
_recorderController -> InitializeRecorder();
_recorderController -> getNewGraphData();
default:
break;
}
}
void JoystickController::setCurrentState(States state){
this -> _currentState = state;
}
States JoystickController::getCurrentState(){
return _currentState;
}
void JoystickController::setPins(uint8_t xPin, uint8_t yPin, uint8_t swPin)
{
this -> _xPin = xPin;
this -> _yPin = yPin;
this -> _swPin = swPin;
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);
}
bool JoystickController::hasUpDownButtonReleased()
{
if( _joystick->getUpReleased() || _joystick->getDownReleased() )
{
return true;
}
else
{
return false;
}
}
bool JoystickController::hasLeftRightButtonReleased()
{
if( _joystick->getLeftReleased() || _joystick->getRightReleased() )
{
return true;
}
else
{
return false;
}
}
void JoystickController::checkSwitches()
{
static byte previousstate[NUMBUTTONS];
static byte currentstate[NUMBUTTONS];
static long lastTime;
if (millis() < lastTime)
{
lastTime = millis(); // initialize lastTime
}
if ((lastTime + DEBOUNCE_TIME) > millis())
{
return; // not enought time has passed for debouncing
}
delay(10);
// we waited DEBOUNCE_TIME, lets reset timer
lastTime = millis();
currentstate[LEFT] = analogRead(_xPin) < 100 ? 0 : 1;
currentstate[UP] = analogRead(_yPin) < 100 ? 0 : 1;
currentstate[RIGHT] = analogRead(_xPin) > 800 ? 0 : 1;
currentstate[DOWN] = analogRead(_yPin) > 800 ? 0 : 1;
currentstate[PUSH] = digitalRead(_swPin);
for (int index = 0; index < NUMBUTTONS; index++)
{
justreleased[index] = 0;
if (currentstate[index] == previousstate[index])
{
if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))
{
// just released
justreleased[index] = 1;
}
pressed[index] = !currentstate[index]; // remember, digital HIGH means NOT pressed
}
previousstate[index] = currentstate[index]; // keep a running tally of the buttons
}
// parse values to model
_joystick -> setLeftReleased(justreleased[LEFT]);
_joystick -> setUpReleased(justreleased[UP]);
_joystick -> setRightReleased(justreleased[RIGHT]);
_joystick -> setDownReleased(justreleased[DOWN]);
_joystick -> setPushButtonReleased(justreleased[PUSH]);
} | true |
f1c3768c12b0d043f2e1e9a4f1ece11156232109 | C++ | xiami2019/LeetCode | /剑指Offer/60.扑克牌中的顺子.cpp | UTF-8 | 1,152 | 3.03125 | 3 | [] | no_license | class Solution {
public:
bool isStraight(vector<int>& nums) {
sort(nums.begin(), nums.end());
int Zeros = 0;
int index = 0;
while (nums[index] == 0) {
Zeros++;
index++;
}
if (Zeros == 4) return true;
int sequence = nums[index++];
while (index < 5) {
if (nums[index] == nums[index - 1]) return false;
sequence++;
if (nums[index] != sequence) {
if (Zeros > 0) {
Zeros--;
}
else {
return false;
}
}
else {
index++;
}
}
return true;
}
};
// 解法2
class Solution {
public:
bool isStraight(vector<int>& nums) {
unordered_set<int> seen;
int maxNum = 0, minNum = 14;
for (int i : nums) {
if (i == 0) continue;
maxNum = max(maxNum, i);
minNum = min(minNum, i);
if (seen.count(i)) return false;
seen.insert(i);
}
return maxNum - minNum < 5;
}
}; | true |
258a1a5b2954fc4ffa507ae0e873132cd7e0f957 | C++ | fedee96/Practico-2 | /TP2/TP2/Operaciones_matematicas.h | UTF-8 | 378 | 2.75 | 3 | [] | no_license | #pragma once
class Operaciones_matematicas
{
public:
Operaciones_matematicas();
~Operaciones_matematicas();
#define CUADR(a) (a*a)
float cuadrado(float a);
#define SUM(a,b) (a+b)
float sum(float a, float b);
double aCirc(double r);
double PI = (3,14159);
#define CIRC(r) (2*PI*r)
#define MAX(a, b) ((a)>(b)?(a):(b))
float max(float a, float b);
};
| true |
1ec1453507b83c88ad0936351b2d18053144fb0d | C++ | ouxu/CppRecord | /OJ/1193.cpp | UTF-8 | 179 | 2.5625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
const double pi=3.1415927;
double r,v;
while (cin>>r)
{
v=4*pi*r*r*r/3;
printf("%.3lf\n",v);
}
return 0;
}
| true |
336172ee1512ceb5e3d72946f6fc93187ef8525c | C++ | tiennm99/CTDL-GT | /Lab4.cpp | UTF-8 | 7,774 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Node {
int data;
Node *next;
Node()
{
this->data = 0;
this->next = nullptr;
}
Node(int data)
{
this->data = data;
this->next = nullptr;
}
Node(int data, Node *next)
{
this->data = data;
this->next = next;
}
~Node() {}
};
enum ErrorCode {
SUCCESS,
FAIL,
OVERFLOW,
UNDERFLOW
};
class Stack
{
private:
Node *sTop;
int sCount;
public:
Stack()
{
this->sTop = nullptr;
this->sCount = 0;
}
~Stack()
{
if (!this->isEmpty())
this->clear();
}
ErrorCode create();
ErrorCode push(int data);
ErrorCode pop();
ErrorCode top(int &data);
bool isEmpty();
bool isFull();
ErrorCode clear();
int size();
};
ErrorCode Stack::create()
{
if (!this->isEmpty())
return this->clear();
return SUCCESS;
}
ErrorCode Stack::push(int data)
{
if (this->isFull())
return OVERFLOW;
Node *temp = new Node(data, this->sTop);
this->sTop = temp;
temp = nullptr;
this->sCount++;
return SUCCESS;
}
ErrorCode Stack::pop()
{
if (this->isEmpty())
return UNDERFLOW;
Node *temp = this->sTop;
this->sTop = this->sTop->next;
delete temp;
temp = nullptr;
this->sCount--;
return SUCCESS;
}
ErrorCode Stack::top(int &data)
{
if (this->isEmpty()) {
data = 0;
return FAIL;
}
data = this->sTop->data;
return SUCCESS;
}
bool Stack::isEmpty()
{
return (this->sCount == 0);
}
bool Stack::isFull()
{
Node *temp = new Node;
if (temp != nullptr) {
delete temp;
temp = nullptr;
return false;
}
return true;
}
ErrorCode Stack::clear()
{
while (!this->isEmpty()) {
this->pop();
}
return SUCCESS;
}
int Stack::size()
{
return this->sCount;
}
class Queue
{
private:
Node *qFront;
Node *qRear;
int qCount;
public:
Queue()
{
this->qFront = nullptr;
this->qRear = nullptr;
this->qCount = 0;
}
~Queue()
{
if (!this->isEmpty())
this->clear();
}
ErrorCode create();
ErrorCode enqueue(int data);
ErrorCode dequeue();
ErrorCode queueFront(int &data);
ErrorCode queueRear(int &data);
bool isFull();
bool isEmpty();
ErrorCode clear();
int size();
};
ErrorCode Queue::create()
{
if (!this->isEmpty())
return this->clear();
return SUCCESS;
}
ErrorCode Queue::enqueue(int data)
{
if (this->isFull())
return OVERFLOW;
Node *temp = new Node(data, this->qRear);
qRear = temp;
temp = nullptr;
if (this->isEmpty()) {
qFront = qRear;
}
this->qCount++;
return SUCCESS;
}
ErrorCode Queue::dequeue()
{
if (this->isEmpty())
return UNDERFLOW;
Node *temp = nullptr;
if (this->qCount == 1) {
this->qRear = nullptr;
} else {
temp = this->qRear;
while (temp->next != this->qFront)
temp = temp->next;
}
delete this->qFront;
this->qFront = temp;
this->qCount--;
return SUCCESS;
}
ErrorCode Queue::queueFront(int &data)
{
if (this->isEmpty()) {
data = 0;
return FAIL;
}
data = this->qFront->data;
return SUCCESS;
}
ErrorCode Queue::queueRear(int &data)
{
if (this->isEmpty()) {
data = 0;
return FAIL;
}
data = this->qRear->data;
return SUCCESS;
}
bool Queue::isEmpty()
{
return (this->qCount == 0);
}
bool Queue::isFull()
{
Node *temp = new Node;
if (temp != nullptr) {
delete temp;
temp = nullptr;
return false;
}
return true;
}
ErrorCode Queue::clear()
{
while (!this->isEmpty())
this->dequeue();
return SUCCESS;
}
int Queue::size()
{
return this->qCount;
}
void stackToQueue(Stack &s, Queue &q)
{
q.create();
while (!s.isEmpty()) {
int data;
s.top(data);
q.enqueue(data);
s.pop();
}
}
void queueToStack(Queue &q, Stack &s)
{
s.create();
Queue qTemp;
Stack sTemp;
while (!q.isEmpty()) {
int data;
q.queueFront(data);
sTemp.push(data);
qTemp.enqueue(data);
q.dequeue();
}
while (!qTemp.isEmpty()) {
int data;
qTemp.queueFront(data);
q.enqueue(data);
qTemp.dequeue();
}
while (!sTemp.isEmpty()) {
int data;
sTemp.top(data);
s.push(data);
sTemp.pop();
}
}
void printStack(Stack &s) //print Stack from top to base
{
Stack sTemp;
while (!s.isEmpty()) {
int data;
s.top(data);
cout << data << " ";
sTemp.push(data);
s.pop();
}
while (!sTemp.isEmpty()) {
int data;
sTemp.top(data);
s.push(data);
sTemp.pop();
}
cout << endl;
}
void printQueue(Queue &q) //print Queue from front to rear
{
Stack sTemp;
Queue qTemp;
while (!q.isEmpty()) {
int data;
q.queueFront(data);
cout << data << " ";
sTemp.push(data);
qTemp.enqueue(data);
q.dequeue();
}
while (!qTemp.isEmpty()) {
int data;
qTemp.queueFront(data);
q.enqueue(data);
qTemp.dequeue();
}
cout << endl;
}
int main()
{
string errorCodeString[] = {
"SUCCESS",
"FAIL",
"OVERFLOW",
"UNDERFLOW"
};
string output;
ErrorCode errorCode;
int data;
cout << "Init Stack:" << endl;
Stack s;
Queue q;
Stack sTemp;
Queue qTemp;
for (int i = 0; i < 10; ++i) {
s.push(i);
printStack(s);
}
cout << "Size of Stack: " << s.size() << endl;
output = s.isFull() ? "YES" : "NO";
cout << "Is Stack full?: " << output << endl;
cout << "Clear and print Stack:" << endl;
s.clear();
printStack(s);
output = s.isEmpty() ? "YES" : "NO";
cout << "Is Stask empty?: " << output << endl;
errorCode = s.pop();
cout << "ErrorCode when pop Stack again: "
<< errorCodeString[errorCode] << endl;
errorCode = s.top(data);
cout << "ErrorCode when top an empty Stack: "
<< errorCodeString[errorCode] << endl;
cout << "Init Queue:" << endl;
for (int i = 0; i < 10; ++i) {
q.enqueue(i);
printQueue(q);
}
cout << "Size of Queue: " << q.size() << endl;
output = q.isFull() ? "YES" : "NO";
cout << "Is Queue full?: " << output << endl;
cout << "Clear and print Queue:" << endl;
q.clear();
printQueue(q);
output = q.isEmpty() ? "YES" : "NO";
cout << "Is Queue empty?: " << output << endl;
errorCode = q.dequeue();
cout << "ErrorCode when dequeue Queue again: "
<< errorCodeString[errorCode] << endl;
errorCode = q.queueFront(data);
cout << "ErrorCode when queueFront an empty Queue: "
<< errorCodeString[errorCode] << endl;
errorCode = q.queueRear(data);
cout << "ErrorCode when queueRear an empty Queue: "
<< errorCodeString[errorCode] << endl;
cout << "Init Stack and Queue again:" << endl;
for (int i = 0; i < 10; i++) {
s.push(i);
q.enqueue(i);
}
cout << "Stack: ";
printStack(s);
cout << "Queue: ";
printQueue(q);
cout << "Use stackToQueue to create new Queue:" << endl;
stackToQueue(s, qTemp);
cout << "New Queue: ";
printQueue(qTemp);
cout << "Stack after: ";
printStack(s);
cout << "Use queueToStack to create new Stack" << endl;
queueToStack(q, sTemp);
cout << "New Stack: ";
printStack(sTemp);
cout << "Queue after: ";
printQueue(q);
return 0;
}
| true |
70514a381d3e937bfc0b2581c31c53496e3e5087 | C++ | navkamalrakra/random | /Lucky String.cc | UTF-8 | 1,109 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<string>
using namespace std;
inline int calculate_digit(long);
inline string create_binary(long);
int main()
{
unsigned long t=0, digit;
cin >> t;
while (cin >> t)
{
digit = calculate_digit(t);
}
return 0;
}
inline int calculate_digit(long num)
{
long exp = 1 ,nod = 0, tmp, total_num=0,nth = 0, nth_start;
/*if (num < nod)
{
exp=1, nod=0, tmp=0, total_num=0, nth=0, nth_start=0;
}*/
char ch;
string binary;
for(;;exp++)
{
tmp = pow(2,exp);
nod += tmp * exp;
total_num += tmp;
if(nod >= num)
{
break;
}
}
nth = (total_num - ((nod-num)/exp));
//nth_start = num - ((nod-num)%exp);
nth_start = (nod - ((total_num - (nth-1))*exp))+1;
binary = create_binary(nth+1);
ch = binary[num-nth_start+1];
switch (ch)
//switch (binary.at(num-nth_start+1))
{
case '0':
cout << "Hacker" << endl;
break;
default:
cout << "Earth" << endl;
}
}
inline string create_binary(long x)
{
if (x == 0) return "0";
if (x == 1) return "1";
if(x%2 == 0)
return create_binary(x/2)+"0";
else
return create_binary(x/2)+"1";
}
| true |
459680510fe87386cfc6a135174bbe44fa1738f1 | C++ | Lee-JaeWon/Cpp_study | /함수참조복사생성자/OpenChallenge.cpp | UHC | 4,310 | 3.453125 | 3 | [] | no_license | // Chapter 5, OpenChallenge
// ȣ ȯ, ȣ
// ASCII code
#include <iostream>
#include <string>
#include <locale>
using namespace std;
class Morse {
private:
string alphabet[26];
string digit[10];
string slash, question, comma, period, plus, equal;
string text;
public:
Morse();
void text_to_Morse(string, string&);
void morse_to_text(string, string&);
};
Morse::Morse() {
alphabet[0] = ".-"; //A
alphabet[1] = "-..."; //B
alphabet[2] = "-.-."; //C
alphabet[3] = "-.."; //D
alphabet[4] = "."; //E
alphabet[5] = "..-."; //F
alphabet[6] = "--."; //G
alphabet[7] = "...."; //H
alphabet[8] = ".."; //I
alphabet[9] = ".---"; //J
alphabet[10] = "-.-"; //K
alphabet[11] = ".-.."; //L
alphabet[12] = "--"; //M
alphabet[13] = "-."; //N
alphabet[14] = "---"; //O
alphabet[15] = ".--."; //P
alphabet[16] = "--.-"; //Q
alphabet[17] = ".-."; //R
alphabet[18] = "..."; //S
alphabet[19] = "-"; //T
alphabet[20] = "..-"; //U
alphabet[21] = "...-"; //V
alphabet[22] = ".--"; //W
alphabet[23] = "-..-"; //X
alphabet[24] = "-.--"; //Y
alphabet[25] = "--.."; //Z
digit[0] = "-----"; //0
digit[1] = ".----"; //1
digit[2] = "..---"; //2
digit[3] = "...--"; //3
digit[4] = "....-"; //4
digit[5] = "....."; //5
digit[6] = "-...."; //6
digit[7] = "--..."; //7
digit[8] = "----.."; //8
digit[9] = "----."; //9
slash = "-..-.";
question = "..--..";
comma = "--..--";
period = ".-.-.-";
plus = ".-.-.";
equal = "-...-";
}
void Morse::text_to_Morse(string text, string& morse) {
this->text = text;
int num = text.length();
for (int i = 0; i < num; i++) text[i] = toupper(text[i]);
for (int i = 0; i < num; i++) {
int tmp = text.at(i);
if (tmp >= 65 && tmp <= 90) { //alphabet
tmp -= 65;
morse += alphabet[tmp];
morse += " / ";
}
else if (tmp == 32) {
morse += " / ";
}
else if (tmp >= 48 && tmp <= 57) { //
tmp -= 48;
morse += digit[tmp];
morse += " / ";
}
else if (tmp == 47) { // '/'
morse += slash;
morse += " / ";
}
else if (tmp == 63) { // '?'
morse += question;
morse += " / ";
}
else if (tmp == 44) { // ','
morse += comma;
morse += " / ";
}
else if (tmp == 46) { // '.'
morse += period;
morse += " / ";
}
else if (tmp == 43) { // '+'
morse += plus;
morse += " / ";
}
else if (tmp == 61) { // '='
morse += equal;
morse += " / ";
}
else
continue;
}
}
void Morse::morse_to_text(string morse, string& text) {
int num = morse.length();
int j = 0;
string s;
char c;
for (int i = 0; i < num; i++) {
int tmp = morse.at(i);
if (tmp == 47) { // '/' ߰
if (j == 0) // ù ó
s = morse.substr(j, i - j - 1);
else
s = morse.substr(j + 2, i - j - 3);
j = i;
for (int k = 0; k < 26; k++) {
if (alphabet[k] == s) {
c = k + 65;
text += c;
break;
}
else if (digit[k] == s) {
text += k + 48;
break;
}
else if (slash == s) {
text += '/';
break;
}
else if (question == s) {
text += '?';
break;
}
else if (comma == s) {
text += ',';
break;
}
else if (period == s) {
text += '.';
break;
}
else if (plus == s) {
text += '+';
break;
}
else if (equal == s) {
text += '=';
break;
}
else if (s == " ") {
text += " ";
break;
}
else {
continue;
}
}
}
else continue;
}
// 빮ڿ ҹ ٽ
int t_num = text.length();
char a, b;
for (int i = 0; i < t_num; i++) text[i] = tolower(text[i]);
int res = this->text.compare(text);
if (res == 0)
exit;
for (int i = 0; i < t_num; i++) {
a = this->text[i];
b = text[i];
if (a != b) text[i] = toupper(text[i]);
}
}
int main() {
string m_text;
string m_morse = "";
cout << "Ʒ ؽƮ Էϼ. ȣ ٲߴϴ." << endl;
cout << "/ /" << " Դϴ." << endl;
getline(cin, m_text, '\n');
Morse morse;
morse.text_to_Morse(m_text, m_morse);
cout << m_morse << endl << endl;
m_text = "";
cout << " ȣ ٽ ؽƮ ٲߴϴ." << endl;
morse.morse_to_text(m_morse, m_text);
cout << m_text << endl;
} | true |
c6184a779a9e628d97bafa9f92d5b9d80c486e89 | C++ | wojiushimogui/leetCode | /isHappy.cpp | GB18030 | 993 | 3.890625 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
//Ĺܣָλĺ
int everyDigitSquareSum(int n){
if(n<0){
return 0;
}
int sum=0;
while(n){
int remainder=n%10;
sum+=(remainder*remainder);
n/=10;
}
return sum;
}
#define N 10000
//ĹܣǷtarget
bool isExist(int *nums,int numsSize,int target){
if(nums==NULL||numsSize<1){
return false;
}
for(int i=0;i<numsSize;i++){
if(nums[i]==target){
return true;
}
}
return false;
}
bool isHappy(int n) {
if(n<0){
return 0;
}
int *value=(int *)malloc(N*sizeof(int));
if(value==NULL){
exit(EXIT_FAILURE);
}
int index=0;
while(n!=1){
value[index++]=n;
int res=everyDigitSquareSum(n);
if(isExist(value,index,res)){//ѭfalse
return false;
}
n=res;
}
return true;
}
int main(void){
int n;
scanf("%d",&n);
bool res=isHappy( n);
if(res){
printf("is a happy number\n");
}
else{
printf("NO\n");
}
}
| true |
20c60a919708559a7dd831c9b3b25e2c32a07238 | C++ | zhengzebin525/LINUX-Environmental-programming | /C++编程/类的封装/lcd.cpp | UTF-8 | 2,032 | 2.890625 | 3 | [] | no_license | #include "lcd.h"
extern "C"
{
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/fb.h>
}
lcd::lcd(string lcdname)
{
this->lcdname = lcdname;
}
bool lcd::open()
{
//this->lcdname.data() 将string转换成const char*类型 this->lcdname.c_str 也是一样
this->fd = ::open(this->lcdname.data(),O_RDWR); //::去系统找open函数
struct fb_var_screeninfo info;
int ret = ioctl(this->fd, FBIOGET_VSCREENINFO,&info);
if(ret < 0)
{
cout<<"info fail"<<endl;
return false;
}
this->screen_w = info.xres_virtual;
this->screen_h = info.xres_virtual;
this->pixel_byte = info.bits_per_pixel/8;
this->mapptr = mmap(NULL, this->screen_h*this->screen_w*pixel_byte,
PROT_READ|PROT_WRITE,MAP_SHARED,this->fd,0);
if(this->mapptr == (void *)-1)
{
cout<<"mapptr fail"<<endl;
return false;
}
return true;
}
void lcd::setcolor(Color color)
{
this->lcdcolor = color;
}
void lcd::linew(int w)
{
this->linewidth = w;
}
//直线
void lcd::setline(int x1, int y1, int x2, int y2,Color color)
{
this->lcdcolor = color;
unsigned int *p = (unsigned int *)this->mapptr;
p = p+x1+y1*this->screen_w;
for(int j=0;j<(y2-y1);j++)
{
for(int i=x1;i<x2;i++)
{
p[i] = this->lcdcolor;
}
p = p+this->screen_w;
}
}
//矩形
void lcd::setrect(int x1,int y1,int x2,int y2,Color color)
{
this->lcdcolor = color;
unsigned int *p = (unsigned int *)this->mapptr;
p = p+x1+y1*this->screen_w;
for(int j=y1;j<y2;j++)
{
for(int i=x1;i<x2;i++)
{
p[i] = this->lcdcolor;
}
p = p+this->screen_w;
}
}
void lcd::lcdclose()
{
::close(this->fd);
free(this->mapptr);
}
| true |
4b8c90464d41879a71f866369631bf7312fb7cd6 | C++ | tibaes/motion | /backup/comp_norm_components.cpp | UTF-8 | 2,798 | 2.734375 | 3 | [
"MIT"
] | permissive | /* Compute Normalized Mixtures
* Input: GMM YML
* Output: Normalized GMM YML
*
* Rafael H Tibaes [ra.fael.nl]
* IMAGO Research Group
*/
#include <cv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/opencv.hpp>
#include <cstdio>
typedef struct Component {
cv::Mat mean, cov;
int flowvector_count;
float weight;
} Component;
void importComponentsFromFile(const char* filename,
std::vector<Component>& vcomp)
{
cv::FileStorage input(filename, cv::FileStorage::READ);
cv::FileNode gmm = input["GMM"];
cv::Size tmp;
for(cv::FileNodeIterator it = gmm.begin(); it < gmm.end(); ++it) {
Component c;
(*it)["mean"] >> c.mean;
(*it)["cov"] >> c.cov;
(*it)["count"] >> tmp;
c.flowvector_count = tmp.height; // TODO - fix Size
c.weight = 0.0f;
vcomp.push_back(c);
}
}
void saveMixture(std::vector<Component>& vcomp, cv::FileStorage& output) {
output << "GMM" << "[";
for (int i = 0; i < vcomp.size(); ++i) {
output << "{"
<< "mean" << vcomp[i].mean
<< "cov" << vcomp[i].cov
<< "weight" << vcomp[i].weight
<< "}";
}
output << "]";
}
void normalize(std::vector<Component>& vcomp) {
// spatial translation + weights
cv::Mat sum_comp = cv::Mat::zeros(vcomp[0].mean.size(), vcomp[0].mean.type());
int sum_flowvector = 0;
for (int i = 0; i < vcomp.size(); ++i) {
sum_comp += vcomp[i].mean;
sum_flowvector += (int)vcomp[i].flowvector_count;
}
cv::Mat meancomp = sum_comp / vcomp.size();
for (int i = 0; i < vcomp.size(); ++i) {
vcomp[i].mean -= meancomp;
vcomp[i].weight = (float)vcomp[i].flowvector_count / (float)sum_flowvector;
}
// Center normalization
cv::Mat max = cv::Mat::zeros(vcomp[0].mean.size(), vcomp[0].mean.type());
for (int i = 0; i < vcomp.size(); ++i) {
for (int d = 0; d < max.cols; ++d) {
float comp_d = fabsf(vcomp[i].mean.at<float>(0,d));
if (comp_d > max.at<float>(0,d)) {
max.at<float>(0,d) = comp_d;
}
}
}
for (int i = 0; i < vcomp.size(); ++i) {
vcomp[i].mean /= max;
}
// Covariance normalization - TODO, conferir!
for (int i = 0; i < vcomp.size(); ++i) {
for (int a = 0; a < max.cols; ++a) {
for (int b = 0; b < max.cols; ++b) {
vcomp[i].cov.at<float>(a,b) *= max.at<float>(0,a) * max.at<float>(0,b);
}
}
}
}
int main(int argc, char** argv) {
if (argc < 3) {
printf("Use %s <output.mixture.yml> [<input.cluster.yml>]+\n", argv[0]);
return -1;
}
std::vector<Component> vcomp;
for(int fileid = 2; fileid < argc; ++fileid) {
importComponentsFromFile(argv[fileid], vcomp);
}
if (vcomp.size() >= 1) normalize(vcomp);
cv::FileStorage output(argv[1], cv::FileStorage::WRITE);
saveMixture(vcomp, output);
return 0;
}
| true |
f986fdfb82934bef708e62ba0c31ae58ed979643 | C++ | silent-lad/GFG | /course/12.BST/ceil.cpp | UTF-8 | 533 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
struct Node
{
ll value;
Node *left;
Node *right;
};
Node *findCiel(ll x, Node *root)
{
Node *temp = root;
Node *res = NULL;
while (temp != NULL)
{
if (temp->value == x)
{
return temp;
}
else if (temp->value < x)
{
temp = temp->right;
}
else
{
res = temp;
temp = temp->left;
}
}
return res;
}
int main()
{
} | true |
49552c8fe26097e1b56b1d1f7abe193394363bf3 | C++ | MPercieduSert/NoteCpp | /Library/Entities/AttributMultiple.h | UTF-8 | 5,785 | 2.90625 | 3 | [] | no_license | /*Auteur: PERCIE DU SERT Maxime
*Date: 17/02/2017
*/
#ifndef ATTRIBUTMULTIPLE_H
#define ATTRIBUTMULTIPLE_H
#include "AttributSimple.h"
/*! \ingroup groupeBaseAttributEntity
* \brief Classe template des attributs multiple.
*/
template<class... Attribut> class Attributs;
template<class Attribut> class Attributs<Attribut> : public Attribut
{
public:
// using AttPre = Attribut;
// using AttSuiv = NoAttribut;
using Attribut::Attribut;
CONSTR_DESTR_DEFAUT(Attributs)
};
template <class AttributPremier, class... AttributSuivant> class Attributs<AttributPremier, AttributSuivant...>
: public AttributPremier, public Attributs<AttributSuivant...>
{
public:
//! Nombre d'attribut de l'entité.
enum {NbrAtt = AttributPremier::NbrAtt + Attributs<AttributSuivant...>::NbrAtt};
using AttPre = AttributPremier;
using AttSuiv = Attributs<AttributSuivant...>;
CONSTR_DESTR_DEFAUT(Attributs)
//! Constructeur
Attributs<AttributPremier, AttributSuivant...>(const AttPre & attPremier)
: AttPre(attPremier) {}
//! Constructeur
Attributs<AttributPremier, AttributSuivant...>(const AttSuiv & attSuivant)
: AttSuiv(attSuivant) {}
//! Renvoie une chaine de caractère contenant les noms, les validités et les valeurs des attributs.
virtual QString affiche() const
{return AttributPremier::affiche().append("\n").append(Attributs<AttributSuivant...>::affiche());}
//! Retourne un QVariant contenant la donnée souhaitée ou un QVariant nulle si num est invalide.
QVariant data(int num) const
{return num < NbrAtt ? dataP(num) : QVariant();}
//! Teste si l'entité est valide.
bool isValid() const
{return AttributPremier::isValid() && Attributs<AttributSuivant...>::isValid();}
//! Retourne le nom de l'attribut donnée souhaitée, pos doit être valide.
static QString nomAttribut(int pos)
{return pos < AttributPremier::NbrAtt ? AttributPremier::nomAttribut(pos)
: Attributs<AttributSuivant...>::nomAttribut(pos - AttributPremier::NbrAtt);}
//! Renvoie une chaine de caractère contenant les valeurs de l'attribut.
QString toString() const
{return AttributPremier::toString().append(",").append(Attributs<AttributSuivant...>::toString());}
//! Test d'égalité entre cette entité et celle transmise en argument.
bool operator ==(const Attributs<AttributPremier, AttributSuivant...> & entity) const
{return AttributPremier::operator ==(entity) && Attributs<AttributSuivant...>::operator ==(entity);}
protected:
//! Retourne un QVariant contenant la donnée souhaitée, pos doit être valide.
QVariant dataP(int pos) const
{return pos < AttributPremier::NbrAtt ? AttributPremier::dataP(pos)
: Attributs<AttributSuivant...>::dataP(pos - AttributPremier::NbrAtt);}
//! Remplace les attributs de l'entité par celle de l'entité transmise.
void set(const Attributs<AttributPremier, AttributSuivant...> & entity)
{
AttributPremier::set(entity);
Attributs<AttributSuivant...>::set(entity);
}
};
template<class AttFound, class Att, class AttPre, class AttSuiv, int Pos> struct PosisionEnumTemp
{
enum {Position = PosisionEnumTemp<AttFound,AttPre,typename AttPre::AttPre,typename AttPre::AttSuiv,Pos>::Position
+ PosisionEnumTemp<AttFound,AttSuiv,typename AttSuiv::AttPre,typename AttSuiv::AttSuiv,AttPre::NbrAtt + Pos>::Position};
};
template<class AttFound, class Att, int Pos> struct PosisionEnumTemp<AttFound,Att,NoAttribut,NoAttribut,Pos>
{enum {Position = 0};};
template<class AttFound, int Pos> struct PosisionEnumTemp<AttFound,AttFound,NoAttribut,NoAttribut,Pos>
{enum {Position = Pos};};
template<class AttFound, int Pos> struct PosisionEnumTemp<AttFound,Attributs<AttFound>,NoAttribut,NoAttribut,Pos>
{enum {Position = Pos};};
template<class AttFound, class Ent> using PositionEnum = PosisionEnumTemp<AttFound,Ent,typename Ent::AttPre,typename Ent::AttSuiv,0>;
using CibleAttributs = Attributs<IdCibleAttribut, CibleAttribut>;
using CibleDateTimeAttribut = Attributs<CibleAttributs, DateTimeValideAttribut>;
using CibleDateTimeNumAttribut = Attributs<CibleDateTimeAttribut, NumAttribut>;
using OrigineAttributs = Attributs<IdOrigineAttribut, OrigineAttribut>;
template<class ValeurAttribut> using CibleDateTimeNumValeurAttribut = Attributs<CibleDateTimeNumAttribut, ValeurAttribut>;
using RelationAttribut = Attributs<Id1Attribut, Id2Attribut>;
using RelationDateTimeAttribut = Attributs<RelationAttribut, DateTimeValideAttribut>;
using RelationNumAttribut = Attributs<RelationAttribut, NumAttribut>;
using IdNumAttribut = Attributs<Id1Attribut, NumAttribut>;
using IdProgNomAttribut = Attributs<IdProgAttribut,NomAttribut>;
template<class ValeurAttribut> using IdNumValeurAttribut = Attributs<IdNumAttribut, ValeurAttribut>;
using NomTypeAttribut = Attributs<NomAttribut, TypeAttribut>;
using NcNomAttribut = Attributs<NcAttribut, NomAttribut>;
using NcNomTypeAttribut = Attributs<NcNomAttribut, TypeAttribut>;
using TexteAttributs = Attributs<CreationAttribut,ModificationAttribut,TexteAttribut>;
/*! \ingroup groupeBaseAttributEntity
* \brief Attributs contenant deux identifiant dont exactement un est non nul pour être valide.
*/
class RelationExactOneNotNullAttribut : public Attributs<Id1NullAttribut,Id2NullAttribut>
{
public:
using Attributs<Id1NullAttribut,Id2NullAttribut>::Attributs;
CONSTR_DESTR_DEFAUT(RelationExactOneNotNullAttribut)
//! Teste si l'entité est valide.
bool isValid() const
{return (Id1NullAttribut::isValid() && id2() == 0) || (id1() == 0 && Id2NullAttribut::isValid());}
};
#endif // ENTITYATTRIBUT_H
| true |