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 |
---|---|---|---|---|---|---|---|---|---|---|---|
112f5ce50dbea9d3be663a524c162930241981f8
|
C++
|
flashxio/FlashX
|
/libsafs/unit-test/GClock_unit_test.cpp
|
UTF-8
| 7,548 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <sys/time.h>
#include "gclock.h"
void testEnhancedGClock()
{
const int BUF_SIZE = 5;
enhanced_gclock_buffer buffer(BUF_SIZE);
LF_gclock_buffer lf_buffer(BUF_SIZE);
for (int i = 0; i < BUF_SIZE; i++) {
frame *f = new frame(i * PAGE_SIZE, (char *) NULL);
frame *f1 = new frame(i * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
f->incrWC(r);
f1->incrWC(r);
frame *ret = buffer.add(f);
lf_buffer.add(f1);
assert(ret == NULL);
}
// buffer.print();
for (int i = 0; i < BUF_SIZE * 4000000; i++) {
frame *f = new frame((i + BUF_SIZE) * PAGE_SIZE, (char *) NULL);
frame *f1 = new frame((i + BUF_SIZE) * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
f->incrWC(r);
f1->incrWC(r);
frame *ret = buffer.add(f);
frame *tmp = lf_buffer.add(f1);
// printf("the evicted frame from buffer is offset %ld, hits: %d\n",
// ret->get_offset(), ret->getWC());
// printf("the evicted frame from lf_buffer is offset %ld, hits: %d\n",
// tmp->get_offset(), tmp->getWC());
assert(ret);
assert(ret->get_offset() == tmp->get_offset());
delete ret;
delete tmp;
// buffer.print();
// lf_buffer.print();
}
}
/**
* This is to test the linked page list.
* It prints the page list and I have to manually check the correctness
* of the status of the list.
*/
void testLinkedPageList()
{
const int LIST_SIZE = 8;
linked_page_queue list;
/* Add 8 frames to the list */
for (int i = 0; i < LIST_SIZE; i++) {
frame *f = new frame(i * PAGE_SIZE, (char *) NULL);
list.push_back(f);
}
list.print();
frame *tmp = new frame (LIST_SIZE * PAGE_SIZE, (char *) NULL);
printf("replace frame %ld with frame %ld\n", list.front()->get_offset(), tmp->get_offset());
linked_page_queue::iterator it = list.begin();
it.next();
it.set(tmp);
list.print();
printf("\n");
tmp = new frame ((LIST_SIZE + 1) * PAGE_SIZE, (char *) NULL);
it.next();
frame *replaced = it.next();
printf("replace frame %ld with frame %ld\n", replaced->get_offset(), tmp->get_offset());
it.set(tmp);
list.print();
printf("\n");
/* Randomly remove a frame from the list. */
int r = random() % list.size();
printf("remove %dth frame\n", r);
list.remove(r);
list.print();
printf("\n");
/* Create another list with 8 frames, and merge it to the first list. */
linked_page_queue list1;
for (int i = LIST_SIZE + 2; i < LIST_SIZE * 2; i++) {
frame *f = new frame(i * PAGE_SIZE, (char *) NULL);
list1.push_back(f);
}
printf("a new created list\n");
list1.print();
list.merge(&list1);
printf("the merged list\n");
list.print();
printf("the new created list after merging\n");
list1.print();
printf("\n");
int i = 0;
printf("print and remove the second page simultaneously\n");
for (linked_page_queue::iterator it = list.begin(); it.has_next(); i++) {
it.next();
if (2 == i)
it.remove();
printf("%ld\t", it.curr()->get_offset());
}
printf("\nthe list has %d pages\n", list.size());
}
/**
* This is to test the behavior of the enhanced gclock with one range.
* Since the result of the enhanced gclock with one range is exactly
* the same as original gclock, the test is to compare the result from
* the two versions of gclock.
*/
void testEnhanced1GClock()
{
const int BUF_SIZE = 5;
int ranges[] = {0};
/*
* When there is only one range, enhanced_gclock_buffer1 should behave
* exactly the same as enhanced_gclock_buffer.
*/
enhanced_gclock_buffer1 buffer(BUF_SIZE, ranges, 1);
LF_gclock_buffer lf_buffer(BUF_SIZE);
for (int i = 0; i < BUF_SIZE; i++) {
frame *f = new frame(i * PAGE_SIZE, (char *) NULL);
frame *f1 = new frame(i * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
frame *ret = buffer.add(f);
lf_buffer.add(f1);
f->incrWC(r);
f1->incrWC(r);
assert(ret == NULL);
}
for (int i = 0; i < 1000000; i++) {
frame *f = new frame(((long) i + BUF_SIZE) * PAGE_SIZE, (char *) NULL);
frame *f1 = new frame(((long) i + BUF_SIZE) * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
frame *ret = buffer.add(f);
frame *tmp = lf_buffer.add(f1);
f->incrWC(r);
f1->incrWC(r);
assert(ret);
printf("ret: %ld, tmp: %ld\n", ret->get_offset(), tmp->get_offset());
assert(ret->get_offset() == tmp->get_offset());
delete ret;
delete tmp;
}
}
/**
* This is to test the behavior of the enhanced gclock with multiple ranges.
* Its behavior is different from the original version, so this test is to run
* many times and print the buffer each time a page is added to the buffer.
*/
void test1Enhanced1GClock()
{
const int BUF_SIZE = 5;
int ranges[] = {0, 5};
enhanced_gclock_buffer1 buffer(BUF_SIZE, ranges, 2);
for (int i = 0; i < BUF_SIZE; i++) {
frame *f = new frame(i * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
frame *ret = buffer.add(f);
f->incrWC(r);
assert(ret == NULL);
}
buffer.print();
for (int i = 0; i < 1000000; i++) {
frame *f = new frame((long) (i + BUF_SIZE) * PAGE_SIZE, (char *) NULL);
int r = random() % 40;
frame *ret = buffer.add(f);
f->incrWC(r);
buffer.print();
assert(ret);
delete ret;
}
}
/**
* This is to measure the performance of three versions of gclock.
* I only measure the performance in terms of the number of writes
* to the shared memory instead of running time.
*/
void testPerformance()
{
const int BUF_SIZE = 1000;
int ranges[] = {0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024};
enhanced_gclock_buffer1 buffer1(BUF_SIZE, ranges, 11);
enhanced_gclock_buffer buffer(BUF_SIZE);
LF_gclock_buffer lf_buffer(BUF_SIZE);
struct timeval start, end;
srandom(0);
gettimeofday(&start, NULL);
for (int i = 0; i < BUF_SIZE * 1000; i++) {
frame *f1 = new frame((long) i * PAGE_SIZE, (char *) NULL);
int r = random() % 2048;
f1->incrWC(r);
frame *ret = buffer1.add(f1);
if (ret)
delete ret;
}
gettimeofday(&end, NULL);
printf("it takes %.3f seconds\n",
end.tv_sec - start.tv_sec + ((double) end.tv_usec - start.tv_usec) / 1000000);
buffer1.print(true);
printf("\n");
srandom(0);
gettimeofday(&start, NULL);
for (int i = 0; i < BUF_SIZE * 1000; i++) {
frame *f = new frame((long) i * PAGE_SIZE, (char *) NULL);
int r = random() % 2048;
f->incrWC(r);
frame *ret = buffer.add(f);
if (ret)
delete ret;
}
gettimeofday(&end, NULL);
printf("it takes %.3f seconds\n",
end.tv_sec - start.tv_sec + ((double) end.tv_usec - start.tv_usec) / 1000000);
buffer.print(true);
printf("\n");
srandom(0);
gettimeofday(&start, NULL);
for (int i = 0; i < BUF_SIZE * 1000; i++) {
frame *lf_f = new frame((long) i * PAGE_SIZE, (char *) NULL);
int r = random() % 2048;
lf_f->incrWC(r);
frame *ret = lf_buffer.add(lf_f);
if (ret)
delete ret;
}
gettimeofday(&end, NULL);
printf("it takes %.3f seconds\n",
end.tv_sec - start.tv_sec + ((double) end.tv_usec - start.tv_usec) / 1000000);
lf_buffer.print(true);
}
int main()
{
// testEnhancedGClock();
printf("test the linked page list. I have to manually check its correctness\n");
testLinkedPageList();
printf("press any key to go to the next test\n");
getchar();
printf("test the enhanced gclock with one range. This test is automic.\n");
testEnhanced1GClock();
printf("press any key to go to the next test\n");
getchar();
printf("test the enhanced gclock with multiple ranges.\n");
printf("It prints the buffer each time a page is added\n");
test1Enhanced1GClock();
printf("press any key to go to the next test\n");
getchar();
printf("measure the performance of three versions of gclock in terms of number of writes to shared memory\n");
testPerformance();
}
| true |
b895ecfa2f31bf51ae154866a3feaecc496e0460
|
C++
|
5cript/mc-modpack-updater
|
/main.cpp
|
UTF-8
| 2,597 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
#include "mod_list.hpp"
#include <iostream>
#include <filesystem>
using namespace std::string_literals;
int main()
{
ModList list;
list.load("modlist.json");
std::cout << "Enter command:\n";
std::cout << "\tu = update\n";
std::cout << "\tl = list new\n";
std::cout << "\tq = quit\n";
char command;
std::cin >> command;
if (command == 'q')
return 0;
if (command == 'u')
{
std::filesystem::create_directory("mods_old");
}
int i = 1;
for (auto& mod: list.mods)
{
auto files = mod.getFiles();
if (files.empty())
{
std::cout << "WARNING! no files found for " << mod.id;
continue;
}
std::cout << i << "/" << list.mods.size() << ") ";
auto newest = files.front();
if (mod.isNewer(newest.timeEpoch))
{
if (mod.mcVersion && mod.mcVersion.value() != newest.mcVersion)
{
bool foundOne = false;
for (auto const file : files)
{
if (file.mcVersion == mod.mcVersion.value())
{
foundOne = true;
newest = file;
break;
}
}
if (!foundOne)
{
std::cout << mod.id << " - ERROR! MC version switch needs manual intervention.";
continue;
}
}
if (command == 'l')
{
std::cout << newest.name;
}
else if (command == 'u')
{
if (!mod.name)
mod.readName();
if (mod.installedName)
std::filesystem::rename("mods/"s + mod.installedName.value(), "mods_old/"s + mod.installedName.value());
newest.download("mods");
std::cout << mod.name.value() << " updated";
mod.installedName = newest.name;
mod.newestInstalled = newest.timeEpoch;
mod.mcVersion = newest.mcVersion;
}
}
else
{
if (mod.name)
std::cout << mod.name.value() << " up to date";
else
std::cout << mod.id << " up to date";
}
std::cout << "\n";
++i;
}
if (command == 'u')
{
list.save("modlist.json");
}
return 0;
}
| true |
d64dbf45b97980fc998e98096b8c87e6edfd1ecc
|
C++
|
LaLlorona/Algorithms
|
/BOJ/10001To15000/11722.cpp
|
UTF-8
| 803 | 2.703125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <utility>
#include <queue>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
int LIS[1001] = {1,};
int seq[1001] = {0,};
int CalcLIS() {
LIS [n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (seq[i] > seq[j]) {
LIS[i] = max(LIS[i], 1 + LIS[j]);
}
}
}
int ret = 0;
for (int i = 0; i < n; i++) {
ret = max(ret, LIS[i]);
}
return ret;
}
int main()
{
// std::ifstream in("in.txt");
// std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
// std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
cin >> n;
for (int i = 0; i < n; i++) {
LIS[i] = 1;
cin >> seq[i];
}
cout << CalcLIS() << endl;
return 0;
}
| true |
5212ab09e58a2d216eaf34d6d03f14195f9e81fe
|
C++
|
kennethh387/proyecto_kenneth_hern-ndez_1190618
|
/lista.h
|
UTF-8
| 2,057 | 3.640625 | 4 |
[] |
no_license
|
#pragma
#include "Comparar.h"
template <typename T>
class lista
{
struct Node
{
T* item;
Node* siguiente;
Node(T* item) {
this->item = item;
this->siguiente = nullptr;
}
};
Node* cabeza;
Node* cola;
int size = 0;
public:
int getSize() {
return this->size;
}
bool vacio() {
return this->size == 0;
}
void agregar(T* item) {
Node* node = new Node(item);
if (this->vacio())
{
this->cabeza = this->cola = node;
}
else
{
this->cola->siguiente = node;
this->cola = this->cola->siguiente;
}
this->size++;
}
T* Obtener(int index) {
if (index >= this->size || index < 0)
{
return nullptr;
}
Node* iterador = this->cabeza;
int i = 0;
while (i < index)
{
iterador = iterador->siguiente;
i++;
}
return iterador->item;
}
T* eliminar(int index) {
if (index >= this->size || index < 0)
{
return nullptr;
}
Node** iterador = &this->cabeza;
Node* anterior = nullptr;
int i = 0;
while (i< index)
{
anterior = *iterador;
iterador = &((*iterador)->siguiente);
i++;
}
if (this->size - 1 == index)
{
this->cola = anterior;
}
*iterador = (*iterador)->siguiente;
this->size--;
}
lista<T>* bubblesort(Comparar<T>* comparar) {
Node** i = &(this->cabeza);
while (*i != nullptr)
{
Node** j = &(*i)->siguiente;
while (*j != nullptr)
{
T** itemA = &(*i)->item;
T** itemB = &(*j)->item;
if (comparar->compare(**itemA , **itemB) > 0)
{
T* aux = *itemA;
*itemA = *itemB;
*itemB = aux;
}
j = &(*j) ->siguiente;
}
i = &(*i)->siguiente;
}
return this;
}
lista<T>* bubblesorted(Comparar<T>* comparar) {
Node** i = &(this->cabeza);
while (*i != nullptr)
{
Node** j = &(*i)->siguiente;
while (*j != nullptr)
{
T** itemA = &(*i)->item;
T** itemB = &(*j)->item;
if (comparar->compare(**itemA, **itemB) < 0)
{
T* aux = *itemA;
*itemA = *itemB;
*itemB = aux;
}
j = &(*j)->siguiente;
}
i = &(*i)->siguiente;
}
return this;
}
};
| true |
3334d1f9e8ef0ef5fad18731f5279c7adbca3aaf
|
C++
|
lkcbharath/CP-Solutions
|
/Codeforces/118A.cpp
|
UTF-8
| 431 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
str = "";
char c;
scanf("%c", &c);
c = tolower(c);
while (c >= 97 && c <= 122)
{
if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != 'y')
{
str += '.';
str += c;
}
scanf("%c", &c);
c = tolower(c);
}
cout << str;
return 0;
}
| true |
a51622bc969cb722b38d41177e2a7ac2639b5922
|
C++
|
s4chin/UVa-Solutions
|
/00341.cpp
|
UTF-8
| 1,085 | 2.703125 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define INF 1e9
int fw[15][15], p[15][15], n, d, r, source, destination, neighbor, number(0);
void printPath(int i, int j) {
if(i!=j) printPath(i, p[i][j]);
printf(" %d", j);
}
int main() {
while(true) {
scanf("%d", &n);
if(n==0) break;
else {
number++;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
fw[i][j] = INF;
for(int i=1; i<=n; i++) {
scanf("%d", &r);
if(r==0)continue;
for(int j=1; j<=r; j++) {
scanf("%d%d", &neighbor, &d);
fw[i][neighbor] = d;
}
}
scanf("%d%d", &source, &destination);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
p[i][j] = i;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
for(int k=1; k<=n; k++)
if(fw[i][k] + fw[k][j] < fw[i][j]) {
fw[i][j] = fw[i][k] + fw[k][j];
p[i][j] = p[k][j];
}
printf("Case %d: Path = ", number);
printPath(source, destination);
printf("; %d second delay\n", fw[source][destination]);
}
}
return 0;
}
| true |
6efb8ff48ca0384b0968b919e0ae3d52fd0bedfe
|
C++
|
bryce-bowers/CS-130A
|
/user_network.cpp
|
UTF-8
| 3,223 | 3.109375 | 3 |
[] |
no_license
|
#include "user_network.h"
#include "wall.h"
#include "user.h"
#include "doubly_linked_list.h"
#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
User* UserNetwork::QueryUser(string uname) {
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
if ((*it).GetUserName() == uname)
return &(*it);
}
return NULL;
}
bool UserNetwork::UserExists(string uname) {
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
if ((*it).GetUserName() == uname)
return true;
}
return false;
}
void UserNetwork::AddUser(string uname, string pass, string rname, string bday) {
if (UserExists(uname)) {
return;
}
Wall* wall = new Wall(uname);
User* user = new User(uname, pass, rname, bday, wall, this);
users.insert(0, *user);
}
void UserNetwork::DeleteUser(string uname) {
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
if ((*it).GetUserName() == uname)
users.remove(it);
}
}
void UserNetwork::WriteUsersToFile(string fname) {
ofstream output_file(fname);
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
output_file << (*it).RetrieveInfo();
}
output_file.close();
}
void UserNetwork::CreateUsersFromFile(string fname) {
ifstream input_file(fname);
if (!input_file) {
cout << "File doesn't exist." << endl;
return;
}
cout << "Adding users from file: " << fname << endl;
string data ((std::istreambuf_iterator<char>(input_file)),
(std::istreambuf_iterator<char>()));
size_t cur_pos = data.find("USERNAME", 0);
if (cur_pos == string::npos) {
cout << "No user data found." << endl;
return;
}
size_t next_pos = data.find("USERNAME", cur_pos+1);
string user_data;
while (next_pos != string::npos) {
user_data = data.substr(cur_pos, next_pos - cur_pos);
User *user = new User(this);
user->ConstructUserFromString(user_data);
users.insert(0, *user);
cur_pos = next_pos;
next_pos = data.find("USERNAME", cur_pos + 1);
}
user_data = data.substr(cur_pos, data.length());
User *user = new User(this);
user->ConstructUserFromString(user_data);
users.insert(0, *user);
input_file.close();
}
User* UserNetwork::AuthorizeUser(string uname, string pass) {
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
if ((*it).GetUserName() == uname && (*it).GetPassword() == pass)
return &(*it);
}
return NULL;
}
void UserNetwork::SearchUser(string keyword) {
transform(keyword.begin(), keyword.end(), keyword.begin(), ::tolower);
DoublyLinkedList<User>::iterator it;
for (it = users.begin(); it != users.end(); it++) {
string uname = it->GetUserName();
string rname = it->GetRealName();
transform(uname.begin(), uname.end(), uname.begin(), ::tolower);
transform(rname.begin(), rname.end(), rname.begin(), ::tolower);
if(uname.find(keyword) != string::npos || rname.find(keyword) != string::npos) {
cout << "Username: " << it->GetUserName()
<< " Realname: " << it->GetRealName() << endl;
}
}
}
| true |
7c8f3cf2e8ade751caac5ec031f3c46c0816db46
|
C++
|
SeungkwanKang/baekjoon_answers_cpp
|
/src/2231.cpp
|
UTF-8
| 429 | 2.671875 | 3 |
[] |
no_license
|
/* Copyright https://www.acmicpc.net/problem/2798
* Generator
* KangSK
*/
#include <iostream>
#include <cmath>
#include "includes/basics.hpp"
int main(void)
{
std::cin.tie(NULL);
std::ios_base::sync_with_stdio(false);
std::cout.precision(10);
int N;
std::cin >> N;
for (int i = 0; i < N; i++)
{
if ((i + sumOfDigits(i)) == N)
{
std::cout << i << '\n';
return 0;
}
}
std::cout << "0\n";
return 0;
}
| true |
19171c69aedc4530f32630aa41317efd8447c9c8
|
C++
|
ljmccarthy/amp
|
/src/types.cpp
|
UTF-8
| 3,331 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#include <cstring>
#include <cassert>
#include "lisp.h"
Type *type_table[NUM_TYPE_CODES];
#define init_type(code, name) \
type_table[code] = new Type(code, make_symbol(name))
void
init_types(void)
{
init_type(TC_CONST, "const");
init_type(TC_BOOL, "bool");
init_type(TC_TYPE, "type");
init_type(TC_FIXNUM, "fixnum");
init_type(TC_CHAR, "char");
init_type(TC_STRING, "string");
init_type(TC_SYMBOL, "symbol");
init_type(TC_AST_PROCEDURE, "ast-procedure");
init_type(TC_C_PROCEDURE, "c-procedure");
init_type(TC_CC_PROCEDURE, "cc-procedure");
type_table[TC_PAIR] = new RecordType(TC_PAIR,
make_symbol("pair"),
cons(make_symbol("car"),
cons(make_symbol("cdr"), NIL)));
}
TypeCode
alloc_type_code(void)
{
static TypeCode tc = TC_USER;
return tc++;
/* TODO: bit-tree type id allocator */
}
RecordType::RecordType(TypeCode typecode, Symbol *name, Value slots)
: Type(typecode, name, TC), slots(slots), nslots(length(slots)),
_cons(0)
{
type_table[typecode] = this;
/*
TODO:
check for non-nil slot list
check all slots names are unique
type extension
*/
}
struct Record : Object {
Value slots[];
};
#define as_product_value(x) _Value_as(x, Record)
static CCProcedure::proc_type constructor, accessor, mutator;
struct Constructor : CCProcedure {
RecordType *type;
inline Constructor(RecordType *type)
: CCProcedure(sym_at_constructor, type->nslots, constructor),
type(type) {}
};
struct Accessor : CCProcedure {
TypeCode typecode;
unsigned index;
inline Accessor(TypeCode typecode, unsigned index)
: CCProcedure(sym_at_accessor, 1, accessor),
typecode(typecode), index(index) {}
};
struct Mutator : CCProcedure {
TypeCode typecode;
unsigned index;
inline Mutator(TypeCode typecode, unsigned index)
: CCProcedure(sym_at_mutator, 2, mutator),
typecode(typecode), index(index) {}
};
static Value
constructor(void *_self, UNUSED unsigned nargs, Value *args)
{
Constructor *self = (Constructor *)_self;
assert(nargs == self->type->nslots);
size_t slotsize = self->type->nslots * sizeof(Value);
Record *p = (Record *) Object::operator new(
sizeof(Record) + slotsize);
p->init_hdr(self->type->typecode);
memcpy(p->slots, args, slotsize);
return p;
}
static Value
accessor(void *_self, UNUSED unsigned nargs, Value *args)
{
Accessor *self = (Accessor *)_self;
if (!is_ptr(args[0]) || as_ptr(args[0])->typecode() != self->typecode)
type_error(self->name->value);
return as_product_value(args[0])->slots[self->index];
}
static Value
mutator(void *_self, UNUSED unsigned nargs, Value *args)
{
Mutator *self = (Mutator *)_self;
if (!is_ptr(args[0]) || as_ptr(args[0])->typecode() != self->typecode)
type_error(self->name->value);
as_product_value(args[0])->slots[self->index] = args[1];
return NIL;
}
Procedure *
RecordType::constructor()
{
return _cons ? _cons : (_cons = new Constructor(this));
}
/* TODO: cache accessor */
Procedure *
RecordType::accessor(Symbol *slot)
{
int index = memq_index(slot, slots);
if (index < 0)
errorf(Error(), "slot not found: %s", slot->value);
return new Accessor(typecode, index);
}
/* TODO: cache mutator */
Procedure *
RecordType::mutator(Symbol *slot)
{
int index = memq_index(slot, slots);
if (index < 0)
errorf(Error(), "slot not found: %s", slot->value);
return new Mutator(typecode, index);
}
| true |
1b5babdd2bfda423bdcfd496eec29d233b0d376c
|
C++
|
unix1986/universe
|
/book/bookcode/4/4.17/CLMutex.cpp
|
UTF-8
| 1,275 | 3.046875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#include "CLMutex.h"
#include "CLLogger.h"
CLMutex::CLMutex()
{
m_pMutex = new pthread_mutex_t;
m_bNeededDestroy = true;
int r = pthread_mutex_init(m_pMutex, 0);
if(r != 0)
{
delete m_pMutex;
CLLogger::WriteLogMsg("In CLMutex::CLMutex(), pthread_mutex_init error", r);
throw "In CLMutex::CLMutex(), pthread_mutex_init error";
}
}
CLMutex::CLMutex(pthread_mutex_t *pMutex)
{
if(pMutex == 0)
throw "In CLMutex::CLMutex(), pMutex is 0";
m_pMutex = pMutex;
m_bNeededDestroy = false;
}
CLMutex::~CLMutex()
{
if(m_bNeededDestroy)
{
int r = pthread_mutex_destroy(m_pMutex);
if(r != 0)
{
delete m_pMutex;
CLLogger::WriteLogMsg("In CLMutex::~CLMutex(), pthread_mutex_destroy error", r);
}
delete m_pMutex;
}
}
CLStatus CLMutex::Lock()
{
int r = pthread_mutex_lock(m_pMutex);
if(r != 0)
{
CLLogger::WriteLogMsg("In CLMutex::Lock(), pthread_mutex_lock error", r);
return CLStatus(-1, 0);
}
else
{
return CLStatus(0, 0);
}
}
CLStatus CLMutex::Unlock()
{
int r = pthread_mutex_unlock(m_pMutex);
if(r != 0)
{
CLLogger::WriteLogMsg("In CLMutex::Unlock(), pthread_mutex_unlock error", r);
return CLStatus(-1, 0);
}
else
{
return CLStatus(0, 0);
}
}
| true |
0a6f1399f063bc493a92c994764605154258d7ac
|
C++
|
AlvaroMonteagudo/PathTracer
|
/include/scene/Material.h
|
UTF-8
| 1,693 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
#include <RGB.h>
#include <memory>
#include <Ray.h>
using namespace std;
class Material {
public:
Material(const RGB &kd = BLACK, const RGB &ks = BLACK, const RGB &kr = BLACK, const RGB &kt = BLACK, float shininess = 0.0f);
float getShininess() const;
Material operator + (const Material &m) const;
RGB Phong(const Ray &ray, const Ray &shadow, const Dir &normal, const Point &point) const;
virtual const RGB &getKd(const Point &point) const;
const RGB &getKs() const;
const RGB &getKr() const;
const RGB &getKt() const;
private:
RGB kd, ks, kr, kt;
float shininess;
};
inline Material Diffuse(const RGB &color) {
return { color, BLACK, BLACK, BLACK };
}
inline Material Specular(const RGB &color, float shininess = 0.0f, const RGB &ks = GRAY) {
return { color, ks, BLACK, BLACK, shininess };
}
inline Material Reflective(const RGB &color) {
return { BLACK, BLACK, color, BLACK };
}
inline Material Transmittive(const RGB &color) {
return { BLACK, BLACK, BLACK, color };
}
static const shared_ptr<Material> MIRROR = make_shared<Material>(Material(BLACK, BLACK, WHITE, BLACK));
static const shared_ptr<Material> TRANSP = make_shared<Material>(Material(BLACK, BLACK, BLACK, WHITE));
static const shared_ptr<Material> DIFF_R = make_shared<Material>(Material(RED, BLACK, BLACK, BLACK));
static const shared_ptr<Material> DIFF_G = make_shared<Material>(Material(GREEN, BLACK, BLACK, BLACK));
static const shared_ptr<Material> DIFF_B = make_shared<Material>(Material(BLUE, BLACK, BLACK, BLACK));
static const shared_ptr<Material> LAMBERTIAN = make_shared<Material>(Material(WHITE / 2, BLACK, BLACK , BLACK));
| true |
3b00ce12746c46aecae356beb153b395a9f78fb8
|
C++
|
JJuniJJuni/algorithm
|
/backjoon/n_m/15651/15651/n_m_3.cpp
|
UTF-8
| 380 | 2.765625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
bool check[7];
int answers[7];
void go(int idx, int n, int m) {
if (idx == m) {
for (int i = 0; i < m; i++) {
cout << answers[i] << " ";
}
cout << "\n";
return;
}
for (int i = 0; i < n; i++) {
if (!check[i]) {
answers[idx] = i + 1;
go(idx + 1, n, m);
}
}
}
int main() {
int N, M;
cin >> N >> M;
go(0, N, M);
}
| true |
9ff409160a28942cd8baa980db25a5583b2d7457
|
C++
|
Serwlashev/ElementaryTasks
|
/Task1/ChessboardFactory.cpp
|
UTF-8
| 639 | 2.640625 | 3 |
[] |
no_license
|
#include "ChessboardFactory.h"
std::unique_ptr<ISXField::Field> ISXBoardFactory::ChessboardFactory::Create(const std::string& height, const std::string& width)
{
unsigned int converted_height = 0;
unsigned int converted_width = 0;
converted_height = ISXChessParser::ChessboardParser::ParseToUI(height);
converted_width = ISXChessParser::ChessboardParser::ParseToUI(width);
if (converted_height > 0U && converted_width > 0U) {
std::unique_ptr<ISXChessboard::ChessBoard> field = std::make_unique<ISXChessboard::ChessBoard>(converted_height, converted_width);
if (field) {
return std::move(field);
}
}
return nullptr;
}
| true |
fa540b7f78af6d9d67a7a8495bbada094397dce7
|
C++
|
makarenya/opengl_learn
|
/src/shader_set.h
|
UTF-8
| 2,260 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include "model.h"
#include "shaders/scene.h"
#include "shaders/particles.h"
#include "shaders/shadow.h"
#include "shaders/depth.h"
#include <glm/glm.hpp>
class IShaderSet {
public:
virtual ~IShaderSet() = default;
virtual void Particles(glm::mat4 model, glm::mat4 single, const TMesh &mesh) = 0;
virtual void Scene(glm::mat4 model, bool opaque, float explosion, const TMaterial &mat, const TMesh &mesh) = 0;
virtual void Scene(glm::mat4 model, bool opaque, float explosion, const TModel &obj) = 0;
virtual glm::vec3 GetPosition() = 0;
};
class TSceneShaderSet: public IShaderSet {
private:
TCubeTexture Sky;
TFlatTexture Shadow;
TCubeTexture SpotShadow;
TCubeTexture SpotShadow2;
glm::mat4 LightMatrix;
TSceneShader *SceneShader;
TParticlesShader *ParticlesShader;
glm::vec3 Position;
bool UseMap;
public:
TSceneShaderSet(TSceneShader *scene, TParticlesShader *particles, TCubeTexture sky,
TFlatTexture shadow, TCubeTexture spotShadow, TCubeTexture spotShadow2,
glm::mat4 lightMatrix, glm::vec3 position, bool useMap);
void Particles(glm::mat4 model, glm::mat4 single, const TMesh &mesh) override;
void Scene(glm::mat4 model, bool opaque, float explosion, const TMaterial &mat, const TMesh &mesh) override;
void Scene(glm::mat4 model, bool opaque, float explosion, const TModel &obj) override;
glm::vec3 GetPosition() override { return Position; }
};
class TShadowShaderSet: public IShaderSet {
private:
TShadowShader *ShadowShader;
std::array<glm::mat4, 6> LightMatrices;
glm::vec3 LightPos;
glm::vec3 Position;
bool Direct;
public:
TShadowShaderSet(TShadowShader *shader, glm::mat4 lightMatrix, glm::vec3 position);
TShadowShaderSet(TShadowShader *shader, const std::array<glm::mat4, 6> &lightMatrices, glm::vec3 lightPos, glm::vec3 position);
void Particles(glm::mat4 model, glm::mat4 single, const TMesh &mesh) override;
void Scene(glm::mat4 model, bool opaque, float explosion, const TMaterial &mat, const TMesh &mesh) override;
void Scene(glm::mat4 model, bool opaque, float explosion, const TModel &obj) override;
glm::vec3 GetPosition() override { return Position; }
};
| true |
b30d4f880963e9c38efff308e22beadcdd60e354
|
C++
|
tktk2104/TktkDirectX12GameLib
|
/TktkDirectX12GameLib/TktkDX12GameLib/inc/TktkDX12Game/DXGameResource/OtherResouse/Sound/SoundManager.h
|
SHIFT_JIS
| 1,555 | 2.859375 | 3 |
[] |
no_license
|
#ifndef SOUND_H_
#define SOUND_H_
/* IXAudio2, IXAudio2MasteringVoice, HANDLE */
#include <xaudio2.h>
#undef min
#undef max
/* tktkContainer::ResourceContainer */
#include <TktkContainer/ResourceContainer/ResourceContainer.h>
namespace tktk
{
class SoundData;
// uSoundDatavǗNX
class SoundManager
{
public:
explicit SoundManager(const tktkContainer::ResourceContainerInitParam& initParam);
~SoundManager();
SoundManager(const SoundManager& other) = delete;
SoundManager& operator = (const SoundManager& other) = delete;
public:
void update();
public:
// VȃTEh[hÃ\[X̃nhԂ
// ̊œǂݍ߂TEȟ`́u.wavv̂
size_t load(const std::string& fileName);
// SẴTEh폜
void clear();
// w肵TEhĐ
void play(size_t handle, bool loopPlay);
// w肵TEh~
void stop(size_t handle);
// w肵TEhꎞ~
void pause(size_t handle);
// 匳̉ʂύXi0.0f`1.0fj
void setMasterVolume(float volume);
private:
tktkContainer::ResourceContainer<SoundData> m_assets;
// TEh̃CxgɎgpϐ
HANDLE m_soundEvent{ NULL };
// XAudiõ|C^
IXAudio2* m_xAudioPtr{ NULL };
// }X^O{CX̃|C^
IXAudio2MasteringVoice* m_masterVoicePtr{ NULL };
};
}
#endif // !SOUND_H_
| true |
7049ab90f32c295c008c5a7accccd23320173d5e
|
C++
|
sykzhong/SocketTest
|
/SocketTest/Main.cpp
|
UTF-8
| 552 | 2.703125 | 3 |
[] |
no_license
|
#include "SocketServer.h"
#include <thread>
#include <chrono>
#include <mutex>
std::chrono::milliseconds interval(10); //10ms time interval for mutex
std::mutex mtx;
void getSocketData(SocketServer socketserver)
{
socketserver.listenClient();
}
void processSocketData(SocketServer socketserver)
{
std::this_thread::sleep_for(interval);
float x, y, z;
while (1)
{
socketserver.getFloatDataFromBuffer(x, y, z);
printf("x = %.2f, y = %.2f, z = %.2f\n", x, y, z);
}
}
int main()
{
SocketServer socketserver;
socketserver.initSocket();
}
| true |
6db70fcf98d60887bb7093a65b735fb1f0ab5362
|
C++
|
verri/vlite
|
/vlite/binary_expr_vector.hpp
|
UTF-8
| 3,394 | 2.9375 | 3 |
[
"Zlib"
] |
permissive
|
#ifndef VLITE_BINARY_EXPR_VECTOR_HPP_INCLUDED
#define VLITE_BINARY_EXPR_VECTOR_HPP_INCLUDED
#include <vlite/common_vector_base.hpp>
#include <vlite/expr_vector.hpp>
#include <iterator>
namespace vlite
{
template <typename LhsIt, typename RhsIt, typename Op>
class binary_expr_vector : public expr_vector<Op>,
public common_vector_base<binary_expr_vector<LhsIt, RhsIt, Op>>
{
using lhs_result = decltype(*std::declval<LhsIt>());
using rhs_result = decltype(*std::declval<RhsIt>());
public:
using value_type = std::decay_t<std::result_of_t<Op(lhs_result, rhs_result)>>;
using typename expr_vector<Op>::size_type;
using typename expr_vector<Op>::difference_type;
class iterator
{
friend class binary_expr_vector<LhsIt, RhsIt, Op>;
public:
using iterator_category = std::input_iterator_tag;
using value_type = std::decay_t<std::result_of_t<Op(lhs_result, rhs_result)>>;
using difference_type = std::ptrdiff_t;
using reference = void;
using pointer = void;
constexpr iterator() = default;
constexpr iterator(const iterator& source) = default;
constexpr iterator(iterator&& source) noexcept = default;
constexpr iterator& operator=(const iterator& source) = default;
constexpr iterator& operator=(iterator&& source) noexcept = default;
constexpr auto operator++() -> iterator&
{
++lhs_;
++rhs_;
return *this;
}
constexpr auto operator++(int) -> iterator
{
auto copy = *this;
++(*this);
return copy;
}
constexpr auto operator==(const iterator& other) const
{
return lhs_ == other.lhs_ && rhs_ == other.rhs_;
}
constexpr auto operator!=(const iterator& other) const { return !(*this == other); }
constexpr auto operator*() const -> value_type
{
return source_->operate(*lhs_, *rhs_);
}
private:
constexpr iterator(LhsIt lhs, RhsIt rhs, const binary_expr_vector* source)
: lhs_{lhs}
, rhs_{rhs}
, source_{source}
{
}
LhsIt lhs_;
RhsIt rhs_;
const binary_expr_vector* source_;
};
using const_iterator = iterator;
public:
binary_expr_vector(LhsIt lhs_first, LhsIt lhs_last, RhsIt rhs_first, RhsIt rhs_last,
const Op& op, std::size_t size)
: expr_vector<Op>(std::move(op), size)
, lhs_first_{lhs_first}
, lhs_last_{lhs_last}
, rhs_first_{rhs_first}
, rhs_last_{rhs_last}
{
}
binary_expr_vector(const binary_expr_vector& source) = delete;
binary_expr_vector(binary_expr_vector&& source) noexcept = delete;
auto operator=(const binary_expr_vector& source) -> binary_expr_vector& = delete;
auto operator=(binary_expr_vector&& source) noexcept -> binary_expr_vector& = delete;
auto begin() const -> const_iterator { return cbegin(); }
auto end() const -> const_iterator { return cend(); }
auto cbegin() const -> const_iterator { return {lhs_first_, rhs_first_, this}; }
auto cend() const -> const_iterator { return {lhs_last_, rhs_last_, this}; }
using expr_vector<Op>::size;
private:
LhsIt lhs_first_, lhs_last_;
RhsIt rhs_first_, rhs_last_;
};
template <typename LhsIt, typename RhsIt, typename Op>
binary_expr_vector(LhsIt, LhsIt, RhsIt, RhsIt, Op, std::size_t)
->binary_expr_vector<LhsIt, RhsIt, Op>;
} // namespace vlite
#endif // VLITE_BINARY_EXPR_VECTOR_HPP_INCLUDED
| true |
966f7cc8ece8d7d0065b4decfd67504bf185db15
|
C++
|
ggu/routemaking_macOS_GUI
|
/RoutemakingGUI/wrapper.cpp
|
UTF-8
| 2,353 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
//
// wrapper.cpp
// RoutemakingGUI
//
// Created by Gabriel Uribe on 7/27/16.
// Copyright © 2016 Gabriel Uribe. All rights reserved.
//
#include <stdio.h>
#include <PathfinderController.h>
#include <pathfinding/LocalPathfinder.h>
#include <pathfinding/Astar.h>
Boat SimpleAISBoat(double lat, double lon, int trueHeading, float sog_knots,
std::chrono::steady_clock::time_point timeReceived){
Boat simpleBoat = Boat();
simpleBoat.m_latitude = lat;
simpleBoat.m_longitude = lon;
simpleBoat.m_trueHeading = trueHeading;
simpleBoat.m_sog = sog_knots;
simpleBoat.m_timeReceived = timeReceived;
simpleBoat.m_positionValid = true;
simpleBoat.m_trueHeadingValid = true;
simpleBoat.m_sogValid = true;
return simpleBoat;
}
struct DynamicTile {
Type type;
int obstacle_risk;
};
struct ATile {
Type type;
int x;
int y;
DynamicTile* tiles;
};
typedef ATile Matrix[62][29];
extern "C" ATile** GetPath(int startX, int startY, int targetX, int targetY, int* boats, int numBoats) {
LocalPathfinder pathfinder = LocalPathfinder(49.2984988, -123.276173, 10, 49.45584988, -122.750173);
std::list<Boat> theBoats;
for (int i = 0; i < numBoats * 4; i += 4) {
std::shared_ptr<Tile> boatTile = pathfinder.matrix_[boats[i]][boats[i + 1]];
Boat boat = SimpleAISBoat(boatTile->lat_, boatTile->lng_, boats[i + 2], boats[i + 3], std::chrono::steady_clock::now());
theBoats.push_back(boat);
}
pathfinder.SetStart(startX, startY, 0);
pathfinder.SetTarget(targetX, targetY);
pathfinder.SetBoats(theBoats, theBoats);
pathfinder.Run();
pathfinder.VisualizePath();
ATile** arr = new ATile*[62];
for(int i = 0; i < 62; ++i) {
arr[i] = new ATile[29];
for (int j = 0; j < 29; j++) {
arr[i][j].tiles = new DynamicTile[100];
}
}
for (int y = 0; y < 29; y++) { // pathfinder.y_len
for (int x = 0; x < 62; x++) { // pathfinder.x_len
std::shared_ptr<Tile> pTile = pathfinder.matrix_[x][y];
DynamicTile *dTiles = new DynamicTile[100];
for (int i = 0; i < 100; i++) {
dTiles[i].obstacle_risk = pTile->t_[i].obstacle_risk_;
dTiles[i].type = pTile->t_[i].type_;
}
// for dynamic tile
ATile tile = {pTile->type_, pTile->x_, pTile->y_, dTiles};
arr[x][y] = tile;
}
}
return arr;
}
| true |
3b423f217f539e225e671d43583b53d5b7cb0d6e
|
C++
|
merkys/jsonapi-client-cpp
|
/src/Resource.h
|
UTF-8
| 691 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#include<string>
#include<iostream>
#include<cstring>
#pragma once
#include"ResourceIdentifier.h"
#include <jsoncpp/json/json.h> //adding json header for second constructor
class Resource: public ResourceIdentifier{
private:
std::string attribute_name_;
std::string value_;
Json::Value JSON;
public:
Resource(const std::string attribute_name="",const std::string value="");
Resource(Json::Value value); //adding second constructor with all items from data payload
std::string get_attribute(const std::string attribute_name);
std::string set_attribute(const std::string atribute_name, const std::string value);
std::string get_data(Json::Value value);
~Resource();
};
| true |
581d0efc7cc3d5e93d695cafb131735566c580e9
|
C++
|
JuliaHarkins/Maze
|
/MazeProject/MazeCreater.cpp
|
UTF-8
| 7,509 | 3.1875 | 3 |
[] |
no_license
|
#include "MazeCreator.h"
#include "MazeObj.h"
#include "DoorObj.h"
#include <fstream>
#include <vector>
#include <random>
#include<map>
/**
loads defalt static maze
*/
MazeObj* MazeCreator::staticMaze() {
//creating the maze
MazeObj* maze = new MazeObj;
//creating Rooms
RoomObj* a = new RoomObj("A");
RoomObj* b = new RoomObj("B");
RoomObj* c = new RoomObj("C");
RoomObj* d = new RoomObj("D");
RoomObj* e = new RoomObj("E");
RoomObj* f = new RoomObj("F");
RoomObj* g = new RoomObj("G");
RoomObj* h = new RoomObj("H");
RoomObj* i = new RoomObj("I");
RoomObj* j = new RoomObj("J");
RoomObj* k = new RoomObj("K");
RoomObj* l = new RoomObj("L");
RoomObj* m = new RoomObj("M");
RoomObj* n = new RoomObj("N");
//Linking room's Doors
DoorObj* ac = new DoorObj(a, "East");
DoorObj* af = new DoorObj(a, "West");
DoorObj* bc = new DoorObj(b, "South");
DoorObj* cd = new DoorObj(c, "East");
SecretDoorObj* cg = new SecretDoorObj(c, "Floor");
DoorObj* ch = new DoorObj(c, "South");
DoorObj* de = new DoorObj(d, "East");
DoorObj* fj = new DoorObj(f, "North");
DoorObj* fk = new DoorObj(f, "West");
DoorObj* hi = new DoorObj(h, "East");
DoorObj* hl = new DoorObj(h, "West");
DoorObj* hm = new DoorObj(h, "South");
DoorObj* kl = new DoorObj(k, "South");
DoorObj* mn = new DoorObj(m, "South");
//setting the second room of the doors
ac->setRoomTwo(c);
af->setRoomTwo(f);
bc->setRoomTwo(c);
cd->setRoomTwo(d);
cg->setRoomTwo(g);
ch->setRoomTwo(h);
de->setRoomTwo(e);
fj->setRoomTwo(j);
fk->setRoomTwo(k);
hi->setRoomTwo(i);
hl->setRoomTwo(l);
hm->setRoomTwo(m);
kl->setRoomTwo(l);
mn->setRoomTwo(n);
//adding the doors to rooms
a->addDoor(ac);
c->addDoor(ac);
a->addDoor(af);
f->addDoor(af);
c->addDoor(bc);
b->addDoor(bc);
c->addDoor(cd);
d->addDoor(cd);
c->addDoor(cg);
g->addDoor(cg);
c->addDoor(ch);
h->addDoor(ch);
d->addDoor(de);
e->addDoor(de);
f->addDoor(fj);
j->addDoor(fj);
f->addDoor(fk);
k->addDoor(fk);
h->addDoor(hi);
i->addDoor(hi);
h->addDoor(hl);
l->addDoor(hl);
h->addDoor(hm);
m->addDoor(hm);
k->addDoor(kl);
l->addDoor(kl);
m->addDoor(mn);
n->addDoor(mn);
//adding all the rooms to the maze
maze->addRoom(a);
maze->addRoom(b);
maze->addRoom(c);
maze->addRoom(d);
maze->addRoom(e);
maze->addRoom(f);
maze->addRoom(g);
maze->addRoom(h);
maze->addRoom(i);
maze->addRoom(j);
maze->addRoom(k);
maze->addRoom(l);
maze->addRoom(m);
maze->addRoom(n);
return maze;
}
/**
loads a random maze
*/
MazeObj* MazeCreator::randomMaze() {
vector<string> direction{ "North", "South", "East", "West", "Floor" }; //creating a vector for the directions
vector<RoomObj*> rooms; //creating a vector for the rooms prior to adding them to the maze
MazeObj* maze = new MazeObj;
random_device rd; // seed
mt19937 rng(rd()); // random-number engine
uniform_int_distribution<int> randomRoom(10, 26); // the range of potential rooms
uniform_int_distribution<int> randomDir(1, 5); //a random number to be taken from the direction vector
uniform_int_distribution<int> maxDoor(1, 2); // the amount of default doors for a room
int roomLimit = randomRoom(rng); //creating the room limit
int doorDir = randomDir(rng); // creating the direction per door
rooms.resize(roomLimit); // setting the rooms array to the same as the room limit
// creating and adding all the rooms
for (int r = 0; r < roomLimit; r++) {
rooms[r] = new RoomObj(to_string(r));
}
int roomTwo; // the number of a room within the array to apply a second to the door.
bool same; //booling to ensure information is valid
bool inUse = false; //used to check if the rooms direction is in use
string dir; // the direction the door is facing
DoorObj* door = nullptr;
int i =0; //loop index/ current room number
uniform_int_distribution<int> getRandomIndex(i, roomLimit - 1); // gets an index greater then the current room
for (i = 0; i < roomLimit; i++) {
int doorCount = maxDoor(rng);
for (int d = 0; d < doorCount; d++) {
same = true;
//checks if theres a door in that direction already and creates it if it does not
if (door == nullptr || ((door->getDirection(rooms[i]) != direction[0]) || (door->getDirection(rooms[i]) != direction[1]) || (door->getDirection(rooms[i]) != direction[2]) || (door->getDirection(rooms[i]) != direction[3]) || (door->getDirection(rooms[i]) != direction[4]))) {
while (same) {
dir = direction[randomDir(rng)-1];
inUse = checkIfExists(dir, rooms[i]);
if (!inUse) {
door = new DoorObj(rooms[i], dir);
rooms[i]->addDoor(door);
same = false;
}
}
}
same = true;
//assines a randomly choosen second room that isn't itself and isn't already taken.
while (same) {
roomTwo = getRandomIndex(rng);
inUse = checkIfExists(secondDir(dir), rooms[roomTwo]);
if (roomTwo != i && !inUse) {
rooms[roomTwo]->addDoor(door);
door->setRoomTwo(rooms[roomTwo]);
same = false;
}
}
}
}
// adding the rooms to the maze
for each(RoomObj* r in rooms) {
maze->addRoom(r);
}
return maze;
}
/**
loads a maze from a file
*/
MazeObj* MazeCreator::loadMaze() {
MazeObj* maze = new MazeObj;
ifstream mazeFile; //the maze file
string name1; //name of the first room
string dir; //direction of door
string name2; //name of the second room
RoomObj* room = nullptr;
DoorObj* door = nullptr;
map <string, RoomObj*> roomList;
mazeFile.open("maze.txt");
//creating an error if the file does not exist
if (mazeFile.fail()) {
cerr << "file could not load, file does not exist"<<endl;
system("PAUSE");
exit(1);
}
//checks if the files open
if (mazeFile.is_open()) {
//read until the end of the file
while (!mazeFile.eof()) {
//takes information from the file
mazeFile >> name1 >> dir >> name2;
//adding rooms to the map
if (roomList.count(name1) == 0) {
room = new RoomObj(name1);
roomList[name1] = room;
}
// attaching the door to the first room
room = roomList[name1];
door = new DoorObj(room, dir);
room->addDoor(door);
//adding the second room to the map
if (roomList.count(name2) == 0) {
room = new RoomObj(name2);
roomList[name2] = room;
}
//attachign the door to the second room
room = roomList[name2];
door->setRoomTwo(roomList[name2]);
room->addDoor(door);
}
//closes the file
mazeFile.close();
//gets rooms from the map and adds them to the maze
for (auto x: roomList) {
maze->addRoom(x.second);
}
}
return maze;
}
/**
checks a door is already facing that direction
*/
bool MazeCreator::checkIfExists(string dir, RoomObj* room) {
bool inUse = false;
string floor = "Floor";
string ladder = "Ladder";
string roomDir;
//checks each door in the room to find out if the direction is taken
for each(DoorObj* d in room->getDoors()) {
roomDir = d->getDirection(room);
if (dir == floor || dir == ladder) {
if (roomDir == floor) {
return true;
}
else if (roomDir == ladder){
return true;
}
}
else if ( roomDir== dir) {
return true;
}
}
return false;
}
/**
sets the seccons direction of the door
*/
string MazeCreator::secondDir(string dir) {
if (dir == "North") {
return "South";
}
else if (dir == "South") {
return "North";
}
else if (dir == "East") {
return "West";
}
else if (dir == "West") {
return "East";
}
else if (dir == "Floor") {
return "Ladder";
}
else {
return "Floor";
}
}
| true |
3a6fb5970bf197b8490cc94d31d6f7df15e1ac98
|
C++
|
pjdurden/Competitive-programming-templates
|
/trees.cc
|
UTF-8
| 2,842 | 3.921875 | 4 |
[] |
no_license
|
//tree class
struct Node {
int key;
Node *left, *right;
Node (int x)
{
key = x;
left = right = NULL;
}
};
//insert function
void insert(Node* temp, int key)
{
queue<Node*> q;
q.push(temp);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (!temp->left) {
temp->left = new Node(key);
break;
} else
q.push(temp->left);
if (!temp->right) {
temp->right = new Node(key);
break;
} else
q.push(temp->right);
}
}
//delete node
struct node * minValueNode(struct node* node)
{
struct node* current = node;
while (current && current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int key)
{
if (root == NULL) return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
//traversal
void printPostorder(struct Node* node)
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right); ode
cout << node->data << " ";
}
void printPreorder(struct Node* node)
{
if (node == NULL)
return;
cout << node->data << " ";
printPreorder(node->left);
printPreorder(node->right);
}
void printInorder(struct Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
//find height
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else
{
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
//leafcount
unsigned int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->left == NULL && node->right == NULL)
return 1;
else
return getLeafCount(node->left)+
getLeafCount(node->right);
}
//
| true |
16ae5a2c64a08288c85d6ae5a78617f6f5c52ac5
|
C++
|
eyedeng/Algorithm
|
/all/list.cpp
|
ISO-8859-7
| 432 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
#include <list>
using namespace std;
int main()
{
int len;
int ele;
list<int> lis;
cin>> len;
while(len--)
{
cin>>ele;
lis.push_back(ele);
}
int delele;
cin>> delele;
lis.remove(delele);
cout<<lis.size()<<": ";
for(list<int>::iterator it = lis.begin(); it!=lis.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
return 0;
}
| true |
df48148afd31d9ce73d3f9b3b96aa21f0a61d374
|
C++
|
ebirenbaum/yurtcraft
|
/project/src/noise.h
|
UTF-8
| 663 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef NOISE_H
#define NOISE_H
#include "vector.h"
class Noise {
public:
Noise(int seed);
virtual ~Noise();
float perlin2(const Vector2 &pos, float period);
float perlin3(const Vector3 &pos, float period);
private:
int fastFloor(float n);
float linterpolate(float a, float b, float x);
float costerpolate(float a, float b, float x);
float noise2(int x, int y);
float smoothNoise2(float x, float y);
float interNoise2(float x, float y);
float noise3(int x, int y, int z);
float smoothNoise3(float x, float y, float z);
float interNoise3(float x, float y, float z);
int m_seed;
};
#endif // NOISE_H
| true |
06eed9671e97b86c11a2a506f5eadad98ad4250f
|
C++
|
mjunior-fitec/52821-lora
|
/lib/lib_enddevice/otica_ftdi.cpp
|
UTF-8
| 3,444 | 2.59375 | 3 |
[] |
no_license
|
#include <cdcftdi.h>
#include <usbhub.h>
#include "abnt.h"
#include "otica_ftdi.h"
//#include "pgmstrings.h"
/*-----------------------------------------*/
/* Variáveis globais do módulo */
/*-----------------------------------------*/
USBHost UsbH;
FTDIAsync FtdiAsync;
FTDI Ftdi(&UsbH, &FtdiAsync);
uint8_t FTDIAsync::OnInit(FTDI *pftdi)
{
uint8_t rcode = 0;
rcode = pftdi->SetBaudRate(ABNT_BAUD);
if (rcode)
{
ErrorMessage<uint8_t>(PSTR("SetBaudRate"), rcode);
return rcode;
}
rcode = pftdi->SetFlowControl(FTDI_SIO_DISABLE_FLOW_CTRL);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SetFlowControl"), rcode);
return rcode;
}
/**
* @brief Envia um buffer para o dispositivo USB FTDI
*
* Esta função envia um buffer de bytes para o dispositivo
* FTDI, considerando que este já foi devidamente inciado
* e está pronto para receber. Esta função pode receber qualquer
* quantidade de bytes e trata a limitação do driver de enviar
* apenas 64 bytes de cada vez.
*
* @param [in] *pftdi Ponteiro para o objeto FTDI já inciado
* @param [in] datasize Quantidade de bytes a ser enviada
* @param [in] *databuf Ponteiro para o início do buffer de dados
* @return Código de erro, 0 para sucesso
*
*/
uint8_t send_dataFTDI(uint32_t datasize, volatile uint8_t *databuf)
{
uint32_t bytes_left = datasize;
uint8_t bytes_tosend, rcode = 0;
volatile uint8_t *curr_buf = databuf;
if (datasize)
{
while (bytes_left)
{
bytes_tosend = (bytes_left >= MAX_SEND) ? MAX_SEND : bytes_left;
rcode = Ftdi.SndData(bytes_tosend, (uint8_t *)curr_buf);
if (rcode)
break;
bytes_left -= bytes_tosend;
curr_buf += bytes_tosend;
}
//NOTE: É necessário fazer este envio com zero bytes para garantir
// que o envio finalizará corretamente. O cabo USB / porta
// ótica ABNT Landis gyr, não funciona sem isso.
Ftdi.SndData(bytes_left, (uint8_t *)curr_buf);
}
return (rcode);
} //send_dataFTDI(
/**
* @brief Recebe um buffer de dados do dispositivo FTDI
*
* Esta função recebe um buffer de dados do dispositivo
* FTDI, considerando que este já foi devidamente inciado
* e está pronto para enviar. Esta função utiliza a função
* do driver FTDI de baixo nível que bufferiza até 64 bytes,
* não sendo garantido o instante de recebimento efetivo de
* cada byte.
*
* @param [in] *pftdi Ponteiro para o objeto FTDI já iniciado
* @param [out] *nBytes Quantidade de bytes recebidos
* @param [out] *buff Ponteiro para o início do buffer de dados
* a ser preenchido
* @return Código de erro, 0 para sucesso
*
*/
uint8_t recv_dataFTDI(uint16_t *nBytes, uint8_t *buffPayload)
{
uint8_t rcode = 0;
uint8_t buff [MAX_RECV];
rcode = Ftdi.RcvData(nBytes, buff);
if (rcode && rcode != USB_ERRORFLOW)
{
ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
return rcode;
}
// NOTE: O driver FTDI retorna informações de
// status (modem e line status registers) nos 2 primeiros
// bytes, portanto eles não contém dados do payload.
if (*nBytes > 2)
{
(*nBytes) -= 2;
//Copia o pyaload para a saída
memcpy(buffPayload, buff+2, *nBytes);
return 0;
}
*nBytes = 0;
return 0;
} //recv_dataFTDI(
| true |
cbff6b23d275f91b7b4e5b5cb124db9c8f99eb6f
|
C++
|
ghiffaryr/Praktikum_PTI_CPlusPlus
|
/TP4/Penjumlahan 2 buah array/PB03-19817097-171109-07.cpp
|
UTF-8
| 698 | 3.3125 | 3 |
[] |
no_license
|
// NIM/Nama : 19817097/Ghiffary Rifqialdi
// Nama File : 19817097-171109-07
// Tanggal : 09/11/2017
// Deskripsi : Program untuk menjumlahkan 2 buah array
#include<iostream>
using namespace std;
int main(){
//Kamus
int N,i;
int A[100];
int B[100];
int C[100];
//Algoritma
cout<<"Masukkan nilai N : "; cin>>N;
for(i=0;i<N;i++){
cout<<"Masukkan A["<<i<<"] : "; cin>>A[i];
}
cout<<endl;
for(i=0;i<N;i++){
cout<<"Masukkan B["<<i<<"] : "; cin>>B[i];
}
for(i=0;i<N;i++){
C[i]=A[i]+B[i];
}
cout<<endl;
cout<<"Isi dari C adalah"<<endl;
for(i=0;i<N;i++){
cout<<C[i]<<" ";
}
return 0;
}
| true |
9b99c8f51651eb8bf669dc6261251255ea0e4b4d
|
C++
|
ACupofAir/C
|
/Algorithm/bomb_search.cpp
|
UTF-8
| 1,731 | 3.515625 | 4 |
[] |
no_license
|
#include <iostream>
#include <stdio.h>
//It is fun
using namespace std;
int main(void) {
int row, col;
cout<<"Set the map's row number: \n";
cin>>row;
cout<<"Set the map's col number: \n";
cin>>col;
char **map = new char *[row];
for(int i = 0; i < row; i++) {
map[i] = new char[col];
}
cout<<"Set your map's object: \n";
for (int i = 0; i < row; i++) {
cout<<"Set "<<i+1<<" row"<<endl;
cin>>map[i];
}
cout<<"Your map's object is: \n";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout<<map[i][j];
}
cout<<endl;
}
int sum,sumMax;
sumMax = 0;
int x,y;
int xMax, yMax;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (map[i][j]=='.') {
//printf("%d,%d ",i,j);
sum = 0;
x = i; y = j;
while(map[x][y] != '#') {
//up:
if(map[x][y] == 'G') {
sum++;
}
x--;
}
x = i; y = j;
while(map[x][y] != '#') {
//down:
if(map[x][y] == 'G') {
sum++;
}
x++;
}
x = i; y = j;
while(map[x][y] != '#') {
//ringht:
if(map[x][y] == 'G') {
sum++;
}
y++;
}
x = i; y = j;
while(map[x][y] != '#') {
//left:
if(map[x][y] == 'G') {
sum++;
}
y--;
}
}
if (sum > sumMax) {
printf("%d,%d ",i,j);
sumMax = sum;
xMax = i;
yMax = j;
}
}
}
printf("Put the bomb at (%d, %d), and the max number of enemy which is destoryed is %d\n", xMax, yMax, sumMax);
return 0;
}
| true |
29b5ca712ec3f84b70bf67a3750d95865803b6cc
|
C++
|
cuberite/cuberite
|
/src/Items/ItemBanner.h
|
UTF-8
| 3,673 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#pragma once
#include "ItemHandler.h"
#include "../World.h"
#include "../Blocks/BlockHandler.h"
#include "../BlockEntities/BannerEntity.h"
#include "../Blocks/ChunkInterface.h"
class cItemBannerHandler final:
public cItemHandler
{
using Super = cItemHandler;
public:
using Super::Super;
private:
virtual bool CommitPlacement(cPlayer & a_Player, const cItem & a_HeldItem, const Vector3i a_PlacePosition, const eBlockFace a_ClickedBlockFace, const Vector3i a_CursorPosition) const override
{
// Cannot place a banner at "no face" and from the bottom:
if ((a_ClickedBlockFace == BLOCK_FACE_NONE) || (a_ClickedBlockFace == BLOCK_FACE_BOTTOM))
{
return false;
}
if (!TryPlaceBanner(a_Player, a_PlacePosition, a_ClickedBlockFace))
{
return false;
}
a_Player.GetWorld()->DoWithBlockEntityAt(a_PlacePosition, [&a_HeldItem](cBlockEntity & a_BlockEntity)
{
ASSERT((a_BlockEntity.GetBlockType() == E_BLOCK_STANDING_BANNER) || (a_BlockEntity.GetBlockType() == E_BLOCK_WALL_BANNER));
static_cast<cBannerEntity &>(a_BlockEntity).SetBaseColor(static_cast<NIBBLETYPE>(a_HeldItem.m_ItemDamage));
return false;
});
return true;
}
virtual bool IsPlaceable(void) const override
{
return true;
}
static bool TryPlaceBanner(cPlayer & a_Player, const Vector3i a_PlacePosition, const eBlockFace a_ClickedBlockFace)
{
const auto Rotation = a_Player.GetYaw();
// Placing on the floor:
if (a_ClickedBlockFace == BLOCK_FACE_TOP)
{
NIBBLETYPE Meta;
if ((Rotation >= -11.25f) && (Rotation < 11.25f))
{
// South
Meta = 0x08;
}
else if ((Rotation >= 11.25f) && (Rotation < 33.75f))
{
// SouthSouthWest
Meta = 0x09;
}
else if ((Rotation >= 23.75f) && (Rotation < 56.25f))
{
// SouthWest
Meta = 0x0a;
}
else if ((Rotation >= 56.25f) && (Rotation < 78.75f))
{
// WestSouthWest
Meta = 0x0b;
}
else if ((Rotation >= 78.75f) && (Rotation < 101.25f))
{
// West
Meta = 0x0c;
}
else if ((Rotation >= 101.25f) && (Rotation < 123.75f))
{
// WestNorthWest
Meta = 0x0d;
}
else if ((Rotation >= 123.75f) && (Rotation < 146.25f))
{
// NorthWest
Meta = 0x0e;
}
else if ((Rotation >= 146.25f) && (Rotation < 168.75f))
{
// NorthNorthWest
Meta = 0x0f;
}
else if ((Rotation >= -168.75f) && (Rotation < -146.25f))
{
// NorthNorthEast
Meta = 0x01;
}
else if ((Rotation >= -146.25f) && (Rotation < -123.75f))
{
// NorthEast
Meta = 0x02;
}
else if ((Rotation >= -123.75f) && (Rotation < -101.25f))
{
// EastNorthEast
Meta = 0x03;
}
else if ((Rotation >= -101.25) && (Rotation < -78.75f))
{
// East
Meta = 0x04;
}
else if ((Rotation >= -78.75) && (Rotation < -56.25f))
{
// EastSouthEast
Meta = 0x05;
}
else if ((Rotation >= -56.25f) && (Rotation < -33.75f))
{
// SouthEast
Meta = 0x06;
}
else if ((Rotation >= -33.75f) && (Rotation < -11.25f))
{
// SouthSouthEast
Meta = 0x07;
}
else // degrees jumping from 180 to -180
{
// North
Meta = 0x00;
}
return a_Player.PlaceBlock(a_PlacePosition, E_BLOCK_STANDING_BANNER, Meta);
}
// We must be placing on the side of a block.
NIBBLETYPE Meta;
if (a_ClickedBlockFace == BLOCK_FACE_EAST)
{
Meta = 0x05;
}
else if (a_ClickedBlockFace == BLOCK_FACE_WEST)
{
Meta = 0x04;
}
else if (a_ClickedBlockFace == BLOCK_FACE_NORTH)
{
Meta = 0x02;
}
else // degrees jumping from 180 to -180
{
Meta = 0x03;
}
return a_Player.PlaceBlock(a_PlacePosition, E_BLOCK_WALL_BANNER, Meta);
}
};
| true |
ae538f4e9eb3680c4f7146e69ace73574841d181
|
C++
|
OnurArdaB/Bayes-Classifier
|
/sample/main.cpp
|
UTF-8
| 3,943 | 2.671875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#include "naive-bayes/model.hpp"
using namespace std;
vector<string> split(const string& str, const string& delim){
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
int main(){
string filename;
string encode_wanted;
/*
cout << "Enter train data as a .CSV file: ";
cin >> filename;
*/
filename="dataset/train_data.csv";
//filename="train_images.csv";
ifstream file_train_features;
file_train_features.open(filename);
vector<vector<double> > dataframe;
if(file_train_features.fail()){
cout << "Program can't find your file that you have entered please enter a valid path that exists" << endl;
}
else{
cout << "File is opened successfully!" << endl;
while(!file_train_features.eof()){
string line;
getline(file_train_features,line);
vector<string> s = split(line,",");
vector<double> s_;
for(int i=0;i<s.size();i++){
s_.push_back(stod(s[i]));
}
dataframe.push_back(s_);
}
file_train_features.close();
}
/*
cout << "Enter train labels as a .CSV file: ";
cin >> filename;
*/
filename="dataset/train_label.csv";
//filename="train_labels.csv";
ifstream file_train_labels;
file_train_labels.open(filename);
vector<double> labels;
set<double> labels_;
if(file_train_labels.fail()){
cout << "Program can't find your file that you have entered please enter a valid path that exists" << endl;
}
else{
cout << "File is opened successfully!" << endl;
//Training
while(!file_train_labels.eof()){
string line;
getline(file_train_labels,line);
labels.push_back(stod(line));
if(labels_.count(stod(line))==0)
labels_.insert(stod(line));
}
file_train_labels.close();
}
BayesClassifier model;
model.train(dataframe,labels);
/*
cout << "Enter test data as a .CSV file: ";
cin >> filename;
*/
filename="dataset/test_data.csv";
//filename="test_images.csv";
ifstream file_test_features;
file_test_features.open(filename);
vector<vector<double> > test_dataframe;
if(file_test_features.fail()){
cout << "Program can't find your file that you have entered please enter a valid path that exists" << endl;
}
else{
cout << "File is opened successfully!" << endl;
while(!file_test_features.eof()){
string line;
getline(file_test_features,line);
vector<string> s = split(line,",");
vector<double> s_;
for(int i=0;i<s.size();i++){
s_.push_back(stold(s[i]));
}
test_dataframe.push_back(s_);
}
file_test_features.close();
}
/*
cout << "Enter test labels as a .CSV file: ";
cin >> filename;
*/
filename="dataset/test_label.csv";
//filename="test_labels.csv";
ifstream file_test_labels;
file_test_labels.open(filename);
vector<double> test_labels;
if(file_test_labels.fail()){
cout << "Program can't find your file that you have entered please enter a valid path that exists" << endl;
}
else{
cout << "File is opened successfully!" << endl;
while(!file_test_labels.eof()){
string line;
getline(file_test_labels,line);
test_labels.push_back(stod(line));
}
file_test_labels.close();
}
cout << "Testing" <<endl;
int match=0;
int counter = 0;
for(auto test_line:test_dataframe){
auto pred = model.predict(test_line);
double class_followed = 0;
double prob_log_followed = 0;
for(auto&[class_,prob_log]:pred){
if(prob_log_followed==0){
class_followed = class_;
prob_log_followed=prob_log;
}
else if(prob_log_followed>prob_log){
class_followed = class_;
prob_log_followed=prob_log;
}
}
if(class_followed==test_labels[counter])
match++;
counter++;
}
cout << match << endl;
}
| true |
9c3e509ecefb5379369144951afc8d810056def1
|
C++
|
T-Bone-Willson/SET09121-GamesEngineering-Labs
|
/practical_4/cmp_player_movement.cpp
|
UTF-8
| 900 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
#include "cmp_player_movement.h"
#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
PlayerMovementComponent::PlayerMovementComponent(Entity* p) : ActorMovementComponent(p) {
}
void PlayerMovementComponent::update(float dt) {
// COPY AND PASTED FROM "player.cpp"
// Movement
sf::Vector2f displacement = { 0.0f, 0.0f };
if (Keyboard::isKeyPressed(Keyboard::Left)) {
displacement.x --;
}
if (Keyboard::isKeyPressed(Keyboard::Right)) {
displacement.x++;
}
if (Keyboard::isKeyPressed(Keyboard::Up)) {
displacement.y--;
}
if (Keyboard::isKeyPressed(Keyboard::Down)) {
displacement.y++;
}
// Normalised displacement
float l = sqrt(displacement.x * displacement.x + displacement.y * displacement.y);
if (l != 0) {
displacement.x = displacement.x / 1;
displacement.y = displacement.y / 1;
}
move((float)dt * displacement * _speed); // direction for player.
}
| true |
f341d395f2f420278d13a72c43904c1e8ce46cdb
|
C++
|
BrStall/uri-solutions-c-
|
/1080 - Maior e posição.cpp
|
UTF-8
| 294 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int X, pos = 0, maior = 0;
for (int i = 0; i < 100; i++)
{
cin >> X;
if (X > maior)
{
maior = X;
pos = i;
}
}
cout << maior << endl;
cout << pos+1<< endl;
}
| true |
c9e19a91f999cfd98ef47bb0db9ee30f66fc8463
|
C++
|
WuZixing/Geo3DML-CPP
|
/include/geo3dml/CuboidVolume.h
|
UTF-8
| 1,692 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
// UTF-8编码
#pragma once
#include "Volume.h"
namespace geo3dml {
/// @brief 大小不一的六面体(如长方体)单元构成的体。
class CuboidVolume : public Volume {
public:
CuboidVolume();
virtual ~CuboidVolume();
/// @name 读写顶点的方法。
///@{
/// @brief 添加一个顶点。
/// @param x 顶点的坐标:x。
/// @param y 顶点的坐标:y。
/// @param z 顶点的坐标:z。
/// @return 返回新添加的顶点的索引号。
virtual int AppendVertex(double x, double y, double z) = 0;
virtual int GetVertexCount() const = 0;
virtual bool GetVertexAt(int i, double& x, double& y, double& z) const = 0;
///@}
/// @name 读写六面体体单元的方法。
///@{
/// @brief 指定构成体元的8个顶点,添加一个六面体体元。
/// @param v1,v2,v3,v4 构成底面的4个顶点的索引号。顶点的顺序应保持该面在右手坐标系下的法向朝向与该面对应的另一底面,即由顶点v5、v6、v7和v8构成的底面。
/// @param v5,v6,v7,v8 构成与前面底面对应的另一底面的4个顶点的索引号。顶点的顺序使得v1、v2、v5和v6构成六面体的一个侧面;其余顶点依此类推。
/// @return 返回新添加的体元的索引号。
virtual int AppendCuboid(int v1, int v2, int v3, int v4, int v5, int v6, int v7, int v8) = 0;
virtual int GetCuboidCount() const = 0;
virtual bool GetCuboidAt(int i, int& v1, int& v2, int& v3, int& v4, int& v5, int& v6, int& v7, int& v8) const = 0;
///@}
};
}
| true |
7d0fce7abd32682e9ad32fa904fed21a69e09d7c
|
C++
|
linton-dawson/collections-cpp
|
/queue/queue.cpp
|
UTF-8
| 530 | 3.421875 | 3 |
[] |
no_license
|
#include "queue.h"
#include <iostream>
using namespace std;
Queue::Queue(const int sz)
{
size = sz;
vec.reserve(sz);
head = -1;
tail = -1;
}
void Queue::enqueue(const int num)
{
vec.push_back(num);
if(head == -1 && tail == -1) {
head++;
tail++;
}
else {
tail++;
}
}
void Queue::dequeue()
{
vec.erase(vec.begin());
// ++head;
}
int Queue::gethead()
{
return vec[head];
}
int Queue::gettail()
{
return vec[tail];
}
void Queue:: print()
{
for(auto i:vec)
cout<<i<<" ";
cout<<endl;
}
| true |
e116f9ebb971dbac9c5e23946c6d3c08c665aa9c
|
C++
|
vamsi12340/entify
|
/src/registry.cc
|
UTF-8
| 1,401 | 2.515625 | 3 |
[] |
no_license
|
#include "entify/registry.h"
#include "context.h"
#include "renderer/backend.h"
EntifyContext EntifyCreateContext() {
return new entify::Context(entify::renderer::MakeDefaultRenderer());
}
void EntifyDestroyContext(EntifyContext context) {
delete static_cast<entify::Context*>(context);
}
EntifyReference EntifyTryGetReferenceFromId(
EntifyContext context, EntifyId id) {
return static_cast<entify::Context*>(context)->TryGetReferenceFromId(id);
}
EntifyReference EntifyCreateReferenceFromProtocolBuffer(
EntifyContext context, EntifyId id, const char* data, size_t data_size) {
return static_cast<entify::Context*>(context)
->CreateReferenceFromProtocolBuffer(id, data, data_size);
}
EntifyReference EntifyCreateReferenceFromFlatBuffer(
EntifyContext context, EntifyId id, const char* data, size_t data_size) {
return static_cast<entify::Context*>(context)
->CreateReferenceFromFlatBuffer(id, data, data_size);
}
int EntifyGetLastError(EntifyContext context, const char** message) {
return static_cast<entify::Context*>(context)->GetLastError(message);
}
void EntifyAddReference(EntifyContext context, EntifyReference reference) {
static_cast<entify::Context*>(context)->AddReference(reference);
}
void EntifyReleaseReference(EntifyContext context, EntifyReference reference) {
static_cast<entify::Context*>(context)->ReleaseReference(reference);
}
| true |
548c39ef338b8068c2ad4766d87af0a86d66fc91
|
C++
|
Deepakku28/Leetcode
|
/560. Subarray Sum Equals K.cpp
|
UTF-8
| 377 | 2.609375 | 3 |
[] |
no_license
|
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n=nums.size();
for(int i=1;i<n;i++){
nums[i]+=nums[i-1];
}
int count=0;
unordered_map<int,int> mp;
mp[0]++;
for(int i=0;i<n;i++){
count+=mp[nums[i]-k];
mp[nums[i]]++;
}
return count;
}
};
| true |
d33cb8ef783345e93a95a9551d4d73ee7de2a576
|
C++
|
chjesus/Estructura-de-Datos
|
/Parcial II/Parcial 2 - 2018-3/Problema 2/Principal.h
|
ISO-8859-10
| 8,490 | 2.90625 | 3 |
[] |
no_license
|
#ifndef PRINCIPAL_H
#define PRINCIPAL_H
#include <fstream>
#include <stdlib.h>
#include <conio.h>
#include "Genero.h"
#include "Canciones.h"
using namespace std;
class Principal{
fstream genero,canciones;
ListDinSimple<Genero> listaGen;
string cadena;
char *auxCadena;
public:
void Main();
void separarGenero();
void separarDatos();
void imprimirListado();
void imprimirListadoPorGenero();
void agregarCancion();
void consultarInformacionCancion();
void eliminarCancion();
void mostrarMensajeError();
};
void Principal::Main(){
bool band = true;
char tecla;
Principal::separarGenero();
Principal::separarDatos();
do{
cout<<"1) Imprimir Catalogo General por Genero."<<endl;
cout<<"2) Imprimir Listado de canciones por Genero."<<endl;
cout<<"3) Agregar una Cancion"<<endl;
cout<<"4) Consultar Informacion de una Cancion."<<endl;
cout<<"5) Eliminar una Cancion."<<endl;
cout<<"6) Salir y Actualizar Archivo";
tecla = getch();
switch(tecla){
case '1':
system("cls");
Principal::imprimirListado();
cout<<endl;
system("PAUSE");
system("cls");
break;
case '2':
system("cls");
Principal::imprimirListadoPorGenero();
system("PAUSE");
system("cls");
break;
case '3':
system("cls");
Principal::agregarCancion();
system("PAUSE");
system("cls");
break;
case '4':
system("cls");
Principal::consultarInformacionCancion();
system("PAUSE");
system("cls");
break;
case '5':
system("cls");
Principal::eliminarCancion();
system("PAUSE");
system("cls");
break;
case '6':
system("cls");
cout<<"Fin del Programa."<<endl<<endl;
band = false;
// listaGen.imprimir();
system("PAUSE");
system("cls");
break;
default:
system("cls");
cout<<"OPCION INVALIDA!"<<endl<<endl;
system("PAUSE");
system("cls");
}
}while(band);
}
void Principal::separarGenero(){
char nombre[40]="mp3.txt";
genero.open(nombre,ios::in);
if(genero.fail()){
cout<<"Error al Abrir el Archivo"<<endl;
}else{
while(getline(genero,cadena)){
auxCadena = strtok(&cadena[0],",");
char auxTitulo[40];
strcpy(auxTitulo,auxCadena);
auxCadena = strtok(NULL,",");
char auxAutor[40];
strcpy(auxAutor,auxCadena);
auxCadena = strtok(NULL,",");
int auxTamKb = atoi(auxCadena);
auxCadena = strtok(NULL,",");
char auxAlbum[40];
strcpy(auxAlbum,auxCadena);
auxCadena = strtok(NULL,"\n");
char auxGenero[40];
strcpy(auxGenero,auxCadena);
// cout<<"Titulo: "<<auxTitulo<<" Auto: "<<auxAutor<<" Tamao: "<<auxTamKb<< " Album: "<<auxAlbum<<" Genero: "<<auxGenero<<endl;
Genero u(auxGenero);
if(listaGen.buscar(u)!=1) listaGen.agregar(u);
}
}
genero.close();
}
void Principal::separarDatos(){
char nombre[40]="mp3.txt";
canciones.open(nombre,ios::in);
if(canciones.fail()){
cout<<"Error al Abrir el Archivo"<<endl;
}else{
while(getline(canciones,cadena)){
auxCadena = strtok(&cadena[0],",");
char auxTitulo[30];
strcpy(auxTitulo,auxCadena);
auxCadena = strtok(NULL,",");
char auxAutor[30];
strcpy(auxAutor,auxCadena);
auxCadena = strtok(NULL,",");
int auxTamKb = atoi(auxCadena);
auxCadena = strtok(NULL,",");
char auxAlbum[30];
strcpy(auxAlbum,auxCadena);
auxCadena = strtok(NULL,"\n");
char auxGenero[30];
strcpy(auxGenero,auxCadena);
// cout<<"Titulo: "<<auxTitulo<<" Auto: "<<auxAutor<<" Tamao: "<<auxTamKb<< " Album: "<<auxAlbum<<" Genero: "<<auxGenero<<endl;
Canciones can(auxTitulo,auxAutor,auxTamKb,auxAlbum,auxGenero);
Genero buscar(auxGenero);
if(listaGen.buscar(buscar)==1){
buscar.agregarCancion(can);
}
}
}
canciones.close();
}
void Principal::imprimirListado(){
Nodo<Genero> *Gen;
Gen = listaGen.getCab();
cout<<"Listado por Genero."<<endl;
while(Gen!=NULL){
Gen->getInfo().imprimir(true);
Gen = Gen->getSig();
}
}
void Principal::agregarCancion(){
char titulo[30];
char autor[30];
int tama;
char album[30];
char genero[30];
cout<<"Agregar Cancion."<<endl<<endl;
cout<<"Ingrese un Titulo: ";
cin>>titulo;
cout<<endl<<"Ingrese un Autor: ";
cin>>autor;
cout<<endl<<"Ingrese Tamao de la cancion: ";
cin>>tama;
cout<<endl<<"Ingrese el Album: ";
cin>>album;
cout<<endl<<"Ingrese el genero: ";
cin>>genero;
Genero consultar(genero);
Canciones can(titulo,autor,tama,album,genero);
if(listaGen.buscar(consultar)==1){
if(consultar.buscarCancion(can)==1){
consultar.agregarCancion(can);
cout<<endl<<"Se Agrego Sastifactoriamente."<<endl<<endl;
}else cout<<endl<<"Dato Existente."<<endl<<endl;
}else{
listaGen.agregar(consultar);
if(listaGen.buscar(consultar)==1){
if(consultar.buscarCancion(can)!=1) consultar.agregarCancion(can);
cout<<endl<<"Se Agrego los Datos Sastifactoriamente."<<endl;
}
cout<<"Genero agregado Sastifactoriamente."<<endl<<endl;
}
}
void Principal::consultarInformacionCancion(){
char nombre[40]="mp3.txt";
char genero[30];
char cancion[30];
char letra;
bool invert = true;
cout<<"Ingrese la cancion que deseas consultar: ";
cin>>cancion;
canciones.open(nombre,ios::in);
if(canciones.fail()){
cout<<"Error al Abrir el Archivo"<<endl;
}else{
while(getline(canciones,cadena)){
auxCadena = strtok(&cadena[0],",");
char auxTitulo[30];
strcpy(auxTitulo,auxCadena);
auxCadena = strtok(NULL,",");
char auxAutor[30];
strcpy(auxAutor,auxCadena);
auxCadena = strtok(NULL,",");
int auxTamKb = atoi(auxCadena);
auxCadena = strtok(NULL,",");
char auxAlbum[30];
strcpy(auxAlbum,auxCadena);
auxCadena = strtok(NULL,"\n");
char auxGenero[30];
strcpy(auxGenero,auxCadena);
if(strcmpi(cancion,auxTitulo)==0){
strcpy(genero,auxGenero);
}
}
}
canciones.close();
Genero consultar(genero);
Canciones can(cancion,"",0,"","");
if(listaGen.buscar(consultar)==1){
if(consultar.buscarCancion(can)==1){
letra = cancion[0];
if((letra >= 'A' && letra<='I') || (letra>='a' && letra<='i')){
if(invert){
cout<<"Existe cancion"<<endl;
consultar.imprimir(true);
}else{
cout<<"Existe cancion"<<endl;
consultar.invertListaCanciones();
consultar.imprimir(true);
invert = true;
}
}else if((letra >= 'J' && letra<='Z') || (letra>='j' && letra<='z')){
if(invert){
cout<<"Existe cancion"<<endl;
consultar.invertListaCanciones();
consultar.imprimir(true);
invert = false;
}else{
cout<<"Existe cancion"<<endl;
consultar.imprimir(true);
}
}
}else cout<<endl<<"La cancion no se Elimino, xq No Existe."<<endl;
}else cout<<endl<<"El Genero no Existe."<<endl;
}
void Principal::eliminarCancion(){
char nombre[40]="mp3.txt";
char genero[30];
char cancion[30];
cout<<"Ingrese la cancion que deseas consultar: ";
cin>>cancion;
canciones.open(nombre,ios::in);
if(canciones.fail()){
cout<<"Error al Abrir el Archivo"<<endl;
}else{
while(getline(canciones,cadena)){
auxCadena = strtok(&cadena[0],",");
char auxTitulo[30];
strcpy(auxTitulo,auxCadena);
auxCadena = strtok(NULL,",");
char auxAutor[30];
strcpy(auxAutor,auxCadena);
auxCadena = strtok(NULL,",");
int auxTamKb = atoi(auxCadena);
auxCadena = strtok(NULL,",");
char auxAlbum[30];
strcpy(auxAlbum,auxCadena);
auxCadena = strtok(NULL,"\n");
char auxGenero[30];
strcpy(auxGenero,auxCadena);
if(strcmpi(cancion,auxTitulo)==0){
strcpy(genero,auxGenero);
}
}
}
canciones.close();
Genero consultar(genero);
Canciones can(cancion,"",0,"","");
if(listaGen.buscar(consultar)==1){
if(consultar.buscarCancion(can)==1){
consultar.eliminarCancion(can);
cout<<endl<<"Se Elimino Sastifactoriamente."<<endl;
}else cout<<endl<<"La cancion no Existe."<<endl;
}else cout<<endl<<"El Genero no Existe."<<endl;
}
void Principal::imprimirListadoPorGenero(){
char genero[30];
cout<<" Ingrese el Genero a Consultar: ";
cin>>genero;
Genero consultar(genero);
if(listaGen.buscar(consultar)==1) consultar.imprimir(true);
}
void Principal::mostrarMensajeError(){
system("cls");
cout<<"Error - Debes Crear el Sistema."<<endl<<endl;
system("PAUSE");
system("cls");
}
#endif
| true |
525f3da93595a7c132f1dab14738452362779a39
|
C++
|
RTRTextures/project
|
/common/include/Renderer.h
|
UTF-8
| 5,612 | 2.953125 | 3 |
[] |
no_license
|
/// @file Renderer.h
/// @brief Defines the interface between OpenGL generic host process and its pluggable 'Renderer' clients
/// Host: Framework OpenGL host process which will load multiple renderers for rendering a scene
/// Renderer: Implementer of the scene container in its class
#ifdef _WIN32
#include <windows.h>
#endif
#pragma once
namespace Interfaces
{
/// Possible return values of methods implemented by renderers
enum RendererResult
{
/// Indicates error in perfoming an operation
RENDERER_RESULT_ERROR = 0,
/// Indicates success in performing an operation
RENDERER_RESULT_SUCCESS = 1,
/// Indicates completion in processing of an operation
RENDERER_RESULT_FINISHED = 2
};
/// Possible scene types supported by the host application. Renderer is per scene.
/// SceneType can be also termed as an epic of scenes.
/// Scenes are transitioned according to their order of registrations and can be transitioned
/// in below cases -
/// 1. When all components have finished rendering present scene
/// 2. There is request to the renderer to switch the scene.
enum SceneType
{
/// General initialization for all the scenes implemented by the component
SCENE_TYPE_TEST0,
SCENE_TYPE_TEST1,
SCENE_SOLAR_SYSTEM, // This will be the main solar system scene
SCENE_NUCLEUS,
SCENE_ATOMS,
SCENE_CHEMICAL_BONDS,
SCENE_CONDUCTORS,
SCENE_SILICON,
SCENE_IMPURITY_DOPING,
SCENE_DIODE,
SCENE_TRIANSISTOR,
SCENE_GATES,
SCENE_CHIPS
};
#ifdef _WIN32
struct Message
{
UINT messageId;
WPARAM wParam;
LPARAM lParam;
};
#define Window HWND
#endif
/// Parameters passed to a scene
struct RenderParams
{
/// Type of the Scene
SceneType scene;
/// Microsecs time elapsed from start of an EPIC
unsigned long long elapsedFromEpicStart;
/// FrameId from start of an EPIC
unsigned long long frameIdFromEpicStart;
/// Microsecs time elapsed from start of a scene
unsigned long long elapsedFromSceneStart;
/// FrameId from start of a scene
unsigned long long frameIdFromSceneStart;
};
/// macro to convert seconds to microseconds
#define SECS_TO_MICROSECS(x) ((x)*1000*1000)
/// @brief interface to render
class IRenderer
{
public:
/// Method for retrieving name of the renderer
/// @return NULL on failure otherwise pointer to null-terminated string mentioning name of
// this renderer.
virtual const char* GetName() = 0;
/// Method for performing one-time renderer initialization.
/// Renderer can initialize global/static instances as part of this method
/// @param window identifier of the window where drawing is directed
/// @return RENDERER_RESULT_SUCCESS if succeded
/// RENDERER_RESULT_ERROR if failed.
virtual RendererResult Initialize(Window window) = 0;
/// Method for performing one-time renderer un-initialization before it is unloaded
/// Renderer can perform global cleanup as part of this method
virtual void Uninitialize(void) = 0;
/// Method for performing scene-specific initialization
/// This method will be called by the host before rendering a scene to the active renderer.
/// Renderer should do initialization of scene specific things as part of this method
/// @param scene Identifier of a scene to be initialized
/// @return RENDERER_RESULT_SUCCESS if succeded
/// RENDERER_RESULT_ERROR if failed.
virtual RendererResult InitializeScene(SceneType scene) = 0;
/// Method for performing scene-specific initialization
/// This method will be called by the host after rendering a scene to the active renderer
/// Renderer should do cleanup of scene specific things done as part of scene initialize.
/// @param scene Identifier of a scene to be cleaned-up
virtual void UninitializeScene(SceneType scene) = 0;
/// Method for rendering a frame in a scene
/// This method will be called by the host per frame of a scene only to the active renderer
/// @param params describes the parameters curresponding to this render
/// @return RENDERER_RESULT_SUCCESS if succeded in building the frame
/// RENDERER_RESULT_ERROR if failed in building the frame
/// RENDERER_RESULT_FINISHED if renderer has finished building its last frame of the scene.
/// in such cases no further frame calls would be made for this scene
/// to the renderer.
virtual RendererResult Render(const RenderParams ¶ms) = 0;
/// Generic method to notify active renderer about a message posted to host window. The message can be
/// from system or initiated by the host itself.
/// @param message OS dependent structure that describes the system message being processed.
virtual void OnMessage(const Message &message) = 0;
/// Generic method to notify active renderer about the change in the dimensions of the host window
/// @param width New width of the window
/// @param height New height of the window
virtual void OnResize(unsigned int width, unsigned int height) = 0;
};
} // Interfaces
| true |
504391134bb6968691c684123a9e455ecd998b18
|
C++
|
MichaelMGabriel/MasliMichael_CSC5_43952
|
/Lab/TruthTable_1/main.cpp
|
UTF-8
| 2,886 | 3.421875 | 3 |
[] |
no_license
|
/*
* File: main.cpp
* Author: Michael Masli
*
* Created on March 18, 2015, 10:02 AM
*
*/
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
//Declare Variables
bool x,y;
//Heading
cout<<"X Y !X !Y X&&Y X||Y X^Y X^Y^Y X^Y^X "
<<"!(X&&Y) !X||!Y !(X||Y) !X&&!Y"<<endl;
//Output the first row of the table
x=true;
y=true;
cout<<(x? 'T' : 'F')<<" "; //Using Ternary Operator
cout<<(y? 'T' : 'F')<<" ";
cout<<(!x? 'T' : 'F')<<" ";
cout<<(!y? 'T' : 'F')<<" ";
cout<<(x&&y? 'T' : 'F')<<" ";
cout<<(x||y? 'T' : 'F')<<" ";
cout<<(x^y? 'T' : 'F')<<" ";
cout<<(x^y^y? 'T' : 'F')<<" ";
cout<<(x^y^x? 'T' : 'F')<<" ";
cout<<(!(x&&y)? 'T' : 'F')<<" ";
cout<<(!x||!y? 'T' : 'F')<<" ";
cout<<(!(x||y)? 'T' : 'F')<<" ";
cout<<(!x&&!y? 'T' : 'F')<<" ";
cout<<endl;
//Output the second row of the table
y=false;
cout<<(x? 'T' : 'F')<<" "; //Using Ternary Operator
cout<<(y? 'T' : 'F')<<" ";
cout<<(!x? 'T' : 'F')<<" ";
cout<<(!y? 'T' : 'F')<<" ";
cout<<(x&&y? 'T' : 'F')<<" ";
cout<<(x||y? 'T' : 'F')<<" ";
cout<<(x^y? 'T' : 'F')<<" ";
cout<<(x^y^y? 'T' : 'F')<<" ";
cout<<(x^y^x? 'T' : 'F')<<" ";
cout<<(!(x&&y)? 'T' : 'F')<<" ";
cout<<(!x||!y? 'T' : 'F')<<" ";
cout<<(!(x||y)? 'T' : 'F')<<" ";
cout<<(!x&&!y? 'T' : 'F')<<" ";
cout<<endl;
//Output the third row of the table
x=false;
cout<<(x? 'T' : 'F')<<" "; //Using Ternary Operator
cout<<(y? 'T' : 'F')<<" ";
cout<<(!x? 'T' : 'F')<<" ";
cout<<(!y? 'T' : 'F')<<" ";
cout<<(x&&y? 'T' : 'F')<<" ";
cout<<(x||y? 'T' : 'F')<<" ";
cout<<(x^y? 'T' : 'F')<<" ";
cout<<(x^y^y? 'T' : 'F')<<" ";
cout<<(x^y^x? 'T' : 'F')<<" ";
cout<<(!(x&&y)? 'T' : 'F')<<" ";
cout<<(!x||!y? 'T' : 'F')<<" ";
cout<<(!(x||y)? 'T' : 'F')<<" ";
cout<<(!x&&!y? 'T' : 'F')<<" ";
cout<<endl;
//Output the fourth row of the table
x=false;
y=false;
cout<<(x? 'T' : 'F')<<" "; //Using Ternary Operator
cout<<(y? 'T' : 'F')<<" ";
cout<<(!x? 'T' : 'F')<<" ";
cout<<(!y? 'T' : 'F')<<" ";
cout<<(x&&y? 'T' : 'F')<<" ";
cout<<(x||y? 'T' : 'F')<<" ";
cout<<(x^y? 'T' : 'F')<<" ";
cout<<(x^y^y? 'T' : 'F')<<" ";
cout<<(x^y^x? 'T' : 'F')<<" ";
cout<<(!(x&&y)? 'T' : 'F')<<" ";
cout<<(!x||!y? 'T' : 'F')<<" ";
cout<<(!(x||y)? 'T' : 'F')<<" ";
cout<<(!x&&!y? 'T' : 'F')<<" ";
cout<<endl;
//Exit Stage Right!!!
return 0;
}
| true |
83d5eccab7929274a1e161bf02e72ce16568f4cc
|
C++
|
Li2012/AdvCiv
|
/CvGameCoreDLL/WarAndPeaceCache.h
|
UTF-8
| 9,935 | 2.6875 | 3 |
[] |
no_license
|
#pragma once
#ifndef WAR_AND_PEACE_CACHE_H
#define WAR_AND_PEACE_CACHE_H
#include "CvEnums.h"
#include "CvDeal.h"
#include "CvInfos.h"
#include "MilitaryBranch.h."
#include <vector>
/* <advc.104>: Cached data used by the war-and-peace AI. Each civ has its own
cache. That said, each civ's cache also contains certain (subjective)
information about all other civs.
Also handles the updating of cached values, i.e. many of the AI's
heuristic functions belong to this class. (Maybe it would be cleaner
if the heuristics were moved to WarAndPeaceAI::Civ? Will have to split
it up a bit more at some point b/c this class is getting too large.) */
class WarAndPeaceCache {
public:
class City;
WarAndPeaceCache();
~WarAndPeaceCache();
/* Call order during initialization and clean-up:
+ When starting a new game directly after starting Civ 4:
Constructors (for CvTeam and all related classes) are called, then init.
Actually, the CvTeam constructor is already called when starting up Civ.
+ When starting a new game after returning to the main menu
from another game: Constructors are _not_ called; objects need
to be reset in init. Highly error-prone, but there's no changing it.
clear(bool) handles the reset.
+ When loading a savegame right after starting Civ:
Constructors are called (some already when starting Civ), read is called
while loading the savegame.
+ When loading a savegame after returning to the main menu:
Only read is called. Will have to reset the object.
+ When returning to the main menu, nothing special happens.
+ Only when exiting Civ, destructors are called. They might be called on
other occasions, but, on exit, it's guaranteeed.
+ When saving a game, write is called. */
void init(PlayerTypes ownerId);
void update();
void write(FDataStreamBase* stream);
void read(FDataStreamBase* stream);
int numReachableCities(PlayerTypes civId) const ;
int size() const;
void sortCitiesByOwnerAndDistance();
void sortCitiesByOwnerAndTargetValue();
void sortCitiesByDistance();
void sortCitiesByTargetValue();
void sortCitiesByAttackPriority();
City* getCity(int index) const;
// Use CvCity::plotNum for the plotIndex of a given CvCity
City* lookupCity(int plotIndex) const;
// Referring to cache owner
bool hasAggressiveTrait() const;
bool hasProtectiveTrait() const;
bool canScrubFallout() const;
// Ongoing combat missions against civId
int targetMissionCount(PlayerTypes civId) const;
/* Long-term military threat by civId between 0 and 1. Can see it as the
probability of them hurting us substantially with an invasion sometime
within the next 50 to 100 turns. */
double threatRating(PlayerTypes civId) const;
// If civId were to capitulate to the cache owner
int vassalTechScore(PlayerTypes civId) const;
int vassalResourceScore(PlayerTypes civId) const;
int numAdjacentLandPlots(PlayerTypes civId) const;
double relativeNavyPower(PlayerTypes civId) const;
int pastWarScore(TeamTypes tId) const;
// Trade value paid to us for declaring war against tId
int sponsorshipAgainst(TeamTypes tId) const;
// Identity of the sponsor who made the above payment
PlayerTypes sponsorAgainst(TeamTypes tId) const;
/* Other classes should base the actual war utility computations on this
preliminary result */
int warUtilityIgnoringDistraction(TeamTypes tId) const;
bool canTrainDeepSeaCargo() const;
bool canTrainAnyCargo() const;
/* Caching of power values. Military planning must not add the power
of hypothetical units to the vector; need to make a copy for that. */
std::vector<MilitaryBranch*> const& getPowerValues() const;
// Counts only combatants
int numNonNavyUnits() const;
// Includes national wonders (which City::updateAssetScore does not count)
double totalAssetScore() const;
/* Number of citizens that are angry now and wouldn't be if it weren't for
the war weariness against civId. */
double angerFromWarWeariness(PlayerTypes civId) const;
double goldValueOfProduction() const;
void reportUnitCreated(CvUnitInfo const& u);
void reportUnitDestroyed(CvUnitInfo const& u);
void reportWarEnding(TeamTypes enemyId);
/* Would prefer to pass a CvDeal object, but no suitable one is available
at the call location */
void reportSponsoredWar(CLinkList<TradeData> const& sponsorship,
PlayerTypes sponsorId, TeamTypes targetId);
bool isReadyToCapitulate(TeamTypes masterId) const;
void setReadyToCapitulate(TeamTypes masterId, bool b);
// When forming a Permanent Alliance
void addTeam(TeamTypes otherId);
/* public b/c this needs to be done ahead of the normal update when a
colony is created (bootsrapping problem) */
void updateTypicalUnits();
private:
// beforeUpdated: Only clear data that is recomputed in 'update'
void clear(bool beforeUpdate = false);
void updateCities(PlayerTypes civId);
void updateLatestTurnReachableBySea();
void updateHasAggressiveTrait();
void updateHasProtectiveTrait();
void updateTargetMissionCounts();
void updateThreatRatings();
void updateVassalScores();
void updateAdjacentLand();
void updateRelativeNavyPower();
void updateTargetMissionCount(PlayerTypes civId);
double calculateThreatRating(PlayerTypes civId) const;
double teamThreat(TeamTypes tId) const;
double longTermPower(TeamTypes tId, bool defensive = false) const;
void updateVassalScore(PlayerTypes civId);
void updateMilitaryPower(CvUnitInfo const& u, bool add);
void updateTotalAssetScore();
void updateWarAnger();
void updateGoldPerProduction();
double goldPerProdBuildings();
double goldPerProdSites();
double goldPerProdVictory();
void updateWarUtility();
void updateWarUtilityIgnDistraction(TeamTypes targetId);
void updateCanScrub();
void updateTrainCargo();
// To supply team-on-team data
WarAndPeaceCache const& leaderCache() const;
PlayerTypes ownerId;
std::vector<City*> v;
std::map<int,City*> cityMap;
std::map<int,std::pair<int,int> > latestTurnReachableBySea;
std::vector<MilitaryBranch*> militaryPower;
int nNonNavyUnits;
double totalAssets;
double goldPerProduction;
bool bHasAggressiveTrait, bHasProtectiveTrait;
bool canScrub;
bool trainDeepSeaCargo, trainAnyCargo;
std::set<TeamTypes> readyToCapitulate;
static double const goldPerProdUpperLimit;
// Serializable arrays
// per civ
double wwAnger[MAX_CIV_PLAYERS];
int nReachableCities[MAX_CIV_PLAYERS];
int targetMissionCounts[MAX_CIV_PLAYERS];
double threatRatings[MAX_CIV_PLAYERS];
int vassalTechScores[MAX_CIV_PLAYERS];
int vassalResourceScores[MAX_CIV_PLAYERS];
bool located[MAX_CIV_PLAYERS];
// (CvTeamAI::AI_calculateAdjacentLandPlots is too slow and per team)
int adjacentLand[MAX_CIV_PLAYERS];
double relativeNavyPow[MAX_CIV_PLAYERS];
// per team
int pastWarScores[MAX_CIV_TEAMS];
// Value of the sponsorship
int sponsorshipsAgainst[MAX_CIV_TEAMS];
// Identity of the sponsor (PlayerTypes)
int sponsorsAgainst[MAX_CIV_TEAMS];
int warUtilityIgnDistraction[MAX_CIV_TEAMS];
public:
/* Information to be cached about a CvCity and scoring functions useful
for computing war utility. */
class City {
public:
City(PlayerTypes cacheOwnerId, CvCity* c);
City(PlayerTypes cacheOwnerId); // for reading from savegame
PlayerTypes cityOwner() const;
int getAssetScore() const;
bool canReach() const;
/* -1 if unreachable
forceCurrentVal: Doesn't fall back on latestTurnReachable if not
currently reachable. */
int getDistance(bool forceCurrentVal = false) const;
int getTargetValue() const;
bool canReachByLand() const;
// Use canReachByLand instead for military analysis
bool canCurrentlyReachBySea() const;
/* CvCity doesn't have a proper ID. Use the plot number (index of
the linearized map) as an ID. It's unique (b/c there is at most
one city per plot), but not consecutive (most plots don't have
a city). */
int id() const;
// NULL if the city no longer exists at the time of retrieval
CvCity* city() const;
/* 'r' is an empty vector in which the 21 CvPlot* will be placed. r[0]
is the city tile itself; the others in no particular order. If a
city's fat cross has fewer plots (edge of the map), some NULL entries
will be included. If the underlying CvCity no longer exists,
all entries are NULL. */
void fatCross(std::vector<CvPlot*>& r);
void write(FDataStreamBase* stream);
void read(FDataStreamBase* stream);
static CvCity* cityById(int id);
/* For sorting cities. The ordering of owners is arbitrary, just
ensures that each civ's cities are ordered consecutively.
For cities of the same owner: true if 'one' is closer to us than 'two'
in terms of getDistance. */
static bool byOwnerAndDistance(City* one, City* two);
static bool byDistance(City* one, City* two);
// Unreachable cities are treated as having targetValue minus infinity.
static bool byOwnerAndTargetValue(City* one, City* two);
static bool byTargetValue(City* one, City* two);
static bool byAttackPriority(City* one, City* two);
private:
/* Auxiliary function for sorting. -1 means one < two, +1 two < one and 0
neither. */
static int byOwner(City* one, City* two);
// Wrapper for CvUnit::generatePath
bool measureDistance(DomainTypes dom, CvPlot* start, CvPlot* dest, int* r);
void updateDistance(CvCity* targetCity);
void updateAssetScore();
/* A mix of target value and distance. Target value alone would
ignore opportunistic attacks. */
double attackPriority() const;
int plotIndex, assetScore, distance, targetValue;
bool reachByLand;
bool reachBySea;
PlayerTypes cacheOwnerId;
};
};
// </advc.104>
#endif
| true |
86655428d7936c5e1c2d0abd17c67511ed8b7c65
|
C++
|
IIvexII/CS
|
/PF-CSC313/Loops/c2.cpp
|
UTF-8
| 651 | 3.734375 | 4 |
[] |
no_license
|
/*
Date: 9-12-2020
Purpose: Print half pyramid using numbers
Author: Zafeer
*/
#include <iostream>
using namespace std;
int main(){
int total_rows;
cout << "Enter number of rows: ";
cin >> total_rows;
// This for loop will run untill the
// rows are less or equal to the total rows.
for(int rows=1; rows<=total_rows; rows++){
// This will print star in a row
// which are equal to the row we are in.
// e.g for 2nd row, columns will be 2 as well.
for(int column=1; column<=rows; column++){
cout << column << " ";
}
cout << endl;
}
return 0;
}
| true |
06cf08ae0f889f28c748b2591287982700be2ba9
|
C++
|
AlexTangus/CHAT
|
/version_1/Chat/server/first_implement/main.cpp
|
UTF-8
| 5,792 | 2.765625 | 3 |
[] |
no_license
|
#include <iostream>
#include <memory>
#include <thread>
#include <atomic>
#include <mutex>
#include <map>
#include <boost/asio.hpp>
using std::cout;
using std::cin;
using std::endl;
using std::cerr;
std::map<std::string, std::shared_ptr<boost::asio::ip::tcp::socket>> name_sock;
std::mutex all_thread_guard;
class Service
{
private:
std::shared_ptr<boost::asio::ip::tcp::socket> pointer_to_sock;
boost::asio::streambuf m_request;
std::string m_response;
std::string name;
bool first_connection;
private:
void onFinish()
{
eraseFromTable();
boost::system::error_code ignored_er;
pointer_to_sock->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_er);
pointer_to_sock->close();
delete this;
}
void addToTable()
{
all_thread_guard.lock();
name_sock[this->name] = pointer_to_sock;
all_thread_guard.unlock();
}
void eraseFromTable()
{
all_thread_guard.lock();
auto it = name_sock.find(this->name);
if(it != name_sock.end())
name_sock.erase(it);
all_thread_guard.unlock();
}
void onResponseSent(const boost::system::error_code &er, std::size_t bytes)
{
if(er != 0)
cerr << "onResponseSent error! Value: " << er.value() << " | Message: " << er.message() << endl;
}
void onRequestRecieved(const boost::system::error_code &er, std::size_t bytes)
{
if(er != 0)
{
cerr << "onRequestRecieved error! Value: " << er.value() << " | Message: " << er.message() << endl;
onFinish();
return;
}
std::istream in(&m_request);
std::getline(in, m_response);
if(m_response != "")
{
//m_response.pop_back(); // pop symbol '\r'
if(m_response[m_response.length() - 1] == '\r')
m_response.pop_back();
if(m_response == "EXIT")
{
onFinish();
return;
}
if(first_connection)
{
name = m_response;
addToTable();
first_connection = false;
readMsg();
}
else if(!first_connection)
{
m_response.push_back('\n'); // push symbol '\n' for write to sockets
writeMsg();
}
}
}
void writeMsg()
{
std::string temp = name + ": " + m_response;
for(std::map<std::string, std::shared_ptr<boost::asio::ip::tcp::socket> >::iterator it = name_sock.begin(); it != name_sock.end(); it++)
{
if(this->name == it->first)
continue;
boost::asio::async_write(*(it->second).get(), boost::asio::buffer(temp), [this](const boost::system::error_code &er, std::size_t bytes)
{
onResponseSent(er, bytes);
});
}
readMsg();
}
void readMsg()
{
boost::asio::async_read_until(*pointer_to_sock.get(), m_request, '\n', [this](const boost::system::error_code &er, std::size_t bytes)
{
onRequestRecieved(er, bytes);
});
}
public:
Service(std::shared_ptr<boost::asio::ip::tcp::socket> &sock): pointer_to_sock(sock), first_connection(true) {}
void startHandling()
{
readMsg();
}
};
class Acceptor
{
private:
boost::asio::io_service &m_ios;
boost::asio::ip::tcp::acceptor m_acc;
std::atomic<bool> m_isStop;
private:
void onAccept(const boost::system::error_code &er, std::shared_ptr<boost::asio::ip::tcp::socket> p_sock)
{
if(er == 0)
(new Service(p_sock))->startHandling();
else
cout << "Accept error. Value: " << er.value() << " | Message: " << er.message() << endl;
if(!m_isStop.load())
initAccept();
else
m_acc.close();
}
void initAccept()
{
std::shared_ptr<boost::asio::ip::tcp::socket> p_sock(new boost::asio::ip::tcp::socket(m_ios));
m_acc.async_accept(*p_sock.get(), [this, p_sock](const boost::system::error_code &er)
{
onAccept(er, p_sock);
});
}
public:
Acceptor(boost::asio::io_service &ios, unsigned short port)
: m_ios(ios), m_acc(m_ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::any(), port)) {}
void start()
{
m_acc.listen();
initAccept();
}
void stop()
{
m_isStop.store(true);
}
};
class Server
{
private:
boost::asio::io_service ios;
std::unique_ptr<boost::asio::io_service::work> work;
std::unique_ptr<Acceptor> acc;
std::vector<std::unique_ptr<std::thread>> m_thread;
public:
Server()
{
work.reset(new boost::asio::io_service::work(ios));
}
void start(unsigned short port, unsigned int amount_threads)
{
acc.reset(new Acceptor(ios, port));
acc->start();
for(unsigned int i(0); i < amount_threads; i++)
{
std::unique_ptr<std::thread> th(new std::thread([this]()
{
ios.run();
}));
m_thread.push_back(std::move(th));
}
}
void stop()
{
acc->stop();
ios.stop();
for(auto &th : m_thread)
th->join();
}
};
int main()
{
unsigned short port = 3333;
try
{
Server obj;
obj.start(port, 3);
std::this_thread::sleep_for(std::chrono::seconds(1200));
obj.stop();
}
catch(boost::system::system_error &er)
{
cerr << "Error occured. With code: " << er.code() << " | With message: " << er.what() << endl;
return er.code().value();
}
return 0;
}
| true |
18f4683a95034159ff31513b2d34b22f33244d1c
|
C++
|
tonycar12002/leetcode
|
/Cpp/26. Remove Duplicates from Sorted Array.cpp
|
UTF-8
| 383 | 2.875 | 3 |
[] |
no_license
|
/*
Author: Tony Hsiao
Date: 2019/04/30
Topic: 26. Remove Duplicates from Sorted Array
Speed: 24 ms
Note:
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int record = 0 ;
for(int i=0;i<nums.size();i++){
if(i==0 || nums[i] != nums[i-1]){
nums[record++] = nums[i];
}
}
return record;
}
};
| true |
266cadcc9db9c8dbdba8b30097ce23d1e8aa1dbe
|
C++
|
bliou/TheQuestOfTheBurningHeart
|
/TheQuestOfTheBurningHeart/TimedTileData.h
|
UTF-8
| 560 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include "AbstractSolidBlockTileData.h"
class TimedTileData: public AbstractSolidBlockTileData
{
public:
TimedTileData(
float timer = 2.f,
bool reset = false,
float resetTimer = 5.f
);
~TimedTileData();
virtual void initializeEntity(
std::string dataId,
anax::Entity& entity,
GameScreen& gameInstance,
sf::Vector2f position,
nlohmann::json::value_type specificData) override;
protected:
static const std::string texturePath;
static const sf::Vector2i graphicSize;
float m_timer;
bool m_reset;
float m_resetTimer;
};
| true |
b73440fc9b742c97e2254711ce781d3bc307d239
|
C++
|
KingsleyYau/LiveClient
|
/common/ImClient/TransportClient.cpp
|
UTF-8
| 9,346 | 2.546875 | 3 |
[] |
no_license
|
/*
* author: Samson.Fan
* date: 2017-05-18
* file: TransportClient.cpp
* desc: 传输数据客户端接口类(负责与服务器之间的基础通讯,如Tcp、WebSocket等)
*/
#include "TransportClient.h"
#include <common/KLog.h>
#include <common/CommonFunc.h>
const long long WEBSOCKET_CONNECT_TIMEOUT = 30*1000; // websoecket超时(毫秒)
TransportClient::TransportClient(void)
{
m_connStateLock = IAutoLock::CreateAutoLock();
m_connStateLock->Init();
m_isInitMgr = false;
m_connState = DISCONNECT;
m_conn = NULL;
m_isWebConnected = false;
// 初始化websocket的锁
mg_global_init();
}
TransportClient::~TransportClient(void)
{
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::~TransportClient() begin");
// 释放mgr
ReleaseMgrProc();
// 释放websocket的锁
mg_global_free();
IAutoLock::ReleaseAutoLock(m_connStateLock);
m_connStateLock = NULL;
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::~TransportClient() end");
}
// -- ITransportClient
// 初始化
bool TransportClient::Init(ITransportClientCallback* callback)
{
m_callback = callback;
return true;
}
// 连接
bool TransportClient::Connect(const char* url)
{
bool result = false;
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Connect() begin");
m_isWebConnected = false;
if (NULL != url && url[0] != '\0') {
// 释放mgr,
ReleaseMgrProc();
m_connStateLock->Lock();
if (DISCONNECT == m_connState) {
// 创建mgr
mg_mgr_init(&m_mgr, NULL);
m_isInitMgr = true;
// 连接url
m_url = url;
struct mg_connect_opts opt = {0};
opt.user_data = (void*)this;
m_conn = mg_connect_ws_opt(&m_mgr, ev_handler, opt, m_url.c_str(), "", NULL);
//mg_set_timer(m_conn, mg_time() + 1.5);
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Connect() m_conn:%p m_conn->err:%d m_conn->sock:%d start", m_conn, m_conn->err, m_conn->sock);
if (NULL != m_conn && m_conn->err == 0) {
m_connState = CONNECTING;
result = true;
}
}
m_connStateLock->Unlock();
// 连接失败, 不放在m_connStateLock锁里面,因为mg_connect_ws_opt已经ev_handler了,导致ReleaseMgrProc关闭websocket回调ev_handler 的关闭 调用OnDisconnect的m_connStateLock锁
if (!result) {
if (NULL != m_conn) {
// 释放mgr
ReleaseMgrProc();
}
else {
// 仅重置标志
m_isInitMgr = false;
}
}
}
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Connect() end");
return result;
}
// 断开连接
void TransportClient::Disconnect()
{
m_connStateLock->Lock();
DisconnectProc();
m_connStateLock->Unlock();
}
// 断开连接处理(不锁)
void TransportClient::DisconnectProc()
{
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::DisconnectProc() m_conn:%p m_connState:%d begin", m_conn, m_connState);
// 当m_connState == CONNECTING时,im的socket还没有connect(可能是连socket都没有(因为ip为域名时mg_connect_ws_opt不去socket,都放到mg_mgr_poll去做,导致socketid没有,mg_shutdown 没有用,就设置DISCONNECT,使mg_mgr_poll结束))
if (m_connState == CONNECTING || m_connState == DISCONNECT) {
m_connState = DISCONNECT;
}
if (NULL != m_conn) {
FileLog("ImClient", "TransportClient::DisconnectProc() m_conn:%p m_conn->err:%d m_conn->sock:%d m_connState:%d", m_conn, m_conn->err, m_conn->sock, m_connState);
mg_shutdown(m_conn);
m_conn = NULL;
}
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::DisconnectProc() m_conn:%p m_connState:%d end", m_conn, m_connState);
}
// 释放mgr
void TransportClient::ReleaseMgrProc()
{
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::ReleaseMgrProc(m_isInitMgr:%d) start", m_isInitMgr);
if (m_isInitMgr) {
mg_mgr_free(&m_mgr);
m_isInitMgr = false;
}
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::ReleaseMgrProc() end");
}
// 获取连接状态
ITransportClient::ConnectState TransportClient::GetConnectState()
{
ConnectState state = DISCONNECT;
m_connStateLock->Lock();
state = m_connState;
m_connStateLock->Unlock();
return state;
}
// 发送数据
bool TransportClient::SendData(const unsigned char* data, size_t dataLen)
{
bool result = false;
if (NULL != data && dataLen > 0) {
if (CONNECTED == m_connState && NULL != m_conn) {
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::SendData() m_conn:%p m_connState:%d begin", m_conn, m_connState);
mg_send_websocket_frame(m_conn, WEBSOCKET_OP_TEXT, data, dataLen);
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::SendData() m_conn:%p m_connState:%d end", m_conn, m_connState);
result = true;
}
}
return result;
}
// 循环
void TransportClient::Loop()
{
//Sleep(1000);
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Loop() m_conn:%p m_connState:%d begin", m_conn, m_connState);
long long preTime = getCurrentTime();
bool isOutTimeConnect = false;
while (DISCONNECT != m_connState) {
mg_mgr_poll(&m_mgr, 100);
// 当websocket连接超过30秒就跳出(防止websocket无限连接,有时在ssl连接一只循环)
if (m_connState == CONNECTING && DiffTime(preTime, getCurrentTime()) > WEBSOCKET_CONNECT_TIMEOUT) {
isOutTimeConnect = true;
break;
}
}
if (!isOutTimeConnect) {
// 如果im是连接中logout,没有走OnDisconnect,现在就走
if (!m_isWebConnected) {
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Loop() m_conn:%p m_connState:%d ", m_conn, m_connState);
// 状态为已连接(返回断开连接)
if (NULL != m_callback) {
m_callback->OnDisconnect();
}
}
} else {
// 连接超时(websocket ssl连不上)
// if (NULL != m_callback) {
// m_callback->OnConnect(false);
// }
// 连接超时(websocket ssl连不上),free websocket的管理器,会直接走到ev_handler 的 MG_EV_CLOSE
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::Loop() OutTimeConnect");
ReleaseMgrProc();
}
Disconnect();
}
// -- mongoose处理函数
void TransportClient::ev_handler(struct mg_connection *nc, int ev, void *ev_data)
{
struct websocket_message *wm = (struct websocket_message *) ev_data;
TransportClient* client = (TransportClient*)nc->user_data;
// FileLog("ImClient", "TransportClient::ev_handler(ev:%d)", ev);
//FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::ev_handler(ev:%d)", ev);
switch (ev) {
case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
// Connected
client->OnConnect(true);
//mg_set_timer(nc, 0);
break;
}
case MG_EV_WEBSOCKET_FRAME: {
// Receive Data
client->OnRecvData(wm->data, wm->size);
break;
}
case MG_EV_CLOSE: {
// Disconnect
client->OnDisconnect();
break;
}
// case MG_EV_TIMER: {
// nc->flags |= MG_F_CLOSE_IMMEDIATELY;
// break;
//}
}
}
void TransportClient::OnConnect(bool success)
{
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::OnConnect(success :%d) start", success);
// 连接成功(修改连接状态)
if (success) {
m_connState = CONNECTED;
m_isWebConnected = true;
// 返回连接成功(若连接失败,则在OnDisconnect统一返回)
if (NULL != m_callback) {
m_callback->OnConnect(true);
}
}
// 连接失败(断开连接)
if (!success) {
Disconnect();
}
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::OnConnect() end");
}
void TransportClient::OnDisconnect()
{
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::OnDisconnect() start");
// 重置连接
m_connStateLock->Lock();
m_conn = NULL;
m_connStateLock->Unlock();
if (CONNECTED == m_connState) {
// 状态为已连接(返回断开连接)
if (NULL != m_callback) {
m_callback->OnDisconnect();
m_isWebConnected = false;
}
}
else if (CONNECTING == m_connState || DISCONNECT == m_connState) {
// 状态为连接中(返回连接失败)
if (NULL != m_callback) {
m_callback->OnConnect(false);
}
}
// 修改状态为断开连接
m_connState = DISCONNECT;
FileLevelLog("ImClient", KLog::LOG_WARNING, "TransportClient::OnDisconnect() end");
}
void TransportClient::OnRecvData(const unsigned char* data, size_t dataLen)
{
// 返回收到的数据
if (NULL != m_callback) {
m_callback->OnRecvData(data, dataLen);
}
}
| true |
0fe491ec22ec6a7559fb03ecd6cb3f5e302cc5d0
|
C++
|
ndsambare/dequeCplusplus
|
/deque_assignment/deque_assignment/deque_assignment.cpp
|
UTF-8
| 507 | 2.578125 | 3 |
[] |
no_license
|
// deque_assignment.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <deque>
#include "my_deque.h"
using namespace std;
int main()
{
//my_deque d = my_deque(init_size);
//for (int i = 0; i < n; i++) {
// d.push_back(i);
//
//}
//for (int i = 0; i < n; i++) {
// int coco = i;
// int noco = d.pop_front();
//}
}
// Jon Shidal: Feel free to use this file to test your program via the command line with tests you create.
| true |
8ca6766f8be8e1f186f3389c9b34672b8d065fba
|
C++
|
zarif98sjs/Competitive-Programming
|
/Spoj/SPOJ LOCKER.cpp
|
UTF-8
| 2,283 | 2.859375 | 3 |
[] |
no_license
|
/**
Idea : Try to make n with numbers such that sum is n and the product is maximum
2 = 2
3 = 3
4 = 2+2 -> 2*2 = 4
5 = 2+3 -> 2*3 = 6
6 = 3+3 -> 3*3 = 9
7 = 3+4 = 3 + 2 + 2 -> 3*2*2 = 12
8 = 3+3+2 -> 3*3*2 = 18
9 = 3+3+3 -> 3*3*3 = 27
Slowly you will see that all the numbers can be made with 2 and 3 . Finding the formula is
pretty much straight-forward.
**/
/**Which of the favors of your Lord will you deny ?**/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define MP make_pair
#define F first
#define S second
#define INF INT_MAX
#define ALL(x) (x).begin(), (x).end()
#define DBG(x) cerr << __LINE__ << " says: " << #x << " = " << (x) << endl
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class TIn>
using indexed_set = tree<
TIn, null_type, less<TIn>,
rb_tree_tag, tree_order_statistics_node_update>;
/*
PBDS
-------------------------------------------------
1) insert(value)
2) erase(value)
3) order_of_key(value) // 0 based indexing
4) *find_by_order(position) // 0 based indexing
*/
inline void optimizeIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
string to_str(LL x)
{
stringstream ss;
ss<<x;
return ss.str();
}
LL po(LL x,LL n) /// x^n
{
LL res = 1;
while(n>0)
{
if(n&1) res = res*x;
x = x*x;
n >>= 1;
}
return res;
}
LL bigMod(LL x,LL n,LL mo) /// x^n % mo
{
x %= mo;
LL res = 1;
while(n>0)
{
if(n&1) res = ((res%mo)*(x%mo)) % mo;
x = ((x%mo)*(x%mo)) %mo;
n >>= 1;
}
return res;
}
/*--------------------------Template Ends-------------------------------------*/
const int nmax = 2e5+7;
const LL LINF = 1e17;
//const LL MOD = 1e9+7;
int main()
{
optimizeIO();
int tc;
cin>>tc;
while(tc--)
{
LL n;
cin>>n;
LL ans;
LL val = n/3;
if(n%3==0) ans = bigMod(3,val,MOD);
else if(n%3==1) ans = (bigMod(3,val - 1,MOD) * bigMod(2,2,MOD))%MOD;
else if(n%3==2) ans = (bigMod(3,val,MOD) * bigMod(2,1,MOD))%MOD;
if(n==1) ans = 1;
cout<<ans%MOD<<endl;
}
return 0;
}
| true |
569c356ab8280443f2319816594869bc11983bc7
|
C++
|
godls1650/ByteC
|
/구직자_오후/CPP/03.Friend/Point.h
|
UHC
| 1,207 | 3.40625 | 3 |
[] |
no_license
|
#pragma once
#include <ostream>
#include <istream>
class Point{
friend std::ostream& operator<<(std::ostream& os ,const Point & target);
friend std::istream& operator>>(std::istream& in, Point& target);
private:
int X;
int Y;
public :
Point(int x = 0, int y = 0);
Point(const Point& ref);
void showPoint();
//
/*
A + B
--Լ
TYPE(A) add(A,B)
-- Ҽ
A.add(B)
C++ :
Լ Ī
operator[ȣ]
: operator+
E : operator-
: operator+=
: operator=
ε Ұ
? : / ::
*****
⺻ ǹ̿ ũ ʰ ۼѴ.
*/
Point operator+(const Point& ref);
Point operator-(const Point& ref);
Point operator-();
bool operator<(const Point& ref);
bool operator>(const Point& ref);
bool operator==(const Point& ref);
bool operator<=(const Point& ref);
bool operator>=(const Point& ref);
bool operator!=(const Point& ref);
Point operator++();
Point operator++(int x);
Point operator--();
Point operator--(int x);
};
| true |
1392f45f250919d6e0c2382a269d9918a3c8f232
|
C++
|
Heatclif/C-
|
/football.cpp
|
UTF-8
| 4,134 | 2.859375 | 3 |
[] |
no_license
|
/*
THIS PROGRAM IS DEVELOPED BY VIVEK BISWAS OF CLASS 11-A 2015-2016.
NO HAS THE RIGHT TO COPY THIS TO ANOTHER PROGRAM OR COMPUTER.
THIS IS A COPYRIGHT PROGRAM COPYING THIS IS A PUNISHABLE OFFENCE.
PRATCING SO MIGHT LEAD TO THE DOER LIFETIME IMPRISONMENT IN CELLULAR
JAIL IN ANDAMAN.
*/
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
using namespace std;
void match();
void goal();
void extra();
int main()
{
int our,opp,z,y;
char team[40];
cout<<"\n\nTHIS PROGRAM IS DEVELOPED BY VIVEK BISWAS OF CLASS 11-A 2015-2016."
<<"\nNO ONE HAS THE RIGHT TO COPY THIS TO ANOTHER PROGRAM OR COMPUTER."
<<"\nTHIS IS A PROGRAM FOR PERSONAL FUN. COPYING THIS IS A PUNISHABLE OFFENCE."
<<"\nPRATCING SO MIGHT LEAD TO THE DOER LIFETIME IMPRISONMENT IN CELLULAR"
<<"\nJAIL IN ANDAMAN.";
cout<<"\n\n\n\n\n\n\n\nPress 1 to continue :";
cin>>y;
cout<<"\T\TFOOTBALL MATCH";
cout<<"\n\n\nEnter Your Team Name (IN UPPER CASE):";
cin.getline(team,40);
//clrscr();
cout<<" FOOTBALL FEDRATION";
cout<<"\n\nON 23 DECEMBER 1990, THE FOOTBALL TEAM "<<team<<" HAD ITS FINAL MATCH WITH "<<"\nFC MADRID... "<<"\n\nTHE MOST STRONGEST TEAM OF LIGA BBVA !!!!!!!";
cout<<"\n\nEVERYONE GAVE THEIR FULL POTENTIAL TO WIN THE MATCH...."<<"\n\nBUT THE MATCH SCORE ENDED WITH 2:2"<<"\n\nTHE GAME WAS TO BE DECIDED WITH PENALTIES!!!!!";
cout<<"\n\nEnter 1 to continue...";
cin>>z;
goal();
match();
}
void match()
{ int a;
int i,shoot,block,block1,shoot1,us=0,opp=0;
cout<<"\n\n\nThis is the GOAL POST.......";
cout<<"\n\nBOTH THE TEAMS HAVE 5 CHANCES TO SHOOT..."<<"\nTHE MAXIMUM SCORER WILL WIN LIGA BBVA..... ";
cout<<"\n\nCLICK ON THE RESPECTIVE NUMBERS TO SHOOT........";
for(i=1;i<=5;i++)
{ cout<<"\n\nITS YOUR TURN TO SHOOT...";
cout<<"\n\nENTER THE NUMBER TO SHOOT :";
cin>>shoot;
if(shoot>6)
{ //clrscr;
cout<<"\n\nTHE BALL WENT WIDE.......";
cout<<"\nThe score is "<<us<<":"<<opp;
}
else
{ block=rand()%6+0;
//clrscr();
goal();
if(block==shoot||block==shoot-1)
{ cout<<"\n\nITS A BLOCK !!!!!!!!!!";
cout<<"\nThe score is "<<us<<":"<<opp;
}
else
{ cout<<"\n\nITS A GOAL !!!!!!!!!!";
us++;
cout<<"\nThe score is "<<us<<":"<<opp;
}
}
cout<<"\n\nITS FC MADRID'S TURN TO SHOOT";
cout<<"\n\nNOW PRESS NUMBER TO BLOCK :";
cin>>block1;
shoot1=rand()%6+0;
//clrscr();
goal();
if(block1==shoot1||block1==shoot1-1)
{ cout<<"\n\nOH! A CLEAN SAVE BY CASSILAS .....";
cout<<"\nThe score is "<<us<<":"<<opp;
}
else
{ cout<<"\n\nITS A CLEAN GOAL.......";
opp++;
cout<<"\nThe score is "<<us<<":"<<opp;
}
}
cout<<"\n\nTHE GAME IS OVER....";
if(us>opp)
{ cout<<"\n\nTHE SCORE IS "<<us<<":"<<opp;
cout<<"\n\nYOU WON THE LEAGUE......"<<"\nCONGRULATIONS !!!!!!!!!!!";
}
else if(us<opp)
{ cout<<"\n\nTHE SCORE IS "<<us<<":"<<opp;
cout<<"\n\nYOU LOOSE THE LEAGUE......"<<"\nBETTER LUCK NEXT YEAR !!!!!!!!!!!";
}
else
{
extra();
}
}
void goal()
{
cout<<" \n\n #########################################################|| ";
cout<<" \n #.......................................................# || ";
cout<<" \n||######################################################|| #|| ";
cout<<" \n||..................|.....................|.............|| #|| ";
cout<<" \n||........ 5 .......|......... 3 .........|...... 1 ....|| #|| ";
cout<<" \n||..................|.....................|.............|| #|| ";
cout<<" \n||------------------|---------------------|-------------|| #|| ";
cout<<" \n||------------------|---------------------|-------------|| #|| ";
cout<<" \n||..................|.....................|.............|| #|| ";
cout<<" \n||....... 6 ........|......... 4 .........|....... 2 ...|| #|| ";
cout<<" \n||..................|.....................|.............|| ## ";
cout<<" \n||..................|.....................|.............|| # ";
}
void extra()
{
cout<<"\nTHE SCORE AFTER 5 PENALTIES ARE SAME ..... ";
cout<<"\n\nNOW YOU HAVE TO USE YOUR FOOT SOME MORE ...... : ";
match();
}
| true |
9a468ea674fd523ec5a4021f71d431ca40227194
|
C++
|
Autonomous-Wang/Leetcode
|
/randomnumber.cpp
|
UTF-8
| 264 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#include <random>
using namespace std;
int main()
{
default_random_engine generator;
uniform_int_distribution<int> distribution(1,6);
int dice = bind(distribution, generator);
int wisdom = dice()+dice()+dice();
cout << wisdom << endl;
}
| true |
02997d163f8c22afb51d109a2e21352a19befaf2
|
C++
|
Pafaul/SD
|
/LA.cpp
|
UTF-8
| 7,566 | 3.15625 | 3 |
[] |
no_license
|
#include "LA.h"
#include <cstring>
#include <math.h>
TVector::TVector() : n(0), data(nullptr) {}
TVector::TVector(int n) : n(0), data(nullptr)
{
resize(n);
}
TVector::TVector(const TVector& rval) : n(0), data(nullptr)
{
*this = rval;
}
TVector& TVector::operator = (const TVector& rval)
{
if (n != rval.n)
{
if (data)
{
delete[] data;
}
data = new long double[rval.n];
n = rval.n;
}
memcpy(data, rval.data, sizeof(long double)*n);
return (*this);
}
TVector::~TVector()
{
if(data)
{
delete[] data;
n = 0;
data = nullptr;
}
}
void TVector::resize(int n)
{
if (n == this->n)
return;
long double *newData = new long double[n];
if (data)
{
int min_n = (this->n < n) ? this->n : n;
memcpy(newData, data, sizeof(long double)*min_n);
delete[] data;
}
data = newData;
this->n = n;
}
long double TVector::length() const
{
long double l = 0;
for (int i = 0; i < n; i ++)
l += data[i]*data[i];
return sqrt(l);
}
TVector TVector::operator - () const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = - data[i];
return V;
}
TVector TVector::operator - (const long double rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = data[i] - rval;
return V;
}
TVector TVector::operator - (const TVector& rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = data[i] - rval[i];
return V;
}
TVector TVector::operator + (const long double rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = data[i] + rval;
return V;
}
TVector TVector::operator + (const TVector& rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = data[i] + rval[i];
return V;
}
TVector TVector::operator ^ (const TVector& rval) const
{
TVector V(3);
V[0] = data[1]*rval[2] - rval[1]*data[2];
V[1] = data[2]*rval[0] - rval[2]*data[0];
V[2] = data[0]*rval[1] - rval[0]*data[1];
return V;
}
long double TVector::operator * (const TVector& rval) const
{
long double res = 0.0;
for (int i = 0; i < n; i++)
res += data[i]*rval[i];
return res;
}
TVector TVector::operator * (const long double rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
V[i] = data[i]*rval;
return V;
}
TMatrix::TMatrix() : n(0), m(0), data(nullptr) {}
TMatrix::TMatrix(int n, int m) : n(n), m(m)
{
resize(n, m);
}
TMatrix::TMatrix(const TMatrix& rval)
{
(*this) = rval;
}
TMatrix& TMatrix::operator =(const TMatrix& rval)
{
if (this != &rval)
{
this->~TMatrix();
resize(rval.n, rval.m);
for (int i = 0; i < n; i++)
memcpy(data[i], rval.data[i], sizeof(long double)*m);
}
return (*this);
}
TMatrix::~TMatrix()
{
if (data)
{
for (int i = 0; i < m; i++)
delete[] data[i];
delete[] data;
data = nullptr;
n = m = 0;
}
}
void TMatrix::resize(int n, int m)
{
/*int min_n = (this->n < n) ? this->n : n;
if(this->m != m)
{
int min_m = (this->m < m) ? this->m : m;
for (int i = 0; i < min_n; i++)
{
long double * newDataRow = new long double [m];
memcpy(newDataRow, data[i], sizeof(long double)*min_m);
delete[] data[i];
data[i] = newDataRow;
}
this->m = m;
}
if (this->n != n)
{
long double **newData = new long double*[n];
memcpy(newData, data, sizeof(long double*)*min_n);
for (int i = n; i < this->n; i++)
newData[i] = new long double[m];
data = newData;
this->n = n;
}*/
int min_n = this->n < n ? this->n : n;
if (this->m != m)
{
int min_m = this->m < m ? this->m : m;
for (int i = 0; i < min_n; i++)
{
long double *newDataRow = new long double[ m ];
memcpy(newDataRow, data[i], sizeof(long double)*min_m);
delete[] data[i];
data[i] = newDataRow;
}
this->m = m;
}
if (this->n != n)
{
long double **newData = new long double*[ n ];
memcpy(newData, data, sizeof(long double*)*min_n);
for (int i = n; i < this->n; i++)
delete[] data[i];
if (data)
delete[] data;
for (int i = this->n; i < n; i++)
newData[i] = new long double[ m ];
data = newData;
this->n = n;
}
}
TMatrix TMatrix::operator - () const
{
TMatrix M(n, m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
M(i, j) = -data[i][j];
return M;
}
TMatrix TMatrix::operator - (const TMatrix& rval) const
{
TMatrix M(n, m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
M(i, j) = data[i][j] - rval(i,j);
return M;
}
TMatrix TMatrix::operator + (const TMatrix& rval) const
{
TMatrix M(n, m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
M(i, j) = data[i][j] + rval(i, j);
return M;
}
TMatrix TMatrix::operator * (const long double rval) const
{
TMatrix M(n, m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
M(i, j) = data[n][m] * rval;
return M;
}
TMatrix TMatrix::operator * (const TMatrix& rval) const
{
TMatrix M(n, rval.m);
for (int i = 0; i < M.n; i++)
for (int j = 0; j < M.m; j++)
{
M(i, j) = 0;
for (int k = 0; k < m; k++)
M(i,j) += data[i][k] * rval(k, j);
}
return M;
}
TVector TMatrix::operator * (const TVector& rval) const
{
TVector V(n);
for (int i = 0; i < n; i++)
{
V[i] = 0;
for (int j = 0; j < m; j++)
V[i] += data[i][j] * rval[j];
}
return V;
}
TMatrix TMatrix::t () const
{
TMatrix M(m, n);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
M(i,j) = data[j][i];
return M;
}
TMatrix TMatrix::E(int n)
{
TMatrix E (n, n);
for (int i = 0; i < n; i++)
E(i, i) = 1;
return E;
}
TMatrix TMatrix::operator ! () const
{
TMatrix X( E(n) ),
A(*this);
long double tmp;
for (int i = 0; i < n; i++)
{
if (A(i,i) == 0)
{
for (int k = i+1; k < n; k++)
if (A(k,i) != 0)
{
A.swapRows(i, k);
X.swapRows(i, k);
break;
}
}
for (int j = 0; j < n; j++)
{
A(i, j) /= tmp;
X(i, j) /= tmp;
}
for (int k = 0; k < n; k++)
if (k != i)
{
tmp = A(k, i);
for (int j = 0; j < n; j++)
{
A(k, j) -= A(i, j) * tmp;
X(k, j) -= X(i, j) * tmp;
}
}
}
return X;
}
/* Function swap rows */
TMatrix& TMatrix::swapRows(int i, int j)
{
long double buf;
for (int k = 0; k < m; k++)
{
buf = data[i][k];
data[i][k] = data[j][k];
data[j][k] = buf;
}
return *this;
}
| true |
492367c6b1c56261595c96ae50da126886ce4620
|
C++
|
AntonyMoes/tp-algo
|
/ДЗ3/task1/CArcGraph.h
|
UTF-8
| 587 | 2.6875 | 3 |
[] |
no_license
|
//
// Created by antonymo on 21.12.18.
//
#ifndef TASK1_CARCGRAPH_H_
#define TASK1_CARCGRAPH_H_
#include <cstddef>
#include "IGraph.h"
class CArcGraph : public IGraph{
public:
explicit CArcGraph(IGraph* graph);
explicit CArcGraph(size_t size);
void AddEdge(int from, int to) override;
int VerticesCount() const override;
std::vector<int> GetNextVertices(int vertex) const override;
std::vector<int> GetPrevVertices(int vertex) const override;
private:
std::vector<std::pair<int, int>> edges;
const size_t size;
};
#endif // TASK1_CARCGRAPH_H_
| true |
193028eb92bd1f1b43b8628f25c304ac1534a597
|
C++
|
karanpratap/CNS_LAB
|
/Labset_6/program.cpp
|
UTF-8
| 1,664 | 3.078125 | 3 |
[] |
no_license
|
//Author: karanpratap
//Program: 48-bit input generation for S-box
#include<bits/stdc++.h>
#include "../headers/conversions.h"
using namespace std;
//global initializations
// Expansion Table (E)
int expansionTable[8][6]={{32,1,2,3,4,5},{4,5,6,7,8,9},{8,9,10,11,12,13},{12,13,14,15,16,17},{16,17,18,19,20,21},{20,21,22,23,24,25},{24,25,26,27,28,29},{28,29,30,31,32,1}};
void functionE(char R[33], char intermediate[49]){
for(int i=0;i<8;i++)
for(int j=0;j<6;j++)
intermediate[i*6+j]=R[expansionTable[i][j]-1];
intermediate[48]='\0';
}
//Function to xor 2 arguements and store result in arg1
void xor48(char arg1[49], char arg2[49]){
for(int i=0;i<48;i++)
arg1[i]=(arg1[i]==arg2[i])?48:49;
//arg1[48]='\0';
}
int main(){
int roundNum, roundNumBup, pointer=0;
char ch, inputHex[17], inputBin[65], R[33], intermediate[49], subkey[49];
cout<<"Enter the round number:";
cin>>roundNum;
ifstream keysFile;
keysFile.open("keys.txt",ios::in);
keysFile.seekg((roundNum==1)?(roundNum-1)*48:(roundNum-1)*48+1,keysFile.beg);
cout<<"Round No:"<<roundNum<<endl;
for(int i=0;i<48;i++){
keysFile>>ch;
subkey[pointer++]=ch;
}
subkey[48]='\0';
keysFile.close();
cout<<"Subkey for Round Number "<<roundNum<<":"<<subkey<<endl;
cout<<"Enter the 64 bit Input in hexadecimal:";
cin>>inputHex;
hexToBinary(inputHex, inputBin);
//extracting right hand side 32 bits of input
for(int i=0;i<32;i++)
R[i]=inputBin[i+32];
R[32]='\0';
functionE(R, intermediate);
cout<<"The calculated Expansion table output is:"<<intermediate<<endl;
xor48(intermediate,subkey);
cout<<"Calculated input for the S-boxes for round : "<<intermediate<<endl;
return 0;
}
| true |
c14c6d4a89a5db92104e29f71f3c8844db770905
|
C++
|
vxl/vxl
|
/contrib/brl/bseg/bstm_multi/space_time_scene.h
|
UTF-8
| 8,288 | 2.53125 | 3 |
[] |
no_license
|
#ifndef bstm_multi_space_time_scene_h_
#define bstm_multi_space_time_scene_h_
//: \file space_time_scene.h
//
// \brief space_time_scene is a scene that represents a 3D
// volume of space over time. It contains a 4D grid of blocks that
// each model a region of that space. The scene data structure is
// templated over block type, and different types of blocks may use
// different implementations for representing the space itself, such
// as space-time trees (e.g. BSTM) or something else.
//
// This is closely based off of bstm/bstm_scene.h. Really the only
// difference is the substitution of template parameters where
// necessary, and that the implementation does not make use of
// bstm_block_metadata's internal members (i.e. only calls functions
// such as bbox()).
//
// \author Raphael Kargon
//
// \date 26 Jul 2017
//
#include <iostream>
#include <iosfwd>
#ifdef _MSC_VER
# include <vcl_msvc_warnings.h>
#endif
#include <vgl/vgl_box_2d.h>
#include <vgl/vgl_box_3d.h>
#include <vgl/vgl_point_3d.h>
#include <vpgl/vpgl_lvcs.h>
#include <vul/vul_file.h>
// smart pointer stuff
#include <vbl/vbl_ref_count.h>
#include <vbl/vbl_smart_ptr.h>
// vpgl camera
#include <vpgl/vpgl_generic_camera.h>
#include <vpgl/vpgl_perspective_camera.h>
#include <bstm/basic/bstm_block_id.h>
#include <bstm_multi/space_time_scene_parser.hxx>
//: space_time_scene: simple scene model that maintains (in world coordinates)
// - scene origin
// - number of blocks in each dimension
// - size of each block in each dimension
// - lvcs information
// - xml path on disk and data path (directory) on disk
// NOTE: This uses bstm_block_id as a generic ID for 4D blocks. The block type
// itself must implement:
// - Block::metadata - type alias for corresponding metadata type
// - Block::metadata must contain:
// - a method vgl_box_3d<double> bbox()
// - a method 'void to_xml(vsl_basic_xml_element&) const' that fills a
// <block></block> XML tag with the metadata as attributes.
// - a static method 'Block::metadata from_xml(const char **atts)' that
// creates a metadata object from a given XML <block></block> tag.
template <typename Block> class space_time_scene : public vbl_ref_count {
public:
typedef typename Block::metadata_t block_metadata;
typedef space_time_scene_parser<Block> scene_parser;
typedef vbl_smart_ptr<space_time_scene<Block> > sptr;
//: empty scene, needs to be initialized manually
space_time_scene() = default;
space_time_scene(std::string data_path,
vgl_point_3d<double> const &origin,
int version = 2);
//: initializes scene from xmlFile
space_time_scene(std::string filename);
//: destructor
~space_time_scene() override = default;
//: save scene xml file
void save_scene();
//: return a vector of block ids in visibility order
std::vector<bstm_block_id> get_vis_blocks(vpgl_generic_camera<double> *cam);
std::vector<bstm_block_id>
get_vis_blocks(vpgl_perspective_camera<double> *cam);
std::vector<bstm_block_id> get_vis_blocks(vpgl_camera_double_sptr &cam) {
if (cam->type_name() == "vpgl_generic_camera")
return this->get_vis_blocks((vpgl_generic_camera<double> *)cam.ptr());
else if (cam->type_name() == "vpgl_perspective_camera")
return this->get_vis_blocks((vpgl_perspective_camera<double> *)cam.ptr());
else
std::cout
<< "space_time_scene::get_vis_blocks doesn't support camera type "
<< cam->type_name() << std::endl;
// else return empty
std::vector<bstm_block_id> empty;
return empty;
}
//: visibility order from point, blocks must intersect with cam box
std::vector<bstm_block_id>
get_vis_order_from_pt(vgl_point_3d<double> const &pt,
vgl_box_2d<double> camBox = vgl_box_2d<double>());
bool block_exists(bstm_block_id id) const {
return blocks_.find(id) != blocks_.end();
}
bool block_on_disk(bstm_block_id id) const {
return vul_file::exists(data_path_ + id.to_string() + ".bin");
}
bool data_on_disk(bstm_block_id id, std::string data_type) {
return vul_file::exists(data_path_ + data_type + "_" + id.to_string() +
".bin");
}
//: a list of block metadata...
std::map<bstm_block_id, block_metadata> &blocks() { return blocks_; }
const std::map<bstm_block_id, block_metadata> &blocks() const {
return blocks_;
}
unsigned num_blocks() const { return (unsigned)blocks_.size(); }
//: returns a copy of the metadata of the given block ID.
block_metadata get_block_metadata(const bstm_block_id &id) const;
std::vector<bstm_block_id> get_block_ids() const;
//: returns the block ids of blocks that intersect the given bounding box at
// given time, as well as the local time
std::vector<bstm_block_id> get_block_ids(vgl_box_3d<double> bb,
float time) const;
//: gets a tight bounding box for the scene
vgl_box_3d<double> bounding_box() const;
//: gets a tight bounding box for the scene
vgl_box_3d<int> bounding_box_blk_ids() const;
//: gets tight time bounds for the scene
void bounding_box_t(double &min_t, double &max_t) const;
//: gets a tight time bounds of the block ids
void blocks_ids_bounding_box_t(unsigned &min_block_id,
unsigned &max_block_id) const;
// returns the dimesnsion of the scene grid where each grid element is a block
vgl_vector_3d<unsigned int> scene_dimensions() const;
//: If a block contains a 3-d point, set the block id, else return false. The
// local coordinates of the point are also returned
bool contains(vgl_point_3d<double> const &p,
bstm_block_id &bid,
vgl_point_3d<double> &local_coords,
double const t,
double &local_time) const;
//: returns the local time if t is contained in scene
bool local_time(double const t, double &local_time) const;
//: scene dimensions accessors
vgl_point_3d<double> local_origin() const { return local_origin_; }
vgl_point_3d<double> rpc_origin() const { return rpc_origin_; }
vpgl_lvcs lvcs() const { return lvcs_; }
//: scene path accessors
std::string xml_path() const { return xml_path_; }
std::string data_path() const { return data_path_; }
//: appearance model accessor
std::vector<std::string> appearances() const { return appearances_; }
bool has_data_type(const std::string &data_type) const;
//: scene version number
int version() const { return version_; }
void set_version(int v) { version_ = v; }
//: scene mutators
void set_local_origin(vgl_point_3d<double> org) { local_origin_ = org; }
void set_rpc_origin(vgl_point_3d<double> rpc) { rpc_origin_ = rpc; }
void set_lvcs(vpgl_lvcs lvcs) { lvcs_ = lvcs; }
void set_blocks(const std::map<bstm_block_id, block_metadata> &blocks) {
blocks_ = blocks;
}
void set_appearances(const std::vector<std::string> &appearances) {
appearances_ = appearances;
}
//: scene path mutators
void set_xml_path(std::string path) { xml_path_ = path; }
void set_data_path(std::string path) { data_path_ = path + "/"; }
private:
//: world scene information
vpgl_lvcs lvcs_;
vgl_point_3d<double> local_origin_;
vgl_point_3d<double> rpc_origin_;
//: location on disk of xml file and data/block files
std::string data_path_, xml_path_;
//: list of block meta data available to this scene
std::map<bstm_block_id, block_metadata> blocks_;
//: list of appearance models/observation models used by this scene
std::vector<std::string> appearances_;
int version_;
};
//: utility class for sorting id's by their distance
class space_time_dist_id_pair {
public:
space_time_dist_id_pair(double dist, bstm_block_id id)
: dist_(dist), id_(id) {}
double dist_;
bstm_block_id id_;
inline bool operator<(space_time_dist_id_pair const &v) const {
return dist_ < v.dist_;
}
};
//: scene output stream operator
template <typename Block>
std::ostream &operator<<(std::ostream &s, space_time_scene<Block> &scene);
//: scene xml write function
template <typename Block>
void x_write(std::ostream &os, space_time_scene<Block> &scene, std::string name);
#endif // bstm_multi_space_time_scene_h_
| true |
e4a8bd6db26692121089850aae645560abbbe6f1
|
C++
|
sureshyhap/Schaums-Outlines-Programming-with-C-plus-plus
|
/Chapter 13/Problems/6/6.cpp
|
UTF-8
| 2,908 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
template<typename T>
class Vector {
public:
Vector(int c = 100) : capacity(c), present_size(0) {data = new T[capacity];}
Vector(T* a) : present_size(sizeof(a)), capacity(present_size) {
data = new T[present_size];
for (int i = 0; i < present_size; ++i) {
data[i] = a[i];
}
}
Vector(const Vector& v) : capacity(v.capacity), present_size(v.present_size) {
data = new T[capacity];
for (int i = 0; i < present_size; ++i) {
data[i] = v.data[i];
}
}
~Vector() {delete [] data;}
Vector& operator=(const Vector& v) {
capacity = v.capacity;
present_size = v.present_size;
delete [] data;
data = new T[capacity];
for (int i = 0; i < present_size; ++i) {
data[i] = v.data[i];
}
}
T& operator[](int index);
void change_cap(int new_cap);
void insert(const T& element); ////////?
// T& element will hold the deleted element
void delete_(T& element);
void print_vec() const;
protected:
T* data;
int capacity, present_size;
private:
};
template<typename T>
T& Vector<T>::operator[](int index) {
return data[index];
}
template<typename T>
void Vector<T>::change_cap(int new_cap) {
// Place holder for the data
T temp[present_size];
for (int i = 0; i < present_size; ++i) {
temp[i] = data[i];
}
delete [] data;
data = new T[new_cap];
present_size = (new_cap > present_size ? present_size: new_cap);
capacity = new_cap;
for (int i = 0; i < present_size; ++i) {
data[i] = temp[i];
}
}
template<typename T>
void Vector<T>::insert(const T& element) {
if (present_size < capacity) {
data[present_size++] = element;
}
else {
return;
}
}
template<typename T>
void Vector<T>::delete_(T& element) {
if (present_size > 0) {
element = data[--present_size];
}
else {
return;
}
}
template<typename T>
void Vector<T>::print_vec() const {
for (int i = 0; i < present_size; ++i) {
std::cout << data[i] << " ";
}
}
////////////////////////////////////////////
enum Index {
FIRST, SECOND, THIRD, FOURTH, FIFTH, SIXTH, SEVENTH, EIGHTH, NINTH, TENTH
};
template<typename T, typename E>
class Array : public Vector<T> {
public:
T& operator[](E I) {
return this->data[I];
}
protected:
private:
};
int main(int argc, char* argv[]) {
Vector<int> v(3);
v.insert(34);
v.insert(4);
v.insert(7);
/*
v.print_vec();
std::cout << std::endl;
v.insert(10);
v.print_vec();
std::cout << std::endl;
int n = 0;
v.delete_(n);
std::cout << n << std::endl;
v.print_vec();
std::cout << std::endl;
v.change_cap(5);
v.print_vec();
std::cout << std::endl;
v.change_cap(1);
v.print_vec();
std::cout << std::endl;
*/
/*
int a[] = {5, 3, 7, 3, 9, 8, 7, 9};
Vector<int> v2(a);
v2.print_vec();
*/
Array<int, Index> a;
a.insert(34);
a.insert(4);
a.insert(7);
std::cout << a[FIRST];
return 0;
}
| true |
05ed8d4d5e10eab522e5a55139c92a56963cf819
|
C++
|
JoeGeC/GamesEngineConstruction
|
/HAPI_Start/Rectangle.h
|
UTF-8
| 469 | 3.4375 | 3 |
[] |
no_license
|
#pragma once
class Rectangle
{
public:
Rectangle();
~Rectangle();
int m_left, m_right, m_top, m_bottom;
Rectangle(int l, int r, int t, int b) : m_left(l), m_right(r), m_top(t), m_bottom(b) {};
Rectangle(int w, int h) : m_left(0), m_right(w), m_top(0), m_bottom(h) {};
int Width() const { return m_right - m_left; }
int Height() const { return m_bottom - m_top; }
void ClipTo(const Rectangle &other);
void Translate(int dx, int dy);
void ShrinkRect();
};
| true |
4b26ca5d8b908b869477fefa11e08a70a3e2f101
|
C++
|
godofthunder8756/CCOS-2.0
|
/CCOS/Memory.cpp
|
UTF-8
| 1,386 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
#include "Memory.h"
void memset(void* start, uint_64 value, uint_64 num) {
if (num <= 8) {
uint_8* valPtr = (uint_8*)&value;
for (uint_8* ptr = (uint_8*)start; ptr < (uint_8*)((uint_64)start + num); ptr++) {
*ptr = *valPtr;
valPtr++;
}
return;
}
uint_64 proceedingBytes = num % 8;
uint_64 newnum = num - proceedingBytes;
for (uint_64* ptr = (uint_64*)start; ptr < (uint_64*)((uint_64)start + newnum); ptr++) {
*ptr = value;
}
uint_8* valPtr = (uint_8*)&value;
for (uint_8* ptr = (uint_8*)((uint_64)start + newnum); ptr < (uint_8*)((uint_64)start + num); ptr++) {
*ptr = *valPtr;
valPtr++;
}
}
void memcpy(void* destination, void* source, uint_64 num) {
if (num <= 8) {
uint_8* valPtr = (uint_8*)source;
for (uint_8* ptr = (uint_8*)destination; ptr < (uint_8*)((uint_64)destination + num); ptr++) {
*ptr = *valPtr;
valPtr++;
}
return;
}
uint_64 proceedingBytes = num % 8;
uint_64 newnum = num - proceedingBytes;
uint_64* srcptr = (uint_64*)source;
for (uint_64* destptr = (uint_64*)destination; destptr < (uint_64*)((uint_64)destination + newnum); destptr++) {
*destptr = *srcptr;
srcptr++;
}
uint_8* srcptr8 = (uint_8*)((uint_64)source + newnum);
for (uint_8* destptr8 = (uint_8*)((uint_64)destination + newnum); destptr8 < (uint_8*)((uint_64)destination + num); destptr8++)
{
*destptr8 = *srcptr8;
srcptr8++;
}
}
| true |
e66e4297908c77aa74c3c50aef5caa12c4e5ec00
|
C++
|
AlexShten/Phone
|
/OurPhone/PhonList.cpp
|
WINDOWS-1252
| 28,715 | 2.515625 | 3 |
[] |
no_license
|
#include "stdafx.h"
using namespace std;
PhonList::PhonList()
{
Head = nullptr;
Tail = nullptr;
count = 0;
onceEnter = 0;
myOperator = " ";
}
PhonList::~PhonList()
{
delete[] Head;
delete[] Tail;
}
void PhonList::ShowPB()
{
}
void PhonList::FacePaint()
{
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t ";
cout << "\n\t\t\t";
}
void PhonList::ShowColorList(int pos, bool isCall)
{
int i = 1;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (count != 0)
{
Node *tmp = Head;
while (tmp != nullptr)
{
if (i == pos)
SetConsoleTextAttribute(hStdOut, (WORD)((14) | 14));
else
SetConsoleTextAttribute(hStdOut, (WORD)((7) | 7));
cout << "\t\t\t" << tmp->_name;
for (int i = 0; i < (20 - tmp->_name.length()); i++)
cout << " ";
cout << "|";
if (isCall && i == pos)
{
SetConsoleTextAttribute(hStdOut, (WORD)((10) | 10));
cout << " CALL ";
SetConsoleTextAttribute(hStdOut, (WORD)((14) | 14));
}
else
cout << " CALL ";
cout << "|\n" << endl;
i++;
tmp = tmp->next;
}
}
}
void PhonList::SetYellowTextColor(string str)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((14) | 14));
cout << str;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
}
void PhonList::ColorPrint(int pos){
cout << "\n\n\t\tUse \"Left\", \"Right\", \"Up\", \"Down\"";
cout << "\n\t\tand \"Enter\" keys arrow for nawigation ";
cout << "\n\t\tpress \"Space\" for call ";
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (pos == -1)
{
cout << "\n\t\t\t____________________________\n\n";
SetYellowTextColor("\t\t\t\t Find");
cout << "\n\t\t\t____________________________\n";
cout << "\t\t\t____________________________\n\n";
cout << "\t\t\t Add new contact";
cout << "\n\t\t\t____________________________\n\n";
}
else if (pos == 0)
{
cout << "\n\t\t\t____________________________\n\n";
cout << "\t\t\t\t Find";
cout << "\n\t\t\t____________________________\n";
cout << "\t\t\t____________________________\n\n";
SetYellowTextColor("\t\t\t Add new contact");
cout << "\n\t\t\t____________________________\n\n";
}
else if (pos > 0 || pos < -1)
{
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
cout << "\n\t\t\t____________________________\n\n";
cout << "\t\t\t\t Find";
cout << "\n\t\t\t____________________________\n";
cout << "\t\t\t____________________________\n\n";
cout << "\t\t\t Add new contact";
cout << "\n\t\t\t____________________________\n\n";
}
}
bool PhonList::Call(int pos)
{
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
system("cls");
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
cout << "\n\t\t\t " << tmpNode->_phoneNumber << endl;
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
FacePaint();
SetConsoleTextAttribute(hStdOut, (WORD)((12) | 12));
cout << "\n\t\t\t____________________________\n\n";
cout << "\t\t\t Finish";
cout << "\n\t\t\t____________________________\n";
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
int act = _getch();
return true;
}
bool PhonList::CallNewNumber(string numb)
{
system("cls");
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\n\t\t\t " << "No name...";
cout << "\n\t\t\t " << numb << endl;
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
FacePaint();
SetConsoleTextAttribute(hStdOut, (WORD)((12) | 12));
cout << "\n\t\t\t____________________________\n\n";
cout << "\t\t\t Finish";
cout << "\n\t\t\t____________________________\n";
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
int act = _getch();
return true;
}
int PhonList::Message(int pos, string &sms)
{
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((2) | 2));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\t\t\t Message:\n";
cout << "\n\t\t\t ";
getline(cin, sms);
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
int act = _getch();
return act;
}
void PhonList::PB_Start(string op)
{
myOperator = op;
int pos = -2;
int action=0;
if (onceEnter == 0)
{
ReadFromFile("phonList.txt");
onceEnter = 1;
}
SortByName();
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bool isCall = false;
do
{
system("cls");
ColorPrint(pos);
ShowColorList(pos, isCall);
BackButton(pos);
action = _getch();
switch (action)
{
case 80: pos++;
system("cls");
ColorPrint(pos);
if (pos >= count+2)
{
pos = -2;
}
isCall = false;
ShowColorList(pos, isCall);
BackButton(pos);
//isCall = false;
break;
case 72:pos--;
system("cls");
ColorPrint(pos);
if (pos < -2)
{
pos = count+1;
}
isCall = false;
ShowColorList(pos, isCall);
BackButton(pos);
break;
case 32:
if (pos >= 1 && pos <= count)
{
isCall = true;
ShowColorList(pos, isCall);
}
break;
case 13:
if (pos == count + 1)
{
action = 27;
break;
}
if (pos==-1)
{
bool isOk = true;
system("cls");
cout << "\n\n\t\t\t Enter name: ";
string name;
getline(cin, name);
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Find ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
int act = 0;
act = _getch();
while (act != 13)
{
switch (act)
{
case 77: system("cls");
cout << "\n\n\t\t\t Enter name: " << name;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t| Find | |";
SetYellowTextColor(" Cancel ");
cout << "|";
cout << "\n\t\t\t ________ _________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
cout << "\n\n\t\t\t Enter name: " << name;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Find ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
pos = FindByName(name);
if (pos == -3)
{
system("cls");
cout << "\n\n\t\t\tContact not found." << endl;
cout << "\n\n\t\t\t ____________\n\n";
cout << "\t\t\t |";
SetYellowTextColor(" Back ");
cout << "|";
cout << "\n\t\t\t ____________\n";
int act = 0;
act = _getch();
if (act == 13)
{
pos = -1;
break;
}
}
else
{
ColorPrint(pos);
isCall = false;
ShowColorList(pos, isCall);
}
break;
}
else if (act == 13 && isOk == false)
{
pos = -1;
break;
}
}
if (pos == 0)
{
int act = 0;
bool isOk = true;
string tmpName, tmpPhon;
int ID;
system("cls");
cout << "\n\n\t\t\t Name: ";
getline(cin, tmpName);
cout << "\n\n\t\t\t Phon Number: ";
getline(cin, tmpPhon);
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
act = _getch();
while (act != 13)
{
switch (act)
{
case 77: system("cls");
cout << "\n\n\t\t\t Name: " << tmpName;
cout << "\n\n\t\t\t Phon Number: " << tmpPhon;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t| Done | |";
SetYellowTextColor(" Cancel ");
cout << "|";
cout << "\n\t\t\t ________ _________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
cout << "\n\n\t\t\t Name: " << tmpName;
cout << "\n\n\t\t\t Phon Number: " << tmpPhon;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
ID = GetMaxID();
++ID;
string fileName = "file" + std::to_string(ID) + ".txt";
AddInTail(tmpName, tmpPhon, ID, fileName);
SortByName();
WriteToFile("phonList.txt");
pos = FindByName(tmpName);
}
else if (act == 13 && isOk == false)
{
pos = 0;
break;
}
}
else if (pos >= 1 && pos <= count)
{
if (isCall)
{
if (myOperator != "no sim")
{
bool act = Call(pos);
if (act)
{
isCall = false;
WriteToFileOutcomingCall("CallsList.txt", pos);
break;
}
}
else
{
isCall = false;
break;
}
}
else
{
int act = 8;
string tmpName, tmpPhon;
Node *tmp = Head;
int j = 1;
while (j < pos)
{
tmp = tmp->next;
j++;
}
system("cls");
cout << "\n\n\t\t\t Name: " << tmp->_name;
cout << "\n\n\t\t\t Phon Number: " << tmp->_phoneNumber;
cout << "\n\n\t\t\t _____ ______ _____ ______\n\n";
cout << "\t\t\t| SMS || Edit || Del || Back |";
cout << "\n\t\t\t _____ ______ _____ ______\n";
int spPres = 0;
int tabPres = 0;
bool isSMS = false;
bool isEdit = false;
bool isDel = false;
bool isBack = false;
act = _getch();
while (act != 13)
{
switch (act)
{
case 77: system("cls");
spPres++;
cout << "\n\n\t\t\t Name: " << tmp->_name;
cout << "\n\n\t\t\t Phon Number: " << tmp->_phoneNumber;
cout << "\n\n\t\t\t _____ ______ _____ ______\n\n";
if (spPres == 1)
{
cout << "\t\t\t|";
SetYellowTextColor(" SMS ");
cout << "|| Edit || Del || Back |";
if (myOperator != "no sim") isSMS = true;
}
if (spPres == 2)
{
cout << "\t\t\t| SMS ||";
SetYellowTextColor(" Edit ");
cout << "|| Del || Back |";
isSMS = false;
isEdit = true;
}
if (spPres == 3)
{
cout << "\t\t\t| SMS || Edit ||";
SetYellowTextColor(" Del ");
cout << "|| Back |";
isEdit = false;
isDel = true;
}
if (spPres >= 4)
{
cout << "\t\t\t| SMS || Edit || Del ||";
SetYellowTextColor(" Back ");
cout << "|";
isDel = false;
isBack = true;
}
cout << "\n\t\t\t _____ ______ _____ ______\n";
act = _getch();
break;
case 75: system("cls");
cout << "\n\n\t\t\t Name: " << tmp->_name;
cout << "\n\n\t\t\t Phon Number: " << tmp->_phoneNumber;
cout << "\n\n\t\t\t _____ ______ _____ ______\n\n";
if (spPres <= 1)
spPres = 2;
if (spPres == 2)
{
cout << "\t\t\t|";
SetYellowTextColor(" SMS ");
cout << "|| Edit || Del || Back |";
isEdit = false;
if (myOperator != "no sim") isSMS = true;
}
if (spPres == 3)
{
cout << "\t\t\t| SMS ||";
SetYellowTextColor(" Edit ");
cout << "|| Del || Back |";
isDel = false;
isEdit = true;
}
if (spPres >= 4)
{
cout << "\t\t\t| SMS || Edit ||";
SetYellowTextColor(" Del ");
cout << "|| Back |";
isBack = false;
isDel = true;
spPres = 4;
}
cout << "\n\t\t\t _____ ______ _____ ______\n";
spPres--;
act = _getch();
break;
default:
act = _getch();
break;
}
if (act == 13 && isSMS == true)
{
string message;
bool isOk = true;
int act = Message(pos, message);
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
while (act != 13)
{
switch (act)
{
case 77: system("cls");
SetConsoleTextAttribute(hStdOut, (WORD)((2) | 2));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\t\t\t Message:\n";
cout << "\n\t\t\t " << message;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t| Done | |";
SetYellowTextColor(" Cancel ");
cout << "|";
cout << "\n\t\t\t ________ _________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
SetConsoleTextAttribute(hStdOut, (WORD)((2) | 2));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\t\t\t Message:\n";
cout << "\n\t\t\t " << message;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
//cout << "\n\n\n\n\t\t\tPlease, whait some time";
string fileName = CreateFileName(pos);
WriteToFileSMS(fileName, pos, message);
WriteToFileOutcomingSMS("SMS_file.txt", pos);
}
else if (act == 13 && isOk == false)
{
break;
}
}
else if (act == 13 && isEdit == true)
{
system("cls");
cout << "\n\n\t\t\t Name: " << tmp->_name;
act = _getch();
if (act == 8)
{
system("cls");
cout << "\n\n\t\t\t Name: ";
getline(cin, tmpName);
}
else
tmpName = tmp->_name;
cout << "\n\n\t\t\t Phon Number: " << tmp->_phoneNumber;
act = _getch();
if (act == 8)
{
system("cls");
cout << "\n\n\t\t\t Name: " << tmpName;
cout << "\n\n\t\t\t Phon Number: ";
getline(cin, tmpPhon);
}
else
tmpPhon = tmp->_phoneNumber;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
act = _getch();
bool isOk = true;
while (act != 13)
{
switch (act)
{
case 77: system("cls");
cout << "\n\n\t\t\t Name: " << tmpName;
cout << "\n\n\t\t\t Phon Number: " << tmpPhon;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t| Done | |";
SetYellowTextColor(" Cancel ");
cout << "|";
cout << "\n\t\t\t ________ _________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
cout << "\n\n\t\t\t Name: " << tmpName;
cout << "\n\n\t\t\t Phon Number: " << tmpPhon;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
tmp->_name = tmpName;
tmp->_phoneNumber = tmpPhon;
SortByName();
WriteToFile("phonList.txt");
pos = FindByName(tmpName);
break;
}
else if (act == 13 && isOk == false)
{
break;
}
}
else if (act == 13 && isDel == true)
{
system("cls");
cout << "\n\n\t\t\t Are you realy want dell " << tmp->_name << "'s contact?";
cout << "\n\n\t\t\t _________ __________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" YES ");
cout << "|| NO |";
cout << "\n\t\t\t _________ __________\n";
act = _getch();
bool isOk = true;
while (act != 13)
{
switch (act)
{
case 77: system("cls");
cout << "\n\n\t\t\t Are you realy want dell " << tmp->_name << "'s contact?";
cout << "\n\n\t\t\t _________ __________\n\n";
cout << "\t\t\t| YES ||";
SetYellowTextColor(" NO ");
cout << "|";
cout << "\n\t\t\t _________ __________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
cout << "\n\n\t\t\t Are you realy want dell " << tmp->_name << "'s contact?";
cout << "\n\n\t\t\t _________ __________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" YES ");
cout << "|| NO |";
cout << "\n\t\t\t _________ __________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
DelByPos(pos);
SortByName();
WriteToFile("phonList.txt");
pos--;
break;
}
if (act == 13 && isOk == false)
{
break;
}
}
else if (act == 13 && isBack == true)
{
break;
}
}
}
}
break;
default:
continue;
}
} while (action != 27);
}
void PhonList::AddInTail(string name, string phonNumber, int ID, string Mfile)
{
Node *newNode = new Node();
newNode->_name = name;
newNode->_phoneNumber = phonNumber;
newNode->id = ID;
newNode->messageFile = Mfile;
newNode->prev = Tail;
newNode->next = nullptr;
if (Tail != nullptr)
Tail->next = newNode;
if (count == 0)
Head = Tail = newNode;
else
Tail = newNode;
count++;
}
int PhonList::GetMaxID()
{
int i = 1;
Node *tmpNode = Head;
int max = tmpNode->id;
while (tmpNode->next != nullptr)
{
tmpNode = tmpNode->next;
if (tmpNode->id > max)
{
max = tmpNode->id;
}
}
return max;
}
void PhonList::DelByPos(int pos)
{
if (pos <= 0 || pos >= count + 1)
{
cout << "Error! Incorrect position.\n";
return;
}
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
Node *prevNode = tmpNode->prev;
Node *nextNode = tmpNode->next;
if (prevNode != nullptr && count != 1)
prevNode->next = nextNode;
if (nextNode != nullptr && count != 1)
nextNode->prev = prevNode;
if (pos == 1)
Head = nextNode;
if (pos == count)
Tail = prevNode;
tmpNode->next = nullptr;
delete tmpNode;
count--;
}
int PhonList::FindByName(string name)
{
int i = 1;
bool isFind = 0;
Node *tmpNode = Head;
while (tmpNode != nullptr)
{
if (tmpNode->_name == name)
{
//isFind = 1;
return i;
}
tmpNode = tmpNode->next;
i++;
}
if (isFind == 0)
{
return -3;
}
}
void PhonList::WriteToFile(string fName)
{
ofstream ofFile;
ofFile.open(fName);
Node *tmpNode = Head;
if (ofFile)
{
while (tmpNode != nullptr)
{
ofFile << tmpNode->_name << "***";
ofFile << tmpNode->_phoneNumber << "id:";
ofFile << tmpNode->id << "file:";
ofFile << tmpNode->messageFile <<endl;
tmpNode = tmpNode->next;
}
}
ofFile.close();
}
void PhonList::WriteToFileOutcomingCall(string fName, int pos)
{
ofstream ofFile;
if (pos != -1)
{
ofFile.open(fName, std::fstream::app);
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
if (ofFile)
{
ofFile << tmpNode->_name << endl;
ofFile << tmpNode->_phoneNumber << endl;
ofFile << "id:" << tmpNode->id;
ofFile << "file:" << tmpNode->messageFile << endl;
}
}
else
{
ofFile.open("CallsList.txt", std::fstream::app);
if (ofFile)
{
ofFile << "No name" << endl;
ofFile << fName << endl;
ofFile << "id:" << "xxx";
ofFile << "file:" << "xxx" << endl;
}
}
ofFile.close();
}
void PhonList::WriteToFileOutcomingSMS(string fName, int pos)
{
ofstream ofFile;
ofFile.open(fName, std::fstream::app);
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
if (ofFile)
{
ofFile << tmpNode->_name << "***";
ofFile << tmpNode->_phoneNumber << "id:";
ofFile << tmpNode->id << "file:";
ofFile << tmpNode->messageFile << endl;
}
ofFile.close();
}
void PhonList::WriteToFileSMS(string fName, int pos, string str)
{
ofstream ofFile;
ofFile.open(fName, std::fstream::app);
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
if (ofFile)
{
ofFile << "me:";
ofFile << str << "&&" << endl;
}
ofFile.close();
}
void PhonList::ReadFromSMSFile(int pos)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
ifstream ifFile;
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
string fName = tmpNode->messageFile;
try
{
ifFile.open(fName);
if (!ifFile)
{
throw (string)"Cannot open the file";
}
while (!ifFile.eof())
{
string message, me;
string tmp;
int index, index1, ID;
while (getline(ifFile, tmp))
{
string character = "me:";
index = tmp.find(character);
string character1 = "&&";
index1 = tmp.find(character1);
if (index != -1)
{
message = tmp.substr(index + 3, index1-3);
SetConsoleTextAttribute(hStdOut, (WORD)((10) | 10));
cout << "\n\t\t\tMe:" << message;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
character = "to me:";
index = tmp.find(character);
if (index != -1)
{
message = tmp.substr(index + 6, index1-3);
cout << "\n\t\t\t" << tmpNode->_name << ": " << message;
}
}
}
}
}
catch (string error)
{
}
}
string PhonList::CreateFileName(int pos)
{
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
string FileName = "file";
int ID = tmpNode->id;
FileName += std::to_string(ID);
FileName += ".txt";
return FileName;
}
void PhonList::ReadFromFile(string fName)
{
ifstream ifFile;
try
{
ifFile.open(fName);
if (!ifFile)
{
throw (string)"Cannot open the file";
}
while (!ifFile.eof())
{
string tmpName;
string tmpPhon;
string tmp;
string Mfile;
int index, ID;
while (getline(ifFile, tmp))
{
string character = "***";
index = tmp.find(character);
if (index != -1)
{
int index2 = tmp.find("id:");
tmpPhon = tmp.substr(index + 3, index2 - (index + 3));
tmpName = tmp.substr(0, index);
index2 = tmp.find("file:");
character = "id:";
index = tmp.find(character);
ID = atoi((tmp.substr(index + 3, index2 - (index + 3))).c_str());
Mfile = tmp.substr(index2 + 5);
AddInTail(tmpName, tmpPhon, ID, Mfile);
}
}
}
}
catch (string error)
{
}
}
void PhonList::SortByName()
{
for (int i = 0; i < count-1; i++)
{
Node *tmpNode = Head;
while (tmpNode->next != nullptr)
{
if (tmpNode->_name > tmpNode->next->_name)
{
string tmpName = tmpNode->_name;
string tmpNumber = tmpNode->_phoneNumber;
int ID = tmpNode->id;
string tmpFile = tmpNode->messageFile;
tmpNode->_name = tmpNode->next->_name;
tmpNode->_phoneNumber = tmpNode->next->_phoneNumber;
tmpNode->id = tmpNode->next->id;
tmpNode->messageFile = tmpNode->next->messageFile;
tmpNode->next->_name = tmpName;
tmpNode->next->_phoneNumber = tmpNumber;
tmpNode->next->id = ID;
tmpNode->next->messageFile = tmpFile;
}
tmpNode = tmpNode->next;
}
}
}
void PhonList::ShowSMSlist(int pos)
{
int i = 1;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
cout << "\n\n\t\tUse \"Left\", \"Right\", \"Up\", \"Down\"";
cout << "\n\t\tand \"Enter\" keys arrow for nawigation ";
SetConsoleTextAttribute(hStdOut, (WORD)((10) | 10));
cout << "\n\n\n\t\t\t Select contact:\n";
if (count != 0)
{
Node *tmp = Head;
while (tmp != nullptr)
{
if (i == pos)
{
SetConsoleTextAttribute(hStdOut, (WORD)((14) | 14));
cout << "\n\t\t\t " << tmp->_name << "\n";
}
else
{
SetConsoleTextAttribute(hStdOut, (WORD)((7) | 7));
cout << "\n\t\t\t " << tmp->_name << "\n";
}
i++;
tmp = tmp->next;
}
}
SetConsoleTextAttribute(hStdOut, (WORD)((7) | 7));
}
void PhonList::MessageListCorrect()
{
}
void PhonList::SelectContactText()
{
}
void PhonList::BackButton(int pos)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (pos == count+1)
{
SetYellowTextColor("\n\t\t\t\t\tBack");
}
else
{
SetConsoleTextAttribute(hStdOut, (WORD)((12) | 12));
cout << "\n\t\t\t\t\tBack";
SetConsoleTextAttribute(hStdOut, (WORD)((8) | 8));
}
}
void PhonList::SMS_Start(string op)
{
int pos = 0;
int action = 0;
if (onceEnter == 0)
{
ReadFromFile("phonList.txt");
onceEnter = 1;
}
SortByName();
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bool isCall = false;
//_getch();
do
{
system("cls");
ShowSMSlist(pos);
BackButton(pos);
action = _getch();
switch (action)
{
case 80: pos++;
system("cls");
if (pos >= count + 2)
{
pos = -1;
}
ShowSMSlist(pos);
BackButton(pos);
break;
case 72:pos--;
system("cls");
if (pos < -1)
{
pos = count+1;
}
ShowSMSlist(pos);
BackButton(pos);
break;
case 13:
if (pos == count+1)
{
action = 27;
break;
}
if (pos >= 1 && pos <= count && op!="no sim")
{
string tmpName, tmpPhon;
Node *tmp = Head;
int j = 1;
while (j < pos)
{
tmp = tmp->next;
j++;
}
system("cls");
string message;
bool isOk = true;
int i = 1;
Node *tmpNode = Head;
while (i < pos)
{
tmpNode = tmpNode->next;
i++;
}
ReadFromSMSFile(pos);
int act = Message(pos, message);
while (act != 13)
{
switch (act)
{
case 77: system("cls");
SetConsoleTextAttribute(hStdOut, (WORD)((2) | 2));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\t\t\t Message:\n";
cout << "\n\t\t\t " << message;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t| Done | |";
SetYellowTextColor(" Cancel ");
cout << "|";
cout << "\n\t\t\t ________ _________\n";
isOk = false;
act = _getch();
break;
case 75: system("cls");
SetConsoleTextAttribute(hStdOut, (WORD)((2) | 2));
cout << "\n\n\n\t\t\t " << tmpNode->_name;
SetConsoleTextAttribute(hStdOut, (WORD)((15) | 15));
cout << "\n\n\t\t\t Message:\n";
cout << "\n\t\t\t " << message;
cout << "\n\n\t\t\t ________ _________\n\n";
cout << "\t\t\t|";
SetYellowTextColor(" Done ");
cout << "| | Cancel |";
cout << "\n\t\t\t ________ _________\n";
isOk = true;
act = _getch();
break;
default:
act = _getch();
break;
}
}
if (act == 13 && isOk == true)
{
string fileName = CreateFileName(pos);
WriteToFileSMS(fileName, pos, message);
WriteToFileOutcomingSMS("SMS_file.txt", pos);
}
else if (act == 13 && isOk == false)
{
break;
}
}
break;
default:
continue;
}
} while (action != 27);
}
| true |
9d8c7666ce75f28554df79bd01059ef8401eb908
|
C++
|
OrangeJuice7/SDL-OpenGL-Game-Framework
|
/src/Scene/Model/EntityManager.hpp
|
UTF-8
| 4,673 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef ENTITY_MANAGER_HPP
#define ENTITY_MANAGER_HPP
#include <forward_list>
#include <functional>
#include "../../util/math.hpp"
class GameModelManager;
class UiManager;
template <class TEntity>
class EntityManager {
// Let all the different EntityManager<> classes talk to each other
// Needed for checkCollisions() to work
template<class UEntity>
friend class EntityManager;
protected:
std::forward_list<TEntity*> entities; // There shouldn't be any nullptrs in here
std::forward_list<TEntity*> toAdd; // Buffer list, to prevent element additions in the middle of iterating thru entities (which will screw up the iterator)
public:
EntityManager();
~EntityManager();
TEntity* addEntity(TEntity* entity);
void clearEntities();
void doTick(GameModelManager& model);
void doTick(GameModelManager& model, std::function<void(const TEntity&)> entityDeletedFunc); // Lets the parent dereference any entity it might be pointing to that has been deleted
void checkCollisionsSelf(
std::function<void(TEntity&, TEntity&)> collisionFunc );
template <class UEntity>
void checkCollisions(
EntityManager<UEntity>& otherManager,
std::function<void(TEntity&, UEntity&)> collisionFunc );
TEntity* pickEntity(float x, float y);
void draw(UiManager &uiManager) const;
};
template <class TEntity>
EntityManager<TEntity>::EntityManager() {}
template <class TEntity>
EntityManager<TEntity>::~EntityManager() {
clearEntities();
}
template <class TEntity>
TEntity* EntityManager<TEntity>::addEntity(TEntity* entity) {
toAdd.push_front(entity);
return toAdd.front();
}
template <class TEntity>
void EntityManager<TEntity>::clearEntities() {
for (TEntity *entity : entities) {
delete entity;
}
entities.clear();
for (TEntity *entity : toAdd) {
delete entity;
}
toAdd.clear();
}
template <class TEntity>
void EntityManager<TEntity>::doTick(GameModelManager& model) {
// Remove dead entities
entities.remove_if( [](const TEntity* entity) -> bool { return entity->isDead(); } );
// Add buffered entities
entities.splice_after(entities.before_begin(), toAdd);
// Update the rest
for (TEntity *entity : entities) {
entity->doTick(model);
}
}
template <class TEntity>
void EntityManager<TEntity>::doTick(GameModelManager& model, std::function<void(const TEntity&)> entityDeletedFunc) {
// Remove dead entities
entities.remove_if( [this, entityDeletedFunc](const TEntity* entity) -> bool {
if (entity->isDead()) {
entityDeletedFunc(*entity);
return true;
} else return false;
} );
// Add buffered entities
entities.splice_after(entities.before_begin(), toAdd);
// Update the rest
for (TEntity *entity : entities) {
entity->doTick(model);
}
}
template <class TEntity>
void EntityManager<TEntity>::checkCollisionsSelf(
std::function<void(TEntity&, TEntity&)> collisionFunc ) {
for (auto entity = entities.begin(); entity != entities.end(); ++entity) {
//if (entity.isDead()) continue;
auto otherEntity = entity; ++otherEntity;
for (; otherEntity != entities.end(); ++otherEntity) {
//if (otherEntity.isDead()) continue;
collisionFunc(**entity, **otherEntity);
}
}
}
template <class TEntity>
template <class UEntity>
void EntityManager<TEntity>::checkCollisions(
EntityManager<UEntity>& otherManager,
std::function<void(TEntity&, UEntity&)> collisionFunc ) {
for (TEntity *entity : entities) {
//if (entity.isDead()) continue;
for (UEntity *otherEntity : otherManager.entities) {
//if (otherEntity.isDead()) continue;
collisionFunc(*entity, *otherEntity);
}
}
}
template <class TEntity>
TEntity* EntityManager<TEntity>::pickEntity(float x, float y) {
for (TEntity *entity : entities) {
float ex = entity->x,
ey = entity->y,
er = entity->getRadius();
// Bounding box check
if (x < ex-er || x > ex+er ||
y < ey-er || y > ey+er ) continue;
// Circle check
if (getdist2(ex-x,ey-y) > er*er) continue;
return entity;
}
return nullptr;
}
template <class TEntity>
void EntityManager<TEntity>::draw(UiManager &uiManager) const {
for (const TEntity *entity : entities) {
if (entity->isWithinScreen(uiManager))
entity->draw(uiManager);
}
}
#endif // ENTITY_MANAGER_HPP
| true |
f8b01f945c7a4d046346bc7283c85d41118d0ad9
|
C++
|
ljhg1124/Data_structure
|
/BFS/BFS.cpp
|
UTF-8
| 1,025 | 3.40625 | 3 |
[] |
no_license
|
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define NUM 9
bool chk[NUM];
vector<int> node_Tree[NUM];
void bfs(int start) // 시작 인덱스값을 할당.
{
queue<int> q; // 탐색 순서를 담을 큐
q.push(start); // 시작 인덱스 값 push
chk[start] = true; // start 먼저 체크 하였으니 true
while(!q.empty()) // q 가 비여질 때까지 돌린다.
{
int cur_Node = q.front(); // 맨 처음 노드값 가져오기
q.pop();
for(int i = 0; i < node_Tree[cur_Node].size(); i++) // 현제 노드 값에 연결 되어 있는 노드를 찾는다.
{
int get_Node = node_Tree[cur_Node][i]; // 찾은 노드값 가져오기
if(!chk[get_Node]) // 처음 보드 노드 값이라면..
{
q.push(get_Node);
chk[get_Node] = true;
// 다음 찾을 값으로 큐에 배정 하고 체크 true 해준다.
}
}
}
}
| true |
ec3ce2980f4b521531f01d65b7558b1300925638
|
C++
|
zyex1108/DataStructures
|
/binary_tree/CharBinaryTree/CharBinaryTree/CharTree.cpp
|
UTF-8
| 545 | 2.96875 | 3 |
[] |
no_license
|
//
// CharTree.cpp
// CharBinaryTree
//
// Created by Ming Chow on 10/20/11.
// Copyright 2011 Tufts University. All rights reserved.
//
#include "CharTree.h"
#include <iostream>
using namespace std;
CharTree::CharTree()
{
root = NULL;
}
void CharTree::buildRoot(char someChar)
{
root = new TreeNode;
root->letter = someChar;
root->left = NULL;
root->right = NULL;
}
TreeNode* CharTree::getRoot()
{
return root;
}
bool CharTree::isEmpty()
{
return (root == NULL);
}
CharTree::~CharTree()
{
delete root;
}
| true |
f7115eba8a2acc75a771a074ba098023d1c766e1
|
C++
|
randomascii/blogstuff
|
/timer_interval/count_interrupts.cpp
|
UTF-8
| 2,720 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2020 Cygnus Software. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This program counts timer interrupts by watching timeGetTime().
*/
#include <Windows.h>
#include <stdio.h>
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "ntdll.lib")
NTSYSAPI NTSTATUS NTAPI NtQueryTimerResolution(PULONG MinimumResolution,
PULONG MaximumResolution,
PULONG CurrentResolution);
ULONG GetTimerResolution() {
static HMODULE ntdll = LoadLibrary("ntdll.dll");
static auto QueryTimerResolution =
reinterpret_cast<decltype(&::NtQueryTimerResolution)>(
GetProcAddress(ntdll, "NtQueryTimerResolution"));
ULONG minimum, maximum, current;
QueryTimerResolution(&minimum, &maximum, ¤t);
return current;
}
void CountInterrupts() {
const ULONG resolution_start = GetTimerResolution();
const DWORD start = timeGetTime();
DWORD last = start;
// Lots of space to store the wakeup times.
DWORD times[2000];
times[0] = start;
int count = 0;
for (;;) {
const DWORD current = timeGetTime();
if (current != last) {
++count;
times[count] = timeGetTime();
last = current;
}
if (current - start >= 1000)
break;
}
const ULONG resolution_end = GetTimerResolution();
// Only report results if the timer resolution hasn't changed during the
// measurement.
if (resolution_start == resolution_end) {
printf("Global timer interrupt interval is %4.1f ms. %d interrupts in one second.\n", resolution_start / 1e4, count);
int interval_counts[50] = {};
for (int i = 0; i < count; ++i) {
DWORD elapsed = times[i + 1] - times[i];
if (elapsed >= _countof(interval_counts))
elapsed = _countof(interval_counts) - 1;
++interval_counts[elapsed];
}
printf("Delay\tCount\tTable of timeGetTime() deltas.\n");
for (int i = 0; i < _countof(interval_counts); ++i)
if (interval_counts[i])
printf("%2d\t%2d\n", i, interval_counts[i]);
}
}
int main(int args, char* argv[]) {
for (;;)
CountInterrupts();
}
| true |
fe962f90faa3c96518230e9f8856309addf14954
|
C++
|
jamesptanner/arduino-arc-reactor
|
/spinner.h
|
UTF-8
| 940 | 2.859375 | 3 |
[] |
no_license
|
#ifndef SPINNER_H
#define SPINNER_H
#include "arcreactor.h"
class Spinner : public Mode
{
private:
static const int loopTrails = 3;
static constexpr Colour loopColour = {20,20,40};
static const int loopLevels = PIXELCOUNT / loopTrails;
Colour looptable[loopLevels] ={};
int spinStep =0;
public:
Spinner(PixelPtr pixel, int loopDelay= 10) : Mode(pixel), m_loopDelay(loopDelay){}
virtual void modeSetup();
virtual void run();
protected:
int spinIndex = 0 ;
void spin();
private:
int m_loopDelay = 0;
};
class SlowSpinner: public Spinner{
public:
SlowSpinner(PixelPtr pixel) : Spinner(pixel,40){}
};
//spinning faster then slower.
class VarSpeedSpinner : public Spinner
{
public:
VarSpeedSpinner(PixelPtr pixel): Spinner(pixel){}
virtual void modeSetup(){
Spinner::modeSetup();
}
virtual void run();
private:
bool forwards = true;
uint8_t m_delay = 10;
uint8_t m_hold = 0;
};
#endif
| true |
d07bfc1df8bba5bb7abf7474fbefcfd296c67b38
|
C++
|
karikera/ken
|
/KR3/msg/pump.h
|
UHC
| 5,749 | 2.546875 | 3 |
[] |
no_license
|
#pragma once
#include <KR3/util/callable.h>
#include <KR3/util/keeper.h>
#include <KR3/mt/criticalsection.h>
#ifdef WIN32
#include <KR3/win/threadid.h>
#endif
#include "promise.h"
namespace kr
{
struct EventProcedure
{
EventHandle * event;
void * param;
void(*callback)(void*);
};
class EventPump:public Interface<Empty>
{
friend TimerEvent;
friend PromisePump;
public:
constexpr static dword MAXIMUM_WAIT = EventHandleMaxWait - 1;
private:
class NodeHead
{
friend EventPump;
protected:
TimerEvent * m_next;
};
public:
void quit(int exitCode) noexcept;
void waitAll() noexcept;
void clearTasks() noexcept;
// node ο ϰ ȴ.
// return: ̹ Ȥ ҵ ̺Ʈ false
bool cancel(TimerEvent* node) noexcept;
// newnode ο ϰԵȴ.
void attach(TimerEvent* newnode) noexcept;
template <typename LAMBDA>
void post(LAMBDA &&lambda) noexcept
{
return attach(TimerEvent::create(timepoint::now(), forward<LAMBDA>(lambda)));
}
template <typename LAMBDA>
void post(timepoint at, LAMBDA &&lambda) noexcept
{
return attach(TimerEvent::create(at, forward<LAMBDA>(lambda)));
}
template <typename LAMBDA>
TimerEvent* makePost(timepoint at, LAMBDA&& lambda) noexcept;
template <typename LAMBDA>
void post(duration wait, LAMBDA &&lambda) noexcept
{
return post(timepoint::now() + wait, forward<LAMBDA>(lambda));
}
template <typename LAMBDA>
TimerEvent* makePost(duration wait, LAMBDA &&lambda) noexcept
{
return makePost(TimerEvent::create(timepoint::now() + wait, forward<LAMBDA>(lambda)));
}
// events Ѵ.
// return: µ ̺Ʈ ε
dword wait(View<EventHandle *> events) throws(QuitException);
// events time Ѵ.
// return: µ ̺Ʈ ε
dword wait(View<EventHandle *> events, duration time) throws(QuitException);
// events timeto Ѵ.
// return: µ ̺Ʈ ε
dword waitTo(View<EventHandle *> events, timepoint timeto) throws(QuitException);
void processOnce() throws(QuitException);
dword processOnce(View<EventHandle *> events) throws(QuitException);
void processOnce(View<EventProcedure> proc) throws(QuitException);
void processOnceWithoutMessage() throws(QuitException);
void processOnceWithoutMessage(View<EventProcedure> proc) throws(QuitException);
void wait(EventHandle * event) throws(QuitException);
void wait(EventHandle * event, duration time) throws(QuitException);
void waitTo(EventHandle * event, timepoint time) throws(QuitException);
void AddRef() noexcept;
void Release() noexcept;
Promise<void> * promise(duration time) noexcept;
Promise<void> * promiseTo(timepoint at) noexcept;
void sleep(duration dura) throws(QuitException);
void sleepTo(timepoint time) throws(QuitException);
int messageLoop() noexcept;
int messageLoopWith(View<EventProcedure> proc) noexcept;
static EventPump * getInstance() noexcept;
private:
EventPump() noexcept;
~EventPump() noexcept;
dword _tryProcess(EventHandle * const * events, dword count) throws(QuitException);
TmpArray<EventHandle *> _makeEventArray(View<EventHandle *> events) noexcept;
TmpArray<EventHandle *> _makeEventArray(View<EventProcedure> proc) noexcept;
void _processMessage() throws(QuitException);
dword _processTimer(dword maxSleep) throws(QuitException);
CriticalSection m_timercs;
EventHandle* m_msgevent;
NodeHead m_start;
ThreadId m_threadId;
atomic<size_t> m_reference;
PromisePump m_prompump;
};
namespace _pri_
{
template <size_t argn>
struct CallWithParamIfHas
{
template <typename LAMBDA>
static void call(LAMBDA && lambda, TimerEvent * param) throws(...)
{
lambda(param);
}
};
template <>
struct CallWithParamIfHas<0>
{
template <typename LAMBDA>
static void call(LAMBDA && lambda, TimerEvent * param) throws(...)
{
lambda();
}
};
}
class TimerEvent :public Interface<EventPump::NodeHead>
{
friend EventPump;
friend Referencable<TimerEvent>;
public:
TimerEvent() noexcept;
TimerEvent(timepoint at) noexcept;
virtual ~TimerEvent() noexcept;
bool isPosted() noexcept;
void setTime(timepoint time) noexcept;
void addTime(duration time) noexcept;
timepoint getTime() const noexcept;
void AddRef() noexcept;
size_t Release() noexcept;
size_t getRefCount() noexcept;
template <typename LAMBDA>
static TimerEvent* create(timepoint at, LAMBDA&& lambda) noexcept;
protected:
virtual void call() = 0;
size_t m_ref;
TimerEvent* m_prev;
timepoint m_at;
};
class EventThread
{
public:
EventThread() noexcept;
~EventThread() noexcept;
void create() noexcept;
void quit(int exitCode) noexcept;
EventPump * operator ->() noexcept;
private:
ThreadHandle * m_thread;
EventPump * m_pump;
};
template <typename LAMBDA>
TimerEvent* EventPump::makePost(timepoint at, LAMBDA&& lambda) noexcept
{
TimerEvent* node = TimerEvent::create(at, forward<LAMBDA>(lambda));
node->AddRef();
if (attach(node))
{
return node;
}
node->Release();
return nullptr;
}
template <typename LAMBDA>
static TimerEvent* TimerEvent::create(timepoint at, LAMBDA&& lambda) noexcept
{
struct LambdaWrap :public TimerEvent
{
decay_t<LAMBDA> m_lambda;
LambdaWrap(LAMBDA&& lambda, timepoint at) noexcept
: TimerEvent(at), m_lambda(forward<LAMBDA>(lambda))
{
}
void call() throws(...) override
{
constexpr size_t argn = meta::function<LAMBDA>::args_t::size;
_pri_::CallWithParamIfHas<argn>::call(m_lambda, this);
}
};
return _new LambdaWrap(forward<LAMBDA>(lambda), at);
}
}
| true |
c9b5863212d262f1e47b10ca962191285352c32f
|
C++
|
kdaiki211/modern_cpp_challenge
|
/8/67.cpp
|
UTF-8
| 3,303 | 3.5625 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
string InputPassword(void)
{
string password;
// TODO: disable echoback
cin >> password;
// TODO: enable echoback
return password;
}
class Checker {
public:
virtual bool isSatisfied(string password) = 0;
};
class LengthChecker : public Checker {
public:
LengthChecker(size_t minCnt) : minCnt(minCnt) {}
bool isSatisfied(string password) override {
return password.length() >= minCnt;
}
protected:
size_t minCnt;
};
class ContainsNCharactersChecker : public Checker {
public:
ContainsNCharactersChecker(size_t minCnt) : minCnt(minCnt) {}
bool isSatisfied(string password) override {
size_t cnt = 0;
for (auto c : password) {
if (isValidChar(c)) cnt++;
if (cnt >= minCnt) return true;
}
return false;
}
protected:
size_t minCnt;
virtual bool isValidChar(char c) = 0;
};
class ContainsNSymbolsChecker : public ContainsNCharactersChecker {
public:
ContainsNSymbolsChecker(size_t minCnt) : ContainsNCharactersChecker(minCnt) {}
protected:
bool isValidChar(char c) override {
return find(symbols.begin(), symbols.end(), c) != symbols.end();
}
vector<char> symbols { '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '-', '=', '^', '~', '\\', '|', '@', '`', '[', '{', ']', '}', ';', '+', ':', '*', ',', '<', '.', '>', '/', '?', '_' };
};
class ContainsNNumbersChecker : public ContainsNCharactersChecker {
public:
ContainsNNumbersChecker(size_t minCnt) : ContainsNCharactersChecker(minCnt) {}
protected:
bool isValidChar(char c) override {
return isdigit(c);
}
};
class ContainsNLowerCasesChecker : public ContainsNCharactersChecker {
public:
ContainsNLowerCasesChecker(size_t minCnt) : ContainsNCharactersChecker(minCnt) {}
protected:
bool isValidChar(char c) override {
return islower(c);
}
};
class ContainsNUpperCasesChecker : public ContainsNCharactersChecker {
public:
ContainsNUpperCasesChecker(size_t minCnt) : ContainsNCharactersChecker(minCnt) {}
protected:
bool isValidChar(char c) override {
return isupper(c);
}
};
class PasswordValidator {
public:
void addChecker(Checker* checker) {
this->checker.push_back(checker);
}
bool isValid(string password) {
for (auto c : checker) {
if (!c->isSatisfied(password)) return false;
}
return true;
}
private:
vector<Checker*> checker;
};
static void initMyValidator(PasswordValidator& validator)
{
static LengthChecker lengthChecker(8);
static ContainsNSymbolsChecker containsNSymbolsChecker(1);
static ContainsNNumbersChecker containsNNumbersChecker(1);
static ContainsNLowerCasesChecker containsNLowerCasesChecker(1);
static ContainsNUpperCasesChecker containsNUpperCasesChecker(1);
validator.addChecker(&lengthChecker);
validator.addChecker(&containsNSymbolsChecker);
validator.addChecker(&containsNNumbersChecker);
validator.addChecker(&containsNLowerCasesChecker);
validator.addChecker(&containsNUpperCasesChecker);
}
int main(void)
{
cout << "Enter password: ";
string password = InputPassword();
PasswordValidator validator;
initMyValidator(validator);
if (validator.isValid(password)) {
cout << "Valid." << endl;
} else {
cout << "Invalid." << endl;
}
return 0;
}
| true |
6ba332c310da2878260bac172d889542605bf2b7
|
C++
|
kellyualberta/Algorithms-Data-Structures
|
/Zenefits/travelMoney1.cpp
|
UTF-8
| 627 | 3.3125 | 3 |
[] |
no_license
|
#include "head.h"
class Solution{
int m;
int n;
public:
int travel(vector<vector<int>> matrix, int k){
m = matrix.size();
n = matrix[0].size();
int ret = INT_MAX;
bfs(0, 0, k, ret, matrix);
return ret;
}
void bfs(int i, int j, int left, int& ret, vector<vector<int>> &matrix){
left -= matrix[i][j];
if(left<0) return;
if(i==m-1 && j==n-1) ret = min(ret, left);
if(i+1<m) bfs(i+1, j, left, ret, matrix);
if(j+1<n) bfs(i, j+1, left, ret, matrix);
}
};
int main(){
vector<vector<int>> matrix = {{0, 5},{2, 9}};
Solution sol;
cout<<sol.travel(matrix, 20)<<endl;
return 0;
}
| true |
ff251b5455855cd3932bd730697dcdafb00c495d
|
C++
|
Miheel/Intro-Cpp
|
/Project/validInput.cpp
|
UTF-8
| 1,837 | 3.265625 | 3 |
[] |
no_license
|
//Namn: Mikael Leuf
//Datum: 2020-01-10
//Kurs: Introduktion till programering
//Lab: Project Contact
#include "validInput.h"
void isValidInput(std::string &contactMember, const REGFILTER ®Filter)
{
bool isValid = false;
std::regex regularFilter;
std::string errFormMsg = "The string must be on the specified format: ";
std::string errContMsg = "Can only contain the folowing characters";
while (!isValid)
{
std::getline(std::cin, contactMember);
switch (regFilter)
{
case NAME:
regularFilter = ("[A-Za-z ]+");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << errFormMsg << "Forename surename" << std::endl;
break;
case ADDER:
regularFilter = ("[A-Za-z- ]+ [0-9]+");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << errFormMsg << "Roadname nr" << std::endl;
break;
case MAIL:
regularFilter = ("[A-Za-z0-9._%+-]{1,20}@[A-Za-z0-9-]{2,20}(\\.[A-Za-z]{2,3}){1,2}");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << errFormMsg << "(email@example.com)\n" << errContMsg << "Letters, Numbers and '._%+-'" << std::endl;
break;
case PHONE:
regularFilter = ("[0-9]{3}[-][0-9]{3} [0-9]{2} [0-9]{2}");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << errFormMsg << "070-123 45 67" << std::endl;
break;
case DATE:
regularFilter = ("[0-9]{4}-[0-9]{2}-[0-9]{2}");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << errFormMsg << "nnnn-nn-nn" << std::endl;
break;
case MISC:
regularFilter = ("[^|]+");
if (std::regex_match(contactMember, regularFilter)) isValid = true;
else std::cout << "the string cant contain the pipe char '|'" << std::endl;
break;
}
}
}
| true |
1ac5efed8ced1c09ec61d8d521dfe6f469452a60
|
C++
|
gustn158/public
|
/[BOJ] SOLUTIONS/[BOJ] SOLUTIONS/[BOJ]3948.cpp
|
UHC
| 1,791 | 3.53125 | 4 |
[] |
no_license
|
/*
̰ 簢 ̰ ־ ִ. ̸ Į ߶ ̰ 簢 ǵ ϰ Ѵ.
Į ̸ ڸ Ģ .
ڸ Ǵ ȴ. , 缱δ ڸ .
ڸ Į ٲ .
ڸ ߿ Į . , ϴ ڸ ϸ ݵ ѷ и ڸ.
߷ ̴ ̾ Ѵ.
Ģ ־ 簢 ̸ ߶ 簢 ǵ ϵ, ߷ ּҰ ǵ ϰ Ѵ.
, Ʒ Ͱ ̰ 5 6 ̰ ־ , ּ 簢 ڸ Ʒ .
#include <iostream>
#include <algorithm>
using namespace std;
int n, m;
int cache[10001][101];
const int MAX = 987654321;
int SLV(int s,int g)
{
if (s == g)
return cache[s][g] = 1;
if (s< 0 || g < 0) return MAX;
int& ret = cache[s][g];
if (ret != -1)
return ret;
ret = s*g;
if (s >= 3 * g) ret = min(ret, SLV(s - g, g) + 1);
else {
for (int k = 1; k <= (g + 1) / 2; k++)
{
ret = min(ret, SLV(s, k) + SLV(s, g - k));
}
for (int k = 1; k <= (s + 1) / 2; k++)
{
ret = min(ret, SLV(k, g) + SLV(s - k, g));
}
}
return ret;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
memset(cache, -1, sizeof(cache));
cout << SLV(n,m);
}
*/
| true |
fdc554ebfe4725bb0ca6e5f5bf4d4e76427af235
|
C++
|
luismoax/Competitive-Programming---luismo
|
/COJ_ACCEPTED/2548 - Gross Weight.cpp
|
ISO-8859-1
| 779 | 2.9375 | 3 |
[] |
no_license
|
/*
Author: Luis Manuel Daz Barn
Problem: 2548 - Gross Weight
Online Judge: COJ
Idea: Precalculate all P^K elements then greedy
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#define ll long long
using namespace std;
ll P, G;
ll used[501];
int calc()
{
used[0] = 1;
int idx = 0;
for(int i = 1 ; i < 500 && used[i-1] < ((ll)1<<50); i++)
{
idx++;
used[i] = used[i-1]*P;
}
return idx;
}
int main()
{
while(1)
{
scanf("%lld",&P);
if(P==0) break;
scanf("%lld",&G);
int idx = calc(); // pre
for(int i = idx - 1 ; i>=0; i--)
{
if(used[i] <= G)
G-=used[i];
}
if(G==0) cout<<"YES\n";
else cout<<"NO\n";
}
}
| true |
979d0087b314d30067b93adeeda1d6fc8eb763f2
|
C++
|
dreamTeamHack/SubiForever
|
/MathematicModel/Utils.hpp
|
UTF-8
| 389 | 3.21875 | 3 |
[] |
no_license
|
#ifndef UTILS_HPP
#define UTILS_HPP
#include <cmath>
class Angle
{
public:
float radians = 0.0;
float getDegrees() const;
Angle();
Angle(float radians);
Angle(const Angle& angle);
};
static constexpr float radians2degrees(float rad){
return rad * 180 / M_PI;
}
static constexpr float degrees2radians(float deg){
return deg * M_PI / 180;
}
#endif
| true |
c2dfff61323e1c5e3f4321a165c84dbfa32b1620
|
C++
|
crandino/Stack
|
/UnitTest1/unittest1.cpp
|
UTF-8
| 3,502 | 3.0625 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "CppUnitTest.h"
#include "../Stack.h"
#include "../Queue.h"
#include "../Trees.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
// ----------------------------
// STACK
// -----------------------------
TEST_METHOD(StackDefaultConstr)
{
Stack<char> s;
s.push('A');
s.push('B');
s.push('C');
char ret;
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'C');
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'B');
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'A');
}
TEST_METHOD(StackConstrMemo)
{
Stack<char> s(2);
s.push('A');
s.push('B');
s.push('C');
char ret;
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'C');
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'B');
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, 'A');
}
TEST_METHOD(StackPushPop)
{
Stack<int> s(50);
for (int i = 0; i < 1000; i++)
s.push(i);
Assert::AreEqual(s.getElements(), (unsigned)1000);
int ret;
for (int i = 999; i >= 0; i--)
{
Assert::IsTrue(s.pop(ret));
Assert::AreEqual(ret, i);
}
Assert::AreEqual(s.getElements(), (unsigned)0);
for (int i = 0; i < 10; i++)
{
Assert::IsFalse(s.pop(ret));
Assert::AreEqual(ret, 0);
}
}
TEST_METHOD(StackPeek)
{
Stack<int> s(50);
for (int i = 0; i < 100; i++)
s.push(i);
for (int i = 0; i < 100; i++)
Assert::AreEqual(*s.peek(i), i);
}
// ----------------------------
// QUEUE
// -----------------------------
TEST_METHOD(QueuePush)
{
Queue<int> q;
for (int i = 0; i < 100; i++)
q.push(i);
int ret;
for (int i = 0; i < 100; i++)
{
q.pop(ret);
Assert::AreEqual(ret, i);
}
for (int i = 0; i < 100; i++)
{
q.pop(ret);
Assert::AreEqual(ret, 99);
}
}
TEST_METHOD(QueueCount)
{
Queue<int> q;
for (int i = 0; i < 100 ; i++)
q.push(i);
Assert::AreEqual(q.count(), (unsigned) 100);
int ret;
for (unsigned int i = 99; i > 0; i--)
{
q.pop(ret);
Assert::AreEqual(q.count(), i);
}
for (unsigned int i = 0; i < 10 ; i++)
{
q.pop(ret);
Assert::AreEqual(q.count(), (unsigned) 0);
}
}
TEST_METHOD(QueuePeek)
{
Queue<int> q;
for (int i = 0; i < 100; i++)
q.push(i);
for (int i = 0; i < 100; i++)
Assert::AreEqual(*(q.peek(i)), i);
}
TEST_METHOD(QueueClear)
{
Queue<int> q;
for (int i = 0; i < 100; i++)
q.push(i);
Assert::AreEqual(q.count(), (unsigned) 100);
q.clear();
Assert::AreEqual(q.count(), (unsigned) 0);
}
// ----------------------------
// QUEUE
// -----------------------------
TEST_METHOD(Queue2Push)
{
Queue2<int> q;
for (int i = 0; i < 100; i++)
q.push(i);
int ret;
for (int i = 0; i < 100; i++)
{
q.pop(ret);
Assert::AreEqual(ret, i);
}
for (int i = 0; i < 100; i++)
{
q.pop(ret);
Assert::AreEqual(ret, 99);
}
}
TEST_METHOD(Queue2Count)
{
Queue2<int> q;
for (int i = 0; i < 100; i++)
q.push(i);
Assert::AreEqual(q.count(), (unsigned)100);
int ret;
for (unsigned int i = 99; i > 0; i--)
{
q.pop(ret);
Assert::AreEqual(q.count(), i);
}
for (unsigned int i = 0; i < 10; i++)
{
q.pop(ret);
Assert::AreEqual(q.count(), (unsigned)0);
}
}
};
}
| true |
4c4fefcf71256ddc27b0b281b9ceae3fb8636d97
|
C++
|
KenjuDari/crutches
|
/program/tsoy_d_a/rect2d/rect2d_test.cpp
|
WINDOWS-1251
| 746 | 3.296875 | 3 |
[] |
no_license
|
#include"rect2d.h"
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
cout << "constructor without paramentrs: r1";
Rect2d r1;
cout << r1 << endl;
cout << "constructor with 4 paramentrs: r2";
Rect2d r2(-1, 0, -6, 4);
cout << r2 << endl;
cout << "constructor with 2 paramentrs: r3";
Rect2d r3(2.2, 7);
cout << r3 << endl;
cout << "copy constructor paramentrs: r4(r1)";
Rect2d r4(r1);
cout << r4 << endl;
cout << "operator= for r4=r2: ";
r4 = r2;
cout << r4 << endl;
cout << endl;
cout << "square r4 = " << r4.square() << endl;
r1.peresech(r3);
cout << "peresech r1 and r3: " << r1; // ?
return 0;
};
| true |
d2b46cd7e8a09da9ff19648301f390b6f2bf18bb
|
C++
|
shurcooL/Hover
|
/HoverSource/common/stuff.cpp
|
UTF-8
| 2,795 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#include "common.h"
void CRectRegion::Set( INT32 sx, INT32 sz, INT32 ex, INT32 ez ){
startX = sx;
startZ = sz;
endX = ex;
endZ = ez;
}
void CRectRegion::Clip( INT32 sx, INT32 sz, INT32 ex, INT32 ez ){
if( startX < sx ){ startX = sx; }
if( startZ < sz ){ startZ = sz; }
if( endX > ex ){ endX = ex; }
if( endZ > ez ){ endZ = ez; }
if( endX < startX ){ endX = startX; } // prevent invalid regions
if( endZ < startZ ){ endZ = startZ; }
}
HRESULT SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom,
D3DVECTOR& vAt, D3DVECTOR& vWorldUp )
{
// Get the z basis vector, which points straight ahead. This is the
// difference from the eyepoint to the lookat point.
D3DVECTOR vView = vAt - vFrom;
FLOAT fLength = Magnitude( vView );
if( fLength < 1e-6f )
return E_INVALIDARG;
// Normalize the z basis vector
vView /= fLength;
// Get the dot product, and calculate the projection of the z basis
// vector onto the up vector. The projection is the y basis vector.
FLOAT fDotProduct = DotProduct( vWorldUp, vView );
D3DVECTOR vUp = vWorldUp - fDotProduct * vView;
// If this vector has near-zero length because the input specified a
// bogus up vector, let's try a default up vector
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
{
vUp = D3DVECTOR( 0.0f, 1.0f, 0.0f ) - vView.y * vView;
// If we still have near-zero length, resort to a different axis.
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
{
vUp = D3DVECTOR( 0.0f, 0.0f, 1.0f ) - vView.z * vView;
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
return E_INVALIDARG;
}
}
// Normalize the y basis vector
vUp /= fLength;
// The x basis vector is found simply with the cross product of the y
// and z basis vectors
D3DVECTOR vRight = CrossProduct( vUp, vView );
// Start building the matrix. The first three rows contains the basis
// vectors used to rotate the view to point at the lookat point
D3DUtil_SetIdentityMatrix( mat );
mat._11 = vRight.x; mat._12 = vUp.x; mat._13 = vView.x;
mat._21 = vRight.y; mat._22 = vUp.y; mat._23 = vView.y;
mat._31 = vRight.z; mat._32 = vUp.z; mat._33 = vView.z;
// Do the translation values (rotations are still about the eyepoint)
mat._41 = - DotProduct( vFrom, vRight );
mat._42 = - DotProduct( vFrom, vUp );
mat._43 = - DotProduct( vFrom, vView );
return S_OK;
}
WORD GetNumberOfBits( DWORD dwMask )
{
WORD wBits = 0;
while( dwMask )
{
dwMask = dwMask & ( dwMask - 1 );
wBits++;
}
return wBits;
}
| true |
59fa032750799a21cd3e9d33ac5290533a052804
|
C++
|
astraizer/algoFJ
|
/Soal/Day 2/S.cpp
|
UTF-8
| 301 | 2.875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
int main(){
int t;
scanf("%d",&t);
for(int tc=0;tc<t;tc++){
char s[1000];
scanf("%s",s);
for(int i=0;i<strlen(s)/2;i++){
char temp = s[i];
s[i]=s[strlen(s)-1-i];
s[strlen(s)-1-i] = temp;
}
printf("Case #%d : %s\n",tc+1,s);
}
return 0;
}
| true |
7b989b8317c7113b6441ca99005b5d2f549213c0
|
C++
|
RyanDJSee/CC3k
|
/wd.cc
|
UTF-8
| 538 | 2.515625 | 3 |
[] |
no_license
|
#include "potion.h"
#include "wd.h"
#include <memory>
using namespace std;
bool WD::wasUsed=false;
WD::WD(int chamber, int r, int c, int amt):
Potion(chamber, r, c, amt) {} //constructor, default amt is for cell on Floor
void WD::notify(shared_ptr<Subject>& whoNotified) {
// wN called this.notify(wN), this should do sth on wN
//called when PC pass by
if (wasUsed) {
//send msg to floor
observers[0]->addaction("sees an WD");
}
}
int WD::getDef() const { // returns the HP amount in this
return amount;
}
| true |
ae2065bb9ce6d5d632263f1033a48755bc6af07e
|
C++
|
Haut-Stone/ACM
|
/INBOX/游戏币问题(简单dp).cpp
|
UTF-8
| 1,392 | 3.21875 | 3 |
[] |
no_license
|
/*问题概述: 在一个n*m的矩形方格里,每个网格里有一定数量的游戏币.我们可以控制机器人从左上角出发,到右下角
结束,并且会拾取沿途经过的格子里的游戏币,请计算机器人最富能得到多少游戏币
输入样例: 对应输出:
3 4 24
3 1 2 8
5 3 4 6
1 0 2 3
*/
#include <stdio.h>
int main(void)
{
int i, j;
int m, n;
int map[22][22] = {0};
int dp[22][22] = {0};
scanf("%d%d", &m, &n);
for(i=1;i<=m;i++) /*将最外围的一圈全部设为0枚金币,这样就不用处理边界问题*/
{
for(j=1;j<=n;j++)
scanf("%d", &map[i][j]);
}
for(i=1;i<=n-1;i++) /*递推求解各个子问题,自问题即从相邻的两步跳过来,二者之一的更大值*/
{
for(j=1;j<=n;j++)
{
if(dp[i][j-1]>dp[i-1][j])//看看上面和左面的数值谁更大
dp[i][j] = dp[i][j-1]+map[i][j];
else
dp[i][j] = dp[i-1][j]+map[i][j];
}
}
printf("%d\n", dp[m][n]);
return 0;
}
/*动态规划:
通过把原问题分解为相对简单的子问题而定方式求解的方法
流程:
找到最小子问题
↓
找到递推关系式,并将每个子问题答案储在表中
↓
求出原问题最优解 */
| true |
3e0679943796ec232b2325a7eaa783cb4209e753
|
C++
|
henry-banks/Base
|
/Example/Factory.h
|
UTF-8
| 6,627 | 2.90625 | 3 |
[] |
no_license
|
#pragma once
#include "Entity.h"
class Factory
{
ObjectPool<Entity> entities;
// The factory will store an object pool for each component type
ObjectPool<Transform> transforms;
ObjectPool<Rigidbody> rigidbodies;
ObjectPool<Collider> colliders;
ObjectPool<Sprite> sprites;
ObjectPool<Lifetime> lifetimes;
ObjectPool<Camera> cameras;
ObjectPool<Text> texts;
ObjectPool<PlayerController> players;
ObjectPool<EnemyController> enemies;
ObjectPool<Trigger> triggers;
ObjectPool<Timer> timers;
public:
// iterators to access the entity pool
ObjectPool<Entity>::iterator begin() { return entities.begin(); }
ObjectPool<Entity>::iterator end() { return entities.end(); }
// for now, they're all the same size
Factory(size_t size = 512)
: entities(size), transforms(size), rigidbodies(size),
colliders(size), sprites(size), lifetimes(size),
cameras(size), players(size), texts(size), enemies(size),
triggers(size), timers(size)
{
}
//general-purpose getter
template<typename T>
ObjectPool<T> getObjectPool(const std::string &name) const
{
switch (name)
{
case "entities":
return entities; break;
case "transforms":
return transforms; break;
case "rigidbodies":
return rigidbodies; break;
case "colliders":
return colliders; break;
case "sprites":
return sprites; break;
case "lifetimes":
return lifetimes; break;
case "cameras":
return cameras; break;
case "texts":
return texts; break;
case "players":
return players; break;
case "enemies":
return enemies; break;
case "triggers":
return triggers; break;
case "timers":
return timers; break;
default:
return entities;
break;
}
}
// What follows are specialized spawning functions
// just observe the steps taken and replicate for your own usages
ObjectPool<Entity>::iterator spawnCamera(float w2, float h2, float zoom)
{
auto e = entities.push();
e->transform = transforms.push();
e->camera = cameras.push();
e->camera->offset = vec2{ w2,h2 };
e->camera->scale = vec2{ zoom,zoom };
return e;
}
ObjectPool<Entity>::iterator spawnStaticImage(unsigned sprite, float x, float y, float w, float h)
{
auto e = entities.push();
e->transform = transforms.push();
e->sprite = sprites.push();
e->sprite->sprite_id = sprite;
e->sprite->dimensions = vec2{w,h};
e->transform->setLocalPosition(vec2{ x,y });
return e;
}
ObjectPool<Entity>::iterator spawnBullet(unsigned sprite, vec2 pos, vec2 dim, float ang, float impulse, unsigned faction, bool isRight)
{
auto e = entities.push();
e->transform = transforms.push();
e->rigidbody = rigidbodies.push();
e->sprite = sprites.push();
e->lifetime = lifetimes.push();
float x = 1.f;
float y = .25f;
float offsetX = 0.f;
float offsetY = 0.f;
vec2 v[4];
v[0] = vec2{ x, y};
v[1] = vec2{-x, y};
v[2] = vec2{-x, -y};
v[3] = vec2{ x, -y};
e->trigger = triggers.push(Trigger(v,4,"bullet"));
e->trigger->isActive = true;
e->transform->setLocalPosition(pos);
e->transform->setLocalScale(dim);
e->transform->setLocalAngle(ang);
e->sprite->sprite_id = sprite;
e->sprite->dimensions = vec2{2.f, .5f};
if(isRight)
e->rigidbody->addImpulse(vec2{ impulse, 0 });
else
e->rigidbody->addImpulse(vec2{ -impulse, 0 });
e->lifetime->lifespan = 1.6f;
return e;
}
ObjectPool<Entity>::iterator spawnPlayer(unsigned sprite, unsigned font)
{
auto e = entities.push();
e->transform = transforms.push();
e->transform->setGlobalPosition(vec2{ 520, 250 });
e->rigidbody = rigidbodies.push();
e->sprite = sprites.push();
float x = .1f, y = .25f;
vec2 v[4] = { vec2{ x, y }, vec2{ -x, y }, vec2{ -x, -y }, vec2{ x, -y } };
e->collider = colliders.push(Collider(v, 4));
x =.25f;
y = .3f;
float offsetX = 2 * x;
float offsetY = .2f;
v[0] = vec2{ x + offsetX, y + offsetY };
v[1] = vec2{ -x + offsetX, y + offsetY };
v[2] = vec2{ -x + offsetX, -y + offsetY };
v[3] = vec2{ x + offsetX, -y + offsetY };
e->trigger = triggers.push(Trigger(v, 4, "player_att"));
e->trigger->isActive = false;
v[0] = vec2{ x - offsetX, y + offsetY };
v[1] = vec2{ -x - offsetX, y + offsetY };
v[2] = vec2{ -x - offsetX, -y + offsetY };
v[3] = vec2{ x - offsetX, -y + offsetY };
e->trigger2 = triggers.push(Trigger(v, 4, "player_att"));
e->trigger->isActive = false;
e->player = players.push();
e->text = texts.push();
e->text->sprite_id = font;
e->text->offset = vec2{ -24,-24 };
e->text->off_scale = vec2{.5f,.5f};
e->text->setString("");
e->transform->setLocalScale(vec2{150,199});
e->sprite->sprite_id = sprite;
return e;
}
ObjectPool<Entity>::iterator spawnEnemy(unsigned sprite)
{
auto e = entities.push();
//determines if the enemy spawns on the left or right side of the screen.
vec2 newPos = ((rand() % 2) == 0) ? vec2{ 100, 200 } : vec2{ 1200, 200 };
e->transform = transforms.push();
e->transform->setGlobalPosition(newPos);
e->transform->setLocalScale(vec2{ 110,199 });
e->rigidbody = rigidbodies.push();
e->sprite = sprites.push();
float x = .35f, y = .45f;
vec2 v[4] = { vec2{ x, y }, vec2{ -x, y }, vec2{ -x, -y }, vec2{ x, -y } };
e->trigger = triggers.push(Trigger(v, 4, "enemy"));
e->trigger->isActive = true;
e->enemy = enemies.push();
e->sprite->sprite_id = sprite;
return e;
}
ObjectPool<Entity>::iterator spawnAsteroid(unsigned sprite)
{
auto e = entities.push();
e->transform = transforms.push();
e->rigidbody = rigidbodies.push();
e->sprite = sprites.push();
e->collider = colliders.push();
e->transform->setLocalScale(vec2{ 48,48 });
e->transform->setGlobalPosition(vec2::fromAngle(randRange(0, 360)*DEG2RAD)*(rand01() * 200 + 64));
e->rigidbody->addSpin(rand01()*12-6);
e->sprite->sprite_id = sprite;
return e;
}
ObjectPool<Entity>::iterator spawnBlank(vec2 pos)
{
auto e = entities.push();
e->transform = transforms.push();
e->transform->setGlobalPosition(pos);
return e;
}
ObjectPool<Entity>::iterator spawnTimer(float time, std::string name = "name")
{
auto e = entities.push();
e->timer = timers.push(Timer(time, name));
return e;
}
ObjectPool<Entity>::iterator spawnText(unsigned font, std::string text_a, vec2 pos, vec2 scl = {1,1}, unsigned tint = WHITE)
{
auto e = entities.push();
e->transform = transforms.push();
e->transform->setGlobalPosition(pos);
e->text = texts.push();
e->text->sprite_id = font;
e->text->setString(text_a.c_str());
e->text->off_scale = scl;
e->text->tint = tint;
return e;
}
};
| true |
e386e907d3627bb56daa06042235edb5cf02f16d
|
C++
|
lorenmanu/variado
|
/ugr_ig-master/P4/Robot.cc
|
UTF-8
| 4,545 | 2.78125 | 3 |
[] |
no_license
|
/*
* Jesús Ángel González Novez
* Práctica 4 IG
*
*/
#include "Robot.h"
Robot::Robot() {
posicion = 0;
baile = false;
}
Robot::Robot(const Robot& orig) {
}
void Robot::draw(int giro, int gla, int gra, int grl, int gll, int tipo) {
modo = tipo;
if (tipo == 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} else if (tipo == 1) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
} else if (tipo == 2) {
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
} else if (tipo == 3) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
drawHead();
glPushMatrix();
glRotatef(giro, 0, 1, 0);
drawEyes();
glPopMatrix();
drawBody();
glPushMatrix();
glTranslatef(0, 0.7, 0.0);
// glRotatef(grl, 1, 0, 0);
glTranslatef(0, -0.7, 0.0);
drawLeftArm();
drawCodo1();
glRotatef(gla, 1, 0, 0);
drawLeftArmAbajo();
drawMano1();
glPopMatrix();
glPushMatrix();
glTranslatef(0, 0.3, 0.0);
//glRotatef(grl, 1, 0, 0);
glTranslatef(0, -0.3, 0.0);
drawRightArm();
drawCodo2();
glRotatef(gra, 1, 0, 0);
drawRightArmAbajo();
drawMano2();
glPopMatrix();
glPushMatrix();
glTranslatef(0, 0.7, 0.0);
glRotatef(grl, 1, 0, 0);
glTranslatef(0, -0.7, 0.0);
drawRightLeg();
glPopMatrix();
glPushMatrix();
glTranslatef(0, 0.7, 0.0);
glRotatef(gll, 1, 0, 0);
glTranslatef(0, -0.7, 0.0);
drawLeftLeg1();
drawLeftLeg2();
glPopMatrix();
}
void Robot::drawHead() {
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(0, 1.15, 0);
glutSolidSphere(.5,20,20);
glPopMatrix();
glPushMatrix();
glColor3f(0, 0, 1);
glTranslatef(0, 1.25, 0);
glRotatef(90,-90,0,0);
//gorro.draw(modo);
gluCylinder(gluNewQuadric(),0.6,0.01,1,25,25);
glPopMatrix();
}
void Robot::drawEyes() {
glPushMatrix();
glTranslatef(-0.2, 1.1, 0.50);
glutSolidSphere(.1,20,20);
glPopMatrix();
glPushMatrix();
glTranslatef(0.2, 1.1, 0.50);
glutSolidSphere(.1,20,20);
glPopMatrix();
}
void Robot::drawBody() {
glPushMatrix();
glColor3f(1, 0, 0);
//glTranslatef(0, -0.5, 0);
glRotatef(90, 0, 1, 0);
glutSolidCube(1.5);
glPopMatrix();
}
void Robot::drawLeftArm() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(-1, 0.8, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1,25,25);
glPopMatrix();
}
void Robot::drawRightArm() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(1, 0.8, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1,25,25);
glPopMatrix();
}
void Robot::drawRightLeg() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(-0.5, -.8, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1.5,25,25);
glPopMatrix();
glPushMatrix();
glColor3f(1, 0, 1);
glTranslatef(-0.5, -2.3, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1.5,25,25);
glPopMatrix();
}
void Robot::drawLeftLeg1() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(0.5, -.8, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1.5,25,25);
glPopMatrix();
}
void Robot::drawLeftLeg2() {
glPushMatrix();
glColor3f(1, 0, 1);
glTranslatef(0.5, -2.3, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1.5,25,25);
glPopMatrix();
}
void Robot::drawMano1() {
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(-1, -1.60, 0);
glutSolidSphere(.25,20,20);
glPopMatrix();
}
void Robot::drawMano2() {
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(1, -1.60, 0);
glutSolidSphere(.25,20,20);
glPopMatrix();
}
void Robot::drawCodo1() {
glPushMatrix();
glColor3f(0, 0, 1);
glTranslatef(-1, -0.40, 0);
glutSolidSphere(.25,20,20);
glPopMatrix();
}
void Robot::drawCodo2() {
glPushMatrix();
glColor3f(0, 0, 1);
glTranslatef(1, -0.40, 0);
glutSolidSphere(.25,20,20);
glPopMatrix();
}
void Robot::drawLeftArmAbajo() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(-1, -.6, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1,25,25);
glPopMatrix();
}
void Robot::drawRightArmAbajo() {
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(1, -.6, 0);
glRotatef(90, 90, 0, 0);
gluCylinder(gluNewQuadric(),0.3,0.3,1,25,25);
glPopMatrix();
}
Robot::~Robot() {
}
| true |
a1d3f3d0c8a5d8f5afe9c8104cb7812928dfcbb5
|
C++
|
manuel-delverme/crop_row_detection
|
/crop_row_detection_cpp/src/ImagePreprocessor.cpp
|
UTF-8
| 3,580 | 2.90625 | 3 |
[] |
no_license
|
//
// Created by noflip on 21/11/16.
//
#include <string>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <CropRowDetector.h>
#include "ImagePreprocessor.h"
namespace crd_cpp {
ImagePreprocessor::ImagePreprocessor(cv::Size target_size) {
m_image_size = target_size;
}
cv::Mat ImagePreprocessor::convertToExG(cv::Mat &image) {
cv::Mat intensity = cv::Mat::zeros(image.size(), CV_8UC1);
cv::Mat bgr[3]; //destination array
cv::split(image, bgr);
double blueMax, greenMax, redMax;
double blueMin, greenMin, redMin;
// Finding maximum values in all channels
cv::minMaxLoc(bgr[0], &blueMin, &blueMax);
cv::minMaxLoc(bgr[1], &greenMin, &greenMax);
cv::minMaxLoc(bgr[2], &redMin, &redMax);
double blueNorm, greenNorm, redNorm;
double blue, green, red;
double sumNorm, ExG;
for (int c = 0; c < bgr[0].rows; c++) {
uchar *blue_ptr = bgr[0].ptr<uchar>(c);
uchar *green_ptr = bgr[1].ptr<uchar>(c);
uchar *red_ptr = bgr[2].ptr<uchar>(c);
uchar *intensity_ptr = intensity.ptr<uchar>(c);
for (int r = 0; r < bgr[0].cols; r++, blue_ptr++, green_ptr++, red_ptr++, intensity_ptr++) {
//normalize all pixels with max value of every channel
blueNorm = (double) *blue_ptr / blueMax;
greenNorm = (double) *green_ptr / greenMax;
redNorm = (double) *red_ptr / redMax;
sumNorm = blueNorm + greenNorm + redNorm;
//normalize every pixel so that sum of all channels is 1
blue = blueNorm / sumNorm;
green = greenNorm / sumNorm;
red = redNorm / sumNorm;
ExG = (2 * green - blue - red) * 255.0;
ExG = std::max(0.0, ExG);
*intensity_ptr = (unsigned char) ExG;
}
}
return intensity;
}
cv::Mat ImagePreprocessor::process(std::string image_path) {
cv::Mat image = cv::imread(image_path, CV_LOAD_IMAGE_COLOR);
return process(image);
}
cv::Mat ImagePreprocessor::process(cv::Mat image) {
cv::Mat resized_image;
cv::resize(image, resized_image, m_image_size);
cv::Mat intensity = ImagePreprocessor::convertToExG(resized_image);
cv::Mat down_ExG_;
down_ExG_ = cv::Mat::zeros(cv::Size(intensity.cols / 2, intensity.rows / 2), intensity.type());
// TODO: improve ExG to become ExBrown if Green>Brown
// Downsampling ottimo
for (int row = 0; row < intensity.rows / 2; row++) {
for (int column = 0; column < intensity.cols / 2; column++) {
int max = intensity.at<uchar>((row - 1) * 2, (column - 1) * 2);
if (intensity.at<uchar>((row - 1) * 2 + 1, (column - 1) * 2) > max)
max = intensity.at<uchar>((row - 1) * 2 + 1, (column - 1) * 2);
if (intensity.at<uchar>((row - 1) * 2, (column - 1) * 2 + 1) > max)
max = intensity.at<uchar>((row - 1) * 2, (column - 1) * 2 + 1);
if (intensity.at<uchar>((row - 1) * 2 + 1, (column - 1) * 2 + 1) > max)
max = intensity.at<uchar>((row - 1) * 2 + 1, (column - 1) * 2 + 1);
assert(max <= UCHAR_MAX);
down_ExG_.at<uchar>(row, column) = (uchar) max;
}
}
return intensity;
}
}
| true |
24ce3f6f9e5227c13f7f03d512684178dd3af678
|
C++
|
Kaboms/CmdTetris
|
/Tetris/CMDGui.h
|
UTF-8
| 982 | 2.5625 | 3 |
[] |
no_license
|
#pragma once
//----------------------------------------------------------------------
#include <Windows.h>
#include <stdint.h>
//----------------------------------------------------------------------
namespace CMDGui
{
enum Color
{
Black = 0,
Blue = 1,
Green = 2,
Aqua = 3,
Red = 4,
Purple = 5,
Yellow = 6,
White = 7,
Gray = 8,
LightBlue = 9,
LightGreen = 10,
LightAqua = 11,
LightRed = 12,
LightPurple = 13,
LightYellow = 14,
BrightWhite = 15
};
//----------------------------------------------------------------------
HANDLE GetOutputHandle();
void ShowColorTable();
void SetConsoleSize(int width, int height);
void SetConsoleTextColor(Color foreground, Color background);
void SetConsoleTextColor(uint8_t color);
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//----------------------------------------------------------------------
}
| true |
7fc9fb1790fdaa5f418ed61bfb2ee4599e84b038
|
C++
|
info-rick/proj-bacpfsec
|
/Bacpfsec_V2/TimelineHor.cc
|
UTF-8
| 1,194 | 3.109375 | 3 |
[] |
no_license
|
/**
* @file TimlineHorr.cc
* @Author Bacpfsec Rick
* @date 20150416
* @brief Implementation of TimelineHor Class
*
* TimelineHor is concrete implementation for Timeline Interface
*/
#include "TimelineHor.h"
void TimelineHor::timeline(std::ostream& os, std::vector<Task>& ts,
Date s, Date e, Date st, Date en) {
timelineHor(os,ts,s,e,st,en);
}
void TimelineHor::timelineHor(std::ostream& os, std::vector<Task>& ts,
Date s, Date e, Date st, Date en) {
// print title and date
os<<std::left<<std::setw(15)<<"Task\\Date";
int last = (en.getValue()>e.getValue()) ? e.getValue() : en.getValue();
Date d(s);
for (int i=d.getValue(); i<=last; i=d.getValue()) {
Date::printDay(os,Date(i),15);
d.nextDate();
}
os<<std::endl;
// print title and states
for (int k=0; k<ts.size(); k++) {
os<<std::left<<std::setw(15)<<ts[k].getTaskName();
d = s;
int curr = 0;
for(int i=d.getValue(); i<=last; i=d.getValue()) {
if (Date(i)==ts[k].getStates()[curr].getDate()) {
os<<std::left<<std::setw(15)<<ts[k].getStates()[curr].getContent();
curr++;
} else {
os<<std::setw(15)<<"";
}
d.nextDate();
}
os<<std::endl;
}
}
| true |
b8e982d15fb19a02cfc90d6a7fc1bfbc37c62a43
|
C++
|
ljt141421/DataStructure
|
/sequenceList/sequence.cpp
|
GB18030
| 9,071 | 3.328125 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#define SEQLIST_INIT_SIZE 8//ʼռ
#define INC_SIZE 4//ռ
typedef int ElemType;
//ṹ
typedef struct SeqList
{
ElemType *base; //Ŀռ
int capacity; //
int size; //ĴС
}SeqList;
//Ϊ
void InitList(SeqList *list);
bool Inc(SeqList *list);
void push_back(SeqList *list,ElemType x);
void show_list(SeqList *list);
void push_front(SeqList *list,ElemType x);
void pop_back(SeqList *list);
void pop_front(SeqList *list);
void insert_pos(SeqList *list,ElemType x,int p);
int find(SeqList *list,ElemType x);
int length(SeqList *list);
void delete_pos(SeqList *list,int p);
void delete_val(SeqList *list,int x);
void sort(SeqList *list);
void reverse(SeqList *list);
void clear(SeqList *list);
void destory(SeqList *list);
void emerge(SeqList *mylist,SeqList *youlist,SeqList *list);
//Ŀ
void main()
{
SeqList mylist,youlist,list;
//ʼ
InitList(&mylist);
InitList(&youlist);
//β
push_back(&mylist,1);
push_back(&mylist,3);
push_back(&mylist,5);
push_back(&mylist,7);
push_back(&mylist,9);
push_back(&youlist,2);
push_back(&youlist,4);
push_back(&youlist,6);
push_back(&youlist,8);
push_back(&youlist,10);
emerge(&mylist,&youlist,&list);
show_list(&list);
}
//ϲ
void emerge(SeqList *mylist,SeqList *youlist,SeqList *list)
{ //listĿռΪûlistyoulistռ֮
list->capacity=mylist->size+youlist->size;
list->base=(ElemType*)malloc(sizeof(ElemType)*list->capacity);
assert(list->base != NULL);
int m=0;
int y=0;
int l=0;
//й鲢
while(m<mylist->size && y<youlist->size)
{
if(mylist->base[m]<youlist->base[y])
list->base[l++]=mylist->base[m++];
else
list->base[l++]=youlist->base[y++];
}
//mylistʣԪ
while(m<mylist->size)
{
list->base[l++]=mylist->base[m++];
}
//youlistʣԪ
while(y<youlist->size)
{
list->base[l++]=youlist->base[y++];
}
//listСΪС֮
list->size=mylist->size+youlist->size;
}
//ʼ˳
void InitList(SeqList *list)
{
list->base=(ElemType *)malloc(sizeof(ElemType) * SEQLIST_INIT_SIZE);
assert(list->base != NULL);
list->capacity=SEQLIST_INIT_SIZE;
list->size=0;
}
//ռڴ治ٷ
bool Inc(SeqList *list)
{
ElemType *newBase=(ElemType*)realloc(list->base,sizeof(ElemType)*(list->capacity+INC_SIZE));
if(newBase == NULL)
{
printf("ڴռ䲻㣬ռ\n");
return false;
}
list->base=newBase;
list->capacity+=INC_SIZE;
return true;
}
//1:β˳
void push_back(SeqList *list,ElemType x)
{
if(list->size >= list->capacity && !Inc(list))
{
printf("ռ%dβ\n",x);
return;
}
list->base[list->size]=x;
list->size++;
}
//3:ʾ˳
void show_list(SeqList *list)
{
if(list->size == 0)
{
printf("˱Ŀǰûݿɹʾ\n");
return;
}
for(int i=0;i<list->size;i++)
{
printf("%d ",list->base[i]);
}
printf("\n");
}
//
/*
void main()
{
SeqList mylist;
InitList(&mylist);
int item;
int pos;
int leng;
int select=1;
while(select)
{
printf("**********************************\n");
printf("* [1]push_back [2]push_front *\n");
printf("* [3]show_list [4]pop_back *\n");
printf("* [5]pop_front [6]insert_pos *\n");
printf("* [7]find [8]length *\n");
printf("* [9]delete_pos [10]delete_val *\n");
printf("* [11]sort [12]reverse *\n");
printf("* [13]clear [14*]destory *\n");
printf("* [0]quit_system *\n");
printf("**********************************\n");
printf("ѡ->");
scanf("%d",&select);
if(select==0)
break;
switch(select)
{
case 1:
printf("Ҫ(-1):\n");
while(scanf("%d",&item),item!=-1)
{
push_back(&mylist,item);
}
break;
case 2:
printf("Ҫ(-1):\n");
while(scanf("%d",&item),item!=-1)
{
push_front(&mylist,item);
}
break;
case 3:
show_list(&mylist);
break;
case 4:
pop_back(&mylist);
break;
case 5:
pop_front(&mylist);
break;
case 6:
printf("ݣ\n");
scanf("%d",&item);
printf("λã\n");
scanf("%d",&pos);
insert_pos(&mylist,item,pos);
break;
case 7:
printf("ҵݣ\n");
scanf("%d",&item);
pos=find(&mylist,item);
if(pos != -1)
printf("ҵ%d%d±λ\n",item,pos);
else
printf("ҵ%dڵǰв\n",item);
break;
case 8:
leng=length(&mylist);
printf("ijΪ%d\n",leng);
break;
case 9:
printf("ɾλ: ");
scanf("%d",&pos);
delete_pos(&mylist,pos);
break;
case 10:
printf("ɾݣ");
scanf("%d",&item);
delete_val(&mylist,item);
break;
case 11:
sort(&mylist);
break;
case 12:
reverse(&mylist);
break;
case 13:
clear(&mylist);
break;
default:
printf("룡\n");
break;
}
}
destory(&mylist);
}
//ʼ˳
void InitList(SeqList *list)
{
list->base=(ElemType *)malloc(sizeof(ElemType) * SEQLIST_INIT_SIZE);
assert(list->base != NULL);
list->capacity=SEQLIST_INIT_SIZE;
list->size=0;
}
//ռڴ治ٷ
bool Inc(SeqList *list)
{
ElemType *newBase=(ElemType*)realloc(list->base,sizeof(ElemType)*(list->capacity+INC_SIZE));
if(newBase == NULL)
{
printf("ڴռ䲻㣬ռ\n");
return false;
}
list->base=newBase;
list->capacity+=INC_SIZE;
return true;
}
//1:β˳
void push_back(SeqList *list,ElemType x)
{
if(list->size >= list->capacity && !Inc(list))
{
printf("ռ%dβ\n",x);
return;
}
list->base[list->size]=x;
list->size++;
}
//3:ʾ˳
void show_list(SeqList *list)
{
if(list->size == 0)
{
printf("˱Ŀǰûݿɹʾ\n");
return;
}
for(int i=0;i<list->size;i++)
{
printf("%d ",list->base[i]);
}
printf("\n");
}
//2:ͷԪ
void push_front(SeqList *list,ElemType x)
{
if(list->size >= list->capacity && !Inc(list))
{
printf("ռ%dβ",x);
return;
}
for(int i=list->size;i>0;i--)
{
list->base[i]=list->base[i-1];
}
list->base[0]=x;
list->size++;
}
//βɾԪ
void pop_back(SeqList *list)
{
if(list->size == 0)
{
printf("Բ𣬴˱ѿգɾԪ\n");
return;
}
list->size--;
}
//ͷɾɾ
void pop_front(SeqList *list)
{
if(list->size == 0)
{
printf("Բ𣬴˱ѿգɾԪ\n");
return;
}
for(int i=0;i<list->size-1;i++)
{
list->base[i]=list->base[i+1];
}
list->size--;
}
//λò
void insert_pos(SeqList *list,ElemType x,int p)
{
if(p<0 || p>list->size)
{
printf("λ÷Ƿ,ܲ");
return;
}
if(list->size>list->capacity && !Inc(list))
{
printf("˱,%d%dλò",x,p);
return;
}
// if(p==0)
// push_front(list,p);
// else if(p==list->size)
// push_back(list,p);
// else
// {
for(int i=list->size;i>p;i--)
{
list->base[i]=list->base[i-1];
}
list->base[p]=x;
list->size++;
}
//
int find(SeqList *list,ElemType x)
{
for(int i=0;i<list->size;i++)
{
if(list->base[i]==x)
return i;
}
return -1;
}
//
int length(SeqList *list)
{
return list->size;
}
//λɾ
void delete_pos(SeqList *list,int p)
{
if(p<0 || p>=list->size)
{
printf("Բɾ%dλ÷Ƿ\n",p);
return;
}
for(int i=p;i<list->size-1;i++)
{
list->base[i]=list->base[i+1];
}
list->size--;
}
//ֵɾ
void delete_val(SeqList *list,int x)
{
int pos=find(list,x);
if(pos == -1)
{
printf("Ҫɾ%d\n",x);
return;
}
delete_pos(list,pos);
}
//ʹð
void sort(SeqList *list)
{
for(int i=0;i<list->size-1;i++)
{
for(int j=0;j<list->size-i-1;j++)
{
if(list->base[j]>list->base[j+1])
{
int temp=list->base[j];
list->base[j]=list->base[j+1];
list->base[j+1]=temp;
}
}
}
}
//ķת
void reverse(SeqList *list)
{
if(list->size==0 || list->size==1)
{
printf("û㹻ת\n");
return;
}
int low=0;
int high=list->size-1;
ElemType temp;
while(low<high)
{
temp=list->base[high];
list->base[high]=list->base[low];
list->base[low]=temp;
low++;
high--;
}
}
//
void clear(SeqList *list)
{
list->size=0;
printf("Ѿ\n");
}
//Ĵݻ
void destory(SeqList *list)
{
free(list->base);
list->base=NULL;
list->capacity=0;
list->size=0;
printf("Ѿݻ\n");
}
*/
| true |
d6260498c8da353135490ae1308cd9d6771d73d6
|
C++
|
BUPTxuxiangzi/xxz_leetcode
|
/leetcode_4_MedianofTwoSortedArray.cpp
|
UTF-8
| 3,853 | 4.21875 | 4 |
[] |
no_license
|
/*
Median of Two Sorted Arrays
Total Accepted: 43715 Total Submissions: 244807
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays. The overall run time
complexity should be O(log (m+n)).
Tags: divide and conquer, array, binary search
*/
//这是一道非常经典的题。这题更通用的形式是,给定两个已经排序好的数组,
//找到两者所有元素中第k 大的元素
/*法1:直接归并,时间复杂度O(m+n), 空间复杂度O(m+n)
Runtime: 57 ms
虽然可以Accepted,但是明显不符合最优O(logn)的解法
*/
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
vector<int> tmp;
int i = 0, j = 0;
while (i != m && j != n)
{
if (A[i] <= B[j])
{
tmp.push_back(A[i++]);
}
else
{
tmp.push_back(B[j++]);
}
}//while
while (i != m)
{
tmp.push_back(A[i++]);
}
while (j != n)
{
tmp.push_back(B[j++]);
}
if ((m + n) % 2)//m+n是奇数
{
return (double)tmp[(m + n) / 2];
}
else
{
return ((double)tmp[(m + n) / 2 - 1] + (double)tmp[(m + n) / 2]) / 2;
}
}
};
/*法2:
我们可以考虑从k 入手。如果我们每次都能够删除一个一定在第k 大元
素之前的元素,那么我们需要进行k 次。但是如果每次我们都删除一半呢?由于A 和B 都是有序
的,我们应该充分利用这里面的信息,类似于二分查找,也是充分利用了“有序”。
假设A 和B 的元素个数都大于k/2,我们将A 的第k/2 个元素(即A[k/2-1])和B 的第k/2
个元素(即B[k/2-1])进行比较,有以下三种情况(为了简化这里先假设k 为偶数,所得到的结
论对于k 是奇数也是成立的):
• A[k/2-1] == B[k/2-1]
• A[k/2-1] > B[k/2-1]
• A[k/2-1] < B[k/2-1]
如果A[k/2-1] < B[k/2-1],意味着A[0] 到A[k/2-1 的肯定在A [ B 的top k 元素的范围
内,换句话说,A[k/2-1 不可能大于A [ B 的第k 大元素。留给读者证明。
因此,我们可以放心的删除A 数组的这k/2 个元素。同理,当A[k/2-1] > B[k/2-1] 时,可
以删除B 数组的k/2 个元素。
当A[k/2-1] == B[k/2-1] 时,说明找到了第k 大的元素,直接返回A[k/2-1] 或B[k/2-1]
即可。
因此,我们可以写一个递归函数。那么函数什么时候应该终止呢?
• 当A 或B 是空时,直接返回B[k-1] 或A[k-1];
• 当k=1 是,返回min(A[0], B[0]);
• 当A[k/2-1] == B[k/2-1] 时,返回A[k/2-1] 或B[k/2-1]
*///Runtime: 50 ms
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int total = m + n;
if (total & 0x1)// k&0x1计算时先将k变成********八位数据 然后再和0x01相位与,
{ //目的就是将k的高七位变成0,及屏蔽,得到k的最低位(是0还是1)
return find_kth(A, m, B, n, total / 2 + 1);
}
else
{
return (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n, total / 2 + 1)) / 2;
}
}
private:
static double find_kth(int A[], int m, int B[], int n, int k)
{
//always assume that m is equal or smaller than n
//即前一个数组的长度小于或等于后一个数组的长度
if (m > n)
return find_kth(B, n, A, m, k);
if (m == 0) //即前一个数组是空数组
return B[k - 1];
if (k == 1)//要查找的事第一个(即要查找最小的)
return min(A[0], B[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
if (A[pa - 1] < B[pb - 1])//意味着A[0]到A[pa-1]区间的数肯定不在AUB的前k个元素范围内
return find_kth(A + pa, m - pa, B, n, k - pa);
else if (A[pa - 1] > B[pb - 1])//意味着B[0]到B[pb-1]区间的数肯定不在AUB的前k个元素范围内
return find_kth(A, m, B + pb, n - pb, k - pb);
else
return A[pa - 1];//找到了要查找的元素
}
};
| true |
328f4f6cc6db8a964d6ea8c75859b6e607e88cf6
|
C++
|
yquemener/ModelKeynes
|
/src/bot.h
|
UTF-8
| 1,563 | 3 | 3 |
[] |
no_license
|
#ifndef BOT_H
#define BOT_H
#include <string>
#include <list>
#include <map>
#include "types.h"
#include "market.h"
#include "good.h"
namespace Econ{
class IndustrialNode;
/// Bot simulates an economical agent. It "lives" in an IndustrialNode and has
/// access to the markets the industrial node is linked to. There are usually
/// numerous agents in competition inside an industrial node. If an agent's cash
/// is below zero, it is considered bankrupted and removed from the simulation
class Bot
{
public:
Bot(IndustrialNode* home);
/// Reads new information from the IndustrialNode
virtual void updateInfo() = 0;
/// generates buying/selling orders
virtual std::list<order> makeTradingDecisions() = 0;
/// generates processing orders. Only a float is necessary : only one kind
/// of goods can be processed
virtual float makeProcessingDecisions() = 0;
virtual bool isBankrupt() {return cash<0; }
agent_id getId() {return m_id;}
// These are public : industrialNode needs to write to them and other actors
// can read them
float cash;
std::map<good_t, float> stock;
// This allows to automatically attribute a unique id to a bot and to easily
// find a bot from its id
static std::map<agent_id, Bot*>* s_idTable()
{
static map<agent_id, Bot*> idTable;
return &idTable;
}
static agent_id s_newId()
{
static agent_id currentId=0;
return currentId++;
}
std::string displayStock();
protected:
agent_id m_id;
IndustrialNode* m_home;
};
}
#endif // BOT_H
| true |
c6d239d4defa97d7cfb5de33bd68de591cdd2cf3
|
C++
|
jtlai0921/PG20045_example
|
/pg20045日文原始程式碼/chap15/stack.h
|
SHIFT_JIS
| 1,154 | 3.515625 | 4 |
[] |
no_license
|
//----------------------------------------------------------------------------//
// X^bNNXev[g Stack "stack.h" //
//----------------------------------------------------------------------------//
//===== X^bNNXev[g =====//
template <class Type> class Stack {
private:
int size; // z̗vf
Type* ptr; // 擪vfւ̃|C^
Type* top; // X^bN|C^
Stack(const Stack&); // Rs[RXgN^
Stack& operator=(const Stack&); // Zq
public:
//----- X^bÑ|bvɑO -----//
class EmptyErr {
private:
Stack* ident;
public:
EmptyErr(Stack* p) : ident(p) { }
Stack* Ptr(void) { return (ident); }
};
Stack(int sz) { ptr = top = new Type[size = sz]; }
~Stack(void) { delete[] ptr; }
int Push(const Type &x) { // vbV
if (ptr - top < size) {
*top++ = x;
return (1);
}
return (0);
}
Type Pop(void) { // |bv
if (top <= ptr)
throw EmptyErr(this); // G[o
return (*--top);
}
};
| true |
e1870fd5c29882d2b96f7bf0a95dd17cb6e17960
|
C++
|
rubaiyat6370/Accepted-Solutions
|
/UVA/11624-Fire!.cpp
|
UTF-8
| 3,537 | 2.984375 | 3 |
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#define S 1001
using namespace std;
struct point {
int x;
int y;
int dis;
};
char input[S][S];
int fireVisited[S][S];
int joeVisited[S][S];
int R, C;
int minimum;
point queue[1000002];
int first, last;
void initData() {
minimum = 999999999;
for (int i = 0;i < R;i++) {
for (int j = 0;j < C;j++) {
input[i][j] = ' ';
fireVisited[i][j] = 0;
joeVisited[i][j] = 0;
}
}
}
void initArr() {
first = 0, last = -1;
for (int i = 0;i < R*C;i++) {
queue[i].x = 0;
queue[i].y = 0;
queue[i].dis = 0;
}
}
void push(int x,int y,int dis) {
++last;
queue[last].x = x;
queue[last].y = y;
queue[last].dis = dis;
}
point pop() {
return queue[first++];
}
void joe(int i, int j, int dis) {
push(i, j, dis);
joeVisited[i][j] = 1;
while (first <= last) {
point p = pop();
dis = p.dis + 1;
if ((p.x == R - 1 && p.y <= C) || (p.x <= R && p.y == C - 1) || (p.x==0 && p.y>=0) || (p.x>=0 && p.y==0)) {
if (dis <= minimum) {
minimum = dis;
}
break;
}
if (input[p.x][p.y + 1] == '.' && (fireVisited[p.x][p.y + 1] > dis || fireVisited[p.x][p.y + 1]==0) && joeVisited[p.x][p.y + 1]==0) {
push(p.x, p.y + 1, dis);
joeVisited[p.x][p.y + 1] = dis;
}
if (input[p.x][p.y - 1] == '.' && joeVisited[p.x][p.y - 1] == 0 && (fireVisited[p.x][p.y - 1]>dis || fireVisited[p.x][p.y - 1]==0)) {
push(p.x, p.y - 1, dis);
joeVisited[p.x][p.y - 1] = dis;
}
if (input[p.x + 1][p.y] == '.' && joeVisited[p.x + 1][p.y] == 0 && (fireVisited[p.x + 1][p.y] > dis || fireVisited[p.x + 1][p.y]==0)) {
push(p.x + 1, p.y, dis);
joeVisited[p.x + 1][p.y] = dis;
}
if (input[p.x - 1][p.y] == '.' && joeVisited[p.x - 1][p.y] == 0 && (fireVisited[p.x - 1][p.y] > dis || fireVisited[p.x - 1][p.y]==0)) {
push(p.x - 1, p.y, dis);
joeVisited[p.x - 1][p.y] = dis;
}
}
}
void fire() {
int dis;
while (first <= last) {
point p = pop();
dis = p.dis+1;
if ((input[p.x][p.y + 1] == '.' || input[p.x][p.y + 1] == 'J') && fireVisited[p.x][p.y + 1]==0) {
push(p.x, p.y + 1,dis);
fireVisited[p.x][p.y + 1] = dis;
}
if ((input[p.x][p.y - 1] == '.' || input[p.x][p.y - 1] == 'J') && fireVisited[p.x][p.y - 1] == 0) {
push(p.x, p.y - 1,dis);
fireVisited[p.x][p.y - 1] = dis;
}
if ((input[p.x + 1][p.y] == '.' || input[p.x + 1][p.y] =='J') && fireVisited[p.x + 1][p.y] == 0) {
push(p.x + 1, p.y,dis);
fireVisited[p.x + 1][p.y] = dis;
}
if ((input[p.x - 1][p.y] == '.' || input[p.x - 1][p.y] == 'J' )&& fireVisited[p.x - 1][p.y] == 0) {
push(p.x - 1, p.y,dis);
fireVisited[p.x - 1][p.y] = dis;
}
}
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt","w", stdout);
int T, jx,jy,fx,fy;
jx = jy = fx = fy = -1;
cin >> T;
for (int i = 1;i <= T;i++) {
cin >> R >> C;
initData();
initArr();
char c;
for (int j = 0;j < R;j++) {
for (int k = 0;k < C;k++) {
cin >> c;
if (c == '#') {
input[j][k] = c;
fireVisited[j][k] = -1;
joeVisited[j][k] = -1;
}
else if (c == '.') {
input[j][k] = c;
}
else if (c == 'J'){
input[j][k] = c;
jx = j;
jy = k;
}
else if (c == 'F') {
input[j][k] = c;
fx = j;
fy = k;
push(fx, fy,0);
fireVisited[j][k] = 1;
}
}
}
if (fx != -1) {
fire();
initArr();
joe(jx, jy, 0);
}
else {
joe(jx, jy, 0);
}
if (minimum < 999999999) {
cout << minimum << endl;
}
else
cout << "IMPOSSIBLE" << endl;
}
return 0;
}
| true |
d646ff45c356031e1c878ec53b0ecb13890f8b1a
|
C++
|
estebanpw/repkiller
|
/src/SequenceOcupationList.cpp
|
UTF-8
| 2,959 | 3.125 | 3 |
[] |
no_license
|
#include "SequenceOcupationList.h"
SequenceOcupationList::SequenceOcupationList(double len_ratio, double pos_ratio, uint64_t seq_size)
: len_ratio(len_ratio), pos_ratio(pos_ratio), max_index(seq_size / DIVISOR),
ocupations(new forward_list<SequenceOcupationList::Ocupation>*[max_index + 1]) {
for (size_t i = 0; i < max_index + 1; i++)
ocupations[i] = new forward_list<Ocupation>();
}
SequenceOcupationList::~SequenceOcupationList() {
for (size_t i = 0; i < max_index + 1; i++)
delete ocupations[i];
delete[] ocupations;
}
const forward_list<SequenceOcupationList::Ocupation> * SequenceOcupationList::get_suitable_indices(uint64_t center) const {
return ocupations[center / DIVISOR];
}
double SequenceOcupationList::deviation(SequenceOcupationList::Ocupation oc, uint64_t center, uint64_t length) const {
uint64_t dif_len = length > oc.length ? length - oc.length : oc.length - length;
// Linear transformation of dif len so 0 is TOO OUT and 1 is EXACT MATCH
auto sim_len = -fabs(dif_len / (length * len_ratio)) + 1.0;
if (sim_len < 0) return 0.0;
uint64_t dif_cen = center > oc.center ? center - oc.center : oc.center - center;
// Linear transformation of dif pos so 0 is TOO DEVIATED and 1 is EXACT MATCH
auto sim_pos = -fabs(dif_cen / (length * pos_ratio)) + 1.0;
if (sim_pos < 0) return 0.0;
return sim_len * 0.4 + sim_pos * 0.6;
}
FragsGroup * SequenceOcupationList::get_associated_group(uint64_t center, uint64_t length) const {
FragsGroup * fg = nullptr;
double d = 0;
{
auto sind = get_suitable_indices(center);
for (auto oc : *sind) {
double curr_dev = deviation(oc, center, length);
if (curr_dev > d) {
d = curr_dev;
fg = oc.group;
}
}
}
if (center > 0) {
auto sind = get_suitable_indices(center - 1);
for (auto oc : *sind) {
double curr_dev = deviation(oc, center, length);
if (curr_dev > d) {
d = curr_dev;
fg = oc.group;
}
}
}
if (center < max_index) {
auto sind = get_suitable_indices(center + 1);
for (auto oc : *sind) {
double curr_dev = deviation(oc, center, length);
if (curr_dev > d) {
d = curr_dev;
fg = oc.group;
}
}
}
if (center > 1) {
auto sind = get_suitable_indices(center - 2);
for (auto oc : *sind) {
double curr_dev = deviation(oc, center, length);
if (curr_dev > d) {
d = curr_dev;
fg = oc.group;
}
}
}
if (center < max_index - 1) {
auto sind = get_suitable_indices(center + 2);
for (auto oc : *sind) {
double curr_dev = deviation(oc, center, length);
if (curr_dev > d) {
d = curr_dev;
fg = oc.group;
}
}
}
return fg;
}
void SequenceOcupationList::insert(uint64_t center, uint64_t length, FragsGroup * group) {
SequenceOcupationList::Ocupation noc(center, length, group);
ocupations[center / DIVISOR]->push_front(noc);
}
| true |
9d7be7909c2521a48d956477b588292829c9423e
|
C++
|
joshua-lucier/Apriori
|
/FinalProject/main.cpp
|
UTF-8
| 909 | 2.96875 | 3 |
[] |
no_license
|
/* ***
* Changed: Joshua Lucier & Ryan Moss
* Last Update: December 5, 2014
* Class: CSI-281
* Filename: main.cpp
*
* Description:
* main logic of program
*
* Certification of Authenticity:
* I certify that changes to this assignment are entirely my own work.
**********************************************************************/
#include "header.h"
void main()
{
/*
DDLinkedList<int>* ddlinkedlist = new DDLinkedList<int>;
for (int i = 0; i < 10; i++)
{
ddlinkedlist->insert(i);
}
ddlinkedlist->display();
ddlinkedlist->removeAt(5);
ddlinkedlist->display();
system("pause");
delete ddlinkedlist;
*/
//database with 1000 transactions, an average of 4 items per transaction with 1000 distinct items at a confidence of .05
Database<int>* database = new Database<int>(10000, 10, 1000, 5);
database->load();
database->apriori(5);
system("pause");
delete database;
}
| true |
4c3a34f53572420a444cd572f740f86b0ef60d15
|
C++
|
Rbtsv2/training
|
/Arme.h
|
UTF-8
| 280 | 2.65625 | 3 |
[] |
no_license
|
#pragma once
#include "Arme.h"
#include <string>
class Arme
{
public:
Arme(); // constructor par default
Arme(std::string nameArme, int degatsArme);
int getDegats() const;
void changer(std::string nom, int degats);
private:
std::string m_name;
int m_degats;
};
| true |
bd837eb4d49559687f2df09c433fd1ce04edd0e8
|
C++
|
patilatp/MS-Projects
|
/proj 6(ameyp)/headsUpDisplay.cpp
|
UTF-8
| 2,114 | 2.640625 | 3 |
[] |
no_license
|
#include "headsUpDisplay.h"
#include <iostream>
#include <string>
#include <iomanip>
#include "gamedata.h"
#include "aaline.h"
HeadsUpDisplay::HeadsUpDisplay() :
HUD_WIDTH(Gamedata::getInstance().getXmlInt("hud/HUD_WIDTH")),
HUD_HEIGHT(Gamedata::getInstance().getXmlInt("hud/HUD_HEIGHT")),
x(8),
y(8),
secondsLocation(10,20),
fpsLocation(10,40),
playerMovementLocation(10,60),
toggleHUDLocation(10,80),
restartGameLocation(10,100),
laserListLocation(10,120),
freeListLocation(10,140),
shootinginfolocation(10,160),
playergoal(10,180),
playergoalextend(10,200)
{}
void HeadsUpDisplay::drawHUD(SDL_Surface * const& screen, const IOManager& io,int seconds,int fps , unsigned int laserCount , unsigned freeCount) const{
const Uint32 RED = SDL_MapRGB(screen->format, 0xff, 0, 0);
Draw_AALine(screen, x, y+HUD_HEIGHT/2, x+HUD_WIDTH, y+HUD_HEIGHT/2, HUD_HEIGHT, 0xff, 0xff, 0xff, 0xff/2);
io.printMessageValueAt("Seconds: ", seconds, secondsLocation[0], secondsLocation[1]);
io.printMessageValueAt("fps: ", fps, fpsLocation[0], fpsLocation[1]);
io.printMessageAt("Use WASD to control the player.", playerMovementLocation[0], playerMovementLocation[1]);
io.printMessageAt("Press F1 to toggle HUD.", toggleHUDLocation[0], toggleHUDLocation[1]);
io.printMessageAt("Press R to restart the game.", restartGameLocation[0], restartGameLocation[1]);
io.printMessageValueAt("Laser List Count: ", laserCount, laserListLocation[0], laserListLocation[1]);
io.printMessageValueAt("Free List Count: ", freeCount, freeListLocation[0], freeListLocation[1]);
io.printMessageAt("Use Space Bar to shoot",shootinginfolocation[0],shootinginfolocation[1]);
io.printMessageAt("Goal: To Shoot the Asteroid &",playergoal[0],playergoal[1]);
io.printMessageAt("earn as much points as you can",playergoalextend[0],playergoalextend[1]);
Draw_AALine(screen, x,y, x+HUD_WIDTH,y, RED);
Draw_AALine(screen, x,y, x,y+HUD_HEIGHT, RED);
Draw_AALine(screen, x,y+HUD_HEIGHT, x+HUD_WIDTH,y+HUD_HEIGHT, RED);
Draw_AALine(screen, x+HUD_WIDTH,y, x+HUD_WIDTH,y+HUD_HEIGHT, RED);
}
| true |
ac0b8aa2a2cda5624a97c38f4a986e0e4353558c
|
C++
|
kogotto/experiments
|
/cpp/018_vector_initialization/main.cpp
|
UTF-8
| 349 | 3.359375 | 3 |
[] |
no_license
|
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct Foo {
vector<string> v;
int a;
};
void print(const Foo& f) {
cout << "print" << endl;
for (const auto s : f.v) {
cout << s << endl;
}
cout << "a = " << f.a << endl;
}
int main() {
Foo v{{"some", "text"}, 10};
print(v);
}
| true |
54733f7532998e8d29d5a4ec686e1fee5140223d
|
C++
|
0xekez/lox-cpp
|
/src/token.h
|
UTF-8
| 1,543 | 2.9375 | 3 |
[] |
no_license
|
// the parser generates tokens. a token has a type, data, a lexme, and a line.
// the type informs how the data should be interpreted later.
#ifndef token_h
#define token_h
#include <memory> // std::unique_ptr
#include <optional> // std::optional
#include <string>
#include <unordered_map>
#include "token_type.h"
#include "val.h"
std::ostream &operator<<(std::ostream &o, loxc::token_type n);
namespace loxc
{
/**
* A token in loxc.
*
* TODO: the current representation of data does not work.
*/
struct token
{
loxc::token_type type;
std::optional<Val> data;
std::string lexme;
int line;
token(loxc::token_type t, Val d, std::string lex, int l)
: type(t), data(std::move(d)), lexme(std::move(lex)), line(l) {}
friend std::ostream &operator<<(std::ostream &os, const loxc::token &tok)
{
return os << "'" << tok.lexme << "'";
}
};
const std::unordered_map<std::string, loxc::token_type> keywords_map =
{
{"and", loxc::AND},
{"abort", loxc::ABORT},
{"or", loxc::OR},
{"if", loxc::IF},
{"else", loxc::ELSE},
{"class", loxc::CLASS},
{"true", loxc::TRUE},
{"false", loxc::FALSE},
{"fun", loxc::FUN},
{"anon", loxc::ANON},
{"for", loxc::FOR},
{"nil", loxc::NIL},
{"or", loxc::OR},
{"print", loxc::PRINT},
{"return", loxc::RETURN},
{"super", loxc::SUPER},
{"this", loxc::THIS},
{"var", loxc::VAR},
{"while", loxc::WHILE}};
} // namespace loxc
#endif
| true |
945ac59d7d4a68752b66a0479a5a8f85d83376f8
|
C++
|
yuyaushiro/pfc_simulator
|
/src/avoidance.cpp
|
UTF-8
| 1,984 | 3.015625 | 3 |
[] |
no_license
|
#include "avoidance.h"
// コンストラクタ
//------------------------------------------------------------------------------
Avoidance::Avoidance()
{}
// コンストラクタ
//------------------------------------------------------------------------------
Avoidance::Avoidance(double weight, double maxWeight, double decreaseTime)
: weight_(weight)
, minWeight_(1.0)
, maxWeight_(maxWeight)
, decreaseTime_(decreaseTime)
{}
// 重みの取得
//------------------------------------------------------------------------------
double Avoidance::getWeight()
{
double weight;
// 現在の重みと最新の候補から大きい方を重みとして返す
(weightCandidates_.size() > 0) ?
weight = std::max(weight_, weightCandidates_.back()) :
weight = weight_;
return weight;
}
// 重み候補の追加
//------------------------------------------------------------------------------
void Avoidance::addWeightCandidate(double reward)
{
// 報酬が通常の遷移より小さい?
(reward < -0.5) ?
weightCandidates_.push_back(maxWeight_) :
weightCandidates_.push_back(minWeight_);
}
// 重みの更新
//------------------------------------------------------------------------------
void Avoidance::updateWeight(int candidateIndex)
{
if (weightCandidates_.size() != 0)
{
std::vector<double>::iterator maxIterator =
std::max_element(weightCandidates_.begin(), weightCandidates_.end());
weight_ = std::max(weight_, *maxIterator);
weightCandidates_.resize(0);
}
// weight_ = std::max(weight_, weightCandidates_[candidateIndex]);
// weightCandidates_.resize(0);
}
// 重みの減少
//------------------------------------------------------------------------------
void Avoidance::decreaseWeight(double dt)
{
// 減少値
double decreaseValue = (maxWeight_ - minWeight_) * dt / decreaseTime_;
if (weight_ > minWeight_)
weight_ -= decreaseValue;
if (weight_ < minWeight_)
weight_ = minWeight_;
}
| true |
f4f1921dee51e99d554f8c5e94b1b3437e117f44
|
C++
|
vw2243564/WaltonVeronica_CIS5_44188
|
/Homework/Assignment _4/Gladdis_8thEd_Chap5_Prob13_Greatest/main.cpp
|
UTF-8
| 1,117 | 3.875 | 4 |
[] |
no_license
|
/*
File: main.cpp
Author: Veronica Walton
Created on April 2, 2017, 5:30 PM
Purpose: Determine the greatest and least numbers
*/
//System Libraries
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
//Such as PI, Vc, -> Math/Science values
//as well as conversions from system of units to
//another
//Function Prototypes
//Executable code begins here!!!
int main(int argc, char** argv) {
//Declare Variables
int num;//User input
int big=-999999,small=999999;//largest and smallest numbers
cout<<"This program will print the least and greatest "
"number from numbers of your choice."<<endl;
//Comparing numbers
while(num!=-99)
{
cout<<"Enter your numbers, -99 to stop. ";
cin>>num;
if(num==-99)
break;
if(num>big)
{
big=num;
}
if(num<small)
{
small=num;
}
}
//Output values
cout<<"The largest number is "<<big<<endl;
cout<<"The smallest number is "<<small<<endl;
//Exit stage right!
return 0;
}
| true |
76bc897133f7912faa69710cd65b616902b5afaf
|
C++
|
LeeSeongDong/DataStructure
|
/그래프/무방향그래프/AdjListNode.h
|
UTF-8
| 334 | 2.65625 | 3 |
[] |
no_license
|
#ifndef __ADJLISTNODE_H__
#define __ADJLISTNODE_H__
#include "Header.h"
class AdjListNode
{
private :
friend class AdjListGraph;
friend class DirectedAdjListGraph;
int data;
AdjListNode* link;
AdjListNode()
{
link = NULL;
}
AdjListNode(int data)
{
this->data = data;
link = NULL;
}
~AdjListNode() {};
};
#endif
| true |
5c7620ce87d89da918480a75f37effbb9a4bf95f
|
C++
|
BoyuGuan/DATASTRUCTURE
|
/Chapter_05_String/sourcecode/DSqStringTest.cpp
|
GB18030
| 1,139 | 2.796875 | 3 |
[] |
no_license
|
#include <iostream.h>
#include"DSqString.h"
int main() {
DSqString S1, S2, S3, S4;
StrAssign_Sq(S1, "child");
StrAssign_Sq(S2, "children");
StrAssign_Sq(S3, "chinese chair technology ");
StrAssign_Sq(S4, "");
StrCopy_Sq(S4, S1);
cout << "S4ƺֵΪ";
StrTraveres_Sq(S4);
if (StrCompare_Sq(S1, S2)>0) cout << "S1>S2" << endl;
else if (StrCompare_Sq(S1, S2) == 0) cout << "S1=S2" << endl;
else if (StrCompare_Sq(S1, S2)<0) cout << "S1<S2" << endl;
if (StrConcat_Sq(S3, S4)) {
cout << "S3S4ӳɹ\n" << endl;
StrTraveres_Sq(S3);
}
else {
cout << "ʧ" << endl;
}
if (SubString_Sq(S3, S4, 0, 4)) {
cout << "ȡӴɹ\nΪ" << endl;
StrTraveres_Sq(S4);
}
else {
cout << "ȡӴʧ" << endl;
}
StrAssign_Sq(S1, "ch");
StrAssign_Sq(S2, "abcd");
cout << "ûǰS3ֵΪ" << endl;
StrTraveres_Sq(S3);
StrReplace_Sq(S3, S1, S2);
cout << "ûS3ֵΪ";
StrTraveres_Sq(S3);
visualization(S3,"show.dot");
DestroyString_Sq(S1);
DestroyString_Sq(S2);
DestroyString_Sq(S3);
DestroyString_Sq(S4);
return 0;
}
| true |
ac4702322e9e6a476320b1bf36351eb027460eab
|
C++
|
liolliaustin/RAM_Mapper
|
/src/Solve.cpp
|
UTF-8
| 22,850 | 2.59375 | 3 |
[] |
no_license
|
#include "Solve.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include "math.h"
using namespace std;
//create vector for final file creation
void Solve::mapCircuit(vector<vector<int> > circuitDefs, vector<int> logicBlockCount){
vector<vector<int> > finalResult;
vector<int> RAM_map;
float logic_block_area, RAM_area, totalArea, areaSum;
vector<float> areaVector;
int bits = 0, max_width = 0, additionalLuts;
int circuit = circuitDefs[0][0], logic = logicBlockCount[0], RAM_ID, Mode, Depth, Width, newlogic = 0, RAM8count=0, RAM8used=0, RAM128count=0, RAM128used=0, LUTRAMcount = 0, LUTRAMused = 0;
int chose128 = 0, chose8 = 0, choseLUT = 0, count=0;
for(int i=0; i<circuitDefs.size(); i++){
if(circuit != circuitDefs[i][0]){
cout << "Circuit " << circuit << " original size: " << logic << endl << "New logic: " << newlogic << endl << "128k: " << RAM128used << endl << "8k: " << RAM8used << endl << "LUTRAM: " << LUTRAMused << endl;
cout << "Total Area: " << totalArea << endl << endl;
newlogic = logicBlockCount[circuit];
RAM8count=0;
RAM8used=0;
RAM128count=0;
RAM128used=0;
LUTRAMcount = 0;
LUTRAMused = 0;
circuit = circuitDefs[i][0];
logic = logicBlockCount[circuit];
}
count++;
RAM_ID = circuitDefs[i][1];
Mode = circuitDefs[i][2];
Depth = circuitDefs[i][3];
Width = circuitDefs[i][4];
int widthExponent = ceil(log2(Width));
int depthExponent = ceil(log2(Depth));
int multiplier = widthExponent + depthExponent;
vector<int> resultVector;
resultVector = returnLowest(newlogic, RAM8used, RAM128used, LUTRAMused, Mode, depthExponent, widthExponent, Width);
if(resultVector[0] == 2){
RAM8used = resultVector[1];
newlogic = resultVector[2];
additionalLuts = resultVector[3];
chose8++;
}
else if(resultVector[0] == 3){
RAM128used = resultVector[1];
newlogic = resultVector[2];
additionalLuts = resultVector[3];
chose128++;
}
else if(resultVector[0] == 1){
LUTRAMused = resultVector[1];
newlogic = resultVector[2];
additionalLuts = resultVector[3];
choseLUT++;
}
RAM_map.push_back(circuit);
RAM_map.push_back(RAM_ID);
RAM_map.push_back(additionalLuts);
RAM_map.push_back(Width);
RAM_map.push_back(Depth);
RAM_map.push_back(count);
RAM_map.push_back(resultVector[4]);
RAM_map.push_back(resultVector[5]);
RAM_map.push_back(resultVector[0]);
RAM_map.push_back(Mode);
RAM_map.push_back(resultVector[6]);
RAM_map.push_back(resultVector[7]);
finalResult.push_back(RAM_map);
RAM_map.clear();
resultVector.clear();
if(i == circuitDefs.size()-1){
cout << "Circuit " << circuit << " original size: " << logic << endl << "New logic: " << newlogic << endl << "128k: " << RAM128used << endl << "8k: " << RAM8used << endl << "LUTRAM: " << LUTRAMused << endl << endl;
}
}
this -> finalResult = finalResult;
cout << "128k: " << chose128 << endl << "8k: " << chose8 << endl << "LUTRAM: " << choseLUT << endl << "Total: " << count << endl;
}
//return lowest cost to implement on type of RAM (128, 8 LUTRAM)
vector<int> Solve::returnLowest(int currentLogic, int RAM8used, int RAM128used, int LUTRAMused, int mode, int depthExponent, int widthExponent, int Width){
vector<int> hit128, hit8, hitLUT, final;
int minimum, LUTcost = 999999999, RAM8cost, RAM128cost, RAM8add = 0, RAM128add = 0, LUTRAMadd = 0;
float RAM8available = floor(float(currentLogic)/10.0) - RAM8used;
float RAM128available = floor(float(currentLogic)/300.0) - RAM128used;
float LUTRAMavailable = float(currentLogic)/2.0 - LUTRAMused;
hit8 = RAM8kconfiguration(mode, depthExponent, widthExponent, Width);
hit128 = RAM128kconfiguration(mode, depthExponent, widthExponent, Width);
if(mode != 4){
hitLUT = LUTRAMconfiguration(mode, depthExponent, widthExponent, Width);
if(LUTRAMavailable >= hitLUT[0]){
LUTcost = hitLUT[1];
}
else{
LUTRAMadd = 2*(hitLUT[0] - LUTRAMavailable);
LUTcost = LUTRAMadd + hitLUT[1];
}
}
if(RAM8available >= hit8[0]){
RAM8cost = hit8[1];
}
else{
RAM8add = 10*(hit8[0] - RAM8available);
RAM8cost = RAM8add + hit8[1];
}
if(RAM128available >= hit128[0]){
RAM128cost = hit128[1];
}
else{
RAM128add = 300*(hit128[0] - RAM128available);
RAM128cost = RAM128add + hit128[1];
}
minimum = min(min(RAM8cost, RAM128cost), LUTcost);
if(mode != 4 && minimum == LUTcost){
final.push_back(1);
final.push_back(LUTRAMused + hitLUT[0]);
final.push_back(currentLogic + ceil(float(hitLUT[1])/10.0) + LUTRAMadd);
final.push_back(hitLUT[1]);
final.push_back(hitLUT[2]);
final.push_back(hitLUT[3]);
final.push_back(hitLUT[4]);
final.push_back(hitLUT[5]);
}
else if(minimum == RAM8cost){
final.push_back(2);
final.push_back(RAM8used + hit8[0]);
final.push_back(currentLogic + ceil(float(hit8[1])/10.0) + RAM8add);
final.push_back(hit8[1]);
final.push_back(hit8[2]);
final.push_back(hit8[3]);
final.push_back(hit8[4]);
final.push_back(hit8[5]);
}
else if (minimum == RAM128cost){
final.push_back(3);
final.push_back(RAM128used + hit128[0]);
final.push_back(currentLogic + ceil(float(hit128[1])/10.0) + RAM128add);
final.push_back(hit128[1]);
final.push_back(hit128[2]);
final.push_back(hit128[3]);
final.push_back(hit128[4]);
final.push_back(hit128[5]);
}
hit128.clear(); hit8.clear(); hitLUT.clear();
return final;
}
//Determine Hit, cost and other parameters of instantiated 8kRAM
vector<int> Solve::RAM8kconfiguration(int mode, int depthExponent, int widthExponent, int Width){
vector<int> solveData;
int depthHit=1, widthHit=1, hit = 0, widthSize=0, extraLogic=0, RAM8width, RAM8depth;
if(depthExponent + widthExponent <= 13 && widthExponent <= 5 && mode < 4 || depthExponent + widthExponent <= 13 && widthExponent <= 4 && mode == 4){
hit = 1;
if(widthExponent == 5 && mode < 4 || widthExponent == 4 && mode ==4 || depthExponent < 8 && mode < 4 || depthExponent < 9 && mode == 4){
RAM8width = pow(2.0,float(widthExponent));
RAM8depth = pow(2.0,float(13-widthExponent));
}
else if(widthExponent < 5 && depthExponent >= 8 && mode < 4 || widthExponent < 4 && depthExponent >= 9 && mode == 4){
RAM8width = pow(2.0,float(13-depthExponent));
RAM8depth = pow(2.0,float(depthExponent));
}
else{
if(mode < 4){
RAM8width = 32;
RAM8depth = 256;
}
else{
RAM8width = 16;
RAM8depth = 512;
}
}
}
else if(depthExponent <= 13 && depthExponent >= 8 && mode < 4 || depthExponent <= 13 && depthExponent >= 9 && mode == 4){
hit = ceil(float(Width)/float(pow(2,(13-depthExponent))));
widthHit = hit;
RAM8width = pow(2.0,float(13-depthExponent));
RAM8depth = pow(2,float(depthExponent));
}
else if(depthExponent < 8 && mode < 4 || depthExponent < 9 && mode == 4){
if(mode < 4){
hit = ceil(float(Width)/32.0);
RAM8depth = 256;
RAM8width = 32;
}
else{
hit = ceil(float(Width)/16.0);
RAM8depth = 512;
RAM8width = 16;
}
widthHit = hit;
}
else if(depthExponent > 13){
if(widthExponent <= 5 && mode < 4 || widthExponent<=4 && mode == 4){
hit = pow(2.0,float((depthExponent - (13 - widthExponent))));
depthHit = hit;
RAM8width = pow(2.0,float(widthExponent));
RAM8depth = pow(2.0, float(13 - widthExponent));
}
else if(widthExponent > 5 && mode < 4 || widthExponent > 4 && mode == 4){
depthHit = pow(2.0,float(depthExponent - 13));
widthHit = pow(2.0,float(widthExponent));
if(depthHit > 16)
hit = 99;
else
hit = depthHit*widthHit;
RAM8depth = 8192;
RAM8width = 1;
}
if(depthHit == 2)
extraLogic += 1;
else
extraLogic += depthHit;
//multiplexers
if(depthHit <=4)
extraLogic += 1*pow(2.0,float(widthExponent));
else if(depthHit <= 8)
extraLogic += 3*pow(2.0,float(widthExponent));
else if(depthHit <=16)
extraLogic += 5*pow(2.0,float(widthExponent));
else
extraLogic += 99*pow(2.0,float(widthExponent));
if(mode == 4)
extraLogic *=2;
}
solveData.push_back(hit);
solveData.push_back(extraLogic);
solveData.push_back(depthHit);
solveData.push_back(widthHit);
solveData.push_back(RAM8width);
solveData.push_back(RAM8depth);
return solveData;
}
//Determine Hit, cost and other parameters of instantiated 128kRAM
vector<int> Solve::RAM128kconfiguration(int mode, int depthExponent, int widthExponent, int Width){
vector<int> solveData;
int depthHit=1, widthHit=1, hit = 0, widthSize=0, extraLogic=0, RAM128width=0, RAM128depth=0;
if(depthExponent + widthExponent <= 17 && widthExponent <= 7 && mode < 4 || depthExponent + widthExponent <= 17 && widthExponent <= 6 && mode == 4){
hit = 1;
if(widthExponent == 7 && mode < 4 || widthExponent == 6 && mode ==4 || depthExponent < 10 && mode < 4 || depthExponent < 11 && mode == 4){
RAM128width = pow(2.0,float(widthExponent));
RAM128depth = pow(2.0,float(17-widthExponent));
}
else if(widthExponent < 7 && depthExponent >= 10 && mode < 4 || widthExponent < 6 && depthExponent >= 11 && mode == 4){
RAM128width = pow(2.0,float(17-depthExponent));
RAM128depth = pow(2.0,float(depthExponent));
}
else{
if(mode < 4){
RAM128width = 128;
RAM128depth = 1024;
}
else{
RAM128width = 64;
RAM128depth = 2048;
}
}
}
else if(depthExponent <= 14 && depthExponent >= 10 && mode < 4 || depthExponent <= 14 && depthExponent >= 11 && mode == 4){
hit = ceil(float(Width)/float(pow(2.0,float(17-depthExponent))));
widthHit = hit;
RAM128width = pow(2.0,float(17-depthExponent));
RAM128depth = pow(2.0, float(depthExponent));
}
else if(depthExponent < 10 && mode < 4 || depthExponent < 11 && mode == 4){
if(mode < 4){
hit = ceil(float(Width)/128.0);
RAM128width = 128;
RAM128depth = 1024;
}
else{
hit = ceil(float(Width)/64.0);
RAM128width = 64;
RAM128depth = 2048;
}
widthHit = hit;
}
solveData.push_back(hit);
solveData.push_back(extraLogic);
solveData.push_back(depthHit);
solveData.push_back(widthHit);
solveData.push_back(RAM128width);
solveData.push_back(RAM128depth);
return solveData;
}
//Determine Hit, cost and other parameters of instantiated LUTRAM
vector<int> Solve::LUTRAMconfiguration(int mode, int depthExponent, int widthExponent, int Width){
vector<int> solveData;
int hit=0, extraLogic =0, depthHit = 1, widthHit = 1, LUTwidth, LUTdepth;
if(depthExponent <= 5){
hit = ceil(float(Width)/20.0);
widthHit = hit;
LUTwidth = 20;
LUTdepth = 32;
}
else if(depthExponent == 6){
hit = ceil(float(Width)/10.0);
widthHit = hit;
LUTwidth = 10;
LUTdepth = 64;
}
else{
depthHit = pow(2.0, float(depthExponent - 6));
widthHit = ceil(float(Width)/10.0);
hit = depthHit*widthHit;
LUTwidth = 10;
LUTdepth = 64;
if(depthHit == 2)
extraLogic += 1;
else
extraLogic += depthHit;
//multiplexers
if(depthHit <=4)
extraLogic += 1*pow(2.0, float(widthExponent));
else if(depthHit <= 8)
extraLogic += 3*pow(2.0,float(widthExponent));
else if(depthHit <=16)
extraLogic += 5*pow(2.0,float(widthExponent));
else
extraLogic = 99*pow(2.0,float(widthExponent));
}
solveData.push_back(hit);
solveData.push_back(extraLogic);
solveData.push_back(depthHit);
solveData.push_back(widthHit);
solveData.push_back(LUTwidth);
solveData.push_back(LUTdepth);
return solveData;
}
//return area based flags
float Solve::getArea(int newlogic, int RAMused, int maxWidth, int bits, int RAM2used, int maxWidth2, int bits2, bool LUTRAM_support, bool MTJ){
float area;
if(LUTRAM_support == false && MTJ == false)
area = newlogic*35000/2 + RAMused*(9000 + 5*bits + 90*sqrt(bits) + 600*2*maxWidth) + RAM2used*(9000 + 5*bits2 + 90*sqrt(bits2) + 600*2*maxWidth2);
else if(LUTRAM_support == true && MTJ == false)
area = newlogic*(40000 + 35000)/2 + RAMused*(9000 + 5*bits + 90*sqrt(bits) + 600*2*maxWidth) + RAM2used*(9000 + 5*bits2 + 90*sqrt(bits2) + 600*2*maxWidth2);
else if(LUTRAM_support == false && MTJ == true)
area = newlogic*35000/2 + RAMused*(9000 + 1.25*bits + 90*sqrt(bits) + 600*2*maxWidth) + RAM2used*(9000 + 1.25*bits2 + 90*sqrt(bits2) + 600*2*maxWidth2);
else if(LUTRAM_support == true && MTJ == true)
area = newlogic*(40000 + 35000)/2 + RAMused*(9000 + 1.25*bits + 90*sqrt(bits) + 600*2*maxWidth) + RAM2used*(9000 + 1.25*bits2 + 90*sqrt(bits2) + 600*2*maxWidth2);;
return area;
}
//based on flags explore specific architecture
void Solve::areaModel(vector<vector<int> > circuitDefs, vector<int> logicBlockCount, int BlockRAMsizeExponent, bool LUTRAM_support, bool MTJ, bool multiRAM){
float minimumArea = 10000000000000;
int minMaxWidth = 0, minLBpRB = 0, minMaxWidth2=0;
if(multiRAM == false){
for(int j = -2; j < 3; j++){
for(int k = 10; k<=50; k+=10){
int circuit = circuitDefs[0][0], logic = logicBlockCount[0], newLogic = logicBlockCount[0], RAM_ID, Mode, Depth, Width, RAMused=0;
int LBpRB = k, LUTRAMused=0;
int BRAMsize = pow(2.0, float(BlockRAMsizeExponent));
int maxWidthExponent = BlockRAMsizeExponent/2+j;
float areaCircuit=0, areaResult=0;
vector<int> ramResult, LUTResult;
vector<float> areaVector;
for(int i=0; i<circuitDefs.size(); i++){
// cout << newLogic << endl;
if(circuit != circuitDefs[i][0]){
areaCircuit = getArea(newLogic, RAMused, pow(2.0, float(maxWidthExponent)), BRAMsize, 0, 0, 0, LUTRAM_support, MTJ);
areaVector.push_back(areaCircuit/100000000.0);
//cout << "Circuit: " << circuit << endl << "RAMs Used: " << RAMused << endl << "Previous Logic: " << logic << endl << "newLogic: " << newLogic << endl << "Area: " << areaCircuit << endl << endl;
circuit = circuitDefs[i][0];
logic = logicBlockCount[circuit];
newLogic = logicBlockCount[circuit];
RAMused = 0;
}
RAM_ID = circuitDefs[i][1];
Mode = circuitDefs[i][2];
Depth = circuitDefs[i][3];
Width = circuitDefs[i][4];
int widthExponent = ceil(log2(Width));
int depthExponent = ceil(log2(Depth));
if(LUTRAM_support == false){
ramResult = returnAmount(newLogic, Mode, BlockRAMsizeExponent, maxWidthExponent, widthExponent, depthExponent, RAMused, LBpRB);
RAMused = ramResult[0];
newLogic += ramResult[1];
//cout << "RAMs Used: " << RAMused << endl << "newLogic: " << newLogic << endl;
ramResult.clear();
}
else{
if(Mode < 4)
LUTResult = LUTRAMconfiguration(Mode, depthExponent, widthExponent, Width);
ramResult = returnAmount(newLogic, Mode, BlockRAMsizeExponent, maxWidthExponent, widthExponent, depthExponent, RAMused, LBpRB);
if(Mode < 4 && LUTResult[1] == 0)
LUTRAMused += LUTResult[0];
else if(ramResult[1] == 0)
RAMused = ramResult[0];
else if(Mode < 4 && LUTResult[1] < ramResult[1]){
newLogic += ceil(float(LUTResult[1])/10.0);
LUTRAMused += LUTResult[0];
}
else{
RAMused = ramResult[0];
newLogic += ramResult[1];
}
}
if(i == circuitDefs.size()-1){
//cout << "Circuit: " << circuit << endl << "RAMs Used: " << RAMused << endl << "Previous Logic: " << logic << endl << "newLogic: " << newLogic << endl;
areaCircuit = getArea(newLogic, RAMused, pow(2.0, float(maxWidthExponent)), 0, 0, 0, BRAMsize, LUTRAM_support, MTJ);
areaVector.push_back(areaCircuit/100000000.0);
}
}
for(int i=0; i<areaVector.size(); i++){
//cout << areaVector[i] << endl;
areaResult += areaVector[i];
}
areaResult /= areaVector.size();
areaResult *= 100000000.0;
if(areaResult < minimumArea){
minMaxWidth = pow(2.0, float(maxWidthExponent));
minimumArea = areaResult;
minLBpRB = LBpRB;
}
areaVector.clear();
}
}
cout << minMaxWidth << " " << minLBpRB << endl;
cout << "Final Area " << pow(2.0, float(BlockRAMsizeExponent)) << " maxWidthExponent (" << minMaxWidth << "): " << minimumArea << endl;
}
else{
int minRAM2;
for(int RAM2exponent = 10; RAM2exponent <= 17; RAM2exponent++){
for(int j = -2; j < 3; j++){
for(int k = 10; k<=50; k+=10){
int circuit = circuitDefs[0][0], logic = logicBlockCount[0], newLogic = logicBlockCount[0], RAM_ID, Mode, Depth, Width, RAMused=0, RAM2used = 0;
int LBpRB = k, LUTRAMused=0;
int BRAMsize = pow(2.0, float(BlockRAMsizeExponent));
int BRAMsize2 = pow(2.0, float(RAM2exponent));
int maxWidthExponent = BlockRAMsizeExponent/2+j;
int maxWidthExponent2 = RAM2exponent/2+j;
float areaCircuit=0, areaResult=0;
vector<int> ramResult, LUTResult, ram2Result;
vector<float> areaVector;
for(int i=0; i<circuitDefs.size(); i++){
// cout << newLogic << endl;
if(circuit != circuitDefs[i][0]){
areaCircuit = getArea(newLogic, RAMused, pow(2.0, float(maxWidthExponent)), BRAMsize, RAM2used, pow(2.0, float(maxWidthExponent2)), BRAMsize2, LUTRAM_support, MTJ);
areaVector.push_back(areaCircuit/100000000.0);
//cout << "Circuit: " << circuit << endl << "RAMs Used: " << RAMused << endl << "Previous Logic: " << logic << endl << "newLogic: " << newLogic << endl << "Area: " << areaCircuit << endl << endl;
circuit = circuitDefs[i][0];
logic = logicBlockCount[circuit];
newLogic = logicBlockCount[circuit];
RAMused = 0;
RAM2used = 0;
}
RAM_ID = circuitDefs[i][1];
Mode = circuitDefs[i][2];
Depth = circuitDefs[i][3];
Width = circuitDefs[i][4];
int widthExponent = ceil(log2(Width));
int depthExponent = ceil(log2(Depth));
if(LUTRAM_support == false){
ramResult = returnAmount(newLogic, Mode, BlockRAMsizeExponent, maxWidthExponent, widthExponent, depthExponent, RAMused, LBpRB);
RAMused = ramResult[0];
newLogic += ramResult[1];
//cout << "RAMs Used: " << RAMused << endl << "newLogic: " << newLogic << endl;
ramResult.clear();
}
else{
if(Mode < 4)
LUTResult = LUTRAMconfiguration(Mode, depthExponent, widthExponent, Width);
ramResult = returnAmount(newLogic, Mode, BlockRAMsizeExponent, maxWidthExponent, widthExponent, depthExponent, RAMused, LBpRB);
ram2Result = returnAmount(newLogic, Mode, RAM2exponent, maxWidthExponent2, widthExponent, depthExponent, RAM2used, LBpRB);
if(Mode < 4 && LUTResult[1] == 0)
LUTRAMused += LUTResult[0];
else if(ramResult[1] == 0)
RAMused = ramResult[0];
else if(ram2Result[1] == 0)
RAM2used = ram2Result[0];
else if(Mode < 4 && LUTResult[1] < ramResult[1] && LUTResult[1] < ram2Result[1]){
newLogic += ceil(float(LUTResult[1])/10.0);
LUTRAMused += LUTResult[0];
}
else if(ramResult[0] - RAMused < ram2Result[0] - RAM2used){
RAMused = ramResult[0];
newLogic += ramResult[1];
}
else{
RAM2used = ram2Result[0];
newLogic += ram2Result[1];
}
}
if(i == circuitDefs.size()-1){
//cout << "Circuit: " << circuit << endl << "RAMs Used: " << RAMused << endl << "Previous Logic: " << logic << endl << "newLogic: " << newLogic << endl;
areaCircuit = getArea(newLogic, RAMused, pow(2.0, float(maxWidthExponent)), BRAMsize, RAM2used, pow(2.0, float(maxWidthExponent2)), BRAMsize2, LUTRAM_support, MTJ);
areaVector.push_back(areaCircuit/100000000.0);
}
}
for(int i=0; i<areaVector.size(); i++){
//cout << areaVector[i] << endl;
areaResult += areaVector[i];
}
areaResult /= areaVector.size();
areaResult *= 100000000.0;
if(areaResult < minimumArea){
minMaxWidth = pow(2.0, float(maxWidthExponent));
minMaxWidth2 = pow(2.0, float(maxWidthExponent2));
minRAM2 = pow(2.0, float(RAM2exponent));
minimumArea = areaResult;
minLBpRB = LBpRB;
}
areaVector.clear();
}
}
}
cout << "Max width RAM 1: " << minMaxWidth << endl << "Max width RAM 2: " << minMaxWidth2 << endl << minLBpRB << endl;
cout << "Final Area " << pow(2.0, float(BlockRAMsizeExponent)) << " maxWidthExponent (" << minMaxWidth << ") and ";
cout << minRAM2 << " maxWidthExponent (" << minMaxWidth2 << "): " << minimumArea << endl;
}
//cout << maxWidthExponent << endl;
}
//Map RAM type passed
vector<int> Solve::returnAmount(int newLogic, int mode, int BlockRAMsizeExponent, int maxWidthExponent, int widthExponent, int depthExponent, int RAMused, int LBpRB){
vector<int> returnVector;
int available = newLogic/LBpRB - RAMused, extraLogic = 0, depthHit=0, newvals =0;
if(depthExponent + widthExponent <= BlockRAMsizeExponent && widthExponent <= maxWidthExponent && mode < 4 || depthExponent + widthExponent <= BlockRAMsizeExponent && widthExponent < (maxWidthExponent-1) && mode == 4){
RAMused += 1;
}
else if(depthExponent <= BlockRAMsizeExponent && depthExponent >= (BlockRAMsizeExponent - maxWidthExponent) && mode <4){
RAMused += ceil(pow(2.0, float(widthExponent - maxWidthExponent)));
}
else if(depthExponent <= BlockRAMsizeExponent && depthExponent >= (BlockRAMsizeExponent - maxWidthExponent + 1) && mode==4){
RAMused += ceil(pow(2.0, float(widthExponent - maxWidthExponent + 1)));
}
else if(depthExponent < (BlockRAMsizeExponent - maxWidthExponent) && mode < 4){
if(widthExponent <= maxWidthExponent)
RAMused += 1;
else
RAMused += ceil(pow(2.0, float(widthExponent - maxWidthExponent)));
}
else if(depthExponent < (BlockRAMsizeExponent - maxWidthExponent -1) && mode == 4){
if(widthExponent <= (maxWidthExponent -1))
RAMused += 1;
else
RAMused += ceil(pow(2.0, float(widthExponent - maxWidthExponent + 1)));
}
else if(depthExponent > BlockRAMsizeExponent){
if(widthExponent <= maxWidthExponent && mode < 4 || widthExponent <= (maxWidthExponent -1) && mode == 4)
RAMused += ceil(pow(2.0, float(depthExponent - BlockRAMsizeExponent)));
else{
if(mode < 4)
RAMused += ceil(pow(2.0, float(depthExponent - BlockRAMsizeExponent)))*ceil(pow(2.0, float(widthExponent - maxWidthExponent)));
else
RAMused += ceil(pow(2.0, float(depthExponent - BlockRAMsizeExponent)))*ceil(pow(2.0, float(widthExponent - maxWidthExponent + 1)));
}
depthHit = ceil(pow(2.0, float(depthExponent - BlockRAMsizeExponent)));
if(depthHit == 2)
extraLogic += 1;
else
extraLogic += depthHit;
//multiplexers
if(depthHit <=4)
extraLogic += 1*pow(2.0, float(widthExponent));
else if(depthHit <= 8)
extraLogic += 3*pow(2.0,float(widthExponent));
else if(depthHit <=16)
extraLogic += 5*pow(2.0,float(widthExponent));
else
extraLogic = 99*pow(2.0,float(widthExponent));
}
if(available <=0){
newvals += LBpRB*RAMused;
}
if(extraLogic != 0)
newvals += ceil(float(extraLogic)/10.0);
returnVector.push_back(RAMused);
returnVector.push_back(newvals);
return returnVector;
}
| true |
834d05abfab61fc2ba95b3f27cd931fdca0389d9
|
C++
|
IHA-Quadro/Drone
|
/Kode/Drone/Gyroscope_ITG3200Common.cpp
|
WINDOWS-1252
| 1,923 | 2.53125 | 3 |
[] |
no_license
|
#include "Gyroscope_ITG3200Common.h"
float gyroTempBias[3] = {0.0,0.0,0.0};
void initializeGyro() {
if ((readWhoI2C(ITG3200_ADDRESS) & ITG3200_IDENTITY_MASK) == ITG3200_IDENTITY)
vehicleState |= GYRO_DETECTED;
gyroScaleFactor = radians(1.0 / 14.375); // ITG3200 14.375 LSBs per /sec
updateRegisterI2C(ITG3200_ADDRESS, ITG3200_RESET_ADDRESS, ITG3200_RESET_VALUE); // send a reset to the device
updateRegisterI2C(ITG3200_ADDRESS, ITG3200_LOW_PASS_FILTER_ADDR, ITG3200_LOW_PASS_FILTER_VALUE); // 10Hz low pass filter
updateRegisterI2C(ITG3200_ADDRESS, ITG3200_RESET_ADDRESS, ITG3200_OSCILLATOR_VALUE); // use internal oscillator
}
void measureGyro()
{
sendByteI2C(ITG3200_ADDRESS, ITG3200_MEMORY_ADDRESS);
Wire.requestFrom(ITG3200_ADDRESS, ITG3200_BUFFER_SIZE);
int gyroADC[3];
measureSpecificGyroADC(gyroADC);
for (byte axis = 0; axis <= ZAXIS; axis++)
{
gyroRate[axis] = gyroADC[axis] * gyroScaleFactor;
}
// Measure gyro heading
long int currentTime = micros();
if (gyroRate[ZAXIS] > radians(1.0) || gyroRate[ZAXIS] < radians(-1.0))
gyroHeading += gyroRate[ZAXIS] * ((currentTime - gyroLastMesuredTime) / 1000000.0);
gyroLastMesuredTime = currentTime;
}
void measureGyroSum()
{
sendByteI2C(ITG3200_ADDRESS, ITG3200_MEMORY_ADDRESS);
Wire.requestFrom(ITG3200_ADDRESS, ITG3200_BUFFER_SIZE);
measureSpecificGyroSum();
gyroSampleCount++;
}
void evaluateGyroRate()
{
int gyroADC[3];
evaluateSpecificGyroRate(gyroADC);
gyroSample[XAXIS] = 0;
gyroSample[YAXIS] = 0;
gyroSample[ZAXIS] = 0;
gyroSampleCount = 0;
for (byte axis = 0; axis <= ZAXIS; axis++)
{
gyroRate[axis] = gyroADC[axis] * gyroScaleFactor;
}
// Measure gyro heading
long int currentTime = micros();
if (gyroRate[ZAXIS] > radians(1.0) || gyroRate[ZAXIS] < radians(-1.0))
gyroHeading += gyroRate[ZAXIS] * ((currentTime - gyroLastMesuredTime) / 1000000.0);
gyroLastMesuredTime = currentTime;
}
| true |
e629d5fe7b44c7dca7e7ce1a77d3f50ddba9e6b2
|
C++
|
gurum77/gengine
|
/gengine-0.1/Engine/GEngine/Src/GAlignment/GHorizontalAlignmentElement.h
|
UHC
| 1,843 | 3.046875 | 3 |
[] |
no_license
|
#pragma once
/**
@brief
- The element of horizontal alignment
- line, arc, clothoid, ovalness
- Element κ Ѵ.
- иǾ Ȱ ϴ
- ü Ư Element ϵ ϱ .
- Element ü Ȱ ֵ ϱ .
*/
class G_EXT_CLASS CGHorizontalAlignmentElement
{
public:
enum Type
{
eTypeUnknown,
eTypeLine,
eTypeArc,
eTypeClothoidA1,
eTypeClothoidA2,
eTypeOvalness
};
void SetStartPos(const CGPoint2D &dptPos);
const CGPoint2D &GetStartPos() const;
void SetDir(const CGVector2D &vDir);
const CGVector2D &GetDir() const;
void SetStartStation(const double &dStation);
const double &GetStartStation() const;
void SetA1(const double &dA1);
const double &GetA1() const;
void SetA2(const double &dA2);
const double &GetA2() const;
void SetR1(const double &dR1);
const double &GetR1() const;
void SetR2(const double &dR2);
const double &GetR2() const;
void SetCCW(const bool &bCCW);
const bool &GetCCW() const;
void SetLength(const double &dLength);
const double &GetLength() const;
Type GetType() const;
bool CalcLengthByParameter();
bool IsIncludeStation(const double &dStation) const;
CGPoint2D CalcPosByStation(const double &dStation, GOUT CGVector2D *pvEndDir = NULL) const;
private:
CGPoint2D m_ptStartPos;
CGVector2D m_vDir;
double m_dStartStation;
double m_dA1;
double m_dA2;
double m_dR1;
double m_dR2;
double m_dLength;
bool m_bCCW;
public:
GDEFINE_OPERATOR_COPY(CGHorizontalAlignmentElement);
GDEFINE_OPERATOR_EQUAL(CGHorizontalAlignmentElement);
CGHorizontalAlignmentElement(void);
CGHorizontalAlignmentElement(const CGHorizontalAlignmentElement &d);
~CGHorizontalAlignmentElement(void);
};
| true |
32b382cef2b33f8865ccc5b00f001447ae089686
|
C++
|
jnaess/ENGO431Lab3
|
/ENGO431_Lab3/ENGO431_Lab3/Functions.h
|
UTF-8
| 1,808 | 3.296875 | 3 |
[] |
no_license
|
#pragma once
#include "Eigen/Dense"
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
using namespace Eigen;
using namespace std;
/*
Description:
Used to test that a MatrixXd has been made correctly
Input:
MatrixXd M: that will be printed
String title: the desirect matrix's title
Output:
Print to the screen of the matrix and its respective title on top
*/
void TestPrint(MatrixXd M, string title);
/*
Description:
Enter the degree, minute, second angle
returns the angle in degrees
Input:
double deg, Degrees
double min, Minutes
double sec, Seconds
Output:
double of the angle in degree decimals
*/
double degrees(double deg, double min, double sec);
/*
Description:
Enter the degree, minute, second angle
returns the angle in degrees
Input:
double degrees, The degrees in decimal degree
Output:
vector of doubles
[0] --> Degrees
[1] --> Minutes
[2] --> Seconds
*/
vector<double> dms(double degrees);
/*
Description:
Convert radians to decimal degrees
Input:
double rad, radians
Output:
double of the angle in degree decimals
*/
double degrees(double rad);
/*
Description:
Write a .txt file via a MatrixXd
Input:
A String for :filename
A MatrixXd to read off
Output:
A .txt file with x decimal precision
*/
void Output(string filename, MatrixXd m);
/*
Description:
return decimal degrees to radians
Input:
decimal degrees
Output:
radians
*/
double radians(double deg);
/*
Definition:
Returns a rotation matrix about x(1),y(2), or z(3) axis
Input:
rotation angle and axis(1,2,3)
Output:
Rotation Matrix
*/
MatrixXd rotate(double angle, int axis);
/*Function: print_mat
Prints matrix to console
Inputs: MatrixXd to be printed and string for a label
Outputs: None
*/
void print_mat(MatrixXd mat, string name);
| true |
c6995f285d9ff4e1ad560118cf3c97c155b1b2f6
|
C++
|
Sadchant/Kollisionserkennung-DirectX
|
/Kollisionserkennung DirectX/FpsClass.h
|
UTF-8
| 899 | 2.609375 | 3 |
[] |
no_license
|
// The FpsClass is simply a counter with a timer associated with it.It counts how many frames occur in a one second period and constantly
// updates that count.
#pragma once
// ***Quelle***: http://www.rastertek.com/tutdx11.html
/////////////
// LINKING //
/////////////
#pragma comment(lib, "winmm.lib")
//////////////
// INCLUDES //
//////////////
#include <windows.h>
#include <mmsystem.h>
#define AMOUNT 50
////////////////////////////////////////////////////////////////////////////////
// Class name: FpsClass
////////////////////////////////////////////////////////////////////////////////
class FpsClass
{
public:
FpsClass();
FpsClass(const FpsClass&);
~FpsClass();
void Initialize();
void Frame();
int GetMS();
int GetFPS();
private:
int m_fps, m_msFrame, m_count;
unsigned long m_msStartTime, m_startTime;
int m_Counter;
unsigned long m_Last10FrameMS[AMOUNT] = {0};
};
| true |
1e3af938805ee0c2181b129ea4dd42d0604ca2b8
|
C++
|
tfcpanda/cBaseExercises
|
/cBasicExercises04/test.cpp
|
UTF-8
| 205 | 2.734375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main( )
{
int x,y;
printf("Enter x:\n");
scanf("%d", &x);
if( x%10 == 0){
y = 3* x;
}
else {
y = x;
}
printf("f(%d)=%d\n",x,y);
return 0;
}
| true |