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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d11c572a6dd9186be0b4bcc3bfd325c69e13cb15 | C++ | Ypostolov/Lafore_tasks | /ClasBookClient/ClasBookClient/ClasBookClient.cpp | UTF-8 | 2,200 | 3.640625 | 4 | [] | no_license |
class Book
{
char* booksName;
int booksIndex;
int abonentsIndex;
public:
Book()
{
booksName = "";
booksIndex = 0;
abonentsIndex = 0;
}
Book(char* inBooksName, int inBooksIndex)
{
booksName = inBooksName;
booksIndex = inBooksIndex;
abonentsIndex = 0;
}
int getBooksIndex()
{
return booksIndex;
}
void takenByAbonent(int inAbonentIndex)
{
abonentsIndex = inAbonentIndex;
}
void returnedByAbonent()
{
abonentsIndex = 0;
}
};
class Abonent
{
char* name;
int index;
int * BooksIndexes;
int booksCapasity;
public:
Abonent(char* inAbonentsName, int inBooksCapasity, int inIndex)
{
name = inAbonentsName;
index = inIndex;
booksCapasity = inBooksCapasity;
BooksIndexes = new int[booksCapasity];
for (int i = 0; i < booksCapasity; i++)
{
BooksIndexes[i] = 0;
}
}
~Abonent()
{
delete BooksIndexes;
}
int getAbonIndex()
{
return index;
}
void takeTheBook(int inBooksIndex)
{
for (int i = 0; i < booksCapasity; i++)
{
if (BooksIndexes[i] == 0)
{
BooksIndexes[i] = inBooksIndex;
}
}
}
void reternTheBook(int inBooksIndex)
{
for (int i = 0; i < booksCapasity; i++)
{
if (BooksIndexes[i] == inBooksIndex)
{
BooksIndexes[i];
}
}
}
};
void main()
{
Book fond[4];
fond[0] = Book("A", 9);
fond[1] = Book("B", 8);
fond[2] = Book("C", 5);
fond[3] = Book("A", 100);
Abonent petia("Petia", 2, 9);
Abonent vasia("Vasia", 2, 7);
petia.takeTheBook(fond[0].getBooksIndex());
fond[0].takenByAbonent(petia.getAbonIndex());
petia.takeTheBook(fond[2].getBooksIndex());
fond[2].takenByAbonent(petia.getAbonIndex());
vasia.takeTheBook(fond[3].getBooksIndex());
fond[3].takenByAbonent(vasia.getAbonIndex());
petia.reternTheBook(fond[2].getBooksIndex());
fond[2].returnedByAbonent();
} | true |
82845ec0721f0aa7f67945e9918f428874ea39b0 | C++ | Jojendersie/Monolith | /tools/ComponentEditor/ComponentEditor/SceneManager.cpp | UTF-8 | 468 | 2.515625 | 3 | [] | no_license | #include "SceneManager.h"
SceneManager::SceneManager(QObject *parent):
QGLAbstractScene(parent),
m_rootNode(new QGLSceneNode(this))
{
}
SceneManager::~SceneManager(void)
{
delete m_rootNode;
}
QList<QObject *> SceneManager::objects() const
{
QList<QGLSceneNode *> children = m_rootNode->allChildren();
QList<QObject *> objects;
for (int index = 0; index < children.size(); ++index)
objects.append(children.at(index));
return objects;
}
| true |
a557d10d68e82c7bd5e9ea8ffb7eaa09c875b0a5 | C++ | Alaxe/noi2-ranking | /2019/solutions/A/NKM-VTarnovo/beatle.cpp | UTF-8 | 1,278 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct duska
{
int x;
int y;
int d;
};
duska k[10001];
int n,t,a[6001],maxy=0,br=0,p;
void init()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>k[i].x>>k[i].y>>k[i].d;
if(k[i].y>maxy) maxy=k[i].y;
}
cin>>t;
for(int i=0;i<t;i++) cin>>a[i];
}
int find(int y1,int i)
{
int j=0;
while(j<n)
{
if(k[j].y==y1&&a[i]>=k[j].x&&a[i]+1>=k[j].x&&a[i]<=(k[j].x+k[j].d)&&a[i]+1<=(k[j].x+k[j].d)) return j;
j++;
}
return 0;
}
int solve(int i)
{
a[i]=p;
br=0; int y1=maxy;
int j;
while(y1>=0)
{
int g=find(y1,i);
if(!g) y1--;
else
{
j=g; a[i]=k[j].x-1; br++; y1--;
}
}
return br;
}
int solve1(int i)
{
a[i]=p;
int br=0; int y1=maxy;
while(y1>=0)
{
int g=find(y1,i);
if(!g) y1--;
else
{
a[i]=k[g].x+k[g].d; br++; y1--;
}
}
return br;
}
int main()
{
init();
for(int i=0;i<t;i++)
{
p=a[i]; cout<<min(solve(i),solve1(i))<<" ";
}
}
//13 1 4 2 9 5 2 8 1 5 2 2 2 6 2 2 2 6 3 1 3 1 4 3 2 9 3 3 5 4 5 4 5 2 7 5 1 8 6 2 5 2 5 7 8 11
//13 1 4 2 9 5 2 8 1 5 2 2 2 6 2 2 2 6 3 1 3 1 4 3 2 9 3 3 5 4 5 4 5 2 7 5 1 8 6 2 1 5
| true |
3bc3801dbaa4f792bcb228b3381f948f2a9311c0 | C++ | Mrtony94/Smart-Home | /riego_probar/riego_probar.ino | UTF-8 | 748 | 2.671875 | 3 | [] | no_license | #define bomba 39
#define sensor_humedad A8
// cuanto mayor numero más seca estará la tierra
#define seco 700
void setup()
{
Serial.begin(9600);
pinMode(sensor_humedad, INPUT);
pinMode(bomba, OUTPUT);
}
void loop()
{
int SensorValue = analogRead(sensor_humedad); //coge una muestra de la humedad de la tierra
Serial.print(SensorValue); Serial.print(" - ");
if(SensorValue >= seco)
{
// Si el suelo esta demasiado seco comienza a regar por unos segundos
// y luego se espera unos segundos antes de volver a medir la humedad
Serial.println("Necesita agua");
digitalWrite(bomba, LOW);
delay(1000);
digitalWrite(bomba, HIGH);
delay(1000);
}
delay(500);
}
| true |
d18b7d5e8419bf31c91aac3832ea18b259563b1b | C++ | gabriel-bri/ccufcqx | /3º semestre/Estruturas de dados avançada/codigos_professor/12_abril/avl.cpp | UTF-8 | 3,243 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include "node.h"
#include "avl.h"
using namespace std;
// retorna a altura do nó.
// se a arvore for vazia ela tem altura 0
// caso contrario, retorna o valor que está no campo height
int avl_tree::height(Node *node) {
return (node == nullptr) ? 0 : node->height;
}
int avl_tree::balance(Node *node) {
return height(node->right) - height(node->left);
}
Node* avl_tree::rightRotation(Node *p) {
Node *u = p->left;
p->left = u->right;
u->right = p;
// recalcular as alturas de p e de u
p->height = 1 + max(height(p->left),height(p->right));
u->height = 1 + max(height(u->left),height(u->right));
return u;
}
Node* avl_tree::leftRotation(Node *p) {
Node *u = p->right;
p->right = u->left;
u->left = p;
// recalcular as alturas de p e de u
p->height = 1 + max(height(p->right),height(p->left));
u->height = 1 + max(height(u->left),height(u->right));
return u;
}
// função pública que recebe uma chave e a insere
// somente se ela não for repetida
void avl_tree::add(int key) {
root = add(root, key);
}
// função recursiva privada que recebe uma raiz de arvore
// e uma chave e insere a chave na tree se e somente se
// ela nao for repetida. Claro, tem que deixar AVL novamente
Node* avl_tree::add(Node *p, int key) {
if(p == nullptr)
return new Node(key);
if(key == p->key)
return p;
if(key < p->key)
p->left = add(p->left, key);
else
p->right = add(p->right, key);
p = fixup_node(p, key);
return p;
}
Node* avl_tree::fixup_node(Node *p, int key) {
// recalcula a altura de p
p->height = 1 + max(height(p->left),height(p->right));
// calcula o balanço do p
int bal = balance(p);
if(bal >= -1 && bal <= 1) {
return p;
}
if(bal < -1 && key < p->left->key) {
p = rightRotation(p);
}
else if(bal < -1 && key > p->left->key) {
p->left = leftRotation(p->left);
p = rightRotation(p);
}
else if(bal > 1 && key > p->right->key) {
p = leftRotation(p);
}
else if(bal > 1 && key < p->right->key) {
p->right = rightRotation(p->right);
p = leftRotation(p);
}
return p;
}
void avl_tree::clear() {
root = clear(root);
}
Node *avl_tree::clear(Node *node) {
if(node != nullptr) {
node->left = clear(node->left);
node->right = clear(node->right);
delete node;
}
return nullptr;
}
avl_tree::~avl_tree() {
clear();
}
void avl_tree::bshow() const {
bshow(root, "");
}
void avl_tree::bshow(Node *node, std::string heranca) const {
if(node != nullptr && (node->left != nullptr || node->right != nullptr))
bshow(node->right , heranca + "r");
for(int i = 0; i < (int) heranca.size() - 1; i++)
std::cout << (heranca[i] != heranca[i + 1] ? "│ " : " ");
if(heranca != "")
std::cout << (heranca.back() == 'r' ? "┌───" : "└───");
if(node == nullptr){
std::cout << "#" << std::endl;
return;
}
std::cout << node->key << std::endl;
if(node != nullptr && (node->left != nullptr || node->right != nullptr))
bshow(node->left, heranca + "l");
} | true |
f2ff3c3d89e456be1267215d75d5cebde827c398 | C++ | Andrewpqc/pat_basic | /1049.cpp | UTF-8 | 416 | 3.0625 | 3 | [
"MIT"
] | permissive | /**
* 找规律 部分正确
**/
#include <iostream>
#include <iomanip>
using namespace std;
int main(void){
int count;
cin >> count;
float arr[count];
float sum = 0.0;
for (int i = 0; i < count; i++)
cin >> arr[i];
for (int i = 0; i < count; i++)
sum += arr[i] * (count - i) * (i + 1);
cout << setiosflags(ios::fixed) << setprecision(2) << sum << endl;
return 0;
} | true |
888af103c6b0190a6b8887960643064f3589a8e4 | C++ | iblackcat/leetcode | /97_Interleaving_String.cpp | UTF-8 | 1,108 | 3.109375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
bool isInterleave(char* s1, char* s2, char* s3) {
int len1 = strlen(s1);
int len2 = strlen(s2);
int len3 = strlen(s3);
if (len3 != len1+len2) return false;
bool *dp = (bool*)malloc(sizeof(bool)*(len1+1)*(len2+1));
memset(dp, 0, sizeof(bool)*(len1+1)*(len2+1));
dp[0] = true;
for (int i=1; i<=len1; i++) {
if (s1[i-1] == s3[i-1]) dp[i*(len2+1)] = true;
else break;
}
for (int i=1; i<=len2; i++) {
if (s2[i-1] == s3[i-1]) dp[i] = true;
else break;
}
for (int i=1; i<=len1; i++) {
for (int j=1; j<=len2; j++) {
dp[i*(len2+1)+j] = (dp[(i-1)*(len2+1)+j] && s1[i-1]==s3[i+j-1]) || (dp[i*(len2+1)+j-1] && s2[j-1]==s3[i+j-1]);
}
}
return dp[len1*(len2+1)+len2];
}
int main() {
char s1[1024] = "z";
char s2[1024] = "dbbca";
char s3[1024] = "zdbbca";
char s4[1024] = "aadbbbaccc";
printf("%d\n%d\n",isInterleave(s1,s2,s3), isInterleave(s1,s2,s4));
return 0;
}
| true |
acc2cf7454d330fef5249daf624c63c7dd2d698d | C++ | RyanLebeau/UniOfWindsorWork | /YearThree/CPP/AOneRyanLebeau.cpp | UTF-8 | 642 | 3.375 | 3 | [] | no_license | /*
Ryan Lebeau
22/01/2018
Assignment One
COMP 3400
*/
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
bool inQuotes = false;
cout<<"Please enter a string:"<<endl;
getline(cin, input);
//loops through each character in the array
for(unsigned int i=0;i<input.length();i++){
//if a double quote was reached
if(input.at(i)=='\"')
inQuotes = !inQuotes;
//if not inside a double quote change punct to whitespace
else if(!inQuotes && (input.at(i)=='.' || input.at(i)==',' || input.at(i)=='-' ||
input.at(i)=='?' || input.at(i)=='\'')){
input.at(i) = ' ';
}
}
cout<<endl<<input<<endl;
}
| true |
cc2fab6e3d2e0047eaa543dd4e76eb1cd5b41229 | C++ | brooksbp/snippets | /book.EOPI/5.2.cc | UTF-8 | 1,567 | 3.71875 | 4 | [] | no_license | // Write a function that takes an arithmetical expression in RPN
// and returns the number that the expression evaluates to.
// "3,4,*,1,2,+,+" -> "12,3,+" -> 15
// A,B,? where A and B are RPN expr and ? is an operation.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
// My mistake was an approach with R->L.. harder than L->R
int eval_rpn(string expr) {
stack<int> operands;
for (string::iterator it = expr.begin(); it != expr.end(); ++it) {
if (*it == ',') {
continue;
}
if (*it == '+' || (*it == '-' && *(it+1) == ',') || *it == '*' || *it == '/') {
if (2 > operands.size()) {
throw "parse error";
}
int a = operands.top(); operands.pop();
int b = operands.top(); operands.pop();
int c;
switch (*it) {
case '+': c = b + a; break;
case '-': c = b - a; break;
case '*': c = b * a; break;
case '/': c = b / a; break;
}
operands.push(c);
} else {
int x = 0;
bool negative = false;
if (*it == '-') {
negative = true;
it++;
}
while (it != expr.end() && *it != ',') {
x = x * 10 + (*it - '0');
it++;
}
if (negative) {
x = -x;
}
operands.push(x);
}
}
return operands.top();
}
int main(int argc, char *argv[]) {
cout << eval_rpn(string("1,3,+")) << endl;
cout << eval_rpn(string("10,30,+")) << endl;
cout << eval_rpn(string("1,3,5,-,+")) << endl;
cout << eval_rpn(string("-11,6,+")) << endl;
return 0;
}
| true |
f3ab3bf6fa5b8818cf695caa3987342a66407f33 | C++ | ravi00ei51/cppos | /kernel/ipc/events/events.cpp | UTF-8 | 2,351 | 2.59375 | 3 | [] | no_license | #include "events.h"
#include "task.h"
#include "schedInfo.h"
events::events( void )
{
uint8_t i;
for( i = 0; i < MAX_NUMBER_OF_EVENT_NODES; i++ )
{
this->eventNodes[i].free = TRUE;
}
}
events::~events( void )
{
}
eventNodeType * events::eventAllocateEventNode( void )
{
uint8_t i;
eventNodeType * pNode = NULL;
for( i = 0; i < MAX_NUMBER_OF_EVENT_NODES; i++ )
{
if( this->eventNodes[i].free == TRUE )
{
this->eventNodes[i].free = FALSE;
pNode = &(this->eventNodes[i]);
break;
}
}
return pNode;
}
void events::eventFreeEventNode( eventNodeType * pNode )
{
if( pNode != NULL )
{
pNode->free = TRUE;
}
}
void events::eventSend( uint8_t maskId )
{
uint32_t mask = 0u;
uint32_t taskId = 0xFFFFFFFFu;
uint32_t i = 0u;
eventNodeType * pNode = NULL;
if( this->eventPendList.listNumberOfNodes() > 0u )
{
sched<SCHEDULER_TYPE>::schedLock();
mask = ( 1u << maskId );
for( i = 1; i <= this->eventPendList.listNumberOfNodes(); i++ )
{
this->eventPendList.listGetNodeData( pNode, 1u );
if( pNode->mask & mask )
{
this->eventPendList.listRemoveNodeData( pNode );
taskId = pNode->taskId;
this->eventFreeEventNode( pNode );
task::setTaskState( taskId, TASK_STATE_READY, TASK_STATE_INVOKE_LATER );
}
}
sched<SCHEDULER_TYPE>::schedUnlock();
asm("SVC #0");
}
else
{
}
}
void events::eventTaskReceive( uint32_t taskId, uint8_t mask, uint32_t timeout )
{
task * pTask = NULL;
eventNodeType * pNode = NULL;
sched<SCHEDULER_TYPE>::schedLock();
pTask = (task *)taskId;
if( pTask != NULL )
{
pNode = this->eventAllocateEventNode();
if( pNode != NULL )
{
mask = (uint8_t)(1 << mask);
pNode->taskId = taskId;
pNode->mask = mask;
pNode->timeout = timeout;
this->eventPendList.listInsertNodeData( pNode );
task::setTaskState( pNode->taskId, TASK_STATE_PENDED, TASK_STATE_INVOKE_LATER );
}
}
else
{
}
sched<SCHEDULER_TYPE>::schedUnlock();
asm("SVC #0");
}
| true |
e9d1990b9cb348d660d35407ad4a2546071ecf62 | C++ | Jeepee-Liu/cpp-course | /20160930/formatOutput/formatOutput.cpp | UTF-8 | 6,161 | 3.0625 | 3 | [] | no_license | #ifdef _FORMAT_OUTPUT_H
/********** public methods **********/
FormatOutput::FormatOutput() {
this->isFileDirSet = false;
this->dataSizeN[0] = 0;
this->dataSizeN[1] = 0;
} // Done & I don't know how to test it
bool FormatOutput::setFileDir(std::string dir) {
this->fileDir = dir;
std::ofstream fOut(dir);
if (!fOut) {
return false;
}
this->isFileDirSet = true;
/***** For test: *****
* std::cout << "File directory set!" << std::endl;
*/
return true;
} // Done & tested
// Append a VECTOR to data array
bool FormatOutput::appendData(std::string name, std::vector<double> dataColumn) {
int columnSize = dataColumn.size();
int &curCol = this->dataSizeN[1];
int &RowN = this->dataSizeN[0];
if( curCol==0 || RowN==columnSize ) {
// If this is the first column OR of matched size
// Allocate certain memory for the column
RowN = columnSize;
double* dataColPtr = new double[RowN];
this->namesVec.push_back(name);
// Change vector into 1-D array
for(int i=0; i!=columnSize; ++i) {
dataColPtr[i] = dataColumn[i];
// For test:
// std::cout << dataColPtr[i] << std::endl;
}
// append a row to data column
this->data[curCol] = dataColPtr;
curCol++;
// *** For test:
// std::cout << " column # : " <<this->dataSizeN[1] <<std::endl;
// std::cout << " row number : " << this->dataSizeN[0] << std::endl;
return true;
}
else {
// Not the first column
if (columnSize != this->dataSizeN[0]) {
// Array size not matched
return false;
}
}
return false;
} // Done & tested
// Append a LIST to data array
bool FormatOutput::appendData(std::string name, double* dataColumn, int len) {
int columnSize = len;
int &curCol = this->dataSizeN[1];
int &RowN = this->dataSizeN[0];
if ( curCol==0 || RowN==columnSize ) {
// If this is the first column OR of matched size
// Allocate certain memory for the column
RowN = columnSize;
double* dataColPtr = new double[RowN];
// Change vector into 1-D array
for(int i=0; i!=columnSize; ++i) {
dataColPtr[i] = dataColumn[i];
}
int curCol = this->dataSizeN[1];
this->data[curCol] = dataColPtr; // append a row to data column
this->namesVec.push_back(name); // append name of this data column to the name vector
this->dataSizeN[0] = columnSize; // define column size under both circumstances
this->dataSizeN[1]++; // add a column in size
return true;
}
else {
// Not the first column AND array size not matched
return false;
}
} // Done & tested
int* FormatOutput::getDataSize(){
// prevent direct call at private pointer
int* dataSizePtr = new int[2];
dataSizePtr[0] = dataSizeN[0];
dataSizePtr[1] = dataSizeN[1];
return this->dataSizeN;
} // Done
bool FormatOutput::writeData() {
if (!isFileDirSet) {
return false;
}
this->data2str(1); // mode: concise
std::ofstream fOut(this->fileDir);
fOut << this->dataStr;
fOut.close();
return true;
} // Done & tested
void FormatOutput::clearData(){
for(int i=0; i!=this->dataSizeN[1]; ++i) {
/***** For test:
* std::cout<< "Loop #: " << i << std::endl;
*/
delete[] this->data[i];
}
this->namesVec.clear();
this->dataSizeN[0] = 0;
this->dataSizeN[1] = 0;
} // Done & debugged & tested
void FormatOutput::printData() {
// int* dataSize = this->getDataSize();
int maxCol = this->dataSizeN[1];
int maxRow = this->dataSizeN[0];
// print header
std::cout << "\ndata table of " << maxRow
<< '*' << maxCol << std::endl;
// refesh the string buffering the output
this->data2str(0); // mode: decorated
/* **** For test:
* std::cout << "****** Break Point 2." << std::endl;
*/
// print data
std::cout << this->dataStr;
} // Done & tested
std::string FormatOutput::num2str(double num) {
char* tmpCharPtr = new char[100];
std::sprintf(tmpCharPtr,"%.6f",num);
std::string str(tmpCharPtr);
delete[] tmpCharPtr;
return str;
} // Done & tested
/********** private methods **********/
void FormatOutput::data2str(){
this->clearDataStr();
// int* dataSize = this->getDataSize();
int maxCol = this->dataSizeN[1];
int maxRow = this->dataSizeN[0];
std::string &bufferStr = this->dataStr;
std::string boldLine(16*maxCol,'=');
std::string thinLine(16*maxCol,'-');
// print correspondent names in the first line
bufferStr += boldLine + '\n';
for(auto name : this->namesVec) {
this->dataStr = this->dataStr + name + "\t\t";
}
bufferStr += '\n' + thinLine + '\n';
// append data to the buffer string
for(int row=0; row<maxRow; ++row) {
// append each row of data
for(int col=0; col<maxCol; ++col) {
/***** For test: *****
* std::cout << "[converting to string...] Row: " << row << ", column: " << col << ". Value: " << num2str(data[row][col]) << std::endl;
*/
// append each column of data in the row
// ATTENTION!!!
// Data element for correspondent position (row, col) is data[col][row]
bufferStr += num2str(data[col][row]) + "\t";
}
bufferStr += '\n'; // end of each line
}
bufferStr += boldLine + '\n';
} // Done & debugged & tested
void FormatOutput::data2str(int mode) {
if( mode == 1 ) {
this->clearDataStr();
int maxCol = this->dataSizeN[1];
int maxRow = this->dataSizeN[0];
std::string &bufferStr = this->dataStr;
std::string boldLine(16*maxCol,'=');
std::string thinLine(16*maxCol,'-');
// print correspondent names in the first line
for(auto name : this->namesVec) {
this->dataStr = this->dataStr + name + "\t\t";
}
bufferStr += '\n';
// append data to the buffer string
for(int row=0; row<maxRow; ++row) {
// append each row of data
for(int col=0; col<maxCol; ++col) {
// append each column of data in the row
/***** For test: *****
* std::cout << "[converting to string...] Row: " << row << ", column: " << col << ". Value: " << num2str(data[row][col]) << std::endl;
*/
// ATTENTION!!!
// Data element for correspondent position (row, col) is data[col][row]
bufferStr += num2str(data[col][row]) + "\t";
}
bufferStr += '\n';
}
}
else if( mode == 0 ) {
this->data2str();
}
} // Done & tested
void FormatOutput::clearDataStr(){
// clear the data buffered in "dataStr"
this->dataStr = "";
} // Done & tested
#endif | true |
5168786a51742b2159c568996b5ef4e0ca8ffb8e | C++ | Sookmyung-Algos/2021algos | /algos_assignment/2nd_grade/최예헌_honi/week4/11650.cpp | UTF-8 | 484 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
struct num{
int x;
int y;
}v[100000];
bool compare(struct num a,struct num b){
if (a.x==b.x)
return a.y<b.y;
return a.x<b.x;
}
int main(){
cin.tie(0); cout.tie(0);
ios_base::sync_with_stdio(false);
int N;
cin>>N;
for (int i=0;i<N;i++)
{
cin>>v[i].x>>v[i].y;
}
sort(v,v+N,compare);
for (int i=0;i<N;i++)
cout<<v[i].x<<' '<<v[i].y<<'\n';
}
| true |
bc2a9386d069c482f559d3def14dac21cfce3a72 | C++ | boredomed/PhysicsEngine | /main.cpp | UTF-8 | 2,265 | 2.625 | 3 | [] | no_license | #include "SmartGL.h"
#include "Colors.h"
#include "Projectile.h"
#include "Momentum.h"
#include "Header.h"
#include "Fahad.h"
//MENU of simulations
class Simulations
: public Activity
{
ImageView background;
ImageView sim1, sim2, sim3, sim4;
Button Simulation1, Simulation2, Simulation3, Simulation4;
public:
Simulations()
: Simulation1("", 20, 310, 370, 270, Cyan)
, Simulation2("", 20, 20, 370, 270, VeryLightPurple)
, Simulation3("", 410, 310, 370, 270, Blue_Clr)
, Simulation4("", 410, 20, 370, 270, BlueViolet)
{
background.loadFromFile("sim.jpg");
sim1.loadFromFile("angrybird.jpg");
sim2.loadFromFile("Momentum.png");
sim3.loadFromFile("eelec.jpg");
sim4.loadFromFile("race.jpg");
Simulation1.setImage(&sim1);
Simulation2.setImage(&sim2);
Simulation3.setImage(&sim3);
Simulation4.setImage(&sim4);
}
void Display() const
{
glClear(GL_COLOR_BUFFER_BIT);
background.Display();
Simulation1.Display();
Simulation2.Display();
Simulation3.Display();
Simulation4.Display();
gout.setPosition(200, 5);
gout.setFont(GLUT_BITMAP_9_BY_15);
gout.setLineWidth(200);
}
void MouseEvents(int& button, int& state, int& x, int& y) //Selection of simulation
{
// ImageButton.isClicked(x - width/2, y + height/2)
if (Simulation1.isClicked(x - 185, y + 135))
{
mActivityManager->setActive("Projectile");
}
else if (Simulation2.isClicked(x - 185, y + 135))
{
mActivityManager->setActive("Momentum");
}
else if (Simulation3.isClicked(x - 185, y + 135))
{
mActivityManager->setActive("Mathh");
}
else if (Simulation4.isClicked(x - 185, y + 135))
{
mActivityManager->setActive("Fahad");
}
}
};
int gWidth = 800, gHeight = 600;
int main()
{
SmartGL app(gWidth, gHeight, "Virtual Simulations");
mActivityManager->addActivity(new Simulations(), "Activity2");
mActivityManager->addActivity(new ProjectileSimulation(), "Projectile");
mActivityManager->addActivity(new momentum(), "Momentum");
mActivityManager->addActivity(new mathh(), "Mathh");
mActivityManager->addActivity(new fahad(), "Fahad");
mActivityManager->setActive("Activity2");
app.startProgram();
} | true |
f5a0f12550f5fe1695336ce2f7c62ac149b2c025 | C++ | mr-d-self-driving/HuskyControl | /husky_mpcc/src/types.h | UTF-8 | 2,633 | 2.625 | 3 | [] | no_license | // Define States of Husky
#ifndef MPCC_TYPES_H
#define MPCC_TYPES_H
#include "config.h"
namespace mpcc{
struct State{
double X;
double Y;
double th; // theta
double v; // linear velocity in x
double w; // angular velocity in z
double s;
double vs;
void setZero()
{
X = 0.0;
Y = 0.0;
th = 0.0;
v = 0.0;
w = 0.0;
s = 0.0;
vs = 0.0;
}
void set(double X, double Y, double th, double v, double w, double s, double vs)
{
this->X = X;
this->Y = Y;
this->th = th;
this->v = v;
this->w = w;
this->s = s;
this->vs = vs;
}
// Fix angle issues when near -180 and 180 deg
// Also allows restarting of lap
void unwrap(double track_length)
{
if (th > M_PI)
th -= 2.0 * M_PI;
if (th < -M_PI)
th += 2.0 * M_PI;
if (s > track_length)
s -= track_length;
if (s < 0)
s += track_length;
}
};
struct Input{
double dV;
double dW;
double dVs;
void setZero()
{
dV = 0.0;
dW = 0.0;
dVs = 0.0;
}
};
struct PathToJson{
const std::string param_path;
const std::string cost_path;
const std::string bounds_path;
const std::string track_path;
const std::string normalization_path;
};
typedef Eigen::Matrix<double,NX,1> StateVector;
typedef Eigen::Matrix<double,NU,1> InputVector;
typedef Eigen::Matrix<double,NX,NX> A_MPC;
typedef Eigen::Matrix<double,NX,NU> B_MPC;
typedef Eigen::Matrix<double,NX,1> g_MPC;
typedef Eigen::Matrix<double,NX,NX> Q_MPC;
typedef Eigen::Matrix<double,NU,NU> R_MPC;
typedef Eigen::Matrix<double,NX,NU> S_MPC;
typedef Eigen::Matrix<double,NX,1> q_MPC;
typedef Eigen::Matrix<double,NU,1> r_MPC;
typedef Eigen::Matrix<double,NPC,NX> C_MPC;
typedef Eigen::Matrix<double,1,NX> C_i_MPC;
typedef Eigen::Matrix<double,NPC,NU> D_MPC;
typedef Eigen::Matrix<double,NPC,1> d_MPC;
typedef Eigen::Matrix<double,NS,NS> Z_MPC;
typedef Eigen::Matrix<double,NS,1> z_MPC;
typedef Eigen::Matrix<double,NX,NX> TX_MPC;
typedef Eigen::Matrix<double,NU,NU> TU_MPC;
typedef Eigen::Matrix<double,NS,NS> TS_MPC;
typedef Eigen::Matrix<double,NX,1> Bounds_x;
typedef Eigen::Matrix<double,NU,1> Bounds_u;
typedef Eigen::Matrix<double,NS,1> Bounds_s;
StateVector stateToVector(const State &x);
InputVector inputToVector(const Input &u);
State vectorToState(const StateVector &xk);
Input vectorToInput(const InputVector &uk);
State arrayToState(double *xk);
Input arrayToInput(double *uk);
}
#endif //MPCC_TYPES_H
| true |
b1979b107deeb8c6af9679a3a4cd9ff1bfc0b39a | C++ | krishauser/KrisLibrary | /planning/KinodynamicPath.h | UTF-8 | 4,339 | 2.796875 | 3 | [] | permissive | #ifndef KINODYNAMIC_PATH_H
#define KINODYNAMIC_PATH_H
#include "EdgePlanner.h"
class KinodynamicSpace;
class ControlSpace;
class SteeringFunction;
typedef Vector State;
typedef Vector ControlInput;
/** @brief Stores a kinodynamic path with piecewise constant controls
*
* Must satisfy the property that milestones[i+1] = f(milestones[i],controls[i]), and the
* simulation trace is stored in paths[i]. Optionally, edges[i] can store
* the trajectory checker.
*
* The Duration and *Time* methods assume there's some state variable that indexes
* time. This variable must be monotonically nondecreasing along the path.
* by default it is element 0, which is compatible with all the SpaceTime* spaces in
* TimeCSpace.h
*/
class KinodynamicMilestonePath : public Interpolator
{
public:
KinodynamicMilestonePath();
KinodynamicMilestonePath(const ControlInput& u,const InterpolatorPtr& path);
virtual const Config& Start() const { return milestones.front(); }
virtual const Config& End() const { return milestones.back(); }
virtual void Eval(Real u,Config& q) const { Eval2(u,q); }
virtual Real Length() const;
bool Empty() const;
bool IsConstant() const;
CSpace* Space() const;
inline int NumMilestones() const { return milestones.size(); }
inline const Config& GetMilestone(int i) const { return milestones[i]; }
void Clear();
///Given milestones and controls, creates the paths and path checkers
void SimulateFromControls(KinodynamicSpace* space);
///Given existing milestones and controls, creates the paths
void MakePaths(ControlSpace* space);
void MakePaths(KinodynamicSpace* space);
///Given existing milestones, controls, and (optionally) paths, creates the path checkers.
///If paths are not filled out, SimulateFromControls is called.
void MakeEdges(KinodynamicSpace* space);
void Append(const ControlInput& u,KinodynamicSpace* space);
void Append(const ControlInput& u,const InterpolatorPtr& path,KinodynamicSpace* space);
void Append(const ControlInput& u,const InterpolatorPtr& path,const EdgePlannerPtr& e);
void Concat(const KinodynamicMilestonePath& suffix);
bool IsValid() const;
bool IsFeasible();
//evaluates the state, given path parameter [0,1]. Returns the edge index
int Eval2(Real u,Config& q) const;
///For timed path, returns the start time.
Real StartTime(int timeindex=0) const { return Start()[timeindex]; }
///For timed path, returns the end time.
Real EndTime(int timeindex=0) const { return End()[timeindex]; }
///For timed path, returns the duration of the known path
Real Duration(int timeIndex=0) const { return milestones.back()[timeIndex] - milestones.front()[timeIndex]; }
//evaluates the state at time t. Returns the edge index
int EvalTime(Real t,Config& q,int timeIndex=0) const;
//splits the path at time t. Note: Assumes u(timeIndex) is equal to dt!
void SplitTime(Real t,KinodynamicMilestonePath& before,KinodynamicMilestonePath& after,int timeIndex=0) const;
//ensures that the time is monotonically increasing
bool IsValidTime(int timeIndex=0) const;
/// Tries to shorten the path by connecting subsequent milestones.
/// Returns # of shortcuts made. The steering function must be exact!
int Shortcut(KinodynamicSpace* space,SteeringFunction* fn);
/// Tries to shorten the path by connecting random points
/// with a shortcut, for numIters iterations. Returns # of shortcuts
/// The steering function must be exact!
int Reduce(KinodynamicSpace* space,SteeringFunction* fn,int numIters);
/// Replaces the section of the path between parameters u1 and u2
/// with a new path. If u1 < 0 or u2 > Length(),
/// erases the corresponding start/goal milestones too.
/// If the edges of this path are made, the space needs to be passed in
/// in the 4th argument.
void Splice(Real u1,Real u2,const KinodynamicMilestonePath& path,KinodynamicSpace* space=NULL);
/// Replaces the section of the path between milestones
/// start and goal with a new path. If the index is negative,
/// erases the corresponding start/goal milestones too.
void Splice2(int start,int goal,const KinodynamicMilestonePath& path);
std::vector<State> milestones;
std::vector<ControlInput> controls;
std::vector<InterpolatorPtr> paths;
std::vector<EdgePlannerPtr> edges;
};
#endif
| true |
b12a7c3d873c84019334b915fb93939111938f02 | C++ | Gavinxyj/Algorithm | /algorithm.cpp | GB18030 | 8,410 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include<deque>
#include<math.h>
#include "algorithm.h"
template<class T>
Algorithm<T>::Algorithm()
{
}
template<class T>
Algorithm<T>::~Algorithm()
{
}
template<class T>
void Algorithm<T>::bubbleSort(T *array, int nLen, int (*fCompare)(const T *, const T *))
{
if(0 == *array || 0 == nLen) return;
bool bFlag = true; //ֱ˳ѭ
for(int nLoop = 0; nLoop < nLen -1; nLoop ++)
{
for(int index = 0; index < nLen - 1 - nLoop; index ++)
{
if(fCompare(&array[index], &array[index + 1]) > 0)
{
T temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
bFlag = false;
}
}
if(bFlag) break;
}
}
template<class T>
void Algorithm<T>::selectionSort(T *array, int length, int (*fCompare)(const T *, const T *))
{
if(0 == *array || 0 == length) return;
for(int nLoop = 0; nLoop < length - 1; nLoop ++)
{
int minKey = nLoop;
for(int index = nLoop + 1; index < length; index ++)
{
if(fCompare(&array[minKey], &array[index]) > 0)
{
minKey = index;
}
}
if(minKey != nLoop)
{
T temp = array[minKey];
array[minKey] = array[nLoop];
array[nLoop] = temp;
}
}
}
template<class T>
void Algorithm<T>::quickSort(T *array, int nLow, int nHigh, int (*fCompare)(const T *, const T *))
{
if(0 == *array || nLow >= nHigh) return ;
int nFirst = nLow;
int nLast = nHigh;
T nKey = array[nFirst];//趨һkeyֵݣkeyֵСߣұ
while(nFirst < nLast)
{
//ұ߿ʼұkeyֵС,keyֵ±
while(nFirst < nLast && fCompare(&nKey, &array[nLast]) <= 0)
{
-- nLast;
}
//ѱkeyֵСԪظֵһԪ
array[nFirst] = array[nLast];
//߿ʼұkeykeyֵС±ƶ
while(nFirst < nLast && fCompare(&nKey, &array[nFirst]) >= 0)
{
++ nFirst;
}
//ѱkeyֵԪظֵһԪ
array[nLast] = array[nFirst];
}
array[nFirst] = nKey;
quickSort(array, nLow, nFirst - 1, fCompare);//Сkey
quickSort(array, nFirst + 1, nHigh, fCompare);//Դkey
}
template<class T>
void Algorithm<T>::insertSort(T *array, int nLength, int (*fCompare)(const T*, const T*))
{
if(0 == *array || nLength <= 0) return;
T temp;
int index = 0;
for(int nLoop = 1; nLoop < nLength; nLoop ++)
{
temp = array[nLoop];
for(index = nLoop; index > 0 && fCompare(&array[index - 1], &temp) > 0; index --)
{
array[index] = array[index -1];
}
array[index] = temp;
}
}
template<class T>
void Algorithm<T>::binaryInsertSort(T *array, int nLength, int (*fCompare)(const T*, const T*))
{
if(0 == *array || nLength <= 0) return;
for(int nLoop = 1; nLoop < nLength; nLoop ++)
{
T temp = array[nLoop];
int nLow = 0;
int nHigh = nLoop - 1;
while(nLow <= nHigh)
{
int nMid = (nLow + nHigh) / 2;
if(fCompare(&temp, &array[nMid]) > 0)
{
nLow = nMid + 1;
}
else
{
nHigh = nMid - 1;
}
}
for(int index = nLoop; index > nLow; index --)
{
array[index] = array[index - 1];
}
array[nLow] = temp;
}
}
template<class T>
void Algorithm<T>::shellSort(T *array, int nLength, int (*fCompare)(const T*, const T*))
{
if(0 == *array || nLength <= 0) return;
for(int nLoop = nLength / 2; nLoop >= 1; nLoop /= 2)
{
//ΪnLoopԪؽ
for(int index = nLoop; index < nLength; index ++)
{
for(int nSwapIndex = index - nLoop; nSwapIndex >= 0; nSwapIndex -= nLoop)
{
if(fCompare(&array[nSwapIndex], &array[index]) > 0)
{
T temp = array[nSwapIndex];
array[nSwapIndex] = array[index];
array[index] = temp;
}
}
}
}
}
template<class T>
void Algorithm<T>::mergeSort(T *array, T *tempArray, int nFirst, int nLast, int (*fCompare)(const T*, const T*))
{
if(0 == *array || (nFirst - nLast) > 0 || nFirst < 0 || nLast < 0 ) return;
int nMidIndex = 0;
if(nFirst < nLast)
{
nMidIndex = (nFirst + nLast) / 2;
mergeSort(array, tempArray, nFirst, nMidIndex, fCompare);//Էֽн
mergeSort(array, tempArray, nMidIndex + 1, nLast, fCompare);//Էֽұн
merge(array, tempArray, nFirst, nMidIndex, nLast, fCompare);//ϲ
}
}
template<class T>
void Algorithm<T>::merge(T *array, T *tempArray, int nFirst, int nMid, int nLast, int (*fCompare)(const T*, const T*))
{
int nStartIndex = nFirst;
int nMidIndex = nMid + 1;
int index = nFirst;
while(nStartIndex != nMid + 1 && nMidIndex != nLast + 1)
{
if(fCompare(&array[nStartIndex], &array[nMidIndex]) > 0)
{
tempArray[index ++] = array[nMidIndex ++];
}
else
{
tempArray[index ++] = array[nStartIndex ++];
}
}
while(nStartIndex != nMid + 1)
{
tempArray[index ++] = array[nStartIndex ++];
}
while(nMidIndex != nLast + 1)
{
tempArray[index ++] = array[nMidIndex ++];
}
for(nStartIndex = nFirst; nStartIndex <= nLast; nStartIndex ++)
{
array[nStartIndex] = tempArray[nStartIndex];
}
}
template<class T>
void Algorithm<T>::radixSort(T *array, int nLength)
{
if(0 == *array) return ;
//ҳеԪȷҪٴ
T max = 0;
for(int nLoop = 0; nLoop < nLength; nLoop ++)
{
if(array[nLoop] > max)
{
max = array[nLoop];
}
}
//ȡֵλ
int count = 0;
while(true)
{
if(max == 0) break;
max /= 10;
count ++;
}
//10ͰֱŸ,Ϊû0-9ɵ
std::deque<T> tempDeque[10];
for(int nLoop = 0; nLoop < count; nLoop ++)
{
for(int index = 0; index < nLength; index ++)
{
//λֱŵӦͰ
int nIndex = (array[index] / (int)pow(10, nLoop)) % 10;
tempDeque[nIndex].push_back(array[index]);
}
//ѴźݷŻصԭ
int nCount = 0;
for(int index = 0; index < 10; index ++)
{
while(!tempDeque[index].empty())
{
array[nCount ++] = tempDeque[index].front();
tempDeque[index].pop_front();
}
}
}
}
template<class T>
void Algorithm<T>::heapSort(T *array, int nLength, int (*fCompare)(const T*, const T*))
{
for(int nLoop = (nLength - 1) / 2 ; nLoop >= 0; nLoop --)
{
//ֻСڸڵ
int lChild = nLoop * 2 + 1;//ڵ
int rChild = lChild + 1;//ҽڵ
if(lChild == nLength - 1 && fCompare(&array[lChild], &array[nLoop]) <= 0)
{
swap(array[lChild], array[nLoop]);
}
//ʼ
adjustHeap(array, nLength - 1, nLoop, fCompare);
}
while(nLength > 0)
{
swap(array[nLength - 1], array[0]);
nLength --;
adjustHeap(array, nLength, 0, fCompare);
}
}
template<class T>
void Algorithm<T>::adjustHeap(T *array, int nLength, T element, int (*fCompare)(const T*, const T*))
{
int lChild = element * 2 + 1;//ڵ
int rChild = lChild + 1;//ҽڵ
while(rChild < nLength)
{
//ڵСҺӽڵĽڵ㲻Ҫ
if(fCompare(&array[element], &array[lChild]) < 0 && fCompare(&array[element], &array[rChild]) < 0) return;
//ȽȷĸС
if(fCompare(&array[lChild], &array[rChild]) <= 0)
{
swap(array[element], array[lChild]);
element = lChild;
}
else
{
swap(array[element], array[rChild]);
element = rChild;
}
lChild = element * 2 + 1;
rChild = lChild + 1;
}
}
template<class T>
void Algorithm<T>::swap(T &firstElement, T &secondElement)
{
T temp = firstElement;
firstElement = secondElement;
secondElement = temp;
} | true |
30c45baa9f6d1ddede940c6425a42de049c2dd14 | C++ | prasoon16081994/CP-algorithmic-programming-database | /Code/WorkspaceB/C++ Files/CF/Practice/500_a.cpp | UTF-8 | 796 | 2.609375 | 3 | [] | no_license | /*input
8 4
1 2 1 2 1 2 1
*/
#include <bits/stdc++.h>
using namespace std;
#define ReadFile freopen("E:/Shreyans/Documents/Coding Workspace/STDINPUT.txt","r",stdin);
#define BoostIO ios_base::sync_with_stdio(false)
#define pii pair<int,int>
#define f first
#define s second
#define mp make_pair
#define endl '\n'
typedef long long int ll;
//Created by Shreyans Sheth [bholagabbar]
int a[100000]={0};
bool visited[100000]={0};
bool BFS(int t)
{
queue<int> q;
q.push(1);
while(!q.empty())
{
int cv=q.front();
q.pop();
if(cv==t)
return 1;
if(!visited[cv])
{
visited[cv]=1;
q.push(cv+a[cv]);
}
}
return 0;
}
int main()
{
BoostIO;
//ReadFile;
int n,t,x;
cin>>n>>t;
for(int i=1;i<=n;i++)
{
cin>>x;
a[i]=x;
}
if(BFS(t))
cout<<"YES";
else
cout<<"NO";
return 0;
} | true |
609a29fc92ebb53d1f7227287096f5fbefc000ec | C++ | maxkidd/HonoursProject | /Classes/network_channel.h | UTF-8 | 1,436 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef _NETWORKCHANNEL_H_
#define _NETWORKCHANNEL_H_
#include <queue>
#include "network_message.h"
/**
Channel packet packs messages sent from the simulation layer
- Created from the connection packet
*/
class ChannelPacket
{
public:
// Serialize functions
template <typename Stream> bool Serialize(Stream& stream, MessageFactory* mf, int channels);
bool SerializeInternal(InStream& stream, MessageFactory* mf, int channels);
bool SerializeInternal(OStream& stream, MessageFactory* mf, int channels);
private:
friend class Channel;
std::vector<NMessage*> messages;
uint32_t numMessages = 0;
};
/**
Channel listener
- For callbacks about channel messages received
- Not fully implemented yet
*/
class ChannelListener
{
public:
virtual ~ChannelListener() {}
virtual void OnReceive(class Channel*) {}
};
/**
Channel
- Stores messages in a send and receive queue
- Receives packet data
- Generates channel packet for connection packets with messages in the send queue
*/
class Channel
{
public:
Channel(MessageFactory* mf);
~Channel() {}
void SendMsg(NMessage* message);
NMessage* ReceiveMsg();
int GetPacketData(ChannelPacket& data, int bitsFree);
void ProcessPacketData(const ChannelPacket& data);
void SetListener(ChannelListener * listener);
protected:
private:
ChannelListener* _listener;
std::queue<NMessage*> _recvQueue;
std::queue<NMessage*> _sendQueue;
MessageFactory* _mf;
};
#endif
| true |
f3ced3cb70d6da367e5a59f9c4a530b5914761b2 | C++ | Aman5613122/30-days-of-code | /Reverse vowels of a strting.cpp | UTF-8 | 936 | 3.296875 | 3 | [] | no_license | //leetcode questions
class Solution {
public:
string reverseVowels(string s) {
int i=0,l=s.size()-1;
char c[] = "aeiou";
bool ans=0;
while(i<l)
{
if(isVowel(s[i]) && isVowel(s[l]))
{
swap(s[i],s[l]);
l--;
i++;
}
else if(isVowel(s[i]) && !isVowel(s[l]))
{
l--;
}
else if(!isVowel(s[i]) && isVowel(s[l]))
{
i++;
}
else {
l--;
i++;
}
}
return s;
}
bool isVowel(char chr)
{
if(chr == 'a' || chr == 'e' || chr == 'i' || chr == 'o' || chr == 'u' || chr == 'A'
|| chr =='E' || chr == 'I' || chr == 'O' || chr == 'U')
{
return true;
}else{
return false;
}
}
};
| true |
c62d39d402f301c3b2aacf9655f796aeb684bf17 | C++ | Andre2205p/Program-Grafica | /AlocacaoDinamicaArray_a/AlocacaoDinamicaArray/main.cpp | IBM852 | 1,114 | 3.609375 | 4 | [] | no_license | #include <iostream>
void func(int* ponteiro){
*ponteiro = 10;
std::cout << "ponteiro: " << *ponteiro << "\n";
}
void init(int * ptr, int tamanho){
int x,y, temp;
int * origem = ptr; //ponteiro para guardar a posiao inicial do ponteiro ptr
for( x = 0; x < tamanho; x++){
std::cout << "Digite um numero: ";
std::cin >> temp;
*ptr = temp;
ptr++;
}
ptr = origem;
for(y = 0; y < tamanho; y++){
std::cout << "Ponteiro " << y << ":" << *ptr << "\n";
ptr++;
}
}
int main()
{
int* ptr = new int;
std::cout << "ptr endereco: " << *ptr << "\n";
std::cout << "ptr endereco: " << ptr << "\n";
* ptr = 5;
std::cout << "*ptr: " << *ptr << "\n";
func (ptr);
delete ptr;
std::cout << "ptr delete: " << *ptr << "\n";
std::cout << "ptr delete: " << ptr << "\n";
ptr = NULL;
//*********************************************
std::cout << "\n\nDigite o tamanho do vetor: ";
int size =0;
std::cin >> size;
int * d_Array = new int[size];
init(d_Array, size);
return 0;
}
| true |
75897aa93e7b7d5e8831c66fbce6142d168aaed0 | C++ | coderdamin/PAT-Basic-Level-Practise | /C++/1019.cpp | GB18030 | 2,529 | 3.375 | 3 | [] | no_license | //
// һλֲȫͬ4λȰ4ְǵٰǵݼȻõ1ּ2֣õһµ֡
// һֱظǺܿͣСֺڶ֮Ƶ6174ҲKaprekar
// 磬Ǵ6767ʼõ
// 7766 - 6677 = 1089
// 9810 - 0189 = 9621
// 9621 - 1269 = 8352
// 8532 - 2358 = 6174
// 7641 - 1467 = 6174
// ... ...
// ָ4λдʾڶĹ̡
//ʽ
// һ(0, 10000)ڵN
//ʽ
// N4λȫȣһN - N = 0000ÿһһֱ6174Ϊ֣ʽעÿְ4λʽ
//1
//6767
//1
//7766 - 6677 = 1089
//9810 - 0189 = 9621
//9621 - 1269 = 8352
//8532 - 2358 = 6174
//
//2
//2222
//2
//2222 - 2222 = 0000
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
void NumberToArray(int nNumber, char* acBuf);
int ArrayToNumber(char* acBuf, bool bDaoxu);
int main() {
int nNumber = 0;
char acNumber[5] = { 0 };
cin >> nNumber;
int nNumber2 = 0;
while (true) {
NumberToArray(nNumber, acNumber);
//0
for (int i = strlen(acNumber); i < 4; ++i) {
acNumber[i] = '0';
}
acNumber[4] = '\0';
sort(acNumber, &acNumber[4]);
nNumber = ArrayToNumber(acNumber, true);
nNumber2 = ArrayToNumber(acNumber, false);
cout << setfill('0') << setw(4) << nNumber << " - " << setfill('0') << setw(4) << nNumber2 << " = ";
nNumber -= nNumber2;
if (nNumber != 6174
&& nNumber != 0) {
cout << setfill('0') << setw(4) << nNumber << '\n';
}
else{
cout << setfill('0') << setw(4) << nNumber;
break;
}
}
cout << endl;
return 0;
}
//
void NumberToArray(int nNumber, char* acBuf) {
while (nNumber != 0) {
*(acBuf++) = '0' + (nNumber % 10);
nNumber /= 10;
}
}
int ArrayToNumber(char* acBuf, bool bDaoxu) {
int nNumber = 0;
int nIndex = (bDaoxu) ? strlen(acBuf) - 1 : 0;
while (nIndex >= 0 && acBuf[nIndex] != '\0') {
//while (nIndex >= 0 && nIndex < strlen(acBuf)) {
nNumber = nNumber * 10 + (acBuf[nIndex] - '0');
nIndex += (bDaoxu) ? -1 : 1;
}
return nNumber;
}
| true |
eac3723770e01b5c605386134627487fcaf5c216 | C++ | ddurio/ProMage2 | /Engine/Code/Engine/Input/InputSystem.hpp | UTF-8 | 903 | 2.53125 | 3 | [] | no_license | #pragma once
#include "Engine/Core/EngineCommon.hpp"
#include "Engine/Input/Keyboard.hpp"
#include "Engine/Input/XboxController.hpp"
constexpr int MAX_CONTROLLERS = 4;
class WindowContext;
enum MouseEvent : int;
class InputSystem {
public:
void Startup( WindowContext* windowContext = nullptr );
void Shutdown();
void BeginFrame();
void EndFrame();
bool HandleKeyPressed( unsigned char keyCode );
bool HandleKeyReleased( unsigned char keyCode );
bool HandleMouseButton( MouseEvent event, float scrollAmount = 0.f );
const KeyboardAndMouse& GetKeyboardAndMouse() const;
const XboxController& GetController( int controllerID ) const;
private:
KeyboardAndMouse m_keyboardAndMouse;
XboxController m_controllers[MAX_CONTROLLERS] = {
XboxController( 0 ),
XboxController( 1 ),
XboxController( 2 ),
XboxController( 3 )
};
};
| true |
fb7696146c24c9d80d47b628c9bc30608ec4ab4a | C++ | smileHorse/C- | /ThinkingInC++/RTTI/CheckedCast/CatchBadCast.cpp | UTF-8 | 419 | 3.140625 | 3 | [] | no_license | #include <typeinfo>
#include "Security.h"
using namespace std;
int main() {
Metal m;
Security& s = m;
try {
Investment& c = dynamic_cast<Investment&>(s);
cout << "It's an Investment" << endl;
} catch(bad_cast&) {
cout << "s is not an Investment type" << endl;
}
try {
Bond& b = dynamic_cast<Bond&>(s);
cout << "It's an Bond" << endl;
} catch(bad_cast&) {
cout << "It's not a Bond type" << endl;
}
} | true |
929409a919469b5fb25792ff2725427199fb5231 | C++ | thegamer1907/Code_Analysis | /contest/1542538730.cpp | UTF-8 | 713 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
char a = s[0];
char b = s[1];
int n;
string d;
vector < string > docs;
cin >> n;
bool check = 0;
for(int i = 0 ; i<n ; i++) {
cin >> d;
if(d == s) check = 1;
docs.push_back(d);
}
if(check) {
cout << "YES" << endl;
exit(0);
}
for(int i = 0 ; i<n ; i++) {
for(int j = 0 ; j<n ; j++) {
if(docs[i][1] == a and b == docs[j][0]) {
return cout << "YES" , 0;
}
}
}
cout << "NO" << endl;
}
| true |
9b8d912041ba9607ef3d5bf11499abccefe3f958 | C++ | PacktPublishing/Beginning-Cpp-Programming | /Chapter02/calc.cpp | UTF-8 | 1,376 | 3.765625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
using namespace std;
void usage()
{
cout << endl;
cout << "calc arg1 op arg2" << endl;
cout << " arg1 and arg2 are the arguments" << endl;
cout << " op is an operator, one of + - / or *" << endl;
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
usage();
return 1;
}
string opArg = argv[2];
if (opArg.length() > 1)
{
cout << endl << "operator should be a single character" << endl;
usage();
return 1;
}
char op = opArg.at(0);
// the following test is equally valid
// if (op == ',' || op == '.' || op < '+' || op > '/')
if (op == 44 || op == 46 || op < 42 || op > 47)
{
cout << endl << "operator not recognised" << endl;
usage();
return 1;
}
double arg1 = atof(argv[1]);
double arg2 = atof(argv[3]);
double result = 0;
switch (op)
{
case '+':
result = arg1 + arg2;
break;
case '-':
result = arg1 - arg2;
break;
case '*':
result = arg1 * arg2;
break;
case '/':
if (arg2 == 0)
{
cout << endl << "divide by zero!" << endl;
return 1;
}
else
{
result = arg1 / arg2;
}
break;
}
cout << endl;
cout << arg1 << " " << op << " " << arg2;
cout << " = " << result << endl;
return 0;
} | true |
59cebabc55480d24b695223afb66ae1abf85276b | C++ | andre-jeon/cpp_pt2 | /Lesson 7/doWhileLoop.cpp | UTF-8 | 287 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int x = 5;
// do this
do {
// decreasing the value of x by 1
cout << x-- << endl;
}
// while x exsists
while (x);
string z;
getline(cin, z);
return 0;
} | true |
e24824c4c4182fcd18682a7c6ee42786307098f8 | C++ | tiandongpo/C-BasicSkill | /10.关联容器/2.9建立int和string的pair 赋值给vector/建立int和string的pair 赋值给vector/建立int和string的pair赋值给ector.cpp | GB18030 | 448 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<utility>//ʹеpair
#include<vector>
#include<string>
using namespace std;
int main()
{
pair<string,int> sipr;
string str;
int ival;
vector< pair<string,int> >pvec;
cout<<"enter a string and an iterget(ctrl+z to end):"<<endl;
while(cin>>str>>ival)
{
sipr = make_pair(str,ival);//pair
pvec.push_back(sipr);//pair洢vector
}
system("pause");
return 0;
}
| true |
d0ab0d9f76a332a0acc9cc6c09f17fe196568d53 | C++ | cardiffman/alloc | /gclisp.cpp | UTF-8 | 12,833 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "alloc.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <climits>
using std::cout;
using std::endl;
element Eval(element in);
extern element NIL;
/*element C(element s_exp){
return car(s_exp);
}*/
element interp_function(element s_exp) {
return Eval(car(s_exp));
}
/*element A(element s_exp){
return cdr(s_exp);
}*/
element interp_lambda(element s_exp) {
return s_exp;
}
element interp_car(element s_exp){
return car(Eval(car(s_exp)));
//return C(Eval(C(s_exp)));
}
element interp_cdr(element s_exp){
return cdr(Eval(car(s_exp)));
//return A(Eval(C(s_exp)));
}
element interp_cons(element s_exp){
//element i=Eval(C(s_exp));
//element t=Eval(C(A(s_exp)));
element i=Eval(car(s_exp));
element t=Eval(car(cdr(s_exp)));
return cons(i, t);
}
element interp_if(element s_exp){
return Eval(car(cdr((Eval(car(s_exp))==NIL)?cdr(s_exp):s_exp)));
}
bool L(element i, element s){
//cout << "L:" << i << " vs. " << s ;
if (BoxIsInteger(i) && BoxIsInteger(s))
return !equal_data(i, s);
if (BoxIsDouble(i) && BoxIsDouble(s))
return !equal_data(i, s);
if (BoxIsDouble(i) && (BoxIsDouble(s) || BoxIsInteger(s))
|| BoxIsDouble(s) && (BoxIsDouble(i) || BoxIsInteger(i)))
{
double id = BoxIsDouble(i) ?i.num : IntFromBox(i);
double sd = BoxIsDouble(s) ?s.num : IntFromBox(s);
return id != sd;
}
if (BoxIsDouble(i)||BoxIsInteger(i)||BoxIsDouble(s)||BoxIsInteger(s))
{
cout << __FUNCTION__ << " NEVER EVER " << i << ' '<< s <<endl;
}
bool r = !equal_data(i, s);
//cout << " -> " << r << endl;
return r;
}
element interp_equal(element s_exp){
return L(Eval(car(s_exp)),Eval(car(cdr(s_exp))))?NIL:symbol_create("t");
}
element interp_less(element s_exp){
element left = Eval(car(s_exp));
element right = Eval(car(cdr(s_exp)));
bool lt = false;
if (BoxIsInteger(left) && BoxIsInteger(right))
lt = IntFromBox(left) <IntFromBox(right);
if (BoxIsInteger(left) && !isnan(right.num))
lt = IntFromBox(left) < right.num;
else if (!isnan(left.num) && BoxIsInteger(right))
lt = left.num < IntFromBox(right);
else if (!isnan(left.num) && !isnan(right.num))
lt = left.num < right.num;
return lt ? symbol_create("t"):NIL;
}
element interp_add(element s_exp){
element left = Eval(car(s_exp));
element right = Eval(car(cdr(s_exp)));
if (BoxIsInteger(left) && BoxIsInteger(right))
return BoxFromInt(IntFromBox(left)+IntFromBox(right));
double d;
element r;
if (BoxIsInteger(left) && !isnan(right.num))
d = IntFromBox(left) + right.num;
else if (!isnan(left.num) && BoxIsInteger(right))
d = left.num + IntFromBox(right);
else if (!isnan(left.num) && !isnan(right.num))
d = left.num + right.num;
else
return NIL;
r.num = d;
return r;
}
element interp_sub(element s_exp){
element left = Eval(car(s_exp));
element right = Eval(car(cdr(s_exp)));
if (BoxIsInteger(left) && BoxIsInteger(right))
return BoxFromInt(IntFromBox(left)-IntFromBox(right));
double d;
element r;
if (BoxIsInteger(left) && !isnan(right.num))
d = IntFromBox(left) - right.num;
else if (!isnan(left.num) && BoxIsInteger(right))
d = left.num - IntFromBox(right);
else if (!isnan(left.num) && !isnan(right.num))
d = left.num - right.num;
else
return NIL;
r.num = d;
return r;
}
element interp_mul(element s_exp){
element left = Eval(car(s_exp));
element right = Eval(car(cdr(s_exp)));
if (BoxIsInteger(left) && BoxIsInteger(right))
return BoxFromInt(IntFromBox(left)*IntFromBox(right));
double d;
element r;
if (BoxIsInteger(left) && !isnan(right.num))
d = IntFromBox(left) * right.num;
else if (!isnan(left.num) && BoxIsInteger(right))
d = left.num * IntFromBox(right);
else if (!isnan(left.num) && !isnan(right.num))
d = left.num * right.num;
else
return NIL;
r.num = d;
return r;
}
element table;
bool builtins_loaded = false;
void enter(element n, element v)
{
Rooter n_r(n);
Rooter v_r(v);
table = array_append_element(table, cons(n, v));
}
void enter(element n, element (*f)(element))
{
Rooter n_r(n);
table = array_append_element(table, cons(n, BoxFromBuiltIn(f)));
}
element find(element n)
{
for (int i=IntFromBox(array_get_size(table)); i>0; --i)
{
element pair = array_get_element(table, BoxFromInt(i-1));
//cout << __FUNCTION__ << " n " << n << " vs. " << pair << " :" <<__FILE__<<':'<<__LINE__<<endl;
element ifirst = car(pair);
if (ifirst == n)
return cdr(pair);
}
return NIL;
}
element defun(element s_exp){
element e=cdr(s_exp);
element n=car(s_exp);
std::cout << "Entering e "<<e<<" n "<<n <<std::endl;
enter(n,e);
return n;
}
struct bi { const char* name; element (*fn)(element); };
bi builtins[] = {
"function", interp_function,
"quote", car,
"lambda", interp_lambda,
"defun", defun,
"if", interp_if,
"equal", interp_equal,
"<" , interp_less,
"+", interp_add,
"-", interp_sub,
"*", interp_mul,
"car", interp_car,
"cdr", interp_cdr,
"cons", interp_cons,
0,0
};
void setup()
{
if (!builtins_loaded) {
builtins_loaded = true;
table = array_create();
gc_add_root(&table); // This is permanent by the way.
for (bi* b=builtins; b->name!=0; ++b) {
enter(symbol_create(b->name), b->fn);
}
enter(symbol_create("t"),symbol_create("t"));
cout << table << endl;
cout << __FUNCTION__ << ' ' << "Built-ins installed" << " :" << __FILE__ << ':' << __LINE__ << endl;
}
}
void check_setup()
{
for (int i=IntFromBox(array_get_size(table)); i>0; --i)
{
element pair = array_get_element(table, BoxFromInt(i-1));
if (!BoxIsList(pair))
{
cout << __FUNCTION__ << " Element " << i << " of the environment is not a pair :" <<__FILE__<<':'<<__LINE__<<endl;
throw "bad setup";
}
//cout << __FUNCTION__ << " n " << n << " vs. " << pair << " :" <<__FILE__<<':'<<__LINE__<<endl;
element name = car(pair);
if (!BoxIsSymbol(name))
{
cout << __FUNCTION__ << " Element " << i << " car is not a symbol :" <<__FILE__<<':'<<__LINE__<<endl;
throw "bad setup";
}
// The names in the environment cannot be limited to a particular type.
}
}
element Eval(element in)
{
//Rooter in_r(in);
setup();
//check_setup();
cout << "eval |" << in << '|' << endl;
if (BoxIsInteger(in))
return in;
if (!isnan(in.num))
return in;
if (in == NIL)
return in;
#if 1
if (BoxIsSymbol(in)) {
element x = find(in);
if (BoxIsBuiltin(x))
return in;
if (x == NIL)
cout << __FUNCTION__ << " Lookup of " << in << " returned "<< x << " " << __FILE__ << ':' << __LINE__ <<endl;
return x;
}
#endif
if (!BoxIsList(in))
return in;
//std::cout << "Is List "<< in << std::endl;
//std::cout << "car: " << car(in) << std::endl;
//std::cout << "cdr: " << cdr(in) << std::endl;
element op = car(in);
if (BoxIsList(op))
op = Eval(op);
//std::cout << "after refinement "<< op << std::endl;
element x = find(op);
Rooter x_r(x);
if (BoxIsBuiltin(x))
{
Builtin f = BuiltinFromBox(x);
element r = f(cdr(in));
cout << __FUNCTION__ << " Result of built-in function " << r << " " << __FILE__ << ':' << __LINE__ <<endl;
return r;
}
element lambda = x;
Rooter lambda_r(lambda);
element formals = car(lambda);
Rooter formals_r(formals);
element actuals = cdr(in);
Rooter actuals_r(actuals);
//cout << "About to eval to environment" << endl;
element top = array_get_size(table);
while (formals != NIL && actuals != NIL) {
element formal = car(formals);
Rooter formal_r(formal);
element actual = Eval(car(actuals));
//cout << "Entering "<< formal << " " << actual << endl;
Rooter actual_r(actual);
enter(formal, actual);
formals = cdr(formals);
actuals = cdr(actuals);
}
//cout <<"Body image: lambda " << lambda << endl; cout <<" cdr(lambda) " << cdr(lambda) << endl; cout <<" car(cdr(lambda)) "<< car(cdr(lambda)) << endl;
element body = car(cdr(lambda));
//std::cout << "Evaluating "<< body <<" with the following:"<<std::endl;
//for (int i=top; i<table.size(); ++i) {
// std::cout << table[i].first << " " << table[i].second.get() << std::endl;
//}
element rv = Eval(body);
table=array_set_size(table, top);
//cout << "Result is " << rv << endl;
return rv;
}
static element atom;
void chartoatom(int ch)
{
string_append_char(atom, BoxFromInt(ch));
}
int peek_char(FILE* fp)
{
int ch = getc(fp);
ungetc(ch, fp);
return ch;
}
int check_delim(FILE* fp)
{
int ch = peek_char(fp);
if (!isspace(ch) && ch!='('&&ch!=')'&&ch!=';'&&ch!='"')
{
fprintf(stderr,"Improper delimiter for literal\n");
return 0;
}
return 1;
}
int skip_white(FILE* fp)
{
int ch;
eat_space:
for (ch=getc(fp); isspace(ch); ch=getc(fp))
;
if (ch==';')
{
while (ch != '\n' && ch!=EOF)
ch = getc(fp);
goto eat_space;
}
return ch;
}
element read_obj(FILE* fp);
element read_pair(FILE* fp)
{
int ch;
element car_obj;
element cdr_obj=NIL;
ch = skip_white(fp);
if (ch==')')
return NIL;
ungetc(ch, fp);
car_obj = read_obj(fp);
ch = skip_white(fp);
if (ch == '.')
{
//printf("read_pair %d\n", __LINE__);
cdr_obj = read_pair(fp);
return cons(car_obj,cdr_obj);
}
else if (ch == ')')
return cons(car_obj,cdr_obj);
ungetc(ch, fp);
//printf("read_pair %d\n", __LINE__);
cdr_obj = read_pair(fp);
return cons(car_obj,cdr_obj);
}
element read_obj(FILE* fp)
{
int ch;
ch = skip_white(fp);
#if 0
if (ch=='#')
{
// some sort of literal
ch = getc(fp);
if (ch=='(') // vector
{
int* elements = 0;
int nElements = 0;
int nElementCapy = 0;
ch = skip_white(fp);
while (ch != ')')
{
ungetc(ch, fp);
int element = read_obj(fp);
if (nElements+1 > nElementCapy) {
if (nElementCapy==0)
nElementCapy = 8;
else
nElementCapy = 6*nElementCapy/5+1;
elements = (int*)realloc(elements, nElementCapy*sizeof(int));
}
elements[nElements++] = element;
ch = skip_white(fp);
}
elements = (int*)realloc(elements, (nElements*4+11)&~7);
memmove(elements+1,elements,nElements*4);
elements[0] = nElements;
return VECTOR+(int)elements;
}
if (ch=='\\') // character literal
{
ch = getc(fp);
if (!check_delim(fp))
{
fprintf(stderr,"Improper delimiter for literal\n");
return NIL;
}
return ch*256+CHAR_LITERAL;
}
if (ch=='t')
return TRUE_LITERAL;
if (ch=='f')
return FALSE_LITERAL;
return NIL;
}
#endif
if (ch=='(')
{
element elt = read_pair(fp);
cout << "read_pair returned " << elt << std::endl;
return elt;
}
if (ch=='"')
{
atom = newstr();
ch = getc(fp);
while (ch != '"')
{
if (ch == '\\')
chartoatom(getc(fp));
else
chartoatom(ch);
ch = getc(fp);
}
return atom;
}
atom = newstr();
for (; ch!=EOF&&!isspace(ch)&&ch!='('&&ch!=')'&&ch!='#'&&ch!=';'; ch=getc(fp))
{
chartoatom(ch);
}
ungetc(ch,fp);
std::ostringstream os; os << atom;
const char* ip = os.str().c_str();
char* tail=0;
long lval = strtol(ip, &tail, 10);
if (tail[0]==0 && tail != ip && lval<INT_MAX && lval>INT_MIN)
return BoxFromInt(lval);
double dval = strtod(ip, &tail);
if (tail[0]==0 && tail!= ip)
atom.num = dval;
return symbol_from_string(atom);
}
#include <cstring>
extern element* alloc;
int main(int argc, char** argv)
{
init_heap();
if (argc==2 && strcmp(argv[1], "-t")==0)
{
setup();
extern element symbols;
cout << symbols << endl;
cout << table << endl;
element n = symbol_create("n");
element nm1 = cons(symbol_create("-"), cons(n,cons(BoxFromInt(1),NIL)));
element fnm1 = cons(symbol_create("fact"), cons(nm1,NIL));
element times = cons(symbol_create("*"), cons(n, cons(fnm1,NIL)));
element one = BoxFromInt(1);
element test = cons(symbol_create("equal"), cons(n, cons(BoxFromInt(0),NIL)));
element ifs = cons(symbol_create("if"), cons(test, cons(one, cons(times,NIL))));
element e = cons(symbol_create("defun"), cons(symbol_create("fact"), cons(cons(n,NIL),cons(ifs,NIL))));
cout << "Test expr " << e << endl;
element e2 = cons(symbol_create("fact"), cons(BoxFromDouble(50.0), NIL));
cout << "Test expr " << e2 << endl;
cout << Eval(e) << endl;
cout << Eval(e2) << endl;
return 0;
}
while (!feof(stdin))
{
cout << '[' << alloc << ']' << "> " << std::flush;
element e = read_obj(stdin);
cout << __FUNCTION__ << " The s-expr: " << e << endl;
element r = Eval(e);
cout << __FUNCTION__ << " Its value: " << r << endl;
cout << endl;
dump_heap();
}
return 0;
}
| true |
68733ef6fff02a958412f9cdf46520dd9da32a6d | C++ | Alexbeast-CN/Notes2Cpp | /Notes/Functions/examples/arrfun1.cpp | UTF-8 | 625 | 4.03125 | 4 | [] | no_license | // arrfun1.cpp -- functions with an array argument
#include <iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n); //prototype
int main(int argc, char const *argv[])
{
using namespace std;
int cookies[ArSize];
cout << "Please enter 8 numbers" << endl;
for (int i = 0; i < 8; i++)
cin >> cookies[i];
int sum = sum_arr(cookies, ArSize);
cout << "Total cookies eaten: " << sum << endl;
return 0;
}
// return the sum of an integer array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i <n; i++)
total = total + arr[i];
return total;
} | true |
803c443197533851648ca96c96a7588feaf82528 | C++ | andrezszambrano/Taller1TP2 | /ControlaArchivo.cpp | UTF-8 | 3,803 | 2.65625 | 3 | [] | no_license | #include "ControlaArchivo.h"
#include "ManejaParticiones.h"
#include <iostream>
#include <utility>
#include <stdint.h>
#include <arpa/inet.h>
#include <cstdio>
#define ARCHIVO_INEXISTENTE -2
#define DOS_BYTES 2
#define UN_BYTE 1
#define CERO_BYTES 0
#define MAX_COLUMNAS 10
#define ERROR -1
#define EXITO 0
#define FIN_DEL_ARCHIVO 1
#define PARTICION_PARCIAL_VALIDA 2
#define PARTICION_INVALIDA 3
//--------------------CLASE ARCHIVO----------------------------------//
Archivo::Archivo(const char* path_al_archivo) {
this->ptr_archivo = fopen(path_al_archivo, "rb");
if (!ptr_archivo)
throw std::runtime_error("Error: el archivo no existe.");
}
Archivo::Archivo(Archivo&& otro_archivo) {
this->ptr_archivo = otro_archivo.ptr_archivo;
otro_archivo.ptr_archivo = nullptr;
}
Archivo& Archivo::operator=(const Archivo& otro_archivo) { //CppLink se quejaba
if (this != &otro_archivo) { //si no estaba
this->ptr_archivo = otro_archivo.ptr_archivo; //esta función
}
return *this;
}
int Archivo::leerNBytes(char* buf, int cant_bytes) {
return fread(buf, 1, cant_bytes, this->ptr_archivo);
}
int Archivo::setearOffset(int offset) {
return std::fseek(this->ptr_archivo, offset, SEEK_SET);
}
Archivo::~Archivo() {
if (ptr_archivo)
fclose(this->ptr_archivo);
}
//--------------------CLASE ARCHIVO----------------------------------//
//-----------------CLASE CONTROLA_ARCHIVO---------------------------//
ControlaArchivo::ControlaArchivo(const char* path_al_archivo, int nro_columnas)
:archivo(path_al_archivo), nro_columnas(nro_columnas),
path_al_archivo(path_al_archivo) {
}
ControlaArchivo::ControlaArchivo(ControlaArchivo&& otroControlador)
:archivo(std::move(otroControlador.archivo)),
nro_columnas(otroControlador.nro_columnas),
path_al_archivo(otroControlador.path_al_archivo) {
}
int ControlaArchivo::cargarFila(Fila& fila) {
for (int i = 0; i < this->nro_columnas; i++){
uint16_t numBE;
int aux = this->archivo.leerNBytes(reinterpret_cast<char*>
(&numBE),
sizeof(numBE));
if (aux == UN_BYTE)
throw std::runtime_error("Error: cada número debe estar compuesto "
"por dos bytes. Revise su dataset.");
else if (aux == CERO_BYTES && i > 0)
throw std::runtime_error("Error: La cantidad de números totales en "
"el dataset no es múltiplo de la cantidad "
"de columnas pedidas.");
else if (aux == CERO_BYTES)
return FIN_DEL_ARCHIVO;
uint16_t num = ntohs(numBE);
fila.aniadirNumero(num);
}
return EXITO;
}
void ControlaArchivo::cargarFilasSegunInfo(std::list<Fila>& filas,
const InfoParticion& info) {
int offset_inicial = info.nro_indice_inicial*this->nro_columnas*DOS_BYTES;
this->archivo.setearOffset(offset_inicial);
cargarHastaNFilas(filas, info.nro_indice_final -
info.nro_indice_inicial);
}
void ControlaArchivo::cargarHastaNFilas(std::list<Fila>& filas,
int cant_filas_a_cargar) {
int filas_cargadas = 0;
while (filas_cargadas < cant_filas_a_cargar){
Fila fila_aux;
int aux = this->cargarFila(fila_aux);
if (aux == FIN_DEL_ARCHIVO)
return;
filas.push_back(std::move(fila_aux));
filas_cargadas++;
}
}
ControlaArchivo::~ControlaArchivo(){
}
//-----------------CLASE CONTROLA_ARCHIVO---------------------------//
| true |
b13e142846487f040c6873092f9fb7ca799b5028 | C++ | Zandriy/NeHe_SDL | /src/Sample_03.h | UTF-8 | 601 | 2.640625 | 3 | [] | no_license | /*
* Sample_03.h
*
* Created on: Feb 21, 2013
* Author: Andrew Zhabura
*/
#ifndef Sample_03_H_
#define Sample_03_H_
#include "Sample.h"
class Sample_03 : public Sample
{
enum classConsts {
INIT_W = 640,
INIT_H = 480
};
public:
Sample_03();
virtual ~Sample_03();
virtual void reshape(int width, int height);
virtual const char* name() const
{
return "03. Color";
}
virtual int width() const
{
return INIT_W;
}
virtual int height() const
{
return INIT_H;
}
protected:
virtual void draw();
virtual void initGL();
virtual void restoreGL();
};
#endif /* Sample_03_H_ */
| true |
abd8d9212fb62efb3728696471952de9038baae0 | C++ | yeppymp/learn-cpp | /pyramid_if.cpp | UTF-8 | 912 | 2.984375 | 3 | [] | no_license | #include<iostream>
using namespace std;
main() {
int i, first_number;
for ( i = 5; i >= 1; i--) {
if (i == 5) {
for ( first_number = 1; first_number <= 5; first_number++ ) {
cout << i;
}
cout << endl;
} else if (i == 4) {
for ( first_number = 1; first_number <= 4; first_number++ ) {
cout << i;
}
cout << endl;
} else if (i == 3) {
for ( first_number = 1; first_number <= 3; first_number++ ) {
cout << i;
}
cout << endl;
} else if (i == 2) {
for ( first_number = 1; first_number <= 2; first_number++ ) {
cout << i;
}
cout << endl;
} else {
for ( first_number = 1; first_number <= 1; first_number++ ) {
cout << i;
}
cout << endl;
}
}
}
| true |
64bde189b9b333b988322d996f09ad33ae1cd638 | C++ | JordyLimaEng/computacao-grafica | /SDL2/Olá Mundo.cpp | ISO-8859-1 | 809 | 2.90625 | 3 | [] | no_license | #include <SDL2/SDL.h>
int main(int argc, char **argv)
{
//Inicializao
bool running = true;
//Gameloop
while(running)
{
///Logica
//Deteco de Evento
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT: //Caso saia
running = false;
break;
}
}
//Atualizaes gerais devem vir aqui
SDL_Window * window = SDL_CreateWindow("Hi mundo!", 100, 100, 800, 600, 0);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
///Rendering
SDL_SetRenderDrawColor(renderer, 127, 0, 127, 255);
SDL_Rect rect = {350, 250, 100, 100};
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);
//No v to rpido!
SDL_Delay(10); //Isso causa algo como 60 quadros por segundo.
}
}
| true |
65adab503a12a4fff6ac197c4c8cce3a319d55e8 | C++ | Gagerdude/raytracer | /models/RectangleXZ.h | UTF-8 | 635 | 2.5625 | 3 | [] | no_license | #ifndef RECTANGLEXZ_H
#define RECTANGLEXZ_H
#include "Model.h"
#include "Material.h"
#include "Ray.h"
#include "AxisAlignedBoundingBox.h"
class RectangleXZ: public Model{
public:
RectangleXZ();
RectangleXZ(double _x_min, double _x_max, double _z_min, double _z_max, double _y, Material* m);
~RectangleXZ();
virtual bool hit(const Ray& r, double t_min, double t_max, hit_record& rec) const;
virtual bool bounding_box(double time_start, double time_end, AxisAlignedBoundingBox& box) const;
private:
double x_min, x_max, z_min, z_max, y;
Material* material;
};
#endif | true |
a4c58512d998dede50f51daccf16703ce809ce2b | C++ | diable201/Algorithms_and_Data_Structures | /informatics_2/matrix.cpp | UTF-8 | 837 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int a[750][750];
int minimum[750], maximum[750];
int answer = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> a[i][j];
for (int i = 0; i < n; i++) {
minimum[i] = 1000;
for (int j = 0; j < m; j++)
if (a[i][j] < minimum[i])
minimum[i] = a[i][j];
}
for (int j = 0; j < m; j++) {
maximum[j] = -1000;
for (int i = 0; i < n; i++)
if (a[i][j] > maximum[j])
maximum[j] = a[i][j];
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if ((a[i][j] == minimum[i]) && (a[i][j] == maximum[j]))
answer++;
cout << answer << '\n';
return 0;
}
| true |
30d36ed7b2f62e4b3c14b44ddb15ba2e924f809d | C++ | AvengineersVex/TowerTakeover-Competition-Code | /src/selector.cpp | UTF-8 | 2,432 | 2.953125 | 3 | [] | no_license | /*Notes
alliance variable:
0 - red
1 - blue
2 - skills
auton variable:
0 - purple
1 - gold
*/
#include "vex.h"
using namespace vex;
extern brain Brain;
extern brain::lcd Screen;
void pressedCallback();
void detectAlliance(int xPosIn, int yPosIn);
void autonSlector();
int gOp(int xPosIn, int yPosIn);
int progress, alliance, auton;
int returnAutonSelection() {
return auton;
}
int returnAllianceSelection() {
return alliance;
}
void startUp() {
progress = 0;
Screen.pressed(pressedCallback);
Screen.setFont(prop40);
Screen.printAt(130, 50, "Alliance Color");
Screen.drawRectangle(100, 80, 100, 80, red);
Screen.drawRectangle(280, 80, 100, 80, blue);
Screen.drawRectangle(0, 180, 480, 50, green);
Screen.setFont(prop20);
Screen.printAt(210, 210, "Skills");
}
void pressedCallback() {
int xPos = Screen.xPosition();
int yPos = Screen.yPosition();
if (progress == 0) {
detectAlliance(xPos, yPos);
}
else if (progress == 2) {
printf("gOp activated\n");
auton = gOp(xPos, yPos);
}
}
void detectAlliance(int xPosIn, int yPosIn) {
if (100 < xPosIn && xPosIn < 200 && 80 < yPosIn && yPosIn < 160) { // Red Alliance
Screen.clearScreen();
progress++;
alliance = 0;
}
else if (280 < xPosIn && xPosIn < 380 && 80 < yPosIn && yPosIn < 160) { // Blue Alliance
Screen.clearScreen();
progress++;
alliance = 1;
}
else if (0 < xPosIn && xPosIn < 480 && 180 < yPosIn && yPosIn < 240) { // Skills
Screen.clearScreen();
progress++;
alliance = 2;
}
autonSlector();
}
void autonSlector() {
Screen.setFont(prop40);
if (alliance == 0) { // Red Alliance
Screen.printAt(110, 50, "Auton Selection");
Screen.drawRectangle(100, 80, 100, 80, purple);
Screen.drawRectangle(280, 80, 100, 80, yellow);
progress++;
}
else if (alliance == 1) { // Blue Alliance
Screen.printAt(110, 50, "Auton Selection");
Screen.drawRectangle(100, 80, 100, 80, purple);
Screen.drawRectangle(280, 80, 100, 80, yellow);
progress++;
}
}
int gOp(int xPosIn, int yPosIn) {
if (100 < xPosIn && xPosIn < 200 && 80 < yPosIn && yPosIn < 160) {
Screen.clearScreen();
return 0;
}
else if (280 < xPosIn && xPosIn < 380 && 80 < yPosIn && yPosIn < 160) {
Screen.clearScreen();
return 1;
}
return -1;
} | true |
02ce36ad739ac35797fe599711b13ce52f0ef7cc | C++ | weijiaming2012/Cpp | /6-7.cc | UTF-8 | 502 | 3.640625 | 4 | [] | no_license | #include<iostream>
using namespace std;
void newLine();
void getInt(int& number);
int main()
{
int n;
getInt(n);
cout<<"Final value read in = "<<n<<endl
<<"End of demonstration.\n";
return 0;
}
void newLine()
{
char symbol;
do{
cin.get(symbol);
}while(symbol!='\n');
}
void getInt(int& number)
{
char ans;
do{
cout<<"Enter input number:";
cin>>number;
cout<<"You entered "<<number
<<" Is that correct?(yes/no):";
cin>>ans;
newLine();
}while((ans!='Y')&&(ans!='y'));
}
| true |
1f37b21a87ff8a4c5b6da0b83963593f52514fdb | C++ | ia7ck/competitive-programming | /AtCoder/arc138/src/bin/a/main.cpp | UTF-8 | 1,068 | 2.515625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <tuple>
#include <algorithm>
#include "atcoder/segtree"
using namespace std;
#define REP(i, n) for (int (i) = 0; (i) < (int)(n); (i)++)
int op(int a, int b) {
return max(a, b);
}
int e() {
return -1;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
REP(i, n) {
scanf("%d", &a[i]);
}
vector<tuple<int, int>> b;
REP(i, k) {
b.emplace_back(a[i], i);
}
sort(b.begin(), b.end());
atcoder::segtree<int, op, e> seg_b(k);
REP(i, k) {
auto &[v, j] = b[i];
seg_b.set(i, j);
}
int inf = 1000000000;
auto ans = inf;
for (int i = k; i < n; i++) {
int j = lower_bound(b.begin(), b.end(), make_tuple(a[i], 0)) - b.begin();
if (j == 0) {
continue;
}
auto min_index = seg_b.prod(0, j);
assert(min_index < k);
ans = min(ans, (k - min_index - 1) + (i - k) + 1);
}
if (ans == inf) {
puts("-1");
} else {
printf("%d", ans);
}
}
| true |
589c189d8b35246ea3de1b931f168897e139b645 | C++ | jonnylagos115/CIS22C | /lab01_JL/Currency.cpp | UTF-8 | 3,313 | 3.484375 | 3 | [] | no_license | // Implementation file for the Currency class
#include "Currency.hpp"
#include <iostream>
std::istream& operator>> (std::istream &in, Currency* &curr)
{
std::string note_n, coin_n;
int note_v, coin_v;
in >> note_n >> note_v >> coin_v >> coin_n;
if (note_n == "Dollar")
{
curr = new Dollar(note_n, note_v, coin_v, coin_n);
}
else if (note_n == "Pound")
{
curr = new Pound(note_n, note_v, coin_v, coin_n);
}
else if (note_n == "Yen")
{
curr = new Yen(note_n, note_v, coin_v, coin_n);
}
else if (note_n == "Rupee")
{
curr = new Rupee(note_n, note_v, coin_v, coin_n);
}
else if (note_n == "Real")
{
curr = new Real(note_n, note_v, coin_v, coin_n);
}
return in;
}
Currency& Dollar::add(Dollar* d)
{
d->note_value = this->note_value + d->note_value;
d->coin_value = this->coin_value + d->coin_value;
if (d->coin_value >= 100)
{
d->coin_value -= 100;
d->note_value += 1;
}
return *this;
}
Currency& Pound::add(Pound* p)
{
p->note_value = this->note_value + p->note_value;
p->coin_value = this->coin_value + p->coin_value;
if (p->coin_value >= 100)
{
p->coin_value -= 100;
p->note_value += 1;
}
return *this;
}
Currency& Yen::add(Yen* y)
{
y->note_value = this->note_value + y->note_value;
y->coin_value = this->coin_value + y->coin_value;
if (y->coin_value >= 100)
{
y->coin_value -= 100;
y->note_value += 1;
}
return *this;
}
Currency& Rupee::add(Rupee* r)
{
r->note_value = this->note_value + r->note_value;
r->coin_value = this->coin_value + r->coin_value;
if (r->coin_value >= 100)
{
r->coin_value -= 100;
r->note_value += 1;
}
return *this;
}
Currency& Real::add(Real* real)
{
real->note_value = this->note_value + real->note_value;
real->coin_value = this->coin_value + real->coin_value;
if (real->coin_value >= 100)
{
real->coin_value -= 100;
real->note_value += 1;
}
return *this;
}
Currency& Dollar::subtract(Dollar *d)
{
d->note_value = d->note_value - this->note_value;
d->coin_value = d->coin_value - this->coin_value;
if (d->coin_value < 0)
{
d->coin_value += 100;
d->note_value -= 1;
}
return *this;
}
Currency& Pound::subtract(Pound *p)
{
p->note_value = p->note_value - this->note_value;
p->coin_value = p->coin_value - this->coin_value;
if (p->coin_value < 0)
{
p->coin_value += 100;
p->note_value -= 1;
}
return *this;
}
Currency& Yen::subtract(Yen* y)
{
y->note_value = y->note_value - this->note_value;
y->coin_value = y->coin_value - this->coin_value;
if (y->coin_value < 0)
{
y->coin_value += 100;
y->note_value -= 1;
}
return *this;
}
Currency& Rupee::subtract(Rupee* r)
{
r->note_value = r->note_value - this->note_value;
r->coin_value = r->coin_value - this->coin_value;
if (r->coin_value < 0)
{
r->coin_value += 100;
r->note_value -= 1;
}
return *this;
}
Currency& Real::subtract(Real* real)
{
real->note_value = real->note_value - this->note_value;
real->coin_value = real->coin_value - this->coin_value;
if (real->coin_value < 0)
{
real->coin_value += 100;
real->note_value -= 1;
}
return *this;
}
Currency&
std::ostream& operator<< (std::ostream &out, Currency* curr)
{
out << "Current total: " << curr->getNoteName() << " "
<< curr->getNoteValue() << " " << curr->getCoinValue() << " "
<< curr->getCoinName() << std::endl;
return out;
} | true |
3119d56ec989615ff6d0a17475ac06742520a7f8 | C++ | smeenai/llvm-project | /clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements.cpp | UTF-8 | 15,037 | 2.84375 | 3 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | // RUN: %check_clang_tidy %s readability-braces-around-statements %t
void do_something(const char *) {}
bool cond(const char *) {
return false;
}
#define EMPTY_MACRO
#define EMPTY_MACRO_FUN()
void test() {
if (cond("if0") /*comment*/) do_something("same-line");
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: statement should be inside braces
// CHECK-FIXES: if (cond("if0") /*comment*/) { do_something("same-line");
// CHECK-FIXES: }
if (cond("if0.1"))
do_something("single-line");
// CHECK-MESSAGES: :[[@LINE-2]]:21: warning: statement should be inside braces
// CHECK-FIXES: if (cond("if0.1")) {
// CHECK-FIXES: }
if (cond("if1") /*comment*/)
// some comment
do_something("if1");
// CHECK-MESSAGES: :[[@LINE-3]]:31: warning: statement should be inside braces
// CHECK-FIXES: if (cond("if1") /*comment*/) {
// CHECK-FIXES: }
if (cond("if2")) {
do_something("if2");
}
if (cond("if3"))
;
// CHECK-MESSAGES: :[[@LINE-2]]:19: warning: statement should be inside braces
// CHECK-FIXES: if (cond("if3")) {
// CHECK-FIXES: }
if (cond("if-else1"))
do_something("if-else1");
// CHECK-MESSAGES: :[[@LINE-2]]:24: warning: statement should be inside braces
// CHECK-FIXES: if (cond("if-else1")) {
// CHECK-FIXES: } else {
else
do_something("if-else1 else");
// CHECK-MESSAGES: :[[@LINE-2]]:7: warning: statement should be inside braces
// CHECK-FIXES: }
if (cond("if-else2")) {
do_something("if-else2");
} else {
do_something("if-else2 else");
}
if (cond("if-else if-else1"))
do_something("if");
// CHECK-MESSAGES: :[[@LINE-2]]:32: warning: statement should be inside braces
// CHECK-FIXES: } else if (cond("else if1")) {
else if (cond("else if1"))
do_something("else if");
// CHECK-MESSAGES: :[[@LINE-2]]:29: warning: statement should be inside braces
else
do_something("else");
// CHECK-MESSAGES: :[[@LINE-2]]:7: warning: statement should be inside braces
// CHECK-FIXES: }
if (cond("if-else if-else2")) {
do_something("if");
} else if (cond("else if2")) {
do_something("else if");
} else {
do_something("else");
}
for (;;)
do_something("for");
// CHECK-MESSAGES: :[[@LINE-2]]:11: warning: statement should be inside braces
// CHECK-FIXES: for (;;) {
// CHECK-FIXES-NEXT: do_something("for");
// CHECK-FIXES-NEXT: }
for (;;) {
do_something("for-ok");
}
for (;;)
;
// CHECK-MESSAGES: :[[@LINE-2]]:11: warning: statement should be inside braces
// CHECK-FIXES: for (;;) {
// CHECK-FIXES-NEXT: ;
// CHECK-FIXES-NEXT: }
int arr[4] = {1, 2, 3, 4};
for (int a : arr)
do_something("for-range");
// CHECK-MESSAGES: :[[@LINE-2]]:20: warning: statement should be inside braces
// CHECK-FIXES: for (int a : arr) {
// CHECK-FIXES-NEXT: do_something("for-range");
// CHECK-FIXES-NEXT: }
for (int &assign : arr)
assign = 7;
// CHECK-MESSAGES: :[[@LINE-2]]:26: warning: statement should be inside braces
// CHECK-FIXES: for (int &assign : arr) {
// CHECK-FIXES-NEXT: assign = 7;
// CHECK-FIXES-NEXT: }
for (int ok : arr) {
do_something("for-range");
}
for (int NullStmt : arr)
;
// CHECK-MESSAGES: :[[@LINE-2]]:27: warning: statement should be inside braces
// CHECK-FIXES: for (int NullStmt : arr) {
// CHECK-FIXES-NEXT: ;
// CHECK-FIXES-NEXT: }
while (cond("while1"))
do_something("while");
// CHECK-MESSAGES: :[[@LINE-2]]:25: warning: statement should be inside braces
// CHECK-FIXES: while (cond("while1")) {
// CHECK-FIXES: }
while (cond("while2")) {
do_something("while");
}
while (false)
;
// CHECK-MESSAGES: :[[@LINE-2]]:16: warning: statement should be inside braces
// CHECK-FIXES: while (false) {
// CHECK-FIXES: }
do
do_something("do1");
while (cond("do1"));
// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: statement should be inside braces
// CHECK-FIXES: do {
// CHECK-FIXES: } while (cond("do1"));
do {
do_something("do2");
} while (cond("do2"));
do
;
while (false);
// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: statement should be inside braces
// CHECK-FIXES: do {
// CHECK-FIXES: } while (false);
if (cond("ifif1"))
// comment
if (cond("ifif2"))
// comment
/*comment*/ ; // comment
// CHECK-MESSAGES: :[[@LINE-5]]:21: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-4]]:23: warning: statement should be inside braces
// CHECK-FIXES: if (cond("ifif1")) {
// CHECK-FIXES: if (cond("ifif2")) {
// CHECK-FIXES: }
// CHECK-FIXES-NEXT: }
if (cond("ifif3"))
// comment1
if (cond("ifif4")) {
// comment2
/*comment3*/; // comment4
}
// CHECK-MESSAGES: :[[@LINE-6]]:21: warning: statement should be inside braces
// CHECK-FIXES: if (cond("ifif3")) {
// CHECK-FIXES-NEXT: // comment1
// CHECK-FIXES-NEXT: if (cond("ifif4")) {
// CHECK-FIXES-NEXT: // comment2
// CHECK-FIXES-NEXT: /*comment3*/; // comment4
// CHECK-FIXES-NEXT: }
// CHECK-FIXES-NEXT: }
if (cond("ifif5"))
; /* multi-line
comment */
// CHECK-MESSAGES: :[[@LINE-3]]:21: warning: statement should be inside braces
// CHECK-FIXES: if (cond("ifif5")) {
// CHECK-FIXES: }/* multi-line
if (1) while (2) if (3) for (;;) do ; while(false) /**/;/**/
// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-2]]:19: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:26: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-4]]:35: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-5]]:38: warning: statement should be inside braces
// CHECK-FIXES: if (1) { while (2) { if (3) { for (;;) { do { ; } while(false) /**/;/**/
// CHECK-FIXES-NEXT: }
// CHECK-FIXES-NEXT: }
// CHECK-FIXES-NEXT: }
// CHECK-FIXES-NEXT: }
int S;
if (cond("assign with brackets"))
S = {5};
// CHECK-MESSAGES: :[[@LINE-2]]:36: warning: statement should be inside braces
// CHECK-FIXES: if (cond("assign with brackets")) {
// CHECK-FIXES-NEXT: S = {5};
// CHECK-FIXES-NEXT: }
if (cond("assign with brackets 2"))
S = { 5 } /* comment1 */ ; /* comment2 */
// CHECK-MESSAGES: :[[@LINE-2]]:38: warning: statement should be inside braces
// CHECK-FIXES: if (cond("assign with brackets 2")) {
// CHECK-FIXES-NEXT: S = { 5 } /* comment1 */ ; /* comment2 */
// CHECK-FIXES-NEXT: }
if (cond("return"))
return;
// CHECK-MESSAGES: :[[@LINE-2]]:22: warning: statement should be inside braces
// CHECK-FIXES: if (cond("return")) {
// CHECK-FIXES-NEXT: return;
// CHECK-FIXES-NEXT: }
while (cond("break and continue")) {
// CHECK-FIXES: while (cond("break and continue")) {
if (true)
break;
// CHECK-MESSAGES: :[[@LINE-2]]:14: warning: statement should be inside braces
// CHECK-FIXES: {{^}} if (true) {{{$}}
// CHECK-FIXES-NEXT: {{^}} break;{{$}}
// CHECK-FIXES-NEXT: {{^ *}}}{{$}}
if (false)
continue;
// CHECK-MESSAGES: :[[@LINE-2]]:15: warning: statement should be inside braces
// CHECK-FIXES: {{^}} if (false) {{{$}}
// CHECK-FIXES-NEXT: {{^}} continue;{{$}}
// CHECK-FIXES-NEXT: {{^ *}}}{{$}}
} //end
// CHECK-FIXES: } //end
if (cond("decl 1"))
int s;
else
int t;
// CHECK-MESSAGES: :[[@LINE-4]]:22: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if (cond("decl 1")) {
// CHECK-FIXES-NEXT: int s;
// CHECK-FIXES-NEXT: } else {
// CHECK-FIXES-NEXT: int t;
// CHECK-FIXES-NEXT: }
if (cond("decl 2"))
int s = (5);
else
int t = (5);
// CHECK-MESSAGES: :[[@LINE-4]]:22: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if (cond("decl 2")) {
// CHECK-FIXES-NEXT: int s = (5);
// CHECK-FIXES-NEXT: } else {
// CHECK-FIXES-NEXT: int t = (5);
// CHECK-FIXES-NEXT: }
if (cond("decl 3"))
int s = {6};
else
int t = {6};
// CHECK-MESSAGES: :[[@LINE-4]]:22: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if (cond("decl 3")) {
// CHECK-FIXES-NEXT: int s = {6};
// CHECK-FIXES-NEXT: } else {
// CHECK-FIXES-NEXT: int t = {6};
// CHECK-FIXES-NEXT: }
}
void test_whitespace() {
while(cond("preserve empty lines"))
if(cond("using continue within if"))
continue;
test();
// CHECK-MESSAGES: :[[@LINE-7]]:{{[0-9]+}}: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-7]]:{{[0-9]+}}: warning: statement should be inside braces
// CHECK-FIXES: {{^}} while(cond("preserve empty lines")) {{{$}}
// CHECK-FIXES-NEXT: {{^}} if(cond("using continue within if")) {{{$}}
// CHECK-FIXES-NEXT: {{^ continue;$}}
// The closing brace is added at beginning of line, clang-format can be
// applied afterwards.
// CHECK-FIXES-NEXT: {{^}$}}
// CHECK-FIXES-NEXT: {{^}$}}
// Following whitespace is assumed to not to belong to the else branch.
// However the check is not possible with CHECK-FIXES-NEXT.
// CHECK-FIXES: {{^}} test();{{$}}
if (cond("preserve empty lines"))
int s;
else
int t;
test();
// CHECK-MESSAGES: :[[@LINE-14]]:{{[0-9]+}}: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-9]]:{{[0-9]+}}: warning: statement should be inside braces
// CHECK-FIXES: {{^}} if (cond("preserve empty lines")) {{{$}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ int s;$}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ } else {$}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ int t;$}}
// The closing brace is added at beginning of line, clang-format can be
// applied afterwards.
// CHECK-FIXES-NEXT: {{^}$}}
// Following whitespace is assumed to not to belong to the else branch.
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^ $}}
// CHECK-FIXES-NEXT: {{^}} test();{{$}}
}
int test_return_int() {
if (cond("return5"))
return 5;
// CHECK-MESSAGES: :[[@LINE-2]]:23: warning: statement should be inside braces
// CHECK-FIXES: if (cond("return5")) {
// CHECK-FIXES-NEXT: return 5;
// CHECK-FIXES-NEXT: }
if (cond("return{6}"))
return {6};
// CHECK-MESSAGES: :[[@LINE-2]]:25: warning: statement should be inside braces
// CHECK-FIXES: if (cond("return{6}")) {
// CHECK-FIXES-NEXT: return {6};
// CHECK-FIXES-NEXT: }
// From https://bugs.llvm.org/show_bug.cgi?id=25970
if (cond("25970")) return {25970};
return {!25970};
// CHECK-MESSAGES: :[[@LINE-2]]:21: warning: statement should be inside braces
// CHECK-FIXES: if (cond("25970")) { return {25970};
// CHECK-FIXES-NEXT: }
// CHECK-FIXES-NEXT: return {!25970};
}
void f(const char *p) {
if (!p)
f("\
");
} // end of f
// CHECK-MESSAGES: :[[@LINE-4]]:10: warning: statement should be inside braces
// CHECK-FIXES: {{^}} if (!p) {{{$}}
// CHECK-FIXES-NEXT: {{^}} f("\{{$}}
// CHECK-FIXES-NEXT: {{^}}");{{$}}
// CHECK-FIXES-NEXT: {{^}}}{{$}}
// CHECK-FIXES-NEXT: {{^}}} // end of f{{$}}
#define M(x) x
int test_macros(bool b) {
if (b) {
return 1;
} else
M(return 2);
// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: statement should be inside braces
// CHECK-FIXES: } else {
// CHECK-FIXES-NEXT: M(return 2);
// CHECK-FIXES-NEXT: }
M(
for (;;)
;
);
// CHECK-MESSAGES: :[[@LINE-3]]:13: warning: statement should be inside braces
// CHECK-FIXES: {{^}} for (;;) {{{$}}
// CHECK-FIXES-NEXT: {{^ ;$}}
// CHECK-FIXES-NEXT: {{^}$}}
#define WRAP(X) { X; }
// This is to ensure no other CHECK-FIXES matches the macro definition:
// CHECK-FIXES: WRAP
// Use-case: LLVM_DEBUG({ for(...) do_something(); });
WRAP({
for (;;)
do_something("for in wrapping macro 1");
});
// CHECK-MESSAGES: :[[@LINE-3]]:13: warning: statement should be inside braces
// CHECK-FIXES: for (;;) {
// CHECK-FIXES-NEXT: do_something("for in wrapping macro 1");
// CHECK-FIXES-NEXT: }
// Use-case: LLVM_DEBUG( for(...) do_something(); );
WRAP(
for (;;)
do_something("for in wrapping macro 2");
);
// CHECK-MESSAGES: :[[@LINE-3]]:13: warning: statement should be inside braces
// CHECK-FIXES: for (;;) {
// CHECK-FIXES-NEXT: do_something("for in wrapping macro 2");
// CHECK-FIXES-NEXT: }
// Use-case: LLVM_DEBUG( for(...) do_something() );
// This is not supported and this test ensure it's correctly not changed.
// We don't want to add the `}` into the Macro and there is no other way
// to add it except for introduction of a NullStmt.
WRAP(
for (;;)
do_something("for in wrapping macro 3")
);
// CHECK-MESSAGES: :[[@LINE-3]]:13: warning: statement should be inside braces
// CHECK-FIXES: WRAP(
// CHECK-FIXES-NEXT: for (;;)
// CHECK-FIXES-NEXT: do_something("for in wrapping macro 3")
// CHECK-FIXES-NEXT: );
// Taken from https://bugs.llvm.org/show_bug.cgi?id=22785
int i;
#define MACRO_1 i++
#define MACRO_2
if( i % 3) i--;
else if( i % 2) MACRO_1;
else MACRO_2;
// CHECK-MESSAGES: :[[@LINE-3]]:13: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:18: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if( i % 3) { i--;
// CHECK-FIXES-NEXT: } else if( i % 2) { MACRO_1;
// CHECK-FIXES-NEXT: } else { MACRO_2;
// CHECK-FIXES-NEXT: }
// Taken from https://bugs.llvm.org/show_bug.cgi?id=22785
#define M(x) x
if (b)
return 1;
else
return 2;
// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if (b) {
// CHECK-FIXES-NEXT: return 1;
// CHECK-FIXES-NEXT: } else {
// CHECK-FIXES-NEXT: return 2;
// CHECK-FIXES-NEXT: }
if (b)
return 1;
else
M(return 2);
// CHECK-MESSAGES: :[[@LINE-4]]:9: warning: statement should be inside braces
// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: statement should be inside braces
// CHECK-FIXES: if (b) {
// CHECK-FIXES-NEXT: return 1;
// CHECK-FIXES-NEXT: } else {
// CHECK-FIXES-NEXT: M(return 2);
// CHECK-FIXES-NEXT: }
}
template <bool A>
auto constexpr_lambda_1 = [] {
if constexpr (A) {
1;
}
};
template <bool A>
auto constexpr_lambda_2 = [] {
// CHECK-MESSAGES: :[[@LINE+1]]:19: warning: statement should be inside braces
if constexpr (A)
1;
// CHECK-FIXES:if constexpr (A) {
// CHECK-FIXES-NEXT:1;
// CHECK-FIXES-NEXT:}
};
void test_constexpr() {
constexpr_lambda_1<false>();
constexpr_lambda_2<false>();
}
| true |
256365ce9165b2208e368362b8f8ee5eb7c031d5 | C++ | Napol-Napol/Practice-algorithm | /plus.cpp | UTF-8 | 403 | 3 | 3 | [] | no_license | #include <iostream>
#include <string>
int res[11];
using namespace std;
void make(int n)
{
for (int i = 4; i <= n; i++)
res[i] = res[i-1] + res[i- 2] + res[i-3];
}
int main()
{
int cnt; string str = "";
cin >> cnt;
res[1] = 1; res[2] = 2; res[3] = 4;
for (int i = 0; i < cnt; i++)
{
int num; cin >> num;
make(num);
str+=to_string(res[num])+"\n";
}
cout << str;
} | true |
a117abbd4bb6658e00197f33aeb2131eac448b6a | C++ | blc1996/leetcode | /106.cpp | UTF-8 | 1,002 | 3.390625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(preorder, inorder, postorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int pIndex, int iLeft, int iRight){
if(iLeft > iRight || pIndex < 0)
return NULL;
if(iLeft == iRight)
return new TreeNode(inorder[iLeft]);
int index = iLeft;
while(preorder[pIndex] != inorder[index])
index++;
TreeNode* output = new TreeNode(preorder[pIndex]);
output->left = helper(preorder, inorder, pIndex - iRight + index - 1, iLeft, index - 1);
output->right = helper(preorder, inorder, pIndex - 1, index + 1, iRight);
return output;
}
};
| true |
bed4210a9d02eac77c2e7966f759837ff5f0249a | C++ | wangqinghe95/PAT-Code | /Advanced-C++/A1009.cpp | UTF-8 | 720 | 2.765625 | 3 | [] | no_license | #include<cstdio>
const int maxn = 2020; //前两个点过不了
double arr[maxn] = {0};
double mul[maxn] = {0};
int main()
{
int exp;
double coe;
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d %lf",&exp,&coe);
arr[exp] = coe;
}
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d %lf",&exp,&coe);
for(int j = 0; j < maxn ; j++)
{
if(arr[j] != 0.0)
{
mul[j + exp] += coe * arr[j];
}
}
}
int count = 0;
for(int i = 0; i < maxn ; i++)
{
if(mul[i] != 0.0)
{
count++;
}
}
printf("%d",count);
if(count == 0) printf(" 0");
else
{
for(int i = maxn; i >= 0; i--)
{
if(mul[i] != 0)
{
printf(" %d %.1f",i,mul[i]);
}
}
}
return 0;
}
| true |
b248b84ac957cefb3aaed261bacd32bd4eb571fb | C++ | lucianosz7/spoj-br | /MATRIZ2.cpp | UTF-8 | 492 | 3.078125 | 3 | [
"MIT"
] | permissive | /*
Resolucao:
Gerar uma matriz de acordo com a formula dada
e entao imprimir o valor da posicao a,b;
*/
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int a, b, p, q, n, r, s, x, y;
cin >> n;
cin >> p >> q >> r >> s >> x >> y;
cin >> a >> b;
long long resp = 0;
for (int i = 0; i < n; ++i)
resp += ((p * a + q * (i + 1)) % x) * ((r * (i + 1) + s * b) % y);
cout << resp;
return 0;
} | true |
bca61b02506e8600395e7f4ba6d0140dc6509921 | C++ | HgScId/TFM | /TFM/ImgDatos.cpp | ISO-8859-1 | 33,340 | 3.109375 | 3 | [] | no_license | #include"ImgDatos.h"
#include<opencv2/core/core.hpp> // Libreras necesarias para usar OpenCV
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<assert.h>
#include<queue>
#include"EstructurasUsadas.h"
#define PI 3.141592653589793238463
imgDatos::imgDatos(cv::Mat& imagenRef, bool comp)
:
contorno(imagenRef.size(), CV_8UC3, cv::Scalar({ 0,0,0 })) // crea la matriz de contornos del objeto ms grande.
{
}
imgDatos::imgDatos(cv::Mat& imagenRef)
:
contorno(imagenRef.size(), CV_8UC3, cv::Scalar({ 0,0,0 })) // crea la matriz de contornos del objeto ms grande.
{
/// FORMACIN DE OBJETOS Y SELECCIN DEL MAYOR (INSECTO)
cv::Mat conect(imagenRef.size(), CV_8UC1, cv::Scalar(0)); // Los miembros de la clase usan su constructor aqu. Usarlo en el cuerpo
for (int i = 0; i < imagenRef.rows; i++)
{
for (int j = 0; j < imagenRef.cols; j++)
{
if (imagenRef.at<unsigned char>(i, j) == 255 && conect.at<unsigned char>(i, j) != 255)
{
int tamObjtemp = 1;// Introduce un nuevo elemento al vector de tamao de objetos
std::queue<cv::Vec2i> conector; // el vector (vector 2D de enteros) que almacenar coordenadas de los pxeles a conectar
/* El formato contenedor queue almacena colocando en cola (en ltima posicin) los elementos entrantres y extrayendo la primera posicin
cada vez que se quita un elemento (FIFO, First In First Out, el primero en entrar el primero en salir). Otra clase de la librera estndar
es stack que introduce elementos en primera posicin y quita tambin la primera posicin (LIFO, Last In First Out, el ltimo en entrar el
primero en salir) */
conector.push({ i, j }); // introducimos el primer contenido detectado como ltimo elemento (est vaco, se coloca el primero)
conect.at<unsigned char>(i, j) = 255; // marcamos primer elemento como visto
std::vector<cv::Vec2i> posPixTemp; // vector temporal de posiciones del objeto ms grande
posPixTemp.push_back({ i,j });
while (!conector.empty())
{ // Comprobacin para que la iteracin de bsqueda se haga siempre en los lmites de la imagen
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (conector.front().val[0] == 0) testfil1 = 0;
if (conector.front().val[0] == conect.rows) testfil1 = 0;
if (conector.front().val[1] == 0) testcol1 = 0;
if (conector.front().val[1] == conect.cols) testcol2 = 0;
assert(conector.front().val[0] - testfil1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(conector.front().val[1] - testcol1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(conector.front().val[0] + testfil2 <= conect.rows); // En el caso de que la resta sea un valor mayor que el nm de filas, error.
assert(conector.front().val[1] + testcol2 <= conect.cols); // En el caso de que la resta sea un valor mayor que el nm de colmns, error.
for (int fil = conector.front().val[0] - testfil1; fil <= conector.front().val[0] + testfil2; fil++)
{
for (int col = conector.front().val[1] - testcol1; col <= conector.front().val[1] + testcol2; col++)
{
if (conect.at<unsigned char>(fil, col) != 255 && imagenRef.at<unsigned char>(fil, col) == 255)
{// Si no est conectado y hay contenido: mtelo en el vector queue
conector.push({ fil,col });
tamObjtemp++; // dale al ltimo elemento del vector(valor utilizado) un pxel ms de tamao.
conect.at<unsigned char>(fil, col) = 255; // marcamos elemento como visto
posPixTemp.push_back({ fil,col }); // cada pxel del objeto aade sus coordenadas al vector temporal
}
}
}
conector.pop(); // elimina el primer elemento
}
// Se comprueba si el vector de posiciones temporal es mayor que el vector de posiciones del objeto ms grande.
if (posPixTemp.size() > posPix.size())
{
posPix.clear(); // Se borra el vector de la clase si es ms pequeo
tamObj = tamObjtemp; // Se cambia el tamao del objeto ms grande.
for (int i = 0; i < posPixTemp.size(); i++)
{
posPix.push_back(posPixTemp[i]); // Se introducen todos los valores
}
}
}
}
}
/// CONTORNO EXTERIOR E INTERIOR
for (int k = 0; k < posPix.size(); k++) // bucle por cada posicin del vector de coordenadas del insecto
{
int i = posPix[k].val[0]; // tomo posicin de fila
int j = posPix[k].val[1]; // tomo posicin de columna
contorno.at<cv::Vec3b>(i, j)[0] = 255; // Insecto en azul
contorno.at<cv::Vec3b>(i, j)[1] = 0; // Le quitas el verde de contornos de otra iteracin
// Si alrededor hay espacio (no te sales de la imagen) y si no valen ya 255 las bandas de azul, dale el verde al contorno.
if (i - 1 >= 0 && contorno.at<cv::Vec3b>(i - 1, j)[0] != 255)
{
contorno.at<cv::Vec3b>(i - 1, j)[1] = 255;
}
if (i + 1 <= contorno.rows && contorno.at<cv::Vec3b>(i + 1, j)[0] != 255)
{
contorno.at<cv::Vec3b>(i + 1, j)[1] = 255;
}
if (j - 1 >= 0 && contorno.at<cv::Vec3b>(i, j - 1)[0] != 255)
{
contorno.at<cv::Vec3b>(i, j - 1)[1] = 255;
}
if (j + 1 <= contorno.cols && contorno.at<cv::Vec3b>(i, j + 1)[0] != 255)
{
contorno.at<cv::Vec3b>(i, j + 1)[1] = 255;
}
}
/// DIFERENCIAR CONTORNO EXTERNO DE INTERNO: ROJO EXTERNO, VERDE INTERNO, INSECTO AZUL
std::queue<cv::Vec2i> vecRellenaCont;
vecRellenaCont.push({ posPix[0].val[0] - 1,posPix[0].val[1] }); // se introduce la posicin inicial del contorno
posPixcontornoext.push_back({ posPix[0].val[0] - 1,posPix[0].val[1] });
contorno.at<cv::Vec3b>(posPix[0].val[0] - 1, posPix[0].val[1])[1] = 0; // le quito el verde
contorno.at<cv::Vec3b>(posPix[0].val[0] - 1, posPix[0].val[1])[2] = 255; // cambiamos el color del contorno externo a rojo. Sirve para diferenciar.
while (!vecRellenaCont.empty())
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (vecRellenaCont.front().val[0] == 0) testfil1 = 0;
if (vecRellenaCont.front().val[0] == imagenRef.rows) testfil1 = 0;
if (vecRellenaCont.front().val[1] == 0) testcol1 = 0;
if (vecRellenaCont.front().val[1] == imagenRef.cols) testcol2 = 0;
assert(vecRellenaCont.front().val[0] - testfil1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(vecRellenaCont.front().val[1] - testcol1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(vecRellenaCont.front().val[0] + testfil2 <= imagenRef.rows); // En el caso de que la resta sea un valor mayor que el nm de filas, error.
assert(vecRellenaCont.front().val[1] + testcol2 <= imagenRef.cols); // En el caso de que la resta sea un valor mayor que el nm de colmns, error.
for (int fil = vecRellenaCont.front().val[0] - testfil1; fil <= vecRellenaCont.front().val[0] + testfil2; fil++)
{
for (int col = vecRellenaCont.front().val[1] - testcol1; col <= vecRellenaCont.front().val[1] + testcol2; col++)
{
if (contorno.at<cv::Vec3b>(fil, col)[1] == 255)
{
vecRellenaCont.push({ fil,col });
contorno.at<cv::Vec3b>(fil, col)[1] = 0;
contorno.at<cv::Vec3b>(fil, col)[2] = 255;
posPixcontornoext.push_back({ fil, col });
}
}
}
vecRellenaCont.pop();
}
/// RELLENAR CONTORNO INTERNO CON AZUL
for (int i = 0; i < contorno.rows; i++)
{
for (int j = 0; j < contorno.cols; j++)
{
if (contorno.at<cv::Vec3b>(i, j)[1] == 255)
{
std::queue<cv::Vec2i> vecRellenaCont;
vecRellenaCont.push({ i,j });
contorno.at<cv::Vec3b>(i, j)[0] = 255;
tamObj++;
contorno.at<cv::Vec3b>(i, j)[1] = 0;
posPix.push_back({ i,j });
while (!vecRellenaCont.empty())
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (vecRellenaCont.front().val[0] == 0) testfil1 = 0;
if (vecRellenaCont.front().val[0] == contorno.rows) testfil1 = 0;
if (vecRellenaCont.front().val[1] == 0) testcol1 = 0;
if (vecRellenaCont.front().val[1] == contorno.cols) testcol2 = 0;
for (int fil = vecRellenaCont.front().val[0] - testfil1; fil <= vecRellenaCont.front().val[0] + testfil2; fil++)
{
for (int col = vecRellenaCont.front().val[1] - testcol1; col <= vecRellenaCont.front().val[1] + testcol2; col++)
{
if (contorno.at<cv::Vec3b>(fil, col)[1] == 255 || contorno.at<cv::Vec3b>(fil, col)[0] == 0)
{
contorno.at<cv::Vec3b>(fil, col)[0] = 255;
tamObj++;
contorno.at<cv::Vec3b>(fil, col)[1] = 0;
vecRellenaCont.push({ fil,col });
posPix.push_back({ fil,col });
}
}
}
vecRellenaCont.pop();
}
}
}
}
/// PERMETRO DEL OBJETO
for (int i = 0; i < contorno.rows; i++)
{
for (int j = 0; j < contorno.cols; j++)
{
if (contorno.at<cv::Vec3b>(i, j)[2] == 255)
{ // Comprobacin para evitar salidas de la imagen
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (i - testfil1 < 0) testfil1 = 0;
if (j - testcol1 < 0) testcol1 = 0;
if (i + testfil2 >= contorno.rows) testfil2 = 0;
if (j + testcol2 >= contorno.cols) testcol2 = 0;
// En el caso de que cualquiera de los puntos del test salga 0, se buscar un punto insecto (banda del azul)
// en la posicin (i,j) que es contorno (banda del rojo) por lo que no sumar al permetro
if (contorno.at<cv::Vec3b>(i - testfil1, j)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i + testfil2, j)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i, j - testcol1)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i, j + testcol2)[0] == 255) perObj++;
}
}
}
/// CALCULO MOMENTOS INERCIA, EJES DE INERCIA, EXCENTRICIDAD, ELIPSE EQUIVALENTE
geometriaImagen =CalculaMomentos(posPix,perObj);
}
void imgDatos::perfilamiento(cv::Mat& imagencontornoentrada, std::vector<cv::Vec2i>& posPixentrada)
{
int Areacuad = 100, Percuad = 40;
double kcuad = double(Percuad*Percuad) / double(Areacuad);
//int iteraciones = 0;
// Localizar la forma para minimizar iteraciones. Encuadrar el insecto.
int filmin= imagencontornoentrada.rows, colmin= imagencontornoentrada.cols, filmax=0, colmax=0;
for (int i = 0; i < posPixentrada.size(); i++)
{
filmin = std::min(filmin, posPixentrada[i].val[0]);
colmin = std::min(colmin, posPixentrada[i].val[1]);
filmax = std::max(filmax, posPixentrada[i].val[0]);
colmax = std::max(colmax, posPixentrada[i].val[1]);
}
for (int i = 0; i <= int((filmax-filmin) / 10); i++)
{
for (int j = 0; j <= int((colmax-colmin) / 10); j++)
{
imgDatos segmento(imagencontornoentrada, true); // trozo extrado de la figura
for (int fil = filmin + i * 10; fil < filmin+10 + i * 10; fil++)
{
for (int col = colmin + j * 10; col < colmin+10 + j * 10; col++)
{
if (imagencontornoentrada.at<cv::Vec3b>(fil, col)[0] == 255)
{
segmento.contorno.at<cv::Vec3b>(fil, col)[0] = 255; // dibuja el insecto
segmento.tamObj++; // contar tamao del segmento
segmento.posPix.push_back({ fil,col }); // almacena los puntos del segmento
}
}
}
// Se cierra toda la figura azul con contornos rojos
if (segmento.tamObj > 0) // Si hay objeto en el extracto, opera!
{
//iteraciones++;
//cv::imwrite("ImagenSalida\\"+std::to_string(iteraciones)+"cosa1.bmp", segmento.contorno); // segmento azul extrado
for (int l = 0; l < segmento.posPix.size(); l++)
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (segmento.posPix[l].val[0] - testfil1 < 0) testfil1 = 0;
if (segmento.posPix[l].val[1] - testcol1 < 0) testcol1 = 0;
if (segmento.posPix[l].val[0] + testfil2 >= segmento.contorno.rows) testfil2 = 0;
if (segmento.posPix[l].val[1] + testcol2 >= segmento.contorno.cols) testcol2 = 0;
if (segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1])[0] == 255)
{
if (segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] - testfil1, segmento.posPix[l].val[1])[2] == 0
&& segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] - testfil1, segmento.posPix[l].val[1])[0] == 0)
{
segmento.posPixcontornoext.push_back({ segmento.posPix[l].val[0] - testfil1, segmento.posPix[l].val[1] });
segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] - testfil1, segmento.posPix[l].val[1])[2] = 255;
segmento.perObj++;
}
if (segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] + testfil2, segmento.posPix[l].val[1])[2] == 0
&& segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] + testfil2, segmento.posPix[l].val[1])[0] == 0)
{
segmento.posPixcontornoext.push_back({ segmento.posPix[l].val[0] + testfil2, segmento.posPix[l].val[1] });
segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0] + testfil2, segmento.posPix[l].val[1])[2] = 255;
segmento.perObj++;
}
if (segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] - testcol1)[2] == 0
&& segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] - testcol1)[0] == 0)
{
segmento.posPixcontornoext.push_back({ segmento.posPix[l].val[0] , segmento.posPix[l].val[1] - testcol1 });
segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] - testcol1)[2] = 255;
segmento.perObj++;
}
if (segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] + testcol2)[2] == 0
&& segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] + testcol2)[0] == 0)
{
segmento.posPixcontornoext.push_back({ segmento.posPix[l].val[0], segmento.posPix[l].val[1] + testcol2 });
segmento.contorno.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1] + testcol2)[2] = 255;
segmento.perObj++;
}
}
}
double ffseg = double(kcuad*segmento.tamObj) / double(segmento.perObj*segmento.perObj);
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa2.bmp", segmento.contorno);
if (segmento.tamObj != 100)
{
cv::Mat contornoTemp=imagencontornoentrada.clone();
std::vector<cv::Vec2i> posPixTemp = posPixentrada;
std::vector<cv::Vec2i> posPixexteriorTemp = posPixcontornoext;
int perObjTemp = perObj;
int tamObjTemp = tamObj;
// Necesitamos el nuevo perimetro
// Borrado de azul del contorno temporal
for (int l = 0; l < segmento.posPix.size(); l++)
{
if (contornoTemp.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1])[0] == 255)
{
contornoTemp.at<cv::Vec3b>(segmento.posPix[l].val[0], segmento.posPix[l].val[1])[0] = 0;
tamObjTemp--;
}
}
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa3.bmp", contornoTemp); // azul borrado de contorno Temporal
// Borrado de pxeles insecto azules del vector de almacenamiento temporal.
for (int k = 0; k < segmento.posPix.size(); k++)
{
for (int p = int(posPixTemp.size()) - 1; p >= 0; p--) // se empieza desde el final de posPixTemp para que no haya problema al borrar dos elementos consecutivos
{
if (posPixTemp[p].val[0] == segmento.posPix[k].val[0] && posPixTemp[p].val[1] == segmento.posPix[k].val[1])
{
posPixTemp.erase(posPixTemp.begin() + p);
break;
}
}
}
// Borrado de rojos aislados
for (int l = 0; l < posPixcontornoext.size(); l++)
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (posPixcontornoext[l].val[0] - testfil1 < 0) testfil1 = 0;
if (posPixcontornoext[l].val[1] - testcol1 < 0) testcol1 = 0;
if (posPixcontornoext[l].val[0] + testfil2 >= contornoTemp.rows) testfil2 = 0;
if (posPixcontornoext[l].val[1] + testcol2 >= contornoTemp.cols) testcol2 = 0;
if (contornoTemp.at<cv::Vec3b>(posPixcontornoext[l].val[0] - testfil1, posPixcontornoext[l].val[1])[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixcontornoext[l].val[0] + testfil2, posPixcontornoext[l].val[1])[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixcontornoext[l].val[0], posPixcontornoext[l].val[1] - testcol1)[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixcontornoext[l].val[0], posPixcontornoext[l].val[1] + testcol2)[0] == 0)
{
contornoTemp.at<cv::Vec3b>(posPixcontornoext[l].val[0], posPixcontornoext[l].val[1])[2] = 0;
perObjTemp--;
}
}
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa4.bmp", contornoTemp); // borrado de rojos aislados
// Borrado de pxeles contorno rojo del vector de almacenamiento temporal.
for (int k = 0; k < segmento.posPixcontornoext.size(); k++)
{
for (int p = static_cast<int>(posPixexteriorTemp.size()) - 1; p >= 0; p--) // se empieza desde el final de posPixTemp para que no haya problema al borrar dos elementos consecutivos
{
if (posPixexteriorTemp[p].val[0] == segmento.posPixcontornoext[k].val[0] && posPixexteriorTemp[p].val[1] == segmento.posPixcontornoext[k].val[1])
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (posPixexteriorTemp[p].val[0] - testfil1 < 0) testfil1 = 0;
if (posPixexteriorTemp[p].val[1] - testcol1 < 0) testcol1 = 0;
if (posPixexteriorTemp[p].val[0] + testfil2 >= contornoTemp.rows) testfil2 = 0;
if (posPixexteriorTemp[p].val[1] + testcol2 >= contornoTemp.cols) testcol2 = 0;
if (contornoTemp.at<cv::Vec3b>(posPixexteriorTemp[p].val[0] - testfil1, posPixexteriorTemp[p].val[1])[0] != 255
&& contornoTemp.at<cv::Vec3b>(posPixexteriorTemp[p].val[0] + testfil2, posPixexteriorTemp[p].val[1])[0] != 255
&& contornoTemp.at<cv::Vec3b>(posPixexteriorTemp[p].val[0], posPixexteriorTemp[p].val[1] - testcol1)[0] != 255
&& contornoTemp.at<cv::Vec3b>(posPixexteriorTemp[p].val[0], posPixexteriorTemp[p].val[1] + testcol2)[0] != 255)
{
posPixexteriorTemp.erase(posPixexteriorTemp.begin() + p);
break;
}
}
}
}
// Colocacin de rojo en azules exteriores
for (int l = 0; l < posPixTemp.size(); l++)
{
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (posPixTemp[l].val[0] - testfil1 < 0) testfil1 = 0;
if (posPixTemp[l].val[1] - testcol1 < 0) testcol1 = 0;
if (posPixTemp[l].val[0] + testfil2 >= contornoTemp.rows) testfil2 = 0;
if (posPixTemp[l].val[1] + testcol2 >= contornoTemp.cols) testcol2 = 0;
if (contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] - testfil1, posPixTemp[l].val[1])[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] - testfil1, posPixTemp[l].val[1])[2] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] - testfil1, posPixTemp[l].val[1])[1] == 0)
{
contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] - testfil1, posPixTemp[l].val[1])[2] = 255;
perObjTemp++;
posPixexteriorTemp.push_back({ posPixTemp[l].val[0] - testfil1, posPixTemp[l].val[1] });
}
if (contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] + testfil2, posPixTemp[l].val[1])[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] + testfil2, posPixTemp[l].val[1])[2] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] + testfil2, posPixTemp[l].val[1])[1] == 0)
{
contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0] + testfil2, posPixTemp[l].val[1])[2] = 255;
perObjTemp++;
posPixexteriorTemp.push_back({ posPixTemp[l].val[0] + testfil2, posPixTemp[l].val[1] });
}
if (contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] - testcol1)[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] - testcol1)[2] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] - testcol1)[1] == 0)
{
contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] - testcol1)[2] = 255;
perObjTemp++;
posPixexteriorTemp.push_back({ posPixTemp[l].val[0], posPixTemp[l].val[1] - testcol1 });
}
if (contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] + testcol2)[0] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] + testcol2)[2] == 0
&& contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] + testcol2)[1] == 0)
{
contornoTemp.at<cv::Vec3b>(posPixTemp[l].val[0], posPixTemp[l].val[1] + testcol2)[2] = 255;
perObjTemp++;
posPixexteriorTemp.push_back({ posPixTemp[l].val[0], posPixTemp[l].val[1] + testcol2 });
}
}
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa5.bmp", contornoTemp); // nuevos rojos exteriores colocados
GeometriaObj nuevaGeo = CalculaMomentos(posPixTemp, perObjTemp);
if (nuevaGeo.factformaelipse > geometriaImagen.factformaelipse)
{
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa6.bmp", imagencontornoentrada);
contornoTemp.copyTo(imagencontornoentrada);
posPixcontornoext = posPixexteriorTemp;
posPixentrada = posPixTemp;
tamObj = tamObjTemp;
geometriaImagen=nuevaGeo;
perObj=perObjTemp;
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa7.bmp", imagencontornoentrada); // borrado de rojos aislados
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa8.bmp", contorno); // borrado de rojos aislados
}
else
{
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa6.bmp", imagencontornoentrada);
imagencontornoentrada.copyTo(contornoTemp);
posPixexteriorTemp = posPixcontornoext;
posPixTemp = posPixentrada;
tamObjTemp= tamObj;
nuevaGeo= geometriaImagen;
perObjTemp = perObj;
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa7.bmp", imagencontornoentrada); // borrado de rojos aislados
//cv::imwrite("ImagenSalida\\" + std::to_string(iteraciones) + "cosa8.bmp", contorno); // borrado de rojos aislados
}
}
}
}
}
}
void imgDatos::Erosion(cv::Mat& imagencontorno, int tamKernel)
{
cv::Mat kernel = cv::getStructuringElement(0, cv::Size(tamKernel, tamKernel), cv::Point(-1,-1)); // El 0 es matriz de convolucin cuadrada. Punto ancla (-1,-1) en el centro del kernel (matriz de convolucin)
cv::Mat salida;
erode(imagencontorno, salida, kernel); // Erosiona la imagen.
salida.copyTo(imagencontorno); // Copia la erosin al contorno de entrada
CreacionObjconCont(imagencontorno); // Creacin de objetos con el contorno erosionado: Obtiene tamObj y posPix nuevos.
DibujaContorno(); // Vuelve a dibujar contorno rojo y calcula perObj
geometriaImagen = CalculaMomentos(posPix, perObj); // se calculan las inercias y centros de gravedad nuevos.
}
void imgDatos::DibujaContorno()
{
/// CONTORNO EXTERIOR SI NO HAY HUECOS DENTRO (MODIFICACION DE LA FUNCIN DEL CONSTRUCTOR PARA INSECTOS CON LOS HUECOS INTERNOS ELIMINADOS)
// Se pinta el insecto de azul y el contorno (slo exterior) de rojo.
// Busco que la imagencontorno de entrada sea modificada por el nuevo contorno detectado. Se usa tras las operaciones de erosin.
contorno = cv::Mat(contorno.size(), CV_8UC3, cv::Scalar({ 0,0,0 }));
posPixcontornoext.clear();
for (int k = 0; k < posPix.size(); k++) // bucle por cada posicin del vector de coordenadas del insecto
{
int i = posPix[k].val[0]; // tomo posicin de fila
int j = posPix[k].val[1]; // tomo posicin de columna
contorno.at<cv::Vec3b>(i, j)[0] = 255; // Insecto en azul
contorno.at<cv::Vec3b>(i, j)[2] = 0; // Le quitas el rojo de contornos de otra iteracin ya que se da el caso de pxeles que al ser analizados en un primer momento
// no tienen valor rojo, pero que s pertenecen al vector de posiciones
// Si alrededor hay espacio (no te sales de la imagen) y si no valen ya 255 las bandas de azul y del rojo, dale el rojo al contorno.
// Se evita dar mltiples veces el rojo tambin ya que se introducira mltiples veces en el vector de posicin del contorno sus puntos.
if (i - 1 >= 0 && contorno.at<cv::Vec3b>(i - 1, j)[0] != 255 && contorno.at<cv::Vec3b>(i - 1, j)[2] != 255)
{
contorno.at<cv::Vec3b>(i - 1, j)[2] = 255;
posPixcontornoext.push_back({ i - 1, j });
}
if (i + 1 <= contorno.rows && contorno.at<cv::Vec3b>(i + 1, j)[0] != 255 && contorno.at<cv::Vec3b>(i + 1, j)[2] != 255)
{
contorno.at<cv::Vec3b>(i + 1, j)[2] = 255;
posPixcontornoext.push_back({ i + 1, j });
}
if (j - 1 >= 0 && contorno.at<cv::Vec3b>(i, j - 1)[0] != 255 && contorno.at<cv::Vec3b>(i, j - 1)[2] != 255)
{
contorno.at<cv::Vec3b>(i, j - 1)[2] = 255;
posPixcontornoext.push_back({ i, j-1 });
}
if (j + 1 <= contorno.cols && contorno.at<cv::Vec3b>(i, j + 1)[0] != 255 && contorno.at<cv::Vec3b>(i, j + 1)[2] != 255)
{
contorno.at<cv::Vec3b>(i, j + 1)[2] = 255;
posPixcontornoext.push_back({ i, j +1});
}
}
for (int i = int(posPixcontornoext.size())-1; i >=0; i--)
{
if (contorno.at<cv::Vec3b>(posPixcontornoext[i].val[0], posPixcontornoext[i].val[1])[0] == 255)
{
posPixcontornoext.erase(posPixcontornoext.begin() + i);
}
}
perObj = 0;
for (int k = 0; k < posPixcontornoext.size(); k++)
{
int i = posPixcontornoext[k].val[0];
int j = posPixcontornoext[k].val[1];
// Comprobacin para evitar salidas de la imagen
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (i - testfil1 < 0) testfil1 = 0;
if (j - testcol1 < 0) testcol1 = 0;
if (i + testfil2 >= contorno.rows) testfil2 = 0;
if (j + testcol2 >= contorno.cols) testcol2 = 0;
// En el caso de que cualquiera de los puntos del test salga 0, se buscar un punto insecto (banda del azul)
// en la posicin (i,j) que es contorno (banda del rojo) por lo que no sumar al permetro
if (contorno.at<cv::Vec3b>(i - testfil1, j)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i + testfil2, j)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i, j - testcol1)[0] == 255) perObj++;
if (contorno.at<cv::Vec3b>(i, j + testcol2)[0] == 255) perObj++;
}
}
GeometriaObj imgDatos::CalculaMomentos(std::vector<cv::Vec2i> posPixentrada, int perObjentrada)
{
GeometriaObj nuevaGeom;
/// CALCULO CENTROIDE (CENTRO DE GRAVEDAD)
for (int i = 0; i < posPixentrada.size(); i++)
{
nuevaGeom.centroide.val[0] += posPixentrada[i].val[0] + 0.5;
nuevaGeom.centroide.val[1] += posPixentrada[i].val[1] + 0.5;
}
nuevaGeom.centroide.val[0] /= posPixentrada.size();
nuevaGeom.centroide.val[1] /= posPixentrada.size();
/// MOMENTOS DE INERCIA CENTRALES (respecto del centroide)
for (int i = 0; i < posPixentrada.size(); i++)
{
nuevaGeom.InerciaX += (posPixentrada[i].val[1] + 0.5 - nuevaGeom.centroide.val[1])*(posPixentrada[i].val[1] + 0.5 - nuevaGeom.centroide.val[1]);
nuevaGeom.InerciaY += (posPixentrada[i].val[0] + 0.5 - nuevaGeom.centroide.val[0])*(posPixentrada[i].val[0] + 0.5 - nuevaGeom.centroide.val[0]);
nuevaGeom.InerciaXY += (posPixentrada[i].val[0] + 0.5 - nuevaGeom.centroide.val[0])*(posPixentrada[i].val[1] + 0.5 - nuevaGeom.centroide.val[1]);
}
/// ANGULO PARA EJES PRINCIPALES
// El angulo realiza el menor giro de los ejes X e Y para alcanzar la posicin de ejes principales de inercia.
// Sentido horario - y sentido antihorario +.
nuevaGeom.AngGiro = -std::atan((-2 * nuevaGeom.InerciaXY) / (nuevaGeom.InerciaY - nuevaGeom.InerciaX)) / 2;
// Se ajusta el angulo de giro para que el eje X (eje fila) siempre tengo el momento principal de inercia
// ms pequeo (alineado con el insecto). Para el otro eje principal habra que aadirle PI/2 ms.
if (nuevaGeom.InerciaX > nuevaGeom.InerciaY)
{
nuevaGeom.AngGiro += (PI / 2);
}
/// EXCENTRICIDAD DEL A FORMA. EJES DE LA ELIPSE EQUIVALENTE COLOCADA EN EL CENTRO DE GRAVEDAD Y ORIENTADA SEGN EL NGULO DE ROTACIN.
double a1 = nuevaGeom.InerciaX + nuevaGeom.InerciaY + std::sqrt((nuevaGeom.InerciaX - nuevaGeom.InerciaY)*(nuevaGeom.InerciaX - nuevaGeom.InerciaY) + 4 * nuevaGeom.InerciaXY*nuevaGeom.InerciaXY);
double a2 = nuevaGeom.InerciaX + nuevaGeom.InerciaY - std::sqrt((nuevaGeom.InerciaX - nuevaGeom.InerciaY)*(nuevaGeom.InerciaX - nuevaGeom.InerciaY) + 4 * nuevaGeom.InerciaXY*nuevaGeom.InerciaXY);
double exc = a1 / a2;
double ra = std::sqrt(2 * a1 / posPixentrada.size());
double rb = std::sqrt(2 * a2 / posPixentrada.size());
double PerIdeal = PI*(3 * (ra + rb) - std::sqrt((3 * ra + rb)*(ra + 3 * rb)));
double AreaIdeal = PI*ra*rb;
nuevaGeom.kelipseIdeal = PerIdeal*PerIdeal / AreaIdeal;
/*
// SI SE QUIERE DEIBUJAR LA ELIPSE!!!
cv::Mat Elipse(contorno.size(), CV_8UC1, cv::Scalar(0));
for (double i = 0; i < 2 * PI; i = i + 0.001)
{
Elipse.at<unsigned char>(int(nuevaGeom.centroide.val[0]+std::cos(nuevaGeom.AngGiro)*ra*std::cos(i)-std::sin(nuevaGeom.AngGiro)*rb*std::sin(i)), int(nuevaGeom.centroide.val[1] + std::sin(nuevaGeom.AngGiro)*ra*std::cos(i) - std::cos(nuevaGeom.AngGiro)*rb*std::sin(i))) = 255;
}
cv::imwrite("ImagenSalida\\elipse.bmp", Elipse);
*/
/// FACTOR DE FORMA PARA LA ELIPSE EQUIVALENTE
nuevaGeom.factformaelipse = nuevaGeom.kelipseIdeal*posPixentrada.size() / (perObjentrada*perObjentrada);
return nuevaGeom;
}
void imgDatos::CreacionObjconCont(cv::Mat& imagencontorno)
{
/// FORMACIN DE OBJETOS Y SELECCIN DEL MAYOR (INSECTO)
tamObj = 0;
posPix.clear();
cv::Mat conect(imagencontorno.size(), CV_8UC1, cv::Scalar(0)); // Los miembros de la clase usan su constructor aqu. Usarlo en el cuerpo
for (int i = 0; i < imagencontorno.rows; i++)
{
for (int j = 0; j < imagencontorno.cols; j++)
{
if (imagencontorno.at<cv::Vec3b>(i, j)[0] == 255 && conect.at<unsigned char>(i, j) != 255)
{
int tamObjtemp = 1;// Introduce un nuevo elemento al vector de tamao de objetos
std::queue<cv::Vec2i> conector; // el vector (vector 2D de enteros) que almacenar coordenadas de los pxeles a conectar
/* El formato contenedor queue almacena colocando en cola (en ltima posicin) los elementos entrantres y extrayendo la primera posicin
cada vez que se quita un elemento (FIFO, First In First Out, el primero en entrar el primero en salir). Otra clase de la librera estndar
es stack que introduce elementos en primera posicin y quita tambin la primera posicin (LIFO, Last In First Out, el ltimo en entrar el
primero en salir) */
conector.push({ i, j }); // introducimos el primer contenido detectado como ltimo elemento (est vaco, se coloca el primero)
conect.at<unsigned char>(i, j) = 255; // marcamos primer elemento como visto
std::vector<cv::Vec2i> posPixTemp; // vector temporal de posiciones del objeto ms grande
posPixTemp.push_back({ i,j });
while (!conector.empty())
{ // Comprobacin para que la iteracin de bsqueda se haga siempre en los lmites de la imagen
int testfil1 = 1, testfil2 = 1, testcol1 = 1, testcol2 = 1;
if (conector.front().val[0] == 0) testfil1 = 0;
if (conector.front().val[0] == conect.rows) testfil1 = 0;
if (conector.front().val[1] == 0) testcol1 = 0;
if (conector.front().val[1] == conect.cols) testcol2 = 0;
assert(conector.front().val[0] - testfil1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(conector.front().val[1] - testcol1 >= 0); // En el caso de que la resta sea un valor menor que cero, salta un error.
assert(conector.front().val[0] + testfil2 <= conect.rows); // En el caso de que la resta sea un valor mayor que el nm de filas, error.
assert(conector.front().val[1] + testcol2 <= conect.cols); // En el caso de que la resta sea un valor mayor que el nm de colmns, error.
for (int fil = conector.front().val[0] - testfil1; fil <= conector.front().val[0] + testfil2; fil++)
{
for (int col = conector.front().val[1] - testcol1; col <= conector.front().val[1] + testcol2; col++)
{
if (conect.at<unsigned char>(fil, col) != 255 && imagencontorno.at<cv::Vec3b>(fil, col)[0] == 255)
{// Si no est conectado y hay contenido: mtelo en el vector queue
conector.push({ fil,col });
tamObjtemp++; // dale al ltimo elemento del vector(valor utilizado) un pxel ms de tamao.
conect.at<unsigned char>(fil, col) = 255; // marcamos elemento como visto
posPixTemp.push_back({ fil,col }); // cada pxel del objeto aade sus coordenadas al vector temporal
}
}
}
conector.pop(); // elimina el primer elemento
}
// Se comprueba si el vector de posiciones temporal es mayor que el vector de posiciones del objeto ms grande.
if (posPixTemp.size() > posPix.size())
{
posPix.clear(); // Se borra el vector de la clase si es ms pequeo
tamObj = tamObjtemp; // Se cambia el tamao del objeto ms grande.
for (int i = 0; i < posPixTemp.size(); i++)
{
posPix.push_back(posPixTemp[i]); // Se introducen todos los valores
}
}
}
}
}
}
| true |
ce5ce78c67d9977447c53ffedbf4038d1d68ad53 | C++ | Smallsherlly/C-note | /day07/08notinher.cpp | UTF-8 | 388 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class A
{
private:
int m_a;
A(int a){m_a = a;}
A(const A& that){}
static A a;
public:
static A& getInstance()
{
return a;
}
void show()
{
cout << m_a << endl;;
}
friend class B;
};
A A::a(100);
class B:public A
{
public:
B(int a):A(a){}
};
int main()
{
A& a = A::getInstance();
B b(200);
a.show();
b.show();
return 0;
}
| true |
b5c75ceb7ad5c6a932ec13c30e5b7b38723a4eee | C++ | CimpeanAndrei/Training | /Queue.c/main.cpp | UTF-8 | 1,253 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include "coada.h"
using namespace std;
int main()
{
coada Coada;
while(true)
{
int optiune;
int data;
cout<<"\n\n===============================\n";
cout<<"\t\tMENU\n";
cout<<"===============================\n";
cout<<"1. AfisCoada\n";
cout<<"2. AdaugaCodaa\n";
cout<<"3. ScoateCoada\n";
cout<<"4. LungimeCoada\n";
cout<<"5. OprireProgram\n";
cout<<"================================\n";
cout<<"Choose your option :";
cin>>optiune;
switch(optiune)
{
case 1:
Coada.afisCoada();
break;
case 2:
cout<<"Introdu elementul : ";
cin>>data;
Coada.adaugaCapat(data);
cout<<"\nAdded successfully";
break;
case 3:
Coada.scoateFata();
break;
case 4:
cout<<"\n Lungimea este :"<<Coada.lungimeCoada();
break;
case 5:
return 0;
default:
cout<<"Introdu o comanda valida";
break;
}
}
return 0;
}
| true |
88701eea0db2a087d6ca5fd5b39087cd87985122 | C++ | DuckMonster/SmallGame | /Game/src/Core/Standard/Array.h | UTF-8 | 7,684 | 3.5625 | 4 | [] | no_license | #pragma once
#include <cstring>
#include "Core/Memory/Allocator.h"
template<typename InType, typename InAllocator>
class ArrayBase
{
template<typename InOtherType, typename InOtherAllocator>
friend class ArrayBase;
public:
class Iterator
{
public:
Iterator(InType* data, uint32 index = 0) :
data(data), index(index) { }
Iterator(const Iterator& other) : data(other.data), index(other.index) {}
~Iterator() {}
Iterator& operator++()
{
index++;
return *this;
}
InType& operator*() const
{
return data[index];
}
bool operator!=(const Iterator& other)
{
return !operator==(other);
}
bool operator==(const Iterator& other)
{
return data == other.data && index == other.index;
}
InType* data;
uint32 index;
};
class ConstIterator
{
public:
ConstIterator(const InType* data, uint32 index = 0) :
data(data), index(index) { }
ConstIterator(const Iterator& other) : data(other.data), index(other.index) {}
~ConstIterator() {}
ConstIterator& operator++()
{
index++;
return *this;
}
const InType& operator*() const
{
return data[index];
}
bool operator!=(const ConstIterator& other)
{
return !operator==(other);
}
bool operator==(const ConstIterator& other)
{
return data == other.data && index == other.index;
}
const InType* data;
uint32 index;
};
public:
ArrayBase() {}
ArrayBase(const ArrayBase& other)
{
Reserve(other.capacity);
size = other.size;
// Call copy constructor for every element
for (uint32 i = 0; i < other.size; ++i)
{
new(data + i) InType(other.data[i]);
}
}
ArrayBase(ArrayBase&& other)
{
data = other.data;
capacity = other.capacity;
size = other.size;
other.data = nullptr;
other.capacity = 0;
other.size = 0;
}
// Allocator conversion
template<typename InOtherAlloc>
ArrayBase(const ArrayBase<InType, InOtherAlloc>& other)
{
Reserve(other.capacity);
size = other.size;
// Call copy constructor for every element
for (uint32 i = 0; i < other.size; ++i)
{
new(data + i) InType(other.data[i]);
}
}
~ArrayBase()
{
Clear();
if (data != nullptr)
InAllocator::Free(data);
}
// Adds an element at the end of the array
InType& Add(const InType& value);
// Only adds an element if it doesnt already exist
InType& AddUnique(const InType& value);
// Adds (with default value) and returns a ref to the new object
InType& AddRef();
// Inserts an element at some index
InType& Insert(uint32 index, const InType& value)
{
return InsertEmplace(index, value);
}
InType& InsertRef(uint32 index)
{
return InsertEmplace(index);
}
template<typename... InArgs>
InType& InsertEmplace(uint32 index, InArgs... args)
{
if (index > size)
{
Error("Insert index outsize array bounds");
return GetErrorValue();
}
Reserve(size + 1);
// Move all elements above the inserted index
memmove(data + index + 1, data + index, sizeof(InType) * (size - index));
new(data + index) InType(args...);
size++;
return data[index];
}
InType& InsertUnitialized(uint32 index)
{
if (index > size)
{
Error("Insert index outsize array bounds");
return GetErrorValue();
}
Reserve(size + 1);
// Move all elements above the inserted index
memmove(data + index + 1, data + index, sizeof(InType) * (size - index));
size++;
return data[index];
}
// Adds an element at the end of the array, but doesn't initialize it (call its constructor)
InType& AddUninitialized()
{
Reserve(size + 1);
InType& item = data[size];
size++;
return item;
}
// Adds and element and initializes it with the specified args (calls its constructor)
template<typename... InArgs>
InType& Emplace(const InArgs&...);
// Removes the first occurance of value in the array
bool Remove(const InType& value);
// Removes the element at a specific index (realigns everything afterwards)
bool RemoveAt(uint32 index);
// Finds the index of a specific value (and returns if it found anything)
bool Find(const InType& value, uint32& out_index);
// Returns if this array contains a specific value
bool Contains(const InType& value);
// Returns if the array has no elements in it
bool IsEmpty() const { return size == 0; }
// Empties the array
void Clear() { Resize(0); }
// Empties the array, but doesnt destroy any objects (call destructor)
void ClearNoDestruct()
{
size = 0;
}
// Returns how many objects are in this array
uint32 Size() const
{
return size;
}
// Resizes the array and adds/removed objects to fit
void Resize(uint32 in_size, const InType& value = InType())
{
ResizeEmplace(in_size, value);
}
// Resizes the array and adds/removed objects to fit (calls the constructor with args when adding)
template<typename... TArgs>
void ResizeEmplace(uint32 in_size, const TArgs&... args)
{
// Same size, we dont care
if (in_size == size)
return;
// Make sure our buffer is big enough
Reserve(in_size);
// If we want the array to be bigger, make sure to construct objects
if (in_size > size)
{
for (uint32 i = size; i < in_size; ++i)
new(data + i) InType(args...);
}
// Otherwise, destruct objects that will get deleted
else
{
for (uint32 i = in_size; i < size; ++i)
{
data[i].~InType();
}
}
size = in_size;
}
// Will resize the internal buffer to fit in_capacity number of elements, but wont actually grow the array
void Reserve(uint32 in_capacity)
{
// Only grow if bigger
if (capacity < in_capacity)
{
InType* old_data = data;
data = (InType*)InAllocator::Malloc(sizeof(InType) * in_capacity);
if (old_data != nullptr)
{
// Copy data from old buffer to new
memcpy(data, old_data, sizeof(InType) * capacity);
InAllocator::Free(old_data);
}
capacity = in_capacity;
}
}
// = operators
ArrayBase& operator=(const ArrayBase& other)
{
Clear();
Reserve(other.size);
for(uint32 i=0; i<other.size; ++i)
new(data + i) InType(other[i]);
size = other.size;
return *this;
}
ArrayBase& operator=(ArrayBase&& other)
{
// For rvalues, we just wanna transfer the memory from the other array
// Clear and de-allocate memory
Clear();
if (data != nullptr)
InAllocator::Free(data);
// Then just transfer the pointers, sizes and such
data = other.data;
capacity = other.capacity;
size = other.size;
other.data = nullptr;
other.capacity = 0;
other.size = 0;
return *this;
}
template<typename InOtherAlloc>
ArrayBase& operator=(const ArrayBase<InType, InOtherAlloc>& other)
{
// Clear this array first
Clear();
Reserve(other.size);
for(uint32 i=0; i<other.size; ++i)
new(data + i) InType(other[i]);
size = other.size;
return *this;
}
InType& operator[](uint32 index);
const InType& operator[](uint32 index) const;
// Pointer getters
InType* Ptr() { return data; }
const InType* Ptr() const { return data; }
InType* operator*() { return Ptr(); }
const InType* operator*() const { return Ptr(); }
// std-iterator compliant functions
Iterator begin()
{
return Iterator(data, 0);
}
Iterator end()
{
return Iterator(data, size);
}
ConstIterator begin() const
{
return ConstIterator(data, 0);
}
ConstIterator end() const
{
return ConstIterator(data, size);
}
private:
// Error value is used when a fatal error has occured, since the error could be expected
static char ERROR_VALUE[sizeof(InType)];
static InType& GetErrorValue();
InType* data = nullptr;
uint32 capacity = 0;
uint32 size = 0;
};
template<typename T>
using Array = ArrayBase<T, HeapAllocator>;
template<typename T>
using TArray = ArrayBase<T, TemporaryAllocator>;
#include "Array.inl" | true |
4345dd2376ad544babc20334a13f15d5c93ffde9 | C++ | ThatRadChad/BellingerChad_CIS_5_Fall2017 | /Homework/Assignment_2/Gaddis_8thEd_Chap3_Prob2_StadiumSeating/main.cpp | UTF-8 | 1,348 | 3.78125 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Chad Bellinger
* Created on September 14, 2017, 2:12 PM
* Purpose: Stadium Seating
*/
//System Libraries
#include <iostream> //Input/Output Stream Library
#include <cmath>
using namespace std; //Standard Name-space under which System Libraries reside
//User Libraries
//Global Constants - Not variables only Math/Science/Conversion constants
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Declare Variables
float classA; //Seating class A
float classB; //Seating class B
float classC; //Seating class C
float profit; //Profit of all tickets sold
//Initialize Variables
//Input Data/Variables
classA=15; //In $
classB=12; //In $
classC=9; //In $
//Process or map the inputs to the outputs
//Display/Output all pertinent variables
cout<<"How many number of tickets were sold for seating class A?"<<endl;
cin>>classA;
cout<<"How many number of tickets were sold for seating class B?"<<endl;
cin>>classB;
cout<<"How many number of tickets were sold for seating class C?"<<endl;
cin>>classC;
profit=classA+classB+classC;
cout<<"The total amount of income generated through ticket sales is "<<profit<<endl;
//Exit the program
return 0;
} | true |
175e42e117030141cde0043eb1341b439f6826eb | C++ | AndreyKulish/arduino | /main/sasha/Svarka/_4/_4.ino | UTF-8 | 797 | 2.65625 | 3 | [] | no_license | boolean flag = true;
void setup() {
pinMode(4,INPUT);
pinMode(5,INPUT);
pinMode(6,OUTPUT);
digitalWrite(6,LOW);
}
void loop() {
for ( int x = 0; x < 100; x++){
work();
}
delay(5000);// если нужно убрать паузу, удали это
}
void work(){
for( int i = 0; i < 5; i++){
if(digitalRead(5) == HIGH){
delay(7);// 0 до 10 задержка сигнала
digitalWrite(6,HIGH);
delayMicroseconds(100);// длина импульса 1-2
digitalWrite(6,LOW);
while(digitalRead(5) == HIGH);
}
//if(digitalRead(4) == HIGH){
//delay(7);// 0 до 10 задержка сигнала
// digitalWrite(6,HIGH);
// delayMicroseconds(100);// длина импульса 1-2
//digitalWrite(6,LOW);
// while(digitalRead(4) == HIGH);
// }
}
}
| true |
8eacfd845fea26971f598d91a0772af71c731816 | C++ | perewodchik/contests | /#1/E/E.cpp | WINDOWS-1251 | 319 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
/* A B*/
int main()
{
int a,b;
int max;
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> a >> b;
if (a>b)
{
max = a;
}
else
{
max = b;
}
cout << max;
}
| true |
db890410504085c80b26de2d1a7e15bbf7771ed4 | C++ | IKholopov/shishkin_forest | /IR/Expressions/Temp.cpp | UTF-8 | 673 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include "Temp.h"
namespace IR {
namespace {
static int counter = 0;
}
Temp::Temp(std::string name, const Coords& coords, int uniqueId) :
Id(counter++),
localId(0),
name(name),
info(AI_Name),
unique(uniqueId != -1),
coords(coords)
{
if(unique) {
Id = uniqueId;
localId = uniqueId;
}
}
Temp::Temp(int localId, const Coords& coords) :
Id(counter++),
localId(localId),
name(""),
info(AI_Id),
unique(false),
coords(coords)
{
}
Temp::Temp(const Temp &temp):
Id(temp.Id),
localId(temp.localId),
name(temp.name),
info(temp.info),
unique(temp.unique),
coords(temp.coords)
{
}
}
| true |
75566206aa363336ff66b7bdac7a815bd52d521e | C++ | manohar2000/DSA_450 | /Graphs/CreatingaGraph.cpp | UTF-8 | 988 | 3.375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
template<typename T>
class Graph
{
public:
map<T, vector< pair<T,int> > > adjList;
void addNode(T a, T b,int weight, bool bidirec=false)
{
adjList[a].push_back(make_pair(b,weight));
if(bidirec) adjList[b].push_back(make_pair(a,weight));
}
void printNodes()
{
for(auto node:adjList )
{
cout<<node.first<<"-->";
// vector<pair<T,int>> :: iterator connectedNode;
for(auto connectedNode: node.second)
{
cout<<"{"<<connectedNode.first<<","<<connectedNode.second<<"}"<<",";
}
cout<<endl;
}
}
};
int main()
{
Graph<int> g;
g.addNode(1,2,10,true);
g.addNode(1,3,12);
g.addNode(2,4,14);
g.addNode(3,2,16);
g.addNode(3,4,18,true);
g.printNodes();
return 0;
} | true |
38f85108aabf519b72db0d1ea318ffbe9dc3351b | C++ | pkchen1129/Cpp_interview | /k_in_a_group.cpp | UTF-8 | 1,334 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool distance_smaller_k (vector<int> p1, vector<int> p2, int k) {
double distance = (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]) + (p1[2] - p2[2])*(p1[2] - p2[2]);
return distance <= k*k;
}
void graph_DFS (vector<vector<int>> input, int k) {
vector<vector<int>> graph(input.size(), vector<int>()); // List of indices
vector<vector<int>> ans; // List of points
vector<bool> visited(input.size());
// Construct the graph
for (int i = 0 ; i < input.size() ; ++i) {
for (int j = i ; j < input[0].size() ; ++j) {
if (distance_smaller_k(input[i], input[j], k)) {
graph[i].push_back(j);
}
}
}
for (int i = 0 ; i < input.size() ; ++i) {
for (int j = 0 ; j < input[i].size() ; ++j) {
dfs(graph, ans, visited, input[i][j]);
}
ans.push_back({});
}
}
void dfs(vector<vector<int>>& graph, vector<vector<int>>& ans, vector<bool>& visited, int index) {
if (visited[index]) return;
visited[index] = true;
ans.back().push_back(index);
for (int i = 0 ; i < graph[index].size() ; ++i) {
if (visited[graph[index][i]]) continue;
dfs(graph, ans, visited, graph[index][i]);
}
} | true |
2a952711805b1dd27c49793804d4c7b904bf67c1 | C++ | pawelskrzy/auto_diff | /AD.h | UTF-8 | 2,941 | 2.875 | 3 | [] | no_license | #pragma once
#include <boost/numeric/ublas/matrix.hpp>
#include <map>
#include <vector>
#include <memory>
#include <iostream>
#include <atomic>
#include <boost/container/flat_map.hpp>
namespace AD {
class ResultType
{
public:
typedef boost::numeric::ublas::matrix<float> matrix;
private:
public:
float m_curValueFloat;
matrix m_curValueMatrix;
bool m_movedAway = false;
enum class CurValueType { scalar, matrix };
CurValueType m_curValueType = CurValueType::scalar;
ResultType();
ResultType(matrix&& m);
ResultType(const matrix& m);
ResultType(float v);
ResultType(int v);
ResultType(ResultType&& other);
ResultType(const ResultType& other);
void operator=(const ResultType& other);
void operator=(ResultType&& other);
~ResultType();
ResultType Transpose() const;
ResultType Product(const ResultType& other) const;
ResultType operator*(const ResultType& other) const;
// 1 to all
template<typename T>
ResultType ApplyUnaryFunc(const T& t) const
{
if (m_curValueType == CurValueType::scalar)
return t(m_curValueFloat);
//matrix m = m_curValueMatrix;
matrix m = MatrixCache::Get().GetMatrix(m_curValueMatrix.size1(), m_curValueMatrix.size2());
const size_t target = m.data().size();
for (size_t i = 0; i < target; i++)
{
m.data()[i] = t(m_curValueMatrix.data()[i]);
}
return m;
}
ResultType operator+(const ResultType& other) const;
ResultType operator-(const ResultType& other) const;
friend std::ostream & operator<<(std::ostream &os, const ResultType& p);
};
class Differentiable;
class Utils
{
public:
typedef boost::numeric::ublas::matrix<float> matrix;
// will create a matrix in 1 row
static matrix CreateRowMatrix(std::vector<float>&& v);
/**
{{0 1 2 3},
{2,3,4,1},
{4,4,4,4}} will create a 3x4 matrix
*/
static matrix CreateMatrix(std::vector<std::vector<float> >&&v);
};
class ExprWrapper
{
std::shared_ptr<Differentiable> m_holdedValue;
template<typename T, typename ...Args>
static std::shared_ptr<T> Make(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
public:
ExprWrapper() {}
ExprWrapper(ResultType v);
ExprWrapper(std::shared_ptr<Differentiable> diff);
ExprWrapper operator+(const ExprWrapper& other) const;
ExprWrapper operator+(const ResultType& other) const;
ExprWrapper operator-(const ExprWrapper& other) const;
ExprWrapper operator-(const ResultType& other) const;
ExprWrapper operator*(const ExprWrapper& other) const;
ExprWrapper operator*(const ResultType& other) const;
ExprWrapper MatrixMult(const ResultType& other) const;
ExprWrapper MatrixMult(const ExprWrapper& other) const;
ExprWrapper Sigmoid() const;
ExprWrapper Pow(int powValue) const;
ExprWrapper Softmax() const;
ResultType Calc();
ResultType GetGradBy(ExprWrapper& other);
void Update(ResultType&& newValue);
};
} | true |
49f46436af59e00eb0b71e7067986688f82770e8 | C++ | Nimor111/LuaCode | /src/ast/parser/parser.cc | UTF-8 | 6,807 | 3.078125 | 3 | [
"Apache-2.0"
] | permissive | #include "../../../include/parser/parser.h"
Parser::Parser(std::vector<Token> tokens)
: tokens_(tokens)
, at_(0)
{
}
std::vector<Stmt*> Parser::Parse()
{
try {
std::vector<Stmt*> statements;
while (!End()) {
statements.push_back(Declaration());
}
return statements;
} catch (ParseError const& e) {
return std::vector<Stmt*>();
}
}
Stmt* Parser::Declaration()
{
if (Match(std::vector<TokenType> { IDENT }) && Match(std::vector<TokenType> { ASSIGN })) {
return VarDeclaration();
}
// if we've consumed an ident but it's not a var decl
if (this->at_) {
this->at_--;
}
return Statement();
}
Stmt* Parser::VarDeclaration()
{
this->at_--;
// Get name
auto name = Previous();
// consume '='
Advance();
auto value = Expression();
return new VarStmt(name, value);
}
Stmt* Parser::Statement()
{
return ExpressionStatement();
}
Stmt* Parser::ExpressionStatement()
{
auto expr = Expression();
auto s = new ExprStmt(expr);
return s;
}
Expr* Parser::Expression()
{
return Or();
}
Expr* Parser::Or()
{
auto expr = And();
std::vector<TokenType> tokens = { OR };
while (Match(tokens)) {
auto op = Previous();
auto right = And();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::And()
{
auto expr = Comparison();
std::vector<TokenType> tokens = { AND };
while (Match(tokens)) {
auto op = Previous();
auto right = Comparison();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::Comparison()
{
auto expr = BitOr();
std::vector<TokenType> tokens = { LT, GT, LTE, GTE, DIFF, EQ };
while (Match(tokens)) {
auto op = Previous();
auto right = BitOr();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::BitOr()
{
auto expr = BitAnd();
std::vector<TokenType> tokens = { BIT_OR };
while (Match(tokens)) {
auto op = Previous();
auto right = BitAnd();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::BitAnd()
{
auto expr = Shift();
std::vector<TokenType> tokens = { BIT_AND };
while (Match(tokens)) {
auto op = Previous();
auto right = Shift();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::Shift()
{
auto expr = Concat();
std::vector<TokenType> tokens = { LEFT_SHIFT, RIGHT_SHIFT };
while (Match(tokens)) {
auto op = Previous();
auto right = Concat();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::Concat()
{
auto expr = AddSub();
std::vector<TokenType> tokens = { CONCAT };
while (Match(tokens)) {
auto op = Previous();
auto right = AddSub();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::AddSub()
{
auto expr = MulDivMod();
std::vector<TokenType> tokens = { PLUS, MINUS };
while (Match(tokens)) {
auto op = Previous();
auto right = MulDivMod();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::MulDivMod()
{
auto expr = Pow();
std::vector<TokenType> tokens = { MUL, DIV, FLOOR_DIV, MOD };
while (Match(tokens)) {
auto op = Previous();
auto right = Pow();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::Pow()
{
auto expr = Unary();
std::vector<TokenType> tokens = { POW };
while (Match(tokens)) {
auto op = Previous();
auto right = Unary();
expr = new BinExpr(expr, op, right);
}
return expr;
}
Expr* Parser::Unary()
{
// TODO scanner handle minus
std::vector<TokenType> tokens = { NOT, LEN };
if (Match(tokens)) {
auto op = Previous();
auto right = Unary();
auto u = new UnaryExpr(op, right);
return u;
}
return Primary();
}
Expr* Parser::Primary()
{
if (Match(std::vector<TokenType> { FALSE })) {
auto e = new LiteralExpr(0);
return e;
}
if (Match(std::vector<TokenType> { TRUE })) {
auto e = new LiteralExpr(1);
return e;
}
if (Match(std::vector<TokenType> { NIL })) {
auto e = new LiteralExpr(-1);
return e;
}
if (Match(std::vector<TokenType> { NUMBER })) {
auto e = new NumberExpr(std::get<double>(Previous().literal()));
return e;
}
if (Match(std::vector<TokenType> { STRING })) {
auto e = new StringExpr(std::get<std::string>(Previous().literal()));
return e;
}
if (Match(std::vector<TokenType> { IDENT })) {
auto e = new VarExpr(Previous());
return e;
}
if (Match(std::vector<TokenType> { LEFT_PAREN })) {
auto e = Expression();
Consume(RIGHT_PAREN, "Expect ')' after expression.");
auto ge = new GroupingExpr(e);
return ge;
}
throw Error(Peek(), "Expected expression.");
}
bool Parser::Match(std::vector<TokenType> const& tokens)
{
for (auto const& tt : tokens) {
// check if current token is any of the given types
if (Check(tt)) {
Advance();
return true;
}
}
return false;
}
bool Parser::Check(TokenType type)
{
if (End()) {
return false;
}
return Peek().type() == type;
}
Token Parser::Advance()
{
if (!End()) {
this->at_++;
}
return Previous();
}
bool Parser::End()
{
return Peek().type() == T_EOF;
}
Token Parser::Peek()
{
if (this->at_ < this->tokens_.size()) {
return this->tokens_[this->at_];
}
return Token(T_EOF, "", "", 0);
}
Token Parser::Previous()
{
if (this->at_ < this->tokens_.size()) {
return this->tokens_[this->at_ - 1];
}
return Token(T_EOF, "", "", 0);
}
Token Parser::Consume(TokenType type, std::string message)
{
if (Check(type)) {
return Advance();
}
throw Error(Peek(), message);
}
ParseError Parser::Error(Token token, std::string message)
{
Error::MakeError(token, message);
return ParseError();
}
// If parser encounters an error, Synchronize will skip tokens until it gets to the next statement
void Parser::Synchronize()
{
Advance();
while (!End()) {
if (Previous().type() == SEMICOLON) {
return;
}
switch (Peek().type()) {
case FUNCTION:
case WHILE:
case REPEAT:
case IF:
case FOR:
case BREAK:
case LOCAL:
case DO:
return;
default:
Advance();
break;
}
}
}
| true |
58edb70c7308bf4f9b63867beddfe98a0d12d8cc | C++ | gdding/MARC | /src/utils/Utility.cpp | GB18030 | 7,927 | 2.671875 | 3 | [] | no_license | #include "Utility.h"
#include "kbhit.h"
#include "DirScanner.h"
#include "AppRunner.h"
bool Exec(const char* cmd)
{
return Exec(cmd, -1);
}
bool Exec(const char* cmd, int nTimeout)
{
string sCommand(cmd);
#if !RUN_APP_WITH_FORK
int nCmdRet = system(sCommand.c_str());
return true;
#else
CAppRunner runner;
time_t nStartTime = time(0);
if(!runner.ExecuteApp(sCommand.c_str()))
{
return false;
}
while(runner.IsAppRunning())
{
if(nTimeout > 0 && time(0) - nStartTime > nTimeout)
{
runner.KillApp();
break;
}
Sleep(200);
}
int nAppExitCode = runner.GetAppExitCode();
switch(nAppExitCode)
{
case APP_EXIT_CODE_TIMEOUT:
return false;
case APP_EXIT_CODE_ABORT:
return false;
default:
return true;
};
#endif
}
string getFilePath(const char* sFilename)
{
string sFilePath = "";
int nFilenameLen = (int)strlen(sFilename);
if(nFilenameLen == 0) return sFilePath;
int nEnd = nFilenameLen - 1;
while(nEnd > 0)
{
if(sFilename[nEnd] == '/' || sFilename[nEnd] == '\\')
{
break;
}
nEnd--;
}
for(int i = 0; i <= nEnd; i++)
{
sFilePath += sFilename[i];
}
return sFilePath;
}
void NormalizePath(char* dir, bool bTail)
{
size_t len = strlen(dir);
#ifdef _WIN32
for(size_t m=0; m<len; m++)
{
if(dir[m]=='/') dir[m]='\\';
}
if(bTail)
{
if(dir[len-1] != '\\')
{
dir[len] = '\\';
dir[len+1] = 0;
}
}
#else
for(size_t m=0; m<len; m++)
{
if(dir[m]=='\\') dir[m]='/';
}
if(bTail)
{
if(dir[len-1] != '/')
{
dir[len] = '/';
dir[len+1] = 0;
}
}
#endif
}
void NormalizePath(string& dir, bool bTail)
{
size_t len = dir.length();
#ifdef _WIN32
for(size_t m=0; m<len; m++)
{
if(dir[m]=='/') dir[m]='\\';
}
if(bTail)
{
if(dir[len-1] != '\\')
{
dir += '\\';
}
}
#else
for(size_t m=0; m<len; m++)
{
if(dir[m]=='\\') dir[m]='/';
}
if(bTail)
{
if(dir[len-1] != '/')
{
dir += '/';
}
}
#endif
}
bool CreateFilePath(const char* path)
{
if(path==NULL || path[0]==0) return false;
string sCurPath("");
int i = 0;
char ch = path[i];
while(ch != 0)
{
sCurPath += ch;
if(ch == '/' || ch == '\\')
{
if(!DIR_EXIST(sCurPath.c_str()) && (MAKE_DIR(sCurPath.c_str()) != 0))
{
return false;
}
}
ch = path[++i];
}
return true;
}
bool KeyboardHit(char ch)
{
if (_kbhit())
{
if (_getch() == ch)
{
return true;
}
}
return false;
}
bool KeyboardHit(const string& s)
{
string sHit;
while(_kbhit())
{
sHit += _getch();
}
if(!sHit.empty())
{
printf("You pressed: %s\n", sHit.c_str());
if(sHit.find(s) != string::npos) return true;
}
return false;
}
bool CreateFlagFile(const char* filepath)
{
FILE *fp = fopen(filepath, "wb");
if(fp == NULL) return false;
fclose(fp);
return true;
}
void deleteFile(const char* file)
{
if(file == NULL || file[0] == 0) return ;
char chDelCmd[1024] = {0};
#ifdef _WIN32
sprintf(chDelCmd, "DEL %s /F /Q", file);
#else
sprintf(chDelCmd, "rm -rf %s", file);
#endif
system(chDelCmd);
}
void deleteDir(const char* path)
{
char chDelCmd[1024] = {0};
#ifdef _WIN32
sprintf(chDelCmd, "rd /S /Q %s", path);
#else
sprintf(chDelCmd, "rm -rf %s", path);
#endif
system(chDelCmd);
}
void CleanDir(const char* path)
{
char chCmd[1024] = {0};
#ifdef _WIN32
char s[1024] = {0};
strcpy(s, path);
NormalizePath(s);
RMDIR(s);
sprintf(chCmd, "del %s*.* /s/f/q", s);
#else
sprintf(chCmd, "rm -rf %s*", path);
#endif
system(chCmd);
}
#ifdef _WIN32
void RMDIR(const char *pPath)
{
CDirScanner ds(pPath);
const vector<string>& dirs = ds.GetDirList();
for(size_t i=0; i<dirs.size(); i++)
{
char chCmd[1024] = {0};
sprintf(chCmd, "rd /S /Q %s%s", pPath, dirs[i].c_str());
system(chCmd);
}
}
#endif
void SplitCmdStringBySpace(const char* str, vector<string>& result)
{
bool bQuotationMark = false;
string s = "";
for(int i = 0; str[i] != 0; i++)
{
char c = str[i];
if(c == '"')
{
bQuotationMark = !bQuotationMark;
}
if(!bQuotationMark)
{
if(c == ' ' || c == '\t')
{
if(!s.empty()) result.push_back(s);
s = "";
continue;
}
}
s += c;
}
if(!s.empty()) result.push_back(s);
}
//ıļжȡkey/valueϢ
//ÿиʽ[KEY]\t[VALUE]
//KEYΪַVALUEΪ
//ضȡɹʧܷ-1
int ReadKeyValues(const char* sFileName, vector<pair<string,int> >& result)
{
FILE *fp = fopen(sFileName, "rb");
if(fp == NULL) return -1;
char sLine[1024];
while (fgets(sLine, 1024, fp))
{
char sKey[512] = "";
int nValue = 0;
if(sscanf(sLine,"%s %d", sKey, &nValue) != 2) continue;
if (sKey[0] == 0) continue;
result.push_back(make_pair(sKey, nValue));
}
fclose(fp);
return (int)result.size();
}
int ReadKeyValues(const char* sFileName, vector<pair<string,string> >& result)
{
FILE *fp = fopen(sFileName, "rb");
if(fp == NULL) return -1;
char sLine[1024];
while (fgets(sLine, 1024, fp))
{
char sKey[512] = {0};
char sValue[512] = {0};
if(sscanf(sLine,"%s %s", sKey, sValue) != 2) continue;
if (sKey[0] == 0) continue;
result.push_back(make_pair(sKey, sValue));
}
fclose(fp);
return (int)result.size();
}
string formatDateTime(time_t nTime, int nFormat)
{
struct tm stTime = *localtime(&nTime);
char sBuffer[256] = {0};
switch (nFormat)
{
case 0:
_snprintf(sBuffer,
sizeof(sBuffer),
"%04d-%02d-%02d %02d:%02d:%02d",
stTime.tm_year+1900,
stTime.tm_mon+1,
stTime.tm_mday,
stTime.tm_hour,
stTime.tm_min,
stTime.tm_sec);
break;
case 1:
_snprintf(sBuffer,
sizeof(sBuffer),
"%04d%02d%02d%02d%02d%02d",
stTime.tm_year+1900,
stTime.tm_mon+1,
stTime.tm_mday,
stTime.tm_hour,
stTime.tm_min,
stTime.tm_sec);
break;
case 2:
_snprintf(sBuffer,
sizeof(sBuffer),
"%04d%02d%02d",
stTime.tm_year+1900,
stTime.tm_mon+1,
stTime.tm_mday);
break;
default:
break;
};
return string(sBuffer);
}
int getCurDate()
{
struct tm* ptime;
time_t now;
time(&now);
ptime = localtime(&now);
int nDate= (ptime->tm_year+1900)*10000 + (ptime->tm_mon+1)*100 + ptime->tm_mday;
return nDate;
}
int getFileSize(const char* sFilename)
{
int nFileSize = -1;
FILE *fp = fopen(sFilename,"rb");
if (fp != NULL)
{
fseek(fp, 0, SEEK_END);
nFileSize = ftell(fp);
fclose(fp);
}
return nFileSize;
}
string getFileName(const string& sFilePath, bool bExtension)
{
string sFileName = "";
int i = (int)sFilePath.length() - 1;
for(; i >= 0; i--)
{
if(sFilePath[i] == '/' || sFilePath[i] == '\\') break;
}
for(int j = i+1; j < (int)sFilePath.length(); j++)
{
sFileName += sFilePath[j];
}
if(!bExtension)
{
string::size_type pos = sFileName.rfind(".");
if(pos != string::npos)
{
sFileName = string(sFileName.c_str(), pos);
}
}
return sFileName;
}
int readFile(const char *sFilename, char* & pBuffer)
{
FILE *fp = fopen(sFilename,"rb");
if (fp == NULL) return -1;
fseek(fp, 0, SEEK_END);
int nFileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
pBuffer = (char*)calloc(nFileSize+1, sizeof(char));
if(pBuffer == NULL)
{
fclose(fp);
return -1;
}
fread(pBuffer, 1, nFileSize, fp);
pBuffer[nFileSize]=0;
fclose(fp);
return nFileSize;
}
int readFile(const char *sFilename, int nOffset, char* pBuffer, int nBufSize)
{
int nReadSize = 0;
FILE *fp = fopen(sFilename, "rb");
if (fp != NULL)
{
fseek(fp, 0, SEEK_END);
int nFileSize = ftell(fp);
if(nOffset < nFileSize)
{
nReadSize = (nFileSize-nOffset<nBufSize ? nFileSize-nOffset:nBufSize);
fseek(fp, nOffset, SEEK_SET);
fread(pBuffer, 1, nReadSize, fp);
}
fclose(fp);
}
return nReadSize;
}
string GenRandomString(int n)
{
static unsigned int seed=1;
srand((unsigned int)time(0) + (seed++));
string s;
const int RANDOM_SET_SIZE = 36;
static char sChars[]="0123456789abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < n; i++)
{
s += sChars[rand()%RANDOM_SET_SIZE];
}
return s;
}
| true |
591315c128e82b645e64cba07b46da9f79b8611e | C++ | JakKopec/Algorithms-data-structures-and-numerical-methods | /Numerical-methods/Interpolacja Lagrangea/InterpolacjaLagrangea.cpp | UTF-8 | 1,894 | 3.203125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
#include<stdlib.h>
using namespace std;
void interpolacja_lagrangea(void)
{
fstream file;
file.open("InterpolacjaLagrangea.txt",ios::in);
if(file.good()==false)
{cout<<"Blad pliku tekstowego!\n";}
string temp;
int ilosc_wezlow;
file>>ilosc_wezlow;
//ilosc_wezlow=atoi(temp.c_str());
//pierwsza linia z pliku - ilosc punktow i jedna linia odstepu
getline(file,temp);
getline(file,temp);
//kolejne linie - wezel,wartosc funkcji,wezel...
double wezly[ilosc_wezlow];
double wartosci_funkcji[ilosc_wezlow];
double obliczenia[ilosc_wezlow];
for(int a=0;a<ilosc_wezlow;a++)
{
getline(file,temp);
wezly[a]=atoi(temp.c_str());
//wezly[a]=atol(temp);
getline(file,temp);
wartosci_funkcji[a]=atoi(temp.c_str());
//wartosci_funkcji[a]=atol(temp);
}
file.close();
double argument;
cout<<"Podaj punkt dla ktorego trzeba obliczyc wartosc wielomianu interpolacyjnego ";cin>>argument;cout<<endl;
for(int e=0;e<ilosc_wezlow;e++)
{cout<<wezly[e]<<"\t\t"<<wartosci_funkcji[e]<<endl;}
for(int b=0;b<ilosc_wezlow;b++)
{
obliczenia[b]=wartosci_funkcji[b];
//licznik ze wzoru na L(x)
for(int c=0;c<ilosc_wezlow;c++)
{
if(wezly[b]!=wezly[c])
{obliczenia[b]=obliczenia[b]*(argument-wezly[c]);}
}
//mianownik ze wzoru na L(x)
for(int c=0;c<ilosc_wezlow;c++)
{
if(wezly[b]!=wezly[c])
{obliczenia[b]=(obliczenia[b]/(wezly[b]-wezly[c]));}
}
}
double suma_tablicy_obliczenia=0;
for(int d=0;d<ilosc_wezlow;d++)
{//liczenie Ln(x)
suma_tablicy_obliczenia=suma_tablicy_obliczenia+obliczenia[d];
}
cout<<"\nDla argumentu x="<<argument<<" wielomian interpolacyjny przyjmuje wartosc "<<suma_tablicy_obliczenia<<endl;
}
int main()
{
interpolacja_lagrangea();
return 0;
}
| true |
1bb4295dea32aaa1a82f031b0e0b7d73ab54584a | C++ | stankogavric/Snake | /main.cpp | UTF-8 | 15,364 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <SDL2/SDL.h> // Glavna SDL biblioteka
#include <SDL2/SDL_ttf.h> // SDL biblioteka za prikaz teksta
using namespace std;
void renderPlayer(SDL_Renderer* renderer, SDL_Rect player, int x, int y, int scale, vector<int> tailX, vector<int> tailY, int tailLength)
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
player.w = scale;
player.h = scale;
// Prolazi kroz x i y koordinate blokova repa zmije i prikazuje ih
for (int i = 0; i < tailLength; i++)
{
player.x = tailX[i];
player.y = tailY[i];
SDL_RenderFillRect(renderer, &player);
}
player.x = x;
player.y = y;
SDL_RenderFillRect(renderer, &player);
}
void renderFood(SDL_Renderer* renderer, SDL_Rect food)
{
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &food);
}
void renderScore(SDL_Renderer* renderer, int tailLength, int scale, int wScale)
{
SDL_Color Black = { 0, 0, 0 };
// Ucitavanje fonta za prikaz teksta
TTF_Font* font = TTF_OpenFont((char*)"arial.ttf", 10);
if (font == NULL)
{
cout << "Font loading error" << endl;
return;
}
SDL_Surface* score = TTF_RenderText_Solid(font, (string("Score: ") + to_string(tailLength * 10)).c_str(), Black);
SDL_Texture* scoreMessage = SDL_CreateTextureFromSurface(renderer, score);
SDL_Rect scoreRect;
scoreRect.w = 100;
scoreRect.h = 30;
scoreRect.x = ((scale*wScale) / 2) - (scoreRect.w / 2);
scoreRect.y = 0;
SDL_RenderCopy(renderer, scoreMessage, NULL, &scoreRect);
TTF_CloseFont(font);
}
bool checkCollision(int foodx, int foody, int playerx, int playery)
{
if (playerx == foodx && playery == foody)
{
return true;
}
return false;
}
pair <int, int> getFoodSpawn(vector <int> tailX, vector <int> tailY, int playerX, int playerY, int scale, int wScale, int tailLength)
{
// Kreiranje validnog bloka hrane koji nije na blokovima zmije
bool valid = false;
int x = 0;
int y = 0;
srand(time(0));
x = scale*(rand() % wScale);
y = scale*(rand() % wScale);
valid = true;
// Provjera da li se hrana nalazi na nekom bloku zmije
for (int i = 0; i < tailLength; i++)
{
if ((x == tailX[i] && y == tailY[i]) || (x == playerX && y == playerY))
{
valid = false;
}
}
if (!valid)
{
pair <int, int> foodLoc;
foodLoc = make_pair(-100, -100);
return foodLoc;
}
pair <int, int> foodLoc;
foodLoc = make_pair(x, y);
return foodLoc;
}
void gameOver(SDL_Renderer* renderer, SDL_Event event, int scale, int wScale, int tailLength)
{
SDL_Color Red = { 255, 0, 0 };
SDL_Color White = { 255, 255, 255 };
SDL_Color Black = { 0, 0, 0 };
// Ucitavanje fonta za prikaz teksta
TTF_Font* font = TTF_OpenFont((char*)"arial.ttf", 10);
if (font == NULL)
{
cout << "Font loading error" << endl;
return;
}
SDL_Surface* gameover = TTF_RenderText_Solid(font, "Game Over", Red);
SDL_Surface* retry = TTF_RenderText_Solid(font, "Press Enter to retry", White);
SDL_Surface* score = TTF_RenderText_Solid(font, (string("Score: ") + to_string(tailLength * 10)).c_str(), Black);
SDL_Texture* gameoverMessage = SDL_CreateTextureFromSurface(renderer, gameover);
SDL_Texture* retryMessage = SDL_CreateTextureFromSurface(renderer, retry);
SDL_Texture* scoreMessage = SDL_CreateTextureFromSurface(renderer, score);
SDL_Rect gameoverRect;
SDL_Rect retryRect;
SDL_Rect scoreRect;
gameoverRect.w = 200;
gameoverRect.h = 100;
gameoverRect.x = ((scale*wScale) / 2)-(gameoverRect.w/2);
gameoverRect.y = ((scale*wScale) / 2)-(gameoverRect.h/2)-50;
retryRect.w = 300;
retryRect.h = 50;
retryRect.x = ((scale*wScale) / 2) - ((retryRect.w / 2));
retryRect.y = (((scale*wScale) / 2) - ((retryRect.h / 2))+150);
scoreRect.w = 100;
scoreRect.h = 30;
scoreRect.x = ((scale*wScale) / 2) - (scoreRect.w / 2);
scoreRect.y = 0;
SDL_RenderCopy(renderer, gameoverMessage, NULL, &gameoverRect);
SDL_RenderCopy(renderer, retryMessage, NULL, &retryRect);
SDL_RenderCopy(renderer, scoreMessage, NULL, &scoreRect);
TTF_CloseFont(font);
while (true)
{
SDL_RenderPresent(renderer);
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
exit(0);
}
if (event.key.keysym.scancode == SDL_SCANCODE_RETURN)
{
return;
}
}
}
}
void YouWin(SDL_Renderer* renderer, SDL_Event event, int scale, int wScale, int tailLength)
{
SDL_Color White = { 255, 255, 255 };
SDL_Color Black = { 0, 0, 0 };
SDL_Color Yellow = { 255, 255, 0 };
// Ucitavanje fonta za prikaz teksta
TTF_Font* font = TTF_OpenFont((char*)"arial.ttf", 10);
if (font == NULL)
{
cout << "Font loading error" << endl;
return;
}
SDL_Surface* gameover = TTF_RenderText_Solid(font, "You won!", Yellow);
SDL_Surface* retry = TTF_RenderText_Solid(font, "Press Enter to play again", White);
SDL_Surface* score = TTF_RenderText_Solid(font, (string("Score: ") + to_string(tailLength * 10)).c_str(), Black);
SDL_Texture* gameoverMessage = SDL_CreateTextureFromSurface(renderer, gameover);
SDL_Texture* retryMessage = SDL_CreateTextureFromSurface(renderer, retry);
SDL_Texture* scoreMessage = SDL_CreateTextureFromSurface(renderer, score);
SDL_Rect gameoverRect;
SDL_Rect retryRect;
SDL_Rect scoreRect;
gameoverRect.w = 200;
gameoverRect.h = 100;
gameoverRect.x = ((scale*wScale) / 2) - (gameoverRect.w / 2);
gameoverRect.y = ((scale*wScale) / 2) - (gameoverRect.h / 2) - 50;
retryRect.w = 300;
retryRect.h = 50;
retryRect.x = ((scale*wScale) / 2) - ((retryRect.w / 2));
retryRect.y = (((scale*wScale) / 2) - ((retryRect.h / 2)) + 150);
scoreRect.w = 100;
scoreRect.h = 30;
scoreRect.x = ((scale*wScale) / 2) - (scoreRect.w / 2);
scoreRect.y = 0;
SDL_RenderCopy(renderer, gameoverMessage, NULL, &gameoverRect);
SDL_RenderCopy(renderer, retryMessage, NULL, &retryRect);
SDL_RenderCopy(renderer, scoreMessage, NULL, &scoreRect);
TTF_CloseFont(font);
while (true)
{
SDL_RenderPresent(renderer);
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
exit(0);
}
if (event.key.keysym.scancode == SDL_SCANCODE_RETURN)
{
return;
}
}
}
}
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
if (TTF_Init() < 0)
{
cout << "Error: " << TTF_GetError() << endl;
}
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Event event;
SDL_Rect player;
player.x = 0;
player.y = 0;
player.h = 0;
player.w = 0;
// tailLength (duzina repa zmije) se uvecava svaki put kad zmija pojede hranu
int tailLength = 0;
// Vektori za cuvanje pozicija blokova repa zmije
vector<int> tailX;
vector<int> tailY;
int scale = 24;
int wScale = 24;
// Podrazumijevana pozicija igraca
int x = 0;
int y = 0;
int prevX = 0;
int prevY = 0;
bool up = false;
bool down = false;
bool right = false;
bool left = false;
bool inputThisFrame = false;
bool redo = false;
// Blok hrane
// x i y koordinate hrane dobijaju random vrijednosti
SDL_Rect food;
food.w = scale;
food.h = scale;
food.x = 0;
food.y = 0;
pair <int, int> foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
food.x = foodLoc.first;
food.y = foodLoc.second;
//Prikazuje prozor igrice
window = SDL_CreateWindow("Snake", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, scale*wScale+1, scale*wScale+1, SDL_WINDOW_RESIZABLE);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
// Odlaganje kretanja blokova
float time = SDL_GetTicks() / 100;
while (true) // Main loop (glavna petlja)
{
// Odlaganje kretanja blokova
float newTime = SDL_GetTicks() / 75; // Vrijednost 75 je brzina kojom se blokovi azuriraju
float delta = newTime - time;
time = newTime;
inputThisFrame = false;
if (tailLength >= 575)
{
YouWin(renderer, event, scale, wScale, tailLength);
x = 0;
y = 0;
up = false;
left = false;
right = false;
down = false;
tailX.clear();
tailY.clear();
tailLength = 0;
redo = false;
foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
if (food.x == -100 && food.y == -100)
{
redo = true;
}
food.x = foodLoc.first;
food.y = foodLoc.second;
}
// Kontrole
if (SDL_PollEvent(&event))
{
// Ako korisnik pokusa da izadje iz prozora, izadji iz programa
if (event.type == SDL_QUIT)
{
exit(0);
}
// Ako se pritisne taster
if (event.type == SDL_KEYDOWN && inputThisFrame == false)
{
// Provjeri koji taster je pritisnut i promjeni smjer u skladu s tim
if (down == false && event.key.keysym.scancode == SDL_SCANCODE_UP)
{
up = true;
left = false;
right = false;
down = false;
inputThisFrame = true;
}
else if (right == false && event.key.keysym.scancode == SDL_SCANCODE_LEFT)
{
up = false;
left = true;
right = false;
down = false;
inputThisFrame = true;
}
else if (up == false && event.key.keysym.scancode == SDL_SCANCODE_DOWN)
{
up = false;
left = false;
right = false;
down = true;
inputThisFrame = true;
}
else if (left == false && event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
{
up = false;
left = false;
right = true;
down = false;
inputThisFrame = true;
}
}
}
// Prethodna pozicija bloka igraca
prevX = x;
prevY = y;
// Kretanje igraca istom brzinom bez obzira na fps (broj slika po sekundi)
if (up)
{
y -= delta*scale;
}
else if (left)
{
x -= delta*scale;
}
else if (right)
{
x += delta*scale;
}
else if (down)
{
y += delta*scale;
}
if (redo == true)
{
redo = false;
foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
food.x = foodLoc.first;
food.y = foodLoc.second;
if (food.x == -100 && food.y == -100)
{
redo = true;
}
}
// Detekcija sudara, da li se igrac sudario s hranom?
if (checkCollision(food.x, food.y, x, y))
{
// Napravi novu hranu nakon sto se pojede
foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
food.x = foodLoc.first;
food.y = foodLoc.second;
if (food.x == -100 && food.y == -100)
{
redo = true;
}
tailLength++;
}
if (delta*scale == 24)
{
// Azurira velicinu i polozaj repa
// Ako velicina repa nija jednaka stvarnoj velicini, dodaje se jedan blok na kraj repa
if (tailX.size() != tailLength)
{
tailX.push_back(prevX);
tailY.push_back(prevY);
}
// Pomjera sve blokove s kraja repa ka pocetku
for (int i = 0; i < tailLength; i++)
{
if (i > 0)
{
tailX[i - 1] = tailX[i];
tailY[i - 1] = tailY[i];
}
}
// Ako je rep porastao, promijeni najblizu poziciju bloka repa u poziciju bloka igraca (prvi blok - glava)
if (tailLength > 0)
{
tailX[tailLength - 1] = prevX;
tailY[tailLength - 1] = prevY;
}
}
// Kraj igre ako igrac udari u rep, sve se resetuje
for (int i = 0; i < tailLength; i++)
{
if (x == tailX[i] && y == tailY[i])
{
gameOver(renderer, event, scale, wScale, tailLength);
x = 0;
y = 0;
up = false;
left = false;
right = false;
down = false;
tailX.clear();
tailY.clear();
tailLength = 0;
redo = false;
foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
if (food.x == -100 && food.y == -100)
{
redo = true;
}
food.x = foodLoc.first;
food.y = foodLoc.second;
}
}
//Kraj igre ako je igrac van granica, sve se resetuje
if (x < 0 || y < 0 || x > scale*wScale-scale || y > scale*wScale-scale)
{
gameOver(renderer, event, scale, wScale, tailLength);
x = 0;
y = 0;
up = false;
left = false;
right = false;
down = false;
tailX.clear();
tailY.clear();
tailLength = 0;
redo = false;
foodLoc = getFoodSpawn(tailX, tailY, x, y, scale, wScale, tailLength);
food.x = foodLoc.first;
food.y = foodLoc.second;
if (food.x == -100 && food.y == -100)
{
redo = true;
}
}
// Prikazuje sve
renderFood(renderer, food);
renderPlayer(renderer, player, x, y, scale, tailX, tailY, tailLength);
renderScore(renderer, tailLength, scale, wScale);
SDL_RenderDrawLine(renderer, 0, 0, 0, 24 * 24);
SDL_RenderDrawLine(renderer, 0, 24*24, 24 * 24, 24 * 24);
SDL_RenderDrawLine(renderer, 24*24, 24 * 24, 24*24, 0);
SDL_RenderDrawLine(renderer, 24*24, 0, 0, 0);
// Stavlja sve na ekran
SDL_RenderPresent(renderer);
// Popunjava prozor bojom (boja pozadine), ovo resetuje sve prije sledeceg frejma (kadra)
SDL_SetRenderDrawColor(renderer, 105, 105, 105, 255);
SDL_RenderClear(renderer);
}
SDL_DestroyWindow(window);
TTF_Quit();
SDL_Quit();
return 0;
}
| true |
0dcf0ca78f0355017a4d07c5b78c27593552aaf3 | C++ | TheNsBhasin/CodeChef | /LUCKY5/main.cpp | UTF-8 | 328 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t;
string str;
cin>>t;
while(t--)
{
cin>>str;
int counter=0;
for(int i=0;str[i];i++)
{
if(str[i]!='4' && str[i]!='7')
counter++;
}
cout<<counter<<endl;
}
return 0;
}
| true |
013b2ac91588245d80059d27fb38a1114d4dc68f | C++ | liangliangdeveloper/PTA_B_Problems | /B1014.cpp | UTF-8 | 1,160 | 2.828125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
using namespace std;
char S1[100],S2[100],S3[100],S4[100];
int min(int a,int b){
if(a<b) return a;
return b;
}
int main(){
scanf("%s", S1);
scanf("%s", S2);
scanf("%s", S3);
scanf("%s", S4);
int len1 = min(strlen(S1),strlen(S2));
int len2 = min(strlen(S3),strlen(S4));
bool first=true;
for(int i = 0; i < len1; i++){
if(S1[i]==S2[i]){
if(first&&S1[i]>='A'&&S1[i]<='G'){
first = false;
int date = S1[i]-'A'+1;
switch(date){
case 1: printf("MON"); break;
case 2: printf("TUE"); break;
case 3: printf("WED"); break;
case 4: printf("THU"); break;
case 5: printf("FRI"); break;
case 6: printf("SAT"); break;
case 7: printf("SUN"); break;
}
printf(" ");
} else if((S1[i]>='A'&&S1[i]<='N')||(S1[i]>='0'&&S1[i]<='9')){
if(first) continue;
int hour;
if(S1[i]>='0' && S1[i]<='9') hour = S1[i]-'0';
else hour = S1[i] - 'A' + 10;
printf("%02d:", hour);
break;
}
}
}
for(int i = 0; i < len2; i++) {
if(S3[i]==S4[i]&&((S3[i]>='A'&&S3[i]<='Z')||(S3[i]>='a'&&S3[i]<='z'))){
printf("%02d", i);
break;
}
}
return 0;
}
| true |
8d4c92ff5e5dba3188af51ce8c04294fe062a7f4 | C++ | jpd002/Play--Framework | /src/layout/LayoutBaseItem.cpp | UTF-8 | 1,125 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive | #include "layout/LayoutBaseItem.h"
using namespace Framework;
CLayoutBaseItem::CLayoutBaseItem(unsigned int preferredSize, unsigned stretch, const LayoutObjectPtr& object)
: m_preferredSize(preferredSize)
, m_stretch(stretch)
, m_object(object)
, m_key(-1)
{
SetRange(0, 0);
}
CLayoutBaseItem::CLayoutBaseItem(unsigned int preferredSize, unsigned int stretch, unsigned int key)
: m_preferredSize(preferredSize)
, m_stretch(stretch)
, m_key(key)
{
SetRange(0, 0);
}
LayoutObjectPtr CLayoutBaseItem::GetObject() const
{
return m_object;
}
unsigned int CLayoutBaseItem::GetKey() const
{
return m_key;
}
unsigned int CLayoutBaseItem::GetPreferredSize() const
{
return m_preferredSize;
}
unsigned int CLayoutBaseItem::GetStretch() const
{
return m_stretch;
}
unsigned int CLayoutBaseItem::GetRangeStart() const
{
return m_rangeStart;
}
unsigned int CLayoutBaseItem::GetRangeEnd() const
{
return m_rangeEnd;
}
void CLayoutBaseItem::SetRange(unsigned int start, unsigned int end)
{
// assert(nStart <= nEnd);
m_rangeStart = start;
m_rangeEnd = end;
}
| true |
e75749ef9a7a444d89868c9c5937836ca15473e2 | C++ | ZoranPandovski/al-go-rithms | /dp/Count_balanced_binarytree/cpp/balanced_trees.cpp | UTF-8 | 526 | 3.015625 | 3 | [
"CC0-1.0"
] | permissive |
// binary trees of height h.
#include <bits/stdc++.h>
#define mod 1000000007
using namespace std;
long long int countBT(int h) {
long long int dp[h + 1];
//base cases
dp[0] = dp[1] = 1;
for(int i = 2; i <= h; i++) {
dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%mod + dp[i - 1])%mod) % mod;
}
return dp[h];
}
// Driver program
int main()
{
int h = 3;
cout << "No. of balanced binary trees"
" of height h is: "
<< countBT(h) << endl;
} | true |
3fb3485b582482db8d3217c3c85943097ede0047 | C++ | lianvk/matrix_multiplication | /par1/par0/par0/par0/Source.cpp | UTF-8 | 788 | 3.21875 | 3 | [] | no_license | //#include <stdlib.h>
#include <chrono>
#include <iostream>
#define N 1000
void main()
{
typedef float elemtype;
static elemtype a[N][N];
static elemtype b[N][N];
static elemtype c[N][N];
for (int j1 = 0; j1 < N; j1++)
{
for (int j2 = 0; j2 < N; j2++)
{
a[j1][j2] = elemtype(rand());
b[j1][j2] = elemtype(rand());
c[j1][j2] = 0;
}
}
std::cout << "Multiplication started" << std::endl;
auto startTime = std::chrono::system_clock::now();
for (int j1 = 0; j1 < N; j1++)
{
for (int j2 = 0; j2 < N; j2++)
{
for (int j3 = 0; j3 < N; j3++)
{
c[j1][j2] += a[j1][j3] * b[j3][j2];
}
}
}
std::chrono::duration<double> delay = std::chrono::system_clock::now() - startTime;
std::cout << "Multiplication ended: delay = " << delay.count() << std::endl;
} | true |
bfe79c3dab9594c32dad9c0e2225fd4d09c9f0d6 | C++ | jarble/transpiler | /translated_functions/cpp/prolog.cpp | UTF-8 | 2,149 | 3.390625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <math.h>
namespace C_sharp{
namespace Convert{
template <class T> std::string ToString(T a){
return std::to_string(a);
}
}
}
namespace Python {
template <class T> void print(T a) {
std::cout << a << "\n";
}
template <class T> int abs(T a){
return std::abs(a);
}
template <class T> int len(T a){
return a.size();
}
template <class T> T __add__(T A,T B){
return A+B;
}
template <class T> T __mul__(T A,T B){
return A*B;
}
std::string type(std::string a){
return "str";
}
}
namespace Java{
namespace Integer{
std::string toString(int a){
return std::to_string(a);
}
}
namespace System{
namespace out{
template <class T> void println(T a) {
std::cout << a << "\n";
}
}
}
}
namespace Ruby{
template <class T> void puts(T A){
std::cout << A << "\n";
}
}
namespace PHP{
std::string gettype(int a){
return "integer";
}
std::string gettype(std::string a){
return "string";
}
std::string gettype(bool a){
return "bool";
}
template <typename T> void echo(T a){
Ruby::puts(a);
}
}
namespace Lua{
std::string type(std::string a){
return "string";
}
std::string type(bool a){
return "boolean";
}
std::string type(int a){
return "number";
}
}
namespace JavaScript{
template <typename T> class console {
public:
static void log(T a){
Ruby::puts(a);
}
};
template <typename T> class Math {
public:
static int round(T A){
return round(A);
}
static int floor(T A){
return floor(A);
}
};
}
namespace Prolog{
bool integer(int a){
return true;
}
template <typename T> void writeln(T a){
Ruby::puts(a);
}
}
int main ()
{
Ruby::puts(PHP::gettype(1));
Ruby::puts(PHP::gettype(2));
Ruby::puts(3);
JavaScript::console<std::string>::log("Length of a is:");
std::string a = "3";
JavaScript::console<int>::log(Python::len(a));
//JavaScript::console<std::string>::log(C_sharp::Convert::ToString(3));
Java::System::out::println(3);
//JavaScript::console<int>::log(JavaScript::Math<double>::round(4.5));
Prolog::writeln(Prolog::integer(3));
return 0;
}
| true |
fc80e95470c0feb7b12bdfd6a2e6a893e68f9ab8 | C++ | luqmanarifin/cp | /0-unclassified/lauk.cpp | UTF-8 | 882 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
map<string, int> num;
vector<string> parse(string s) {
vector<string> ret;
for(int i = 0; i < s.size(); ) {
while(s[i] == ' ' && i < s.size()) i++;
int j = i;
while(s[j] != '+' && j < s.size()) j++;
int to = j + 1;
j--;
while(s[j] == ' ' && j > i) j--;
ret.push_back(s.substr(i, j - i + 1));
i = to;
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
string buf;
getline(cin, buf);
string now = buf;
while(buf[0] != '!') {
if(buf[0] == '#') {
int i = 1;
while(buf[i] == ' ') i++;
now = buf.substr(i);
} else {
num[now]++;
}
getline(cin, buf);
}
while(getline(cin, buf)) {
long long ans = 1;
vector<string> ret = parse(buf);
for(auto it : ret) {
ans *= num[it];
}
printf("%lld\n", ans);
}
return 0;
}
| true |
377dbf7db31f68044d61d07981bbff331c3a2dea | C++ | jasha64/jasha64 | /2012/day8(5-12)/图案与数字的结合.cpp | GB18030 | 315 | 2.828125 | 3 | [
"MIT"
] | permissive | //nӦͼ
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int N,i,j;
cin>>N;
for (i=1;i<=N;i++)
{
for (j=1;j<=N-i;j++) cout<<" ";
for (j=1;j<=2*i-1;j++) cout<<"*";
cout<<endl;
}
system("pause");
return 0;
}
| true |
c2a5270978f44342c5f38525f4e10ccaab5d9702 | C++ | Oneinone/SteveBase | /SteveBase/include/utility/PowerDraw.hpp | UTF-8 | 8,941 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <misc/TypeAliases.hpp>
#include <vendor/imgui/imgui.h>
namespace SteveBase::Utility {
using namespace Misc;
struct PowerDraw {
struct StyleVar {
template<class Fn>
constexpr FORCEINLINE StyleVar(Fn &&fn, ImGuiStyleVar idx, float val) {
ImGui::PushStyleVar(idx, val);
fn();
ImGui::PopStyleVar();
}
};
struct ToolTip {
FORCEINLINE ToolTip(const char * toolTipOnHover) {
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip(toolTipOnHover);
}
}
};
struct TreeNode {
template<class Fn>
constexpr FORCEINLINE TreeNode(Fn &&fn, const char * text) {
if (ImGui::TreeNode(text)) {
fn();
ImGui::TreePop();
}
}
};
struct Text {
FORCEINLINE Text(const char * text) {
ImGui::Text(text);
}
FORCEINLINE Text(const char * text, const char * toolTipOnHover) : Text(text) {
ToolTip{ toolTipOnHover };
}
};
struct BulletText {
FORCEINLINE BulletText(const char * text) {
ImGui::BulletText(text);
}
FORCEINLINE BulletText(const char * text, const char * toolTipOnHover) : BulletText(text) {
ToolTip{ toolTipOnHover };
}
};
struct Combo {
template<class Fn>
constexpr FORCEINLINE Combo(Fn &&onClick, const char * name, List<const char *> &list, int &selected) {
const int saved = selected;
if (ImGui::Combo(name, &selected, list.data(), list.size())) {
if (selected == saved) { // no change in input
return; // invalidate the change
}
if (!onClick(selected, list[selected])) { // if the input was invalid
selected = saved; // invalidate and revert the selection to the value before
}
}
}
template<class Fn>
constexpr FORCEINLINE Combo(Fn &&onClick, const char * name, List<const char *> &list, int &selected, const char * toolTipOnHover) : Combo(onClick, name, list, selected) {
ToolTip{ toolTipOnHover };
}
};
struct Button {
template<class Fn>
constexpr FORCEINLINE Button(Fn &&onClick, const char * text, ImVec2 size) {
if (ImGui::Button(text, size)) {
onClick();
}
}
template<class Fn>
constexpr FORCEINLINE Button(Fn &&onClick, const char * text) : Button(onClick, text, {}) {
}
template<class Fn>
constexpr FORCEINLINE Button(Fn &&onClick, const char * text, ImVec2 size, const char * toolTipOnHover) : Button(onClick, text, size) {
ToolTip{ toolTipOnHover };
}
};
struct SmallButton {
template<class Fn>
constexpr FORCEINLINE SmallButton(Fn &&onClick, const char * text) {
if (ImGui::SmallButton(text)) {
if (onClick) {
onClick();
}
}
}
template<class Fn>
constexpr FORCEINLINE SmallButton(Fn &&onClick, const char * text, const char * toolTipOnHover) : SmallButton(onClick, text) {
ToolTip{ toolTipOnHover };
}
};
struct CheckBox {
FORCEINLINE CheckBox(const char *text, bool &check) {
ImGui::Checkbox(text, &check);
}
FORCEINLINE CheckBox(const char * text, bool &check, const char * toolTipOnHover) : CheckBox(text, check) {
ToolTip{ toolTipOnHover };
}
};
struct ChoiceBox {
template<class Fn>
constexpr FORCEINLINE ChoiceBox(Fn &&onClick, List<const char *> &list, int &selected) {
const int saved = selected;
if (ImGui::ListBox("", &selected, list.data(), list.size())) {
if (selected == saved) { // no change in input
return; // invalidate the change
}
if (!onClick(selected, list[selected])) { // if the input was invalid
selected = saved; // invalidate and revert the selection to the value before
}
}
}
template<class Fn>
constexpr FORCEINLINE ChoiceBox(Fn &&onClick, List<const char *> &list, int &selected, const char * toolTipOnHover) : ChoiceBox(onClick, list, selected) {
ToolTip{ toolTipOnHover };
}
};
struct Line {
struct Same {
FORCEINLINE Same() {
ImGui::SameLine();
}
};
};
struct Column {
template<class Fn>
constexpr FORCEINLINE Column(Fn &&fn, size_t count, bool border = false) {
ImGui::Columns(count, nullptr, border);
fn();
ImGui::Columns(1);
}
struct Next {
FORCEINLINE Next() {
ImGui::NextColumn();
}
};
};
struct Separator {
FORCEINLINE Separator() {
ImGui::Separator();
}
};
struct Begin {
template<class Fn>
constexpr FORCEINLINE Begin(Fn &&fn, const char * name, bool* p_open = NULL, ImGuiWindowFlags flags = 0) {
if (ImGui::Begin(name, p_open, flags)) {
fn();
ImGui::End();
}
}
template<class Fn>
constexpr FORCEINLINE Begin(Fn &&fn, const char * name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0) {
if (ImGui::Begin(name, p_open, size_on_first_use, bg_alpha, flags)) {
fn();
ImGui::End();
}
}
};
struct Child {
template<class Fn>
constexpr FORCEINLINE Child(Fn &&fn, const char * str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags extra_flags = 0) {
if (ImGui::BeginChild(str_id, size, border, extra_flags)) {
fn();
ImGui::EndChild();
}
}
};
struct MenuBar {
template <class Fn>
constexpr FORCEINLINE MenuBar(Fn &&fn) {
if (ImGui::BeginMenuBar()) {
fn();
ImGui::EndMenuBar();
}
}
};
struct Group {
template<class Fn>
constexpr FORCEINLINE Group(Fn &&fn) {
ImGui::BeginGroup();
fn();
ImGui::EndGroup();
}
};
struct Menu {
template<class Fn>
constexpr FORCEINLINE Menu(Fn &&fn, const char * id) {
if (ImGui::BeginMenu(id)) {
fn();
ImGui::EndMenu();
}
}
struct Item {
FORCEINLINE Item(const char * label, const char * shortcut, bool selected = false, bool enabled = true) {
ImGui::MenuItem(label, shortcut, selected, enabled);
}
template<class Fn>
constexpr FORCEINLINE Item(Fn &&fn, const char * label, const char * shortcut, bool selected = false, bool enabled = true) {
if (ImGui::MenuItem(label, shortcut, selected, enabled)) {
fn();
}
}
FORCEINLINE Item(const char * label, bool selected = false, bool enabled = true) {
ImGui::MenuItem(label, nullptr, selected, enabled);
}
template<class Fn>
constexpr FORCEINLINE Item(Fn &&fn, const char * label, bool selected = false, bool enabled = true) {
if (ImGui::MenuItem(label, nullptr, selected, enabled)) {
fn();
}
}
};
};
};
} | true |
b26ecf279fe85b342c3349df9059f3dd97162c32 | C++ | jxygzzy/Luogu | /P1111 修复公路.cpp | UTF-8 | 866 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int Set[1005];
struct code{
int x,y,z;
}codes[100005];
bool cmp(code a,code b)
{
return a.z<b.z;
}
int Find(int x){
return (Set[x]==x) ? x : (Set[x] = Find(Set[x]));
}
void Init(int cnt) { // 初始化并查集,cnt 是元素个数
for (int i=1; i<=cnt; i++)
Set[i]=i;
}
int main()
{
int n,m;
cin>>n>>m;
Init(n);
for(int i=1;i<=m;i++)
cin>>codes[i].x>>codes[i].y>>codes[i].z;
sort(codes+1,codes+m+1,cmp);
int num=0,maxtime=0;
for(int i=1;i<=m;i++)
{
int u=Find(codes[i].x);
int v=Find(codes[i].y);
if(u!=v){
Set[u]=v;
num++;
maxtime=max(maxtime,codes[i].z);
}
if(num>=n-1){
cout<<maxtime<<endl;
return 0;
}
}
cout<<-1<<endl;
return 0;
} | true |
9ce15e59c9182a21bcb100f33f8a1586781c1070 | C++ | GuoZhiyong/OBD-II | /src/Adapter/helloworld/src/adapter/ecumsg.cpp | UTF-8 | 7,316 | 2.859375 | 3 | [] | no_license | /**
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009-2016 ObdDiag.Net. All rights reserved.
*
*/
#include <adapter_inc/adaptertypes.h>
#include <adapter_inc/ecumsg.h>
#include <utility_inc/algorithms.h>
using namespace util;
const int HEADER_SIZE = 3;
class EcumsgISO9141 : public Ecumsg {
friend class Ecumsg;
public:
virtual void addHeaderAndChecksum();
virtual bool stripHeaderAndChecksum();
private:
EcumsgISO9141(uint32_t size) : Ecumsg(ISO9141, size) {
const uint8_t header[] = { 0x68, 0x6A, 0xF1 };
memcpy(header_, header, sizeof(header));
}
};
class EcumsgISO14230 : public Ecumsg {
friend class Ecumsg;
public:
virtual void addHeaderAndChecksum();
virtual bool stripHeaderAndChecksum();
private:
EcumsgISO14230(uint32_t size) : Ecumsg(ISO14230, size) {
const uint8_t header[] = { 0xC0, 0x33, 0xF1 };
memcpy(header_, header, sizeof(header));
}
};
class EcumsgVPW : public Ecumsg {
friend class Ecumsg;
public:
virtual void addHeaderAndChecksum();
virtual bool stripHeaderAndChecksum();
private:
EcumsgVPW(uint32_t size) : Ecumsg(VPW, size) {
const uint8_t header[] = { 0x68, 0x6A, 0xF1 };
memcpy(header_, header, sizeof(header));
}
};
class EcumsgPWM : public Ecumsg {
friend class Ecumsg;
public:
virtual void addHeaderAndChecksum();
virtual bool stripHeaderAndChecksum();
private:
EcumsgPWM(uint32_t size) : Ecumsg(PWM, size) {
const uint8_t header[] = { 0x61, 0x6A, 0xF1 };
memcpy(header_, header, sizeof(header));
}
};
/**
* Factory method for adapter protocol messages
* @param[in] type Message type
* @return The message instance
*/
Ecumsg* Ecumsg::instance(uint8_t type)
{
const uint32_t size = 255;
Ecumsg* instance = 0;
switch(type) {
case ISO9141:
instance = new EcumsgISO9141(size);
break;
case ISO14230:
instance = new EcumsgISO14230(size);
break;
case VPW:
instance = new EcumsgVPW(size);
break;
case PWM:
instance = new EcumsgPWM(size);
break;
}
if (instance) {
// if header
const ByteArray* bytes = AdapterConfig::instance()->getBytesProperty(PAR_HEADER_BYTES);
if (bytes->length)
instance->setHeader(bytes->data);
}
return instance;
}
/**
* Adds the checksum to ISO 9141/14230 message
* @param[in,out] data Data bytes
* @param[in,out] length Data length
*/
static void IsoAddChecksum(uint8_t* data, uint8_t& length)
{
uint8_t sum = 0;
for (int i = 0; i < length; i++) {
sum += data[i];
}
data[length++] = sum;
}
/**
* Strip the header from ISO9141/14230 or J1850 message
* @param[in,out] data Data bytes
* @param[in,out] length Data length
*/
static void StripHeader(uint8_t* data, uint8_t& length)
{
length -= HEADER_SIZE;
memmove(&data[0], &data[HEADER_SIZE], length);
}
/*
* Add the checksum to J1850 message
* @param[in,out] data Data bytes
* @param[in,out] length Data length
*/
static void J1850AddChecksum(uint8_t* data, uint8_t& length)
{
const uint8_t* ptr = data;
int len = length;
uint8_t chksum = 0xFF; // start with all one's
while (len--) {
int i = 8;
uint8_t val = *(ptr++);
while (i--) {
if (((val ^ chksum) & 0x80) != 0) {
chksum ^= 0x0E;
chksum = (chksum << 1) | 1;
}
else {
chksum = chksum << 1;
}
val = val << 1;
}
}
data[length++] = ~chksum;
}
/**
* Strip the checksum from J1850 message
* @param[in,out] data Data bytes
* @param[in,out] length Data length
*/
static void J1850StripChecksum(uint8_t* data, uint8_t& length)
{
length--;
}
/**
* Strip the checksum from ISO 9141/1423 message
* @param[in,out] data Data bytes
* @param[in,out] length Data length
*/
static void ISOStripChecksum(uint8_t* data, uint8_t& length)
{
length--;
}
/**
* Construct Ecumsg object
*/
Ecumsg::Ecumsg(uint8_t type, uint32_t size) : type_(type), length_(0), size_(size)
{
data_ = new uint8_t[size];
}
/**
* Destructor
*/
Ecumsg::~Ecumsg()
{
delete[] data_;
}
/**
* Get the string representation of message bytes
* @param[out] str The output string
*/
void Ecumsg::toString(string& str) const
{
to_ascii(data_, length_, str);
}
/**
* Set the message data bytes
* @param[in] data Data bytes
* @param[in] length Data length
*/
void Ecumsg::setData(const uint8_t* data, uint8_t length)
{
length_ = length;
memcpy(data_, data, length);
}
/**
* Set header bytes
* @param[in] header The header bytes
*/
void Ecumsg::setHeader(const uint8_t* header)
{
memcpy(header_, header, sizeof(header_));
}
/**
* Adds the header/checksum to ISO 9141 message
*/
void EcumsgISO9141::addHeaderAndChecksum()
{
// Shift data on 3 bytes to accommodate the header
memmove(&data_[HEADER_SIZE], &data_[0], length_);
length_ += HEADER_SIZE;
memcpy(&data_[0], header_, HEADER_SIZE);
IsoAddChecksum(data_, length_);
}
/**
* Adds the header/checksum to ISO 14230 message
*/
void EcumsgISO14230::addHeaderAndChecksum()
{
// Shift data on 3 bytes to accommodate the header
memmove(&data_[HEADER_SIZE], &data_[0], length_);
uint8_t len = length_;
length_ += HEADER_SIZE;
memcpy(&data_[0], header_, HEADER_SIZE);
// The length is in the 1st byte
data_[0] = (data_[0] & 0xC0) | len;
IsoAddChecksum(data_, length_);
}
/**
* Adds the header/checksum to J1850 VPW message
*/
void EcumsgVPW::addHeaderAndChecksum()
{
// Shift data on 3 bytes to accommodate the header
memmove(&data_[HEADER_SIZE], &data_[0], length_);
length_ += HEADER_SIZE;
memcpy(&data_[0], header_, HEADER_SIZE);
J1850AddChecksum(data_, length_);
}
/**
* Adds the header/checksum to J1850 PWM message
*/
void EcumsgPWM::addHeaderAndChecksum()
{
// Shift data on 3 bytes to accommodate the header
memmove(&data_[HEADER_SIZE], &data_[0], length_);
length_ += HEADER_SIZE;
memcpy(&data_[0], header_, HEADER_SIZE);
J1850AddChecksum(data_, length_);
}
/**
* Strips the header/checksum from ISO 9141 message
* @return true if header is valid, false otherwise
*/
bool EcumsgISO9141::stripHeaderAndChecksum()
{
StripHeader(data_, length_);
ISOStripChecksum(data_, length_);
return true;
}
/**
* Strips the header/checksum from ISO 14230 message
* @return true if header is valid, false otherwise
*/
bool EcumsgISO14230::stripHeaderAndChecksum()
{
StripHeader(data_, length_);
ISOStripChecksum(data_, length_);
return true;
}
/**
* Strips the header/checksum from J1850 VPW message
* @return true if header is valid, false otherwise
*/
bool EcumsgVPW::stripHeaderAndChecksum()
{
StripHeader(data_, length_);
J1850StripChecksum(data_, length_);
return true;
}
/**
* Strips the header/checksum from J1850 PWM message
* @return true if header is valid, false otherwise
*/
bool EcumsgPWM::stripHeaderAndChecksum()
{
StripHeader(data_, length_);
J1850StripChecksum(data_, length_);
return true;
}
| true |
08a85ff962655675e97e31d3db936a62373f82c0 | C++ | thomaslee0131/competitive-programming | /leetcode/weekly_162/1252.cpp | UTF-8 | 616 | 2.859375 | 3 | [] | no_license | class Solution {
public:
int cnt[50][50];
void add(int r, int c, int n, int m){
for(int i=0;i<n;i++){
cnt[i][c]++;
}
for(int i=0;i<m;i++){
cnt[r][i]++;
}
}
int oddCells(int n, int m, vector<vector<int>>& inds) {
for(auto& ind: inds){
int r = ind[0], c = ind[1];
add(r, c, n, m);
}
int ans = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(cnt[i][j] % 2 != 0){
ans++;
}
}
}
return ans;
}
};
| true |
7688da6bb809cf622f1f3ecaa8160de015f1807f | C++ | kjlau0112/ringfile | /src/varint.cc | UTF-8 | 1,012 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2014 Ross Kinder. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "varint.h"
#include <math.h>
int Varint::Read(const void * buffer) {
value_ = 0;
for (int shift = 0; shift < 10; ++shift) {
uint8_t byte = *(reinterpret_cast<const uint8_t *>(buffer) + shift);
value_ |= (static_cast<uint64_t>(byte & 0x7f) << (shift * 7));
if ((byte & 0x80) == 0) {
return shift + 1;
}
}
}
int Varint::ByteSize() const {
for (int shift = 0; shift < 10; ++shift) {
if (value_ < exp2((shift + 1) * 7)) {
return shift + 1;
}
}
}
void Varint::Write(void * buffer) const {
for (int shift = 0; shift < 10; ++shift) {
uint8_t * byte_ptr = reinterpret_cast<uint8_t *>(buffer) + shift;
uint8_t marker = 0x80;
if (value_ < exp2((shift + 1) * 7)) {
marker = 0;
}
*byte_ptr = ((value_ >> (shift * 7)) & 0x7f) | marker;
if (!marker) {
break;
}
}
}
| true |
0964c8f149aa8a7a95767c9f287efb47d96eaa89 | C++ | RishabhDevbanshi/C-Codes | /Inverse-Number.cpp | UTF-8 | 693 | 3.125 | 3 | [] | no_license | //Problem Link : https://www.youtube.com/watch?v=dbk42TKwk4M
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll n;
cin>>n;
string str = to_string(n); //int to string
vector<int> v;
for(char a : str)
{
int x = (int)a - 48; //char with numbers to int
v.push_back(x);
}
vector<int> ans(v.size());
reverse(v.begin(),v.end()); //to reverse a vector
int i=1;
for(int x: v)
{
ans[x-1]=i;
i++;
}
reverse(ans.begin(),ans.end());
str="";
for(int x : ans)
{
str.append(to_string(x)); //string to int and appending in string
}
cout<<str;
}
| true |
e16cd4c6c344ae836865cf5a6eeea9c3acb0414e | C++ | tomsksoft-llc/cis1-core-native | /include/os_interface.h | UTF-8 | 4,550 | 3.0625 | 3 | [
"MIT"
] | permissive | /*
* TomskSoft CIS1 Core
*
* (c) 2019 TomskSoft LLC
* (c) Mokin Innokentiy [mia@tomsksoft.com]
*
*/
#pragma once
#include <filesystem>
#include <string>
#include <memory>
#include <istream>
#include <boost/process.hpp>
#include "ifstream_interface.h"
#include "ofstream_interface.h"
#include "fs_entry_interface.h"
namespace cis1
{
/**
* \brief Interface for all os calls
*/
struct os_interface
{
virtual ~os_interface() = default;
/**
* \brief Makes clone of current os instance
* \return Cloned os instance
*/
virtual std::unique_ptr<os_interface> clone() const = 0;
/**
* \brief Environment var getter
* \return Environment var string if var exists empty string otherwise
* @param[in] name Variable name
*/
virtual std::string get_env_var(
const std::string& name) const = 0;
/**
* \brief Checks whether dir is directory
* @param[in] dir Path to fs entry
* @param[out] ec
*/
virtual bool is_directory(
const std::filesystem::path& dir,
std::error_code& ec) const = 0;
/**
* \brief Check whether fs entry exists
* @param[in] path Path to entry
* @param[out] ec
*/
virtual bool exists(
const std::filesystem::path& path,
std::error_code& ec) const = 0;
/*
virtual polymorphic_range<fs_entry_interface> directory_iterator(
const std::filesystem::path& path) const = 0;
*/
/**
* \brief Getter for directory entries
* \return Array of fs_entries in directory
* @param[in] path Path to directory
*/
virtual std::vector<
std::unique_ptr<fs_entry_interface>> list_directory(
const std::filesystem::path& path) const = 0;
/**
* \brief Makes new directory
* \return true is directory created successfully false otherwise
* @param[in] dir Path to directory
* @param[out] ec
*/
virtual bool create_directory(
const std::filesystem::path& dir,
std::error_code& ec) const = 0;
/**
* \brief Copies fs entry
* @param[in] from Path to source fs entry
* @param[in] to Path to destination fs entry
* @param[out] ec
*/
virtual void copy(
const std::filesystem::path& from,
const std::filesystem::path& to,
std::error_code& ec) const = 0;
/**
* \brief Open file for reading
* @param[in] path Path to file
* @param[in] mode Open mode default is std::ios_base::in
*/
virtual std::unique_ptr<ifstream_interface> open_ifstream(
const std::filesystem::path& path,
std::ios_base::openmode mode = std::ios_base::in) const = 0;
/**
* \brief Open file for writing
* @param[in] path Path to file
* @param[in] mode Open mode default is std::ios_base::out
*/
virtual std::unique_ptr<ofstream_interface> open_ofstream(
const std::filesystem::path& path,
std::ios_base::openmode mode = std::ios_base::out) const = 0;
/**
* \brief Creates child process and detaches it
* @param[in] start_dir Dir where process will be executed
* @param[in] executable
* @param[in] args Args passed to process
* @param[in] env Environment passed to process
*/
virtual void spawn_process(
const std::string& start_dir,
const std::string& executable,
const std::vector<std::string>& args,
boost::process::environment env) const = 0;
/**
* \brief Remove fs entry (except for non-empty dir)
* @param[in] path Path to fs entry
* @param[out] ec
*/
virtual void remove(
const std::filesystem::path& path,
std::error_code& ec) const = 0;
/**
* \brief Remove fs entry
* @param[in] path Path to fs entry
* @param[out] ec
*/
virtual void remove_all(
const std::filesystem::path& path,
std::error_code& ec) const = 0;
/**
* \brief Checks fs entry is executable
* @param[in] path Path to fs entry
* @param[out] ec
*/
virtual bool is_executable(
const std::filesystem::path& path,
std::error_code& ec) const = 0;
/**
* \brief Makes fs entry executable
* @param[in] path Path to fs entry
* @param[out] ec
*/
virtual void make_executable(
const std::filesystem::path& path,
std::error_code& ec) const = 0;
};
} // namespace cis1
| true |
5d1f0597ce802d2f023c6de9f88e2286602f78c1 | C++ | areebbeigh/CompetitiveProgramming | /HackerEarth/magical_word.cpp | UTF-8 | 1,191 | 3.25 | 3 | [] | no_license | // https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/magical-word/
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
bool isPrime(const int &n) {
if (n == 2) return true;
if (n == 1) return false;
for (int i = 2; i < sqrt(n) + 1; ++i) {
if (n % i == 0) return false;
}
return true;
}
int main(int argc, const char** argv) {
vector<int> p;
for (int i = 65; i < 91; i++) {
if (isPrime(i)) p.push_back(i);
}
for (int i = 97; i < 123; i++) {
if (isPrime(i)) p.push_back(i);
}
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
while (n--) {
char c;
cin >> c;
int d = static_cast<int>(c);
int x = __INT_MAX__;
int r;
for(auto i : p) {
if (abs(i - d) <= x) {
if (abs(i-d) == x && i > r) continue;
x = abs(i-d);
r = i;
}
}
cout << static_cast<char>(r);
}
cout << endl;
}
}
| true |
f92ecc18a0bd17e078113aed6fea1b069849f71d | C++ | johnsonjx/code_examples | /hello_world_josh.cpp | UTF-8 | 349 | 2.546875 | 3 | [] | no_license | /*I love creativity, art, and learning new things!
It's honestly super dope. I hope I can continue to grow and improve.*/
//Hmmm, these comments are getting lengthy. I should progress.
#include <iostream>
int main()
{
std::cout << "Hello, Uncle Jeremiah! Say, what's with this funny tasting driNkFKdsofads0[fsd.............." << std::endl;
return 0;
}
| true |
ceae233ceee141bf19eca27246a0e93447bc5c91 | C++ | Metalhead33-Foundation/Haruka-Engine-GL-Reference | /audio/AudioPositioner.cpp | UTF-8 | 1,129 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include "AudioPositioner.hpp"
namespace Audio {
Positioner::Positioner(const sSource src)
: panner(Audio::PositionalPanner::createPositionPanner()),
unit(Unit::create(src))
{
panner->setInput(unit);
}
Positioner::Positioner(const Positioner& cpy, const sSource src)
: panner(Audio::PositionalPanner::createPositionPanner()),
unit(Unit::create(src))
{
panner->setInput(unit);
}
const sPositionalPanner Positioner::getPanner() const
{
return panner;
}
const sUnit Positioner::getUnit() const
{
return unit;
}
bool Positioner::isPlaying() const
{
return unit->isPlaying();
}
int Positioner::getFramerate() const
{
return unit->getFramerate();
}
int Positioner::getChannelCount() const
{
return 4;
}
long Positioner::pullAudio(float* output, long maxFrameNum, int channelNum, int frameRate)
{
return panner->pullAudio(output,maxFrameNum,channelNum,frameRate);
}
sPositioner Positioner::create(const sSource src)
{
return sPositioner(new Positioner(src));
}
sPositioner Positioner::create(const sPositioner cpy, const sSource src)
{
if(cpy) return sPositioner(new Positioner(*cpy,src));
else return nullptr;
}
}
| true |
e84e0849d8b7ae8397a2e107c4c8e92f12adf977 | C++ | carlaMorral/raytracing-f01-1 | /Geometry/Triangle.cpp | UTF-8 | 2,054 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | #include "Triangle.h"
#include <iostream>
Triangle::Triangle(vec3 p1, vec3 p2, vec3 p3, float data) :Object(data) {
this->p1 = p1;
this->p2 = p2;
this->p3 = p3;
// Pla que conte el triangle
vec3 w = p3 - p2;
vec3 v = p2 - p1;
this->n = cross(w,v)/length(cross(w,v));
this->plane = make_shared<Plane>(n, p1, -1.0f);
}
bool Triangle::hit(const Ray& raig, float t_min, float t_max, HitInfo& info) const {
// Vectors del triangle
vec3 w = p3 - p2;
vec3 v = p2 - p1;
vec3 u = p1 - p3;
// 1. Mirem si el raig interseca amb el pla que conté el triangle
HitInfo infoPlane;
if (!plane->hit(raig, t_min, t_max, infoPlane)) {
return false;
}
// 2. Calcul de les baricèntriques
vec3 v1 = infoPlane.p - p1;
if (dot(n,cross(v1,v)) < 0) {
return false;
}
vec3 v2 = infoPlane.p - p2;
if (dot(n,cross(v2,w)) < 0) {
return false;
}
vec3 v3 = infoPlane.p - p3;
if (dot(n,cross(v3,u)) < 0) {
return false;
}
// Omplim el camp de info
info.t = infoPlane.t;
info.p = infoPlane.p;
info.normal = n;
info.mat_ptr = material.get();
return true;
}
void Triangle::aplicaTG(shared_ptr<TG> t) {
if (dynamic_pointer_cast<TranslateTG>(t)) {
// Transformem els 3 punts del triangle
vec4 newp1(this->p1, 1.0);
vec4 newp2(this->p2, 1.0);
vec4 newp3(this->p3, 1.0);
newp1 = t->getTG() * newp1;
newp2 = t->getTG() * newp2;
newp3 = t->getTG() * newp3;
this->p1.x = newp1.x;
this->p1.y = newp1.y;
this->p1.z = newp1.z;
this->p2.x = newp2.x;
this->p2.y = newp2.y;
this->p2.z = newp2.z;
this->p3.x = newp3.x;
this->p3.y = newp3.y;
this->p3.z = newp3.z;
}
}
vec3 Triangle::calculaBaricentre(){
float a = 1/3;
return a*(p1+p2+p3);
}
void Triangle::applyAnimation(shared_ptr<CustomAnimation> anim, int nFrame){
//Implementar si es vol poder animar aquest tipus d'objecte
}
| true |
b33350ff58e9b6b7f6b875d076515398d9a9ccf8 | C++ | mberg-ConU/MBProjects2021 | /Graph_Proj/DGraph.h | UTF-8 | 993 | 2.984375 | 3 | [] | no_license | // M. Bergeron
// E. Bouskila
// DGraph.h
#ifndef DGRAPH_H
#define DGRAPH_H
#include <string>
#include "Graph.h"
#include <vector>
// definition of derived class DGraph
class DGraph : public Graph
{
private:
virtual void display(Person&, vector<bool>&); // private recursive function used in display functions
public:
DGraph(int, int); // constructor
DGraph(const DGraph&); // copy constructor
virtual ~DGraph(); // destructor
virtual void display(); // displays all paths in the graph
virtual void display(Friendship&); // display the paths that contain the Friendship
bool remove_friendship(Friendship&); // remove Friendship from graph
bool removeEdges(Friendship*, int); // remove multiple Friendships
virtual void showEdges(); // display Friendships for clarity
virtual void query_by_value(string); // print paths of Person with given value
virtual void call_DGraph_display(Person&, vector<bool>&); // display paths of a Person
};
#endif // DGRAPH_H
| true |
3d4b039b1490ab407d46e2ccd70ca3af1f39ea9e | C++ | oroko123/JNPI | /zadanie6/rozwiazanie/helper.h | UTF-8 | 2,157 | 3.21875 | 3 | [] | no_license | #ifndef HELPER_H
#define HELPER_H
#include <string>
using Age = unsigned int;
using HealthPoints = unsigned int;
using AttackPower = unsigned int;
using Time = unsigned int;
class Status {
std::string monsName;
HealthPoints monsHealth;
size_t aliveCitizens;
public:
Status(const std::string &monsName, HealthPoints monHealth, size_t aliveCit)
: monsName(monsName), monsHealth(monHealth), aliveCitizens(aliveCit) { }
const std::string &getMonsterName() const {
return monsName;
}
HealthPoints getMonsterHealth() const {
return monsHealth;
}
size_t getAliveCitizens() const {
return aliveCitizens;
}
};
class Creature {
protected:
HealthPoints health;
public:
Creature(HealthPoints h) : health(h) {
assert(h > 0);
}
// PW: brak wirtualnych destruktorow
virtual HealthPoints getHealth() const {
return health;
}
virtual bool isAlive() const {
return health > 0;
}
virtual void takeDamage(AttackPower attack) {
health -= attack > health ? health : attack;
}
};
class Attacker : public virtual Creature {
protected:
AttackPower attack;
public:
Attacker(HealthPoints h, AttackPower att) : Creature(h), attack(att) {
assert(att > 0);
}
virtual AttackPower getAttackPower() const {
return isAlive() ? attack : 0;
}
};
class BaseAttackTimeStrategy {
public:
virtual bool isAttackTime(Time t) const = 0;
};
class NeverAttackTimeStrategy : public BaseAttackTimeStrategy {
NeverAttackTimeStrategy() = default;
public:
static NeverAttackTimeStrategy &getInstance() {
static NeverAttackTimeStrategy instance;
return instance;
}
virtual bool isAttackTime(Time t) const { return false; }
};
class FirstAttackTimeStrategy : public BaseAttackTimeStrategy {
public:
static FirstAttackTimeStrategy &getInstance() {
static FirstAttackTimeStrategy instance;
return instance;
}
virtual bool isAttackTime(Time t) const {
return ((t % 3 == 0) || (t % 13 == 0)) && (t % 7 != 0);
}
};
#endif //HELPER_H | true |
34a48419e735841f60ffd6d9462b29af61712459 | C++ | punzoamh/C-Code | /inkisthw8_punzo.h | UTF-8 | 8,097 | 3.75 | 4 | [] | no_license | /**
CS219_HW4
inkisthw8__punzo.h
Purpose: Header File for linked list
@author Antonio M.H. Punzo
@version 1.0 5/5/2015
Compiled using g++ -o hw9 -Wall -Wextra CS219_Punzo/hw9/inkisthw8_punzo.h
*/
/**
* This header file will create the struct node,
* ->and class inkist for the program
* inkist will contain a method for the following:
* add to front, add to rear, boolean empty,
* size, clear, display, delete from front and delete from rear
* @author Tony
*
*/
/**
* This Application will Use pointers to add nodes to a linked list
* It will use template class to add any type required.
* Nodes will be added or deleted
* based on the manipulation of the pointers.
* @author Tony
*
*/
#ifndef inkisthw8_punzo_h
#define inkisthw8_punzo_h
#include <iostream>
using namespace std;
/**
* struct node used to create new instances of node
* each node will have a prev pointer and a next pointer
* and contain variable-data.
*/
template<class T>
struct node
{
T data;
node<T>* prev;
node<T>* next;
};
/**
* Creates class inkist
* contains methods for manipulating the pointers
* and nodes of the linked list
*
*/
template<class T>
class inkist
{
public:
/**
* Default Constructor
* Set pointers next and prev to head
* for null/empty list
*/
inkist() :head(new node<T>)
{head->next = head; head->prev = head;}
/**
* Copy Constructor
*
*/
inkist(const inkist& source);
/**
* Operator overload Function
*
*/
inkist &operator =(const inkist& source);
/**
* Destructor
*
*/
virtual ~inkist(void); //{clear(); delete head;}
/**
* test if linked list is empty
*
*/
bool empty() const;
/**
* Method for inserting an integer at front
*
*/
void push_front(const T value);
/**
* Method for inserting an integer at rear
*
*/
void push_back(const T value);
/**
* Method for displaying items in list
*
*/
//void display() const;
/**
* Method for deleting all items in list
*
*/
void clear();
/**
* Method for returning size of list
*
*/
int size() const;
/**
* Method for deleting an integer at front
*
*/
void pop_front();
/**
* Method for deleting an integer at rear
*
*/
void pop_back();
/**
* Method for finding an address of a particular value
*
*/
node<T>* find(const T& val) const;
/**
* Method for inserting a node before a node
* with a particular value
*
*/
node<T>* insert(node<T>* pos, const T& val);
/**
* Method for erasing a node
*
*/
node<T>* erase(node<T>* pos);
/**
* Class creating Iterator
*
*/
class Iterator
{
public:
typedef bidirectional_iterator_tag
iterator_category;
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
Iterator() {}
Iterator(node<T>* new_iter){iter=new_iter;}
Iterator& operator++(){iter=iter->next; return *this;}
Iterator& operator--(){iter=iter->prev; return *this;}
T& operator*() const{return iter->data;}
Iterator& operator++(int)
{
Iterator tmp= *this;
++(*this);
return tmp;
}
Iterator& operator--(int)
{
Iterator tmp= *this;
--(*this);
return tmp;
}
bool operator==(const Iterator& x) const
{
return iter == x.iter;
}
bool operator!=(const Iterator& x) const
{
return iter != x.iter;
}
private:
node<T>* iter;
};
/**
* Iterator begining
*
*/
Iterator begin(){return Iterator(head->next);}
/**
* Iterator end
*
*/
Iterator end(){return Iterator(head);}
/**
* private member variables
* creates node head
*/
private: node<T>* head;
};
/**
* Function for adding element to front of list
* Creates new node push_F
* Stores data from value into push_F
* Stores address of the pointer head
* transfers address of push_F to head
*
*/
template<class T>
void inkist<T>::push_front(const T value)
{
node<T>* push_F = new node<T>;
push_F->data = value;
push_F->next = head->next;
push_F->prev = head;
head->next->prev = push_F;
head->next = push_F;
}
/**
* Function for adding element to rear of list
* Creates new node push_B
* stores push_B in head prev
* Uses loop to go to last node
* transfers address of push_B->next to push_B
* Creates new node push_B2
* Stores data from value into push_B
* Stores address of the head->next to push_B
* transfers address of push_B to head
*/
template<class T>
void inkist<T>::push_back(const T value)
{
node<T>* push_B = new node<T>;
push_B->data = value;
push_B->prev = head->prev;
push_B->next = head;
head->prev->next = push_B;
head->prev = push_B;
}
/**
* Function for displaying list
* If list is empty displays a message
* If not empty list is displayed
*/
/**template<class T>
void inkist<T>::display() const{
node<T>* list=head->next;
while(list != head)
{cout << list->data << "-->"; list = list->next;}
cout << endl;
}*/
/**
* Function for clearing list
* Uses loop to go through each element in list
* Deletes all elements in list
*/
template<class T>
void inkist<T>::clear()
{
while(head != head->next) pop_front();
}
template<class T>
bool inkist<T>::empty() const
{
return(head->next == head);
}
/**
* Function for displaying size of list
* Uses a counter and transverses the list
* Each element increments the counter
* Displays total number of elements in list
*/
template<class T>
int inkist<T>::size() const
{
node<T>* counter = head->next; int size = 0;
while (counter != head)
{counter = counter->next; size++;}
return (size);
}
/**
* Function for deleting element from front of list
*/
template<class T>
void inkist<T>::pop_front()
{
head->next = head->next->next;
delete head->next->prev;
head->next->prev = head;
}
/**
* Function for deleting element from rear of list
*/
template<class T>
void inkist<T>::pop_back()
{
node<T>* pop_B = head->prev;
pop_B->prev->next = head;
head->prev = pop_B->prev;
delete pop_B;
/**
head->prev = head->prev->prev;
delete head->prev->next;
head->prev->next = head;*/
}
/**
* Function for finding element in list
*/
template<class T>
node<T>* inkist<T>::find(const T& val) const
{
node<T>* pos = head->next;
while(pos != head)
{
if(pos->data==val)
{
return pos;
}
pos = pos->next;
}
}
/**
* Function for inserting a node before a certain node
*/
template<class T>
node<T>* inkist<T>::insert(node<T>* pos, const T& val)
{
node<T>* temp = new (struct node<T>);
temp->data = val;
temp->next = pos;
pos->prev->next = temp;
temp->prev = pos->prev;
pos->prev = temp;
return 0;
}
/**
* Function for erasing a paticular node
*/
template<class T>
node<T>* inkist<T>::erase(node<T>* pos)
{
pos->prev->next = pos->next;
pos->next->prev = pos->prev;
delete pos;
return 0;
}
/**
* Copy Constructor definition
*
*/
template<class T>
inkist<T>::inkist (const inkist& source)
:head(new node<T>)
{
head->next = head;
head->prev = head;
node<T>* temp = source.head->next;
while(temp != source.head)
{
push_back(temp->data);
temp = temp->next;
}
}
/**
* = Operator Function definition
*
*/
template<class T>
inkist<T>& inkist<T>::operator =(const inkist& source)
{
clear();
node<T>* temp = source.head->next;
while(temp != source.head)
{
push_back(temp ->data);
temp = temp->next;
}
return* this;
}
/**
* Destructor definition
*
*/
template<class T>
inkist<T>::~inkist()
{
clear();
erase(head);
cout<< "List Destroyed" << endl;
}
#endif
| true |
08a5b8538cbef74a9cf9bf453604e44b694b4d94 | C++ | pivovard/ZCU | /UPS/UPS_Scrabble_server-master/Game.h | UTF-8 | 784 | 2.59375 | 3 | [] | no_license | //
// Created by pivov on 25-Dec-16.
//
#ifndef UPS_SCRABBLE_SERVER_GAME_H
#define UPS_SCRABBLE_SERVER_GAME_H
#include "stdafx.h"
#include "Player.h"
class Game
{
public:
int id;
char matrix[15][15];
int PlayerCount;
int PlayerNext;
int PlayerOnTurn;
int PlayerDisconnected;
vector<Player*> Players;
Game(int id, Player *pl1, Player *pl2);
Game(int id, Player *pl1, Player *pl2, Player *pl3);
Game(int id, Player *pl1, Player *pl2, Player *pl3, Player *pl4);
void RecvTurn(string msg);
void Reconnect(Player *pl);
void Disconnect(int id);
private:
void Init();
void NextTurn();
void SendTurn(string msg);
int CheckScore(string msg);
static int multiplier[];
};
#endif //UPS_SCRABBLE_SERVER_GAME_H
| true |
ee8cd975e136682ebcd95d6731a09db86c7f3e87 | C++ | Flare-k/Programming | /자료구조/Project(part.2)/장서진_2017102832/프로젝트1/Application.h | UHC | 3,432 | 2.890625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <windows.h>
#include "BestSorted.h"
#include "BestType.h"
#include "LyricList.h"
#include "LyricType.h"
#include "MusicSorted.h"
#include "MusicType.h"
#include "PlayQueue.h"
#include "PlayType.h"
#define FILENAMEMAX 100000
using namespace std;
class Application
{
public:
// 1: Admin 2: User 1
void RunAdminOrUser(); // ɼ
int GetCommand(); // Ű ɼ ޱ
void RunAdmin(); // Admin ɼ
void RunUser(); // User ɼ
int FirstGetCommand(); // 1 Admin αƮ Ű ޱ
int SecondGetCommand(); // 2 User Ű ޱ
// 1. Admin (ü & α Ʈ )
//
int AddMusic(); // ߰
int DeleteMusic(); // id ġϴ
int ReplaceMusic(); // id ġϴ Ű Է ٲٱ
int DisplayById_Binary(); // list id binaryϰ ã
int DisplayAllMusic(); // ȭ鿡
int MakeEmpty(); //
int ReadMusicDataFromFile(); // Ű Է¹ ̸ ġϴ ҷ
int WriteMusicDataToFile(); // Է ̸ Ͽ ϱ
// α Ʈ
int AddBest(); // ߰
int DeleteBest(); // ġϴ
int ReplaceBest(); // ġϴ Ű Է ٲٱ
int GetBestByName_Binary(BestType& data); // α Ʈ ̸
int DisplayBestByName(); // α Ʈ ãƼ
int DisplayAllBest(); // α Ʈ Ʈ
int WriteBestDataToFile(); // Է ̸ Ͽ ϱ
int ReadBestDataFromFile(); // Ű Է¹ ̸ ġϴ ҷ
int OpenInFile(char* fileName); //
int OpenOutFile(char* fileName); //
// 2. User ( & ˻)
int DisplayBestNames(); // α Ʈ ãƼ
int AddRecordToPL(); // Id ŰƮκ о list class Լ ̿Ͽ list ã ã ڵ PlayList Enque߰
int DeletePL(); // Űκ Id о ش ڵ带 PL ãƼ
int DisplayPL(); // PlayList ȭ鿡
int PlayPL(); //
int SearchLyric();// ˻ (簡 ؽƮ ̸ Ǿ )
private:
MusicSorted<MusicType> m_List; // Ʈ
BestSorted<BestType> m_bestList; // α Ʈ Ʈ
PlayList<PlayType> m_playList; //
LyricList<LyricType> m_lyricList; // Ʈ
ifstream m_InFile; ///< input file descriptor.
ofstream m_OutFile; ///< output file descriptor.
int m_Command = 0; // Ŀ ޱ
int m_Command_Ad = 0; // Admin Ŀǵ ޱ
int m_Command_User = 0; // User Ŀǵ ޱ
}; | true |
d0565d90121587e4085411ec946302eecbef2c5f | C++ | srpatel/spellsmith | /Classes/ClickMe.cpp | UTF-8 | 1,492 | 2.546875 | 3 | [
"MIT"
] | permissive | //
// ClickMe.cpp
// Gems
//
// Created by Sunil Patel on 03/12/2017.
//
#include "ClickMe.hpp"
bool ClickMe::init(bool big) {
if ( !Layer::init() ) {
return false;
}
// Circles...
auto circle1 = LoadSprite("ui/circle.png");
circle1->setAnchorPoint(Vec2(0.5, 0.5));
addChild(circle1);
// auto circle2 = LoadSprite("ui/circle.png");
// circle2->setAnchorPoint(Vec2(0.5, 0.5));
// circle2->setOpacity(0);
// addChild(circle2);
circle1->runAction(
RepeatForever::create(
Sequence::create(
FadeTo::create(0, 255),
ScaleTo::create(0, 0.1),
Spawn::create(
FadeTo::create(1, 0),
ScaleTo::create(1, big ? 1.5 : 1),
nullptr
),
DelayTime::create(0.1),
nullptr
)
)
);
/*circle2->runAction(
Sequence::create(
DelayTime::create(0.2),
CallFunc::create([circle2](){
circle2->runAction(RepeatForever::create(
Sequence::create(
FadeTo::create(0, 255),
ScaleTo::create(0, 0.1),
Spawn::create(
FadeTo::create(1, 0),
ScaleTo::create(1, 1),
nullptr
),
nullptr
)
));
}),
nullptr
)
);*/
// circle2->runAction(
// Sequence::create(
// DelayTime::create(0.5),
// RepeatForever::create(
// Sequence::create(
// FadeTo::create(0, 255),
// ScaleTo::create(0, 0.1),
// Spawn::create(
// FadeTo::create(1, 0),
// ScaleTo::create(1, 1),
// nullptr
// ),
// nullptr
// )
// ),
// nullptr
// )
// );
return true;
}
| true |
f5a59d12370252ba8ebb4a647936038e9fdf9966 | C++ | dibolek/TaskMan | /datastorage.cpp | UTF-8 | 4,324 | 3.09375 | 3 | [] | no_license | #include "datastorage.h"
DataStorage::DataStorage()
{
}
void DataStorage::userDataExport(User &usr)
{
vector<Event *> tmp = usr.getEventsVector();
Date datetime;
ofstream plik( usr.getFileName().c_str() );
plik << tmp.size() << endl
<< usr.getUserID() << endl
<< usr.getUserName() << endl
<< usr.getFileName() << endl;
for (vector<Event *>::iterator itr = tmp.begin(), end = tmp.end() ; itr != end ; ++itr) {
datetime.setDateAndTimeObject( (*itr)->getDataIczas() );
Event * p_Event = *itr;
Meeting *p_Meeting = 0;
ToDoList *p_ToDoList = 0;
Note *p_Note = 0;
// type : 1 - meeting, 2 - todolist, 3 -note
if( (p_Meeting = dynamic_cast<Meeting*>(p_Event)) ){
plik << 1 << endl
<< p_Meeting->getPlaceOfMeeting() << endl
<< p_Meeting->getDurationOfMeeting() << endl;
}else if ( (p_ToDoList = dynamic_cast<ToDoList*>(p_Event)) ) {
plik << 2 << endl
<< "nothing" << endl
<< 0 << endl;
}else if ( (p_Note = dynamic_cast<Note*>(p_Event)) ) {
plik << 3 << endl
<< "nothing" << endl
<< 0 << endl;
}
plik << p_Event->getEventID() << endl
<< p_Event->getMessage() << endl
<< datetime.ExportDateAndTimeToString() << endl;
}//for
plik.flush();
plik.close();
}
void DataStorage::userDataImport(User &usr, string _nazwaPliku)
{
ifstream plik(_nazwaPliku.c_str());
Date datetime;
int x;
string y;
getline(plik, y);
int eventsCount = convertStringToInt( y );
vector<Event *> tmp;
getline(plik, y);
usr.setUserID( convertStringToInt( y ) );
getline(plik, y);
usr.setUserName( y );
getline(plik, y);
usr.setFileName( y );
Event * p_Event = 0;
Meeting *p_Meeting = 0;
for (int i = 0; i < eventsCount; ++i) {
getline(plik, y);
x = convertStringToInt( y );
if ( x == 1 ) {
p_Meeting = new Meeting();
getline(plik, y);
p_Meeting->setPlaceOfMeeting( y );
getline(plik, y);
p_Meeting->setDurationOfMeeting( convertStringToInt( y ) );
p_Event = dynamic_cast<Event*>(p_Meeting);
}else if ( x == 2 ) {
p_Event = new ToDoList();
getline(plik, y);
getline(plik, y);
}else if ( x == 3 ) {
p_Event = new Note();
getline(plik, y);
getline(plik, y);
}
getline(plik, y);
p_Event->setEventID( convertStringToInt( y ) );
getline(plik, y);
p_Event->setMessage( y );
getline(plik, y);
datetime.ImportDateAndTimeFromString(y);
p_Event->setDataIczas( datetime.getDateAndTimeObject() );
tmp.push_back(p_Event);
}//for
usr.setEventsVector(tmp);
plik.close();
}
void DataStorage::allUsersVectorExport(vector<UsersListStruct> &vec, string nazwapliku)
{
ofstream plik(nazwapliku.c_str());
plik << vec.size() << endl;
for (vector<UsersListStruct>::iterator itr = vec.begin(), end = vec.end(); itr != end; ++itr) {
plik << (*itr).userID << endl
<< (*itr).userName << endl
<< (*itr).fileName << endl;
}
plik.flush();
plik.close();
}
vector<UsersListStruct> DataStorage::allUsersVectorImport(string nazwapliku)
{
ifstream plik(nazwapliku.c_str());
int x;
string y;
getline(plik, y);
x = convertStringToInt(y);
vector<UsersListStruct> temporary(x);
for (vector<UsersListStruct>::iterator itr = temporary.begin(), end = temporary.end(); itr != end; ++itr) {
getline(plik, y);
(*itr).userID = convertStringToInt(y);
getline(plik, y);
(*itr).userName = y;
getline(plik, y);
(*itr).fileName = y;
}
plik.close();
return temporary;
}
| true |
4cbf468f1afb5f01bd955ad97059d9e38252753b | C++ | marc-hanheide/cogx | /scenarios/george/trunk/src/c++/components/Testing/statemachine.hpp | UTF-8 | 8,881 | 2.5625 | 3 | [] | no_license | /**
* @author Marko Mahnič
* @created April 2012
*/
#ifndef _TESTING_STATEMACHINE_HPP_4F7967EF_
#define _TESTING_STATEMACHINE_HPP_4F7967EF_
#include <castutils/Timers.hpp>
#include <cassert>
#include <stdexcept>
#include <memory>
#include <string>
#include <sstream>
#include <map>
#include <functional>
#include <mutex>
namespace testing
{
class CMachine;
typedef std::shared_ptr<CMachine> CMachinePtr;
class CState;
typedef std::shared_ptr<CState> CStatePtr;
class CLinkedState;
typedef std::shared_ptr<CLinkedState> CLinkedStatePtr;
// The state can contain varios fields with arbitrary infromation that can be
// used for processing.
typedef std::map<std::string, std::string> TStateInfoMap;
enum TStateFunctionResult {
Continue, // go to next stage/state
Sleep, // wait in this stage (uses sleep timer)
WaitChange, // wait for (any) registered WM change
NotImplemented
};
typedef std::function<TStateFunctionResult(CState*)> TStateFunction;
class CState
{
private:
enum EActivity {
acActive, acSleeping, acWaiting, acWaitInt, acDone
};
enum EPhase {
phInit, phEnter, phWork, phExit, phDone
};
static std::map<EPhase, std::string> mPhaseName;
class CStaticInit { CStaticInit(); };
private:
friend class CMachine;
friend class CWaitState;
CMachine* mpMachine;
std::string mId;
EPhase mPhase;
EActivity mActivity;
long mFirstSleepMs;
long mSleepMs;
long mTimeoutMs;
bool mbSwitchStateCalled;
castutils::CMilliTimer mSleepTimer;
castutils::CMilliTimer mTimeoutTimer;
std::vector<std::string> mEvents;
std::string msExitReason;
TStateInfoMap mInitInfo; // this is copied to mStateInfo in phInit/restart().
protected:
TStateInfoMap mInfo;
castutils::CMilliTimer mRunningTimer; // how long are we in phWork
private:
// List of registered exits from this state. It enables link verification
// before the machine is started. Entries are added in linkedState().
std::vector<CLinkedStatePtr> mLinkedStates;
TStateFunction _enter;
TStateFunction _work;
TStateFunction _exit;
public:
CState(CMachine* pmachine, std::string id);
const std::string& id();
// set during configuration
void setEnter(TStateFunction pEnter);
void setWork(TStateFunction pWork);
void setExit(TStateFunction pExit);
// The default implementation of enter() calls the function set by setEnter()
// (same for work and exit). The programmer can either call setEnter or/and
// reimplement the enter() method in a derived class.
virtual TStateFunctionResult enter();
virtual TStateFunctionResult work();
virtual TStateFunctionResult exit();
// set in enter or during configuration
void setSleepTime(long workingMs, long firstTimeMs=0);
void setTimeout(long milliseconds);
void setWatchEvents(const std::vector<std::string>& events);
// Can be used to transfer some info between states
void setInfo(const TStateInfoMap& info);
CLinkedStatePtr linkedState(const std::string& stateName, const std::string& reasons="");
// TODO: std::vector<CLinkedStatePtr> getBadLinks();
bool isWaitingForEvent(const std::string& evnet);
bool hasTimedOut();
virtual std::string getProgressText();
private:
void restart();
void execute();
void advance();
static TStateFunctionResult noAction(CState* pState); // default TStateFunction
};
class CLinkedState
{
private:
friend class CState;
CMachine* mpMachine;
std::string mId;
std::string mReasons;
CState* mpFromState;
CStatePtr mpToState;
CLinkedState(CMachine* pMachine, CState* pFromState, const std::string& toStateName, const std::string& reasons);
public:
CStatePtr getState();
std::string description();
};
class CWaitState: public CState
{
private:
friend class CMachine;
CLinkedStatePtr mExitState;
CWaitState(CMachine* pmachine): CState(pmachine, "(Wait)")
{
}
void setNextState(CLinkedStatePtr state, long timeoutMs=1000)
{
mExitState = state;
setSleepTime(20, timeoutMs);
}
protected:
virtual TStateFunctionResult enter();
virtual TStateFunctionResult work();
};
class CMachine
{
private:
std::map<std::string, CStatePtr> mStates;
CStatePtr mpPrevState;
CStatePtr mpCurrentState;
CStatePtr mpNextState;
castutils::CMilliTimer mWaitTimer; // periodically activate even if there are no events
long mStepNumber;
CStatePtr mWaitState;
protected:
std::mutex mReceivedEventsMutex;
std::map<std::string, bool> mReceivedEvents;
void checkReceivedEvent(const std::string& event);
public:
CStatePtr addState(std::string id);
CStatePtr addState(CState* pState);
CStatePtr findState(std::string id);
void switchToState(CStatePtr pNextState, const std::string& reason = "");
void switchToState(CLinkedStatePtr pNextState, const std::string& reason = "");
void switchToState(CLinkedStatePtr pNextState, long timeoutMs, const std::string& reason = "");
void runOneStep();
virtual void onTransition(CStatePtr fromState, CStatePtr toState);
bool isWaitingForEvent();
bool isFinished();
bool isSwitching();
void checkEvents();
long timeToSleep();
long getStepNumber();
virtual void writeStateDescription(std::ostringstream& ss);
virtual void writeMachineDescription(std::ostringstream& ss);
};
template<class MachineT>
class CMachineStateMixin
{
MachineT* __mpMachine;
public:
CMachineStateMixin(MachineT* pMachine);
MachineT* machine();
};
inline
CState::CState(CMachine* pmachine, std::string id)
: mpMachine(pmachine), mId(id), mPhase(phInit), mSleepMs(0), mTimeoutMs(0),
_enter(noAction), _work(noAction), _exit(noAction)
{
}
inline
const std::string& CState::id()
{
return mId;
}
inline
void CState::setSleepTime(long workingMs, long firstTimeMs)
{
mSleepMs = workingMs;
mFirstSleepMs = firstTimeMs;
}
inline
void CState::setTimeout(long milliseconds)
{
mTimeoutMs = milliseconds;
}
inline
void CState::setWatchEvents(const std::vector<std::string>& events)
{
mEvents = events;
}
inline
void CState::setInfo(const TStateInfoMap& info)
{
mInitInfo = info;
}
inline
bool CState::isWaitingForEvent(const std::string& event)
{
for (auto s : mEvents) {
if (event.find(s) != std::string::npos) {
return true;
}
}
return false;
}
inline
bool CState::hasTimedOut()
{
if (mTimeoutMs > 0) {
return mTimeoutTimer.isTimeoutReached();
}
return false;
}
inline
void CState::setEnter(TStateFunction pEnter)
{
this->_enter = pEnter;
}
inline
void CState::setWork(TStateFunction pWork)
{
this->_work = pWork;
}
inline
void CState::setExit(TStateFunction pExit)
{
this->_exit = pExit;
}
inline
CLinkedState::CLinkedState(CMachine* pMachine, CState* pFromState,
const std::string& toStateName, const std::string& reasons)
:mpMachine(pMachine), mId(toStateName), mReasons(reasons),
mpFromState(pFromState), mpToState(nullptr)
{
}
inline
CStatePtr CLinkedState::getState()
{
if (!mpToState) {
mpToState = mpMachine->findState(mId);
}
return mpToState;
}
inline
CStatePtr CMachine::addState(std::string id)
{
CStatePtr pState(new CState(this, id));
mStates[id] = pState;
return pState;
}
inline
CStatePtr CMachine::addState(CState* pState)
{
assert(pState);
CStatePtr pst(pState);
mStates[pst->mId] = pst;
return pst;
}
inline
CStatePtr CMachine::findState(std::string id)
{
auto it = mStates.find(id);
if (it == mStates.end()) {
throw std::runtime_error((std::string("State not found: ") + id));
return CStatePtr();
}
return mStates[id];
}
inline
void CMachine::switchToState(CLinkedStatePtr pNextState, const std::string& reason)
{
switchToState(pNextState->getState(), reason);
}
inline
long CMachine::getStepNumber()
{
return mStepNumber;
}
inline
bool CMachine::isWaitingForEvent()
{
if (! mpCurrentState.get()) return false;
return mpCurrentState->mActivity == CState::acWaiting;
}
inline
bool CMachine::isFinished()
{
if (! mpCurrentState.get()) return true;
return (mpCurrentState->mPhase == CState::phDone && !mpNextState.get());
}
inline
bool CMachine::isSwitching()
{
if (! mpCurrentState.get()) return true;
return (mpCurrentState->mbSwitchStateCalled);
}
inline
void CMachine::checkReceivedEvent(const std::string& event)
{
std::lock_guard<std::mutex> lock(mReceivedEventsMutex);
mReceivedEvents[event] = true;
}
inline
long CMachine::timeToSleep()
{
if (!mpCurrentState.get()) {
return 0;
}
if (mpCurrentState->mActivity == CState::acSleeping) {
return mpCurrentState->mSleepTimer.timeToWait();
}
return 0;
}
template<class MachineT>
CMachineStateMixin<MachineT>::CMachineStateMixin(MachineT* pMachine)
{
__mpMachine = pMachine;
}
template<class MachineT>
MachineT* CMachineStateMixin<MachineT>::machine()
{
return __mpMachine;
}
}// namespace
#endif /* _TESTING_STATEMACHINE_HPP_4F7967EF_ */
// vim: set fileencoding=utf-8 sw=2 sts=4 ts=8 et ft=cpp11.cpp :vim
| true |
3adec608fe6b88b6df8588ea3dde82d6a551779f | C++ | EliasJadon/MeshPlane | /src/mat.cpp | UTF-8 | 6,411 | 2.65625 | 3 | [] | no_license | #include "mat.hpp"
#include "string.h"
#include <stdlib.h>
void Mat3::h_pivot_decomp(int *p, int *q) {
int i,j,k;
int n=DIM;
int pi,pj,tmp;
real_t max;
real_t ftmp;
for (k=0; k<n; k++) {
pi=-1,pj=-1,max=0.0;
//find pivot in submatrix a(k:n,k:n)
for (i=k; i<n; i++) {
for (j=k; j<n; j++) {
if (std::abs(_m[i][j])>max) {
max = std::abs(_m[i][j]);
pi=i;
pj=j;
}
}
}
//Swap Row
tmp=p[k];
p[k]=p[pi];
p[pi]=tmp;
for (j=0; j<n; j++) {
ftmp=_m[k][j];
_m[k][j]=_m[pi][j];
_m[pi][j]=ftmp;
}
//Swap Col
tmp=q[k];
q[k]=q[pj];
q[pj]=tmp;
for (i=0; i<n; i++) {
ftmp=_m[i][k];
_m[i][k]=_m[i][pj];
_m[i][pj]=ftmp;
}
//END PIVOT
//check pivot size and decompose
if ((std::abs(_m[k][k])>1e-20)) {
for (i=k+1; i<n; i++) {
//Column normalisation
_m[i][k]/=_m[k][k];
ftmp=_m[i][k];
for (j=k+1; j<n; j++) {
//a(ik)*a(kj) subtracted from lower right submatrix elements
_m[i][j]-=(ftmp*_m[k][j]);
}
}
}
//END DECOMPOSE
}
}
void Mat3::h_solve(real_t *x, int *p, int *q) {
//forward substitution; see Golub, Van Loan 96
//And see http://www.cs.rutgers.edu/~richter/cs510/completePivoting.pdf
int i,ii=0,j;
real_t ftmp;
real_t xtmp[DIM];
//Swap rows (x=Px)
for (i=0; i<DIM; i++) {
xtmp[i]=x[p[i]]; //value that should be here
}
//Lx=x
for (i=0; i<DIM; i++) {
ftmp=xtmp[i];
if (ii != 0)
for (j=ii-1; j<i; j++)
ftmp-=_m[i][j]*xtmp[j];
else if (ftmp!=0.0)
ii=i+1;
xtmp[i]=ftmp;
}
//backward substitution
//partially taken from Sourcebook on Parallel Computing p577
//solves Uy=z
xtmp[DIM-1]/=_m[DIM-1][DIM-1];
for (i=DIM-2; i>=0; i--) {
ftmp=xtmp[i];
for (j=i+1; j<DIM; j++) {
ftmp-=_m[i][j]*xtmp[j];
}
xtmp[i]=(ftmp)/_m[i][i];
}
for (i=0; i<DIM; i++) {
x[i]=xtmp[q[i]];
}
}
void Mat3::invert_full(Mat3 & rv)
{
int p[DIM];
int q[DIM];
real_t b[DIM];
for(int ii=0; ii<DIM; ii++) {
p[ii]=ii;
q[ii]=ii;
b[ii]=0;
}
h_pivot_decomp(p,q);
for(int ii=0; ii<3; ii++) {
b[ii]=1;
h_solve(b,p,q);
for(int jj=0; jj<3; jj++) {
rv._m[jj][ii]=b[q[jj]];
b[q[jj]]=0;
}
}
}
void Mat3::transpose()
{
for(int ii=0; ii<DIM; ii++) {
for(int jj=0; jj<DIM; jj++) {
real_t tmp = _m[ii][jj];
_m[ii][jj]=_m[jj][ii];
_m[jj][ii]=tmp;
}
}
}
void Mat3::gauss_pivot(Mat3 & rv)
{
int n=3;
real_t * A=m;
real_t * AInverse=rv.m;
int i, j, iPass, imx, icol, irow;
real_t det, temp, pivot, factor=0;
real_t* ac = (real_t*)calloc(n*n, sizeof(real_t));
det = 1;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
AInverse[n*i+j] = 0;
ac[n*i+j] = A[n*i+j];
}
AInverse[n*i+i] = 1;
}
// The current pivot row is iPass.
// For each pass, first find the maximum element in the pivot column.
for (iPass = 0; iPass < n; iPass++)
{
imx = iPass;
for (irow = iPass; irow < n; irow++)
{
if (std::abs(A[n*irow+iPass]) > std::abs(A[n*imx+iPass])) imx = irow;
}
// Interchange the elements of row iPass and row imx in both A and AInverse.
if (imx != iPass)
{
for (icol = 0; icol < n; icol++)
{
temp = AInverse[n*iPass+icol];
AInverse[n*iPass+icol] = AInverse[n*imx+icol];
AInverse[n*imx+icol] = temp;
if (icol >= iPass)
{
temp = A[n*iPass+icol];
A[n*iPass+icol] = A[n*imx+icol];
A[n*imx+icol] = temp;
}
}
}
// The current pivot is now A[iPass][iPass].
// The determinant is the product of the pivot elements.
pivot = A[n*iPass+iPass];
det = det * pivot;
if (det == 0)
{
free(ac);
return;
}
for (icol = 0; icol < n; icol++)
{
// Normalize the pivot row by dividing by the pivot element.
AInverse[n*iPass+icol] = AInverse[n*iPass+icol] / pivot;
if (icol >= iPass) A[n*iPass+icol] = A[n*iPass+icol] / pivot;
}
for (irow = 0; irow < n; irow++)
// Add a multiple of the pivot row to each row. The multiple factor
// is chosen so that the element of A on the pivot column is 0.
{
if (irow != iPass) factor = A[n*irow+iPass];
for (icol = 0; icol < n; icol++)
{
if (irow != iPass)
{
AInverse[n*irow+icol] -= factor * AInverse[n*iPass+icol];
A[n*irow+icol] -= factor * A[n*iPass+icol];
}
}
}
}
free(ac);
}
void Mat3::mult(const Mat3 & rv, Mat3& result)
{
for(int ii=0; ii<3; ii++) {
for(int jj=0; jj<3; jj++) {
result._m[ii][jj]=0;
for(int kk=0; kk<3; kk++) {
result._m[ii][jj]+=_m[ii][kk]*rv._m[kk][jj];
}
}
}
}
void Mat3::inverse(Mat3& rv) const
{
rv._m[0][0] = _m[1][1]*_m[2][2] - _m[1][2]*_m[2][1];
rv._m[0][1] = _m[0][2]*_m[2][1] - _m[0][1]*_m[2][2];
rv._m[0][2] = _m[0][1]*_m[1][2] - _m[0][2]*_m[1][1];
rv._m[1][0] = _m[1][2]*_m[2][0] - _m[1][0]*_m[2][2];
rv._m[1][1] = _m[0][0]*_m[2][2] - _m[0][2]*_m[2][0];
rv._m[1][2] = _m[0][2]*_m[1][0] - _m[0][0]*_m[1][2];
rv._m[2][0] = _m[1][0]*_m[2][1] - _m[1][1]*_m[2][0];
rv._m[2][1] = _m[0][1]*_m[2][0] - _m[0][0]*_m[2][1];
rv._m[2][2] = _m[0][0]*_m[1][1] - _m[0][1]*_m[1][0];
real_t det = _m[0][0]*rv._m[0][0] +
_m[0][1]*rv._m[1][0] +
_m[0][2]*rv._m[2][0];
real_t invdet = 1.0 / det;
for (int i = 0; i < SIZE; i++)
rv.m[i] *= invdet;
}
const Mat3 Mat3::Identity = Mat3( 1, 0, 0,
0, 1, 0,
0, 0, 1 );
const Mat3 Mat3::Zero = Mat3( 0, 0, 0,
0, 0, 0,
0, 0, 0 );
Mat3::Mat3(real_t r[SIZE])
{
memcpy(m ,r, sizeof r);
}
Mat3::Mat3(real_t m00, real_t m10, real_t m20,
real_t m01, real_t m11, real_t m21,
real_t m02, real_t m12, real_t m22)
{
_m[0][0] = m00;
_m[1][0] = m10;
_m[2][0] = m20;
_m[0][1] = m01;
_m[1][1] = m11;
_m[2][1] = m21;
_m[0][2] = m02;
_m[1][2] = m12;
_m[2][2] = m22;
}
Mat3::Mat3(const Vec3& v1,const Vec3& v2,const Vec3& v3)
{
for(int ii=0; ii<3; ii++) {
_m[ii][0]=v1.get(ii);
_m[ii][1]=v2.get(ii);
_m[ii][2]=v3.get(ii);
}
}
| true |
3fb012fc5be32caf52ba879887f1568eabdc2cd0 | C++ | TheOctan/Labs-in-cpp | /Basics of programming/Laba №9/Task 7/Task 7.cpp | UTF-8 | 358 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void matrix(int side, char x)
{
for (int i = 0; i < side; i++)
{
for (int i = 0; i < side; i++)
{
cout << x << " ";
}
cout << endl;
}
}
int main()
{
int side; char x;
cout << "Input side the matrix "; cin >> side;
cout << "Input a simbol "; cin >> x;
matrix(side, x);
system("pause");
return 0;
} | true |
3d7492e2262dc6dbfbc18828a5381d33e97b729b | C++ | CBE7F1F65/bc38ca3dff4f1fc5a94a5450ba9806c6 | /DES_GOBSTG/DES_GOBSTG/Header/VectorList.h | UTF-8 | 5,048 | 3.15625 | 3 | [] | no_license | #ifndef _VECTORLIST_H
#define _VECTORLIST_H
#include <windows.h>
#define VECLST_INDEXERROR 0xffffffff
template <class _Ty>
class VectorList
{
typedef VectorList<_Ty> _Myt;
public:
VectorList()
{
item = NULL;
valid = NULL;
}
VectorList(DWORD count)
{
item = NULL;
valid = NULL;
init(count);
}
~VectorList()
{
clear();
}
void clear()
{
if (item)
{
delete[] item;
item = NULL;
}
if (valid)
{
delete[] valid;
valid = NULL;
}
index = 0;
}
void clear_item()
{
if (valid)
{
ZeroMemory(valid, sizeof(bool) * capacity);
}
ibegin = 0;
iend = 0;
size = 0;
zero = 0;
index = 0;
}
void init(DWORD count)
{
clear();
if (count < 1)
{
count = 1;
}
capacity = count;
item = new _Ty[capacity];
valid = new bool[capacity];
clear_item();
}
_Ty * push_back()
{
DWORD _index = index;
toEnd();
if (size)
{
toNext();
}
iend = index;
if (size && ibegin == iend)
{
ibegin = toNext();
}
else
{
size++;
}
index = _index;
valid[iend] = true;
return &item[iend];
}
_Ty * push_back(const _Ty & _item)
{
memcpy(push_back(), &_item, sizeof(_Ty));
return &item[iend];
}
_Ty * push_front()
{
DWORD _index = index;
toBegin();
if (size)
{
toPrev();
}
ibegin = index;
if (size && ibegin == iend)
{
iend = toPrev();
}
else
{
size++;
}
index = _index;
valid[ibegin] = true;
return &item[ibegin];
}
_Ty * push_front(const _Ty & _item)
{
memcpy(push_front(), &_item, sizeof(_Ty));
}
DWORD pop()
{
if (!size || !valid[index])
{
return index;
}
DWORD _index = index;
valid[index] = false;
if (index == ibegin)
{
size--;
if (size)
{
ibegin = toNext();
while (!valid[index])
{
size--;
if (!size)
{
break;
}
ibegin = toNext();
}
}
}
else if (index == iend)
{
size--;
if (size)
{
iend = toPrev();
while (!valid[index])
{
size--;
if (!size)
{
break;
}
iend = toPrev();
}
}
}
index = _index;
return index;
}
DWORD pop(DWORD _index)
{
DWORD _tindex = index;
if (toIndex(_index) == VECLST_INDEXERROR)
{
return VECLST_INDEXERROR;
}
pop();
index = _tindex;
return _index;
}
DWORD pop_back()
{
return pop(iend);
}
DWORD pop_front()
{
return pop(ibegin);
}
DWORD toBegin()
{
index = ibegin;
return index;
}
DWORD toEnd()
{
index = iend;
return index;
}
DWORD toNext()
{
if (index < capacity - 1)
{
index++;
}
else
{
index = zero;
}
return index;
}
DWORD toNext(bool sizeonly)
{
if (sizeonly)
{
DWORD _zero = zero;
DWORD _capacity = capacity;
zero = ibegin;
capacity = iend + 1;
toNext();
if (!isInRange())
{
index = zero;
}
zero = _zero;
capacity = _capacity;
return index;
}
return toNext();
}
DWORD toPrev()
{
if (index > zero)
{
index--;
}
else
{
index = capacity - 1;
}
return index;
}
DWORD toPrev(bool sizeonly)
{
if (sizeonly)
{
DWORD _zero = zero;
DWORD _capacity = capacity;
zero = ibegin;
capacity = iend + 1;
toPrev();
if (!isInRange())
{
index = capacity - 1;
}
zero = _zero;
capacity = _capacity;
return index;
}
return toPrev();
}
DWORD toIndex(DWORD _index)
{
if (_index >= capacity)
{
return VECLST_INDEXERROR;
}
index = _index;
return index;
}
_Ty * begin()
{
return &item[ibegin];
}
_Ty * end()
{
return &item[iend];
}
_Ty * next()
{
toNext();
return &item[index];
}
_Ty * prev()
{
toPrev();
return &item[index];
}
bool isBegin()
{
if (index == ibegin)
{
return true;
}
return false;
}
bool isEnd()
{
if (index == iend)
{
return true;
}
return false;
}
bool isValid()
{
return valid[index];
}
bool isInRange()
{
if (!size)
{
return false;
}
if (index > capacity)
{
return false;
}
if (index == ibegin || index == iend)
{
return true;
}
if ((ibegin < iend) && (index > ibegin && index < iend))
{
return true;
}
if ((ibegin < iend) && (index > ibegin || index < iend))
{
return true;
}
return false;
}
DWORD getIndex()
{
return index;
}
DWORD getBeginIndex()
{
return ibegin;
}
DWORD getEndIndex()
{
return iend;
}
_Ty & operator*() const
{
return item[index];
}
_Ty & operator[](DWORD _index) const
{
if (_index < capacity)
{
return item[_index];
}
else
{
return item[capacity - 1];
}
}
public:
_Ty * item;
bool * valid;
DWORD index;
DWORD ibegin;
DWORD zero;
DWORD iend;
DWORD size;
DWORD capacity;
};
#endif | true |
2565116f236558a07d30646cb8ecad138a8925c1 | C++ | shanta3220/UVA-Solutions | /Problems-solved-using-Queue/11034 - Ferry Loading IV.cpp | UTF-8 | 1,037 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<queue>
using namespace std;
int main()
{
int t,l,m,size,i,sum,count;
string side;
bool true1;
queue<int> left;
queue<int> right;
cin>>t;
for (int j = 0; j < t; j++){
cin>>l>>m;
for(i=0; i<m; i++){
cin>>size>>side;
if(side == "left")
left.push(size);
else right.push(size);
}
l= l*100;
count=0,sum=0,true1=0;
while(!left.empty() || !right.empty()){
sum=0;
if(true1==1){
while (!right.empty() && sum + right.front() <= l ){
sum+=right.front();
right.pop();
}
}
else{
while (!left.empty() && sum + left.front() <=l){
sum+=left.front();
left.pop();
}
}
count++;
true1=true1-1;
}
cout<<count<<"\n";
}
return 0;
}
| true |
ab4667216acdff5fef0b448e73a8ee67ff930b96 | C++ | Shtaiven/NailArt | /qip_win/MP/header/Matrix4.h | UTF-8 | 4,098 | 2.984375 | 3 | [] | no_license | // ======================================================================
// IMPROC: Image Processing Software Package
// Copyright (C) 2015 by George Wolberg
//
// Matrix4.h - 4x4 matrix class.
//
// Written by: George Wolberg and Gene Yu, 2015
// ======================================================================
//! \file Matrix4.h
//! \brief 4x4 matrix class.
//! \author George Wolberg and Gene Yu, 2015
//!
//! \class MP::Matrix4
//! \brief 4x4 matrix class.
//! \details The Matrix4 class represents 4x4 matrices of type \a double.
//!
//! <b>Example:</b>
//! \verbinclude example_matrix4.cpp
//!
//! <b>Output:</b>
//! \verbinclude example_matrix4.out
#ifndef MATRIX4_H
#define MATRIX4_H
#include "MPdefs.h"
namespace MP {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Matrix4 class declaration
//
class Matrix4 {
public:
Matrix4(); // default constructor
Matrix4(const Matrix4 &); // copy constructor
Matrix4(const double *); // array constructor
// component constructor
Matrix4(const double &, const double &, const double &, const double &,
const double &, const double &, const double &, const double &,
const double &, const double &, const double &, const double &,
const double &, const double &, const double &, const double &);
// public methods
int size () const; // number of elements
int rows () const; // number of rows
int cols () const; // number of columns
double norm2 () const; // squared Frobenius norm
double norm () const; // Frobenius norm
Matrix4 transpose() const; // matrix transpose
Matrix4 &clear (); // clear matrix
void identity (); // identity matrix
// array index operators (for 1D arrays)
const double &operator[](int i) const;
double &operator[](int i);
// array index operators (for 2D arrays)
const double &operator()(int i, int j) const;
double &operator()(int i, int j);
// assignment operators
Matrix4 &operator= (const Matrix4 &); // copy
Matrix4 &operator+=(const Matrix4 &); // addition
Matrix4 &operator-=(const Matrix4 &); // subtraction
Matrix4 &operator*=(const double &); // scalar multiplication
Matrix4 &operator*=(const Matrix4 &); // pre-multiplication
Matrix4 &operator/=(const double &); // scalar division
// type cast operators
operator Matrix3() const; // cast to 3x3 matrix
operator MatrixN() const; // cast to dynamic matrix
private:
int m_rows; // number of rows
int m_cols; // number of columns
double m_matrix[16]; // array pointer
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Arithmetic operators
//
extern Matrix4 operator+ (const Matrix4 &A, const Matrix4 &B);
extern Matrix4 operator- (const Matrix4 &A);
extern Matrix4 operator- (const Matrix4 &A, const Matrix4 &B);
extern Matrix4 operator* (const Matrix4 &A, const double &k);
extern Matrix4 operator* (const double &k, const Matrix4 &A);
extern Matrix4 operator/ (const Matrix4 &A, const double &k);
extern Vector3 operator* (const Matrix4 &A, const Vector3 &u);
extern Vector3 operator* (const Vector3 &u, const Matrix4 &A);
extern Vector4 operator* (const Matrix4 &A, const Vector4 &u);
extern Vector4 operator* (const Vector4 &u, const Matrix4 &A);
extern Matrix4 operator* (const Matrix4 &A, const Matrix4 &B);
extern bool operator==(const Matrix4 &A, const Matrix4 &B);
extern bool operator!=(const Matrix4 &A, const Matrix4 &B);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Output stream operator: <<
//
extern std::ostream &operator<<(std::ostream &out, const Matrix4 &A);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Miscellaneous matrix functions
//
extern double MP_det (const Matrix4 &A, int r1, int r2, int r3,
int c1, int c2, int c3);
extern double MP_det (const Matrix4 &A);
extern Matrix4 MP_inverse (const Matrix4 &A);
extern Matrix4 MP_outerProduct (const Vector4 &u, const Vector4 &v);
extern void MP_eulerAngles (const Matrix4 &A, double &,double &,double &);
} // namespace MP
#endif // MATRIX4_H
| true |
ff94eda02307a34dd167e50ff2026c5d090ce416 | C++ | vietjtnguyen/ucla-winter09-cs174a-opengl-engine | /Composite2Animator.h | UTF-8 | 694 | 3 | 3 | [] | no_license | #ifndef COMPOSITE_2_ANIMATOR_H
#define COMPOSITE_2_ANIMATOR_H
#include "Animator.h"
template <class T>
class Composite2 : public Animator< Vector2<T> >
{
public:
Composite2(Animator<T> a, Animator<T> b)
:Animator< Vector2<T> >()
,_a(a)
,_b(b)
{
}
virtual ~Composite2()
{
}
virtual Vector2<T> GetValue(float t)
{
return Vector2<T>(
this->_a.GetValue(t),
this->_b.GetValue(t));
}
Animator<T>& GetAnimatorA()
{
return this->_a;
}
Animator<T>& GetAnimatorB()
{
return this->_b;
}
protected:
Animator<T> _a;
Animator<T> _b;
};
typedef Composite2<float> Composite2f;
#endif // COMPOSITE_2_ANIMATOR_H | true |
83d07427ccc04bc8d8b2efe9120788d4d9ea49f6 | C++ | zhenghello/QTobj | /d190104_sshCan/Anyone/youLib/FtreeDateBase/timeSeqExplain.cpp | GB18030 | 5,397 | 2.640625 | 3 | [] | no_license | /* ļڽʱĹ
* ʱЭ timeSeq_TreeDb.dat УѾ̶
* ʱЭĴŹ
* item 1.ؼ֣2.
* itemŲݣǴitemĸûвûࣩ
* itemݣ1.գ2. 3.ͣ1ͨ 2ַƥݣƥ
* δitemݣ1.գ2.ΪƥʱIJؼ֣3.ؼֽ
* δδitem
*
*/
#include "timeSeqExplain.h"
#include <QFile>
#include<QDebug>
// timeSeq ļĹ̶
timeSeqExplain::timeSeqExplain(QWidget *parent):FtreeDabeBase(parent,"timeSeq")
{
}
// Э
// strPack :ԭʼһ 0 VU_PUMP -1 END
// strExplain :
// strExplain :ԭʼ+
// ʧܷfalse ɹtrue
bool timeSeqExplain::protocolExplain(const QByteArray *qbyPack,QByteArray *qbyExplain,QByteArray *qbyAll)
{
// 0.
qbyAll->clear();
qbyAll->append(*qbyPack);
// 0.ȥո
QByteArray qby_deal;
qby_deal=qbyPack->simplified();
// 1.ոָ
QList<QByteArray> list;
list.append(qby_deal.split(' '));
// 2.ûENDģλòԵģ
if(2 > list.indexOf("END"))
{
return false;
}
// 4.ҹؼ - // 0->ʱ䣬1->ؼ2->
// 4.1.
int argCount;
argCount = list.indexOf("END")-2;
// qDebug()<<argCount;
// 4.1.ʱ
double runTime=list.at(0).toDouble();
// qDebug()<<runTime;2
// 4.2.ؼֲ - ڿеĵ0
QByteArray key=list.at(1);
const QTreeWidgetItem *item;
item = findKey(0,key,argCount);
if(item == NULL)
{
// ʧܵĹؼ֣ӵ explainFailstr
if(explainFailKey.indexOf(key) == -1)
{ // ԭûеģӽ
explainFailKey.append(key);
}
return false;
}
// 5.ɽ
qbyExplain->clear();
// 5.1.ؼֽ
qbyExplain->append("// zkp " + item->text(1).toLocal8Bit()+":");
// 5.2.
for(int i=0;i<argCount;i++)
{
const QTreeWidgetItem *itemChild;
itemChild = item->child(i);
if(itemChild == NULL)break;
// ,0λΪ, 1.Dzƣ2Dz
qbyExplain->append(" " + itemChild->text(1).toLocal8Bit() + "=");
// -> ֱ֣
if(itemChild->text(2) == "number")
{
qbyExplain->append(list.at(2+i));
}
// ַƥ ->
if(itemChild->text(2) == "match")
{
QString str = list.at(2+i);
for(int j=0;j<itemChild->childCount();j++)
{
const QTreeWidgetItem *itemChildChild;
itemChildChild = itemChild->child(j);
// ַƥ ->
if(itemChildChild->text(1) == str)
{
qbyExplain->append(itemChildChild->text(2).toLocal8Bit());
}
}
}
}
// 6.ԭʼ+ = ϳ
QString strSpace;
if(qbyPack->indexOf("END")<50) // ֻENDԺ
{
strSpace = QString("%1").arg("",50-qbyPack->indexOf("END"));
}
qbyExplain->prepend(strSpace.toLatin1());//ȫֶ
qbyAll->clear();
qbyAll->append(*qbyPack);
qbyAll->insert(qbyPack->indexOf("END")+3,*qbyExplain);
return false;
}
// ļЭ
// :ļ·+ļ
// ڸĿ¼£ ļ+explain.txt ־
bool timeSeqExplain::txtExplain(QString timeSeqName)
{
QByteArrayList byteList;
QByteArrayList byteList_explain;
byteList.clear();
// 1.ļȡŵ byteList
QFile file(timeSeqName); // ļhandle
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))return false; // ʧ
while(!file.atEnd())
{ //
QByteArray line = file.readLine();
// ݲ
byteList.append(line);
}
file.close();
// 2.ݷнŵbyteList_explain
byteList_explain.clear();
explainFailKey.clear();
for(int i=0;i<byteList.size();i++)
{
QByteArray qbyPack,qbyExplain,qbyAll;
qbyPack = byteList.at(i);
bool bret ;
bret = protocolExplain(&qbyPack,&qbyExplain,&qbyAll);
byteList_explain.append(qbyAll);
}
// 3.ļŻԭλ+_explain
// 3.1.ļ
int index = timeSeqName.indexOf(".txt");
if(index == -1)return false;
timeSeqName.insert(index,"_explain");
// 3.2.ļ
file.setFileName(timeSeqName); // ļhandle
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))return false; // ʧ
// 3.3.дļ
for(int i=0;i<byteList_explain.size();i++)
{
file.write(byteList_explain.at(i));
}
file.close();
return true;
}
// ȡʧܵĹؼϢ
QStringList timeSeqExplain::getExplainFailKey()
{
return explainFailKey;
}
| true |
3ebee2fd9a1cef48721d8c8883a9f17a9fac7899 | C++ | jamesbertel/CS-311 | /CS311Progs/DemoPrograms/matrixVectorDemo.cpp | UTF-8 | 960 | 3.75 | 4 | [] | no_license | // CS311 Yoshii - matrix-vector demo
// Demonstrates a matrix containing a vector of chars
// in each slot.
// --------------------------------------------------------
#include <iostream>
#include <vector>
using namespace std;
void displayAll(vector<char> V)
{ cout << "[";
for (int i = 0; i < V.size(); i++)
cout << V[i];
cout << "]";
}
int main()
{
vector<char> M[3][3]; // every slot is a vector
char x; // user input
for (int row = 0; row <= 2; row++)
for (int col = 0; col <= 2; col++)
{ cout << "For row " << row << " column " << col << endl;
cout << " Enter a character:";
cin >> x;
M[row][col].push_back(x);
cout << " Enter a character:";
cin >> x;
M[row][col].push_back(x);
}// to next slot
for (int row = 0; row <=2; row++)
{
for (int col = 0; col <=2; col++)
{ displayAll(M[row][col]); cout << " | ";}
cout << endl; // end of row
}
}
| true |
fb894d73fcb59e577778acf6c82a0db240accba4 | C++ | NuriYuri/LiteRGSS | /ext/LiteRGSS/CShape_Element.h | UTF-8 | 1,414 | 2.546875 | 3 | [] | no_license | #ifndef CShape_Element_H
#define CShape_Element_H
#include <memory>
#include "ruby.h"
#include "CDrawable_Element.h"
class CShape_Element : public CDrawable_Element {
protected:
std::unique_ptr<sf::Shape> shape;
bool visible = true;
sf::RenderStates* render_states = nullptr;
public:
CShape_Element() = default;
virtual ~CShape_Element() = default;
void draw(sf::RenderTarget& target) const override;
void drawFast(sf::RenderTarget& target) const override;
bool isViewport() const override { return false; };
bool isPureSprite() const override { return false; };
bool isShape() const override { return true; };
sf::Shape* getShape() { return shape.get(); }
template <class ShapeC, class ... Args>
void setShape(Args&& ... args) {
shape = std::make_unique<ShapeC>(std::forward<Args>(args)...);
}
void setVisible(bool value);
bool getVisible();
void setRenderState(sf::RenderStates* states);
/* Instance variable for Ruby */
VALUE rBitmap = Qnil;
VALUE rX = Qnil;
VALUE rY = Qnil;
VALUE rZ = Qnil;
VALUE rOX = Qnil;
VALUE rOY = Qnil;
VALUE rAngle = Qnil;
VALUE rZoomX = Qnil;
VALUE rZoomY = Qnil;
VALUE rRect = Qnil;
VALUE rShapeType = Qnil;
VALUE rRenderStates = Qnil;
VALUE rColor = Qnil;
VALUE rOutlineColor = Qnil;
VALUE rOutlineThickness = Qnil;
};
namespace meta {
template<>
struct Log<CShape_Element> {
static constexpr auto classname = "Shape";
};
}
#endif
| true |
61cab354b67de35ee33beeaedf59e06dfb03a6df | C++ | AbhayaV2001/ADA_1bm18cs001 | /median_msort.cpp | UTF-8 | 1,236 | 3.5625 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
float median(int a[], int n)
{
if (n % 2 == 0)
return (float)(a[n / 2] + a[(n / 2 )- 1]) / 2;
else
return a[n / 2];
}
float findMedian(int a1[], int a2[], int n)
{
if (n <= 0)
return -1;
if (n == 1)
return (float)(a1[0] + a2[0]) / 2;
if (n == 2)
return (float)(max(a1[0], a2[0]) + min(a1[1], a2[1])) / 2;
int m1 = median(a1, n);
int m2 = median(a2, n);
if (m1 == m2)
return m1;
if (m1 < m2)
{
if (n % 2 == 0)
return findMedian(a1 + (n / 2) - 1, a2, n -( n / 2) + 1);
return findMedian(a1 + (n / 2), a2, n - (n / 2));
}
if (n % 2 == 0)
return findMedian(a2 + (n / 2 )- 1, a1, n - (n / 2 )+ 1);
return findMedian(a2 + (n / 2), a1, n -( n / 2));
}
int main()
{
int n;
cout<<"Enter size of the arrays"<<endl;
cin>>n;
int a[n],b[n];
cout<<"Enter elements of 1st array"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Enter the elements of 2nd array"<<endl;
for(int i=0;i<n;i++)
cin>>b[i];
cout<<"Median : "<<findMedian(a,b,n)<<endl;
return 0;
}
| true |
addcb83f01b584736c64cfe60349f4e27a6c8cce | C++ | colinblack/game_server | /server/app/data/HeroPropertyManager.h | UTF-8 | 11,969 | 2.703125 | 3 | [] | no_license | /*
* HeroPropertyManager.h
*
* Created on: 2016-9-2
* Author: Ralf
*/
#ifndef HEROPROPERTYMANAGER_H_
#define HEROPROPERTYMANAGER_H_
#include "Kernel.h"
class HeroFightAttr
{
public:
HeroFightAttr();
void Clear();
void SetAttr(DemoHeroProperty attr, int val);
void AddAttr(DemoHeroProperty attr, int val);
int GetAttr(DemoHeroProperty attr) const;
//各属性加成
void AdditionFightBase(map<unsigned, double> & addition_percent);
HeroFightAttr& operator +=(const HeroFightAttr& obj)
{
for (int i = 0; i < DemoHeroProperty_max; i++)
{
val_[(DemoHeroProperty)i] += obj.val_[(DemoHeroProperty)i];
}
return *this;
}
HeroFightAttr operator +(const HeroFightAttr& obj)
{
HeroFightAttr result;
for (int i = 0; i < DemoHeroProperty_max; i++)
{
DemoHeroProperty prop = (DemoHeroProperty)i;
result.val_[prop] = val_[prop] + obj.val_[prop];
}
return result;
}
bool operator ==(const HeroFightAttr& obj)
{
for (int i = 0; i < DemoHeroProperty_max; i++)
{
DemoHeroProperty prop = (DemoHeroProperty)i;
if (val_[prop] != obj.val_[prop])
{
return false;
}
}
return true;
}
void FullMessage(ProtoHero::HeroBaseInfoCPP* hero) const
{
int attack = GetAttr(DemoHeroProperty_attack); //攻击
int hp = GetAttr(DemoHeroProperty_hp); //血量
int defend = GetAttr(DemoHeroProperty_defend); //防御
int rule = GetAttr(DemoHeroProperty_int); //统
int courage = GetAttr(DemoHeroProperty_str); //勇
int power = GetAttr(DemoHeroProperty_power);
hero->set_attack(attack);
hero->set_hp(hp);
hero->set_defend(defend);
hero->set_rule(rule);
hero->set_courage(courage);
hero->set_power(power);
}
private:
int val_[DemoHeroProperty_max];//英雄属性
};
//////////////////////////////////////////////////////////////////////////////////////
struct HeroPropertyItemIndex
{
unsigned uid;
unsigned id;//英雄id
HeroPropertyItemIndex()
{
uid = id = 0;
}
HeroPropertyItemIndex(unsigned u, unsigned i)
{
uid = u;
id = i;
}
bool operator <(const HeroPropertyItemIndex& other) const
{
if(uid != other.uid)
return uid < other.uid;
else
return id < other.id;
}
bool operator ==(const HeroPropertyItemIndex& other) const
{
if(uid == other.uid && id == other.id)
return true;
return false;
}
bool operator !=(const HeroPropertyItemIndex& other) const
{
if(uid == other.uid && id == other.id)
return false;
return true;
}
bool empty() const
{
return uid == 0;
}
bool IsUser() const
{
return IsValidUid(uid);
}
bool notHero() const
{
return uid && uid < ADMIN_UID;
}
bool isVision() const
{
return uid == e_vision_npc;
}
bool isOtherVision() const
{
return uid == e_vision_other;
}
bool isUserVision() const
{
return isVision() || isOtherVision();
}
bool isWorldNPC() const
{
return uid == e_normal_npc || uid == e_attack_npc || uid == e_defend_npc;
}
bool isWorldActNpc() const
{
return uid == e_act_npc;
}
bool isWorldTTTNpc() const
{
return uid == e_ttt_npc;
}
bool isWorldNBNpc() const
{
return uid == e_nb_npc;
}
bool isWorld() const
{
return isWorldNPC() || isWorldActNpc() || isWorldTTTNpc() || isWorldNBNpc();
}
bool isGateNPC() const
{
return uid == e_gate_npc;
}
bool notReal() const
{
return isGateNPC() || isOtherVision();
}
bool isPVE() const
{
return notHero() && !isUserVision();
}
void Clear()
{
uid = id = 0;
}
};
struct HeroPropertyItem
{
HeroPropertyItemIndex index;
int property[DemoHeroProperty_max];//英雄属性
int hp[SG17_HERO_SOLDIER];//各排血量
unsigned extraid;//副将id
uint16_t city;//所在城市
uint16_t gate;//所在关卡
unsigned ouid;//幻影的uid,npc的kingdom
unsigned oid;//npc或幻影的hero id
HeroPropertyItem()
{
extraid = city = gate = oid = ouid = 0;
memset(property, 0, sizeof(property));
memset(hp, 0, sizeof(hp));
}
void CreateVision(HeroPropertyItem& obj)
{
memcpy(property, obj.property, sizeof(property));
memcpy(hp, obj.hp, sizeof(hp));
extraid = obj.extraid;
city = obj.city;
gate = obj.gate;
ouid = obj.index.uid;
oid = obj.index.id;
bool flag = false;
for(unsigned i=0;i<SG17_HERO_SOLDIER;++i)
{
if(!flag && hp[i])
flag = true;
if(flag && hp[i] == 0)
break;
hp[i] = property[DemoHeroProperty_hp];
}
}
void CreateWorldNPC(unsigned k, unsigned c)
{
memset(property, 1, sizeof(property));
memset(hp, 0, sizeof(hp));
hp[0] = 1;
extraid = 0;
city = c;
gate = 0;
ouid = k;
oid = 0;
}
void CreateActNPC(unsigned k, unsigned c, unsigned id, unsigned s, unsigned h)
{
memset(property, 1, sizeof(property));
memset(hp, 0, sizeof(hp));
for(unsigned i=0;i<s;++i)
hp[i] = h;
extraid = 0;
city = c;
gate = 0;
ouid = k;
oid = id;
}
bool IsDie()
{
for(unsigned i=0;i<SG17_HERO_SOLDIER;++i)
{
if(hp[i])
return false;
}
return true;
}
void Die(uint16_t cid)
{
memset(hp, 0, sizeof(hp));
gate = 0;
city = cid;
//debug_log("die hero uid=%u,id=%u,cid=%u", index.uid, index.id, city);
}
void SyncHP(vector<int> h)
{
for(unsigned i=0;i<h.size();++i)
hp[i] = h[i];
}
bool IsNeedRecover(unsigned s)
{
s = min(s, (unsigned)SG17_HERO_SOLDIER);
unsigned h = 0;
for(unsigned i=0;i<s;++i)
h += hp[i];
return h * 4 < property[DemoHeroProperty_hp] * s;
}
void SetMessage(ProtoBattleField::Hero* msg, unsigned s)
{
if(extraid)
++s;
msg->set_id(index.id);
for(unsigned i=0;i<DemoHeroProperty_max;++i)
msg->add_property(property[i]);
for(unsigned i=0;i<s;++i)
msg->add_hp(hp[i]);
msg->set_extraid(extraid);
msg->set_city(city);
msg->set_gate(gate);
if(index.notHero())
{
msg->set_ouid(ouid);
msg->set_oid(oid);
}
}
unsigned SetMessage(ProtoBattleField::HidUid* msg)
{
msg->set_uid(index.uid);
msg->set_id(index.id);
if(index.notHero())
{
msg->set_ouid(ouid);
msg->set_oid(oid);
return ouid;
}
return index.uid;
}
void FullMessage(unsigned nTotalRows, ProtoHero::HeroSoldiersCPP* obj)
{
obj->set_heroid(index.id);
obj->set_max(GetTotalTroops(nTotalRows));
obj->set_soldiers(GetActualTroops(nTotalRows));
}
void UpdateProperty(const HeroFightAttr& fight_attr);
void GetHeroFightAttr(HeroFightAttr& fight_attr) const;
//总兵力//@input 英雄的总排数
//英雄上限兵力=英雄血量*3*士兵排数
unsigned GetTotalTroops(unsigned nTotalRows);
unsigned GetActualTroops(unsigned nTotalRows);
int GetFreeTroops(unsigned nTotalRows);
bool IsFullTroops(unsigned nTotalRows);
void RecruitSoldires(unsigned nTotalRows, int rate);
unsigned CalcRealRecruitSoldires(unsigned nTotalRows, int rate);
//恢复所有
void FullSoldires(unsigned nTotalRows);
};
struct HeroProperty
{
HeroPropertyItem item[MEMORY_HERO_PROPERTY_NUM*SG17_HERO_NUM];
unsigned npc_id;
HeroProperty()
{
npc_id = 0;
}
HeroPropertyItemIndex CreateNPCIndex(unsigned type)
{
return HeroPropertyItemIndex(type, ++npc_id);
}
};
typedef map<HeroPropertyItemIndex, unsigned> HeroPropertyMap;
typedef map<unsigned, set<HeroPropertyItemIndex> > HeroIndexMap;
class HeroPropertyManager : public MemorySingleton<HeroProperty, MEMORY_HERO_PROPERTY>, public CSingleton<HeroPropertyManager>
{
private:
friend class CSingleton<HeroPropertyManager>;
HeroPropertyManager(){};
virtual ~HeroPropertyManager(){}
set<unsigned> m_freeIndex;
HeroPropertyMap m_map;
HeroIndexMap m_indexmap;
public:
virtual void CallDestroy() {Destroy();}
virtual int OnInit();
const HeroPropertyMap& GetMap() {return m_map;}
const HeroIndexMap& GetIndexMap(){return m_indexmap;}
unsigned GetFreeCount()
{
return m_freeIndex.size();
}
unsigned GetFreeIndex()
{
if(m_freeIndex.empty())
return -1;
return *(m_freeIndex.begin());
}
bool IsNeedClear()
{
return GetFreeCount() * 10 / (MEMORY_HERO_PROPERTY_NUM*SG17_HERO_NUM) <= 1;
}
void DoClear(unsigned uid)
{
if(m_indexmap.count(uid))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[uid].begin();it!=m_indexmap[uid].end();++it)
{
unsigned i = m_map[*it];
memset(&(m_data->item[i]), 0, sizeof(HeroPropertyItem));
m_freeIndex.insert(i);
m_map.erase(*it);
}
m_indexmap.erase(uid);
}
if(m_indexmap.count(e_vision_npc))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[e_vision_npc].begin();it!=m_indexmap[e_vision_npc].end();++it)
{
unsigned i = m_map[*it];
if(m_data->item[i].ouid == uid)
{
memset(&(m_data->item[i]), 0, sizeof(HeroPropertyItem));
m_freeIndex.insert(i);
m_map.erase(*it);
}
}
if(m_indexmap[e_vision_npc].empty())
m_indexmap.erase(e_vision_npc);
}
if(m_indexmap.count(e_attack_npc))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[e_attack_npc].begin();it!=m_indexmap[e_attack_npc].end();++it)
{
unsigned i = m_map[*it];
memset(&(m_data->item[i]), 0, sizeof(HeroPropertyItem));
m_freeIndex.insert(i);
m_map.erase(*it);
}
m_indexmap.erase(e_attack_npc);
}
if(m_indexmap.count(e_defend_npc))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[e_defend_npc].begin();it!=m_indexmap[e_defend_npc].end();++it)
{
unsigned i = m_map[*it];
memset(&(m_data->item[i]), 0, sizeof(HeroPropertyItem));
m_freeIndex.insert(i);
m_map.erase(*it);
}
m_indexmap.erase(e_defend_npc);
}
}
bool GetHeros(unsigned uid, set<HeroPropertyItemIndex>& hero)
{
if(m_indexmap.count(uid))
{
hero = m_indexmap[uid];
return true;
}
return false;
}
bool GetHeros(unsigned uid, vector<HeroPropertyItemIndex>& hero)
{
if(m_indexmap.count(uid))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[uid].begin();it!=m_indexmap[uid].end();++it)
hero.push_back(*it);
return true;
}
return false;
}
bool HasHero(HeroPropertyItemIndex index)
{
return m_map.count(index);
}
unsigned GetIndex(HeroPropertyItemIndex index)
{
if(m_map.count(index))
return m_map[index];
return -1;
}
int Add(HeroPropertyItemIndex index)
{
unsigned i = GetFreeIndex();
if(i == (unsigned)-1)
return R_ERR_DATA;
m_freeIndex.erase(i);
m_map[index] = i;
m_indexmap[index.uid].insert(index);
m_data->item[i].index = index;
return 0;
}
void Del(HeroPropertyItemIndex index)
{
if(m_map.count(index))
{
unsigned i = m_map[index];
memset(&(m_data->item[i]), 0, sizeof(HeroPropertyItem));
m_freeIndex.insert(i);
m_map.erase(index);
m_indexmap[index.uid].erase(index);
if(m_indexmap[index.uid].empty())
m_indexmap.erase(index.uid);
}
}
HeroPropertyItem& Get(unsigned uid, unsigned heroId)
{
HeroPropertyItemIndex index(uid, heroId);
if(m_map.count(index))
{
unsigned i = m_map[index];
return m_data->item[i];
}
error_log("get_hero_property_error. uid=%u,hero=%u", uid, heroId);
throw std::runtime_error("get_hero_property_error");
}
void SetMessage(unsigned uid, ProtoBattleField::Field* msg, unsigned s)
{
if(m_indexmap.count(uid))
{
for(set<HeroPropertyItemIndex>::iterator it=m_indexmap[uid].begin();it!=m_indexmap[uid].end();++it)
m_data->item[m_map[*it]].SetMessage(msg->add_hero(), s);
}
}
HeroPropertyItemIndex CreateVision(HeroPropertyItemIndex hi)
{
HeroPropertyItemIndex vi = m_data->CreateNPCIndex(e_vision_npc);
Add(vi);
m_data->item[m_map[vi]].CreateVision(m_data->item[m_map[hi]]);
return vi;
}
HeroPropertyItemIndex CreateWorldNPC(unsigned t, unsigned k, unsigned c)
{
HeroPropertyItemIndex ni = m_data->CreateNPCIndex(t);
if(Add(ni))
ni.Clear();
else
m_data->item[m_map[ni]].CreateWorldNPC(k, c);
return ni;
}
HeroPropertyItemIndex CreateActNPC(unsigned type, unsigned k, unsigned c, unsigned id, unsigned s, unsigned h)
{
HeroPropertyItemIndex ni = m_data->CreateNPCIndex(type);
if(Add(ni))
ni.Clear();
else
m_data->item[m_map[ni]].CreateActNPC(k, c, id, s, h);
return ni;
}
};
#endif /* HEROPROPERTYMANAGER_H_ */
| true |
09b0a6306cb5ecb115c30ea3a37e2beba2d23543 | C++ | BigRoss/stickmanGame | /Stage2BaseCodeB/positioninterface.h | UTF-8 | 488 | 2.78125 | 3 | [] | no_license | #ifndef POSITIONINTERFACE_H
#define POSITIONINTERFACE_H
class PositionInterface
{
public:
PositionInterface();
PositionInterface(int x, int y);
~PositionInterface();
virtual void set_x(int x);
virtual void set_y(int y);
virtual void set_position(int x, int y);
virtual int get_x();
virtual int get_y();
virtual int get_z();
virtual void set_z(int z) = 0;
protected:
int xpos;
int ypos;
int z_value;
};
#endif // POSITIONINTERFACE_H
| true |
09b323da6ab90f2e561ea4d90eaad3027521ba7f | C++ | AyushYadav/competetiveArchive | /hourglass.cpp | UTF-8 | 785 | 3.0625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <iostream>
#define n 6
using namespace std;
int retCount(int arr[][n],int k, int l){ // Row count == k Column Count == l
int cnt=0;
//if(n>=3) return 0;
for(int i=k;i<(k+3);i+=2){
for(int j=l;j<(l+3);j++){
cnt+=arr[i][j];
}
}
//cout << arr[k+1][l+1];
cnt+=arr[k+1][l+1];
//cout << cnt<<"\n";
return cnt;
}
int retMaxCount(int arr[][n]){
int maxCount=-1000;
for(int i=0;i<=3;i++){
for(int j=0;j<=3;j++){
int cnt=retCount(arr,i,j);
if(cnt>maxCount)
maxCount=cnt;
}
}
// cout << maxCount;
return maxCount;
}
int main(){
int arr[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin >> arr[i][j];
int answer=retMaxCount(arr);
cout << answer;
return 0;
}
| true |
b2a9f365e97c9930f0f25d6cca37594ebedb2afc | C++ | aaroexxt/BikeOSMKII | /bikeOS/useless code/bigFont.cpp | UTF-8 | 11,746 | 3.0625 | 3 | [] | no_license | /*
Custom large numbers that look hot
Credit to Michael Pilcher, adapted by Aaron Becker
*/
//big font library
#include <Arduino.h>
#include "bigFont.h"
#include "bigFontChars.h"
#include <LiquidCrystal_I2C.h>
//Constant data declaration
int bigFont::writeString(String str, int xPos, int yPos) {
int strLen = str.length()+1; //optimize gang!
char charBuffer[strLen];
str.toCharArray(charBuffer, strLen);
for (int i=0; i<strLen; i++) {
//Serial.println(charBuffer[i]);
writeChar(charBuffer[i], xPos, yPos);
xPos+=4;
}
return xPos; //returns new pos
}
int bigFont::writeChar(char tW, int x, int y) {
if (tW >= 65 && tW <= 90) {
tW = tolower(tW);
}
switch (tW) { //lower case char, will only affect letters
case '0':
case 'o':
custom0O(x, y);
break;
case '1':
custom1(x, y);
break;
case '2':
custom2(x, y);
break;
case '3':
custom3(x, y);
break;
case '4':
custom4(x, y);
break;
case '5':
custom5(x, y);
break;
case '6':
custom6(x, y);
break;
case '7':
custom7(x, y);
break;
case '8':
custom8(x, y);
break;
case '9':
custom9(x, y);
break;
case 'a':
customA(x, y);
break;
case 'b':
customB(x, y);
break;
case 'c':
customC(x, y);
break;
case 'd':
customD(x, y);
break;
case 'e':
customE(x, y);
break;
case 'f':
customF(x, y);
break;
case 'g':
customG(x, y);
break;
case 'h':
customH(x, y);
break;
case 'i':
customI(x, y);
break;
case 'j':
customJ(x, y);
break;
case 'k':
customK(x, y);
break;
case 'l':
customL(x, y);
break;
case 'm':
customM(x, y);
break;
case 'n':
customN(x, y);
break;
case 'p':
customP(x, y);
break;
case 'q':
customQ(x, y);
break;
case 'r':
customR(x, y);
break;
case 's':
customS(x, y);
break;
case 't':
customT(x, y);
break;
case 'u':
customU(x, y);
break;
case 'v':
customV(x, y);
break;
case 'w':
customW(x, y);
break;
case 'x':
customX(x, y);
break;
case 'y':
customY(x, y);
break;
case 'z':
customZ(x, y);
break;
}
return x+4; //return new xPos
}
bigFont::bigFont(LiquidCrystal_I2C & lcd) : lcdRef (lcd) {
//Assign segments write numbers
lcdRef.createChar(8,C_LT);
lcdRef.createChar(1,C_UB);
lcdRef.createChar(2,C_RT);
lcdRef.createChar(3,C_LL);
lcdRef.createChar(4,C_LB);
lcdRef.createChar(5,C_LR);
lcdRef.createChar(6,C_UMB);
lcdRef.createChar(7,C_LMB);
}
void bigFont::custom0O(int offsetX, int offsetY)
{ // uses segments to build the number 0
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(1);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(5);
}
void bigFont::custom1(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(2);
lcdRef.setCursor(offsetX+1, offsetY+1);
lcdRef.write(255);
}
void bigFont::custom2(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(7);
lcdRef.write(7);
}
void bigFont::custom3(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(7);
lcdRef.write(7);
lcdRef.write(5);
}
void bigFont::custom4(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(2);
lcdRef.setCursor(offsetX+2, offsetY+1);
lcdRef.write(255);
}
void bigFont::custom5(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(7);
lcdRef.write(7);
lcdRef.write(5);
}
void bigFont::custom6(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(7);
lcdRef.write(5);
}
void bigFont::custom7(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(1);
lcdRef.write(2);
lcdRef.setCursor(offsetX+1, offsetY+1);
lcdRef.write(8);
}
void bigFont::custom8(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(7);
lcdRef.write(5);
}
void bigFont::custom9(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX+2, offsetY+1);
lcdRef.write(255);
}
void bigFont::customA(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(255);
}
void bigFont::customB(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(5);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(7);
lcdRef.write(2);
}
void bigFont::customC(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(1);
lcdRef.write(1);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(4);
}
void bigFont::customD(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(1);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(4);
lcdRef.write(5);
}
void bigFont::customE(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(7);
lcdRef.write(7);
}
void bigFont::customF(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
}
void bigFont::customG(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(1);
lcdRef.write(1);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(2);
}
void bigFont::customH(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(4);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(255);
}
void bigFont::customI(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(255);
lcdRef.write(1);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(4);
lcdRef.write(255);
lcdRef.write(4);
}
void bigFont::customJ(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX+2, offsetY);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(4);
lcdRef.write(4);
lcdRef.write(5);
}
void bigFont::customK(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(4);
lcdRef.write(5);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(2);
}
void bigFont::customL(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(4);
lcdRef.write(4);
}
void bigFont::customM(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(3);
lcdRef.write(5);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(254);
lcdRef.write(255);
}
void bigFont::customN(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(2);
lcdRef.write(254);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(3);
lcdRef.write(5);
}
void bigFont::customP(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
}
void bigFont::customQ(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(1);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(255);
lcdRef.write(4);
}
void bigFont::customR(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(2);
}
void bigFont::customS(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(8);
lcdRef.write(6);
lcdRef.write(6);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(7);
lcdRef.write(7);
lcdRef.write(5);
}
void bigFont::customT(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(255);
lcdRef.write(1);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(254);
lcdRef.write(255);
}
void bigFont::customU(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(5);
}
void bigFont::customV(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(3);
lcdRef.write(254);
lcdRef.write(254);
lcdRef.write(5);
lcdRef.setCursor(offsetX+1, offsetY+1);
lcdRef.write(2);
lcdRef.write(8);
}
void bigFont::customW(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.write(254);
lcdRef.write(254);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(3);
lcdRef.write(8);
lcdRef.write(2);
lcdRef.write(5);
}
void bigFont::customX(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(5);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(8);
lcdRef.write(254);
lcdRef.write(2);
}
void bigFont::customY(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(3);
lcdRef.write(4);
lcdRef.write(5);
lcdRef.setCursor(offsetX+1, offsetY+1);
lcdRef.write(255);
}
void bigFont::customZ(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(6);
lcdRef.write(5);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(8);
lcdRef.write(7);
lcdRef.write(4);
}
void bigFont::customQM(int offsetX, int offsetY) //Question mark
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(1);
lcdRef.write(6);
lcdRef.write(2);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(254);
lcdRef.write(7);
}
void bigFont::customSM(int offsetX, int offsetY)
{
lcdRef.setCursor(offsetX, offsetY);
lcdRef.write(255);
lcdRef.setCursor(offsetX, offsetY+1);
lcdRef.write(7);
}
| true |