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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5412a4d25348fc5f0336a32593632c96f9b83f28 | C++ | zhangzhenyu13/TankWar | /MapData.cpp | WINDOWS-1252 | 11,717 | 2.796875 | 3 | [] | no_license | #include"MapData.h"
#include"CommonFunc.h"
using namespace std;
void MapData::generateMap(std::vector<Brick>& data) {
Brick brick;
brick.health = 100000;
brick.style = 1;
int x, y;
RECT rt;
//up
x = 0;
y = -20;
rt.left=x;rt.top=y;rt.right=x+1200;rt.bottom=y+20;
brick.rect = rt;
data.push_back(brick);
//left
x = -20;
y = 0;
rt.left=x;rt.top=y;rt.right=x+20;rt.bottom=y+750;
brick.rect = rt;
data.push_back(brick);
//down
x = 0;
y = 750;
rt.left=x;rt.top=y;rt.right=x+1200;rt.bottom=y+20;
brick.rect = rt;
data.push_back(brick);
//right
x = 1200;
y = 0;
rt.left=x;rt.top=y;rt.right=x+20;rt.bottom=y+750;
brick.rect = rt;
data.push_back(brick);
}
//map of stages
//stage 1
bool MapData1::interset(RECT rect) {
RECT inrect;
for (int i = 0; i < data.size(); i++) {
if (IntersectRect(&inrect,&data[i].rect,&rect))
return true;
if(rect.top < 0 || rect.bottom > 700 || rect.left < 0 || rect.right > 1200)
return true;
}
return false;
}
void MapData1::method1() {
Brick brick;
brick.health = 6;
brick.style = 1;
RECT rt;
int x, y;
//T
for (int i = 0; i < 5; i++) {
x = 50 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 150;
y = 100 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//A
for (int i = 0; i < 2; i++) {
x = 400 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
for (int i = 0; i < 5; i++) {
x = 350;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
x = 500;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
//N
for (int i = 0; i < 5; i++) {
x = 600;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
x = 800;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 650 + i * 50;
y = 100 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//K
for (int i = 0; i < 5; i++) {
x = 900;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
if (i == 0) {
x = 950;
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
else
x = 950 + i * 50;
y = 150 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
y = 150 - i * 50;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
}
void MapData1::method2() {
Brick brick;
brick.health = 6;
brick.style = 1;
RECT rt;
int x, y;
//T
for (int i = 0; i < 5; i++) {
x = 50 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 150;
y = 100 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//A
for (int i = 0; i < 2; i++) {
x = 400 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
for (int i = 0; i < 5; i++) {
x = 350;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
x = 500;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
//N
for (int i = 0; i < 5; i++) {
x = 600;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
x = 800;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 650 + i * 50;
y = 100 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//K
for (int i = 0; i < 5; i++) {
x = 900;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
if (i == 0) {
x = 950;
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
else
x = 950 + i * 50;
y = 150 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
y = 150 - i * 50;
brick.rect = { x,y,x + 50,y + 50 };
data.push_back(brick);
}
//Middle Line
for (int i = 0; i < 4; i++) {
x = 50 + i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 1050 - i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 250 + i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 3;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 850 - i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 3;
data.push_back(brick);
}
for (int i = 0; i < 5; i++) {
x = 450 + i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//Square
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i*j != 1) {
x = 50 + i * 50;
y = 450 + j * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i*j != 1) {
x = 250 + i * 50;
y = 450 + j * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i*j != 1) {
x = 1050 - i * 50;
y = 450 + j * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i*j != 1) {
x = 850 - i * 50;
y = 450 + j * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
}
//Home
for (int i = 0; i < 5; i++) {
x = 450 + i * 50;
y = 500;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 450;
y = 550 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 650;
y = 550 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//Line
for (int i = 0; i < 7; i++) {
x = 400 + i * 50;
y = 450;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 3;
data.push_back(brick);
}
}
void MapData1::method3() {
Brick brick;
int x, y;
//б
for (int i = 0; i < 11; i++) {
x = 250 + i * 50;
y = 550 - i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 11; i++) {
x = 350 + i * 50;
y = 600 - i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 2; i++) {
x = 250 + i * 50;
y = 600;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 2; i++) {
x = 800 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//б
for (int i = 0; i < 12; i++) {
if (i != 5 && i != 6) {
x = 300 + i * 50;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
for (int i = 0; i < 12; i++) {
if (i != 6 && i != 7) {
x = 200 + i * 50;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
for (int i = 0; i < 12; i++) {
if (i != 5 && i != 6) {
x = 250 + i * 50;
y = 50 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
}
//Home
for (int i = 0; i < 3; i++) {
x = 500 + i * 50;
y = 560;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 1; i++) {
x = 500;
y = 610 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 1; i++) {
x = 600;
y = 610 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//
for (int i = 0; i < 3; i++) {
x = 0 + i * 50;
y = 250;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 0 + i * 50;
y = 300;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 0 + i * 50;
y = 350;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 3; i++) {
x = 0 + i * 50;
y = 400;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//ϲ
for (int i = 0; i < 4; i++) {
x = 450 + i * 50;
y = 0;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 450 + i * 50;
y = 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//Ҳ
for (int i = 0; i < 4; i++) {
x = 1000;
y = 250 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 1050;
y = 250 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 1100;
y = 250 + i * 50;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 5;
brick.style = 1;
data.push_back(brick);
}
//ǽ
for (int i = 0; i < 4; i++) {
x = 0 + i * 50;
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 99;
brick.style = 3;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 0 + i * 50;
y = 500;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 99;
brick.style = 3;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 950 + i * 50;
y = 150;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 99;
brick.style = 3;
data.push_back(brick);
}
for (int i = 0; i < 4; i++) {
x = 950 + i * 50;
y = 500;
brick.rect = { x,y,x + 50,y + 50 };
brick.health = 99;
brick.style = 3;
data.push_back(brick);
}
}
void MapData1::generateMap(int r) {
MapData::generateMap(data);
switch (r)
{
case 1:
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
default:
break;
}
} | true |
4cac3f84f4389648856d880982f658538795b743 | C++ | rara1818/games | /Cpp/Video/src/Scenery.cpp | UTF-8 | 3,637 | 2.546875 | 3 | [] | no_license | /*
* Scenery.cpp
*
* Created on: 29/07/2013
* Author: vitor
*/
#include "Scenery.h"
#include <unistd.h>
#include "enemies.h"
#include "objects.h"
#include "viewpoints.h"
/* Testing purpose only! */
#include "utils.h"
#include <time.h>
#include "scen0.h"
/*************************************************************************************************/
Scenery::Scenery(Video& video):
m_Video(video)
{
VisualElement *under_layer0 = new(VisualElement);
SDL_Surface *layer = NULL;
/* Testing purpose only! */
size_t layer_len = array_length(layer0);
srand(time(NULL)*(int)(this));
/* Remove this thing. */
for (unsigned int i = 0; i < layer_len; ++i) {
layer0[i] = (rand() % 4) + 4;
}/* Testing purpose only until here! */
if (build_layer(&layer, layer0_bounds, layer0) != 0) {
cout << "Failed to build scenery under layer." << endl;
return;
}
st_element_pos area_size = {layer0_bounds.x*TILE_SIZE, layer0_bounds.y*TILE_SIZE};
m_CollDomain_dynamic.build_collAreas(area_size);
m_CollDomain_static.build_collAreas(area_size);
under_layer0->set_viewpoint(layer, 0);
m_UnderLayer_list.push_back(under_layer0);
video.push_under_layer(under_layer0->m_Viewpoints[0]);
}
/*************************************************************************************************/
Scenery::~Scenery(void)
{
cout << "Scenery destroyed." << endl;
}
/*************************************************************************************************/
void Scenery::add_element(Character *element)
{
m_Video.add_visualElement(element);
if (element->type() == INANIMATED) {
m_CollDomain_static.add_collisionElement(*element);
}
else {
m_CollDomain_dynamic.add_collisionElement(*element);
}
cout << "Character added to scenery." << endl;
}
/*************************************************************************************************/
void Scenery::add_element(Object *element)
{
m_Video.add_visualElement(element);
if (element->type() == INANIMATED) {
m_CollDomain_static.add_collisionElement(*element);
}
else {
m_CollDomain_dynamic.add_collisionElement(*element);
}
cout << "Object added to scenery." << endl;
}
/*************************************************************************************************/
void Scenery::add_element(Enemy *element)
{
m_Video.add_visualElement(element);
if (element->type() == INANIMATED) {
m_CollDomain_static.add_collisionElement(*element);
}
else {
m_CollDomain_dynamic.add_collisionElement(*element);
}
cout << "Enemy added to scenery." << endl;
}
/*************************************************************************************************/
void Scenery::play(void)
{
Character player;
this->add_element(&player);
GiantSpider crit(200, 200);
this->add_element(&crit);
Rock1 rock(120, 120);
this->add_element(&rock);
m_Video.start();
en_ctrl_actions action;
while((action = m_Control.get_action()) != CTRL_EXIT) {
switch (action) {
// UP;
case CTRL_MOVE_UP:
player.move_up();
break;
// RIGHT
case CTRL_MOVE_RIGHT:
player.move_right();
break;
// DOWN:
case CTRL_MOVE_DOWN:
player.move_down();
break;
// LEFT
case CTRL_MOVE_LEFT:
player.move_left();
break;
case CTRL_NONE:
player.stand();
break;
// STAND
case CTRL_SUMMON:
this->add_element(new GiantSpider(200, 200));
break;
default:
cout << "invalid action: " << action << endl;
break;
}
usleep(player.m_Speed_ms*MILI);
}
m_Control.get_keyDown();
m_Video.freeze();
m_Control.get_keyDown();
}
| true |
0d045bba1af6c751b527f74b0db77f16ecf7c019 | C++ | nunik2255/program-konversi-waktu | /program konversi waktu.cpp | UTF-8 | 646 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
int hari,jam,menit,detik;
cout<<"PROGRAM KONVERSI WAKTU"<<endl;
cout<<"Konversi hari ke detik"<<endl;
cout<<"Masukan jumlah hari = " ;
cin>>hari;
hari=hari*86400;
cout<<"hasillnya = "<<hari<<"detik"<<endl;
cout<<"konversi jam ke detik"<<endl;
cout<<"masukan jumlah jam = " ;
cin>>jam;
jam=jam*3600;
cout<<"hasilnya = "<<jam<<"detik"<<endl;
cout<<"konversi menit ke detik"<<endl;
cout<<"masukan jumlah menit = " ;
cin>>menit;
menit=menit*60;
cout<<"hasilnya = "<<menit<<"detik"<<endl;
return 0;
}
| true |
b1a964518193cc5b32aae2c35159e5a568495a30 | C++ | yehudis-k/DNA-Analyzer-project | /Controller/Command/new.cpp | UTF-8 | 1,787 | 3.0625 | 3 | [] | no_license | //
// Created by student on 10/08/2020.
//
#include "new.h"
size_t New::s_counter = 1;
std::string New::getDocumentation() const{
return "Creates a new DNA sequence.\n"
"New accepts sequence and adds it to the system.\n"
"A name for the new sequence can be given by the user after the sequence - with a @.\n"
"If not provided - a default name will be given.";
}
std::string New::getDefaultName()
{
while (!isValidName("seq"+std::to_string(s_counter)))
s_counter++;
s_counter++;
return "seq"+std::to_string(s_counter-1);
}
bool New::setParams(std::vector<std::string> params) {
if ((params.size() < 2) || (params.size() > 3)) {// too many or too little arguments
m_message = "Invalid number of arguments";
return false;
}
if (params.size() == 2)
m_new_name = getDefaultName();
else {
if (params[2][0] != '@') {
m_message = "Invalid argument sequence name";
return false;
}
m_new_name = params[2].substr(1);
}
if (!isValidName(m_new_name)) {
m_message = "DNA sequence name already exists";
return false;
}
m_new_sequence = params[1];
return true;
}
std::string New::execute() {
// create new DnaData object
SharedPtr<DnaData> dna;
try {
dna = SharedPtr<DnaData>(new DnaData(m_new_name, m_new_sequence));
}
catch (ValidError& e) {
dna->decreaseId();
s_counter--;
return "Error! Invalid DNA Nucleotide";
}
bool checkAdd = DnaCollection::addDna(dna);
if (!checkAdd)
{
dna->~DnaData();
return "Error adding dna";
}
DnaCollection::addNew();
//DnaCollection::updateCache(dna);
return getOutput(dna);
}
| true |
d2e887f98db3605aa086f48191b84f9ea83102fa | C++ | chengyeh/EECS268 | /workspace/Lab5/Lee-2482962-Lab-05/main.cpp | UTF-8 | 3,927 | 3.359375 | 3 | [] | no_license | /*
* File Name: main.cpp
* Author: Cheng Yeh Lee
* KUID: 2482962
* Email: chengyeh@ku.edu
* Assignment: EECS-268 Lab5
* Description: This is the main class. It is where we give the user a set of options to interact with AnimalPen.
* Created on: Oct 17, 2015
*
*/
#include <iostream>
#include "FarmAnimal.h"
#include "Cow.h"
#include "Chicken.h"
#include "CyberChicken.h"
#include "AnimalPen.h"
void goodbyeMessage(const FarmAnimal& animal)
{
std::cout << "Upon release the " << animal.getName() << " said " << animal.getSound() << "." << std::endl;
}
int main()
{
AnimalPen* pen = new AnimalPen();
FarmAnimal* fa;
Cow* c = nullptr;
Chicken* chick = nullptr;
CyberChicken* cyber = nullptr;
int userChoice;
int numEggs;
int totalEggs = 0;
double totalGallons = 0;
double gallons = 0.0;
char quitAdding;
bool end = false;
while(end == false)
{
std::cout << "Select an animal to add to the pen:\n"
<< "1.) Cow (produces milk)\n"
<< "2.) Chicken (cannot lay eggs)\n"
<< "3.) Cyber Chicken (seems dangerous, but lays eggs)\n"
<< "---------------------------------------------------\n"
<< "choice: ";
std::cin >> userChoice;
if(userChoice == 1)
{
c = new Cow();
std::cout << "How many gallons of milk did this cow produce?: ";
std::cin >> gallons;
c->setMilkProduced(gallons);
pen->addAnimal(c);
}
if(userChoice == 2)
{
chick = new Chicken();
std::cout << "Add an eggless chicken to the pen? OK. You're the boss.\n";
pen->addAnimal(chick);
}
if(userChoice == 3)
{
cyber = new CyberChicken();
std::cout << "How many eggs did this cyber chicken produce?: ";
std::cin >> numEggs;
cyber->setCyberEggs(numEggs);
pen->addAnimal(cyber);
}
do
{
std::cout << "Done adding animals? (y/n): ";
std::cin >> quitAdding;
}while(quitAdding != 'Y' && quitAdding != 'y' && quitAdding != 'N' && quitAdding != 'n');
if(quitAdding == 'Y' || quitAdding == 'y')
{
std::cout << "\n";
end = true;
}
if(quitAdding == 'N' || quitAdding == 'n')
{
std::cout << "\n";
end = false;
}
}
std::cout << "Releasing all animals!\n"
<< "-------------------------" << std::endl;
while(!pen->isPenEmpty())
{
fa = static_cast<FarmAnimal*>(pen->peakAtNextAnimal());
if(fa->getName().compare("Cow") == 0)
{
c = static_cast<Cow*>(pen->peakAtNextAnimal());
totalGallons = totalGallons + c->getMilkProduced();
std::cout << "This cow produced " << c->getMilkProduced() << " gallons of milk" << std::endl;
goodbyeMessage(*(fa));
pen->releaseAnimal();
delete c;
c = nullptr;
}
else if(fa->getName().compare("Chicken") == 0)
{
chick = static_cast<Chicken*>(pen->peakAtNextAnimal());
std::cout << "Chicken unable to lay eggs. Perhaps cybornetic implants will help?" << std::endl;
goodbyeMessage(*(fa));
pen->releaseAnimal();
std::cout << "Chicken Destructor called\n";
delete chick;
chick = nullptr;
}
else if(fa->getName().compare("Cyber Chicken") == 0)
{
cyber = static_cast<CyberChicken*>(pen->peakAtNextAnimal());
totalEggs = totalEggs + cyber->getCyberEggs();
std::cout << "This Cyber Chicken laid " << cyber->getCyberEggs() << " cyber eggs. Humanity is in trouble." << std::endl;
goodbyeMessage(*(fa));
pen->releaseAnimal();
std::cout << "CyberChicken Destructor called\n"
<< "Chicken Destructor called\n";
delete cyber;
cyber = nullptr;
}
}
std::cout << "Your farm produced " << totalGallons << " of milk and " << totalEggs << " eggs." << std::endl;
delete pen;
pen = nullptr;
return(0);
}
| true |
40f4d6c75c671864e3240cf8cf4449acba854843 | C++ | so-soon/coding_test_boj | /17471_gerrymandering1.cpp | UTF-8 | 2,642 | 2.59375 | 3 | [] | no_license | //
// main.cpp
// cplusplus
//
// Created by soonhyuk on 2020/01/22.
// Copyright © 2020 soonhyuk. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <set>
#include <queue>
#include <map>
#include <vector>
using namespace std;
int N;
int popularity[11];
map<int,vector<int> > ametrix;
void dfs(int depth,int k,int max);
void check(int max);
set<int> combi;
set<int> res;
int main(int argc, const char * argv[]) {
int temp,amn;
scanf("%d",&N);
for(int i = 1 ; i <=N ; i++){
scanf("%d",&temp);
popularity[i] = temp;
}
for(int i = 1 ; i <=N ; i++){
scanf("%d",&amn);
for(int m = 1; m<=amn;m++){
scanf("%d",&temp);
ametrix[i].push_back(temp);
}
}
for(int i = 1; (2*i)<=N; i++){
dfs(0,0,i);
}
if(int(res.size()) == 0) printf("%d",-1);
else printf("%d",*(res.begin()));
return 0;
}
void dfs(int depth,int k,int max){
if (depth == max) {
check(max);
}
else{
for (int i = k+1; i <= N; i++) {
combi.insert(i);
dfs(depth+1, i, max);
combi.erase(i);
}
}
}
void check(int max){
set<int> uncombi;
int tot1 = 0,tot2 = 0,temp,co1=0,co2=0;
queue<int> q;
map<int,bool> visit;
for(int i = 1 ; i <=N ; i++){
if (combi.find(i) == combi.end()) {
uncombi.insert(i);
}
}
q.push(*(combi.begin()));
visit[*(combi.begin())] = true;
while (!(q.empty())) {
temp = q.front();
tot1 += popularity[temp];
q.pop();
co1++;
for(vector<int>::iterator iter = ametrix[temp].begin(); iter != ametrix[temp].end(); ++iter){
if ((visit.find((*iter)) == visit.end()) && (combi.find((*iter)) != combi.end()) ) {
q.push((*iter));
visit[(*iter)] = true;
}
}
}
visit.clear();
q.push(*(uncombi.begin()));
visit[*(uncombi.begin())] = true;
while (!(q.empty())) {
temp = q.front();
tot2 += popularity[temp];
q.pop();
co2++;
for(vector<int>::iterator iter = ametrix[temp].begin(); iter != ametrix[temp].end(); ++iter){
if ((visit.find((*iter)) == visit.end()) && (uncombi.find((*iter)) != uncombi.end()) ) {
q.push((*iter));
visit[(*iter)] = true;
}
}
}
if ((co1 == max) && (co2 == N-max)) {
res.insert(abs(tot1-tot2));
}
}
| true |
cda8f924e88e036f3ce2821c6c21b3b1cc67183e | C++ | Antonija5654/oop_vjezbe | /Vjezba3/Zadatak3/zadatak3.cpp | UTF-8 | 844 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<char> popravi(string str, vector<char> novi)
{
int i;
for (i = 0; i < str.size(); i++)
{
cout << "OMEGALUL" << endl;
if (str[i]==' ')
{
cout << "test1" << endl;
if (str[i + 1] == ',' || str[i + 1] == '.')
{
novi.push_back(str[i + 1]);
}
else
{
novi.push_back(str[i]);
}
}
else if (str[i] == ',' || str[i] == '.')
{
cout << "test2" << endl;
if (str[i + 1] != ' ')
{
novi.push_back(' ');
}
}
else
{
cout << "test3" << endl;
novi.push_back(str[i]);
}
}
return novi;
}
int main()
{
string str = "Ja bih ,ako ikako mogu , ovu recenicu napisala ispravno .";
vector<char> novi;
novi = popravi(str, novi);
int i;
for (i = 0; i < novi.size(); i++)
cout << novi[i];
system("pause");
} | true |
5d0a971e335f4b4c275729f1515276c00f4619dc | C++ | 13465220927/ven | /ven/include/ven/util/func.h | UTF-8 | 8,743 | 2.796875 | 3 | [] | no_license | #pragma once
#if defined(WINDOWS)
#else
# include <cstdarg>
# include <cstring>
# include <unistd.h>
# include <sys/stat.h>
# include <iconv.h>
# include <termios.h>
# include <unistd.h>
#endif
// thread
namespace ven {
static uint64_t tid()
{
std::stringstream ss;
ss << std::this_thread::get_id();
return std::stoull(ss.str());
}
static uint64_t tid(std::thread& th)
{
std::stringstream ss;
ss << th.get_id();
return std::stoull(ss.str());
}
static void sleep(int64_t msec)
{
std::this_thread::sleep_for(std::chrono::milliseconds(msec));
}
}
// string
namespace ven {
template <std::size_t size>
static void copy(const char* s, char(&d)[size])
{
strncpy_s(d, s, size - 1);
}
template <std::size_t size>
static void copy(const wchar_t* s, wchar_t(&d)[size])
{
#if defined(WINDOWS)
wcsncpy_s(d, s, size - 1);
#else
wcsncpy(d, s, size - 1);
#endif
}
static void copy(const wchar_t* s, wchar_t* d, int size)
{
#if defined(WINDOWS)
wcsncpy_s(d, size, s, size - 1);
#else
wcsncpy(d, s, size - 1);
#endif
}
template <std::size_t size = 1024>
static std::string make_str(const char* format, ...)
{
char buf[size] = { 0, };
va_list list;
va_start(list, format);
#if defined(WINDOWS)
vsnprintf_s(buf, size, size - 1, format, list);
#else
vsnprintf(buf, size, format, list);
#endif
va_end(list);
return buf;
}
template <std::size_t size>
static void make_str(char(&buf)[size], const char* format, ...)
{
va_list list;
va_start(list, format);
#if defined(WINDOWS)
vsnprintf_s(buf, size, size - 1, format, list);
#else
vsnprintf(buf, size, format, list);
#endif
va_end(list);
}
template <std::size_t size = 1024>
static std::wstring make_str(wchar_t* format, ...)
{
wchar_t buf[size] = { 0, };
va_list list;
va_start(list, format);
_vsnwprintf_s(buf, size, size - 1, format, list);
va_end(list);
return buf;
}
}
// encode character
namespace ven {
#if defined(WINDOWS)
// multibyte -> wide
static std::wstring m2w(const std::string& in)
{
int len = ::MultiByteToWideChar(CP_ACP, 0, in.c_str(), -1, 0, 0);
std::wstring out(len - 1, 0);
::MultiByteToWideChar(CP_ACP, 0, in.c_str(), -1, const_cast<wchar_t*>(out.c_str()), len);
return out;
}
// wide -> multibyte
static std::string w2m(const std::wstring& in)
{
int len = ::WideCharToMultiByte(CP_ACP, 0, in.c_str(), -1, 0, 0, 0, 0);
std::string out(len - 1, 0);
::WideCharToMultiByte(CP_ACP, 0, in.c_str(), -1, const_cast<char*>(out.c_str()), len, 0, 0);
return out;
}
// wide -> utf8
static std::string w2u(const std::wstring& in)
{
int len = ::WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, 0, 0, 0, 0);
std::string out(len - 1, 0);
::WideCharToMultiByte(CP_UTF8, 0, in.c_str(), -1, const_cast<char*>(out.c_str()), len, 0, 0);
return out;
}
// utf8 -> wide
static std::wstring u2w(const std::string& in)
{
int len = ::MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, 0, 0);
std::wstring out(len -1 , 0);
::MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, const_cast<wchar_t*>(out.c_str()), len);
return out;
}
// multibye -> utf8
static std::string m2u(const std::string& in)
{
return w2u(m2w(in));
}
// utf8 -> multibye
static std::string u2m(const std::string& in)
{
return w2m(u2w(in));
}
#else
static std::size_t iconv_to(const char* to, const char* from, char* in, std::size_t in_bytes_left, char* out, std::size_t out_bytes_left)
{
iconv_t cd = iconv_open(to, from);
iconv(cd, &in, &in_bytes_left, &out, &out_bytes_left);
iconv_close(cd);
return out_bytes_left;
}
static std::wstring m2w(const std::string& in)
{
std::wstring out(in.size(), 0x00);
iconv_to(
"WCHAR_T", "",
const_cast<char*>(in.c_str()),
in.size(),
reinterpret_cast<char*>(const_cast<wchar_t*>(out.c_str())),
(out.size() * sizeof(wchar_t))
);
return out;
}
static std::string w2m(const std::wstring& in)
{
std::string out(in.size(), 0x00);
iconv_to(
"", "WCHAR_T",
reinterpret_cast<char*>(const_cast<wchar_t*>(in.c_str())),
(in.size() * sizeof(wchar_t)),
const_cast<char*>(out.c_str()),
out.size()
);
return out;
}
static std::string w2u(const std::wstring& in)
{
std::string out(in.size() * 2, 0x00);
std::size_t bytes_left = iconv_to(
"UTF-8", "WCHAR_T",
reinterpret_cast<char*>(const_cast<wchar_t*>(in.c_str())),
(in.size() * sizeof(wchar_t)),
const_cast<char*>(out.c_str()),
out.size()
);
out.resize(out.size() - bytes_left);
return out;
}
static std::wstring u2w(const std::string& in)
{
std::wstring out(in.size(), 0x00);
std::size_t bytes_left = iconv_to(
"WCHAR_T", "UTF-8",
const_cast<char*>(in.c_str()),
in.size(),
reinterpret_cast<char*>(const_cast<wchar_t*>(out.c_str())),
(out.size() * sizeof(wchar_t))
);
out.resize(out.size() - (bytes_left / sizeof(wchar_t)));
return out;
}
static std::string m2u(const std::string& in)
{
std::string out(in.size() * 2, 0x00);
std::size_t bytes_left = iconv_to(
"UTF-8", "",
const_cast<char*>(in.c_str()),
in.size(),
const_cast<char*>(out.c_str()),
out.size()
);
out.resize(out.size() - bytes_left);
return out;
}
static std::string u2m(const std::string& in)
{
std::string out(in.size(), 0x00);
std::size_t bytes_left = iconv_to(
"", "UTF-8",
const_cast<char*>(in.c_str()),
in.size(),
const_cast<char*>(out.c_str()),
out.size()
);
out.resize(out.size() - bytes_left);
return out;
}
#endif
}
// file
namespace ven {
static const char* filename(const char* path)
{
if (!path) return path;
const char* p = strrchr(path, '\\');
if (!p) p = strrchr(path, '/');
if (p) return p + 1;
return path;
}
static std::string basedir(const char* path)
{
if (!path) return path;
const char* p = strrchr(path, L'\\');
if (!p) p = strrchr(path, '/');
if (p) return std::string(path, p);
return path;
}
static const wchar_t* filename(const wchar_t* path)
{
if (!path) return path;
const wchar_t* p = wcsrchr(path, L'\\');
if (!p) p = wcsrchr(path, L'/');
if (p) return p + 1;
return path;
}
static std::wstring basedir(const wchar_t* path)
{
if (!path) return path;
const wchar_t* p = wcsrchr(path, L'\\');
if (!p) p = wcsrchr(path, L'/');
if (p) return std::wstring(path, p);
return path;
}
static std::string binary_path()
{
#if defined(WINDOWS)
char str[256] = { 0, };
GetModuleFileNameA(NULL, str, 256);
return str;
#else
char str[256] = { 0, };
readlink("/proc/self/exe", str, 256);
return str;
#endif
}
static std::wstring binary_wpath()
{
#if defined(WINDOWS)
wchar_t str[256] = { 0, };
GetModuleFileNameW(NULL, str, 256);
return str;
#else
return m2w(binary_path());
#endif
}
static std::string binary_filename()
{
return filename(binary_path().c_str());
}
static std::wstring binary_wfilename()
{
return filename(binary_wpath().c_str());
}
static bool mkdir(const std::string& path)
{
char buf[1024] = { 0, };
std::size_t len = path.size();
const char* p = path.c_str();
for (std::size_t i = 0; i < len; i++) {
buf[i] = *(p + i);
if (buf[i] == '\\' || buf[i] == '/' || (i == (len - 1))) {
#if defined(WINDOWS)
::CreateDirectoryA(buf, NULL);
#else
::mkdir(buf, 0755);
#endif
}
}
return true;
}
static bool mkdir(const std::wstring& path)
{
#if defined(WINDOWS)
wchar_t buf[1024] = { 0, };
std::size_t len = path.size();
const wchar_t* p = path.c_str();
for (std::size_t i = 0; i < len; i++) {
buf[i] = *(p + i);
if (buf[i] == L'\\' || buf[i] == L'/' || (i == (len - 1))) {
::CreateDirectoryW(buf, NULL);
}
}
#else
return mkdir(w2u(path));
#endif
return true;
}
}
// etc
namespace ven {
static bool has_console()
{
#if defined(WINDOWS)
return (GetStdHandle(STD_INPUT_HANDLE) != NULL);
#else
return isatty(STDOUT_FILENO);
#endif
}
#if !defined(WINDOWS)
static int linux_kbhit(void)
{
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
#endif
}
| true |
224e3db671b926177bec34864d5f12b1001d33b6 | C++ | iam-abbas/cs-algorithms | /Searching and Sorting/Binary Search/C++/Binary Search.cpp | UTF-8 | 910 | 3.953125 | 4 | [
"MIT"
] | permissive | // Coding Binary Search Algorithm through Functions Topic Approach
#include<iostream>
using namespace std ;
//Function that implements the binary search algorithm
int BinarySearch(int arr[] ,int n , int val )
{
int start=0 ;
int end=n-1 ;
int mid ;
while(start<=end)
{
mid=(start+end)/2 ;
if(val==arr[mid])
{
return mid ;
}
else if(val > arr[mid])
{
start=mid+1 ;
}
else
{
end=mid-1 ;
}
}
return -1 ;
}
//Driver code for the function
int main()
{
int arr[50],n ;
int result ;
cout << "Enter the no. of elements do u want to enter" ;
cin >> n ;
cout << "Enter the elements that you want to insert in the Array " << endl ;
for(int i=0 ; i<n ; i++)
{
cin >> arr[i] ;
}
cout << "Enter the element that you want to search for in the Array" << endl ;
int val ;
cin >> val ;
result= BinarySearch(arr,n,val) ;
cout << result << endl ;
}
| true |
f2ab3363c1daf74e294f01c0d4b866407a305f20 | C++ | rwalker-com/Arduino | /libraries/misc/md10c/md10c.ino | UTF-8 | 435 | 2.890625 | 3 | [] | no_license | #include "md10c.h"
static MD10C motor(4,/* aka D4, direction */
3 /* aka D3, pwm */);
static void setup(void)
{
Serial.begin(115200);
}
static void loop(void)
{
static int speed = 0;
static int increment = 1;
motor.run(speed += increment);
if (speed >= 255 || speed <= -255) {
increment = -increment;
}
Serial.print(speed); Serial.print(" ");
Serial.println();
delay(100);
}
| true |
435f5ee1d40c9efd3625ff0058b3a9efbfe6983d | C++ | T1g/Ray-Tracer | /RGBColor.cpp | UTF-8 | 1,344 | 3.625 | 4 | [] | no_license | #include "RGBColor.h"
RGBColor::RGBColor(){
}
RGBColor::RGBColor (float RR, float GG, float BB) {
r = RR;
g = GG;
b = BB;
}
RGBColor::RGBColor(const RGBColor& old){
r = old.r;
g = old.g;
b = old.b;
}
RGBColor::~RGBColor(){
}
RGBColor& RGBColor::operator= (const RGBColor& old){
//delete anything if necessary
r = old.r;
g = old.g;
b = old.b;
return *this;
}
//NOTE: might have to declare new when passing back these things.
RGBColor RGBColor::operator+ (const RGBColor& other){
RGBColor sum(r+other.r, g+other.g, b+other.b);
return sum;
}
RGBColor RGBColor::operator- (const RGBColor& other){
RGBColor diff(r-other.r, g-other.g, b-other.b);
return diff;
}
RGBColor RGBColor::operator*(float s){
RGBColor scalar_product(s*r, s*g, s*b);
return scalar_product;
}
RGBColor RGBColor::operator/(float s){
RGBColor scalar_divide(r/s, g/s, b/s);
return scalar_divide;
}
void RGBColor::setValues(float RR, float GG, float BB){
r = RR;
g = GG;
b = BB;
}
void RGBColor::setR(float RR){
r = RR;
}
void RGBColor::setG(float GG){
g = GG;
}
void RGBColor::setB(float BB){
b = BB;
}
float RGBColor::getR() const{
return r;
}
float RGBColor::getG() const{
return g;
}
float RGBColor::getB() const{
return b;
}
void RGBColor::printFloats() const{
printf("(R: %f, G: %f, B: %f)\n", r, g, b);
} | true |
c9bede99b865935a57a2cbb4fccd6a2c06f98800 | C++ | JingxueLiao/Data_Structures_and_Algorithms | /problems/longest_common_prefix.cpp | UTF-8 | 602 | 3.765625 | 4 | [
"MIT"
] | permissive | // Write a function to find the longest common prefix string amongst an array of strings.
#include <string>
#include <vector>
using namespace std;
string LongestCommonPrefix(const vector<string> &strs) {
if (strs.empty())
return string();
string prefix;
int i = 0;
while (true) {
int j = 0;
while (j < strs.size()) {
if (i == strs[j].size() || strs[j][i] != strs[0][i])
break;
++j;
}
if (j != strs.size())
break;
prefix.push_back(strs[0][i]);
++i;
}
return prefix;
}
| true |
8f715e1fcd018a4152d6596512725dbe113f65b7 | C++ | shawwn/bootstrap | /Documentation/Code/Engine/Common/MRay.h | WINDOWS-1252 | 2,820 | 2.71875 | 3 | [
"MIT"
] | permissive | //----------------------------------------------------------
//! File: MRay.h
//! Author: Kevin Bray
//! Created: 07-17-06
//
//! Purpose: To contain a ray.
//
//! Copyright 2004 Bootstrap Studios. All rights reserved.
//----------------------------------------------------------
#pragma once
//! project includes.
#include "MVec3.h"
//! forward declarations.
class MMat4x4;
class MMat3x3;
class MSphere;
class MAABox;
class MOBox;
class MPlane;
class MLineSegment;
//**********************************************************
//! class MRay
//**********************************************************
class MRay
{
public:
MRay();
MRay( const MVec3& start, const MVec3& dir );
~MRay();
void SetStart( const MVec3& start ) { _start = start; }
void SetDir( const MVec3& dir );
void SetDirFast( const MVec3& dir );
const MVec3& GetStart() const { return _start; }
const MVec3& GetDir() const { return _dir; }
//! returns true if the ray intersects with the box provided.
bool Intersect( const MAABox& box, float maxDist = FLT_MAX ) const;
bool Intersect( MVec3& hitLoc, const MAABox& box, float maxDist = FLT_MAX ) const;
bool Intersect( const MOBox& box ) const;
bool Intersect( MVec3& coord, const MOBox& box ) const;
bool Intersect( const MSphere& sphere ) const;
//! transforms the ray.
MRay Transform( const MMat4x4& mat, const MMat3x3& normalRot ) const;
//! returns true if the ray intersects with the plane. It also returns where
//! the ray intersects with the plane.
bool Intersect( MVec3& hitPos, const MPlane& plane, float maxDist ) const;
//! returns the distance from the ray to the triangle as well as the barycentric
//! coordinates of the intersection if a intersection occurs. If no intersection
//! occurs, then the function returns -1.0.
bool Intersect( MVec3& point, float& u, float& v, const MVec3& pt0, const MVec3& pt1, const MVec3& pt2,
bool twoSided = false ) const;
bool Intersect( float& dist, MVec3& point, float& u, float& v, const MVec3& pt0, const MVec3& pt1, const MVec3& pt2, bool twoSided = false, float maxDist = FLT_MAX ) const;
bool Intersect( MVec3& point, float& u, float& v, const MVec3& pt0, const MVec3& pt1, const MVec3& pt2,
const MVec3& faceNormal, bool twoSided = false ) const;
//! distance from the ray to a point.
float Dist( const MVec3& point ) const;
//! distance between two rays.
// float Dist( const MRay& ray, float epsilon ) const;
//! distance between a ray and a line segment. This function returns -1.0f if
//! the line segment is just a point.
float Dist( const MLineSegment& segment, float epsilon ) const;
float Dist( const MLineSegment& segment, float& rayMu, float& segMu, float epsilon ) const;
private:
MVec3 _start;
MVec3 _dir;
};
| true |
0214cee574963c6e08169c27f8edce99da132c91 | C++ | justin111175/GE2 | /課題1/Project1/CardServer.h | SHIFT_JIS | 525 | 2.6875 | 3 | [] | no_license | #pragma once
#include <utility>
#define LpCardServer CardServer::GetInstance()
using PairInt = std::pair<int, int>;
class CardServer
{
public:
// ÓIVOh
static CardServer& GetInstance()
{
static CardServer s_Instance;
return s_Instance;
}
bool Payment(int price); // J[hx
PairInt& GetCardState(void); // J[hf[^
private:
PairInt cardData; // J[h̃f[^ifirstFcAsceondFzj
CardServer();
~CardServer();
};
| true |
91a74291aad16cb0a8dd5d590a0272ee123b5b11 | C++ | kusejoan/FlightSimulator | /src/Models/PlaneParts/Wing.cpp | UTF-8 | 1,153 | 2.71875 | 3 | [] | no_license | //
// Created by igor on 22.05.19.
//
#include <Models/AtmosphereModel.h>
#include <Basic/Physics.h>
#include "Wing.h"
#include <math.h>
std::pair<ForceV, MomentOfForce> Wing::getForces(const PlaneState &state) const {
VelocityV airspeed = getRlativeAirspeed(state);
Velocity parallelAirspeed = Velocity(airspeed.dot(forward).getMagnitude());
double angleOfAttack = atan((airspeed.dot(up) / airspeed.dot(forward)).getMagnitude());
Density d = AtmosphereModel::getDensity(Length(state.position.point.getY()));
ForceV drag = 0.5 * forward * d * area * parallelAirspeed * parallelAirspeed
* getCoefficientOfDrag(angleOfAttack);
ForceV lift = 0.5 * up * d * area * parallelAirspeed * parallelAirspeed
* getCoefficientOfLift(angleOfAttack);
MomentOfForce momentOfDrag = (drag + lift).cross(LengthV(centerOfMass - state.centerOfMass));
return std::make_pair(drag + lift, momentOfDrag);
}
double Wing::getCoefficientOfDrag(double angleOfAttack) const {
return angleOfAttack / 3.14 + 0.01;
}
double Wing::getCoefficientOfLift(double angleOfAttack) const {
return angleOfAttack;
}
| true |
d5241f4b7d8fa63d797ac03cd5de1a6b85db5b93 | C++ | YannGarcia/repo | /dev/g++/ifsttar/wifiMapping/aggreg/src/datum.cpp | UTF-8 | 6,668 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include <sstream> // Used for std::ostringstream
#include <stdexcept> // Used for std::invalid_argument
#include "ipcCommon.h"
#include "datum.h"
namespace beagleboneStorage {
datum::datum(const std::vector<unsigned char> & p_data) : _archive(), _xfer(0.0), _bw(0.0), _atemp(0.0), _dutyCycle(0.0), _elevation(0.0), _speed(0.0), _heading(), _latitude(""), _longitude(""), _gpsDateTime(0), _timestamp(0), _bssids() {
processArchive(p_data);
} // End of Constructor
datum::~datum() {
} // End of Destructor
void datum::processArchive(const std::vector<unsigned char> & p_data) {
// Sanity check
if (p_data.size() == 0) {
std::cerr << "datum::processArchive: Wrong parameters" << std::endl;
return;
}
// Extract shared memory segment identifer
unsigned char segmentId;
std::vector<unsigned char> data(p_data);
do {
_archive.deserialize(data, reinterpret_cast<char *>(&segmentId));
processSegmentId(data, segmentId);
// std::clog << "datum::processArchive: current size=" << (int)data.size() << std::endl;
} while (data.size() != 0);
}
void datum::processSegmentId(std::vector<unsigned char> & p_data, unsigned char p_segmentId) {
// std::clog << ">>> datum::processSegmentId: " << static_cast<unsigned int>(p_segmentId) << std::endl;
switch (p_segmentId) {
case IPERF_SEGMENT_ID:
_archive.deserialize(p_data, &_xfer);
_archive.deserialize(p_data, &_bw);
break;
case GPS_SEGMENT_ID:
deserializeGpsData(p_data);
break;
case ACC_SEGMENT_ID:
break;
case TEMP_SEGMENT_ID:
_archive.deserialize(p_data, &_atemp);
_archive.deserialize(p_data, &_dutyCycle);
break;
case RTC_SEGMENT_ID: {
unsigned char status;
_archive.deserialize(p_data, reinterpret_cast<char *>(&status));
_archive.deserialize(p_data, &_timestamp);
}
break;
case WLAN_SEGMENT_ID:
deserializeWlanData(p_data);
break;
default:
std::cerr << "datum::processSegmentId: Corrupted archive: " << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(p_segmentId) << std::endl;
} // End of 'switch' statement
// std::clog << "<<< datum::processSegmentId" << std::endl;
}
void datum::deserializeGpsData(std::vector<unsigned char> & p_data) {
// std::clog << ">>> datum::deserializeGpsData" << std::endl;
std::string str;
_archive.deserialize(p_data, str);
// std::clog << "datum::processSegmentId: date/time='" << str << "'" << std::endl;
// TODO Convert GPS date/time into time_t
_gpsDateTime = time(NULL);
/*if (_timestamp == 0) {
_timestamp = _gpsDateTime;
}*/
// std::clog << "datum::processSegmentId: _timestamp='" << _timestamp << "'" << std::endl;
_archive.deserialize(p_data, _latitude);
// std::clog << "datum::processSegmentId: latitude='" << _latitude << "'" << std::endl;
_archive.deserialize(p_data, _longitude);
// std::clog << "datum::processSegmentId: longitude='" << _longitude << "'" << std::endl;
// Speed
_archive.deserialize(p_data, str);
// std::clog << "datum::processSegmentId: speed='" << str << "'" << std::endl;
if (str.length() != 0) {
try {
_speed = 1.852/*knots to km/h*/ * std::stof(str); // Convert into float
} catch (std::invalid_argument & i) {
_speed = 0.0;
}
}
// Elevation
_archive.deserialize(p_data, str);
// std::clog << "datum::processSegmentId: elevation='" << str << "'" << std::endl;
if (str.length() != 0) {
try {
_elevation = std::stof(str); // Convert into float
} catch (std::invalid_argument & i) {
_elevation = 0.0;
}
}
// Heading
_archive.deserialize(p_data, str);
// std::clog << "datum::processSegmentId: heading='" << str << "'" << std::endl;
if (str.length() != 0) {
try {
_heading = std::stof(str); // Convert into float
} catch (std::invalid_argument & i) {
_heading = 0.0;
}
}
// Yawrate
_archive.deserialize(p_data, str);
// std::clog << "datum::processSegmentId: yawrate='" << str << "'" << std::endl;
// if (str.length() != 0) {
// _yawrate = std::stof(str); // Convert into float
// }
// std::clog << "<<< datum::deserializeGpsData" << std::endl;
}
void datum::deserializeWlanData(std::vector<unsigned char> & p_data) {
// Number of BSSID detected
unsigned char bssidsNum = 0x00;
_archive.deserialize(p_data, reinterpret_cast<char *>(&bssidsNum));
if (bssidsNum != 0x00) {
// std::clog << "datum::deserializeWlanData: #bssid=" << static_cast<unsigned int>(bssidsNum) << std::endl;
for (unsigned char i = 0x00; i < bssidsNum; i++) { // Get BSSIDs
unsigned char fieldsNum = 0x00;
_archive.deserialize(p_data, reinterpret_cast<char *>(&fieldsNum));
// std::clog << "datum::deserializeWlanData: #field=" << static_cast<unsigned int>(fieldsNum) << std::endl;
std::vector<std::string> v(fieldsNum);
for (unsigned char j = 0x00; j < fieldsNum; j++) { // Get BSSIDs description
std::string str;
_archive.deserialize(p_data, str);
v[j] = str;
} // End of 'for' statement
// std::clog << "datum::deserializeWlanData: key=" << v[0] << std::endl;
_bssids.insert(std::pair<std::string, std::vector<std::string> >(v[0], v));
} // End of 'for' statement
}
}
const std::string & datum::toString() const {
static std::string str;
std::ostringstream os;
os <<
"timestamp=" << static_cast<unsigned int>(_timestamp) <<"," <<
"xfer=" << _xfer << "," <<
"bw=" << _bw << "," <<
"atemp=" << _atemp << "," <<
"dutyCycle=" << static_cast<unsigned int>(_dutyCycle) << "," <<
"latitude=" << _latitude << "," <<
"longitude=" << _longitude << "," <<
"elevation=" << _elevation << "," <<
"speed=" << _speed << "," <<
"heading=" << _heading;
// "yawrate = " << _yawrate << "," <<
unsigned int counter = 0;
for (std::map<std::string, std::vector<std::string> >::const_iterator it = _bssids.begin(); it != _bssids.end(); ++it) {
os << ",bssid#" << counter++ << "=" << it->first << ",";
os << " datarate=" << it->second[IDX_DATARATE] << ",";
os << " channelId=" << it->second[IDX_CHANNEL] << ",";
os << " rssid=" << it->second[IDX_RSSID] << ",";
os << " essid=" << it->second[IDX_ESSID];
} // End of 'for' statement
os << std::endl;
str = os.str();
return str;
}
} // End of namespace beagleboneStorage
| true |
69f424e115487f986751cd8a5253e8ddbf705977 | C++ | suhyunx/xcode-files | /20131122/main.cpp | UTF-8 | 687 | 3 | 3 | [] | no_license | //
// main.cpp
// 20131122
//
// Created by JM Park on 13. 11. 22..
// Copyright (c) 2013년 JM Park. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
const int number=4;
int en[number];
int sum=0;
int avg=0;
int *pen;
pen=en;
cout << " 영어 점수를 입력해 주세요 " << endl;
for(int i=0; i<number; i++) {
cin >> pen[i];
}
for(int i=0; i<number; i++) {
sum+=*(pen+i);
}
avg=(int)(sum/number);
cout << " 영어점수의 합점은 " << sum << endl;
cout << " 영어점수의 평균은 " << avg << endl;
return 0;
}
| true |
f3013776645a988e5ce02d4b22811a8d4f50a8f8 | C++ | Igronemyk/OI | /HDU/3001.cpp | UTF-8 | 1,782 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
int myPow(int a,int b){
int result = 1,base = a;
while(b){
if(b & 1) result*=base;
base*=base;
b >>= 1;
}
return result;
}
int graph[10][10],visit[59049][10],dp[10][59049];
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){
memset(graph,INF,sizeof(graph));
memset(visit,0,sizeof(visit));
memset(dp,INF,sizeof(dp));
for(int i = 0;i < m;i++){
int from,to,weight;
scanf("%d%d%d",&from,&to,&weight);
from--;to--;
graph[from][to] = min(graph[from][to],weight);
graph[to][from] = min(graph[to][from],weight);
}
int maxState = myPow(3,n);
for(int i = 0;i < maxState;i++){
int tmpState = i,index = 0;
while(tmpState){
visit[i][index++] = tmpState % 3;
tmpState /= 3;
}
}
for(int i = 0;i < n;i++) dp[i][myPow(3,i)] = 0;
int ans = INF;
for(int i = 0;i < maxState;i++){
bool canUpdate = true;
for(int j = 0;j < n;j++){
if(!visit[i][j]) canUpdate = false;
if(dp[j][i] == INF) continue;
for(int k = 0;k < n;k++){
if(k == j || graph[j][k] == INF || visit[i][k] == 2) continue;
dp[k][i + myPow(3,k)] = min(dp[k][i + myPow(3,k)],dp[j][i] + graph[j][k]);
}
}
if(canUpdate){
for(int j = 0;j < n;j++){
ans = min(ans,dp[j][i]);
}
}
}
printf("%d\n",ans == INF ? -1 : ans);
}
return 0;
}
| true |
0bc173eb4fff22907271646e7dfba89f28fc6b44 | C++ | alxsoares/Topcoder-4 | /srm_550_2/250.cpp | UTF-8 | 719 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class EasyConversionMachine {
public:
string isItPossible(string originalWord, string finalWord, int k);
};
string EasyConversionMachine::isItPossible(string originalWord, string finalWord, int k) {
int size = originalWord.size(), c = 0;
for (int i = 0; i < size; i++) {
if (originalWord[i] != finalWord[i]) c++;
}
cout << c << endl;
cout << c-k % 2 << endl;
if (c >= k && (c-k) % 2 == 0) return "POSSIBLE";
else return "IMPOSSIBLE";
}
int main() {
EasyConversionMachine em;
int k;
string original, final;
while (cin >> original) {
cin >> final;
cin >> k;
cout << em.isItPossible(original, final, k) << endl;
}
}
| true |
99d2ee02c0fd7a34ede32e517c95a337947c367b | C++ | KevinRobichon/Makemupo | /Makemupo/Singleton.h | UTF-8 | 369 | 3.03125 | 3 | [] | no_license | #pragma once
namespace MKPatterns
{
template<typename T> class Singleton
{
public:
static T* getInstance()
{
if (m_instance == NULL)
m_instance = new T();
}
static void destroy()
{
if (m_instance != NULL)
delete m_instance;
m_instance = NULL;
}
protected:
static T* m_instance;
private:
Singleton(){};
~Singleton(){};
};
}; | true |
3cf20287d64919b3b7757bfa7a994214d7a5cb85 | C++ | JerryTheUser/Leetcode | /Valid_Sudoku.cpp | UTF-8 | 2,650 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unsigned char rows[9][9] = {0}, cols[9][9] = {0}, boxes[9][9] = {0}, val = 0;
bool ret = true;
for(int i=0 ; i<9 ; ++i){
for(int j=0 ; j<9 ; ++j){
if(board[i][j] != '.'){
val = board[i][j] - '1';
if(rows[i][val]++ || cols[j][val]++ || boxes[i/3*3+j/3][val]++)
return false;
}
}
}
return ret;
}
};
/*
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool ret = true;
unordered_set<char> set;
for(int i=0 ; i<9 ; ++i){
for(int j=0 ; j<9 ; ++j){
if(board[i][j] != '.'){
if(set.count(board[i][j]))
return false;
else
set.insert(board[i][j]);
}
}
set.clear();
}
for(int i=0 ; i<9 ; ++i){
for(int j=0 ; j<9 ; ++j){
if(board[j][i] != '.'){
if(set.count(board[j][i]))
return false;
else
set.insert(board[j][i]);
}
}
set.clear();
}
for(int i=0 ; i<3 ; ++i){
for(int j=0 ; j<3 ; ++j){
for(int k=0 ; k<3 ; ++k){
for(int l=0 ; l<3 ; ++l){
if(board[3*i+k][3*j+l] != '.'){
if(set.count(board[3*i+k][3*j+l]))
return false;
else
set.insert(board[3*i+k][3*j+l]);
}
}
}
set.clear();
}
}
return ret;
}
};
*/
int main(){
Solution sol;
vector<vector<char>> sudoku {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};
cout << boolalpha << sol.isValidSudoku(sudoku) << '\n';
return 0;
} | true |
5388be17c207644a5e41774561d2e7f66fa22e6b | C++ | josokw/Fuzzy | /libFuzzyEngine/Defuzzification.h | UTF-8 | 2,049 | 3 | 3 | [
"MIT"
] | permissive | #ifndef DEFUZZIFICATION
#define DEFUZZIFICATION
#include "OutputFuzzySet.h"
#include <cmath>
#include <iostream>
#include <vector>
namespace {
constexpr double EPSILON = 1e-4;
inline bool equals(double d1, double d2)
{
return std::fabs(d1 - d2) < EPSILON;
}
const OutputFuzzySet *findHighestMbsSet(const std::vector<OutputFuzzySet *> &fs)
{
double highestMBS{0};
int highestIndex{0};
int index{0};
for (auto &f : fs) {
if (f->getMbs() > highestMBS) {
highestMBS = f->getMbs();
highestIndex = index;
}
++index;
}
return fs[highestIndex];
}
} // namespace
enum class DEFUZ { MoM, FoM, LoM, WA, CoS };
/// Maxima method: MoM.
inline double defuzMeanOfMaximum(const std::vector<OutputFuzzySet *> &fs)
{
return findHighestMbsSet(fs)->meanOfMaximum();
}
/// Maxima method: FoM.
inline double defuzFirstOfMaxima(const std::vector<OutputFuzzySet *> &fs)
{
return findHighestMbsSet(fs)->firstOfMaxima();
}
/// Maxima method: LoM.
inline double defuzLastOfMaxima(const std::vector<OutputFuzzySet *> &fs)
{
return findHighestMbsSet(fs)->lastOfMaxima();
}
/// Also known as Sugeno defuzzyfication, this method can only be used for
/// symmetrical memebrship functions.
inline double defuzWeightedAverage(const std::vector<OutputFuzzySet *> &fs)
{
double crisp{0.0};
double numerator{0.0};
double denomenator{0.0};
for (auto &f : fs) {
numerator += f->getMbs() * f->meanOfMaximum();
denomenator += f->getMbs();
}
crisp = denomenator != 0.0 ? numerator / denomenator : 0;
return crisp;
}
/// A centroid method: CoS.
inline double defuzCenterOfSums(const std::vector<OutputFuzzySet *> &vfs)
{
double crisp{0};
double numerator{0.0};
double denomenator{0.0};
for (auto &fs : vfs) {
auto [minr, maxr] = fs->range();
auto midpoint{(minr + maxr) / 2.0};
auto ar{fs->area()};
numerator += ar * midpoint;
denomenator += ar;
}
crisp = numerator / denomenator;
return crisp;
}
#endif // DEFUZZIFICATION
| true |
0d88c4253bffd7a6190645ca2a14817a28115017 | C++ | clairew17/LeetCode | /322.CoinChange.cc | UTF-8 | 1,318 | 3.140625 | 3 | [] | no_license | //322.CoinChange.cc
#include"../CC/header.h"
void helper(vector<int>& coins, int begin, int amount, int count, int &min_num){
if(begin>=coins.size()){
return;
}
if(coins[begin]>amount)return;
int maxnum = amount/coins[begin];
for(int i=0;i<=maxnum;i++){
int newcount = count + i;
int new_amount = amount-i*coins[begin];
if(new_amount == 0){
if(min_num==-1 || newcount < min_num)
min_num = newcount;
return;
}
//cout << amount-i*coins[begin] << '\t' << coins[begin] <<endl;
helper(coins, begin+1, new_amount, newcount, min_num);
}
return;
}
/*
int coinChange(vector<int>& coins, int amount){
int min_num = -1;
int count = 0;
helper(coins, 0, amount, count, min_num);
return min_num;
}*/
//dp
int coinChange(vector<int>& coins, int amount) {
vector<int>dp(amount+1,INT_MAX-1);
dp[0] = 0;
for(int i=1;i<=amount;i++){
for(int j =0;j<coins.size();j++){
if(coins[j]<=i)
dp[i] = min(dp[i], dp[i-coins[j]]+1);
}
}
//PrintVector(dp);
return dp[amount]>amount?-1:dp[amount];
}
int main(){
//int arr[] = {1, 2, 5};
//int arr[] = {5, 306, 188, 467, 494};
int arr[] = {3, 7, 405, 436};
int amount = 11;
amount = 7047;
amount= 8839;
vector<int>coins = Arr2Vec(arr, 4);
PrintVector(coins);
int res = coinChange(coins, amount);
cout << res << endl;
return 0;
} | true |
00d1d6614575064a5ddf02fb4e326e6fd8de18d2 | C++ | ckhawks/utd-cs-assignments | /cs2336/ParkingLot/Bus.h | UTF-8 | 544 | 2.765625 | 3 | [] | no_license | /*
* Bus.h
*
* Author: Carter Hawks from CS2336.001
* To run: the main() is located in ParkingLot.cpp
* Different sections of the code are commented out;
* these sections accomplish the different variations of the parking lot.
*/
// Bus: simple class that represents a Bus object. Sole purpose is to return the correct vehicleType enum in the getVehicleType() method.
#ifndef BUS_H_
#define BUS_H_
#include "Vehicle.h"
class Bus: public Vehicle {
public:
Bus();
virtual ~Bus();
int getVehicleType();
};
#endif /* BUS_H_ */
| true |
2445b91747a2e94b6aff537d18fce0559cc6967f | C++ | Mohamed-Hossam/Problem-Solving | /codeforces/513-A/513-A-9748482.cpp | UTF-8 | 590 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include <functional>
#include <sstream>
#include<stack>
#include<queue>
#include <bitset>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
using namespace std;
int main()
{
int n1, n2, k1, k2;
cin >> n1 >> n2 >> k1 >> k2;
for (int i = 0; i < 1000; i++)
{
if (i % 2 == 0)
{
n1--;
if (n1 == 0){ cout << "Second"; return 0; }
}
else
{
n2--;
if (n2 == 0){ cout << "First"; return 0; }
}
}
} | true |
ae6e541fc62b3605a9e955e536b72cfb6c956242 | C++ | chromium/chromium | /chrome/browser/performance_manager/policies/working_set_trimmer_policy_unittest.cc | UTF-8 | 2,671 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/performance_manager/policies/working_set_trimmer_policy.h"
#include <memory>
#include "components/performance_manager/graph/process_node_impl.h"
#include "components/performance_manager/test_support/graph_test_harness.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace performance_manager {
namespace policies {
class MockWorkingSetTrimmerPolicy : public WorkingSetTrimmerPolicy {
public:
MockWorkingSetTrimmerPolicy() {}
MockWorkingSetTrimmerPolicy(const MockWorkingSetTrimmerPolicy&) = delete;
MockWorkingSetTrimmerPolicy& operator=(const MockWorkingSetTrimmerPolicy&) =
delete;
~MockWorkingSetTrimmerPolicy() override {}
MOCK_METHOD1(TrimWorkingSet, void(const ProcessNode*));
};
class WorkingSetTrimmerPolicyTest : public GraphTestHarness {
public:
using Super = GraphTestHarness;
WorkingSetTrimmerPolicyTest() {}
WorkingSetTrimmerPolicyTest(const WorkingSetTrimmerPolicyTest&) = delete;
WorkingSetTrimmerPolicyTest& operator=(const WorkingSetTrimmerPolicyTest&) =
delete;
~WorkingSetTrimmerPolicyTest() override {}
void SetUp() override {
Super::SetUp();
policy_ = std::make_unique<WorkingSetTrimmerPolicy>();
}
void SetLastTrimTime(const ProcessNode* node, base::TimeTicks time) {
policy_->SetLastTrimTime(node, time);
}
base::TimeTicks GetLastTrimTime(const ProcessNode* node) {
return policy_->GetLastTrimTime(node);
}
protected:
std::unique_ptr<WorkingSetTrimmerPolicy> policy_;
};
// Validate that we can set and get the last trim time on a ProcessNode.
TEST_F(WorkingSetTrimmerPolicyTest, SetTrimTimeOnNode) {
auto process_node = CreateNode<ProcessNodeImpl>();
ASSERT_NE(process_node.get(), nullptr);
auto now_ticks = base::TimeTicks::Now();
SetLastTrimTime(process_node.get(), now_ticks);
ASSERT_EQ(GetLastTrimTime(process_node.get()), now_ticks);
}
// Validate that when all frames in a ProcessNode are frozen we attempt to trim
// the working set.
TEST_F(WorkingSetTrimmerPolicyTest, TrimOnFrozen) {
std::unique_ptr<MockWorkingSetTrimmerPolicy> mock_policy(
new MockWorkingSetTrimmerPolicy);
auto process_node = CreateNode<ProcessNodeImpl>();
ASSERT_NE(process_node.get(), nullptr);
EXPECT_CALL(*mock_policy, TrimWorkingSet(process_node.get())).Times(1);
graph()->PassToGraph(std::move(mock_policy));
process_node->OnAllFramesInProcessFrozenForTesting();
}
} // namespace policies
} // namespace performance_manager
| true |
2277305547ad9217f556de5353cbf65ac5e6877d | C++ | setzer22/miri_CA_crowdsym | /PlaneRenderer.h | UTF-8 | 1,501 | 2.703125 | 3 | [] | no_license | #pragma once
#include "Geometry.h"
#include "Texture.h"
#include <SDL2/SDL_opengl.h>
namespace plane_renderer {
int plane_tex_id;
void init() {
plane_tex_id = texture::load_texture("./plane_texture.tga");
}
void render_plane(const Plane &p, float box_size) {
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_COLOR_MATERIAL);
// set the texture id we stored in the map user data
glBindTexture(GL_TEXTURE_2D, (GLuint)plane_tex_id);
// set the texture coordinate buffer
glm::vec3 o = p.origin;
glm::vec3 n = glm::normalize(p.normal);
glm::vec3 up(0, 0, 1);
glm::vec3 r = glm::cross(n, up);
float hscale = box_size;
float vscale = 0.25 * box_size;
glm::vec3 points[4];
points[0] = o + r * hscale + up * vscale;
points[1] = o + r * hscale;
points[2] = o + -r * hscale;
points[3] = o + -r * hscale + up * vscale;
static float tex_coords[4][2] = {
{8.0f, 2.0f}, {8.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 2.0f}};
glBegin(GL_QUADS);
for (int i = 0; i < 4; ++i) {
glNormal3f(n.x, n.y, n.z);
glColor3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(tex_coords[i][0], tex_coords[i][1]);
glVertex3f(points[i].x, points[i].y, points[i].z);
}
glEnd();
glDisable(GL_DEPTH_TEST);
glDisable(GL_COLOR_MATERIAL);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
} // namespace plane_renderer
| true |
5cb8158649687f9218e21ae3c51647022f60d761 | C++ | chrystallagh/HavadjiaChrystalla_CSC17a_42824 | /Homework/Assignment 4/Assignmnet4.sngl_Funtion/RetailItem.h | UTF-8 | 905 | 2.78125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: RetailItem.h
* Author: chrystallahavadjia
*
* Created on April 28, 2016, 5:41 PM
*/
#ifndef RETAILITEM_H
#define RETAILITEM_H
#include<string>
using namespace std;
//user libraries
class RetailItem
{
private:
string dscrptn; // variable with a brief description of the item.
int untsOnHand; // number of units currently in inventory.
float price; //holds the item’s retail price.
public:
RetailItem(string, int, float);
void setDscrptn(string);
void setUnstOnHand(int);
void setPrice(float);
string getDscrptn() const;
int getUnstOnHand() const;
float getPrice() const;
};
#endif /* RETAILITEM_H */
| true |
08c8eacd0c9b3bd4a2ce76ab9375d06145306270 | C++ | Vasiliska89/myList | /l.cpp | WINDOWS-1251 | 3,466 | 3.328125 | 3 | [] | no_license | #include "l.h"
void menu() {
std::cout << "\n";
std::cout << "1 - " << "\n";
std::cout << "2 - " << "\n";
std::cout << "3 - " << "\n";
std::cout << "4 - " << "\n";
std::cout << "5 - " << "\n";
std::cout << "6 - " << "\n";
std::cout << "7 - " << "\n";
std::cout << "8 - " << "\n";
std::cout << "9 - " << "\n";
std::cout << "10 - - L " << "\n";
std::cout << "0 - " << "\n";
}
void push(list*& head, int val) {
list* tmp = new list;
tmp->id = val;
tmp->next = head;
head = tmp;
}
void show(list* sp) {
while (sp != NULL)
{
std::cout << sp->id << " ";
sp = sp->next;
}
}
void addbefore(list*& sp, int val, int id) {
if (sp->id == id) push(sp, val);
else {
if (sp->next != NULL && sp->next->id == id) {
list* tmp = new list;
tmp->id = val;
tmp->next = sp->next;
sp->next = tmp;
}
else {
if (sp->next == NULL) std::cout << "\n" << " ." << "\n";
else addbefore(sp->next, val, id);
}
}
}
void addafter(list*& sp, int val, int id) {
if (sp->id == id) {
list* tmp = new list;
tmp->id = val;
tmp->next = sp->next;
sp->next = tmp;
}
else {
if (sp->next != NULL) addafter(sp->next, val, id);
else std::cout << "\n" << " ." << "\n";
}
}
void tail(list*& sp, int val) {
if (sp->next == NULL) {
list* tmp = new list;
tmp->id = val;
tmp->next = NULL;
sp->next = tmp;
}
else tail(sp->next, val);
}
void pop(list*& sp) {
list* tmp = sp->next;
free(sp);
sp = tmp;
}
void poptail(list*& sp) {
if (sp->next == NULL) {
list* tmp = sp->next;
free(sp);
sp = tmp;
}
else poptail(sp->next);
}
void del(list*& sp, int id) {
if (sp->id == id) {
list* tmp = sp->next;
free(sp);
sp = tmp;
}
else {
if (sp->next != NULL && sp->next->id == id) sp->next = sp->next->next;
else {
if (sp->next != NULL) del(sp->next, id);
else std::cout << "\n" << " ." << "\n";
}
}
}
void del2(list*& sp, int id) {
if (sp->next != NULL && sp->next->id == id) {
list* tmp = sp->next->next;
free(sp->next);
sp->next = tmp;
del2(sp, id);
}
else if (sp->next != NULL && sp->next->id != id) del2(sp->next, id);
}
void firstonly(list*& sp) {
del2(sp, sp->id);
if (sp->next != NULL)firstonly(sp->next);
}
void generate(list*& head) {
srand(time(0));
push(head, rand()%10);
for (int i = 0; i < 9; i++) {
tail(head, rand() % 10);
}
} | true |
41c759ccb0f0ad69be6bd29e392087d26c75fddb | C++ | 237K/ProblemSolving | /SAMSUNG_SWEA#2382_ver2.cpp | UHC | 3,121 | 2.625 | 3 | [] | no_license | //
// OS Windows
// 2019.05.09
//
// [Algorithm Problem Solving]
//
// SAMSUNG SW Expert Academy <#2382> () ̻ ݸ
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <memory.h>
#include <vector>
using namespace std;
typedef pair<int, int> coor;
const static int SIZE = 100;
const static int MAX_MICROORGA = 1000;
const static int DIRECT = 5;
struct MICROORGA
{
int r, c, k, d;
};
static int dir[DIRECT][2] = { {0, 0}, {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
static MICROORGA mo[MAX_MICROORGA];
static vector<int> crush[SIZE][SIZE];
static vector<coor> crush_loc;
static int N, M, K;
inline void print()
{
for (register int r = 0; r < N; ++r)
{
for (register int c = 0; c < N; ++c)
{
cout << crush[r][c].size() << ' ';
}
cout << "\n\n";
}
cout << "\n\n";
}
inline void crush_init()
{
for (register int r = 0; r < N; ++r)
{
for (register int c = 0; c < N; ++c)
{
crush[r][c].clear();
}
}
crush_loc.clear();
}
inline int change_direct(int cur_dir)
{
int next_dir = 0;
if (cur_dir == 1 || cur_dir == 3) next_dir = cur_dir + 1;
else next_dir = cur_dir - 1;
return next_dir;
}
inline int cal_ret()
{
int sum = 0;
for (register int i = 0; i < K; ++i)
sum += mo[i].k;
return sum;
}
inline int simulation()
{
while (M--)
{
/*cout << "time : " << M << '\n';
print();*/
for (register int i = 0; i < K; ++i)
{
if (mo[i].k > 0)
{
int cr = mo[i].r;
int cc = mo[i].c;
int cd = mo[i].d;
int nr = cr + dir[cd][0];
int nc = cc + dir[cd][1];
mo[i].r = nr;
mo[i].c = nc;
if (nr == 0 || nc == 0 || nr == N - 1 || nc == N - 1)
{
mo[i].d = change_direct(cd);
mo[i].k /= 2;
continue;
}
crush[nr][nc].push_back(i);
if (crush[nr][nc].size() > 1)
crush_loc.push_back({ nr, nc });
}
}
if (crush_loc.size())
{
int first_order_mo = 0, idx = 0;
int num_crush = crush_loc.size();
for (register int j = 0; j < num_crush; ++j)
{
int ccr = crush_loc[j].first;
int ccc = crush_loc[j].second;
// ū ̻ ã
int temp = 0;
for (vector<int>::size_type s = 0; s < crush[ccr][ccc].size(); ++s)
{
int cur_mo_idx = crush[ccr][ccc][s];
temp += mo[cur_mo_idx].k;
if (first_order_mo < mo[cur_mo_idx].k)
{
first_order_mo = mo[cur_mo_idx].k;
idx = cur_mo_idx;
}
}
// ū ̻ ħ
for (vector<int>::size_type s = 0; s < crush[ccr][ccc].size(); ++s)
{
int cur_mo_idx = crush[ccr][ccc][s];
if (idx != cur_mo_idx)
mo[cur_mo_idx].k = 0;
}
mo[idx].k = temp;
}
}
crush_init();
}
return cal_ret();
}
int main(int argc, char** argv)
{
freopen("s_input2382.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(NULL);
int T;
register int test_case, i;
int _r, _c, _k, _d;
cin >> T;
for (test_case = 1; test_case <= T; ++test_case)
{
cin >> N >> M >> K;
for (i = 0; i < K; ++i)
{
cin >> _r >> _c >> _k >> _d;
mo[i] = { _r, _c, _k, _d };
}
cout << "#" << test_case << ' ' << simulation() << '\n';
}
return 0;
} | true |
a74e6556423bff75a6f6dfc201e05aff21952c7b | C++ | vaneet-hash/Competitive-Programming-codes-CPP | /COVIDLQ.cpp | UTF-8 | 515 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t, n;
cin>>t;
while(t--) {
cin>>n;
vector<int> a(n);
for(int i=0; i<n; i++)
cin>>a[i];
bool flag=true;
for(int i=0; i<n; i++) {
if(!flag)
break;
if(a[i]==1) {
for(int j=i+1; j<i+6 && j<n; j++) {
if(a[j]==1) {
flag=false;
break;
}
}
}
}
if(flag)
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
} | true |
76384c9f38bfb1226b16e9c67ba85b04ef451709 | C++ | arturoverdin/AVLTree-BSTree-RotateTree | /rotateBST.h | UTF-8 | 4,303 | 3.609375 | 4 | [] | no_license | #ifndef ROTATEBST_H
#define ROTATEBST_H
#include "bst.h"
#include <set>
template<typename Key, typename Value>
class rotateBST : public BinarySearchTree<Key, Value> {
public:
rotateBST();
virtual ~rotateBST();
bool sameKeys(const rotateBST& t2) const;
void transform(rotateBST& t2) const;
protected:
void leftRotate(Node<Key, Value>* r);
void rightRotate(Node<Key, Value>* r);
private:
void linkedList(Node<Key,Value>* root, rotateBST& t2) const;
void transformHelper(Node<Key,Value>* root, Node<Key,Value>* t2_root,
rotateBST& t2) const;
Node<Key, Value>* smallestSubtree(Node<Key,Value>* r) const;
};
/**
* Calls the constructor for a BST.
*/
template<typename Key, typename Value>
rotateBST<Key,Value>::rotateBST():BinarySearchTree<Key,Value>() { }
template<typename Key, typename Value>
rotateBST<Key,Value>::~rotateBST() { }
/**
* Iterates through both BST's and inserts their keys into sets,
* returns true if they equate.
*/
template<typename Key, typename Value>
bool rotateBST<Key,Value>::sameKeys(const rotateBST& t2) const
{
std::set<Key> one;
std::set<Key> two;
typename rotateBST<Key, Value>::iterator it(this->getSmallestNode());
typename rotateBST<Key, Value>::iterator end(nullptr);
for(; it != end; ++it) {
one.insert(it->first);
}
typename rotateBST<Key, Value>::iterator jt(t2.getSmallestNode());
for(; jt != end; ++jt) {
two.insert(jt->first);
}
return one == two;
}
/**
* Calls the helper function that does the transformation.
*/
template<typename Key, typename Value>
void rotateBST<Key,Value>::transform(rotateBST& t2) const
{
if(!sameKeys(t2)) return;
transformHelper(this->mRoot, t2.mRoot, t2);
}
/**
* Performs the right rotations that create a linked list
* we can then shape.
*/
template<typename Key, typename Value>
void rotateBST<Key,Value>::linkedList(Node<Key,Value>* t2_root, rotateBST& t2) const
{
if(t2_root == nullptr) {
return;
}
while(t2_root->getLeft())
{
t2.rightRotate(t2_root);
t2_root = t2_root->getParent();
}
linkedList(t2_root->getRight(), t2);
}
/**
* Calls left left rotate recursively on each child of each node
* eventually equating the values.
*/
template<typename Key, typename Value>
void rotateBST<Key,Value>::transformHelper(Node<Key,Value>* root,
Node<Key,Value>* t2_root, rotateBST& t2) const {
if(t2_root == nullptr && root == nullptr) {
return;
}
Node<Key,Value>* subRoot = smallestSubtree(t2_root);
linkedList(t2_root, t2);
t2_root = subRoot;
while(t2_root->getKey() != root->getKey())
{
t2.leftRotate(t2_root);
if(t2_root->getParent()) {
t2_root = t2_root->getParent();
} else {
break;
}
}
transformHelper(root->getRight(), t2_root->getRight(), t2);
transformHelper(root->getLeft(), t2_root->getLeft(), t2);
}
/**
* Function that finds the smallest value in a given subtree.
*/
template<typename Key, typename Value>
Node<Key, Value>* rotateBST<Key,Value>::smallestSubtree(Node<Key,Value>* r) const
{
while(r->getLeft()) {
r = r->getLeft();
}
return r;
}
/**
* Performs a left rotate on a given node.
*/
template<typename Key, typename Value>
void rotateBST<Key,Value>::leftRotate(Node<Key,Value>* r)
{
if(!r->getRight()) {
return;
}
Node<Key, Value>* new_parent = r->getRight();
r->setRight(new_parent->getLeft());
if(new_parent->getLeft()) {
new_parent->getLeft()->setParent(r);
}
new_parent->setParent(r->getParent());
if(!r->getParent()) {
this->mRoot = new_parent;
} else if(r == r->getParent()->getLeft()) {
r->getParent()->setLeft(new_parent);
} else {
r->getParent()->setRight(new_parent);
}
new_parent->setLeft(r);
r->setParent(new_parent);
}
/**
* Performs a right rotate on a given node.
*/
template<typename Key, typename Value>
void rotateBST<Key,Value>::rightRotate(Node<Key,Value>* r)
{
if(!r->getLeft()) {
return;
}
Node<Key, Value>* new_parent = r->getLeft();
r->setLeft(new_parent->getRight());
if(new_parent->getRight()) {
new_parent->getRight()->setParent(r);
}
new_parent->setParent(r->getParent());
if(!r->getParent()) {
this->mRoot = new_parent;
} else if(r == r->getParent()->getLeft()) {
r->getParent()->setLeft(new_parent);
} else {
r->getParent()->setRight(new_parent);
}
new_parent->setRight(r);
r->setParent(new_parent);
}
#endif | true |
138dc878e98959c298188b7d878e321b46a2d621 | C++ | foolisb/PAT-A-level | /C语言代码/pat1002.cpp | UTF-8 | 905 | 3.28125 | 3 | [] | no_license | //注意系数相加等于0的情况,要删除该项
//声明的变量类型与输入的格式化匹配,%d不能赋值给float变量
#include<stdio.h>
struct Dot{
int ex;
float co;
bool f;
};
int main( )
{
int i = 0;
struct Dot bn[1001];
int q,k1,k2,count = 0;
float p;
for(i = 0;i < 1001;i++)
{
bn[i].f = false;
bn[i].co = 0;
}
scanf("%d",&k1);
for(i = 1;i <= k1;i++){
scanf("%d",&q);
bn[q].ex = q;
scanf("%f",&p);
bn[q].co += p;
}
scanf("%d",&k2);
for(i = 1;i <= k2;i++){
scanf("%d",&q);
bn[q].ex = q;
scanf("%f",&p);
bn[q].co += p;
}
for(i = 0;i <= 1000;i++)
{
if(bn[i].co != 0){
bn[i].f = true;
count++;
}
}
printf("%d",count);
for(i = 1000;i >= 0;i--)
{
if(bn[i].f == true){
printf(" %d %.1f",bn[i].ex,bn[i].co);
}
}
}
| true |
d7245ac37ba6c4884d9b7905e711c24f992c37a7 | C++ | MICHAEL-MAURICE/problem_solving_training | /Majority Element/main.cpp | UTF-8 | 235 | 2.6875 | 3 | [] | no_license | #include <bits//stdc++.h>
using namespace std;
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
| true |
05bafea2993616fb614eead216e832b8700c58c5 | C++ | WhereIsHeroFrom/Algorithm | /数学/图论/有向图判环/HDU 3592 ( World Exhibition ) .cpp | WINDOWS-1252 | 1,589 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MAXN 1010
struct edge {
int to, val;
edge() {
}
edge(int _t, int _v) {
to = _t;
val = _v;
}
};
int n;
int dis[MAXN];
int visitCount[MAXN];
vector <edge> vec[MAXN];
// Ƿڻ
bool spfa(int s) {
int i;
for (i = 1; i <= n; i++) {
dis[i] = -1;
visitCount[i] = 0;
}
dis[s] = 0;
queue <edge> Q;
Q.push(edge(s, 0));
while (!Q.empty()) {
edge now = Q.front();
Q.pop();
int from = now.to;
int predist = now.val;
if (visitCount[from]++ > n) {
return true;
}
for (i = vec[from].size() - 1; i >= 0; i--) {
int to = vec[from][i].to;
int nextdist = vec[from][i].val + predist;
if (nextdist < dis[to] || dis[to] == -1) {
dis[to] = nextdist;
Q.push(edge(to, nextdist));
}
}
}
return false;
}
void addEdge(int u, int v, int c) {
vec[u].push_back(edge(v, c));
}
int main() {
int t;
int X, Y;
int i, j;
scanf("%d", &t);
while (t--) {
scanf("%d %d %d", &n, &X, &Y);
for (i = 1; i <= n; i++) {
vec[i].clear();
if (i > 1) {
addEdge(i, i - 1, -1);
}
}
while (X--) {
int A, B, C;
scanf("%d %d %d", &A, &B, &C);
addEdge(A, B, C);
}
while (Y--) {
int A, B, C;
scanf("%d %d %d", &A, &B, &C);
addEdge(B, A, -C);
}
bool ans = spfa(1);
if (dis[n] == -1) {
printf("-2\n");
}
else {
if (ans) {
printf("-1\n");
}
else {
printf("%d\n", dis[n]);
}
}
}
return 0;
}
/*
2
4 2 1
1 3 8
2 4 15
2 3 4
2 1 1
1 2 4
1 2 5
*/
[Copy to Clipboard][Save to File]
| true |
a162fd8a21f535e6e62e938fff74e4b7189dd92f | C++ | TulioAbreu/uri-online-judge | /code/1007.cpp | UTF-8 | 233 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
int a[5];
cin >> a[1] >> a[2] >> a[3] >> a[4];
a[5] = a[1] * a[2] - a[3] * a[4];
cout << fixed << setprecision(1) << "DIFERENCA = "<< a[5] <<endl;
return 0;
} | true |
5a59e5ec04971e3284077f47069be26e799e8208 | C++ | wewe799/100 | /36.0.cpp | GB18030 | 884 | 3.59375 | 4 | [] | no_license | //ڼĵһĸжһڼһĸһжϵڶĸ
#include<stdio.h>
int main(void)
{
char c,ch;
printf("ڵĸ\n");
c=getchar();
switch(c)
{
case 'M':printf("һ\n");break;
case 'T':
{
printf("ڶĸ\n");
getchar();
ch=getchar();
switch(ch)
{
case'u':printf("ڶ");break;
case'h':printf("");break;
default:printf("");
}
}
break;
case 'W':printf("");break;
case 'F':printf("");break;
case 'S':
{
printf("ڶĸ\n");
getchar();
ch=getchar();
switch(ch)
{
case'a':printf("");break;
case'u':printf("");break;
default:printf("");
}
}
break;
}
return 0;
}
| true |
9c8d992890d72ce78b8232db6a76695243d383ed | C++ | RI45816/341_SP2018 | /Projects/proj3/QTNode.h | UTF-8 | 1,953 | 3.046875 | 3 | [] | no_license | #ifndef QTNODE_H
#define QTNODE_H
#include <vector>
#include "Point.h"
#include "BBox.h"
#define QT_NUM_KIDS 4
enum {BL,BR,TL,TR}; // Enumerator with the values of the directions
class QTNode {
public:
class iterator {
public:
iterator();
bool operator==(const QTNode::iterator &other);
bool operator!=(const QTNode::iterator &other);
iterator &operator++(); // Prefix: e.g. "++it"
iterator operator++(int dummy); // Postfix: "it++"
QTNode *&operator*();
private:
// Add data members here to record state of current iterator position
// vector<QTNode*>::iterator it;
int m_position;
QTNode * m_node;
friend class QTNode;
};
QTNode();
~QTNode();
bool add(const Point &pt, int data); // actually, add/replace
bool remove(const Point &pt, bool &empty);
bool find(const Point &pt, int &data);
int findPoints(const BBox ®ion, std::vector<Point> &found);
void dump();
iterator begin();
iterator end();
BBox m_bounds; // The bounding box for this node
Point m_point; // If leaf node (i.e., no kids), m_point, m_data hold the
int m_data; // actual point and data value the user inserted.
// YOu must add data member(s) to store pointers to child QTNode's
//
// YOU CAN ADD ANY OTHER CONSTRUCTORS, MEMBER FUNCTIONS, MEMBER DATA, ETC.
// AS NEEDED.
//
QTNode * m_nodes[QT_NUM_KIDS]; // Store the QTNodes for top left, top right, bottom left, and bottom right
bool isEmpty(); // Return true if there are no sub-nodes
bool m_isLeaf; // True if current node is a leaf
bool m_isNull;
int sortPoint(Point &pt); // Return the index of the sub-node to sort the point into
QTNode(Point &pt,int data, int dim); // Create a new leaf node and set the data accordingly
QTNode(QTNode * nodes[], BBox bounds,int dim); // Create a new subnode
static int debug_count;
};
#endif
| true |
5c306a16281d69829360e61ad512336f503a9d31 | C++ | intelfx/data-processing | /differentiator/node-compare.cpp | UTF-8 | 2,914 | 2.75 | 3 | [] | no_license | #include "node.h"
namespace Node
{
bool Base::compare (const Base::Ptr& rhs) const
{
if (typeid (*this) == typeid (*rhs.get())) {
return compare_same_type (rhs);
} else {
return false;
}
}
bool Base::less (const Base::Ptr& rhs) const
{
if (typeid (*this) == typeid (*rhs.get())) {
return less_same_type (rhs);
} else {
return get_type() < rhs->get_type();
}
}
#define COMPARE_CHECK_TYPE(Type) \
const Type* node = static_cast<const Type*> (rhs.get()); \
bool Value::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Value);
return (value_ == node->value_);
}
bool Variable::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Variable);
return (name_ == node->name_) &&
(is_error_ == node->is_error_);
}
bool Function::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Function);
return (name_ == node->name_) &&
(children_ == node->children_);
}
bool Power::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Power);
return base_->compare (node->base_) &&
exponent_->compare (node->exponent_);
}
bool AdditionSubtraction::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(AdditionSubtraction);
return children_ == node->children_;
}
bool MultiplicationDivision::compare_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(MultiplicationDivision);
return children_ == node->children_;
}
#define LEXICOGRAPHICAL_COMPARE_CHAIN(less, equal) \
if (less) return true; \
else if (!(equal)) return false;
#define LEXICOGRAPHICAL_COMPARE_LAST(less) \
return (less);
bool Value::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Value);
LEXICOGRAPHICAL_COMPARE_LAST(value_ < node->value_);
}
bool Variable::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Variable);
LEXICOGRAPHICAL_COMPARE_CHAIN(is_error_ < node->is_error_,
is_error_ == node->is_error_);
LEXICOGRAPHICAL_COMPARE_LAST(name_ < node->name_);
}
bool Function::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Function);
LEXICOGRAPHICAL_COMPARE_LAST(name_ < node->name_);
}
bool Power::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(Power);
LEXICOGRAPHICAL_COMPARE_CHAIN(exponent_->less (node->exponent_),
exponent_->compare (node->exponent_));
LEXICOGRAPHICAL_COMPARE_LAST(base_->less (node->base_));
}
bool AdditionSubtraction::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(AdditionSubtraction);
LEXICOGRAPHICAL_COMPARE_LAST(children_ < node->children_);
}
bool MultiplicationDivision::less_same_type (const Base::Ptr& rhs) const
{
COMPARE_CHECK_TYPE(MultiplicationDivision);
LEXICOGRAPHICAL_COMPARE_LAST(children_ < node->children_);
}
} // namespace Node
| true |
30afc2795939d31e0dcd795d7e922f826881e69b | C++ | lxq2537664558/Leetcode-1 | /11. Container With Most Water.cpp | UTF-8 | 768 | 3.140625 | 3 | [] | no_license | // Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
// Note: You may not slant the container.
// Subscribe to see which companies asked this question
class Solution {
public:
int maxArea(vector<int>& height) {
int i=0, j=height.size()-1,h=0,capacity=0;
while (i<j)
{
h=min(height[i],height[j]);
capacity=max(capacity,(j-i)*h);
while (height[i]==h && i<j) ++i;
while (height[j]==h && i<j) --j;
}
return capacity;
}
}; | true |
d6c1fc5f269e9a0e681a22f936d37d945798d4b5 | C++ | wxinjie/Fushilianxi | /数学问题/最大公约数.cpp | UTF-8 | 242 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int GCD(int a, int b){
if(b == 0){
return a;
} else {
GCD(b, a % b);
}
}
int main(){
int a,b;
while(scanf("%d%d",&a,&b) != EOF){
printf("%d\n",GCD(a,b));
}
return 0;
}
| true |
c893432f3eba76b90b0f765ed52c770ce73933b7 | C++ | haipz/LeetCode | /13. Roman to Integer | Easy | Math, String.cpp | UTF-8 | 1,786 | 3.65625 | 4 | [
"MIT"
] | permissive | /*
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*/
// I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)
/* old version
class Solution {
public:
int romanToInt(string s) {
int nums[] = {1, 5, 10, 50, 100, 500, 1000}, res = 0;
string chs("IVXLCDM??");
for (int i = 0; i < s.size(); ++i) {
int curi = chs.find(s[i]);
if (curi & 1) {
res += nums[curi];
while (i + 1 < s.size() && curi > 0 && chs[curi - 1] == s[i + 1]) {
res += nums[curi - 1];
++i;
}
} else {
if (i + 1 < s.size() && chs[curi + 2] == s[i + 1]) {
res += nums[curi + 2] - nums[curi];
++i;
} else if (i + 1 < s.size() && chs[curi + 1] == s[i + 1]) {
res += nums[curi + 1] - nums[curi];
++i;
} else {
res += nums[curi];
while (i + 1 < s.size() && chs[curi] == s[i + 1]) {
res += nums[curi];
++i;
}
}
}
}
return res;
}
};
*/
class Solution {
public:
int romanToInt(string s) {
map<char, int> dict;
dict['I'] = 1;
dict['V'] = 5;
dict['X'] = 10;
dict['L'] = 50;
dict['C'] = 100;
dict['D'] = 500;
dict['M'] = 1000;
int res = 0;
for (int i = 0; i < s.size(); ++i)
if (i + 1 < s.size() && dict[s[i]] < dict[s[i + 1]]) res -= dict[s[i]];
else res += dict[s[i]];
return res;
}
};
| true |
aa0eb5c87759d6c0920a840a2617e82b85dc43b7 | C++ | personaluser01/Algorithm-problems | /20130527/LAH08/contestant/Dung/badgras.cpp | UTF-8 | 1,767 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
typedef pair<long,long> ii;
long r, c, i, j, result;
vector<vector<bool> > sign;
vector<bool> b;
void bfs(long u, long v){
long step, now, ofqueue, i, j, f, g;
queue<ii> ryo;
ryo.push(ii(u,v));
ofqueue= 1;
for(;;){
now= 0;
for(i=1;i<=ofqueue;i++){
ii x= ryo.front(); ryo.pop();
sign[x.first][x.second]= true;
f= x.first; g= x.second;
if(f+1<r && g+1<c && sign[f+1][g+1]==false) {ryo.push(ii(f+1,g+1)); now++;}
if(f-1>=0 && g+1<c && sign[f-1][g+1]==false) {ryo.push(ii(f-1,g+1)); now++;}
if(f+1<r && g-1>=0 && sign[f+1][g-1]==false) {ryo.push(ii(f+1,g-1)); now++;}
if(f-1>=0 && g-1>=0 && sign[f-1][g-1]==false) {ryo.push(ii(f-1,g-1)); now++;}
if(f+1<r && sign[f+1][g]==false) {ryo.push(ii(f+1,g)); now++;}
if(f-1>=0 && sign[f-1][g]==false) {ryo.push(ii(f-1,g)); now++;}
if(g+1<r && sign[f][g+1]==false) {ryo.push(ii(f,g+1)); now++;}
if(g-1>=0 && sign[f][g-1]==false) {ryo.push(ii(f,g-1)); now++;}
}
if(now==0) break; else ofqueue= now;
}
return;
}
main(){
freopen("badgras.inp","r",stdin);
freopen("badgras.out","w", stdout);
long x;
scanf("%ld%ld", &r, &c);
result= 0;
for(i=0;i<r;i++){
b.clear();
for(j=0;j<c;j++){
scanf("%ld", &x);
if(x==0) b.push_back(true);
else b.push_back(false);
}
sign.push_back(b);
}
for(i=0;i<r;i++)
for(j=0;j<c;j++){
if(sign[i][j]==false) {
bfs(i,j);
result++;
}
}
printf("%ld\n", result);
}
| true |
21493e0df0210b1a01dd9665ac57fcadfb330592 | C++ | JayGitH/839C-language-and-data-structure | /839数据结构/c语言/839代码(来自一位2018届考研学长)/HDSDC/AB升序数组合并我做的15.cpp | UTF-8 | 297 | 3.09375 | 3 | [] | no_license | #include<stdio.h>
void Merge(int *A,int n,int *B,int m){
int i,j,t;
for(i=0;i<m;i++){
t=B[i];
for(j=n+i-1;j>=0&&t<A[j];j--)
A[j+1]=A[j];
A[j+1]=t;
}
}
int main(){
int a[20]={-1,6,28,38};
int b[20]={2,7,11};
Merge(a,4,b,3);
for(int i=0;i<7;i++)
printf("%5d",a[i]);
return 0;
}
| true |
f23aca2ab198ca140b91e997a3733d22c85d2fca | C++ | alok27a/CSE2011-Data-Structures-Algorithm | /Lab/Module 4/Assignment 3/Practice/Q1BST.cpp | UTF-8 | 4,426 | 4.09375 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
struct node
{
int data;
struct node *left_child;
struct node *right_child;
};
struct node *newNode(int n)
{
struct node *node = new struct node;
node->data = n;
node->left_child = NULL;
node->right_child = NULL;
};
struct node *find_minimum(struct node *root);
void inorder_traversal(struct node *p)
{
if (p == NULL)
return;
inorder_traversal(p->left_child);
cout << p->data << " ";
inorder_traversal(p->right_child);
}
void preorder_traversal(struct node *p)
{
if (p == NULL)
return;
cout << p->data << " ";
preorder_traversal(p->left_child);
preorder_traversal(p->right_child);
}
void postorder_traversal(struct node *p)
{
if (p == NULL)
return;
postorder_traversal(p->left_child);
postorder_traversal(p->right_child);
cout << p->data << " ";
}
struct node *insert(struct node *root, int n)
{
if (root == NULL)
{
return newNode(n); //Creating the main root node
}
else if (n > root->data)
{
root->right_child = insert(root->right_child, n);
}
else if (n < root->data)
{
root->left_child = insert(root->left_child, n);
}
return root;
}
struct node *del(struct node *root, int key)
{
if (root == NULL)
return root;
if (key < root->data)
root->left_child = del(root->left_child, key);
else if (key > root->data)
root->right_child = del(root->right_child, key);
else
{
// node with only one child or no child
if (root->left_child == NULL)
{
struct node *temp = root->right_child;
free(root);
return temp;
}
else if (root->right_child == NULL)
{
struct node *temp = root->left_child;
free(root);
return temp;
}
// node with two children:
struct node *temp = find_minimum(root->right_child);
// Copy the inorder
root->data = temp->data;
// Delete the inorder successor
root->right_child = del(root->right_child, temp->data);
}
return root;
}
struct node *find_minimum(struct node *root)
{
if (root == NULL)
return NULL;
else if (root->left_child != NULL)
return find_minimum(root->left_child);
return root;
}
struct node *max_element(struct node *root)
{
struct node *temp = root;
while (temp->right_child != NULL)
temp = temp->right_child;
return temp;
}
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 70);
insert(root, 20);
insert(root, 40);
insert(root, 60);
insert(root, 80);
cout << "**BST**" << endl;
int choice, x, k, a;
struct node *t;
struct node *temp;
while (choice != 10)
{
cout << "Options available are:-" << endl;
cout << "1.Insert an element into BST\n2.Deletion of Node\n3.Inorder Traversal\n4.Preorder Traversal\n5.Postorder Traversal\n6.Minimum element\n7.Maximum element\n8.Exit" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the number to be inserted" << endl;
cin >> x;
insert(root, x);
break;
case 2:
cout << "Enter the element to be deleted " << endl;
cin >> x;
del(root, x);
inorder_traversal(root);
cout << "\n";
break;
case 3:
inorder_traversal(root);
cout << "\n";
break;
case 4:
preorder_traversal(root);
cout << "\n";
break;
case 5:
postorder_traversal(root);
cout << "\n";
break;
case 6:
t = find_minimum(root);
cout << t->data << endl;
break;
case 7:
temp = max_element(root);
cout << temp->data << endl;
break;
case 8:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid Input" << endl;
break;
}
}
return 1;
} | true |
79c076acaea16a1611d0bb8fc60870fa7ccff47c | C++ | TakuyaKimura/Leetcode | /093 Restore IP Addresses/93.cpp | ISO-8859-1 | 4,229 | 3.578125 | 4 | [] | no_license | /*
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string address;
restore(result, s, address, 0, 0, s.length());
return result;
}
private:
void restore(vector<string>& result, string s, string address, int part, int start, int n) {
if (start == n && part == 4)
{
address.pop_back();
result.push_back(address);
}
if (start == n || part == 4)
return;
for (int num = 0, i = start; i < start + 3 && i < n; ++i)
{
num = num * 10 + s[i] - '0';
if (num <= 255)
{
address += s[i];
restore(result, s, address + '.', part + 1, i + 1, n);
}
if (num == 0)
break;
}
}
};
class Solution2 {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string ip; // save temporary result in processing
dfs(s, 0, 0, ip, result);
return result;
}
/**
* @brief: split the string
* @param[in] s stringinput
* @param[in] startIndex, start from which index in s
* @param[in] step current step indexstart from 0valid values: 0,1,2,3,4, as special, 4 means ending of split
* @param[out] intermediate, split result in current spliting process
* @param[out] result, save all possible IP address
* @return none
*/
void dfs(string s, size_t start, size_t step, string ip, vector<string>& result) {
if (start == s.size() && step == 4) // found a possible result
{
ip.resize(ip.size() - 1); // strip the last '.'
result.push_back(ip);
return;
}
// since each part of IP address is in 0...255, the length will not be more than 3, and not less than 1 as well.
if (s.size() - start > (4 - step) * 3)
return; // optimize, the length of rest part of s string should not be more than 3 * remaining step count.
if (s.size() - start < (4 - step))
return; // optimize, the length of rest part of s string should not be less than 1 * remaining step count.
int num = 0;
for (size_t i = start; i < start + 3 && i < s.size(); ++i)
{
num = num * 10 + (s[i] - '0');
if (num <= 255)
{
ip += s[i];
dfs(s, i + 1, step + 1, ip + '.', result); // current split is valid, go to next recursion
}
if (num == 0) // single 0 is allowed, but '0X' is not
break;
}
}
};
3 {
public:
vector<string> restoreIpAddress(string s) {
vector<string> res;
size_t len = s.size();
if (len > 12 || len < 4)
return res;
string first, second, third, fourth;
// i, j, k are the lengths of each substring
for (size_t i = 1; i < 4 && i < len - 2; ++i)
{
first = s.substr(0, i);
if (!isValid(first))
continue;
for (size_t j = 1; j < 4 && i + j < len - 1; ++j)
{
second = s.substr(i, j);
if (!isValid(second))
continue;
for (size_t k = 1; k < 4 && i + j + k < len; ++k)
{
third = s.substr(i + j, k);
fourth = s.substr(i + j + k);
if (isValid(third) && isValid(fourth))
res.push_back(first + "." + second + "." + third + "." + fourth);
}
}
}
return res;
}
private:
bool isValid(string s) {
if (s[0] == '0' && s.size() > 1)
return false;
if (stoi(s) <= 255)
return true;
return false;
}
};
int main()
{
Solution s;
s.restoreIpAddresses("1234");
} | true |
77f6d999dd655fc6ea47144734f50529e9059a83 | C++ | zXif/lab2 | /main — копия.cpp | UTF-8 | 3,039 | 3.828125 | 4 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
class Triangle
{
protected:
int first_side;
int second_side;
int third_side;
public:
Triangle() {
first_side = 0;
second_side = 0;
third_side = 0;
}
Triangle(int first_side, int second_side) {
this->first_side = first_side;
this->second_side = second_side;
this->third_side = third_side;
}
Triangle(Triangle *rect) {
first_side = rect->first_side;
second_side = rect->second_side;
third_side = rect->third_side;
}
~Triangle() {}
void setTriangle();
void getTriangle();
int perimetr();
void equal();
friend int operator +(Triangle& a1) {
int p = a1.perimetr();
return p;
}
Triangle operator =(Triangle& a1) {
first_side = a1.first_side;
second_side = a1.second_side;
return this;
}
};
class ColoredTriangle : protected Triangle {
protected:
string color;
public:
ColoredTriangle();
ColoredTriangle( int first_side, int second_side, int third_side);
~ColoredTriangle() {}
void setColor();
void getColor();
};
ColoredTriangle::ColoredTriangle() {
color = "NULL";
}
ColoredTriangle::ColoredTriangle(int first_side, int second_side, int third_side) {
this->color = color;
}
void Triangle::setTriangle() {
cout << "Enter fiest side " << endl;
cin >> first_side;
cout << "Enter second side " << endl;
cin >> second_side;
cout << "Enter third side " << endl;
cin >> third_side;
}
void ColoredTriangle::setColor() {
cout << "Enter color" << endl;
cin >> color;
}
void Triangle::getTriangle() {
cout << "First side = " << first_side << endl;
cout << "Second side = " << second_side << endl;
cout << "Third side = " << third_side << endl;
}
void ColoredTriangle::getColor() {
cout << "Color is " << color << endl;
}
void Triangle::equal() {
if (first_side == second_side == third_side)
cout << "It's a equilateral triangle!" << endl;
if ( ( first_side == second_side ) || ( first_side == third_side ) || ( second_side == third_side ) )
cout << "It's a isosceles triangle!" << endl;
}
int Triangle::perimetr() {
if ((first_side + second_side < third_side) || (first_side + third_side < second_side) ||
(second_side + third_side < first_side)) {
cout << "Triangle is not exist!" << endl;
return -1;
}
else
return (first_side + second_side + third_side);
}
int main(){
Triangle A;
Triangle B;
B = A;
B.getTriangle();
Triangle* R;
R = new Triangle;
Triangle rect = new Triangle;
rect.getTriangle();
R->setTriangle();
R->getTriangle();
R->equal();
int P = R->perimetr();
if (P !=-1)
cout << "Perimetr = " << P << endl;
delete R;
ColoredTriangle* C;
C = new ColoredTriangle;
C->setColor();
C->getColor();
return 0;
}
| true |
77458cfa102a1911e93f51ad9e7cc3323cca2649 | C++ | MechEmpire/Mechempire-meches | /5551ef4d6d65633918cb0000/code/RobotAI.cpp | UTF-8 | 5,175 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include "RobotAI.h"
RobotAI::RobotAI()
{
}
RobotAI::~RobotAI()
{
}
//-----------------------------------------------------
//1.必须完成的战斗核心
//-----------------------------------------------------
void Aim (RobotAI_Order & order,const RobotAI_BattlefieldInformation& info, int myID) {
double a=atan2(info.robotInformation[1-myID].circle.y-info.robotInformation[myID].circle.y,info.robotInformation[1-myID].circle.x-info.robotInformation[myID].circle.x);
double c=info.robotInformation[myID].weaponRotation;
if(-180<a<-90||90<a<=180){
a=a+PI;
AngleToRadian(c);
c+=PI;
RadianToAngle(c);
RadianToAngle(a);
}
if(-90<=a<=90){
RadianToAngle(a);
}
double b=a-c;
// AngleAdjust(b);
if(b>1e-4){
order.wturn=1;
}
else if(b<-1e-4){
order.wturn=-1;
}
else{
order.wturn=0;
}
}
void RobotAI::Update(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info,int myID)
{
Aim(order,info, myID);
order.fire=1;
if(info.robotInformation[myID].engineRotation!=90&&info.robotInformation[myID].remainingAmmo==0){
order.eturn=1;
}
if(info.robotInformation[myID].engineRotation==90&&info.robotInformation[myID].remainingAmmo==0){
order.run=1;
}
if(info.robotInformation[myID].circle.y>=info.arsenal[0].circle.y) {
order.eturn=-1;
if(info.robotInformation[myID].engineRotation==0&&info.robotInformation[myID].remainingAmmo!=0){
order.run=1;
}
}
//帧操纵函数
//功能:在每一帧被调用,完成你的机甲在这一帧的动作决策
//参数:order ... 机甲操纵指令,你在函数体中给它赋值以操纵机甲在这一帧的行为
// info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
// (这几个参数的详细说明在开发手册可以找到,你也可以在RobotAIstruct.h中直接找到它们的代码)
}
void RobotAI::ChooseArmor(weapontypename& weapon,enginetypename& engine,bool a)
{
//挑选装备函数
//功能:在战斗开始时为你的机甲选择合适的武器炮塔和引擎载具
//参数:weapon ... 代表你选择的武器,在函数体中给它赋值
// engine ... 代表你选择的引擎,在函数体中给它赋值
//tip: 括号里的参数是枚举类型 weapontypename 或 enginetypename
// 开发文档中有详细说明,你也可以在RobotAIstruct.h中直接找到它们的代码
//tip: 最后一个bool是没用的。。那是一个退化的器官
weapon = WT_Machinegun; //啊,我爱加农炮
engine = ET_XCraft; //啊,我爱小蜘蛛
}
//-----------------------------------------------------
//2.个性信息
//-----------------------------------------------------
string RobotAI::GetName()
{
//返回你的机甲的名字
return "X战机";
}
string RobotAI::GetAuthor()
{
//返回机甲制作人或团队的名字
return "ABC";
}
//返回一个(-255,255)之间的机甲武器炮塔的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetWeaponRed()
{
//返回一个-255-255之间的整数,代表武器红色的偏移值
return 200;
}
int RobotAI::GetWeaponGreen()
{
//返回一个-255-255之间的整数,代表武器绿色的偏移值
return -50;
}
int RobotAI::GetWeaponBlue()
{
//返回一个-255-255之间的整数,代表武器蓝色的偏移值
return -100;
}
//返回一个(-255,255)之间的机甲引擎载具的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetEngineRed()
{
//返回一个-255-255之间的数,代表载具红色的偏移值
return -100;
}
int RobotAI::GetEngineGreen()
{
//返回一个-255-255之间的整数,代表载具绿色的偏移值
return 200;
}
int RobotAI::GetEngineBlue()
{
//返回一个-255-255之间的整数,代表载具蓝色的偏移值
return -50;
}
//-----------------------------------------------------
//3.用不用随你的触发函数
//-----------------------------------------------------
void RobotAI::onBattleStart(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗开始时被调用,可能可以用来初始化
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
}
void RobotAI::onBattleEnd(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗结束时被调用,可能可以用来析构你动态分配的内存空间(如果你用了的话)
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
}
void RobotAI::onSomeoneFire(int fireID)
{
//有机甲开火时被调用
//参数:fireID ... 开火的机甲下标
}
void RobotAI::onHit(int launcherID,bullettypename btn)
{
//被子弹击中时被调用
//参数:btn ... 击中你的子弹种类(枚举类型)
}
//TODO:这里可以实现你自己的函数 | true |
1b31cce13bb4fc816f56e38ae9928ffd80e0118f | C++ | watashi/AlgoSolution | /zoj/14/1453.cpp | GB18030 | 2,294 | 2.984375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
// Convex Hull
const double eps = 1e-8;
template<class T>
struct Point
{
T x, y;
Point() { }
Point(int x, int y) : x(x), y(y) { }
};
template<class T>
bool operator <(const Point<T>& lhs, const Point<T>& rhs)
{
return (lhs.y != rhs.y) ? lhs.y < rhs.y : lhs.x < rhs.x;
}
template<class T>
Point<T> operator -(const Point<T>& lhs, const Point<T>& rhs)
{
return Point<T>(lhs.x - rhs.x, lhs.y - rhs.y);
}
template<class T>
T xmult(const Point<T>& lhs, const Point<T>& rhs)
{
return lhs.x * rhs.y - lhs.y * rhs.x;
}
// p˳ı
// ûmark˻Ϊ߶ʱظ
// if all = true then йߵ
template<class T>
int GrahamScan(int n, Point<T> p[], Point<T> ret[], bool all = false)
{
const double eps = all ? ::eps : -::eps;
int sp, tmp;
if (n < 3) {
for (int i = 0; i < n; i++) {
ret[i] = p[i];
}
return n;
}
sort(p, p + n);
ret[0] = p[0];
ret[1] = p[1];
sp = 2;
for (int i = 2; i < n; i++) {
while (sp > 1 && xmult(ret[sp - 1] - ret[sp - 2], p[i] - ret[sp - 2]) > eps) {
--sp;
}
ret[sp++] = p[i];
}
tmp = sp;
ret[sp++] = p[n - 2];
for (int i = n - 3; i >= 0; i--) {
while (sp > tmp && xmult(ret[sp - 1] - ret[sp - 2], p[i] - ret[sp - 2]) > eps) {
--sp;
}
ret[sp++] = p[i];
}
return sp - 1;
}
Point<int> p[128], ch[128];
int main(void)
{
int n;
double ans;
while (scanf("%d", &n) != EOF && n > 0) {
for (int i = 0; i < n; i++) {
scanf("%d%d", &p[i].x, &p[i].y);
}
n = GrahamScan(n, p, ch);
ans = hypot((double)(ch[0].x - ch[n - 1].x), (double)(ch[0].y - ch[n - 1].y));
for (int i = 1; i < n; i++) {
ans += hypot((double)(ch[i].x - ch[i - 1].x), (double)(ch[i].y - ch[i - 1].y));
}
printf("%.2lf\n", ans);
}
return 0;
}
//Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name
//3028361 2008-08-09 11:11:03 Accepted 1453 C++ 00:00.05 452K Re:ReJudge
//
// 2012-09-07 00:49:51 | Accepted | 1453 | C++ | 10 | 180 | watashi | Source
| true |
10b613ca2a3fc1d51843ac89e3791634a5288112 | C++ | pedrolinhares/ANN | /src/Layer.cpp | UTF-8 | 2,118 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include "Layer.h"
Layer::Layer(int numOfNeurones): hidden(true) {
for (int i = 0; i < numOfNeurones; i++)
neurones.push_back (Neurone());
}
void Layer::setHidden(bool value) {
hidden = value;
}
void Layer::setInput(const std::vector<double>& input) {
int size = neurones.size();
for (int i = 0; i < size; i++)
neurones[i].setInput(input);
}
void Layer::calculate_output() {
output.clear();
for (int i = 0; i < neurones.size(); i++)
output.push_back(neurones[i].output());
}
std::vector<double> Layer::getOutput() {
return output;
}
std::vector<std::vector<double> > Layer::getLayerDownStream() {
std::vector<std::vector<double> > layerDownStream;
for (int i = 0; i < neurones.size(); i++) {
layerDownStream.push_back(neurones[i].getSigma());
}
return layerDownStream;
}
void Layer::updateWeights(const std::vector<double>& correctOutput, double learningRate) {
for (int i = 0; i < neurones.size(); i++) {
neurones[i].calculateSigma(correctOutput[i], true);
neurones[i].updateWeights(learningRate);
}
}
void Layer::updateWeights(const std::vector<std::vector<double> >& downStream, double learningRate) {
for (int i = 0; i < neurones.size(); i++) {
std::vector<double> nextLayerStream;
for (int j = 0; j < downStream.size(); j++)
nextLayerStream.push_back (downStream[j][i]);
neurones[i].calculateSigma(nextLayerStream, true);
neurones[i].updateWeights(learningRate);
}
}
std::string Layer::printWeights() {
std::stringstream out(std::stringstream::in | std::stringstream::out);
for (int i = 0; i < neurones.size(); i++) {
out << neurones[i].printWeights();
out << '\n';
}
return out.str();
}
void Layer::updateWeightsFromFile(std::ifstream &file) {
std::string line;
for (int i = 0; i < neurones.size(); i++) {
getline (file, line);
std::vector<double> lineInput;
std::stringstream stream (line);
std::string value;
while (getline (stream, value, ' '))
lineInput.push_back (atof (value.c_str()));
neurones[i].setWeights(lineInput);
}
} | true |
6280690629a0e899980e4f28e5b7aa2af4d94567 | C++ | gcc-o-o/cpp_code | /content_1/CD/classic.cpp | UTF-8 | 815 | 3.171875 | 3 | [] | no_license | //classic.cpp
#include <iostream>
#include <cstring>
#include "classic.h"
Classic::Classic(const char * sg, const char * pf, const char * lb, int sl, double pt)
: Cd(pf, lb, sl, pt)
{
songs = new char [std::strlen(sg) + 1];
std::strcpy(songs, sg);
}
Classic::Classic(const Classic & c)
: Cd(c)
{
songs = new char [std::strlen(c.songs) + 1];
std::strcpy(songs, c.songs);
}
Classic::Classic()
: Cd()
{
songs = new char [10];
std::strcpy(songs, "No songs");
}
Classic::~Classic()
{
delete [] songs;
}
void Classic::Report() const
{
this -> Cd::Report();
std::cout << "Songs: " << songs << std::endl;
std::cout << std::endl;
}
Classic & Classic::operator=(const Classic & c)
{
this -> Cd::operator=(c);
delete [] songs;
songs = new char [std::strlen(c.songs) + 1];
std::strcpy(songs, c.songs);
} | true |
86cada5841e482057365c08c998d339068156b96 | C++ | Vlajzi/KriptoAlgoritmi | /KriptoAlgoritmi/Knapsak.h | UTF-8 | 627 | 2.5625 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <random>
#include <ctime>
class Knapsak
{
public:
uint16_t PrivateKey[8];
unsigned int n;
uint16_t im;
public:
uint16_t PublicKey[8];
Knapsak();
void SetKey(uint16_t PublicKey[8], uint16_t PrivateKey[8], uint32_t n, uint16_t im);
void GenKey();
uint16_t* Encript(uint8_t* stream, uint64_t lenght);
uint8_t* Decript(uint16_t* stream, uint64_t lenght);
uint16_t* GetPublicKey();
uint16_t* GetPrivateKey();
uint64_t Get_N();
uint16_t Get_iM();
private:
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
};
| true |
553e529a0f0208a490240a4c40bc82c0e6636298 | C++ | keyclicker/labs | /Term4/OOOP/Lab1/include/Space.hpp | UTF-8 | 777 | 2.890625 | 3 | [] | no_license | #pragma once
#include "Particle.hpp"
#include <vector>
class Space
{
private:
bool sideCollision = true;
public:
void setSideCollision(bool sideCollision);
private:
double entropy = 0;
double speed = 1;
double resistance = 1;
std::vector<Particle> particles;
void collisionDetection();
public:
Space() = default;
Space(const Space &val) = delete;
Space &operator=(const Space &val) = delete;
Space(Space &&val) = default;
void push(const Particle &val);
void push(size_t r, double px, double py, double vx = 0.0, double vy = 0.0);
void reserve(size_t val);
void step(double time = 0.1);
const std::vector<Particle> &getPars();
void setEntropy(double entropy);
void setSpeed(double speed);
void setResistance(double resistance);
}; | true |
3e65ff62e6e2cad14db0f2c314cebc1481935d1e | C++ | JiananYuan/OpenGL_simple_framework | /main.cpp | UTF-8 | 2,945 | 2.609375 | 3 | [] | no_license | // dev
#include "Angel.h"
#include <string>
// #pragma comment(lib, "glew32.lib")
const int NUM_POINTS = 3;
void init()
{
// 定义三角形的三个点
vec2 vertices[3] = {
vec2(-0.75, -0.75), vec2(0.0, 0.75), vec2(0.75, -0.75)
};
// 创建顶点数组对象
GLuint vao;
#ifdef __APPLE__ // for MacOS
glGenVertexArraysAPPLE(1, &vao); // 分配1个顶点数组对象
glBindVertexArrayAPPLE(vao); // 绑定顶点数组对象
#else // for Windows
glGenVertexArrays(1, &vao); // 分配1个顶点数组对象
glBindVertexArray(vao); // 绑定顶点数组对象
#endif
// 创建顶点缓存对象
GLuint buffer;
// 分配1个顶点缓存对象
glGenBuffers(1, &buffer);
// 绑定顶点缓存对象
glBindBuffer(GL_ARRAY_BUFFER, buffer);
// 分配数据所需的存储空间,将数据拷贝到OpenGL服务端内存
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// 读取着色器并使用
std::string vshader, fshader;
#ifdef __APPLE__ // for MacOS
vshader = "shaders/vshader_mac.glsl";
fshader = "shaders/fshader_mac.glsl";
#else // for Windows
vshader = "shaders/vshader_win.glsl";
fshader = "shaders/fshader_win.glsl";
#endif
GLuint program = InitShader(vshader.c_str(), fshader.c_str());
glUseProgram(program);
// 从顶点着色器中初始化顶点的位置
GLuint location = glGetAttribLocation(program, "vPosition");
// 启用顶点属性数组
glEnableVertexAttribArray(location);
// 关联到顶点属性数组 (index, size, type, normalized, stride, *pointer)
glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
// 白色背景
glClearColor(1.0, 1.0, 1.0, 1.0);
}
void display(void)
{
// 清理窗口
glClear(GL_COLOR_BUFFER_BIT);
// 绘制所有点
glDrawArrays(GL_TRIANGLES, 0, NUM_POINTS);
glFlush();
}
int main(int argc, char **argv)
{
// 初始化GLUT库,必须是应用程序调用的第一个GLUT函数
glutInit(&argc, argv);
// 配置窗口的显示特性
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(512, 512);
glutCreateWindow("Red Triangle");
// for Windows
#ifdef WIN32
// 检测是否使用了freeglut,并检测是否使用到了OpenGL 3.3
glutInitContextVersion(3, 3);
glutInitContextProfile(GLUT_CORE_PROFILE);
// 保证GLEW使用更多的现代技术管理OpenGL,防止core profile出现崩溃
glewExperimental = GL_TRUE;
glewInit();
#endif
init();
// 指定当前窗口进行重绘时要调用的函数
glutDisplayFunc(display);
std::cout << "OpenGL Vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "Supported GLSL version is: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
// 负责一直处理窗口和操作系统的用户输入等操作
glutMainLoop();
return 0;
}
| true |
9bff4335b421aa4410b4d41c8d5497c328be654b | C++ | bingmann/distributed-string-sorting | /src/util/measuringTool.hpp | UTF-8 | 9,797 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include "mpi/environment.hpp"
#include "util/nonTimer.hpp"
#include "util/timer.hpp"
#include "util/leanNonTimer.hpp"
#include <ostream>
#include <vector>
namespace dss_schimek {
namespace measurement {
struct PhaseValue {
using PseudoKey = std::string;
std::string phase;
size_t value;
PhaseValue(const std::string& phase, const size_t value) : phase(phase), value(value) {}
const std::string& pseudoKey() const { return phase; }
void setValue(size_t value_) { value = value_; }
size_t getValue() const { return value; }
};
struct PhaseCounterPerPhaseRoundDescriptionTypeRawCommunicationSumUpValue {
using PseudoKey = std::string;
std::string phase;
size_t counterPerPhase;
size_t round;
std::string description;
std::string type;
bool rawCommunication;
bool sumUp;
size_t value;
PhaseCounterPerPhaseRoundDescriptionTypeRawCommunicationSumUpValue(
const std::string& phase, const size_t counterPerPhase,
const size_t round, const std::string& description,
const std::string& type, const bool rawCommunication, const bool sumUp,
const size_t value)
: phase(phase), counterPerPhase(counterPerPhase), round(round),
description(description), type(type),
rawCommunication(rawCommunication), sumUp(sumUp), value(value) {}
const std::string& pseudoKey() const { return phase; }
void setPseudoKeyCounter(size_t counter) { counterPerPhase = counter; }
void setType(const std::string& type_) { type = type_; }
void setValue(size_t value_) { value = value_; }
size_t getValue() const { return value; }
bool getSumUp() { return sumUp; }
friend std::ostream& operator<<(std::ostream& stream,
PhaseCounterPerPhaseRoundDescriptionTypeRawCommunicationSumUpValue&
elem) {
return stream << "[" << elem.phase << ", " << elem.counterPerPhase
<< ", " << elem.round << ", " << elem.description << ", "
<< elem.rawCommunication << ", " << elem.sumUp
<< elem.value << "]";
}
};
struct PhaseRoundDescription {
using PseudoKey = std::string;
std::string phase;
size_t round;
std::string description;
PhaseRoundDescription(const std::string& phase, const size_t round,
const std::string& description)
: phase(phase), round(round), description(description) {}
const std::string& pseudoKey() const { return phase; }
bool operator<(const PhaseRoundDescription& rhs) const {
return std::tie(phase, round, description) <
std::tie(rhs.phase, rhs.round, rhs.description);
}
friend std::ostream& operator<<(
std::ostream& stream, const PhaseRoundDescription& elem) {
return stream << "[" << elem.phase << ", " << elem.round << ", "
<< elem.description << "]";
}
};
struct CounterPerPhaseTypeRawCommunicationSumUpValue {
size_t counterPerPhase;
std::string type;
bool rawCommunication;
bool sumUp;
size_t value;
CounterPerPhaseTypeRawCommunicationSumUpValue(const size_t counterPerPhase,
const std::string& type, const bool rawCommunication, const bool sumUp,
const size_t value)
: counterPerPhase(counterPerPhase), type(type),
rawCommunication(rawCommunication), sumUp(sumUp), value(value) {}
void setPseudoKeyCounter(size_t counter) { counterPerPhase = counter; }
void setType(const std::string& type_) { type = type_; }
void setValue(size_t value_) { value = value_; }
};
class MeasuringTool {
// Columns:
// Prefix | Phase | CounterPerPhase | Round | Description | Type |
// RawCommunication | SumUp | Value
//
// NonTimer: Duplicates are allowed (but since counterPerPhase is
// incremented there are no duplicates if all fields are taken into account)
// Timer: Key = (Phase, Round, Description) Value = (CounterPerPhase, Type,
// RawCommunication, SumUp, Value)
using NonTimerRecord =
PhaseCounterPerPhaseRoundDescriptionTypeRawCommunicationSumUpValue;
// NonTimerRecord must contain type PseudoKey and functions pseudoKey() and
// setPseudoKeyCounter, setValue(), getValue()
using TimerKey = PhaseRoundDescription;
// TimerKey must contain type PseudoKey and function pseudoKey()
using TimerValue = CounterPerPhaseTypeRawCommunicationSumUpValue;
// TimerValue must contain functions setType() and setPseudoKeyCounter
//
dss_schimek::mpi::environment env;
struct OutputFormat {
std::string prefix;
std::string phase;
size_t counterPerPhase;
size_t round;
std::string description;
std::string type;
bool rawCommunication;
bool sumUp;
size_t value;
friend std::ostream& operator<<(
std::ostream& stream, const OutputFormat& outputFormat) {
return stream << outputFormat.prefix
<< " phase=" << outputFormat.phase
<< " counterPerPhase=" << outputFormat.counterPerPhase
<< " round=" << outputFormat.round
<< " operation=" << outputFormat.description
<< " type=" << outputFormat.type
<< " rawCommunication="
<< outputFormat.rawCommunication
<< " sumUp=" << outputFormat.sumUp
<< " value=" << outputFormat.value;
}
};
public:
static MeasuringTool& measuringTool() {
static MeasuringTool measuringTool;
return measuringTool;
}
void reset() {
timer = Timer<TimerKey, TimerValue>();
nonTimer = NonTimer<NonTimerRecord>();
leanNonTimer = LeanNonTimer<PhaseValue>();
disabled = false;
verbose = false;
prefix = "";
curPhase = "none";
curRound = 0;
}
void add(size_t value) {
//if (disabled) return;
//add(value, "unkown");
}
void add(
size_t value, const std::string& description, const bool sumUp = true) {
//if (disabled) return;
//if (verbose && env.rank() == 0) std::cout << description << std::endl;
//nonTimer.add(NonTimerRecord(curPhase, 0u, curRound, description,
// "number", false, sumUp, value));
}
void addRawCommunication(size_t value, const std::string& description) {
//if (disabled) return;
if (verbose && env.rank() == 0) std::cout << description << std::endl;
leanNonTimer.add(PhaseValue(curPhase, value));
}
void start(const std::string& description) {
if (disabled) return;
if (verbose && env.rank() == 0) std::cout << description << std::endl;
timer.start(TimerKey(curPhase, curRound, description),
TimerValue(0u, "", false, false, 0u));
}
void stop(const std::string& description) {
if (disabled) return;
if (verbose && env.rank() == 0) std::cout << description << std::endl;
timer.stop(TimerKey(curPhase, curRound, description));
}
std::vector<OutputFormat> collect() {
disable();
const size_t numMeasurements = 1000;
std::vector<OutputFormat> data;
data.reserve(10 * numMeasurements);
std::vector<NonTimerRecord> nonTimerRecords;
std::vector<PhaseValue> leanNonTimerRecords;
std::vector<std::pair<TimerKey, TimerValue>> timerRecords;
nonTimerRecords.reserve(numMeasurements);
leanNonTimerRecords.reserve(numMeasurements);
timerRecords.reserve(6 * numMeasurements);
nonTimer.collect(std::back_inserter(nonTimerRecords));
leanNonTimer.collect(std::back_inserter(leanNonTimerRecords));
timer.collect(std::back_inserter(timerRecords));
for (const auto& nonTimerRecord : nonTimerRecords)
data.push_back(
{prefix, nonTimerRecord.phase, nonTimerRecord.counterPerPhase,
nonTimerRecord.round, nonTimerRecord.description,
nonTimerRecord.type, nonTimerRecord.rawCommunication,
nonTimerRecord.sumUp, nonTimerRecord.value});
for (const auto& leanNonTimerRecord : leanNonTimerRecords)
data.push_back(
{prefix, leanNonTimerRecord.phase, 0,
0, "commVolume",
"number", true,
false, leanNonTimerRecord.value});
for (const auto& [timerKey, timerValue] : timerRecords)
data.push_back({prefix, timerKey.phase, timerValue.counterPerPhase,
timerKey.round, timerKey.description, timerValue.type,
timerValue.rawCommunication, timerValue.sumUp,
timerValue.value});
enable();
return data;
}
void writeToStream(std::ostream& stream) {
for (const auto& data : collect())
stream << data << std::endl;
}
void disableBarrier(bool value) {
timer.setDisableBarrier(value);
}
void enable() { disabled = false; }
void disable() { disabled = true; }
void setVerbose(const bool value) { verbose = value; }
void setPrefix(const std::string& prefix_) { prefix = prefix_; }
void setPhase(const std::string& phase) { curPhase = phase; }
void setRound(size_t round) { curRound = round; }
private:
bool disabled = false;
bool verbose = false;
std::string prefix = "";
std::string curPhase = "none";
size_t curRound = 0;
NonTimer<NonTimerRecord> nonTimer;
LeanNonTimer<PhaseValue> leanNonTimer;
Timer<TimerKey, TimerValue> timer;
};
} // namespace measurement
} // namespace dss_schimek
| true |
4ef77c804e32f86983b9515fff37c9aec1e26159 | C++ | cmusteata/workspace | /matrix/main.cpp | UTF-8 | 864 | 2.9375 | 3 | [] | no_license | #include <cassert>
#include <iostream>
#include "matrix.h"
const std::vector<std::vector<int>> before =
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9,10,11,12},
{13,14,15,16}
};
int main(int argc, char**)
{
assert(argc == 1);
for (const auto& r : before)
{
std::cout << "before:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
auto after = matrix_sum(before);
for (const auto& r : after)
{
std::cout << "after:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
auto before = matrix_restore(after);
for (const auto& r : before)
{
std::cout << "restore:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
return 0;
}
| true |
589ed98fcb881ac672727c6d6d658d8c049159d4 | C++ | Und3rMySk1n/ood | /lab04_factory/Painter/Painter.cpp | UTF-8 | 1,065 | 2.546875 | 3 | [] | no_license | // Painter.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../libpainter/SVGCanvas.h"
#include "../libpainter/Painter.h"
#include "../libpainter/Designer.h"
#include "../libpainter/ShapeFactory.h"
#include "../libpainter/PictureDraft.h"
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
string canvasFileName = "../canvas/canvas.svg";
ofstream canvasFile(canvasFileName.c_str());
if (!canvasFile.is_open())
{
throw runtime_error("Error while opening file for canvas.");
}
CSVGCanvas canvas(canvasFile);
CPainter painter;
CPictureDraft draft;
CShapeFactory shapeFactory;
CDesigner designer(shapeFactory);
try
{
draft = designer.CreateDraft(cin);
unique_ptr<CShape> newPolygon = shapeFactory.CreateShape("polygon green 100 100 70 5");
auto polygonClone = newPolygon->Clone();
draft.AddShape(move(polygonClone));
painter.DrawPicture(draft, canvas);
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}
| true |
66b1a515637d2be7ae6f041664ed97caa47c0096 | C++ | KashinYana/recognitionScans | /thresholding/thresholding.hpp | UTF-8 | 6,984 | 3.0625 | 3 | [] | no_license | #ifndef THRESHOLDING_H_INCLUDED
#define THRESHOLDING_H_INCLUDED
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
#include <iostream>
#include "../images/image.hpp"
class Thresholding
{
private:
cv::Mat matrix;
const int middleValue;
const int maxValue;
const int minValue;
const int upperBound;
const int downBound;
int numberColors;
int shift;
std::vector<std::vector<std::vector<int> > > partialSum;
public:
explicit Thresholding(const cv::Mat& matrix_, int shift_ = 11)
: matrix(matrix_), middleValue(128), minValue(0), maxValue(255),
upperBound(245), downBound(15), numberColors(3)
{
// matrix = Image::makeBlackAndWhite(matrix_);
// cvtColor(matrix_, matrix, CV_RGB2GRAY);
if (matrix.type() == CV_8UC1) {
numberColors = 1;
} else if (matrix.type() == CV_8UC3) {
} else {
throw std::logic_error("unsupported matrix type");
}
shift = shift_;
resizePartialSum();
initPartialSum();
}
cv::Mat simpleTransform(int middleValue_ = 128)
{
cv::Mat result(matrix.rows, matrix.cols, CV_8UC1);
for (int i = 0; i < result.rows; i++)
{
for (int j = 0; j < result.cols; j++)
{
for(int k = 0; k < numberColors; k++)
{
if(matrix.at<cv::Vec3b>(i, j)[k] > middleValue_)
{
result.at<uchar>(i, j) = maxValue;
}
else
{
result.at<uchar>(i, j) = minValue;
}
}
}
}
return result;
}
cv::Mat transform(int upperBound_ = 245, int downBound_ = 15)
{
cv::Mat result(matrix.rows, matrix.cols, CV_8UC1);
if (matrix.type() == CV_8UC3) { // process normal image
for (int i = 0; i < result.rows; i++)
{
for (int j = 0; j < result.cols; j++)
{
for(int k = 0; k < numberColors; k++)
{
int leftx = i;
int rightx = i + 2*shift;
int lefty = j;
int righty = j + 2*shift;
int threshold = partialSum[rightx][righty][k] - partialSum[rightx][lefty][k]
- partialSum[leftx][righty][k] + partialSum[leftx][lefty][k];
threshold /= (righty - lefty) * (rightx - leftx );
if (matrix.at<cv::Vec3b>(i, j)[k] > upperBound_)
{
result.at<uchar>(i, j) = maxValue;
}
else if (matrix.at<cv::Vec3b>(i, j)[k] < downBound_)
{
result.at<uchar>(i, j) = minValue;
}
else if (matrix.at<cv::Vec3b>(i, j)[k] > threshold)
{
result.at<uchar>(i, j) = maxValue;
}
else if (matrix.at<cv::Vec3b>(i, j)[k] < threshold)
{
result.at<uchar>(i, j) = minValue;
}
else if (matrix.at<cv::Vec3b>(i, j)[k] < middleValue)
{
result.at<uchar>(i, j) = minValue;
}
else
{
result.at<uchar>(i, j) = maxValue;
}
}
}
}
return result;
}
if (matrix.type() == CV_8UC1) { // process white-black image
for (int i = 0; i < result.rows; i++)
{
for (int j = 0; j < result.cols; j++)
{
int leftx = i;
int rightx = i + 2*shift;
int lefty = j;
int righty = j + 2*shift;
int threshold = partialSum[rightx][righty][0] - partialSum[rightx][lefty][0]
- partialSum[leftx][righty][0] + partialSum[leftx][lefty][0];
threshold /= (righty - lefty) * (rightx - leftx );
if (matrix.at<uchar>(i, j) > upperBound_)
{
result.at<uchar>(i, j) = maxValue;
}
else if (matrix.at<uchar>(i, j) < downBound_)
{
result.at<uchar>(i, j) = minValue;
}
else if (matrix.at<uchar>(i, j) > threshold)
{
result.at<uchar>(i, j) = maxValue;
}
else if (matrix.at<uchar>(i, j) < threshold)
{
result.at<uchar>(i, j) = minValue;
}
else if (matrix.at<uchar>(i, j) < middleValue)
{
result.at<uchar>(i, j) = minValue;
}
else
{
result.at<uchar>(i, j) = maxValue;
}
}
}
return result;
}
throw std::logic_error("unsupported matrix type for thresholding");
}
private:
void resizePartialSum()
{
partialSum.resize(matrix.rows + 2*shift);
for (int i = 0; i < partialSum.size(); i++)
{
partialSum[i].resize(matrix.cols + 2*shift);
for(int j = 0; j < partialSum[i].size(); j++)
{
partialSum[i][j].resize(numberColors);
}
}
}
void initPartialSum()
{
for (int i = 0; i < partialSum.size(); i++)
{
for (int j = 0; j < partialSum[i].size(); j++)
{
for(int k = 0; k < numberColors; k++)
{
if(i < shift || j < shift || i >= matrix.rows + shift || j >= matrix.cols + shift)
{
partialSum[i][j][k] = middleValue;
}
else
{
partialSum[i][j][k] = matrix.at<cv::Vec3b>(i - shift, j - shift)[k];
}
if(i > 0)
{
partialSum[i][j][k] += partialSum[i - 1][j][k];
}
if(j > 0)
{
partialSum[i][j][k] += partialSum[i][j - 1][k];
}
if(i > 0 && j > 0)
{
partialSum[i][j][k] -= partialSum[i - 1][j - 1][k];
}
}
}
}
}
};
#endif // THRESHOLDING_H_INCLUDED
| true |
4cd081549de0ad56aa1606b74b14843299cf1f94 | C++ | lingnand/Helium | /src/srchilite/textstylebuilder.h | UTF-8 | 751 | 2.75 | 3 | [] | no_license | /**
* Author: Lorenzo Bettini <http://www.lorenzobettini.it>, (C) 2005
* Copyright: See COPYING file that comes with this distribution
*/
#ifndef _TEXTSTYLEBUILDER_H_
#define _TEXTSTYLEBUILDER_H_
#include "textstyle.h"
namespace srchilite {
/**
* Given TextStyle objects build a new one,
* adding a starting part, and ending part, and separating
* them.
*/
class TextStyleBuilder {
std::string start_, separator_;
TextStyle buffer; ///< where we store intermediate results
bool added; ///< whether we've already added something
public:
TextStyleBuilder(const std::string &st = "", const std::string &sep = "");
void start();
void add(const TextStyle &textStyle);
TextStyle end();
};
}
#endif /*_TEXTSTYLEBUILDER_H_*/
| true |
508e0086e71e3ad03a9390d0fa0c57e8172bcb7a | C++ | bkyileo/algorithm-practice | /leetcode/Burst Balloons.cpp | WINDOWS-1252 | 622 | 3.09375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// ģ
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(),1);
nums.push_back(1);
int len=nums.size();
vector< vector<int> > dp(len,vector<int>(len,0));
for(int L=2;L<len;++L)
{
for(int left=0;left+L<len;++left)
{
int right=left+L;
for(int k=left+1;k<right;++k)
dp[left][right]=max(dp[left][right],dp[left][k]+dp[k][right]+nums[left]*nums[k]*nums[right]);
}
}
for(auto i:dp)
{
for(auto j:i)
{
cout<<j<<" ";
}
cout<<endl;
}
return dp[0][len-1];
}
int main()
{
vector<int> t{3, 1, 5, 8};
cout<<maxCoins(t)<<endl;
}
| true |
73c7b2bfb2cd3bdc025c74dfc6166e8bb1b991e1 | C++ | colinw7/CQGnuPlot | /src/CGnuPlotBoxPlotStyleValue.h | UTF-8 | 1,622 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef CGnuPlotBoxPlotStyleValue_H
#define CGnuPlotBoxPlotStyleValue_H
#include <COptVal.h>
#include <CGnuPlotTypes.h>
#include <CGnuPlotStyleValue.h>
class CGnuPlotBoxPlotStyleValue : public CGnuPlotStyleValue {
public:
typedef CGnuPlotTypes::BoxType BoxType;
typedef CGnuPlotTypes::BoxLabels BoxLabels;
public:
CGnuPlotBoxPlotStyleValue(CGnuPlotPlot *plot=nullptr);
virtual ~CGnuPlotBoxPlotStyleValue() { }
void init(const CGnuPlotBoxPlotStyleValue &boxPlot);
const BoxType &type() const { return type_; }
void setType(const BoxType &t) { type_ = t; }
const COptReal &range() const { return range_; }
void setRange(double r) { range_ = r; }
const COptReal &fraction() const { return fraction_; }
void setFraction(double r) { fraction_ = r; }
bool outliers() const { return outliers_; }
void setOutliers(bool b) { outliers_ = b; }
const COptReal &separation() const { return separation_; }
void setSeparation(double s) { separation_ = s; }
const COptInt &pointType() const { return pointType_; }
void setPointType(int t) { pointType_ = t; }
const BoxLabels &labels() const { return labels_; }
void setLabels(const BoxLabels &l) { labels_ = l; }
bool sorted() const { return sorted_; }
void setSorted(bool b) { sorted_ = b; }
void show(std::ostream &os) const;
void unset();
protected:
BoxType type_ { BoxType::CandleSticks };
COptReal range_;
COptReal fraction_;
bool outliers_ { true };
COptReal separation_;
COptInt pointType_;
BoxLabels labels_ { BoxLabels::Auto };
bool sorted_ { false };
};
#endif
| true |
63ca0c550e0a2fbb1266a77334bb880c0a7230b4 | C++ | JeffersonLab/qphix | /codegen/twisted_mass_enum.h | UTF-8 | 1,206 | 3.03125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include <map>
#include <string>
#include <vector>
/**
Versions of twisted mass.
Previously, there was a simple `bool` value `twisted_mass` that
would switch
twisted mass on or off. Now with the non-degenerate case, there
are three
options that need to be represented. Having a second `bool` named
`non_degenerate` would not suffice as the combination of
non-degernate
non-twisted mass does not make sense.
*/
enum class TwistedMassVariant {
/// Plain Wilson fermions.
none,
/// Degenerate, \f$ N_\mathrm f = 2 \f$, Wilson twisted mass
/// fermions.
degenerate,
/// Non-degernate, \f$ N_\mathrm f = 1 + 1 \f$, Wilson twisted
/// mass
/// fermions.
non_degenerate,
};
std::vector<TwistedMassVariant> const
selected_twisted_mass_variants{TwistedMassVariant::none,
TwistedMassVariant::degenerate};
/// Prefixes for the generated kernels.
std::map<TwistedMassVariant const, std::string const> const
twisted_mass_prefixes = {
{TwistedMassVariant::none, std::string("")},
{TwistedMassVariant::degenerate, std::string("tm_")},
{TwistedMassVariant::non_degenerate, std::string("ndtm_")},
};
| true |
cf83c7d830a5e93c36efc31c52695a6ab34b00a9 | C++ | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc026/A/2196084.cpp | UTF-8 | 167 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include <string>
#include<vector>
using namespace std;
int main(){
int a;
cin >> a;
cout << (a/2)*(a/2) << endl;
return 0;
} | true |
e3470be45c1a859d1fff1e5bc9e134c976ea21b0 | C++ | Ruturaj4/pin_examples | /flora.cpp | UTF-8 | 23,328 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "pin.H"
#include <fstream>
#include <string>
#include <list>
#include <boost/algorithm/string.hpp>
#include <unordered_map>
#include <exception>
// TODOs can be searched with ----> TODO:
// #define RPB_DEBUG // comment out to disable rbp debugging
// #define RBP_DETECTION // comment out to disable rbp detection
// #define DISASS_DEBUG // comment out to disable disassembly debugging
// key to detect the main Routine
static uint32_t key = 0;
// Map containing Blocks
// The keys are function name and the values are blocks per function
// std::list<struct Block> Blocks;
std::unordered_map <std::string, struct Block*> blocks;
// access bounds
class AccessBounds
{
private:
uint64_t base;
uint64_t bound;
public:
AccessBounds(uint64_t base, uint64_t bound){this->base = base; this->bound = bound;}
uint64_t get_base(){return base;}
uint64_t get_bound(){return bound;}
};
// Map to store all bound information globally
// key: owner
std::unordered_map <std::string, AccessBounds*> accessboundsmap;
// Stucture holds the control flow information
class RegisterBlock
{
private:
// -32
int64_t stack_pos;
// Actual value
int64_t value = -1;
public:
RegisterBlock(int64_t stack_pos, int64_t value)
{
this->stack_pos = stack_pos;
this-> value = value;
}
void set_stack_pos(int64_t stack_pos)
{
this->stack_pos = stack_pos;
}
void set_value(int64_t value)
{
this->value = value;
}
int64_t get_stack_pos()
{
return stack_pos;
}
int64_t get_value()
{
return value;
}
};
// position relative to the rbp
class RelPos
{
private:
// value present at the particular location on the stack
int64_t value;
// Owner
std::string owner;
// other info such as owner can be added here
public:
RelPos(int64_t value, std::string owner){this->value = value; this->owner = owner;}
void set_val(int64_t value){this->value = value;}
void set_owner(int64_t owner){this->owner = owner;}
int64_t get_value(){return value;}
std::string get_owner(){return owner;}
};
// Owner infomation of each location
class InsInfo
{
private:
ADDRINT address;
std::string owner;
public:
InsInfo(ADDRINT address, std::string owner) { this->address = address; this->owner = owner;}
ADDRINT get_address() {return address;}
std::string get_owner() {return owner;}
};
// Contains the information of all the objects
class ObjInfo
{
private:
// Location from the base pointer and the upper bound
int64_t ub;
// Data Type
std::string type;
// Object Type
std::string obj;
// Object name
std::string owner;
// Object size
int64_t obj_size;
// lower bound
int64_t lb;
public:
ObjInfo(int64_t ub, std::string type, std::string obj, string owner, int64_t obj_size)
{
this->ub = ub;
this->type = type;
this->obj = obj;
this->owner = owner;
this->obj_size = obj_size;
// Lower bounds calculated here
this->lb = ub + obj_size;
}
int64_t get_ub() {return ub;}
std::string get_type() {return type;}
std::string get_obj() {return obj;}
std::string get_owner() {return owner;}
int64_t get_obj_size() {return obj_size;}
int64_t get_lb() {return lb;}
};
// A structure to store all the file related information
struct Block
{
// Block name
std::string name;
// Allocated stack size
uint64_t size;
// Set the rbp value for the particular block
uint64_t rbp_value;
// Set the rsp value for the particular block
uint64_t rsp_value;
// Stucture to store control flow block information
// TODO: update this per control flow block
std::unordered_map <std::string, RegisterBlock*> registerblock;
// Object information hash map
std::unordered_map <std::string, ObjInfo*> objinfostack;
// static code locations hash map
std::unordered_map <ADDRINT, InsInfo*> inscodestack;
// Actual stack (positions related to rbp) hash map
std::unordered_map <uint64_t, RelPos*> relPosStack;
};
// rbp value Check
VOID rpb_check(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins)
{
if (addr > 0x700000000000)
return;
#ifdef DISASS_DEBUG
std::cout<<std::hex<<addr<<"\t"<<disassins<<dec<<std::endl;
#endif
// Set the rbp value for the particular function.
// Check if the rbp value is 0 which is equivalent to either return or unset
// If rbp value is changed other than 0 for the function give an error
if (i.rbp_value == PIN_GetContextReg(ctxt, REG_RBP))
{
#ifdef RPB_DEBUG
std::cout << hex << "rbp: " << i.rbp_value << '\n';
#endif
}
else if (i.rbp_value == 0)
{
#ifdef RPB_DEBUG
std::cout << "return: " << i.rbp_value << '\n';
#endif
}
else
{
std::cout << "RBP is changed(!) to: " << i.rbp_value << '\n';
}
}
// This sets up rbp and rsp values and sets the size of the stack for the corresponding block
VOID reg_val_set(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins)
{
std::cout << "rbp val: " << PIN_GetContextReg(ctxt, REG_RBP) << '\n';
// set the rbp value -- This value will stay same throughout the function
i.rbp_value = PIN_GetContextReg(ctxt, REG_RBP);
std::cout << "rsp val: " << PIN_GetContextReg(ctxt, REG_RSP) << '\n';
// set the rsp value -- This value will stay same throughout the function
i.rsp_value = PIN_GetContextReg(ctxt, REG_RSP);
// Set the stack size
i.size = i.rbp_value - i.rsp_value;
}
// mov DWORD PTR [rbp-0x20],0x1
VOID mov_immediate(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins,
std::string owner, int64_t displacement, int64_t immediate)
{
// Now check if the owner has correct stack access, i.e. if the owner is accessible
// this can be used to validate, otherwise it leads to a seg fault
auto iter = i.objinfostack.find(owner);
if ( iter == i.objinfostack.end())
{
std::cout << "Check your input!" << '\n';
std::exit(1);
}
// if the value is already in the map
// TODO: see if this is really required
// TODO: Effective address = Displacement + BaseReg + IndexReg * Scale
uint64_t effective_dispacement = i.rbp_value + displacement;
std::cout << "effective dispacement: " << effective_dispacement << '\n';
if(i.relPosStack.find(effective_dispacement) != i.relPosStack.end())
{
// Set the value of immediate at the particular stack position
i.relPosStack[effective_dispacement]->set_val(immediate);
}
else
{
// set the value and the owner
// There is no need of the absolute value, as the stack can grow both ways
i.relPosStack.insert(std::make_pair(effective_dispacement, new RelPos(immediate, owner)));
}
/* This part can actually be deleted or make bound check enabled*/
// Check if the address really has an owner: (this is equivalent to pass in python)
//while (i->inscodestack[INS_Address(ins)]);
// Get The lower and upper bounds
std::cout << "Upper bounds: " << i.objinfostack[owner]->get_ub() << '\n';
std::cout << "Lower bounds: " << i.objinfostack[owner]->get_lb() << '\n';
// If the type is array and the access is not within the bounds
// If rsp is to be detected and rsp + x is equivalent to ebp - (rsp + x)
if ((effective_dispacement < i.objinfostack[owner]->get_ub() + i.rbp_value ||
effective_dispacement > i.objinfostack[owner]->get_lb() + i.rbp_value) &&
i.objinfostack[owner]->get_obj() == "array")
std::cout << "Boundover accessed by " << owner << '\n';
}
// lea rax,[rbp-0x20]
VOID lea_inreg(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins,
int64_t displacement, REG reg)
{
std::cout << "reg val: " << hex << PIN_GetContextReg(ctxt, reg) << '\n';
std::cout<< hex <<addr<<"\t"<<disassins<<dec<<std::endl;
// std::cout << i->inscodestack[INS_Address(ins)]->get_owner() << '\n';
std::cout << "disas: " << hex << disassins << dec << '\n';
// move that value in the
// INS_MemoryDisplacement(ins) gives the location of the stack and then
// get_value() gives the value at that particular location of the stack
// register used in the instruction
std::string insreg = REG_StringShort(reg);
// Let the register structure hold the location on the stack for the particular register
// and not the value
// set the Register with the apporpriate value
// I made a map, using which we can work with any register
if(i.registerblock.find(insreg) != i.registerblock.end())
{
// TODO: Check if the register value needs to be set everytime
i.registerblock[insreg]->set_stack_pos(i.rbp_value + displacement);
}
else
{
// Setting the register value -1, as for now
i.registerblock.insert(std::make_pair(insreg, new RegisterBlock(i.rbp_value + displacement, i.rbp_value + displacement)));
}
}
// mov QWORD PTR [rbp-0x8],rax
VOID mov_reg(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins,
std::string owner, int64_t displacement, REG reg)
{
// Get the register value
std::string insreg = REG_StringShort(reg);
// TODO: temporary
if (insreg == "eax")
insreg = "rax";
// TODO: temporary
if (insreg == "edi")
return;
if (insreg == "rsi")
return;
std::cout << "disas: " << hex << disassins << dec << '\n';
// set the value of of the pos stack if the owner is a pointer
// TODO: Check is needed here - to check whether the register value is available in the
// structure as a key - maybe look for other places for the same
if(i.relPosStack.find(i.rbp_value + displacement) != i.relPosStack.end())
{
i.relPosStack[i.rbp_value + displacement]->set_val(i.registerblock[insreg]->get_stack_pos());
}
else
{
// set the value and the owner
// There is no need of the absolute value, as the stack can grow both ways
i.relPosStack.insert(std::make_pair(i.rbp_value + displacement, new RelPos(i.registerblock[insreg]->get_stack_pos(), owner)));
}
// Check to see if the owner is a pointer
if (i.objinfostack[owner]->get_obj() == "pointer")
{
// get the Register value
// pointer is getting the address of owner_prop and hence its bounds
std::string owner_prop = i.relPosStack[i.registerblock[insreg]->get_stack_pos()]->get_owner();
accessboundsmap.insert(std::make_pair(owner, new AccessBounds(i.objinfostack[owner_prop]->get_lb() +
i.rbp_value, i.objinfostack[owner_prop]->get_ub() + i.rbp_value)));
std::cout << "lower bounds: " << accessboundsmap[owner]->get_base() <<'\n';
std::cout << "Upper bounds: " << accessboundsmap[owner]->get_bound() <<'\n';
}
}
// mov rax,QWORD PTR [rbp-0x8]
VOID mov_mem_reg(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins,
std::string owner, int64_t displacement, REG reg)
{
std::cout << "reg val: " << hex << PIN_GetContextReg(ctxt, reg) << '\n';
std::cout<< hex <<addr<<"\t"<<disassins<<dec<<std::endl;
if (i.objinfostack[owner]->get_obj() == "pointer")
{
std::string insreg = REG_StringShort(reg);
i.registerblock[insreg]->set_stack_pos(i.rbp_value + displacement);
}
}
// mov DWORD PTR [rbp-0xc],eax
VOID mov_mem_reg_2(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins,
std::string owner, int64_t displacement, REG base_reg)
{
if (i.objinfostack[owner]->get_obj() == "scalar")
{
// operand memory base register
std::string opbasereg = REG_StringShort(base_reg);
std::cout << "INS_OperandMemoryIndexReg: " << base_reg << '\n';
// Checks can be done here
// Get the owner
if (i.objinfostack[i.relPosStack[i.registerblock[opbasereg]->get_stack_pos()]->get_owner()]->get_obj() == "pointer")
{
if (((accessboundsmap[i.relPosStack[i.registerblock[opbasereg]->get_stack_pos()]->get_owner()]->get_base() -
i.rbp_value + displacement) > (accessboundsmap[i.relPosStack[i.registerblock[opbasereg]->get_stack_pos()]->get_owner()]->get_base())) ||
((accessboundsmap[i.relPosStack[i.registerblock[opbasereg]->get_stack_pos()]->get_owner()]->get_base()) - i.objinfostack[owner]->get_obj_size() -
i.rbp_value + displacement) < accessboundsmap[i.relPosStack[i.registerblock[opbasereg]->get_stack_pos()]->get_owner()]->get_bound())
{
std::cout << "abort" << '\n';
}
}
}
}
// set the value of rbp after detecting using sub rsp, xx instruction
VOID rbp_set(uint64_t addr, CONTEXT * ctxt, Block &i, std::string disassins)
{
#ifdef RPB_DEBUG
std::cout << "rbp set: " << i.rbp_value << '\n';
std::cout << "rbp_routine name: " << i.name << '\n';
#endif
// set the rbp value -- This value will stay same throughout the function
i.rbp_value = PIN_GetContextReg(ctxt, REG_RBP);
// #ifdef RPB_DEBUG
std::cout << hex << "rbp set: " << i.rbp_value << dec << '\n';
// #endif
}
// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
// Functin variables
std::string opbasereg = "";
// First check if the routine is valid
if (!RTN_Valid(RTN_FindByAddress(INS_Address(ins))))
return;
// skip if the address is over 0x700000000000
if (INS_Address(ins) > 0x700000000000)
return;
// Block hash map access
// Find the current routine
if ( blocks.find(RTN_Name(RTN_FindByAddress(INS_Address(ins)))) == blocks.end())
return;
struct Block *i = blocks[RTN_Name(RTN_FindByAddress(INS_Address(ins)))];
/* set rbp and rsp values */
// mov rbp, rsp
// This is so that, a function can be detected
// If the below insturction is not detected, rsp and rbp will remain same
// Detect sub rbp, rsp instruction - another way
// if (REG_is_stackptr_type(INS_OperandReg(ins, 0)))
if (INS_Opcode(ins) == XED_ICLASS_MOV && (INS_OperandReg(ins,0) == REG_RBP)
&& (INS_OperandReg(ins,1) == REG_RSP))
{
INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)reg_val_set, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
}
if((INS_Opcode(ins) == XED_ICLASS_ADD || INS_Opcode(ins) == XED_ICLASS_SUB)
&&(INS_OperandIsImmediate(ins, 1)) && (INS_OperandReg(ins,0) == REG_RSP))
{
INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)reg_val_set, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
}
/* END */
/* Get the owner */
// Get the owner for the particular static address
std::string owner;
if ( i->inscodestack.find(INS_Address(ins)) == i->inscodestack.end())
{
// An exeption can be called here
return;
}
else
{
owner = i->inscodestack[INS_Address(ins)]->get_owner();
}
/* END */
// Returns the name of the block
// std::cout << "RTN: " << RTN_Name(RTN_FindByAddress(INS_Address(ins))) << '\n';
#ifdef RPB_DEBUG
std::cout << "rbp: " << i->rbp_value << '\n';
#endif
#ifdef RBP_DETECTION
// Detect the mov rbp, rsp instruction
// This is so that, a function can be detected
if (INS_Opcode(ins) == XED_ICLASS_MOV && (INS_OperandReg(ins,0) == REG_RBP))
{
INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)rbp_set, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
}
#endif
// Detect the return instruction
// For rbp detection
// This can be done after the end of a particular function - but not needed as the
// values of rbp and rsp are specific to the function and not global
#ifdef RBP_DETECTION
if (INS_IsRet(ins))
{
#ifdef RPB_DEBUG
std::cout << "Return instruction detected" << '\n';
#endif
// Make rbp 0 before each return
i->rbp_value = 0;
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)rpb_check, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
}
#endif
/**** Detection of instructions starts here ****/
// Detect all memory store instructions (check only fro rbp and not rsp)
// Array bounds check - not related to the softbounds technique
// But it protects the array overflow
// DWORD PTR [rbp-0x20],0x1
if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 0)
&& ((INS_OperandWidth(ins, 0) == 32)
|| (INS_OperandWidth(ins, 0) == 64))
&& ((INS_OperandMemoryBaseReg(ins, 0) == REG_RBP)
|| (INS_OperandMemoryBaseReg(ins, 0) == REG_EBP))
&& INS_OperandIsImmediate(ins, 1))
{
// Check if the rbp is not changed
#ifdef RBP_DETECTION
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)rpb_check, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)), IARG_END);
#endif
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)mov_immediate, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)),
IARG_PTR, new string(owner), IARG_ADDRINT, INS_OperandMemoryDisplacement(ins, 0),
IARG_ADDRINT, INS_OperandImmediate(ins, 1), IARG_END);
}
// If the owner is a pointer
// First check for the load instruction in the register
// This will assume that the register will be used in future
if ((INS_Opcode(ins) == XED_ICLASS_LEA) && (INS_OperandIsReg(ins, 0)) &&
INS_HasExplicitMemoryReference(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)lea_inreg, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)),
IARG_ADDRINT, INS_MemoryDisplacement(ins), IARG_UINT32, REG(INS_OperandReg(ins, 0)), IARG_END);
}
// If operand is a register - mov QWORD PTR [rbp-0x8],rax
if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 0)
&& ((INS_OperandWidth(ins, 0) == 32)
|| (INS_OperandWidth(ins, 0) == 64))
&& ((INS_OperandMemoryBaseReg(ins, 0) == REG_RBP)
|| (INS_OperandMemoryBaseReg(ins, 0) == REG_EBP))
&& INS_OperandIsReg(ins, 1))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)mov_reg, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)),
IARG_PTR, new string(owner), IARG_ADDRINT, INS_MemoryDisplacement(ins), IARG_UINT32, REG(INS_OperandReg(ins, 1)), IARG_END);
}
// If the pointer value is loaded
// rax,QWORD PTR [rbp-0x8]
if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 1) && INS_OperandIsReg(ins, 0)
&& ((INS_OperandWidth(ins, 1) == 32)
|| (INS_OperandWidth(ins, 1) == 64))
&& ((INS_OperandMemoryBaseReg(ins, 1) == REG_RBP)
|| (INS_OperandMemoryBaseReg(ins, 1) == REG_EBP)))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)mov_mem_reg, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)),
IARG_PTR, new string(owner), IARG_ADDRINT, INS_MemoryDisplacement(ins), IARG_UINT32, REG(INS_OperandReg(ins, 0)), IARG_END);
}
if ((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_OperandIsMemory(ins, 1)
&& ((INS_OperandWidth(ins, 1) == 32)
|| (INS_OperandWidth(ins, 1) == 64))
&& ((INS_OperandMemoryBaseReg(ins, 1) != REG_RBP)
&& (INS_OperandMemoryBaseReg(ins, 1) != REG_EBP)))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)mov_mem_reg_2, IARG_ADDRINT,
INS_Address(ins), IARG_CONTEXT, IARG_PTR, &(*i), IARG_PTR, new string(INS_Disassemble(ins)),
IARG_PTR, new string(owner), IARG_ADDRINT, INS_OperandMemoryDisplacement(ins, 1),
IARG_UINT32, REG(INS_OperandMemoryBaseReg(ins, 1)), IARG_END);
}
// if (i->objinfostack[owner]->get_obj() == "pointer")
// {
// std::cout << hex << INS_Disassemble(ins) << dec << '\n';
// // if ((INS_Opcode(ins) == XED_ICLASS_MOV) && (INS_OperandIsReg(ins, 1)))
// }
// For control flow Blocks
if (INS_BranchTakenPrefix(ins))
std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << '\n';
if (INS_IsBranchOrCall(ins))
std::cout << "Branch: " << hex << INS_Disassemble(ins) << dec << '\n';
if (!INS_HasFallThrough(ins))
std::cout<<"\nbranch!\n\n";
}
// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
}
INT32 Usage()
{
cerr << "This tool counts the number of dynamic instructions executed" << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
void readInput(char *filename)
{
std::string line;
std::ifstream myfile(filename);
if (myfile.is_open())
{
// Get the count of the total number of blocks
getline (myfile,line);
int64_t count = atoi(line.c_str());
// Ignore newline after the count
getline (myfile,line);
while (count)
{
// Initialize the structure
struct Block *block = new Block;
// for the function name
getline (myfile,line);
block->name = line;
// for the stack size
getline (myfile,line);
block->size = atoi(line.c_str());
block->rbp_value = 0;
while ( getline (myfile,line) )
{
if (line.empty())
{
break;
}
else
{
std::vector<std::string> temp;
boost::split(temp, line, boost::is_any_of("\t "));
block->inscodestack.insert(std::make_pair(strtol(temp[0].c_str(), NULL, 16), new InsInfo(strtol(temp[0].c_str(), NULL, 16), temp[1])));
//std::cout << "temp[1]: " << hex <<strtol(temp[0].c_str(), NULL, 16) << '\n';
}
}
while ( getline (myfile,line) )
{
if (line.empty())
{
break;
}
else
{
std::vector<std::string> temp;
boost::split(temp, line, boost::is_any_of("\t "));
//ObjInfo *objinfo = new ObjInfo {atoi(temp[0].c_str()), temp[1], temp[2], temp[3], atoi(temp[4].c_str())};
block->objinfostack.insert(std::make_pair(temp[3], new ObjInfo(atoi(temp[0].c_str()), temp[1], temp[2], temp[3], atoi(temp[4].c_str()))));
}
}
// // make every location zero upon initialization
// for (uint64_t i = 0; i <= block.size; ++i)
// block.relPosStack.insert(std::make_pair(i, new RelPos(0)));
blocks.insert(std::make_pair(block->name, block));
--count;
}
myfile.close();
}
else std::cout << "Unable to open file\n";
}
// Lock Routines
void mutex_lock()
{
key = 0;
//std::cout<<"out\n";
}
void mutex_unlock()
{
key = 1;
//std::cout<<"in\n";
}
void Image(IMG img, VOID *v)
{
RTN mainrtn = RTN_FindByName(img, "main");
if (RTN_Valid(mainrtn))
{
std::cout << "Routine " << RTN_Name(mainrtn)<< '\n';
RTN_Open(mainrtn);
// Apply the locks to the main routine
RTN_InsertCall(mainrtn, IPOINT_BEFORE, (AFUNPTR)mutex_unlock, IARG_END);
RTN_InsertCall(mainrtn, IPOINT_AFTER, (AFUNPTR)mutex_lock, IARG_END);
RTN_Close(mainrtn);
}
}
int main(int argc, char * argv[])
{
// Initialize pin
PIN_InitSymbols();
if (PIN_Init(argc, argv)) return Usage();
// Argv[7] is the name of the input file
readInput(argv[7]);
// Register Instruction to be called to instrument instructions
INS_AddInstrumentFunction(Instruction, 0);
// Image instrumentation
IMG_AddInstrumentFunction(Image, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
| true |
4e54fc40e2180afc6f10011c06bf7feb2bf3b433 | C++ | true-bear/cpp_server_study_projects_Pub | /ebook_GameServerProgramming/ServerCore/ServerLibrary/Util/GameObject.h | UHC | 725 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "stdafx.h"
class Object
{
wstr_t allocFile_;
int allocLine_;
};
class NameObject
{
wstr_t name_;
public:
wstr_t& name()
{
return name_;
}
void setName(wstr_t name)
{
name_ = name;
}
};
class Work
{
public:
virtual void tick() = 0;
virtual void wakeup() {};
virtual void suspend() {};
virtual void stop() {};
virtual void start() {};
};
class GameObject : public NameObject, public Work
{
POINT position_;
float direction_;
public:
// Ŭ ̸ Ҹ ̸ ٸǷ, free Ű
virtual ~GameObject()
{
this->free();
}
virtual void initialize() {};
virtual void free() {};
}; | true |
4c0aa5dcd9a3fed8777d5029a319711a50d9bd4b | C++ | jjdredd/math536 | /hw1.cpp | UTF-8 | 1,613 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "sbms.hpp"
#include "util.hpp"
// problem 2
void Problem_2() {
std::cout << "Problem_2" << std::endl;
unsigned N = 5;
SBMS A(N, N);
std::vector<double> R, b = {5, 3.55, 2.81428571428571,
2.34642857142857, 2.01746031746032};
for (unsigned i = 0; i < N; i++) {
for (unsigned j = i; j < N; j++)
A.Set(i, j, 1.0/((i + 1) + (j + 1) - 1));
}
std::cout << "Hilbert matrix" << std::endl
<< A << std::endl;
LSBMS C = A.Cholesky(); // need smart ptrs
std::cout << "Cholesky (H)" << std::endl
<< C << std::endl;
R = CSolve(C, b);
std::cout << "x = " << R << std::endl << std::endl;
std::cout << "perturbed" << std::endl;
A.Set(0, 4, .20001);
std::cout << "Perturbed Hilbert matrix" << std::endl
<< A << std::endl;
C = A.Cholesky();
R = CSolve(C, b);
std::cout << "x = " << R << std::endl;
return;
}
void Problem_3() {
char *fname = "./conv.txt";
std::cout << "Problem_3" << std::endl
<< "output in " << fname << std::endl;
// here bandwidth is defined differently
// than in problem formulation
unsigned N = 10, k = 3, steps;
std::vector<double> b = {9, 10, 11, 11, 11, 11, 11, 11, 10, 9};
SBMS A(N, k);
ProblemTwoFill(A);
std::cout << "==========[ A ]==========" << std::endl
<< A << std::endl << std::endl;
std::vector<double> x;
std::ofstream ofile("./conv.txt");
for (double w = 0.1; w < 2; w += 0.1) {
x = SORSolve(A, b, steps, w, 1e-6);
ofile << w << '\t' << steps << std::endl;
}
std::cout << "x = " << x << std::endl;
}
int main() {
Problem_2();
Problem_3();
return 0;
}
| true |
1e253707a42775f3d08cbf9273d0724c9b58eeac | C++ | KriAB/Oblig3Visualisering | /mousepicker.cpp | UTF-8 | 8,490 | 2.59375 | 3 | [] | no_license | #include "mousepicker.h"
#include <QMouseEvent>
#include "renderwindow.h"
#include "resourcefactory.h"
#include "transformcomponent.h"
#include "meshcomponent.h"
#include "collisioncomponent.h"
#include "systemmanager.h"
#include "componentsystem.h"
MousePicker::MousePicker(RenderWindow *renderWindow, Camera *cam, SystemManager *syst/*, gsl::Matrix4x4 projMat*/)
{
mRenderWindow = renderWindow;
currentCamera = cam;
mProjectionMatrix = currentCamera->mProjectionMatrix;
mViewMatrix = currentCamera->mViewMatrix;
mSystemManager = syst;
}
void MousePicker::update()
{
mViewMatrix = currentCamera->mViewMatrix;
mProjectionMatrix = currentCamera->mProjectionMatrix;
currentRay = calculateMouseRay();
}
gsl::Vector3D MousePicker::calculateMouseRay()
{
//Mouse er i Viewport space, må convertere til worldspace
float mouseX =mRenderWindow->mMouseX; //putte inn i renderWindow, så det kan henter derfra heller
float mouseY = mRenderWindow->mMouseY;
//Convert from Viewport space to Normalized device space
gsl::Vector2D normalizedCoords = getNormalizedDeviceCoordinates(mouseX,mouseY);
// std::cout << normalizedCoords << std::endl;
//Convert from Normalized device space to homogeneous clip space
gsl::Vector4D clipCoords = gsl::Vector4D(normalizedCoords.x,normalizedCoords.y, -1.f,1.f);
// std::cout << clipCoords << std::endl;
//Convert from Clip space to Eye space
gsl::Vector4D eyeCoords = toEyeCoords(clipCoords);
//std::cout << eyeCoords << std::endl;
//Convert from Eye space to World space
gsl::Vector3D worldRay = toWorldCoords(eyeCoords);
//std::cout << worldRay << std::endl;
// std::cout << "World Ray: " << worldRay <<std::endl;
return worldRay;
}
gsl::Vector2D MousePicker::getNormalizedDeviceCoordinates(float xMouse, float yMouse)
{
QSize windowSize = mRenderWindow->getWindowSize();
float x = (2.0f*xMouse) / windowSize.width() -1;
float y = 1 - (2.0f*yMouse) / windowSize.height();
return gsl::Vector2D(x,y); //kan være jeg må returnere (x, -y)
}
gsl::Vector4D MousePicker::toEyeCoords(gsl::Vector4D clipCoords)
{
gsl::Matrix4x4 invertedProjection = mProjectionMatrix;
invertedProjection.inverse();
gsl::Vector4D eyeCoords = invertedProjection*clipCoords;
//Kun interessert i x,y
eyeCoords = gsl::Vector4D(eyeCoords.x, eyeCoords.y, -1.0f, 0.0f);
return eyeCoords;
}
gsl::Vector3D MousePicker::toWorldCoords(gsl::Vector4D eyeCoords)
{
gsl::Matrix4x4 invertetViewMat = mViewMatrix;
invertetViewMat.inverse();
gsl::Vector4D rayWorld = invertetViewMat * eyeCoords;
gsl::Vector3D rayMouse = gsl::Vector3D(rayWorld.x,rayWorld.y,rayWorld.z);
rayMouse.normalize();
return rayMouse;
}
gsl::Vector3D MousePicker::getIntersectionPoint()
{
return intersectionPoint;
}
gsl::Vector3D MousePicker::getPointOnRay(gsl::Vector3D ray, float distance)
{
gsl::Vector3D camPos = currentCamera->position();
gsl::Vector3D start = gsl::Vector3D(camPos.x,camPos.y,camPos.z);
gsl::Vector3D scaledRay = gsl::Vector3D(ray.x*distance, ray.y*rayLenght, ray.z*distance);
gsl::Vector3D pointOnRay = start+scaledRay;
return pointOnRay;
}
int MousePicker::intersectedEntity()
{
ComponentSystem *compS = mSystemManager->componentSystem();
gsl::Vector3D tempIntersectionCoord = currentRay;
//Hvis man får lengden mellom posisjonen til objektet og rayen
// std::cout << "IntersectionPoint: " << tempIntersectionCoord <<std::endl;
//sjekke at Objektet har kollisjon, hvis ikke bruke meshen. Må tenke på scale
for(int i = 0; i <compS->getTransformComponents().size(); i++)
{
TransformComponent* tempTrans = compS->getTransCompWithEId(i);
MeshComponent* tempMesh = compS->getMeshCompWithEId(i);
CollisionComponent* tempColl = compS->getCollCompWithEId(i);
//Loop som sjekker for forskjellige lengder til rayen
for(float j = 0; j < rayLenght; j ++)
{
tempIntersectionCoord = currentRay;
tempIntersectionCoord = getPointOnRay(currentRay,j);
if(tempColl!= nullptr)
{
// if(tempTrans.at(i)->position().x - tempIntersectionCoord.x < tempColl.at(i)->getLengthX()/2 && tempTrans.at(i)->position().x - tempIntersectionCoord.x > -tempColl.at(i)->getLengthX()/2 )
// if(tempTrans.at(i)->position().y - tempIntersectionCoord.y < tempColl.at(i)->getLengthY()/2 && tempTrans.at(i)->position().y - tempIntersectionCoord.y > -tempColl.at(i)->getLengthY()/2 )
// if(tempTrans.at(i)->position().z - tempIntersectionCoord.z < tempColl.at(i)->getLengthZ()/2 && tempTrans.at(i)->position().z - tempIntersectionCoord.z > -tempColl.at(i)->getLengthZ()/2 )
// {
// intersectionPoint = tempIntersectionCoord;
// std::cout << "IntersectionPoint: " << intersectionPoint << " Entity: " << i << std::endl;
// return i;
// }
//Må være true for alle x,y,z
if(tempTrans->position().x - ((tempColl->getLengthX())/2) < tempIntersectionCoord.x && tempTrans->position().x + tempColl->getLengthX()/2 > tempIntersectionCoord.x)
{
if(tempTrans->position().y - ((tempColl->getLengthY())/2) < tempIntersectionCoord.y && tempTrans->position().y + tempColl->getLengthY()/2 > tempIntersectionCoord.x)
{
if(tempTrans->position().z - ((tempColl->getLengthZ())/2) < tempIntersectionCoord.z && tempTrans->position().z + tempColl->getLengthZ()/2 > tempIntersectionCoord.z)
{
intersectionPoint = tempIntersectionCoord;
// std::cout << "IntersectionPoint: " << intersectionPoint << " Entity: " << i << std::endl;
return i;
}
}
} //Hvis ikke bruk meshens minste og største verdi. Må finne en bedre løsning
else if(tempMesh != nullptr)
{
if(tempTrans->position().x+tempMesh->getSmallestBiggestXYZ().at(0) < tempIntersectionCoord.x && tempTrans->position().x+tempMesh->getSmallestBiggestXYZ().at(1) > tempIntersectionCoord.x)
{
if(tempTrans->position().y+tempMesh->getSmallestBiggestXYZ().at(2) < tempIntersectionCoord.y &&tempTrans->position().y+tempMesh->getSmallestBiggestXYZ().at(3) > tempIntersectionCoord.y)
{
if(tempTrans->position().z+tempMesh->getSmallestBiggestXYZ().at(4) < tempIntersectionCoord.z && tempTrans->position().z+tempMesh->getSmallestBiggestXYZ().at(5) > tempIntersectionCoord.z)
{
intersectionPoint = tempIntersectionCoord;
//std::cout << "IntersectionPoint: " << intersectionPoint << " Entity: " << i << " Position: " << tempTrans.at(i)->position()<<std::endl;
return i;
}
}
}
// if(tempTrans.at(i)->position().x - tempIntersectionCoord.x < tempMeshes.at(i)->getLengthX()/2 && tempTrans.at(i)->position().x - tempIntersectionCoord.x > -tempMeshes.at(i)->getLengthX()/2 )
// if(tempTrans.at(i)->position().y - tempIntersectionCoord.y < tempMeshes.at(i)->getLengthY()/2 && tempTrans.at(i)->position().y - tempIntersectionCoord.y > -tempMeshes.at(i)->getLengthY()/2 )
// if(tempTrans.at(i)->position().z - tempIntersectionCoord.z < tempMeshes.at(i)->getLengthZ()/2 && tempTrans.at(i)->position().z - tempIntersectionCoord.z > -tempMeshes.at(i)->getLengthZ()/2 )
// {
// intersectionPoint = tempIntersectionCoord;
// std::cout << "IntersectionPoint: " << intersectionPoint << " Entity: " << i << std::endl;
// return i;
// }
}
else
{
std::cout << "Something wrong with Intersected Entity!" << std::endl;
return -1;
}
}
}
}
return - 1;
}
| true |
87de34e2ecfa2d76799baa5039832740cbc9124b | C++ | devanshdalal/leetcode-solutions | /MaximalSquare.cpp | UTF-8 | 916 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int maximalSquare(vector<vector<char>>& a) {
int n=a.size();
if(n==0)return 0;
int m=a[0].size();
// cerr << a[0][0] << endl;
int x[n+1][m+1];
int y[n+1][m+1];
int d[n+1][m+1];
for(int i=0;i<=n;i++){
x[i][m]=y[i][m]=d[i][m]=0;
}
for(int i=0;i<=m;i++){
x[n][i]=y[n][i]=d[n][i]=0;
}
int ans =0;
for(int i=n-1;i>=0;i--){
for(int j=m-1;j>=0;j--){
x[i][j]=(a[i][j]-'0')*(x[i+1][j]+1) ;
y[i][j]=(a[i][j]-'0')*(y[i][j+1]+1) ;
d[i][j]=(a[i][j]-'0')*min(min(d[i+1][j+1]+1,x[i][j]),y[i][j]);
ans = max(ans,d[i][j]*d[i][j]);
}
}
return ans;
}
}; | true |
6c4e43864210344c2faca45a582f8d70bd8123ae | C++ | timcsy/SelfDrivingCar | /connection.cpp | UTF-8 | 904 | 2.859375 | 3 | [] | no_license | #include <Arduino.h>
#include "connection.h"
int status = WL_IDLE_STATUS;
void wifi_connect(char * ssid, char * pass) {
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = (pass[0] == '\0')? WiFi.begin(ssid): WiFi.begin(ssid, pass);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
} | true |
70be2a4861e92f55fd969cbbd9287033efbe5902 | C++ | kevinclark/kata | /cpp/texting/include/Trie.hpp | UTF-8 | 3,134 | 3.625 | 4 | [] | no_license | #ifndef TRIE_HPP
#define TRIE_HPP
#include <map>
#include <set>
#include <utility>
#include <iterator>
#include <boost/foreach.hpp>
template <typename Key, typename Value>
class TrieNode
{
public:
typedef Key key_type;
typedef Value value_type;
typedef std::set<value_type> storage_type;
private:
typedef std::map<key_type, TrieNode*> map_type;
public:
TrieNode* operator[](const key_type& key) const
{
typename map_type::const_iterator edge = m_edges.find(key);
if (edge != m_edges.end())
{
return edge->second;
}
else
{
return NULL;
}
}
void AddValue(const value_type& value)
{
m_values.insert(value);
}
const storage_type& Values() const
{
return m_values;
}
TrieNode* AddEdge(key_type key)
{
TrieNode* node(new TrieNode());
m_edges.insert(std::make_pair(key, node));
return node;
}
~TrieNode()
{
BOOST_FOREACH(const typename map_type::value_type& edge, m_edges)
{
if (edge.second != NULL)
{
delete edge.second;
}
}
}
private:
storage_type m_values;
map_type m_edges;
};
template <typename Key, typename Value>
class Trie
{
public:
typedef Key key_type;
typedef Value value_type;
typedef TrieNode<key_type, value_type> node_type;
typedef typename node_type::storage_type::const_iterator result_const_iterator;
typedef std::pair<result_const_iterator, result_const_iterator> result_type;
template <typename Container>
void insert(const Container& keys, const value_type& value)
{
node_type* currentNode = &m_root;
BOOST_FOREACH(const key_type& key, keys)
{
node_type* nextNode = (*currentNode)[key];
// If this length isn't built, build it
if (nextNode == NULL)
{
nextNode = currentNode->AddEdge(key);
}
currentNode = nextNode;
}
if (currentNode != NULL)
{
currentNode->AddValue(value);
}
}
template <typename Container>
result_type find(const Container keys) const
{
const node_type* currentNode = &m_root;
const node_type* nextNode = NULL;
BOOST_FOREACH(const key_type& key, keys)
{
nextNode = (*currentNode)[key];
if (nextNode == NULL)
{
break;
}
currentNode = nextNode;
}
if (nextNode == NULL)
{
return std::make_pair(result_const_iterator(), result_const_iterator());
}
return std::make_pair(nextNode->Values().begin(), nextNode->Values().end());
}
private:
node_type m_root;
};
#endif
| true |
94fe0684f5366957bf02ade5f7ab34c3a97cac57 | C++ | Al3x76/cpp | /Pbinfo/KSort.cpp | UTF-8 | 497 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
void sortare(int a, int b, int v[], bool cresc){
for(int i=a; i<b; i++)
for(int j=i+1; j<=b; j++)
if(cresc){
if(v[i]>v[j]) swap(v[i], v[j]);
}
else if(v[i]<v[j]) swap(v[i], v[j]);
}
int main(){
int n, k, a[1005];
cin>>n>>k;
for(int i=1; i<=n; i++) cin>>a[i];
sortare(1, k, a, 1);
sortare(k+1, n, a, 0);
for(int i=1; i<=n; i++) cout<<a[i]<<" ";
return 0;
} | true |
a920e5d89975bcc4331a04971b9df4a19d50a02b | C++ | billux/budgetwarrior | /include/console.hpp | UTF-8 | 8,285 | 2.984375 | 3 | [
"MIT"
] | permissive | //=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CONSOLE_H
#define CONSOLE_H
#include <vector>
#include <string>
#include <iostream>
#include "money.hpp"
#include "date.hpp"
#include "accounts.hpp"
namespace budget {
inline std::string red(const std::string& str){
return "\033[0;31m" + str + "\033[0;3047m";
}
inline std::string green(const std::string& str){
return "\033[0;32m" + str + "\033[0;3047m";
}
inline std::string cyan(const std::string& str){
return "\033[0;33m" + str + "\033[0;3047m";
}
std::string format_money(const budget::money& m);
std::string format_money_reverse(const budget::money& m);
/**
* Returns the real size of a string. By default, accented characteres are
* represented by several chars and make the length of the string being bigger
* than its displayable length. This functionr returns only a size of 1 for an
* accented chars.
* \param value The string we want the real length for.
* \return The real length of the string.
*/
std::size_t rsize(const std::string& value);
template<typename T>
void print_minimum(const T& value, std::size_t min_width){
auto str = to_string(value);
auto old_width = std::cout.width();
std::cout.width(min_width + (str.size() - rsize(str)));
std::cout << str;
std::cout.width(old_width);
}
/**
* Indicate if the given option was present in the list. If present, the option
* is removed from the list.
* \param option The full option name with any - included
* \param args The command line arguments
* \return true if the option was present, false otherwise.
*/
bool option(const std::string& option, std::vector<std::string>& args);
/**
* Return the value of the given option if present or the default value
* otherwise
* \param option The full option name with any - included
* \param args The command line arguments
* \return The string value of the option or the default value is not present.
*/
std::string option_value(const std::string& option, std::vector<std::string>& args, const std::string& value);
std::string format_code(int attr, int fg, int bg);
std::string format(const std::string& value);
void display_table(std::vector<std::string> columns, std::vector<std::vector<std::string>> contents, std::size_t groups = 1);
template<typename T>
bool check(const T&){
return true;
}
template<typename T, typename CheckerA, typename ...Checker>
bool check(const T& value, CheckerA first, Checker... checkers){
if(!first(value)){
std::cout << first.message() << std::endl;
return false;
}
return check(value, checkers...);
}
template<typename ...Checker>
void edit_string(std::string& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = answer;
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_number(std::size_t& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<std::size_t>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_double(double& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<double>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_money(budget::money& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = parse_money(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_date(date& ref, const std::string& title, Checker... checkers){
bool checked;
do {
try {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
bool math = false;
if(answer[0] == '+'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref += days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref += months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref += years(std::stoi(str));
math = true;
}
} else if(answer[0] == '-'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref -= days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref -= months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref -= years(std::stoi(str));
math = true;
}
}
if(!math) {
ref = from_string(answer);
}
}
checked = check(ref, checkers...);
} catch(const date_exception& e){
std::cout << e.message() << std::endl;
checked = false;
}
} while(!checked);
}
struct not_empty_checker {
bool operator()(const std::string& value){
return !value.empty();
}
std::string message(){
return "This value cannot be empty";
}
};
struct not_negative_checker {
bool operator()(const budget::money& amount){
return !(amount.dollars() < 0 || amount.cents() < 0);
}
std::string message(){
return "The amount cannot be negative";
}
};
struct not_zero_checker {
bool operator()(const budget::money& amount){
return amount.dollars() > 0 || amount.cents() > 0;
}
std::string message(){
return "The amount cannot be negative";
}
};
struct account_checker {
bool operator()(const std::string& value){
return account_exists(value);
}
std::string message(){
return "The account does not exist";
}
};
template<std::size_t First, std::size_t Last>
struct range_checker {
bool operator()(const std::size_t& value){
return value >= First && value <= Last;
}
std::string message(){
std::string m = "Value must in the range [";
m += to_string(First);
m += ", ";
m += to_string(Last);
m += "]";
return m;
}
};
struct one_of_checker {
std::vector<std::string> values;
one_of_checker(std::vector<std::string> values) : values(values){
//Nothing to init
}
bool operator()(const std::string& value){
for(auto& v : values){
if(value == v){
return true;
}
}
return false;
}
std::string message(){
std::string value = "This value can only be one of these values [";
std::string comma = "";
for(auto& v : values){
value += comma;
value += v;
comma = ", ";
}
value += "]";
return value;
}
};
} //end of namespace budget
#endif
| true |
2a9674172678aee957a3c6c1b0c6b851ac21c57b | C++ | Ayesha049/leetcode | /289-game-of-life/289-game-of-life.cpp | UTF-8 | 1,140 | 2.59375 | 3 | [] | no_license | class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int n = board.size();
if(n==0) return;
int m = board[0].size();
if(m==0) return;
vector<bool>temp(m,0);
vector<vector<bool> >v(n,temp);
int dx[] = {0,0,1,-1,-1,-1,1,1};
int dy[] = {1,-1,0,0,-1,1,-1,1};
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
int cnt = 0;
for(int d=0;d<8;d++) {
int x = i+dx[d];
int y = j+dy[d];
if(x>=0 && x<n && y>=0 && y<m) {
cnt+=board[x][y];
}
}
int val = 0;
if(board[i][j] == 1) {
if(cnt == 2 || cnt == 3) {
val = 1;
}
} else {
if(cnt == 3) val = 1;
}
v[i][j] = val;
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
board[i][j] = v[i][j];
}
}
}
}; | true |
f8d88504af931ce6e30d39cbb12e200894867581 | C++ | wusiyan11/Flood-it | /Flood-it/floodit.cpp | UTF-8 | 1,292 | 3.078125 | 3 | [] | no_license | #include "game.h"
#include "textdisplay.h"
#include "cell.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include "PRNG.h"
using namespace std;
int seed;
void change_option(char * first, char * second, int &moves, int &size, int &seed) {
string option = string(first);
int num = atoi(second);
if (option == "-moves" && num >= 2) {
moves = num;
}
if (option == "-size" && num >= 1) {
size = atoi(second);
}
if (option == "-seed") {
seed = atoi(second);
}
}
int main (int argc, char * argv[]) {
istream * infile = &cin;
int size = 10, moves = 20;
seed = getpid();
switch (argc) {
case 7: {
change_option(argv[5],argv[6],moves,size,seed);
}
case 5: {
change_option(argv[3],argv[4],moves,size,seed);
}
case 3: {
change_option(argv[1],argv[2],moves,size,seed);
break;
}
default: {
//Usage Error
}
}
Game g(size,moves);
int move;
int movesleft = g.getTurns();
while (movesleft) {
g.print();
cout << movesleft << " moves left" << endl;
if (infile->eof()) {
break;
}
*infile >> move;
g.change(move);
if (g.isWon()) {
g.print();
movesleft = g.getTurns();
cout << movesleft << " moves left" << endl;
cout << "Won" << endl;
return 0;
}
movesleft = g.getTurns();
}
cout << "Lost" << endl;
}
| true |
5bcf77791b9b0ab5b6dc2f63a9eace7e16c12dae | C++ | diamante0018/tekno_uttv2 | /ultimateteknotool.v2/CWinAPIFileW.cpp | UTF-8 | 1,730 | 2.796875 | 3 | [] | no_license | #include "pch.h"
#include "CWinAPIFileW.h"
constexpr LARGE_INTEGER zero = { 0 };
CWinAPIFileW::CWinAPIFileW()
{
}
CWinAPIFileW::~CWinAPIFileW()
{
if (this->m_hFile != INVALID_HANDLE_VALUE)
{
::CloseHandle(this->m_hFile);
}
}
bool CWinAPIFileW::OpenForWriting(wchar_t* name)
{
this->Close();
this->m_hFile = CreateFileW(name, GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (this->m_hFile != INVALID_HANDLE_VALUE)
{
return true;
}
return false;
}
void CWinAPIFileW::WriteInAppend(const char* src, size_t len)
{
if (::SetFilePointerEx(this->m_hFile, zero, NULL, FILE_END))
/* If the function succeeds, the return value is nonzero. */
{
::WriteFile(this->m_hFile, src, len, &m_byteswriten, NULL);
}
}
bool CWinAPIFileW::OpenForReading(wchar_t* name)
{
this->Close();
this->m_hFile = CreateFileW(name, GENERIC_READ, 0, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (this->m_hFile != INVALID_HANDLE_VALUE)
{
return true;
}
return false;
}
void CWinAPIFileW::ReadFrom(char* dst, size_t len)
{
::ReadFile(this->m_hFile, dst, len, &m_bytesread, NULL);
}
void CWinAPIFileW::Truncate(wchar_t* name)
{
this->Close();
this->m_hFile = CreateFileW(name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
this->Close();
}
bool CWinAPIFileW::IsFileExist(wchar_t* name) const
{
HANDLE DummyBoi = INVALID_HANDLE_VALUE;
DummyBoi = CreateFileW(name, 0, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (DummyBoi != INVALID_HANDLE_VALUE)
{
::CloseHandle(DummyBoi);
return true;
}
return false;
}
void CWinAPIFileW::Close()
{
if (this->m_hFile != INVALID_HANDLE_VALUE)
{
::CloseHandle(this->m_hFile);
}
}
| true |
4eb5764063f0075ce003d74a632461467249524a | C++ | Botrix/Minimax | /C4Board.cpp | UTF-8 | 6,628 | 2.765625 | 3 | [] | no_license | #include <algorithm>
#include "../MyEngine/MainEngine/ResourceManager.h"
#include "../MyEngine/MainEngine/Random.h"
#include "C4Board.h"
C4Board::C4Board() {
}
C4Board::~C4Board() {
}
C4Board* C4Board::makeMove(int col) const {
C4Board* newBoard = new C4Board(*this);
for (int i = 5; i >= 0; i--) {
if (newBoard->m_cells[i][col] == EMPTY && inRange(col,0,6) && m_winner == EMPTY) {
newBoard->m_cells[i][col] = m_currPlayer;
newBoard->switchTurn();
newBoard->checkWinner();
return newBoard;
}
}
return newBoard;
}
Cell C4Board::getTurn() const {
if (m_winner != EMPTY || std::count(&m_cells[0][0], &m_cells[0][0]+42, EMPTY) == 0) {
return EMPTY;
} else {
return m_currPlayer;
}
}
Cell C4Board::checkWinner() {
auto checkDirection =
[&](int r, int c, int dr, int dc) {
if (!inRange(r+3*dr,0,5) || !inRange(c+3*dc,0,6)) {
return false;
}
for (int i = 1; i < 4; i++) {
if (m_cells[r][c] != m_cells[r+i*dr][c+i*dc]) {
return false;
}
}
return true;
};
m_winner = EMPTY;
for (int r = 0; r < 6; r++) {
for (int c = 0; c < 7; c++) {
if (m_cells[r][c] == EMPTY) {
continue;
} else if (checkDirection(r,c,0,1)) {
m_winner = m_cells[r][c];
return m_cells[r][c];
} else if (checkDirection(r,c,1,1)) {
m_winner = m_cells[r][c];
return m_cells[r][c];
} else if (checkDirection(r,c,1,0)) {
m_winner = m_cells[r][c];
return m_cells[r][c];
} else if (checkDirection(r,c,1,-1)) {
m_winner = m_cells[r][c];
return m_cells[r][c];
}
}
}
return EMPTY;
}
bool C4Board::isEmpty() const {
return (std::count(&m_cells[0][0], &m_cells[0][0]+42, EMPTY) == 42);
}
int C4Board::getClickedColumn(crvec2 mouse) const {
for (int i = 0; i < 7; i++) {
if (mouse.x >= -75+i*150/7 && mouse.x <= -75+(i+1)*150/7 && mouse.y >= -75 && mouse.y <= 75) {
return i;
}
}
return -1;
}
glm::vec4 C4Board::getNumRows() const {
auto checkDirection =
[&](int r, int c, int dr, int dc) {
for (int i = 1; i < 4; i++) {
if (m_cells[r][c] != m_cells[r+i*dr][c+i*dc] || !inRange(r+i*dr,0,5) || !inRange(c+i*dc,0,6)) {
return i;
}
}
return 4;
};
glm::vec4 pcounter(0), ccounter(0);
for (int r = 0; r < 6; r++) {
for (int c = 0; c < 7; c++) {
if (m_cells[r][c] == PLAYER) {
pcounter[checkDirection(r,c,0,1)-1]++;
pcounter[checkDirection(r,c,1,1)-1]++;
pcounter[checkDirection(r,c,1,0)-1]++;
pcounter[checkDirection(r,c,1,-1)-1]++;
} else if (m_cells[r][c] == COMPUTER) {
ccounter[checkDirection(r,c,0,1)-1]++;
ccounter[checkDirection(r,c,1,1)-1]++;
ccounter[checkDirection(r,c,1,0)-1]++;
ccounter[checkDirection(r,c,1,-1)-1]++;
}
}
}
return glm::vec4(ccounter[1],ccounter[2],pcounter[1],pcounter[2]);
}
void C4Board::switchTurn() {
m_currPlayer = (m_currPlayer == PLAYER) ? COMPUTER : PLAYER;
}
void C4Board::reset() {
m_currPlayer = nta::Random::randBool() ? PLAYER : COMPUTER;
m_winner = EMPTY;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
m_cells[i][j] = EMPTY;
}
}
}
void C4Board::drawCircs(nta::SpriteBatch& sBatch, nta::SpriteFont* font) const {
static int boarder = 1;
static float width = 150/7-2*boarder;
static float height = 25-2*boarder;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
glm::vec4 col(0);
if (m_cells[i][j] == PLAYER) {
col = PLAYER_COLOR;
} else if (m_cells[i][j] == COMPUTER) {
col = COMPUTER_COLOR;
}
font->drawText(sBatch, "O", glm::vec4(-75+boarder+j*150/7,75-boarder-25*i,width,height), col);
}
}
std::string text = (m_currPlayer == PLAYER) ? "Player's Turn" : "Computer's Turn";
glm::vec4 col = (m_currPlayer == PLAYER) ? PLAYER_COLOR : COMPUTER_COLOR;
if (m_winner == PLAYER) {
col = PLAYER_COLOR;
text = "Player won";
} else if (m_winner == COMPUTER) {
col = COMPUTER_COLOR;
text = "Computer won";
}
font->drawText(sBatch, text, glm::vec4(-80,98,160,21), col);
}
void C4Board::drawPrims(nta::PrimBatch& pBatch) const {
static GLuint id = nta::ResourceManager::getTexture("solid.png").id;
for (int i = 0; i < 5; i++) {
pBatch.addPrimitive({{glm::vec2(-75+150./7*(i+1),75)},{glm::vec2(-75+150./7*(i+1),-75)}},id);
pBatch.addPrimitive({{glm::vec2(-75,75-25*(i+1))},{glm::vec2(75,75-25*(i+1))}},id);
}
pBatch.addPrimitive({{glm::vec2(-75+150./7*6,75)},{glm::vec2(-75+150./7*6,-75)}},id);
pBatch.addPrimitive({{glm::vec2(-75,75)},{glm::vec2(-75,-75)}},id);
pBatch.addPrimitive({{glm::vec2(-75,-75)},{glm::vec2(75,-75)}},id);
pBatch.addPrimitive({{glm::vec2(75,-75)},{glm::vec2(75,75)}},id);
pBatch.addPrimitive({{glm::vec2(75,75)},{glm::vec2(-75,75)}},id);
}
MMNode* C4Board::generateMove(int move) {
return makeMove(move);
}
float C4Board::evaluate() const {
/**/
static float weights[] = {3,8};
switch(m_winner) {
case PLAYER: return -100;
case COMPUTER: return 100;
}
glm::vec4 rows = getNumRows();
return (weights[0]*rows[0] + weights[1]*rows[1])-((weights[0]+1)*rows[2] + (weights[1]+1)*rows[3]);
/**
float val = 0;
for (int r = 0; r < 6; r++) {
for (int c = 0; c < 7; c++) {
if (m_cells[r][c] == m_cells[r][6-c]) {
val++;
} else if (std::min<int>(m_cells[r][c],m_cells[r][6-c]) == (int)EMPTY){
val--;
} else {
val -= 10;
}
}
}
return val;
/**/
}
bool C4Board::same(MMNode* rhs) const {
C4Board* board = (C4Board*)rhs;
for (int r = 5; r >= 0; r--) {
for (int c = 0; c < 7; c++) {
if (m_cells[r][c] != board->m_cells[r][c]) {
return false;
}
}
}
return true;
}
int C4Board::getNumMoves() const {
return 7;
}
| true |
71d8f86ff8a4609fc9592b98dee108fe2a5582c7 | C++ | InochiTanaka/COMP_3512_Lab2 | /Stack/Stack/Stacktester.cpp | UTF-8 | 2,091 | 3.640625 | 4 | [] | no_license | #include "Stack.hpp"
void stackTest()
{
cout << "Test 1: Store data { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }" << endl;
int inputArray1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int numInput = sizeof(inputArray1) / sizeof(int);
testing(inputArray1, numInput);
cout << "Test 2: Store data { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }" << endl;
int inputArray2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
numInput = sizeof(inputArray2) / sizeof(int);
testing(inputArray2, numInput);
cout << "Test 3: Store data { 1 }" << endl;
int inputArray3[] = {1};
numInput = sizeof(inputArray3) / sizeof(int);
testing(inputArray3, numInput);
}
void testing(int inputArray[], int numInput)
{
cout << endl;
cout << "*********** Start test program ***********" << endl;
cout << endl;
cout << "Push content : " << endl;
int i = 0;
while (i < numInput && !full())
{
push(inputArray[i]);
cout << i+1 << " : ";
print();
i++;
}
if (i < numInput && full())
{
cout << endl;
cout << "The Stack had been overflow" << endl;
cout << endl;
cout << "**************** Test End ****************" << endl;
cout << endl;
cleanStack();
return;
}
if (i < numInput && empty())
{
cout << endl;
cout << "The Stack is nothing" << endl;
cout << endl;
cout << "**************** Test End ****************" << endl;
cout << endl;
cleanStack();
return;
}
cout << endl;
cout << endl;
checkState();
cout << "Pop 1 content : ";
pop();
print();
cout << endl;
cout << endl;
checkState();
if (!empty())
{
cout << "Current Top : ";
cout << top() << endl;
}
else
{
cout << "Current Top is not exist "<< endl;
}
cout << endl;
cout <<"**************** Test End ****************"<< endl;
cout << endl;
cleanStack();
}
void checkState()
{
cout << "Current state :";
if (full())
{
cout << "The Stack is Full" << endl;
}
else if (empty())
{
cout << "The Stack is Empty" << endl;
}
else
{
cout << "The Stack has space" << endl;
}
cout << endl;
cout << endl;
}
void cleanStack()
{
for (int i = 0; i < 10; i++)
{
pop();
}
} | true |
f5eb3c10959d7e8909b85d022f013e6314cd0c91 | C++ | philipwolfe/Samples | /WPF/Windows SDK WPF Samples/GraphicsMM_Shapes/ShapesProcedural/CPP/ShapesProcedural.cpp | UTF-8 | 10,373 | 3.140625 | 3 | [] | no_license | //ShapesProcedural.cpp file
using namespace System;
using namespace System::Windows;
using namespace System::Windows::Controls;
using namespace System::Windows::Media;
using namespace System::Windows::Shapes;
using namespace System::Threading;
namespace ShapesProcedural {
public ref class app : Application {
private:
Border^ myBorder;
Rectangle^ myRect;
Ellipse^ myEllipse;
Line^ myLine;
Path^ myPath;
Polygon^ myPolygon;
Polyline^ myPolyline;
Grid^ myGrid;
TextBlock^ myTextBlock;
ColumnDefinition^ myColDef1;
ColumnDefinition^ myColDef2;
RowDefinition^ myRowDef;
RowDefinition^ myRowDef1;
RowDefinition^ myRowDef2;
RowDefinition^ myRowDef3;
RowDefinition^ myRowDef4;
RowDefinition^ myRowDef5;
RowDefinition^ myRowDef6;
Window^ myWindow;
protected: virtual void OnStartup (StartupEventArgs^ e) override
{
Application::OnStartup(e);
CreateAndShowMainWindow();
};
private: void CreateAndShowMainWindow ()
{
// Create the application's main window
myWindow = gcnew Window();
// Add a Border
myBorder = gcnew Border();
myBorder->BorderBrush = Brushes::Black;
myBorder->BorderThickness = Thickness(2);
myBorder->Width = 400;
myBorder->Height = 600;
myBorder->Padding = Thickness(15);
myBorder->Background = Brushes::White;
// Create a Grid to host the Shapes
myGrid = gcnew Grid();
myGrid->Margin = Thickness(15);
myColDef1 = gcnew ColumnDefinition();
myColDef1->Width = GridLength(125);
myColDef2 = gcnew ColumnDefinition();
myColDef2->Width = GridLength(1, GridUnitType::Star);
myGrid->ColumnDefinitions->Add(myColDef1);
myGrid->ColumnDefinitions->Add(myColDef2);
myRowDef = gcnew RowDefinition();
myRowDef1 = gcnew RowDefinition();
myRowDef2 = gcnew RowDefinition();
myRowDef3 = gcnew RowDefinition();
myRowDef4 = gcnew RowDefinition();
myRowDef5 = gcnew RowDefinition();
myRowDef6 = gcnew RowDefinition();
myGrid->RowDefinitions->Add(myRowDef);
myGrid->RowDefinitions->Add(myRowDef1);
myGrid->RowDefinitions->Add(myRowDef2);
myGrid->RowDefinitions->Add(myRowDef3);
myGrid->RowDefinitions->Add(myRowDef4);
myGrid->RowDefinitions->Add(myRowDef5);
myGrid->RowDefinitions->Add(myRowDef6);
myTextBlock = gcnew TextBlock();
myTextBlock->FontSize = 20;
myTextBlock->Text = "WPF Shapes Gallery";
myTextBlock->HorizontalAlignment = HorizontalAlignment::Left;
myTextBlock->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock);
Grid::SetRow(myTextBlock, 0);
Grid::SetColumnSpan(myTextBlock, 2);
// Add a Rectangle Element
myRect = gcnew Rectangle();
myRect->Stroke = Brushes::Black;
myRect->Fill = Brushes::SkyBlue;
myRect->HorizontalAlignment = HorizontalAlignment::Left;
myRect->VerticalAlignment = VerticalAlignment::Center;
myRect->Height = 50;
myRect->Width = 50;
myGrid->Children->Add(myRect);
Grid::SetRow(myRect, 1);
Grid::SetColumn(myRect, 0);
TextBlock^ myTextBlock1 = gcnew TextBlock();
myTextBlock1->FontSize = 14;
myTextBlock1->Text = "A Rectangle Element";
myTextBlock1->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock1);
Grid::SetRow(myTextBlock1, 1);
Grid::SetColumn(myTextBlock1, 1);
// Add an Ellipse Element
myEllipse = gcnew Ellipse();
myEllipse->Stroke = Brushes::Black;
myEllipse->Fill = Brushes::DarkBlue;
myEllipse->HorizontalAlignment = HorizontalAlignment::Left;
myEllipse->VerticalAlignment = VerticalAlignment::Center;
myEllipse->Width = 50;
myEllipse->Height = 75;
myGrid->Children->Add(myEllipse);
Grid::SetRow(myEllipse, 2);
Grid::SetColumn(myEllipse, 0);
TextBlock^ myTextBlock2 = gcnew TextBlock();
myTextBlock2->FontSize = 14;
myTextBlock2->Text = "An Ellipse Element";
myTextBlock2->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock2);
Grid::SetRow(myTextBlock2, 2);
Grid::SetColumn(myTextBlock2, 1);
// Add a Line Element
myLine = gcnew Line();
myLine->Stroke = Brushes::LightSteelBlue;
myLine->X1 = 1;
myLine->X2 = 50;
myLine->Y1 = 1;
myLine->Y2 = 50;
myLine->HorizontalAlignment = HorizontalAlignment::Left;
myLine->VerticalAlignment = VerticalAlignment::Center;
myLine->StrokeThickness = 2;
myGrid->Children->Add(myLine);
Grid::SetRow(myLine, 3);
Grid::SetColumn(myLine, 0);
TextBlock^ myTextBlock3 = gcnew TextBlock();
myTextBlock3->FontSize = 14;
myTextBlock3->Text = "A Line Element";
myTextBlock3->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock3);
Grid::SetRow(myTextBlock3, 3);
Grid::SetColumn(myTextBlock3, 1);
//Add the Path Element
myPath = gcnew Path();
myPath->Stroke = Brushes::Black;
myPath->Fill = Brushes::MediumSlateBlue;
myPath->StrokeThickness = 4;
myPath->HorizontalAlignment = HorizontalAlignment::Left;
myPath->VerticalAlignment = VerticalAlignment::Center;
EllipseGeometry^ myEllipseGeometry = gcnew EllipseGeometry();
myEllipseGeometry->Center = Point(50, 50);
myEllipseGeometry->RadiusX = 25;
myEllipseGeometry->RadiusY = 25;
myPath->Data = myEllipseGeometry;
myGrid->Children->Add(myPath);
Grid::SetRow(myPath, 4);
Grid::SetColumn(myPath, 0);
TextBlock^ myTextBlock4 = gcnew TextBlock();
myTextBlock4->FontSize = 14;
myTextBlock4->Text = "A Path Element";
myTextBlock4->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock4);
Grid::SetRow(myTextBlock4, 4);
Grid::SetColumn(myTextBlock4, 1);
//Add the Polygon Element
myPolygon = gcnew Polygon();
myPolygon->Stroke = Brushes::Black;
myPolygon->Fill = Brushes::LightSeaGreen;
myPolygon->StrokeThickness = 2;
myPolygon->HorizontalAlignment = HorizontalAlignment::Left;
myPolygon->VerticalAlignment = VerticalAlignment::Center;
Point Point1 = Point(1, 50);
Point Point2 = Point(10, 80);
Point Point3 = Point(50, 50);
PointCollection^ myPointCollection = gcnew PointCollection();
myPointCollection->Add(Point1);
myPointCollection->Add(Point2);
myPointCollection->Add(Point3);
myPolygon->Points = myPointCollection;
myGrid->Children->Add(myPolygon);
Grid::SetRow(myPolygon, 5);
Grid::SetColumn(myPolygon, 0);
TextBlock^ myTextBlock5 = gcnew TextBlock();
myTextBlock5->Text = "A Polygon Element";
myTextBlock5->FontSize = 14;
myTextBlock5->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock5);
Grid::SetRow(myTextBlock5, 5);
Grid::SetColumn(myTextBlock5, 1);
// Add the Polyline Element
myPolyline = gcnew Polyline();
myPolyline->Stroke = Brushes::SlateGray;
myPolyline->StrokeThickness = 2;
myPolyline->FillRule = FillRule::EvenOdd;
Point Point4 = Point(1, 50);
Point Point5 = Point(10, 80);
Point Point6 = Point(20, 40);
PointCollection^ myPointCollection2 = gcnew PointCollection();
myPointCollection2->Add(Point4);
myPointCollection2->Add(Point5);
myPointCollection2->Add(Point6);
myPolyline->Points = myPointCollection2;
myGrid->Children->Add(myPolyline);
Grid::SetRow(myPolyline, 6);
Grid::SetColumn(myPolyline, 0);
TextBlock^ myTextBlock6 = gcnew TextBlock();
myTextBlock6->FontSize = 14;
myTextBlock6->Text = "A Polyline Element";
myTextBlock6->VerticalAlignment = VerticalAlignment::Center;
myGrid->Children->Add(myTextBlock6);
Grid::SetRow(myTextBlock6, 6);
Grid::SetColumn(myTextBlock6, 1);
// Add the Grid to the Window as Content and show the Window
myBorder->Child = myGrid;
myWindow->Content = myBorder;
myWindow->Background = Brushes::LightSlateGray;
myWindow->Title = "Shapes Sample";
myWindow->Show();
};
};
private ref class EntryClass {
public:
[System::STAThread()]
static void Main ()
{
ShapesProcedural::app^ app = gcnew ShapesProcedural::app();
app->Run();
};
};
}
//Entry Point:
[System::STAThreadAttribute()]
void main ()
{
return ShapesProcedural::EntryClass::Main();
}
| true |
62d10d86c0b1cfad1851923d89da65787b41ae02 | C++ | el-bart/TIGER | /shared/src/Parallel/Queue.t.cpp | UTF-8 | 1,846 | 3.1875 | 3 | [] | no_license | #include <tut/tut.hpp>
#include <thread>
#include "Parallel/Queue.hpp"
using namespace Parallel;
namespace
{
typedef Queue<std::string> StrQueue;
struct TestClass
{
StrQueue q_;
};
typedef tut::test_group<TestClass> factory;
typedef factory::object testObj;
factory tf("Parallel/Queue");
} // unnamed namespace
namespace tut
{
// test initial state
template<>
template<>
void testObj::test<1>(void)
{
ensure_equals("invalid initial size", q_.size(), 0);
ensure("initial state is not empty", q_.empty() );
}
// test addition of an element
template<>
template<>
void testObj::test<2>(void)
{
q_.push("doom");
ensure_equals("invalid element", q_.pop(), "doom");
}
// test waiting for element
template<>
template<>
void testObj::test<3>(void)
{
q_.push("doom");
ensure("wait() failed", q_.waitForElementUntil( std::chrono::steady_clock::now() + std::chrono::milliseconds(1) ) );
ensure_equals("invalid element", q_.pop(), "doom");
}
// test wait() timeout
template<>
template<>
void testObj::test<5>(void)
{
ensure("wait() didn't failed", !q_.waitForElementUntil( std::chrono::steady_clock::now() + std::chrono::milliseconds(1) ) );
}
namespace
{
struct ThreadJoiner
{
template<typename F>
ThreadJoiner(F f): th_( std::move(f) ) { }
~ThreadJoiner(void) { th_.join(); }
std::thread th_;
};
}
// test waiting while other thread adds elements
template<>
template<>
void testObj::test<6>(void)
{
constexpr size_t count = 420;
ThreadJoiner th( [&]{ for(size_t i=0; i<count; ++i) q_.push("hello there"); } );
for(size_t i=0; i<count; ++i)
{
ensure("wait() failed while waiting for element", q_.waitForElementUntil( std::chrono::steady_clock::now() + std::chrono::milliseconds(500) ) );
ensure_equals("invalid element received", q_.pop(), "hello there");
}
}
} // namespace tut
| true |
e2d1db0076460649cfbd27410a249e685c9add1c | C++ | jindongh/pyfarm | /other/oj/checker_orig.cc | UTF-8 | 1,428 | 2.640625 | 3 | [] | no_license | /**
ID: hankjin1
LANG: C++
TASK: checker
*/
//hint4: reduce half by rotate
//
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;
int N;
int found;
int pos[13];
bool used[13];//used rows
bool xadd[26];//used left-down to right-up
bool xsub[26];//used left-top to right-down
ifstream fin("checker.in");
ofstream fout("checker.out");
int hist[13];
void dfs(int x){
if(x==N){
if(found<3){
int i;
for(i=0;i<N-1;i++){
fout<<(1+pos[i])<<" ";
hist[i]=pos[i];
}
fout<<(1+pos[i])<<endl;
hist[i]=pos[i];
}
found++;
return ;
}
int i;
for(i=0;i<N;i++){
if(used[i])
continue;
if(xadd[x+i])
continue;
if(xsub[13+x-i])
continue;
used[i]=true;
xadd[x+i]=true;
xsub[13+x-i]=true;
pos[x]=i;
dfs(x+1);
used[i]=false;
xadd[x+i]=false;
xsub[13+x-i]=false;
}
}
int place(int n){
used[n]=true;
xadd[0+n]=true;
xsub[13+0-n]=true;
pos[0]=n;
dfs(1);
used[n]=false;
xadd[0+n]=false;
xsub[13+0-n]=false;
}
int main(){
fin>>N;
fill_n(used, 0, 13);
fill_n(xadd, 0, 26);
fill_n(xsub, 0, 26);
found = 0;
int i, top, sum;
for(i=0;i<N/2;i++){
place(i);
}
top = found;
if(N%2!=0)
place(i);
if(found<3){
for(i=0;i<N-1;i++){
fout<<(N-hist[i])<<" ";
}
fout<<(N-hist[i])<<endl;
}
sum = (found-top)+2*top;
fout<<sum<<endl;
return 0;
}
| true |
0259ef32ec6d67b7e2a9be6795cf6e3767cfd15c | C++ | Rockmen0113/ConsoleSnakePractice | /SnakeGame/ConsoleSetting.cpp | UTF-8 | 531 | 2.578125 | 3 | [] | no_license | #include "pch.h"
#include "ConsoleSetting.h"
HANDLE ConsoleSetting::hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
void ConsoleSetting::ShowCursor(bool visible)
{
CONSOLE_CURSOR_INFO cci = { sizeof(cci), visible };
SetConsoleCursorInfo(hStdOut, &cci);
}
void ConsoleSetting::SetColor(Color::ConsoleColor text, Color::ConsoleColor background)
{
SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
void ConsoleSetting::GotoXY(int X, int Y)
{
COORD coord = { X, Y };
SetConsoleCursorPosition(hStdOut, coord);
} | true |
733e75e8aa0b063cfa8bea20cbc9a16f672c31af | C++ | smilu97/hamtris | /common/server/player.cpp | UTF-8 | 1,341 | 2.734375 | 3 | [] | no_license | #include "player.h"
using namespace tetris;
TetrisPlayer::TetrisPlayer(PlayerId id, tcp::socket socket):
id(id),
socket (std::move(socket)) {
}
void TetrisPlayer::Start() {
ReadHeader();
}
void TetrisPlayer::Deliver(const char* buf, int len) {
socket.async_write_some(boost::asio::buffer(buf, len), [this](std::error_code err, std::size_t){
if (err) {
return;
}
return;
});
}
void TetrisPlayer::ReadMessage(int len, ReadHandler readHandler) {
socket.async_read_some(boost::asio::buffer(readBuffer, len), readHandler);
}
void TetrisPlayer::ReadHeader() {
ReadMessage(sizeof(HeaderMessage), [this](std::error_code err, std::size_t) {
if (err) {
return;
} else {
HeaderMessage * msg = (HeaderMessage*) readBuffer;
switch (msg->type) {
case MESSAGE_TETRIS:
ReadTetrisMessage();
break;
case MESSAGE_CREATE_ROOM:
CreateRoom();
break;
case MESSAGE_JOIN_ROOM:
ReadJoinRoomMessage();
break;
}
}
});
}
void TetrisPlayer::ReadTetrisMessage() {
}
void TetrisPlayer::ReadJoinRoomMessage() {
}
void TetrisPlayer::CreateRoom() {
}
| true |
3a82a496796bbd563f8c4fa5702d0e8863719523 | C++ | zhangwengame/LeetCode | /155.cpp | UTF-8 | 915 | 3.046875 | 3 | [] | no_license | class MinStack {
private:
long long minV;
stack<long long > sta;
public:
/** initialize your data structure here. */
MinStack() {
minV=0;
}
void push(int x) {
if (sta.empty()){
minV=x;
sta.push(0);
} else {
sta.push((long long)x-minV);
minV=min(minV,(long long)x);
}
}
void pop() {
if (sta.top()>=0)
sta.pop();
else {
minV=minV-sta.top();
sta.pop();
}
}
int top() {
if (sta.top()<0)
return minV;
else
return minV+sta.top();
}
int getMin() {
return minV;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/ | true |
0d0758ad8bd3ae4415e661dd34bea329b36ae61a | C++ | biancadragomir/school-work | /Faculty/TrenchCoatStoreQT/qt_lab/controller.cpp | UTF-8 | 1,896 | 2.984375 | 3 | [] | no_license | #include "controller.h"
#include <assert.h>
void Controller::set_basket(Basket * b)
{
this->basket = b;
}
//function used for adding a new coat via the controller
int Controller::controller_add(int size, const std::string color, int price, int quantity, const std::string photograph, int length)
{
Trench_coat c{ size, color, price, quantity, photograph, length };
this->validator.validate(c);
return this->repo.repo_add_coat(c);
}
//function used for deleting a coat
int Controller::controller_delete(int size, const std::string photograph)
{
return this->repo.repo_delete_coat(size, photograph);
}
int Controller::controller_update(int size, const std::string photograph, int new_quantity, int new_price)
{
return this->repo.repo_update_coat(size, photograph, new_quantity, new_price);
}
int Controller::c_add_to_basket(int size, const std::string color, int price, int quantity, const std::string photograph, int length)
{
Trench_coat c{ size, color, price, quantity, photograph, length };
this->basket->basket_add_coat(c);
this->basket->basket_add_to_price(c.get_price());
return 1;
}
int Controller::c_update_coat(int size, const std::string photograph, int new_quantity, int new_price)
{
return this->repo.repo_update_coat(size, photograph, new_quantity, new_price);
}
int Controller::c_update_basket_coat(int size, const std::string photograph, int new_quantity, int new_price)
{
this->basket->basket_update_coat(size, photograph, new_quantity, new_price);
return 1;
}
//int Controller::c_csv_add_to_basket(int size, const std::string color, int price, int quantity, const std::string photograph, int length)
//{
// Trench_coat c{ size, color, price, quantity, photograph, length };
//
// this->basket->basket_add_coat(c);
// this->basket->basket_add_to_price(c.get_price());
// return 1;
//}
//Basket * Controller::c_get_csv_basket()
//{
// return this->basket;
//} | true |
6a1986fa53a5a551501eb5b6ea95c3099768eaec | C++ | wolves3d/idea | /_Shared/Math/matrix.h | UTF-8 | 7,522 | 2.828125 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
class mat3
{
public:
float Determinant()
{
return ( pArray[0] * ( pArray[4] * pArray[8] - pArray[7] * pArray[5] )
- pArray[1] * ( pArray[3] * pArray[8] - pArray[6] * pArray[5] )
+ pArray[2] * ( pArray[3] * pArray[7] - pArray[6] * pArray[4] ) );
}
scalar pArray[ 9 ];
};
class mat4
{
public :
void Rotate( const quat & qRot );
inline void RotateX( const float fAngle )
{
mat4 mMult;
const float fSin = sinf( fAngle * TO_RADIAN ),
fCos = cosf( fAngle * TO_RADIAN );
mMult.m11 = 1; mMult.m12 = 0; mMult.m13 = 0; mMult.m14 = 0;
mMult.m21 = 0; mMult.m22 = fCos; mMult.m23 = fSin; mMult.m24 = 0;
mMult.m31 = 0; mMult.m32 = -fSin; mMult.m33 = fCos; mMult.m34 = 0;
mMult.m41 = 0; mMult.m42 = 0; mMult.m43 = 0; mMult.m44 = 1;
Mult( mMult );
}
inline void RotateY( const float fAngle )
{
mat4 mMult;
const float fSin = sinf( fAngle * TO_RADIAN ),
fCos = cosf( fAngle * TO_RADIAN );
mMult.m11 = fCos; mMult.m12 = 0; mMult.m13 = -fSin; mMult.m14 = 0;
mMult.m21 = 0; mMult.m22 = 1; mMult.m23 = 0; mMult.m24 = 0;
mMult.m31 = fSin; mMult.m32 = 0; mMult.m33 = fCos; mMult.m34 = 0;
mMult.m41 = 0; mMult.m42 = 0; mMult.m43 = 0; mMult.m44 = 1;
Mult( mMult );
}
inline void Mult( const mat4 & mMult )
{
mat4 mResult;
mResult.m11 = m11 * mMult.m11 + m12 * mMult.m21 + m13 * mMult.m31 + m14 * mMult.m41;
mResult.m12 = m11 * mMult.m12 + m12 * mMult.m22 + m13 * mMult.m32 + m14 * mMult.m42;
mResult.m13 = m11 * mMult.m13 + m12 * mMult.m23 + m13 * mMult.m33 + m14 * mMult.m43;
mResult.m14 = m11 * mMult.m14 + m12 * mMult.m24 + m13 * mMult.m34 + m14 * mMult.m44;
mResult.m21 = m21 * mMult.m11 + m22 * mMult.m21 + m23 * mMult.m31 + m24 * mMult.m41;
mResult.m22 = m21 * mMult.m12 + m22 * mMult.m22 + m23 * mMult.m32 + m24 * mMult.m42;
mResult.m23 = m21 * mMult.m13 + m22 * mMult.m23 + m23 * mMult.m33 + m24 * mMult.m43;
mResult.m24 = m21 * mMult.m14 + m22 * mMult.m24 + m23 * mMult.m34 + m24 * mMult.m44;
mResult.m31 = m31 * mMult.m11 + m32 * mMult.m21 + m33 * mMult.m31 + m34 * mMult.m41;
mResult.m32 = m31 * mMult.m12 + m32 * mMult.m22 + m33 * mMult.m32 + m34 * mMult.m42;
mResult.m33 = m31 * mMult.m13 + m32 * mMult.m23 + m33 * mMult.m33 + m34 * mMult.m43;
mResult.m34 = m31 * mMult.m14 + m32 * mMult.m24 + m33 * mMult.m34 + m34 * mMult.m44;
mResult.m41 = m41 * mMult.m11 + m42 * mMult.m21 + m43 * mMult.m31 + m44 * mMult.m41;
mResult.m42 = m41 * mMult.m12 + m42 * mMult.m22 + m43 * mMult.m32 + m44 * mMult.m42;
mResult.m43 = m41 * mMult.m13 + m42 * mMult.m23 + m43 * mMult.m33 + m44 * mMult.m43;
mResult.m44 = m41 * mMult.m14 + m42 * mMult.m24 + m43 * mMult.m34 + m44 * mMult.m44;
(*this) = mResult;
}
inline void AbsTranslate( vec3 vOffset )
{
vOffset.Multiply( *this );
m41 = vOffset.x;
m42 = vOffset.y;
m43 = vOffset.z;
}
inline void Scale( float fScale )
{
m11 *= fScale;
m12 *= fScale;
m13 *= fScale;
m21 *= fScale;
m22 *= fScale;
m23 *= fScale;
m31 *= fScale;
m32 *= fScale;
m33 *= fScale;
}
inline void Scale( const vec3 & vScale )
{
m11 *= vScale.x;
m12 *= vScale.x;
m13 *= vScale.x;
m21 *= vScale.y;
m22 *= vScale.y;
m23 *= vScale.y;
m31 *= vScale.z;
m32 *= vScale.z;
m33 *= vScale.z;
}
inline void Translate( vec3 vOffset )
{
mat4 mTrans;
mTrans.Identity();
mTrans.m41 = vOffset.x;
mTrans.m42 = vOffset.y;
mTrans.m43 = vOffset.z;
Mult( mTrans );
}
inline void Identity()
{
m11 = m22 = m33 = m44 = 1.0f;
m12 = m13 = m14 =
m21 = m23 = m24 =
m31 = m32 = m34 =
m41 = m42 = m43 = 0;
}
void m4_submat( mat4 & mr, mat3 & mb, int i, int j )
{
int ti, tj, idst, jdst;
for ( ti = 0; ti < 4; ti++ )
{
if ( ti < i )
{
idst = ti;
}
else
{
if ( ti > i )
{
idst = ti-1;
}
}
for ( tj = 0; tj < 4; tj++ )
{
if ( tj < j )
{
jdst = tj;
}
else
{
if ( tj > j )
{
jdst = tj-1;
}
}
if ( ti != i && tj != j )
{
mb.pArray[idst*3 + jdst] = mr.pArray[ti*4 + tj ];
}
}
}
}
// determinant
float m4_det( mat4 & mr )
{
float det, result = 0, i = 1;
mat3 msub3;
int n;
for ( n = 0; n < 4; n++, i *= -1 )
{
m4_submat( mr, msub3, 0, n );
det = msub3.Determinant();
result += mr.pArray[n] * det * i;
}
return( result );
}
bool Inverse()
{
mat4 mr;
mat4 & ma = (*this);
float mdet = m4_det( ma );
mat3 mtemp;
int i, j, sign;
if ( fabs( mdet ) < 0.0005 )
return false;
mdet = 1.f / mdet; // ( to replace dev by mul )
for ( i = 0; i < 4; i++ )
{
for ( j = 0; j < 4; j++ )
{
sign = 1 - ( (i +j) % 2 ) * 2;
m4_submat( ma, mtemp, i, j );
mr.pArray[i+j*4] = ( mtemp.Determinant() * sign ) * mdet;
}
}
for ( i = 0; i < 16; ++i )
pArray[ i ] = mr.pArray[ i ];
return true;
}
inline void Ortho( scalar fLeft, scalar fRight, scalar fTop, scalar fBottom, scalar fZNear, scalar fZFar )
{
m11 = 2 / ( fRight - fLeft );
m12 = 0;
m13 = 0;
m14 = 0;//- ( fRight + fLeft ) / ( fRight - fLeft );
m21 = 0;
m22 = 2 / ( fTop - fBottom );
m23 = 0;
m24 = 0;//- ( fTop + fBottom ) / ( fTop - fBottom );
m31 = 0;
m32 = 0;
m33 = - 2 / ( fZFar - fZNear );
m34 = 0;//- ( fZFar + fZNear ) / ( fZFar - fZNear );
m41 = -1;
m42 = -1;
m43 = 0;
m44 = 1;
/*
m11 = 2 / ( fRight - fLeft );
m12 = 0;
m13 = 0;
m14 = - ( fRight + fLeft ) / ( fRight - fLeft );
m21 = 0;
m22 = 2 / ( fTop - fBottom );
m23 = 0;
m24 = - ( fTop + fBottom ) / ( fTop - fBottom );
m31 = 0;
m32 = 0;
m33 = - 2 / ( fZFar - fZNear );
m34 = - ( fZFar + fZNear ) / ( fZFar - fZNear );
m41 = 0;//-1;
m42 = 0;//-1;
m43 = 0;
m44 = 1;*/
}
inline void SetProjection( scalar fFOV, scalar fAspect, scalar fZnear, scalar fZfar )
{
fFOV /= 180;
fFOV *= 3.14159265358979323846f;
m11 = ( 1.f / tan( fFOV / 2.f ) ) / fAspect;
m12 = 0;
m13 = 0;
m14 = 0;
m21 = 0;
m22 = 1.f / tan( ( fFOV ) / 2.f );
m23 = 0;
m24 = 0;
m31 = 0;
m32 = 0;
m33 = fZfar / ( fZnear - fZfar );
m34 = -1;
m41 = 0;
m42 = 0;
m43 = fZnear * fZfar / ( fZnear - fZfar );
m44 = 0;
}
/*void Transpose()
{
for ( uint i = 0; i < 4; ++i )
{
for ( uint j = 0; j < 4; ++j )
{
if ( i != j )
{
scalar temp = pArray[ i * 4 + j ];
pArray[ i * 4 + j ] = pArray[ j * 4 + i ];
pArray[ j * 4 + i ] = temp;
}
}
}
}*/
union
{
struct
{
scalar m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44;
};
struct
{
vec4 vRow0, vRow1, vRow2, vRow3;
};
struct
{
vec4 pRows[4];
};
scalar pArray[ 16 ];
};
static mat4 mIdentity;
};
//////////////////////////////////////////////////////////////////////////////// | true |
e957b0fa2e63eae614aa190e38406780c60b6720 | C++ | royredman4/SI-Sessions | /CPSC-121/Inheritance-Polymorphism/Rv.cpp | UTF-8 | 1,186 | 2.90625 | 3 | [] | no_license | // Created by Roy Redman IV
#include "Rv.h"
#include <iostream>
#include <string>
using namespace std;
Rv::Rv():Cars() {
bathroomCount = seatCount = bedCount = hasStove = 0;
}
Rv::Rv(double mpppg, string clr, bool tm, int trSz, int bc, int sc, int bedc, bool hStove) : Cars(mpppg, clr, tm, trSz) {
bathroomCount = bc;
seatCount = sc;
bedCount = bedc;
hasStove = hStove;
}
void Rv::SetbathroomCount(int bc) {
bathroomCount = bc;
}
void Rv::SetseatCount(int sc) {
seatCount = sc;
}
void Rv::SetbedCount(int bedc) {
bedCount = bedc;
}
void Rv::SethasStove(bool hStove) {
hasStove = hStove;
}
int Rv::GetbathroomCount() {
return bathroomCount;
}
int Rv::GetseatCount() {
return seatCount;
}
int Rv::GetbedCount() {
return bedCount;
}
bool Rv::GethasStove() {
return hasStove;
}
void Rv::print() {
Cars::print();
cout << "Bathroom Count is: " << GetbathroomCount() << " bathrooms" << endl;
cout << "Seat Count is: " << GetseatCount() << " seats" << endl;
cout << "Bed Count is: " << GetbedCount() << " beds" << endl;
string value;
if (GethasStove())
value = "true";
else
value = "false";
cout << "Has stove is: " << value << endl;
}
| true |
388f811f75a5eb316ed43a41768019bcc74619c5 | C++ | Alfeim/njuee_LeetCode_Solutions | /Cpp/Submit Records/491. Increasing Subsequences.cpp | UTF-8 | 1,009 | 3.140625 | 3 | [] | no_license | /********************************************
作者:Alfeim
题目:递增子序列
时间消耗:320ms
解题思路:dfs
********************************************/
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> findSubsequences(vector<int>& nums) {
int n = nums.size();
vector<int> tmp;
dfs(nums,0,n,tmp);
return res;
}
void dfs(vector<int> nums,int pos,int len,vector<int> &tmp){
if(pos >= len)
return;
unordered_set<int> record;
for(int i = pos; i < len ; ++i){
if(record.count(nums[i]) > 0)
continue;
if(tmp.empty() || nums[i] >= tmp.back()){
record.insert(nums[i]);
tmp.push_back(nums[i]);
if(tmp.size() >= 2) res.push_back(tmp);
dfs(nums,i + 1, len , tmp);
tmp.pop_back();
}
}
return;
}
};
| true |
b5daefd9a65b4f16404ce4da95ab9099d4e8e36d | C++ | ryanulep/cs010_lab03 | /lab3.cpp | UTF-8 | 1,551 | 3.65625 | 4 | [] | no_license | // =============== BEGIN ASSESSMENT HEADER ================
/// @file lab3.cpp
/// @brief Lab 3
///
/// @author Ryan Ulep [rulep001@ucr.edu]
/// @date April 13, 2015
// ================== END ASSESSMENT HEADER ===============
#include <iostream>
using namespace std;
int main()
{
double purchasePrice = 0.0;
double amountPaid = 0.0;
double changeAmount = 0;
int numPennies = 0;
int numNickels = 0;
int numDimes = 0;
int numQuarters = 0;
int numDollars = 0;
// Ask for purchase price and amount tendered
cout << "Enter purchase amount: ";
cin >> purchasePrice;
cout << endl;
cout << "Enter amount received: ";
cin >> amountPaid;
cout << endl;
// Calculate change value
changeAmount = amountPaid - purchasePrice;
numPennies = static_cast<int>(changeAmount * 100 + 0.5);
// Use integer division to calculate the number of each denomination
numDollars = numPennies / 100;
numPennies = numPennies % 100;
numQuarters = numPennies / 25;
numPennies = numPennies % 25;
numDimes = numPennies / 10;
numPennies = numPennies % 10;
numNickels = numPennies / 5;
numPennies = numPennies % 5;
// Output all values to screen
cout << "Total Change: $" << changeAmount << endl;
cout << endl;
cout << "dollars " << numDollars << endl;
cout << "quarters " << numQuarters << endl;
cout << "dimes " << numDimes << endl;
cout << "nickels " << numNickels << endl;
cout << "pennies " << numPennies << endl;
return 0;
}
| true |
561ac3c528afff45f12f6dba262b1d6067feeb0d | C++ | fsatka/msu_cpp_spring_2018 | /homework/Sokolova/03/Items.h | UTF-8 | 2,328 | 3.671875 | 4 | [
"MIT"
] | permissive | /**
@file
@brief Header file with item classes declaration.
File contains hierarchy of buyable items in the game.
*/
/**
* @brief Interface of buyable items.
* Can be bought.
*/
class Buyable {
public:
virtual void beBought();
};
/**
* @brief Base class of all items.
* Item has a unique id.
* Every item can be bought so has some cost.
* Item can be worn out and can be renewed.
* Item can be upgraded to new level.
*
* Must implement beBought() method.
*/
class Item: public Buyable {
int id;
int cost;
int state;
int level;
int power;
public:
void renew();
void upgrade();
};
/**
* @brief Interface of attacking items.
*
*/
class Attacker {
public:
virtual void attack(int);
};
/**
* @brief Base class of weapons.
* Every weapon has a list of actions that can be done with it.
* Weapon is attacker.
*/
class Weapon: public Item, public Attacker {
int actions[];
public:
void attack(int action);
};
/**
* @brief Bow attacks with arrows.
* Available actions: shoot, beat with arc.
* Main advantage: can be used from far of enemy.
* Upgrade: increase number of arrows that can be used in a row.
*/
class Bow: public Weapon {
int arrows;
};
/**
* @brief Shovel attacks with blade.
* Available actions: cut with blade, beat with handle.
* Main advantage: can be used suddenly.
* Upgrade: increase in weight and blade sharpening.
*/
class Shovel: public Weapon {
int weight;
int sharpness;
};
/**
* @brief Sword attacks with blade.
* Available actions: several special methods.
* Main advantage: diversity of actions.
* Upgrade: longen, sharpen.
*/
class Sword: public Weapon {
};
class Defender {
public:
virtual void defend(int);
};
/**
* @brief Base class of armor.
* Main armor function is to defend.
* Power defines the power of attack it can repel.
*/
class Armor: public Item {
int defences[];
public:
void defend(int defence);
};
/**
* @brief Hauberk can defend of shovel and somehow of arrows but cannot defend of sword.
*/
class Hauberk: public Armor {
};
/**
* @brief Lats can defend of everything exept beats with heavy stuff.
*/
class Lats: public Armor {
};
/**
* @brief Basin can defend of everything in one-to-one fight but is useless in far distance.
*/
class Basin: public Armor {
};
| true |
8a0addf9eb12040a9d4fc7e7dbb69fd666936945 | C++ | rayfill/cpplib | /tests/MPITest.cpp | UTF-8 | 14,563 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include <math/MPI.hpp>
#include <math/MersenneTwister.hpp>
class MPITest : public CppUnit::TestFixture
{
private:
CPPUNIT_TEST_SUITE(MPITest);
CPPUNIT_TEST(notEqualOpTest);
CPPUNIT_TEST(multiplyOpTest);
CPPUNIT_TEST(plusOpTest);
CPPUNIT_TEST(minusOpTest);
CPPUNIT_TEST(divideOpTest);
CPPUNIT_TEST(lessThanOpTest);
CPPUNIT_TEST(lessOrEqualOpTest);
CPPUNIT_TEST(equalOpTest);
CPPUNIT_TEST(equivalenceOpTest);
CPPUNIT_TEST(graterThanOpTest);
CPPUNIT_TEST(graterEqualOpTest);
CPPUNIT_TEST(constructerTest);
CPPUNIT_TEST(adjustTest);
CPPUNIT_TEST(divideTest);
CPPUNIT_TEST(bitLengthTest);
CPPUNIT_TEST(MaxColumnTest);
CPPUNIT_TEST(toStringTest);
CPPUNIT_TEST(makeNumberTest);
CPPUNIT_TEST(shiftTest);
CPPUNIT_TEST(fromConverterTest);
CPPUNIT_TEST(toConverterTest);
CPPUNIT_TEST(montgomeryTest);
CPPUNIT_TEST(unitBaseModulusTest);
CPPUNIT_TEST_SUITE_END();
public:
void unitBaseModulusTest()
{
MPInteger a(
"cb785082c998a3dbaaae00ca9f5f80af77765a466ba9976d60cb8af8"
"900c146f9212a62c1ce20305ec5ed6f32041d23e68e5d4ca278881d1"
"6bac0e28728044064c210d7b0e1a04d637c4f917b08877001c7b5038"
"55912363442ed8bfbe7b962a6af48c66d981e5d4985a7dde976d8f9c"
"3c0c0e2ab57106f170a690039880d01b");
MPInteger b("efdc");
CPPUNIT_ASSERT((a % b) == MPInteger(a.modulus(0xefdc)));
}
void montgomeryTest()
{
MPInteger a(7U);
MPInteger e(10U);
MPInteger n(13U);
a.montgomeryModulusExponential(e, n);
CPPUNIT_ASSERT_MESSAGE(a.toString(), a.toString() == "4");
}
void fromConverterTest()
{
std::vector<unsigned char> bigendianVector;
bigendianVector.push_back(0x80);
bigendianVector.push_back(0);
bigendianVector.push_back(0);
bigendianVector.push_back(0x01);
CPPUNIT_ASSERT(bigendianVector[0] == 0x80);
CPPUNIT_ASSERT(bigendianVector[1] == 0);
CPPUNIT_ASSERT(bigendianVector[2] == 0);
CPPUNIT_ASSERT(bigendianVector[3] == 0x01);
MPInteger a;
a.fromBigEndianMemory(bigendianVector);
CPPUNIT_ASSERT_MESSAGE(a.toString(), a.toString() == "80000001");
}
void toConverterTest()
{
MPInteger a("80000001");
CPPUNIT_ASSERT(a.getMaxColumn() == 1);
std::vector<unsigned char> result = a.toBigEndianMemory();
CPPUNIT_ASSERT(result.size() == 4);
CPPUNIT_ASSERT(result[0] == 0x80);
CPPUNIT_ASSERT(result[1] == 0);
CPPUNIT_ASSERT(result[2] == 0);
CPPUNIT_ASSERT(result[3] == 0x01);
MPInteger b("100080000001");
CPPUNIT_ASSERT(b.getMaxColumn() == 2);
result = b.toBigEndianMemory();
CPPUNIT_ASSERT(result.size() == 8);
CPPUNIT_ASSERT(result[0] == 0);
CPPUNIT_ASSERT(result[1] == 0);
CPPUNIT_ASSERT(result[2] == 0x10);
CPPUNIT_ASSERT(result[3] == 0);
CPPUNIT_ASSERT(result[4] == 0x80);
CPPUNIT_ASSERT(result[5] == 0);
CPPUNIT_ASSERT(result[6] == 0);
CPPUNIT_ASSERT(result[7] == 0x01);
}
void notEqualOpTest()
{
MPInteger a;
for (int index = 0; index < 100; ++index)
{
a.value.push_back(index);
}
MPInteger b;
for (int index = 0; index < 100; ++index)
{
b.value.push_back(a.value[index] ^ 0xffff);
}
b.value.push_back(1);
CPPUNIT_ASSERT(!(a != a));
CPPUNIT_ASSERT(a != b);
}
void equalOpTest()
{
MPInteger a;
for (int index = 0; index < 100; ++index)
{
a.value.push_back(index);
}
MPInteger b;
for (int index = 0; index < 100; ++index)
{
b.value.push_back(a.value[index] ^ 0xffff);
}
CPPUNIT_ASSERT(a == a);
CPPUNIT_ASSERT(!(a == b));
b = a;
a.value.push_back(0);
CPPUNIT_ASSERT(a == b);
}
void multiplyOpTest()
{
MPInteger a(0xffffU);
MPInteger b(0xffffffffU);
MPInteger result(a);
result *= b;
result.adjust();
CPPUNIT_ASSERT_MESSAGE(result.toString(), result.toString() == "fffeffff0001");
result = a * MPInteger(0U);
result.adjust();
CPPUNIT_ASSERT(result.toString() == "0");
a = MPInteger("e69b42ac4aeaffa8904c554f5d7d3bd9b8181cd42eea336cad912faf1ac6d253cda309447c8cca6e10757dac6486a725f7e08fc18042320b01033fb9594415fd51de3d24e65104e4b79575f41bce66b5e7dd8e810d55d0fd23c5d34dac9c50423616e89f8d43b3f2d10bdd84930d40ceda2a1ebb4db651a1031af52e18b9deb0640bf47a000a1c2858a3680fd02d84e13fead399ff8deef3779ead793191f6269039f9a282a7bb53507681129ee6653ae8501ef2700a8586374161fa58553278249dfb9efedf3535f56b3050b4480a17cc987d535703c94e1a1218e208475b3e0e63c32b3c235e01f6152727a72e8aceefb72e59cf1a853fe3c70ed7cf81acf1faec1c21911db5da8a1b1f45a66374b8948dc654a4eb22fd1dbc6f913f30e356122a7ab8b253e502f24d11bbf3f08bdec720760cd881c0e202d912d422a76b395c36d7b7040220ee23d559797ef37f05a5c8635b02cff5a2797448ebcc663d3e84f33ba2e2fd32d82528d40e88daa1598f3dfaf0eb797200c92b82a52d0f9930ee875aff3624d93f63d4afca6c3d8e1446bf684c6eaff4663c61392c127414aa5e27bdf46896087637bf84d43bb3625028f54f36e5da4f8659e047da5f2c8607d9c250959963c4e7b4cdd72964abda2c6ca4a0e08aeb9598dce98914dfeb0a1f405e89b2500dfcff08ed88cf1112aeb42407a57582d111e1e917d5898dbf6130");
b = MPInteger("9672f2e5cb4a522b4cb0edaf7d35667cd357fd23603f1f64d24fa4c1a1a5ec0bdc57fbfca6963d63f150493503e92b64e4b49e4e53ab24c63838ab0a94343c99a5d40f226099dea546604772accc74b054d63d5c13f1d456ba4548fbf0301e486092f4572ca1d876c3ef72400f13c9e1b7003995477e75f147b66659bcab6ae2edfb0079d344ade7d3f03406f210e2204a0f898027bd9739e0c59814afb69e0aaa9843ee08b48156c8946514150255689368e64879197a6c366b1747e5fc860923b5ea2578b174c255dab05ca7e54e0a8be367e72119bebf102196473f0b32dea9a611d06072480163a81db4e7f95462ff369647b9f701626c3f17f2e6e90c83bc4454dd408e605dea3fd7cbeeaf947c2bfd3b316f7b282a8c97afcec55ceeda70c0c2f0453bf16ab7ebd1208c52bc390353e201ba8f2ec63bf68f8a9256f92fa4404049402dd1362aafda20de2a13252c8cd0bd493c312140946fcb612bb00708eeea04807d038151a74a7aaabc507a96a4dfb61ea50fc948cc6105dc0fb9e0a338a27445f65c6b0b67c78864ae0a4156c688d9fd3aff32e5a8f3701e24cb2c32b2455c23065243f84da63ca869020a5fd7e6947104ce310f875ea01e7dc1ecd91af6916e6ca5991f8d57ad08e6e12a5128c0a82cbadd4bf643d9f86d31e95a89f73d115f909dd92f5c18fb64346b7a9a74383b20b9c7d34373c77e48d620");
CPPUNIT_ASSERT(a * b > a);
}
void plusOpTest()
{
MPInteger a("ffffffffffffffffffffffffffffffff");
MPInteger b("1");
MPInteger result = a + b;
result.adjust();
CPPUNIT_ASSERT_MESSAGE(result.toString(),
result.toString() ==
"100000000000000000000000000000000");
result = b + a;
result.adjust();
CPPUNIT_ASSERT_MESSAGE(
result.toString().c_str(),
result.toString() ==
"100000000000000000000000000000000");
result = a + MPInteger(0U);
result.adjust();
CPPUNIT_ASSERT(result.toString() ==
"ffffffffffffffffffffffffffffffff");
result = MPInteger(0U) + a;
result.adjust();
CPPUNIT_ASSERT_MESSAGE(
result.toString().c_str(),
result.toString() ==
"ffffffffffffffffffffffffffffffff");
result = MPInteger(0U) + MPInteger(0U);
result.adjust();
CPPUNIT_ASSERT(result.toString() ==
"0");
MPInteger c = a.getNegateValue();
result = a + c;
CPPUNIT_ASSERT(result.isZero());
result = b + c;
CPPUNIT_ASSERT_MESSAGE(result.toString(),
result.toString() ==
"-fffffffffffffffffffffffffffffffe");
result = c + b.negate();
CPPUNIT_ASSERT_MESSAGE(result.toString(),
result.toString() ==
"-100000000000000000000000000000000");
result = b + c.negate();
CPPUNIT_ASSERT_MESSAGE(result.toString(),
result.toString() ==
"fffffffffffffffffffffffffffffffe");
result = a + b.getNegateValue();
CPPUNIT_ASSERT_MESSAGE(result.toString(),
result.toString() ==
"100000000000000000000000000000000");
}
void minusOpTest()
{
MPInteger a("100000000000000000000");
MPInteger b("1");
MPInteger result = a - b;
result.adjust();
CPPUNIT_ASSERT(result.toString() ==
"ffffffffffffffffffff");
result = result - MPInteger(0U);
result.adjust();
CPPUNIT_ASSERT(result.toString() ==
"ffffffffffffffffffff");
CPPUNIT_ASSERT(
(MPInteger(0U) - result).toString() ==
"-ffffffffffffffffffff");
result = result - result;
result.adjust();
CPPUNIT_ASSERT(result.toString() ==
"0");
result = result - result;
result.adjust();
CPPUNIT_ASSERT(result.toString() == "0");
a = MPInteger(1U);
b = MPInteger("ffffffff");
MPInteger c = b.getNegateValue();
CPPUNIT_ASSERT((a-b).toString() == "-fffffffe");
CPPUNIT_ASSERT((b-a).toString() == "fffffffe");
CPPUNIT_ASSERT((a-c).toString() == "100000000");
CPPUNIT_ASSERT((a.getNegateValue() - b).adjust().toString() ==
"-100000000");
CPPUNIT_ASSERT((a.getNegateValue() - c).toString() == "fffffffe");
a = MPInteger(1U);
CPPUNIT_ASSERT((--a).toString() == "0");
}
void divideOpTest()
{
PRNGen random;
random.initialize(1234);
std::vector<MPInteger::BaseUnit> val;
const int length = 128;
for (int count = 0; count < length * 3; ++count)
val.push_back(static_cast<MPInteger::BaseUnit>(random.getNumber()));
MPInteger a(&val[0], &val[length*1]);
MPInteger b(&val[length*1], &val[length*2]);
MPInteger c(&val[length*2], &val[length*3]);
CPPUNIT_ASSERT(a != b);
CPPUNIT_ASSERT(b != c);
CPPUNIT_ASSERT(c != a);
MPInteger modulasTarget = a * b + c;
MPInteger result = modulasTarget / b;
MPInteger modResult = modulasTarget % b;
CPPUNIT_ASSERT(modulasTarget == (result * b + modResult));
}
void lessThanOpTest()
{
MPInteger a(1U);
MPInteger b(123456U);
MPInteger c("ffffffffffff");
MPInteger d;
CPPUNIT_ASSERT(a < b);
CPPUNIT_ASSERT(!(a < a));
CPPUNIT_ASSERT(!(b < a));
CPPUNIT_ASSERT(a < c);
CPPUNIT_ASSERT(b < c);
CPPUNIT_ASSERT(!(d < d));
CPPUNIT_ASSERT(d < a);
CPPUNIT_ASSERT(!(a < d));
}
void lessOrEqualOpTest()
{
MPInteger a(1U);
MPInteger b(123456U);
MPInteger c("ffffffffffff");
MPInteger d;
CPPUNIT_ASSERT(a <= b);
CPPUNIT_ASSERT(a <= a);
CPPUNIT_ASSERT(!(b <= a));
CPPUNIT_ASSERT(a <= c);
CPPUNIT_ASSERT(b <= c);
CPPUNIT_ASSERT(d <= d);
CPPUNIT_ASSERT(d <= a);
CPPUNIT_ASSERT(!(a <= d));
}
void equivalenceOpTest()
{
MPInteger a(1U);
MPInteger b(123456U);
MPInteger c("ffffffffffff");
MPInteger d;
CPPUNIT_ASSERT(a == a);
CPPUNIT_ASSERT(b == b);
CPPUNIT_ASSERT(c == c);
CPPUNIT_ASSERT(d == d);
CPPUNIT_ASSERT(!(a == b));
CPPUNIT_ASSERT(!(a == d));
CPPUNIT_ASSERT(!(c == d));
}
void graterThanOpTest()
{
MPInteger a(1U);
MPInteger b(123456U);
MPInteger c("ffffffffffff");
MPInteger d;
CPPUNIT_ASSERT(!(a > b));
CPPUNIT_ASSERT(!(a > a));
CPPUNIT_ASSERT(b > a);
CPPUNIT_ASSERT(!(a > c));
CPPUNIT_ASSERT(!(b > c));
CPPUNIT_ASSERT(!(d > d));
CPPUNIT_ASSERT(!(d > a));
CPPUNIT_ASSERT(a > d);
}
void graterEqualOpTest()
{
MPInteger a(1U);
MPInteger b(123456U);
MPInteger c("ffffffffffff");
MPInteger d;
CPPUNIT_ASSERT(!(a >= b));
CPPUNIT_ASSERT(a >= a);
CPPUNIT_ASSERT(b >= a);
CPPUNIT_ASSERT(!(a >= c));
CPPUNIT_ASSERT(!(b >= c));
CPPUNIT_ASSERT(d >= d);
CPPUNIT_ASSERT(!(d >= a));
CPPUNIT_ASSERT(a >= d);
}
void constructerTest()
{
MPInteger a;
CPPUNIT_ASSERT(a.value.size() == 0);
MPInteger b(12345U);
CPPUNIT_ASSERT(b.value.size() == 1 &&
b.value[0] == 12345);
b.adjust();
CPPUNIT_ASSERT(b.value.size() == 1);
MPInteger c(1, 15);
for (int index = 0; index < 15; ++index)
CPPUNIT_ASSERT(c.value[index] == 1);
MPInteger::BaseUnit temp[] = {1, 2, 3, 4, 5, 6, 7, 7};
MPInteger d(temp, temp + 7);
for (unsigned int index = 0;
index < 7;
++index)
CPPUNIT_ASSERT(d.value[index] == index + 1);
MPInteger e("1b3f22fe00b1");
CPPUNIT_ASSERT(e.value[1] == 0x1b3f);
CPPUNIT_ASSERT(e.value[0] == 0x22fe00b1);
CPPUNIT_ASSERT(e.isMinusSign == false);
MPInteger f(e);
CPPUNIT_ASSERT(f.value[1] == 0x1b3f);
CPPUNIT_ASSERT(f.value[0] == 0x22fe00b1);
CPPUNIT_ASSERT(f.isMinusSign == false);
MPInteger g("-1b3f22fe00b1");
CPPUNIT_ASSERT(g.value[1] == 0x1b3f);
CPPUNIT_ASSERT(g.value[0] == 0x22fe00b1);
CPPUNIT_ASSERT(g.isMinusSign == true);
MPInteger h("-1b3");
CPPUNIT_ASSERT(h.value[0] == 0x1b3);
CPPUNIT_ASSERT(h.isMinusSign == true);
CPPUNIT_ASSERT_THROW(MPInteger(""), TokenParseException);
}
void adjustTest()
{
MPInteger a(0, 20);
a.value[0] = 1;
a.adjust();
CPPUNIT_ASSERT(a.value.size() == 1);
}
void divideTest()
{
MPInteger modulo;
MPInteger modulas("ffffffff");
MPInteger modulasZero(0U);
MPInteger a("ffffffffffff");
MPInteger b("12345678");
MPInteger c(0U);
CPPUNIT_ASSERT_THROW(c.divide(modulasZero, modulo),
ZeroDivideException);
MPInteger result = a.divide(modulas, modulo);
CPPUNIT_ASSERT_MESSAGE(result.toString().c_str(),
result == MPInteger("10000"));
CPPUNIT_ASSERT_MESSAGE(modulo.toString().c_str(),
modulo == MPInteger("ffff"));
}
void bitLengthTest()
{
MPInteger a(0, 20);
a.value[1] = 2;
CPPUNIT_ASSERT(a.getBitLength() == sizeof(MPInteger::BaseUnit) * 8 + 2);
}
void MaxColumnTest()
{
MPInteger a(0, 20);
a.value[1] = 1;
CPPUNIT_ASSERT(a.getMaxColumn() == 2);
}
void toStringTest()
{
MPInteger a(11, 20);
CPPUNIT_ASSERT(a.toString() == std::string(
"b" // 1
"0000000b" // 2
"0000000b" // 3
"0000000b" // 4
"0000000b" // 5
"0000000b" // 6
"0000000b" // 7
"0000000b" // 8
"0000000b" // 9
"0000000b" //10
"0000000b" //11
"0000000b" //12
"0000000b" //13
"0000000b" //14
"0000000b" //15
"0000000b" //16
"0000000b" //17
"0000000b" //18
"0000000b" //19
"0000000b" //20
));
CPPUNIT_ASSERT(a.getBitLength() == 19 * sizeof(MPInteger::BaseUnit)*8 + 4);
}
void makeNumberTest()
{
MPInteger::BaseUnit
sample[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
MPInteger a =
MPInteger::makeNumberOfBitSafe(
sample,
sample + (sizeof(sample) / sizeof(MPInteger::BaseUnit)));
CPPUNIT_ASSERT_MESSAGE(a.toString().c_str(),
a.toString() ==
"80000000000000"
"00000000000000"
"00000000000000"
"00000000000000"
"00000000000000"
"00000000000000"
"00000000000000"
"00000000000001");
}
void shiftTest()
{
MPInteger a("AAAAAAAAAAAA");
MPInteger b(a);
b >>= 1;
CPPUNIT_ASSERT(b.toString() == "555555555555");
b >>= 1;
CPPUNIT_ASSERT_MESSAGE(b.toString(),
b.toString() == "2aaaaaaaaaaa");
b >>= 9;
CPPUNIT_ASSERT(b.toString() == "1555555555");
MPInteger c(a);
c <<= 1;
CPPUNIT_ASSERT_MESSAGE(c.toString(), c.toString() == "1555555555554");
c <<= 8;
CPPUNIT_ASSERT(c.toString() == "155555555555400");
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MPITest );
| true |
010e8d3569ff40b5988f8ad2053fbc3c8beff49e | C++ | LittlePupper/DrawingProgram | /DrawingProgram/Text.cpp | UTF-8 | 1,206 | 3.5625 | 4 | [] | no_license | // \author Nora White
// \date 2017-10-19
#include "stdafx.h"
#include "Text.h"
#include "Exception.h"
// \fn Text::Text(int row = 20, int col = 40, string phrase = "HelloWorld");
// \brief Constructor for Text which takes in 3 parameters
// \param row (Optional) int, the row of which the text will be on
// \param col (Optional) int, the column of which the first character of the text will start on
// \param phrase (Optional) string, the phrase to display on the screen
Text::Text(int row, int col, string phrase)
{
this->row = row;
this->col = col;
this->phrase = phrase;
};
// \fn Text::~Text();
// \brief Destructor
Text::~Text()
{
}
// \fn virtual void Text::draw(Screen &screen);
// \brief Draws itself to the given screen
// \param &screen Screen, a reference to screen
void Text::draw(Screen &screen)
{
for (int i = 0; i < phrase.length(); i++)
screen.set(row, col + i, phrase[i]);
}
// \fn virtual void Text::read(istream &is);
// \brief Reads the given input stream
// \param &is istream, reference to the input stream to read
// \throws input_format_error
void Text::read(istream &is)
{
is >> row >> col >> phrase;
if (is.fail())
{
throw input_format_error();
}
}
| true |
96d295ad3493c9b705c96bf461e7dbfbd828dad1 | C++ | banhtieu/AnimoGame | /Source/Game/GameStates/InGameState.cpp | UTF-8 | 3,912 | 2.75 | 3 | [] | no_license | //
// InGameState.cpp
// AnimoGame
//
// Created by Tran Khiem on 3/14/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include "InGameState.h"
#include "Animals.h"
#define ANIMAL_WIDTH 120
#define MAX_ANIMALS 6
#define ANIMAL_Y SCREEN_H - ANIMAL_WIDTH / 2 - 10
#define CELL_WIDTH (ANIMAL_WIDTH + 10)
#define ROW_WIDTH (CELL_WIDTH * ROWS)
#define TOP_PADDING 200
/**
* Init The In Game State
**/
void InGameState::Init()
{
animalSprite = new Sprite();
animalSprite->LoadSprite("Animals");
shadowSprite = new Sprite();
shadowSprite->LoadSprite("AnimalShadows");
animals.clear();
srand(time(NULL));
gameTime = 0;
rightest = SCREEN_W + ANIMAL_WIDTH / 2;
InitLevel(0);
selectedAnimal = NULL;
}
/**
* Update In Game State
**/
void InGameState::Update()
{
TouchManager *touchManager = TouchManager::GetInstance();
if (!selectedAnimal)
{
if (touchManager->HasNewTouch())
{
for (int i = 0; i < animals.size(); i++)
{
// get touched animal;
if (touchManager->IsTouchDownInRect(animals[i].x - ANIMAL_WIDTH / 2, animals[i].y - ANIMAL_WIDTH / 2, ANIMAL_WIDTH, ANIMAL_WIDTH))
{
selectedAnimal = new Animal(animals[i]);
Touch *touch = touchManager->GetFirstTouch();
if (touch)
{
oldX = touch->GetX();
oldY = touch->GetY();
}
break;
}
}
}
}
else
{
Touch *touch = touchManager->GetFirstTouch();
if (touch)
{
selectedAnimal->x += touch->GetX() - oldX;
selectedAnimal->y += touch->GetY() - oldY;
oldX = touch->GetX();
oldY = touch->GetY();
LOGI("X:%d, Y:%d", selectedAnimal->x, selectedAnimal->y);
}
else
{
selectedAnimal = NULL;
}
}
currentOffset = (currentOffset + 2) % ROW_WIDTH;
if (gameTime % 100 == 0)
{
RandomAnimal();
}
for (int i = 0; i < animals.size(); i++)
{
int limit = rightest;
if (i > 0)
{
limit = animals[i - 1].x;
}
if (animals[i].x + ANIMAL_WIDTH + 5 < limit)
{
animals[i].x += 5;
}
}
gameTime++;
}
/**
* Update In Game State
**/
void InGameState::Render(Graphics2D *g)
{
for (int i = 0; i < LINES; i++)
{
int startX = - currentOffset;
if (i & 0x1)
{
startX = - (ROW_WIDTH - currentOffset);
}
for (int j = 0; j < ROWS * 2; j++)
{
DrawAnimal(currentAnimals[i][j % LINES].animal, startX + CELL_WIDTH * j, TOP_PADDING + i * CELL_WIDTH, true);
}
}
for (vector<Animal>::iterator i = animals.begin(); i < animals.end(); i++)
{
DrawAnimal((*i).animal, (*i).x, (*i).y);
}
if (selectedAnimal)
{
DrawAnimal(selectedAnimal->animal, selectedAnimal->x, selectedAnimal->y);
}
}
/**
* Free In Game State
**/
void InGameState::Free()
{
SAFE_DEL(animalSprite);
}
/**
* draw an animal
**/
void InGameState::DrawAnimal(int animal, int x, int y, int isShadow)
{
Graphics2D *g = Graphics2D::GetInstance();
g->SetColor(Color(0xffff0000));
g->DrawRectangle(x - ANIMAL_WIDTH / 2, y - ANIMAL_WIDTH / 2, ANIMAL_WIDTH, ANIMAL_WIDTH);
if (isShadow)
{
shadowSprite->DrawModule(animal, x - shadowSprite->GetModuleWidth(animal) / 2, y - shadowSprite->GetModuleHeight(animal) / 2);
}
else
{
animalSprite->DrawModule(animal, x - animalSprite->GetModuleWidth(animal) / 2, y - animalSprite->GetModuleHeight(animal) / 2);
}
}
// Init a Level...
void InGameState::InitLevel(int level)
{
currentLevel = level;
currentOffset = 0;
maxAnimals = 6;
for (int i = 0; i < LINES; i++)
{
for (int j = 0; j < ROWS; j++)
{
currentAnimals[i][j].animal = rand() % maxAnimals;
currentAnimals[i][j].reveal = false;
}
}
}
void InGameState::RandomAnimal()
{
animals.push_back(Animal(rand() % maxAnimals, -ANIMAL_WIDTH, ANIMAL_Y));
}
| true |
19dc5f5e137e0cb79f49770838099be771a9194e | C++ | jeffrey-cochran/tsl | /tse/src/application.cpp | UTF-8 | 4,739 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #include <utility>
#include <functional>
#include <stdexcept>
#include <vector>
#include <thread>
#include <chrono>
#include <tsl/util/println.hpp>
#include <tsl/util/panic.hpp>
#include "tse/application.hpp"
using std::string;
using std::istreambuf_iterator;
using std::bind;
using std::move;
using std::make_pair;
using std::out_of_range;
using std::vector;
using std::this_thread::sleep_until;
using std::chrono::milliseconds;
using std::chrono::seconds;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using tsl::panic;
using tsl::println;
namespace tse {
void application::init_glfw() const {
glfwSetErrorCallback(&application::glfw_error_callback);
if (!glfwInit()) {
panic("ERROR: Failed to init GLFW!");
}
glfwSetTime(0);
}
void application::glfw_error_callback(int error, const char* description) {
println("ERROR ({}): {}", error, description);
}
void application::glfw_key_callback(GLFWwindow* glfw_window, int key, int scancode, int action, int mods) {
// println("INFO: key pressed!");
// if (action == GLFW_PRESS) {
// println("INFO: key pressed!");
// }
auto& instance = get_instance();
try {
auto& window = instance.windows.at(glfw_window);
window.glfw_key_callback(key, scancode, action, mods);
} catch (out_of_range&) {
println("WARNING: key caught for unknown window!");
}
}
void application::glfw_framebuffer_size_callback(GLFWwindow* glfw_window, int width, int height) {
println("INFO: framebuffer size callback! ({}, {})", width, height);
// TODO: make this window specific
glViewport(0, 0, width, height);
auto& instance = get_instance();
try {
auto& window = instance.windows.at(glfw_window);
window.glfw_framebuffer_size_callback(width, height);
} catch (out_of_range&) {
println("WARNING: framebuffer size callback for unknown window!");
}
}
void application::glfw_window_size_callback(GLFWwindow* glfw_window, int width, int height) {
println("INFO: window size callback! ({}, {})", width, height);
auto& instance = get_instance();
try {
auto& window = instance.windows.at(glfw_window);
window.glfw_window_size_callback(width, height);
} catch (out_of_range&) {
println("WARNING: window size callback for unknown window!");
}
}
void application::glfw_mouse_button_callback(GLFWwindow* glfw_window, int button, int action, int mods) {
// println("INFO: mouse button pressed");
auto& instance = get_instance();
try {
auto& window = instance.windows.at(glfw_window);
window.glfw_mouse_button_callback(button, action, mods);
} catch (out_of_range&) {
println("WARNING: mouse button pressed callback for unknown window!");
}
}
application& application::get_instance() {
static application instance;
return instance;
}
application::application() : windows(), last_num_frames(0), last_sleep(0) {
init_glfw();
}
void application::create_window(string&& title, uint32_t width, uint32_t height) {
window win(move(title), width, height);
windows.insert(make_pair(win.glfw_window.get(), move(win)));
}
void application::run() {
vector<GLFWwindow*> to_close;
auto last_time = get_time();
uint32_t num_frames = 0;
uint32_t num_sleep = 0;
while (true) {
auto now = steady_clock::now();
auto end = now + milliseconds(static_cast<uint32_t>((1.0f / FPS_TARGET) * 1000));
// mesaure speed
auto current_time = get_time();
num_frames += 1;
if (current_time - last_time >= 1.0) {
last_num_frames = num_frames;
last_sleep = num_sleep;
num_frames = 0;
num_sleep = 0;
last_time += 1.0;
}
if (windows.empty()) {
break;
}
// render all windows
for (auto&& [k, w] : windows) {
if (w.should_close()) {
to_close.push_back(k);
}
w.render();
}
// close requested windows
if (!to_close.empty()) {
for (const auto& w: to_close) {
windows.erase(w);
}
to_close.clear();
}
auto sleep = duration_cast<milliseconds>(end - steady_clock::now()).count();
if (sleep > 0) {
num_sleep += sleep;
}
sleep_until(end);
}
}
application::~application() {
glfwTerminate();
}
double application::get_time() const {
return glfwGetTime();
}
uint32_t application::get_last_num_frames() const {
return last_num_frames;
}
uint32_t application::get_last_sleep() const {
return last_sleep;
}
}
| true |
ddc5df13fcd2734d5c7737f5a33ea2773dc21304 | C++ | MikamiTetsuro365/Atcoder | /ABC116/D.cpp | UTF-8 | 1,615 | 2.59375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
typedef long long int ll;
typedef pair<ll, ll > pi;
typedef pair<pair<ll, ll >, ll > pii;
vector<ll > vec;
vector<vector<ll > > vec2;
ll MOD = 1000000007;
ll INF = 1145141919454519;
int main() {
ll N, K;
cin >> N >> K;
//入力
priority_queue<pi > que;
for(ll i = 0; i < N; i++){
ll t, d;
cin >> t >> d;
que.push(make_pair(d, t));
}
//選んだネタとその個数を記録
//mapで管理するのはよくないほんとよくない
//map<ll, ll > mp;
set<ll > st;
//美味しいさが大きい順に選ぶ
ll sum = 0;
priority_queue<pi , vector<pi >, greater<pi > > kouho;
for(ll i = 0; i < K; i++){
ll t = que.top().second;
ll d = que.top().first;
que.pop();
sum += d;
if(st.find(t) != st.end()) kouho.push(make_pair(d, t));
st.insert(t);
}
//選び直し,食べる寿司の種類を増やしてみた時,ポイントが増えますか?
ll ans = sum + st.size() * st.size();
for(ll i = 0; i < N; i++){
if(kouho.empty() || que.empty()) break;
ll t = que.top().second;
ll d = que.top().first;
que.pop();
//cout << ans - (type * type) - kouho.top().first.first + d + (type+1) * (type+1) << endl;
if(st.find(t) != st.end()) continue;
sum = sum - kouho.top().first + d;
st.insert(t);
kouho.pop();
ans = max(ans, (ll)(sum + st.size() * st.size()));
//cout << ans << endl;
}
cout << ans << endl;
} | true |
2be6f02d785f839c49c68fe93b9f71afbf729cd0 | C++ | itomilin/freelance | /lab6/patient.hpp | UTF-8 | 441 | 2.765625 | 3 | [] | no_license | #ifndef PATIENT_H
#define PATIENT_H
#include <string>
#include <QDebug>
// Класс для создания сущностей пациентов.
class Patient
{
public:
~Patient();
Patient(std::string gender,
std::string initials,
size_t age);
std::string getInfo();
private:
const std::string _gender;
const std::string _initials;
const size_t _age;
};
#endif // PATIENT_H
| true |
a412dafa5ab497e817f1adecc70679a004c7201c | C++ | guiOsorio/CPP-Practice | /Section8Challenge/main.cpp | UTF-8 | 1,278 | 4.09375 | 4 | [] | no_license | #include <iostream>
using namespace std;
// this program calculates the most efficient way (in terms of number of coins required)
// to have a certain quantity of cents
int main() {
int cents_amount {};
int dollars {}, quarters {}, dimes {}, nickels {}, pennies {};
const int one_dollar {100};
const int one_quarter {25};
const int one_dime {10};
const int one_nickel {5};
// prompt user to enter number of cents he wants displayed
cout << "Enter the number of cents: ";
cin >> cents_amount;
// calculate the number of dollars
dollars = cents_amount / one_dollar;
cents_amount %= one_dollar;
// calculate the number of quarters
quarters = cents_amount / one_quarter;
cents_amount %= one_quarter;
// calculate the number of dimes
dimes = cents_amount / one_dime;
cents_amount %= one_dime;
// calculate the number of nickels
nickels = cents_amount / one_nickel;
cents_amount %= one_nickel;
// whatever is left represents the number of pennies
pennies = cents_amount;
// display how many coins of each value the user needs
cout << "Dollars: " << dollars << endl;
cout << "Quarters: " << quarters << endl;
cout << "Dimes: " << dimes << endl;
cout << "Nickels: " << nickels << endl;
cout << "Pennies: " << pennies << endl;
return 0;
}
| true |
095dee65d98cd6b3aa47fee4815e4c6e2a1ce5fc | C++ | nrqu/answersprimer | /chapter 9/chap9_9.10/Source.cpp | UTF-8 | 312 | 3.171875 | 3 | [] | no_license | //Exercise 9.10: What are the types of the following four objects ?
//vector<int> v1;
//const vector<int> v2;
//auto it1 = v1.begin() vector<int>::iterator , it2 = v2.begin(); vector<int>::const_iterator;
//auto it3 = v1.cbegin() vector<int>::const_iterator;, it4 = v2.cbegin(); vector<int>::const_iterator; | true |
707d18737497d32136dce568fbaa458810241357 | C++ | drichardson/examples | /C++/max_subarray.cc | UTF-8 | 1,577 | 3.640625 | 4 | [
"Unlicense"
] | permissive | #include <algorithm>
#include <iostream>
#include <vector>
struct max_subarray_result {
unsigned start = 0;
unsigned end = 0;
int value = 0;
std::vector<int> maxes;
};
max_subarray_result max_subarray_kadane(std::vector<int> const & v) {
max_subarray_result r;
r.maxes.resize(v.size());
if (v.size() == 0) return r;
int max_ending_here = v[0];
int max_so_far = v[0];
unsigned start = 0;
unsigned max_start = start;
unsigned end = 0;
for(unsigned i = 1; i < v.size(); ++i) {
auto e = v[i];
if (e > max_ending_here+e) {
max_ending_here = e;
start = i;
} else {
max_ending_here += e;
}
max_so_far = std::max(max_so_far, max_ending_here);
if (max_so_far > max_ending_here) {
// same
} else {
max_so_far = max_ending_here;
max_start = start;
end = i;
}
}
r.value = max_so_far;
r.start = max_start;
r.end = end;
return r;
}
void print_max_subarray(std::vector<int> const & v) {
using std::vector;
using std::cout;
for(auto e : v) {
cout << e << ' ';
}
cout << '\n';
auto r = max_subarray_kadane(v);
cout << "max range=[ " << r.start << "," << r.end
<< "] value: " << r.value
<< "\n";
}
int main() {
print_max_subarray({1,2,3,4,5});
print_max_subarray({1,2,-3,4,5});
print_max_subarray({1,2,-4,4,5});
print_max_subarray({-10, -40, -100});
print_max_subarray({0,0,1,0,0,-1,2,-1,0});
}
| true |
72ca1cdd5515a97dfe9d9d2c1eca19ce88cc6ad9 | C++ | amirrezatav/Single-instance-applications | /source.cpp | UTF-8 | 246 | 2.59375 | 3 | [] | no_license | #include <windows.h>
int main()
{
HANDLE hMutex = CreateMutex(0, 0 , L"MutexName");
if (GetLastError() == ERROR_ALREADY_EXISTS)
return 0;
// your code
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return 0;
}
| true |
3d57f1e64595fb38c3a48a31ea2ed3b4c01d21f8 | C++ | igalakhov/mks66-mdl | /matrix/transformation_matrix.h | UTF-8 | 1,515 | 2.5625 | 3 | [] | no_license | //
// Created by Ivan Galakhov on 2019-02-19.
//
#ifndef WORK_01_LINE_TRANSFORMATION_MATRIX_H
#define WORK_01_LINE_TRANSFORMATION_MATRIX_H
#include <cassert>
#include "edge_matrix.h"
#include "../settings.h"
class EdgeMatrix;
class TransformationMatrix {
public:
TransformationMatrix(float_mat *); // constructor
~TransformationMatrix(); // destructor
void print_self(); // print self
float_mat * get_start();
// transformations
void add_transformation(TransformationMatrix *); // add a transformation
void add_transformation_inverse(TransformationMatrix *);
// copying
void copy_vals(TransformationMatrix *);
// for conversion (basically never used but it's here I guess)
static TransformationMatrix * from_edge(EdgeMatrix *);
// static constructors for making special transformation matrixes and copies
static TransformationMatrix * copy(TransformationMatrix *);
static TransformationMatrix * identity();
static TransformationMatrix * zero();
static TransformationMatrix * rotationX(float_mat);
static TransformationMatrix * rotationY(float_mat);
static TransformationMatrix * rotationZ(float_mat);
static TransformationMatrix * rotationXYZ(float_mat, float_mat, float_mat);
static TransformationMatrix * translation(float_mat, float_mat, float_mat);
static TransformationMatrix * dilation(float_mat, float_mat, float_mat);
private:
float_mat * vals; // ROW MAJOR!!!
};
#endif //WORK_01_LINE_TRANSFORMATION_MATRIX_H
| true |