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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
386389af980021b0ed5e2d3a84cf58d020595f49 | C++ | Gressee/WallpGen | /src/bmp_image.h | UTF-8 | 1,702 | 3.375 | 3 | [] | no_license | /*
Code from
https://www.youtube.com/watch?v=vqT5j38bWGg&t=1142s
*/
#pragma once
#include <vector>
#include <string>
#include <cstdint>
using namespace std;
// strcut that stores th rgb values of a pixel
// The range of rgb is 0.0 - 1.0
struct Pixel {
double r;
double g;
double b;
double a;
};
class BMPImage {
// IMPORTANT:
// The origin of the coords system is at
// the BOTTOM LEFT
public:
// Store dimensions of img
int layers;
int width;
int height;
// This vec stores every Pixel in every layer
// The first width*height belong to layer 0
// The next width*height belong to layer 1 etc
vector<Pixel> pixels;
// Constructor
BMPImage(int imgLayers, int imgWidth, int imgHeight);
// Destructor
~BMPImage();
/* BASIC FUNCTIONS */
// Get data of one pixel
Pixel getPixel(int layer, int x, int y) const;
// Set the on pixel
void setPixel(int layer, int x, int y, Pixel color);
// Compose the different layers
Pixel getAlphaCompositionPixel(int x, int y) const;
// Bluer a single layer with the Gausian blur algorithm
void blurlayer(int layer, int blurRadius);
// Export the image to a .bmp file
void exportToFile(const string path) const;
/* DRAW FUNCTIONS */
// Basic single color shapes
// The Pixel arg is just the color that the shape should be in
void drawRect(Pixel color, int layer, int pos_x, int pos_y, int rect_width, int rect_height);
void drawCircle(Pixel color, int layer, int center_x, int center_y, int rad);
void drawTriangle(Pixel color, int layer, int x1, int y1, int x2, int y2, int x3, int y3);
};
| true |
da18f3ad96f8f27d10bd60795884618c92534366 | C++ | kamomil/Hackerrank-leetcode | /longest-increasing-subsequent/longest-increasing-subsequent.cpp | UTF-8 | 991 | 3.234375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
Solution to https://www.hackerrank.com/challenges/longest-increasing-subsequent/problem
based on: https://stackoverflow.com/questions/2631726/how-to-determine-the-longest-increasing-subsequence-using-dynamic-programming
*/
int main() {
int n;
cin >> n;
//smallest[k] - the smallest in that ends a sequence of length k+1 from what was scanned so far
vector<int> smallest = vector<int>(n);
cin >> smallest[0];
auto true_end = smallest.begin();
true_end++;//point to the true end of the vector
for(int i=1;i<n;i++){
int num;
cin >> num;
if( *prev(true_end, 1) < num){
*true_end = num;
true_end++;
}
else{
auto lower = lower_bound(smallest.begin(),true_end, num);
*lower = num;
}
}
cout << true_end-smallest.begin();
}
| true |
36a0cbf6127b12d9b85076167acef46c207554f6 | C++ | gitqwerty777/Online-Judge-Code | /categorized/[Simple] 10018-Reverse-And-Add.cpp | UTF-8 | 889 | 3.03125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int N;
char in[20];
bool check_sym(char* sum){
int len = strlen(sum);
for(int i = 0; i*2 <= len; i++){
if(sum[i] != sum[len-i-1])
return false;
}
return true;
}
void Reverse_And_Add(){
char sum[20];
strcpy(sum, in);
int count = 0;
while(!check_sym(sum)){
int len = strlen(in);
bool addnum = false;
for(int i = 0; i < len; i++){
sum[len-i-1] += in[i]-'0';
if(sum[len-i-1] > '9'){
sum[len-i-1] -= 10;
if(len-i-1 == 0){
addnum = true;
} else {
sum[len-i-2]++;
}
}
}
strcpy(in, sum);
if(addnum){
strcpy(sum+1, in);
sum[0] = '1';
strcpy(in, sum);
}
count++;
// printf("%d %s\n", count, sum);
}
printf("%d %s\n", count, sum);
}
int main(){
scanf("%d", &N);
while(N--){
scanf("%s", in);
Reverse_And_Add();
}
return 0;
} | true |
d9d2cf0d4767a1ab79c7fa89c2c90143d747d626 | C++ | spokoynj/OSU-Projects | /CS 162 - Intro to CS II/Assignment 1/main.cpp | UTF-8 | 3,822 | 3.46875 | 3 | [] | no_license | /*********************************************************************
** Program Filename: main.cpp
** Author: Jessica Spokoyny
** Date: 01/14/16
** Description: Assignment 1: Implementation of Conway's Game of Life
** Input:
** Output:
*********************************************************************/
#include "life.hpp"
/*********************************************************************
** Function: main
** Description: main is required for program to run
*********************************************************************/
int main()
{
/* intro for game*/
cout << endl << "This program runs the game of life." << endl
<< endl << endl << "There are three options for starting shapes:"
<< endl << "an oscillator (1), a glider (2), or a glider gun (3)"
<< endl << endl;
/* get shape selection from user */
int shape;
cout << "Enter your selection (1 or 2 or 3) : ";
cin >> shape;
cout << endl;
/* get shape's starting location from user */
cout << "Where would you like to place the top left corner of the shape?" << endl;
int startRow;
int startCol;
/* recommend placement for each shape for full viewing */
if (shape == 1)
{
cout << "ROW (choose between 1 - 19) : ";
cin >> startRow;
cout << endl;
cout << "COLUMN (choose between 0 - 38 ) : ";
cin >> startCol;
cout << endl;
}
else if (shape == 2)
{
cout << "ROW (choose betwee 0 - 18) : ";
cin >> startRow;
cout << endl;
cout << "COLUMN (choose between 0 - 38) : ";
cin >> startCol;
cout << endl;
}
else if (shape == 3)
{
cout << "ROW (choose between 0 - 11) : ";
cin >> startRow;
cout << endl;
cout << "COLUMN (choose between 0 - 4) : ";
cin >> startCol;
cout << endl;
}
/* create a new array with extra room on each side */
int array[80][100];
/* initialize the array to all dead */
for (int i = 0; i < 80; i++)
{
for (int j = 0; j < 100; j++)
{
array[i][j] = 0;
}
}
/* change appropriate cells to alive based on user's shape selection */
buildShape(array, shape, startRow, startCol);
/* get number of generations from user */
int generations;
cout << "How many generations would you like to see performed? ";
cin >> generations;
cout << endl;
/* create new temporary array */
int temp[80][100];
do
{
/* clear the screen */
system("clear");
/* print only the 20x40 portion of array */
for (int i = 30; i < 50; i++)
{
for (int j = 30; j < 70; j++)
{
if (array[i][j] == 0)
{
/* dead cells will be ' ' */
cout << "-";
}
else
{
/* live cells will be 'X' */
cout << "X";
}
}
cout << endl;
}
/* pause to let user see the movements */
system("sleep .1");
/* coppy array to temp array to save pending changes before printing */
copyArray(array, temp);
/* loop through all cells to check state */
for (int i = 0; i < 80; i++)
{
for (int j = 0; j < 100; j++)
{
/* count number of neighbors */
int count = 0;
count = array[i - 1][j - 1]
+ array[i][j - 1]
+ array[i + 1][j - 1]
+ array[i - 1][j]
+ array[i + 1][j]
+ array[i - 1][j + 1]
+ array[i][j + 1]
+ array[i + 1][j + 1];
/* cell becomes/remains dead */
if (count < 2 || count > 3)
{
temp[i][j] = 0;
}
/* cell becomes/remains alive */
else if (count == 3)
{
temp[i][j] = 1;
}
/* cell remains unchanged */
else
{
temp[i][j] = array[i][j];
}
}
}
/* copy temp array back to array */
copyArray(temp, array);
/* loop through again for each remaining generation */
generations--;
} while (generations > 0);
return 0;
}
| true |
d91839f4bf082c59e4c02714eb9bd8eacdc3c9cb | C++ | RantNRave31/beladysAnomaly | /b4.cpp | UTF-8 | 3,130 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include<deque>
#include<unordered_map>
#include<vector>
#include<random>
#include<time.h>
void printAnomaly(int i, int j, int faultStorage, int faultCounter){
std::cout << "Anomaly Discovered" << std::endl;
std::cout << "Sequence:" << i << std::endl;
std::cout << "\tPage Faults:" << faultStorage << " @ Frame Size: " << (j) << std::endl;
std::cout << "\tPage Faults:" << faultCounter << " @ Frame Size: " << j+1 << std::endl << std::endl;
}
int main(){
// anomalyCounter holds the total number of anomalies
int anomalyCounter = 0;
//seeding random
srand(time(NULL));
int memoryIterator = 0;
//for 100 sequences
for(int i = 0; i < 100; i++){
//generate a sequence
std::vector<int> sequence;
for(int g = 0; g < 1000; g++){
sequence.push_back(rand() %250);
}
//faultCounter should hold the number of page faults on the current iteration
int faultCounter = 0;
//faultStorage should hold the number of page faults on the previous iteration
//It is set to 9999 so that on the very first iteration it will be greater than
//the faultCounter iterator
int faultStorage = 9999;
//for page sizes from 1 to 100
for(int j = 1; j < 101; j++){
//Sanity check: making sure faultStorage is going to be the larger value on the first iteration
if(j == 1){
faultStorage = 9999;
}
//Keep the current values in a hash table
std::unordered_map<int,int> memory;
//Impliment FIFO with a std::queue
std::deque<int> q;
//For every number in the sequence
for(int h = 0; h < 1000; h++){
//check whether it is in memory
bool check = false;
for(auto e : q){
if(e == sequence.at(h)){check = true;}
}
//if it is NOT in memory,
if(check == false){
//and if the size of the queue is greater than the number of pages
if(q.size() >= j){
//delete the first element from memory
auto iterator = memory.find(q.front());
if(iterator != memory.end()){memory.erase(iterator);}
//if(memory.find(0) != memory.end()){std::cout << "fuck" << std::endl;}
//Pop the first element off of the queue
q.pop_front();
}
//(we fall back into scope of the first if statement) If it is not in memory, insert that element of the sequence into memory
memory.insert({memoryIterator, sequence.at(h)});
memoryIterator++;
//push it onto the queue
q.push_back(sequence.at(h));
//any time we have to insert something into memeory, that counts as a page fault
faultCounter++;
}
}
//If the number of faults from the previous iteration exceeds that of the current iteration,
if(faultStorage < faultCounter){
//An anomaly happened
printAnomaly(i, j, faultStorage, faultCounter);
anomalyCounter++;
}
//faultStorage gets fault Counter
faultStorage = faultCounter;
//faultCounter is zero for the next round
faultCounter = 0;
//clear out the queue
q.clear();
memoryIterator = 0;
//clear out memeory
memory.clear();
//go to the next iteration
}
//this is more tidying than anything, but clear the sequence
sequence.clear();
//start again.
}
std::cout << anomalyCounter << std::endl;
return 0;
}
| true |
0754bb00feb2b4a56afe8a882e17252eefa7b56f | C++ | wwhhh/DX11 | /Codes/Client/DX/Events/EventManager.cpp | UTF-8 | 1,594 | 2.671875 | 3 | [] | no_license | #include "PCH.h"
#include "EventManager.h"
EventManager* EventManager::m_spEventManager = 0;
EventManager::EventManager()
{
if (!m_spEventManager)
m_spEventManager = this;
}
EventManager::~EventManager()
{
for (unsigned int e = 0; e < NUM_EVENTS; e++) {
for (unsigned int i = 0; i < m_EventHandlers[e].size(); i++) {
m_EventHandlers[e][i]->SetEventManager(nullptr);
}
}
}
EventManager* EventManager::Get()
{
return(m_spEventManager);
}
bool EventManager::AddEventListener(eEVENT EventID, IEventListener* pListener)
{
if (EventID >= NUM_EVENTS)
return(false);
m_EventHandlers[EventID].push_back(pListener);
return(true);
}
bool EventManager::DelEventListener(eEVENT EventID, IEventListener* pListener)
{
if (EventID >= NUM_EVENTS)
return(false);
bool bResult = false;
int index = -1;
for (std::vector< IEventListener* >::iterator it = m_EventHandlers[EventID].begin(); it != m_EventHandlers[EventID].end(); ++it)
{
if (*it == pListener)
{
m_EventHandlers[EventID].erase(it);
bResult = true;
break;
}
}
return(bResult);
}
bool EventManager::ProcessEvent(EventPtr pEvent)
{
if (!pEvent)
return(false);
eEVENT e = pEvent->GetEventType();
unsigned int num = m_EventHandlers[e].size();
bool bHandled = false;
for (unsigned int i = 0; i < num; i++)
{
bHandled = m_EventHandlers[e][i]->HandleEvent(pEvent);
if (bHandled)
break;
}
return(bHandled);
} | true |
dd6b87a5d1346f34a932a62ecec204ef73af10ab | C++ | tajirhas9/Problem-Solving-and-Programming-Practice | /Algorithms/Graph Theory/Lowest Common Ancestor (LCA).cpp | UTF-8 | 1,257 | 3.0625 | 3 | [] | no_license | /*
* The nodes are to be 0-based.
*/
class LowestCommonAncestor {
vector < vector < int > > graph;
int nodes;
vector < int > size , depth , tin , tout;
int timer,max_anc=0;
vector < vector < int > > anc;
vector < bool > vis;
void dfs(int u , int par = 1 , int d = 0) {
vis[u] = true;
depth[u] = d;
tin[u] = timer++;
size[u] = 1;
anc[u][0] = par;
for(int i = 1; i < max_anc; ++i)
anc[u][i] = anc[ anc[u][i-1] ][i-1];
for(int i = 0; i < graph[u].size(); ++i) {
int v = graph[u][i];
if(!vis[v]) {
dfs(v, u , d+1 );
size[u] += size[v];
}
}
tout[u] = timer++;
}
bool ancestor(int a, int b) {
return ( (tin[a] <= tin[b] ) && (tout[b] <= tout[a] ) );
}
int go_up(int a, int b) {
for(int i = max_anc-1 ; i >= 0; --i) {
if(!ancestor(anc[a][i],b))
a = anc[a][i];
}
return a;
}
public:
LowestCommonAncestor(vector < vector < int > > g, int n) {
max_anc = log2(n);
nodes = n;
graph = g;
size.assign(n,0);
depth.assign(n,0);
tin.assign(n,0);
tout.assign(n,0);
anc.assign(n,vi(max_anc));
vis.assign(n,false);
timer = 0;
dfs(0);
}
int lca(int a, int b) {
if(ancestor(a,b))
return a;
else if(ancestor(b,a))
return b;
else
return anc[go_up(a,b)][0];
}
};
| true |
d4df4d1b0fd06f6c3b20449a8c5d92c7d0463dc0 | C++ | opendarkeden/server | /src/server/gameserver/quest/ActionGiveNewbieItem.cpp | UHC | 9,840 | 2.59375 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
// Filename : ActionGiveNewbieItem.cpp
// Written By :
// Description :
////////////////////////////////////////////////////////////////////////////////
#include "ActionGiveNewbieItem.h"
#include "Slayer.h"
#include "FlagSet.h"
#include "Item.h"
#include "Zone.h"
#include "ItemFactoryManager.h"
#include "item/Magazine.h"
#include "GCCreateItem.h"
#include "GCNPCResponse.h"
#include "GCModifyInformation.h"
#include "GamePlayer.h"
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
void ActionGiveNewbieItem::read (PropertyBuffer & propertyBuffer)
{
__BEGIN_TRY
try
{
// read script type
string ItemType = propertyBuffer.getProperty("Type");
if (ItemType == "SWORD") m_ItemClass = Item::ITEM_CLASS_SWORD;
else if (ItemType == "BLADE") m_ItemClass = Item::ITEM_CLASS_BLADE;
else if (ItemType == "AR") m_ItemClass = Item::ITEM_CLASS_AR;
else if (ItemType == "SR") m_ItemClass = Item::ITEM_CLASS_SR;
else if (ItemType == "SG") m_ItemClass = Item::ITEM_CLASS_SG;
else if (ItemType == "SMG") m_ItemClass = Item::ITEM_CLASS_SMG;
else if (ItemType == "CROSS") m_ItemClass = Item::ITEM_CLASS_CROSS;
else if (ItemType == "MACE") m_ItemClass = Item::ITEM_CLASS_MACE;
else
{
cout << "ActionGiveNewbieItem::read() : Unknown item type" << endl;
throw ("ActionGiveNewbieItem::read() : Unknown item type");
}
}
catch (NoSuchElementException & nsee)
{
cout << nsee.toString() << endl;
throw Error(nsee.toString());
}
__END_CATCH
}
////////////////////////////////////////////////////////////////////////////////
// Ѵ.
////////////////////////////////////////////////////////////////////////////////
void ActionGiveNewbieItem::execute (Creature * pCreature1 , Creature * pCreature2)
{
__BEGIN_TRY
Assert(pCreature1 != NULL);
Assert(pCreature2 != NULL);
Assert(pCreature1->isNPC());
Assert(pCreature2->isPC());
Player* pPlayer = pCreature2->getPlayer();
Assert(pPlayer != NULL);
// Ŭ̾Ʈ GCNPCResponse ش.
GCNPCResponse okpkt;
pPlayer->sendPacket(&okpkt);
// ʺڰ ̾ ƴ .
if (!pCreature2->isSlayer()) return;
Slayer* pSlayer = dynamic_cast<Slayer*>(pCreature2);
FlagSet* pFlagSet = pSlayer->getFlagSet();
Inventory* pInventory = pSlayer->getInventory();
Zone* pZone = pSlayer->getZone();
////////////////////////////////////////////////////////////
// ¥ ʺ ˻Ѵ.
// 0 ʺ Ҵ ÷ ߴ.
// ̰ ڵ.
////////////////////////////////////////////////////////////
if (pFlagSet->isOn(0)) return;
////////////////////////////////////////////////////////////
// Ŭ Ѵ.
////////////////////////////////////////////////////////////
Item* pItem[10] = { NULL, };
int i = 0;
for (i=0; i<10; i++) pItem[i] = NULL;
list<OptionType_t> nullList;
if (m_ItemClass == Item::ITEM_CLASS_SWORD)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_SWORD, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
}
else if (m_ItemClass == Item::ITEM_CLASS_BLADE)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_BLADE, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
}
else if (m_ItemClass == Item::ITEM_CLASS_CROSS)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_CROSS, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
}
else if (m_ItemClass == Item::ITEM_CLASS_MACE)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_MACE, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
}
else if (m_ItemClass == Item::ITEM_CLASS_AR)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_AR, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
// źâ
pItem[5] = CREATE_ITEM(Item::ITEM_CLASS_MAGAZINE, 2, nullList);
Magazine* pMagazine = dynamic_cast<Magazine*>(pItem[5]);
pMagazine->setNum(9);
}
else if (m_ItemClass == Item::ITEM_CLASS_SR)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_SR, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
// źâ
pItem[5] = CREATE_ITEM(Item::ITEM_CLASS_MAGAZINE, 6, nullList);
Magazine* pMagazine = dynamic_cast<Magazine*>(pItem[5]);
pMagazine->setNum(9);
}
else if (m_ItemClass == Item::ITEM_CLASS_SG)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_SG, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
// źâ
pItem[5] = CREATE_ITEM(Item::ITEM_CLASS_MAGAZINE, 0, nullList);
Magazine* pMagazine = dynamic_cast<Magazine*>(pItem[5]);
pMagazine->setNum(9);
}
else if (m_ItemClass == Item::ITEM_CLASS_SMG)
{
//
pItem[0] = CREATE_ITEM(Item::ITEM_CLASS_SMG, 0, nullList);
//
pItem[1] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[2] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 0, nullList);
pItem[3] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
pItem[4] = CREATE_ITEM(Item::ITEM_CLASS_POTION, 5, nullList);
// źâ
pItem[5] = CREATE_ITEM(Item::ITEM_CLASS_MAGAZINE, 4, nullList);
Magazine* pMagazine = dynamic_cast<Magazine*>(pItem[5]);
pMagazine->setNum(9);
}
else
{
return;
}
////////////////////////////////////////////////////////////
// ϰ, DB ϰ,
// Ŭ̾Ʈ ش.
////////////////////////////////////////////////////////////
ObjectRegistry& OR = pZone->getObjectRegistry();
TPOINT pt;
GCCreateItem gcCreateItem;
for (i=0; i<10; i++)
{
if (pItem[i] != NULL)
{
OR.registerObject(pItem[i]);
if (pInventory->addItem(pItem[i], pt))
{
pItem[i]->create(pSlayer->getName(), STORAGE_INVENTORY, 0, pt.x, pt.y);
gcCreateItem.setObjectID(pItem[i]->getObjectID());
gcCreateItem.setItemClass(pItem[i]->getItemClass());
gcCreateItem.setItemType(pItem[i]->getItemType());
gcCreateItem.setOptionType(pItem[i]->getOptionTypeList());
gcCreateItem.setDurability(pItem[i]->getDurability());
gcCreateItem.setSilver(pItem[i]->getSilver());
if (pItem[i]->getItemClass() == Item::ITEM_CLASS_MAGAZINE)
{
Magazine* pMag = dynamic_cast<Magazine*>(pItem[i]);
gcCreateItem.setItemNum(pMag->getNum());
}
else
{
gcCreateItem.setItemNum(pItem[i]->getNum());
}
gcCreateItem.setInvenX(pt.x);
gcCreateItem.setInvenY(pt.y);
pPlayer->sendPacket(&gcCreateItem);
}
else
{
SAFE_DELETE(pItem[i]);
}
}
}
// شٳ...
//pSlayer->setGoldEx(pSlayer->getGold() + 500);
// by sigi. 2002.9.18
pSlayer->increaseGoldEx(500);
GCModifyInformation gcModifyInformation;
gcModifyInformation.addLongData(MODIFY_GOLD, pSlayer->getGold());
pPlayer->sendPacket(&gcModifyInformation);
////////////////////////////////////////////////////////////
// , FlagSet Ѵ.
// 0 ʺ Ҵ ÷ ߴ.
// ̰ ڵ.
////////////////////////////////////////////////////////////
pFlagSet->turnOn(FLAGSET_RECEIVE_NEWBIE_ITEM);
if (m_ItemClass == Item::ITEM_CLASS_SWORD || m_ItemClass == Item::ITEM_CLASS_BLADE)
{
// 1
pFlagSet->turnOn(FLAGSET_RECEIVE_NEWBIE_ITEM_FIGHTER);
}
else if (m_ItemClass == Item::ITEM_CLASS_CROSS || m_ItemClass == Item::ITEM_CLASS_MACE)
{
// 2
pFlagSet->turnOn(FLAGSET_RECEIVE_NEWBIE_ITEM_CLERIC);
}
else
{
// 3
pFlagSet->turnOn(FLAGSET_RECEIVE_NEWBIE_ITEM_GUNNER);
}
pFlagSet->save(pSlayer->getName());
__END_CATCH
}
////////////////////////////////////////////////////////////////////////////////
// get debug string
////////////////////////////////////////////////////////////////////////////////
string ActionGiveNewbieItem::toString () const
{
__BEGIN_TRY
StringStream msg;
msg << "ActionGiveNewbieItem("
<< ")";
return msg.toString();
__END_CATCH
}
| true |
d860c82041364df38bde492410cd668534dce23f | C++ | Jung-Woo-sik/CNU-assistant | /Object_Oriented_Programing/assignment4/asssignment/ShapePattern.cpp | UTF-8 | 236 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | #include "ShapePattern.h"
//set up the default pattern as '*' star
ShapePattern::ShapePattern()
{
pattern = '*';
}
void ShapePattern::set_pattern(char c)
{
pattern = c;
}
char ShapePattern::get_pattern() const
{
return pattern;
}
| true |
2b2a101575c4b72a845efcd3fe571fbe5cd4aa9e | C++ | wangoasis/cpp_primer_practice | /ch_12/ex12_20.cpp | UTF-8 | 519 | 3.296875 | 3 | [] | no_license | //Exercise 12.20
//Write a program that reads an input file a line at a time into a StrBlob and uses a StrBlobPtr to point to ench element in that StrBlob
#include <fstream>
#include <iostream>
#include "ch12_StrBlob.h"
int main() {
std::ifstream ifs("ex11_33_inputFile.txt");
StrBlob blob;
for(std::string str; std::getline(ifs, str); )
blob.push_back(str);
for(StrBlobPtr pbeg(blob.begin()), pend(blob.end()); pbeg != pend; pbeg.incr())
std::cout << pbeg.deref() << std::endl;
}
| true |
b549a7b5ad6823a570e9e4cec8c8c851f1028da5 | C++ | Bourns-A/LeetCode | /Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2.cpp | UTF-8 | 364 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int change(int amount, vector<int>& coins)
{
vector<int>dp(amount+1,0);
dp[0] = 1;
for (int coin: coins)
{
for (int i=1; i<=amount; i++)
{
if (i>=coin)
dp[i] += dp[i-coin];
}
}
return dp[amount];
}
};
| true |
5bdddff8d36256e1e73d6374b3a9caaa6deee4c9 | C++ | angelinaserova/aip_lessons | /week1task8d_AiP/task8d_AiP/task8d_AiP.cpp | UTF-8 | 594 | 3.015625 | 3 | [] | no_license | /*Вычислите значение выражения:
(abs(x-5)-sin(x))/3+sqrt(x*x+2014)*cos(2*x)-3
*/
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
std::cout << "vvedite x"<< std::endl;
float x;
std::ofstream fo;
std::ifstream fi;
cin >> x;
std::cout << "x= "<< x << std::endl;
std::cout << "otvet= " << (abs(x-5)-sin(x))/3+sqrt(x*x+2014)*cos(2*x)-3 << std::endl;
fo.open("in.txt");
fo << x;
fo.close();
fi.open("in.txt");
fi >> x;
fi.close();
}
| true |
1e583d1ec08fd4428522654b72b901d7a405537c | C++ | JeffersonLab/sim-recon | /src/programs/Simulation/mcsmear/DRandom2.h | UTF-8 | 4,329 | 2.921875 | 3 | [] | no_license | // $Id$
//
// Random number generator used in mcsmear. All random numbers
// should come from the global "gDRandom" object declared here.
//
// Because we want to record the seeds used for every event,
// we use the TRandom2 class. This one has only 3 seed values
// (as opposed to 24 for TRandom1 and 624 for TRandom3) but
// is fast with a large period (10^26).
//
// Because the seeds in TRandom2 are declared protected in
// the class with no methods to access/set them, we derive
// a new class, DRandom2 from TRandom2. This allows us access
// to the numbers for easy recording/retrieving.
#ifndef _DRANDOM2_H_
#define _DRANDOM2_H_
#include <TRandom2.h>
#include <iostream>
using std::cerr;
using std::endl;
class DRandom2:public TRandom2{
public:
DRandom2(UInt_t seed=1):TRandom2(seed){}
void GetSeeds(UInt_t &seed, UInt_t &seed1, UInt_t &seed2){
seed = this->fSeed;
seed1 = this->fSeed1;
seed2 = this->fSeed2;
}
void SetSeeds(UInt_t &seed, UInt_t &seed1, UInt_t &seed2){
// See the comments in TRandom2::SetSeed(int)
if( (seed<2) | (seed1<8) | (seed2<16) ){
cerr << endl;
cerr << "*********************************************************" << endl;
cerr << "WARNING: Random seeds passed to DRandom2::SetSeeds have" << endl;
cerr << "forbidden values: " << endl;
cerr << " seed = " << seed << " (must be at least 2)" <<endl;
cerr << " seed1 = " << seed1 << " (must be at least 8)" <<endl;
cerr << " seed1 = " << seed2 << " (must be at least 16)" <<endl;
cerr << "See comments in source for TRandom2::SetSeed(int)" <<endl;
cerr << "The seeds will all be adjusted to be in range." <<endl;
cerr << "*********************************************************" << endl;
cerr << endl;
seed += 2;
seed1 += 8;
seed2 += 15;
}
this->fSeed = seed;
this->fSeed1 = seed1;
this->fSeed2 = seed2;
}
// legacy mcsmear interface
inline double SampleGaussian(double sigma) {
return Gaus(0.0, sigma);
}
inline double SamplePoisson(double lambda) {
return Poisson(lambda);
}
inline double SampleRange(double x1, double x2) {
double s, f;
double xlo, xhi;
if(x1<x2){
xlo = x1;
xhi = x2;
}else{
xlo = x2;
xhi = x1;
}
s = Rndm();
f = xlo + s*(xhi-xlo);
return f;
}
inline bool DecideToAcceptHit(double prob) {
// This function is used for sculpting simulation efficiencies to match those
// in the data. With the data/sim matching efficiency as an input parameter,
// this function decides if we should keep the hit or not
// Tolerance for seeing if a number is near zero
// Could use std::numeric_limits::epsilon(), but that's probably too restrictive
const double maxAbsDiff = 1.e-8;
// If the hit efficiency is zero, then always reject it
// For floating point numbers, using the absolute difference to see if a
// number is consistent with zero is preferred.
// Reference: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
if( fabs(prob - 0.0) < maxAbsDiff )
return false;
// If the effiency is less than 0, then we always reject it
// This really shouldn't happen, though
if( prob < 0.0 )
return false;
// If the efficiency is greater than 1, then always accept it
// (though why would it be larger?)
if( prob > 1.0 )
return true;
// If the efficiency is equal to one, then always accept it
if(AlmostEqual(prob, 1.0))
return true;
// Otherwise, our efficiency should be some number in (0,1)
// Throw a random number in that range, and reject if the random
// number is larger than our efficiency
if(Uniform() > prob)
return false;
return true;
}
private:
bool AlmostEqual(double a, double b) {
// Comparing floating point numbers is tough!
// This should work for numbers not near zero.
// Reference: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
const double maxRelDiff = 1.e-8;
double diff = fabs(a-b);
a = fabs(a);
b = fabs(b);
double largest = (b > a) ? b : a;
if(diff <= largest*maxRelDiff)
return true;
return false;
}
};
#endif // _DRANDOM2_H_
extern DRandom2 gDRandom;
| true |
35c90df3bf8902ec3ae03aae7d8de4d7ad791e45 | C++ | wszdwp/algm_practice | /ctci_c++/q4.6.cpp | UTF-8 | 2,800 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <cstring>
using namespace std;
const int maxn = 10;
typedef struct tNode
{
int data;
tNode *lchild;
tNode *rchild;
tNode *parent;
}tNode;
tNode *p, node[maxn];
int cnt;
tNode* init(){
p = NULL;
memset(node, '\0', sizeof(node));
cnt = 0;
}
void create_minimal_tree(tNode* &root, tNode *parent, int a[], int start, int end){
if(start <= end){
int mid = (start + end)>>1;
node[cnt].data = a[mid];
node[cnt].parent = parent;
root = &node[cnt++];
create_minimal_tree(root->lchild, root, a, start, mid-1);
create_minimal_tree(root->rchild, root, a, mid+1, end);
}
}
void printIn(tNode *root){
if(root == NULL) return;
printIn(root->lchild);
cout << root->data << " ";
printIn(root->rchild);
}
tNode* first_ancestor1(tNode* n1, tNode* n2){
if(n1 == NULL || n2 == NULL) return NULL;
map<tNode*, bool> m;
while(n1){
m[n1] = true;
n1 = n1->parent;
}
while(n2 && !m[n2]){
n2 = n2->parent;
}
return n2;
}
bool father(tNode* n1, tNode* n2){
if(n1 == NULL || n2 == NULL) return false;
if(n1 == n2) return true;
else return father(n1->lchild, n2) || father(n1->rchild, n2);
}
tNode* first_ancestor2(tNode* n1, tNode* n2){
if(n1 == NULL || n2 == NULL) return NULL;
while(n1){
if(father(n1, n2)) return n1;
n1 = n1->parent;
}
return NULL;
}
void first_ancestor3(tNode* root, tNode* n1, tNode* n2, tNode* &ans){
if(root == NULL || n1 == NULL || n2 == NULL) return;
if(root && father(root, n1) && father(root, n2)){
ans = root;
first_ancestor3(root->lchild, n1, n2, ans);
first_ancestor3(root->rchild, n1, n2, ans);
}
}
tNode* search(tNode* root, int x){
if(root == NULL) return NULL;
else if(x == root->data) return root;
else if(x <= root->data) search(root->lchild, x);
else search(root->rchild, x);
}
int main(){
int a[] = {
1, 2, 3, 4, 5, 6, 7, 8
};
init();
tNode *root = NULL;
create_minimal_tree(root, NULL, a, 0, 7);
printIn(root);
cout << endl;
tNode* ans = NULL;
//tNode *node1 = search(root, 3);
//tNode *node2 = search(root, 5);
//tNode *node1 = search(root, 5);
//tNode *node2 = search(root, 7);
tNode *node1 = search(root, 3);
tNode *node2 = search(root, 7);
tNode *ancestor1stbyway1 = first_ancestor1(node1, node2);
cout << "(Way1)ancestor of " << node1->data << " and " << node2->data << " is " << ancestor1stbyway1->data << endl;
tNode *ancestor1stbyway2 = first_ancestor2(node1, node2);
cout << "(Way2)ancestor of " << node1->data << " and " << node2->data << " is " << ancestor1stbyway2->data << endl;
first_ancestor3(root, node1, node2, ans);
cout << "(Way3)ancestor of " << node1->data << " and " << node2->data << " is " << ans->data << endl;
} | true |
8c8666d92859c02d7e6e5351c4f02c7c6c4b6a05 | C++ | IshidaTakuto/Works | /吉田学園情報ビジネス専門学校_石田琢人/ゲーム/05_3Dアクション_チーム制作/開発環境/rain.cpp | SHIFT_JIS | 5,090 | 2.8125 | 3 | [] | no_license | //=============================================================================
//
// J [rain.cpp]
// Author : TAKUTO ISHIDA
//
//=============================================================================
#include "rain.h"
//*****************************************************************************
// }N`
//*****************************************************************************
#define TEXTURE_RAIN "data/TEXTURE/rain01.png" // ǂݍރeNX`t@C
#define MAX_RAIN (2) // J̍ő吔
#define RAIN_SPEED (2.0f) // J̑
//*****************************************************************************
// O[oϐ
//*****************************************************************************
LPDIRECT3DTEXTURE9 g_pTextureRain = NULL; // eNX`ւ̃|C^
LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffRain = NULL; // _obt@ւ̃|C^
int g_nCntRain;
//=============================================================================
// |S
//=============================================================================
void InitRain(void)
{
LPDIRECT3DDEVICE9 pDevice;
// foCX̎擾
pDevice = GetDevice();
g_nCntRain = 0;
// eNX`̓ǂݍ
D3DXCreateTextureFromFile(pDevice, TEXTURE_RAIN, &g_pTextureRain);
// _obt@̐
pDevice->CreateVertexBuffer(sizeof(VERTEX_3D) * 4 * MAX_RAIN,
D3DUSAGE_WRITEONLY,
FVF_VERTEX_3D,
D3DPOOL_MANAGED,
&g_pVtxBuffRain,
NULL);
VERTEX_2D *pVtx; // _ւ̃|C^
// _obt@bNA_f[^ւ̃|C^擾
g_pVtxBuffRain->Lock(0, 0, (void**)&pVtx, 0);
// _̍W
for (int nCntRain = 0; nCntRain < MAX_RAIN; nCntRain++)
{
pVtx[0].pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
pVtx[1].pos = D3DXVECTOR3(SCREEN_WIDTH, 0.0f, 0.0f);
pVtx[2].pos = D3DXVECTOR3(0.0f, SCREEN_HEIGHT, 0.0f);
pVtx[3].pos = D3DXVECTOR3(SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f);
//1.0fŌŒ
pVtx[0].rhw = 1.0f;
pVtx[1].rhw = 1.0f;
pVtx[2].rhw = 1.0f;
pVtx[3].rhw = 1.0f;
// _J[
pVtx[0].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[1].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[2].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
pVtx[3].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
// eNX`W
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f + (nCntRain * 1.5f), 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f + (nCntRain * 1.5f));
pVtx[3].tex = D3DXVECTOR2(1.0f + (nCntRain * 1.5f), 1.0f + (nCntRain * 1.5f));
pVtx += 4; //_f[^̃|C^4i߂
}
// _obt@AbN
g_pVtxBuffRain->Unlock();
}
//=============================================================================
// |SI
//=============================================================================
void UninitRain(void)
{
// eNX`̔j
if (g_pTextureRain != NULL)
{
g_pTextureRain->Release();
g_pTextureRain = NULL;
}
// _obt@̔j
if (g_pVtxBuffRain != NULL)
{
g_pVtxBuffRain->Release();
g_pVtxBuffRain = NULL;
}
}
//=============================================================================
// |SXV
//=============================================================================
void UpdateRain(void)
{
VERTEX_2D *pVtx; // _ւ̃|C^
// _obt@bNA_f[^ւ̃|C^擾
g_pVtxBuffRain->Lock(0, 0, (void**)&pVtx, 0);
// _̍W
for (int nCntRain = 0; nCntRain < MAX_RAIN; nCntRain++)
{
// eNX`W
pVtx[0].tex -= D3DXVECTOR2(0.0f, 0.015f);
pVtx[1].tex -= D3DXVECTOR2(0.0f, 0.015f);
pVtx[2].tex -= D3DXVECTOR2(0.0f, 0.015f);
pVtx[3].tex -= D3DXVECTOR2(0.0f, 0.015f);
pVtx += 4;
}
// _obt@AbN
g_pVtxBuffRain->Unlock();
}
//=============================================================================
// |S`揈
//=============================================================================
void DrawRain(void)
{
LPDIRECT3DDEVICE9 pDevice = GetDevice(); // foCX̎擾
// eXg̐ݒ
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
// _obt@f[^Xg[ɐݒ
pDevice->SetStreamSource(0, g_pVtxBuffRain, 0, sizeof(VERTEX_2D));
// _tH[}bg̐ݒ
pDevice->SetFVF(FVF_VERTEX_2D);
// eNX`̐ݒ
pDevice->SetTexture(0, g_pTextureRain);
for (int nCntRain = 0; nCntRain < MAX_RAIN; nCntRain++)
{
// |S̕`
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 4 * nCntRain, 2);
}
// eXg̐ݒ߂
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
}
| true |
854003ff335b49e3cc3e7a599bbc23024a6635a0 | C++ | TimHollies/ngraph.native | /src/layout.cc | UTF-8 | 5,344 | 2.703125 | 3 | [
"MIT"
] | permissive | //
// layout.cpp
// layout++
//
// Created by Andrei Kashcha on 5/21/15.
// Copyright (c) 2015 Andrei Kashcha. All rights reserved.
//
#include "layout.h"
#include <iostream>
#include <cmath>
#include <map>
Layout::Layout() :tree(settings) {}
void Layout::init(int* bodyIds, size_t bodyIdSize, int* links, long size) {
random = Random(42);
initBodies(bodyIds, bodyIdSize, links, size);
// Now the graph is initialized. Let's make sure we get
// good initial positions:
setDefaultBodiesPositions();
}
void Layout::loadPositionsFromArray(int *initialPositions) {
for (size_t i = 0; i < bodies.size(); ++i) {
Vector2 initialPos(initialPositions[i * 3 + 0], //+ Random::nextDouble(),
initialPositions[i * 3 + 1] //+ Random::nextDouble(),
);
bodies[i].setPos(initialPos);
}
}
void Layout::setDefaultBodiesPositions() {
size_t maxBodyId = bodies.size();
for (size_t i = 0; i < maxBodyId; ++i) {
bodies[i].setPos(Vector2(0,0));
// Body *body = &(bodies[i]);
// if (!body->positionInitialized()) {
// Vector2 initialPos(random.nextDouble() * log(maxBodyId) * 100,
// random.nextDouble() * log(maxBodyId) * 100);
// bodies[i].setPos(initialPos);
// }
// Vector2 *sourcePos = &(body->pos);
// // init neighbours position:
// for (size_t j = 0; j < body->springs.size(); ++j) {
// if (!bodies[body->springs[j]].positionInitialized()) {
// Vector2 neighbourPosition(
// sourcePos->x + random.next(settings.springLength) - settings.springLength/2,
// sourcePos->y + random.next(settings.springLength) - settings.springLength/2
// );
// bodies[j].setPos(neighbourPosition);
// }
// }
}
}
void Layout::initBodies(int* bodyIds, size_t bodyIdSize, int* links, long size) {
std::map<int, size_t> bodyMap;
bodies.reserve(bodyIdSize);
for (int i = 0; i < bodyIdSize; i++) {
bodies.push_back(Body(bodyIds[i]));
bodyMap[bodyIds[i]] = i;
}
// Now that we have bodies, let's add links:
for (int i = 0; i < size; i+=2) {
bodies[bodyMap.at(links[i])].springs.push_back(bodyMap.at(links[i+1]));
bodies[bodyMap.at(links[i+1])].incomingCount += 1;
}
// Finally, update body mass based on total number of neighbours:
for (size_t i = 0; i < bodies.size(); i++) {
Body *body = &(bodies[i]);
// TODO: Dividing by 2 rather than 3 due to changing to 2d only?
body->mass = 1 + (body->springs.size() + body->incomingCount)/3.0;
}
}
void Layout::setBodiesWeight(int *weights) {
// FIXME: Verify that size of the weights matches size of the bodies.
// Unfortunately current graph format does not properly store nodes without
// edges.
for (size_t i = 0; i < bodies.size(); i++) {
Body *body = &(bodies[i]);
body->mass = weights[i];
}
}
size_t Layout::getBodiesCount() {
return bodies.size();
}
bool Layout::step() {
accumulate();
double totalMovement = integrate();
// cout << totalMovement << " move" << endl;
return totalMovement < settings.stableThreshold;
}
void Layout::accumulate() {
tree.insertBodies(bodies);
#pragma omp parallel for
for (size_t i = 0; i < bodies.size(); i++) {
Body* body = &bodies[i];
body->force.reset();
tree.updateBodyForce(&(*body));
updateDragForce(&(*body));
}
#pragma omp parallel for
for (size_t i = 0; i < bodies.size(); i++) {
Body* body = &bodies[i];
updateSpringForce(&(*body));
}
}
double Layout::integrate() {
double dx = 0, tx = 0,
dy = 0, ty = 0,
timeStep = settings.timeStep;
//dx should be private or defined inside loop
//tx need to be reduction variable, or its value will be unpredictable.
#pragma omp parallel for reduction(+:tx,ty) private(dx,dy)
for (size_t i = 0; i < bodies.size(); i++) {
Body* body = &bodies[i];
double coeff = timeStep / body->mass;
body->velocity.x += coeff * body->force.x;
body->velocity.y += coeff * body->force.y;
double vx = body->velocity.x,
vy = body->velocity.y,
v = sqrt(vx * vx + vy * vy);
if (v > 1) {
body->velocity.x = vx / v;
body->velocity.y = vy / v;
}
dx = timeStep * body->velocity.x;
dy = timeStep * body->velocity.y;
body->pos.x += dx;
body->pos.y += dy;
tx += abs(dx); ty += abs(dy);
}
return (tx * tx + ty * ty)/bodies.size();
}
void Layout::updateDragForce(Body *body) {
body->force.x -= settings.dragCoeff * body->velocity.x;
body->force.y -= settings.dragCoeff * body->velocity.y;
}
void Layout::updateSpringForce(Body *source) {
Body *body1 = source;
for (size_t i = 0; i < source->springs.size(); ++i){
Body *body2 = &(bodies[source->springs[i]]);
double dx = body2->pos.x - body1->pos.x;
double dy = body2->pos.y - body1->pos.y;
double r = sqrt(dx * dx + dy * dy);
if (r == 0) {
dx = (random.nextDouble() - 0.5) / 50;
dy = (random.nextDouble() - 0.5) / 50;
r = sqrt(dx * dx + dy * dy);
}
double d = r - settings.springLength;
double coeff = settings.springCoeff * d / r;
body1->force.x += coeff * dx;
body1->force.y += coeff * dy;
body2->force.x -= coeff * dx;
body2->force.y -= coeff * dy;
}
}
| true |
fafb22ccb0389ec078985eeedc205bdbf21be5f7 | C++ | zeel01/ChristmasLights | /Twinkle.hpp | UTF-8 | 950 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef TWINKLE
#define TWINKLE
#include "Animate.hpp"
#include "MacroStrand.hpp"
#include "Star.hpp"
#include "AnimList.hpp"
struct Twinkle : public Animation {
MacroStrand* lights;
AnimList stars;
int density;
int pts;
int temp;
int delay;
int time;
Twinkle(MacroStrand* lts, int d) : lights(lts), density(d) {
pts = lights->totalPoints;
temp = 200;
delay = 0;
time = delay;
// stars = new Star*[density];
// genStarList();
}
boolean next() {
dimStars();
time--;
if (time > 0) return true;
time = delay;
addStar();
return true;
}
void dimStars() {
stars.runSequence();
}
void setColors() {
for (int i = 0; i < density; i++) {
}
}
void genStarList() {
while (stars.size < density) addStar();
}
void addStar() {
Serial.print(stars.size);
if (stars.size < density) {
stars.add(new Star(lights, random(0, pts), random(50, 100), HSV(30, 0, temp), 0, 1));
}
}
};
#endif | true |
aac6ee403d7345043fd0f69cb990d9a5c75b07bc | C++ | spiralgenetics/biograph | /modules/variants/scaffold.h | UTF-8 | 3,731 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include "modules/variants/assemble.h"
namespace variants {
class scaffold {
public:
struct extent {
aoffset_t offset = 0;
dna_slice sequence;
};
class iterator {
public:
iterator() = default;
iterator(const iterator&) = default;
iterator& operator=(const iterator&) = default;
dna_base operator*() const { return *m_extent_it; }
dna_const_iterator operator->() const { return m_extent_it; }
iterator& operator++() {
++m_extent_it;
++m_offset;
if (m_extent_it == m_scaffold_it->sequence.end()) {
++m_scaffold_it;
if (m_scaffold_it == m_scaffold->extents().end()) {
m_offset = m_scaffold->end_pos();
} else {
m_offset = m_scaffold_it->offset;
m_extent_it = m_scaffold_it->sequence.begin();
}
}
return *this;
}
aoffset_t offset() const { return m_offset; }
bool first_in_extent() const { return m_extent_it == m_scaffold_it->sequence.begin(); }
aoffset_t extent_end_offset() const {
CHECK(m_scaffold_it != m_scaffold->extents().end());
return m_scaffold_it->offset + aoffset_t(m_scaffold_it->sequence.size());
}
bool operator==(const iterator& rhs) const { return m_offset == rhs.m_offset; }
bool operator!=(const iterator& rhs) const { return !((*this) == rhs); }
// Description is debug info for where this skip comes from, in
// case of problems. TODO(nils): Remove "description" arg once we
// save debug symbols for release builds.
void skip_to(aoffset_t offset, const char* description);
private:
friend class scaffold;
iterator(const scaffold* s, std::vector<scaffold::extent>::const_iterator scaffold_it,
dna_const_iterator extent_it, aoffset_t offset)
: m_scaffold(s), m_scaffold_it(scaffold_it), m_extent_it(extent_it), m_offset(offset) {}
const scaffold* m_scaffold = nullptr;
std::vector<scaffold::extent>::const_iterator m_scaffold_it;
dna_const_iterator m_extent_it;
aoffset_t m_offset = 0;
};
scaffold() = default;
scaffold(dna_slice simple) { add(0, simple); }
scaffold(const dna_sequence& simple) { add(0, simple); }
scaffold(const std::vector<extent>& extents) : m_extents(extents) { m_end_pos = calc_end_pos(); }
scaffold(const std::vector<extent>& extents, aoffset_t end_pos)
: m_extents(extents), m_end_pos(end_pos) {
CHECK_GE(m_end_pos, calc_end_pos());
}
void add(aoffset_t offset, dna_slice seq);
void add(aoffset_t offset, const dna_sequence& seq) { add(offset, save_storage(seq)); }
const std::vector<extent>& extents() const { return m_extents; }
bool empty() const { return m_extents.empty(); }
scaffold subscaffold(aoffset_t start, aoffset_t len) const;
std::pair<dna_slice, dna_slice> split_extent_at(aoffset_t start) const;
bool is_simple() const;
dna_slice get_simple() const;
aoffset_t end_pos() const { return m_end_pos; }
void set_end_pos(aoffset_t new_end_pos);
friend std::ostream& operator<<(std::ostream& os, const scaffold& s) {
s.print_to(os);
return os;
}
void print_to(std::ostream& os) const;
std::string as_string() const { return subscaffold_str(0, end_pos()); }
std::string subscaffold_str(aoffset_t start, aoffset_t len) const;
unsigned shared_prefix_length(dna_slice seq) const;
scaffold rev_comp() const;
iterator begin() const;
iterator end() const;
void save_all_storage();
private:
aoffset_t calc_end_pos() const;
dna_slice save_storage(dna_slice seq);
void reverse_in_place();
std::vector<extent> m_extents;
aoffset_t m_end_pos = 0;
std::shared_ptr<std::list<dna_sequence>> m_seq_storage;
};
} // namespace variants
| true |
728090dd979c9ca098df7301bd7a571077d554c7 | C++ | FranklinBF/SocialForceModel | /vecmath/Vector2.h | UTF-8 | 4,573 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
Copyright (C) 1997,1998,1999
Kenji Hiranabe, Eiwa System Management, Inc.
This program is free software.
Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
conforming to the Java(TM) 3D API specification by Sun Microsystems.
Permission to use, copy, modify, distribute and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation. Kenji Hiranabe and Eiwa System Management,Inc.
makes no representations about the suitability of this software for any
purpose. It is provided "AS IS" with NO WARRANTY.
*/
#ifndef VECTOR2_H
#define VECTOR2_H
#include <VmUtil.h>
#include <Tuple2.h>
VM_BEGIN_NS
/**
* A 2 element vector that is represented by x,y coordinates.
* @version specification 1.1, implementation $Revision: 1.3 $, $Date: 1999/10/06 02:52:46 $
* @author Kenji hiranabe
*/
template<class T>
class Vector2 : public Tuple2<T> {
/*
* $Log: Vector2.h,v $
* Revision 1.3 1999/10/06 02:52:46 hiranabe
* Java3D 1.2 and namespace
*
* Revision 1.2 1999/05/26 00:59:37 hiranabe
* support Visual C++
*
* Revision 1.1 1999/03/04 11:07:09 hiranabe
* Initial revision
*
* Revision 1.1 1999/03/04 11:07:09 hiranabe
* Initial revision
*
*/
public:
/**
* Constructs and initializes a Vector2 from the specified xy coordinates.
* @param x the x coordinate
* @param y the y coordinate
*/
Vector2(T x, T y) : Tuple2<T>(x, y) { }
/**
* Constructs and initializes a Vector2 from the specified array.
* @param v the array of length 2 containing xy in order
*/
Vector2(const T v[]) : Tuple2<T>(v) { }
/**
* Constructs and initializes a Vector2 from the specified Tuple2.
* @param t1 the Tuple2 containing the initialization x y data
*/
Vector2(const Tuple2<T>& t1) : Tuple2<T>(t1) { }
/**
* Constructs and initializes a Vector2 to (0,0).
*/
Vector2(): Tuple2<T>() { }
/**
* Computes the dot product of the this vector and vector v1.
* @param v1 the other vector
*/
T dot(const Vector2& v1) const {
return this->x*v1.x + this->y*v1.y;
}
/**
* Returns the squared length of this vector.
* @return the squared length of this vector
*/
T lengthSquared() const {
return this->x*this->x + this->y*this->y;
}
/**
* Returns the length of this vector.
* @return the length of this vector
*/
T length() const {
return VmUtil<T>::sqrt(lengthSquared());
}
/**
* Normalizes this vector in place.
*/
void normalize() {
T d = length();
// zero-div may occur.
this->x /= d;
this->y /= d;
}
/**
* Sets the value of this vector to the normalization of vector v1.
* @param v1 the un-normalized vector
*/
void normalize(const Vector2& v1) {
set(v1);
normalize();
}
/**
* Returns the angle in radians between this vector and
* the vector parameter; the return value is constrained to the
* range [0,PI].
* @param v1 the other vector
* @return the angle in radians in the range [0,PI]
*/
T angle(const Vector2& v1) const {
// stabler than acos
return VmUtil<T>::abs(VmUtil<T>::atan2(this->x*v1.y - this->y*v1.x , dot(v1)));
}
// copy constructor and operator = is made by complier
Vector2& operator=(const Tuple2<T>& t) {
Tuple2<T>::operator=(t);
return *this;
}
};
/*
* 0. value_type typedef added
* 1. copy constructo, oeprator = are delegated to compiler
* 4. typdef value type
* 7. typedefs for <float>, <double>
* removed construction from Vector2f
*/
VM_END_NS
template <class T>
inline
VM_VECMATH_NS::Vector2<T> operator*(T s, const VM_VECMATH_NS::Vector2<T>& t1) {
return operator*(s, (const VM_VECMATH_NS::Tuple2<T>&)t1);
}
#ifdef VM_INCLUDE_IO
template <class T>
inline
VM_IOSTREAM_STD::ostream& operator<<(VM_IOSTREAM_STD::ostream& o, const VM_VECMATH_NS::Vector2<T>& t1) {
return operator<<(o, (const VM_VECMATH_NS::Tuple2<T>&)t1);
}
#endif
VM_BEGIN_NS
typedef Vector2<double> Vector2d;
typedef Vector2<float> Vector2f;
VM_END_NS
#endif /* VECTOR2_H */
| true |
a526bbbf0f61c8198122abfb0f1e73c507bf50da | C++ | AbsoluteNeutral/ZEngine | /ZeroGraphicEngine/ZeroGraphicEngine/HashString.cpp | UTF-8 | 4,108 | 2.6875 | 3 | [] | no_license |
#include "stdafx.h"
#include "HashString.h"
#include "Logging.h"
#include <unordered_map>
static std::unordered_map<size_t, std::string> GLOBAL_HASH_STRING_TABLE;
static std::unordered_map<size_t, std::string> GLOBAL_HASH_STRING_TABLE2;
static std::unordered_map<size_t, std::string> GLOBAL_HASH_STRING_TABLE3;
size_t GenerateHash(const std::string& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE.emplace(hashedString, string_);
return hashedString;
}
size_t GenerateHash(std::string&& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE.emplace(hashedString, string_);
return hashedString;
}
size_t GenerateHash2(std::string&& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE2.emplace(hashedString, string_);
return hashedString;
}
size_t GenerateHash2(const std::string& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE2.emplace(hashedString, string_);
return hashedString;
}
size_t GenerateHash3(std::string&& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE2.emplace(hashedString, string_);
return hashedString;
}
size_t GenerateHash3(const std::string& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
GLOBAL_HASH_STRING_TABLE3.emplace(hashedString, string_);
return hashedString;
}
size_t GetHashFromString(const std::string& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
// Search lookup table for the hashed string
auto it = GLOBAL_HASH_STRING_TABLE.find(hashedString);
//If the hashedString is not registered
if (it == GLOBAL_HASH_STRING_TABLE.end())
GenerateHash(string_);
// ErrorMsg(std::string{ "Texture String name not found" + string_ }.c_str());
return hashedString;
}
size_t GetHashFromString2(const std::string& string_) {
static std::hash<std::string> hasher;
size_t hashedString = hasher(string_); // Compute the hash for the string
// Search lookup table for the hashed string
auto it = GLOBAL_HASH_STRING_TABLE2.find(hashedString);
//If the hashedString is not registered
if (it == GLOBAL_HASH_STRING_TABLE2.end())
GenerateHash2(string_);
// ErrorMsg(std::string{ "Texture String name not found" + string_ }.c_str());
return hashedString;
}
const std::string& GetStringFromHash(size_t hash_) {
#if defined(_DEBUG) || defined(_EDITOR_ON)
auto it = GLOBAL_HASH_STRING_TABLE.find(hash_);
// If it is not found, return the empty string
if (it == GLOBAL_HASH_STRING_TABLE.end())
ErrorMsg(std::string{ "Hash number not found" }.c_str());
return it->second;
#else
return GLOBAL_HASH_STRING_TABLE[hash_];
#endif
}
const std::string& GetStringFromHash2(size_t hash_) {
#if defined(_DEBUG) || defined(_EDITOR_ON)
auto it = GLOBAL_HASH_STRING_TABLE2.find(hash_);
// If it is not found, return the empty string
if (it == GLOBAL_HASH_STRING_TABLE2.end())
ErrorMsg(std::string{ "Hash number not found" }.c_str());
return it->second;
#else
return GLOBAL_HASH_STRING_TABLE[hash_];
#endif
}
//void MergeHashTables()
//{
// GLOBAL_HASH_STRING_TABLE.insert(GLOBAL_HASH_STRING_TABLE2.begin(), GLOBAL_HASH_STRING_TABLE2.end());
// GLOBAL_HASH_STRING_TABLE.insert(GLOBAL_HASH_STRING_TABLE3.begin(), GLOBAL_HASH_STRING_TABLE3.end());
//
// GLOBAL_HASH_STRING_TABLE2.clear();
// GLOBAL_HASH_STRING_TABLE2.rehash(0);
// GLOBAL_HASH_STRING_TABLE3.clear();
// GLOBAL_HASH_STRING_TABLE3.rehash(0);
//}
| true |
55b346529db4ac614aa8887e925d48c331c72550 | C++ | nodamushi/nsvd-reader | /include/nodamushi/svd/normalized/Enumeration.hpp | UTF-8 | 3,493 | 2.75 | 3 | [
"CC0-1.0"
] | permissive | /*!
@brief Normalized enumerationValues element
@file nodamushi/svd/normalized/Enumeration.hpp
*/
/*
* These codes are licensed under CC0.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
#ifndef NODAMUSHI_SVD_NORMALIZED_ENUMERATION_HPP
#define NODAMUSHI_SVD_NORMALIZED_ENUMERATION_HPP
# include <string>
# include "nodamushi/svd/EnumUsage.hpp"
# include "nodamushi/svd/normalized/EnumeratedValue.hpp"
# include "nodamushi/svd/normalized/derived_from_helper.hpp"
namespace nodamushi{
namespace svd{
namespace normalized{
/**
* @brief normalized <enumeratedValues> element. iterable
* @see http://www.keil.com/pack/doc/CMSIS/SVD/html/elem_registers.html#elem_enumeratedValues
* @see nodamushi::svd::Enumeration
*/
template<typename STRREF>struct Enumeration
{
using Field = ::nodamushi::svd::normalized::Field<STRREF>;
using EnumeratedValue = ::nodamushi::svd::normalized::EnumeratedValue<STRREF>;
//! @brief <name>
std::string name;
//! @brief <headerEnumName>
STRREF headerEnumName;
//! @brief <usage>
EnumUsage usage;
//! @brief <enumeratedValue> list
std::vector<EnumeratedValue> enumeratedValue;
Enumeration()=default;
Enumeration(Enumeration&&)=default;
Enumeration(const Enumeration&)=default;
template<typename T>
Enumeration(const T& n): // don't change name
name(n.name),
__NORMALIZED_DERIVED_FROM(headerEnumName),
__NORMALIZED_DERIVED_FROM(usage),
enumeratedValue()
{
__NORMALIZED_DERIVED_FROM_HELPER(enumeratedValue);
if(enumeratedValue){
const auto& v = *enumeratedValue;
auto& d=this->enumeratedValue;
d.reserve(v.size());
for(const auto& c:v)
d.emplace_back(c);
sort();
}
}
//--------------------------------------------------------------
/**
* @brief sort enumeratedValue by enumratedValue.value.
* @note enumratedValue whose isDefault member is true will be last
*/
void sort()
{
std::sort(enumeratedValue.begin(),enumeratedValue.end());
}
/**
* @brief <enumeratedValue> is empty
* @return <enumeratedValue> is empty
*/
bool empty()const noexcept{return enumeratedValue.empty();}
/**
* @brief count of <enumeratedValue>
* @return count of <enumeratedValue>
*/
size_t size()const noexcept{return enumeratedValue.size();}
/**
* @brief count of <enumeratedValue>
* @return count of <enumeratedValue>
*/
size_t length()const noexcept{return enumeratedValue.size();}
using iterator = typename std::vector<EnumeratedValue>::iterator;
using const_iterator = typename std::vector<EnumeratedValue>::const_iterator;
//! @brief enumeratedValue iterator.
iterator begin() noexcept{return enumeratedValue.begin();}
//! @brief enumeratedValue iterator.
iterator end() noexcept{return enumeratedValue.end();}
//! @brief enumeratedValue iterator.
const_iterator begin()const noexcept{return enumeratedValue.begin();}
//! @brief enumeratedValue iterator.
const_iterator end()const noexcept{return enumeratedValue.end();}
};
//---------- Visitor --------------------
__NX_NORM_HANDLE_VISIT(Enumeration)
{
namespace nv = ::nodamushi::visitor;
using r = nv::result;
r ret;
ret = CONTROLLER::apply(t.enumeratedValue,v);
if(ret == r::BREAK)return ret;
return r::CONTINUE;
}};
//--------------------------------------------
}}} // end namespace svd
#endif // NODAMUSHI_SVD_NORMALIZED_ENUMERATION_HPP
| true |
7e5b27bacc98d077a36badaae6f6f605f56a7b9a | C++ | wyaadarsh/LeetCode-Solutions | /C++/1518-Water-Bottles/soln.cpp | UTF-8 | 424 | 2.625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int numWaterBottles(int nfulls, int exchange) {
int nempties = 0;
int ndrinks = 0;
while(nfulls > 0) {
nempties += nfulls;
ndrinks += nfulls;
nfulls = 0;
if(nempties >= exchange) {
nfulls += nempties / exchange;
nempties %= exchange;
}
}
return ndrinks;
}
};
| true |
5236a1c79382cdc52793dd82dc5f88e7096effc7 | C++ | acctouhou/Introduction-to-Computers-and-Programming | /HW/HW7/1.cpp | UTF-8 | 537 | 2.859375 | 3 | [] | no_license | #include <stdio.h>
#include <ctime>
#include <cstdlib>
int main(){
int die,temp_1=0,temp_2=0,temp_3=0,temp_4=0,temp_5=0,temp_6=0;
srand(time(NULL));
for(int i=1;i<=6000;i++){
die=rand()%6+1;
switch(die){
case 1:
temp_1++;
break;
case 2:
temp_2++;
break;
case 3:
temp_3++;
break;
case 4:
temp_4++;
break;
case 5:
temp_5++;
break;
case 6:
temp_6++;
break;
}
}
printf("1=%d 2=%d 3=%d 4=%d 5=%d 6=%d ",temp_1,temp_2,temp_3,temp_4,temp_5,temp_6);
return 0;
}
| true |
485a0233d41ac99881b7a07004ed4fa9b5ea8e15 | C++ | lukarolak/GameEngine | /EngineCode/Synchronization/SynchronizationObjectsGroup.cpp | UTF-8 | 2,129 | 2.71875 | 3 | [] | no_license | #include <Synchronization/SynchronizationObjects.h>
#include <Debuging/Assert.h>
#include <Synchronization/SynchronizationObjectsGroup.h>
#include <Debuging/Assert.h>
void CSynchronizationObjects::CreateSynchronnizationObjects(const VkDevice& Device)
{
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
VkResult cratedImageAvailabeSemaphore = vkCreateSemaphore(Device, &semaphoreInfo, nullptr, &m_ImageAvailableSemaphore);
VkResult cratedRenderFinishedSemaphore = vkCreateSemaphore(Device, &semaphoreInfo, nullptr, &m_RenderFinishedSemaphore);
VkResult createdInFlightFence = vkCreateFence(Device, &fenceInfo, nullptr, &m_InFlightFence);
ENG_ASSERT(cratedImageAvailabeSemaphore == VK_SUCCESS && cratedRenderFinishedSemaphore == VK_SUCCESS && createdInFlightFence == VK_SUCCESS, "failed to create synchronization objects for a frame!");
m_SynchronizationObjectsCreated = true;
}
const VkSemaphore& CSynchronizationObjects::GetImageAvailableSemaphore() const
{
ENG_ASSERT(m_SynchronizationObjectsCreated, "Semaphore not created");
return m_ImageAvailableSemaphore;
}
const VkSemaphore& CSynchronizationObjects::GetRenderFinishedSemaphore() const
{
ENG_ASSERT(m_SynchronizationObjectsCreated, "Semaphore not created");
return m_RenderFinishedSemaphore;
}
const VkFence& CSynchronizationObjects::GetInFlightFence() const
{
return m_InFlightFence;
}
const VkFence& CSynchronizationObjects::GetImageInFlightFence() const
{
return m_ImageInFlight;
}
void CSynchronizationObjects::SetImageInFlight(const VkFence& Fence)
{
m_ImageInFlight = Fence;
}
void CSynchronizationObjects::Release(const VkDevice& Device)
{
vkDestroySemaphore(Device, m_RenderFinishedSemaphore, nullptr);
vkDestroySemaphore(Device, m_ImageAvailableSemaphore, nullptr);
vkDestroyFence(Device, m_InFlightFence, nullptr);
m_ImageInFlight = VK_NULL_HANDLE;
}
void CSynchronizationObjects::SetImageInUse()
{
m_ImageInFlight = m_InFlightFence;
}
| true |
0eac5e6ccad5ca9d056feb23533e8e9d24f2fda6 | C++ | jewon/2018-1_DS | /DS_Lab_Assignment/Application.h | UHC | 1,235 | 2.75 | 3 | [] | no_license | #ifndef _APPLICATION_H
#define _APPLICATION_H
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "AVL.h"
#include "ConferenceType.h"
#include "MoreFeatures.h"
#include "Admin.h"
#define FILENAMESIZE 1024
/**
* мȸ ø̼ Ŭ
*/
class Application
{
public:
/**
* ⺻
*/
Application()
{
m_Command = 0;
PaperIndex = NULL;
//AuthorIndex = NULL;
}
/**
* Ҹ
*/
~Application()
{
PaperIndex = NULL;
//AuthorIndex = NULL;
}
/**
* @brief α
* @pre α
* @post α
*/
void Run();
/**
* @brief ȭ鿡 ϰ Է¹´
* @pre .
* @post .
* @return Է
*/
int GetCommand();
/**
* @brief ߰ Ŭ Ѵ.
* @pre .
* @post .
* @return .
*/
void RunMoreFeatures();
/**
* @brief Ѵ.
* @pre .
* @post .
* @return .
*/
void RunAdmin();
private:
BinarySearchTree<ConferenceType> m_List; ///< item list.
BinarySearchTree<PaperType> * PaperIndex;
int m_Command; ///< current command number.
};
#endif // _APPLICATION_H | true |
b80f27bb66001e09d44ee3611e86f4c77840f6cd | C++ | github188/DotaGame | /GameServer/MySql/ConnectionBuilder.h | UTF-8 | 822 | 2.859375 | 3 | [] | no_license | #ifndef _MYSQL_CONNECTION_BUILDER_H_
#define _MYSQL_CONNECTION_BUILDER_H_
#include <string>
namespace MySql
{
#ifdef SetPort
#undef SetPort
#endif
class ConnectionBuilder
{
public:
ConnectionBuilder();
~ConnectionBuilder();
void SetHostName(const std::string& hostname);
const std::string& GetHostName();
void SetDbName(const std::string& dbname);
const std::string& GetDbName();
void SetUser(const std::string& user);
const std::string& GetUser();
void SetPwd(const std::string& pwd);
const std::string& GetPwd();
void SetPort(unsigned short port);
unsigned short GetPort();
std::string GetConnectionString();
private:
std::string m_hostname;
std::string m_dbname;
std::string m_user;
std::string m_pwd;
unsigned short m_port;
};
}; // namespace MySql
#endif // _MYSQL_CONNECTION_BUILDER_H_ | true |
ba71ae3175e93f2791eab7fe83ed154e9e4ee685 | C++ | juli27/basaltcpp | /libruntime/basalt/gfx/device_state_cache.h | UTF-8 | 1,945 | 2.5625 | 3 | [] | no_license | #pragma once
#include <basalt/api/gfx/backend/types.h>
#include <basalt/api/shared/color.h>
#include <basalt/api/math/matrix4x4.h>
#include <basalt/api/base/enum_array.h>
#include <basalt/api/base/types.h>
#include <array>
#include <optional>
namespace basalt::gfx {
struct DeviceStateCache final {
DeviceStateCache() noexcept = default;
auto update(Pipeline) noexcept -> bool;
auto update(VertexBuffer, u64 offset) noexcept -> bool;
auto update(IndexBuffer) noexcept -> bool;
auto update(u8 slot, Sampler) noexcept -> bool;
auto update(u8 slot, Texture) noexcept -> bool;
auto update(TransformState, const Matrix4x4f32&) noexcept -> bool;
auto update_ambient_light(const Color&) noexcept -> bool;
auto update(const Color& diffuse, const Color& ambient, const Color& emissive,
const Color& specular, f32 specularPower) noexcept -> bool;
auto update_fog_parameters(const Color&, f32 start, f32 end, f32 density)
-> bool;
auto update_blend_constant(const Color&) -> bool;
auto update_reference_alpha(u8) -> bool;
private:
struct Material final {
Color diffuse;
Color ambient;
Color emissive;
Color specular;
f32 specularPower {};
};
struct FogParams final {
Color color;
f32 start {};
f32 end {};
f32 density {};
};
using MaybeMatrix = std::optional<Matrix4x4f32>;
EnumArray<TransformState, MaybeMatrix, TRANSFORM_STATE_COUNT> mTransforms {};
std::optional<Color> mAmbientLight;
std::optional<Material> mMaterial;
std::optional<FogParams> mFogParams;
std::optional<Color> mBlendConstant;
std::optional<u8> mReferenceAlpha;
Pipeline mBoundPipeline {Pipeline::null()};
VertexBuffer mBoundVertexBuffer {VertexBuffer::null()};
u64 mVertexBufferOffset {0ull};
IndexBuffer mBoundIndexBuffer {IndexBuffer::null()};
std::array<Sampler, 8> mBoundSamplers {};
std::array<Texture, 8> mBoundTextures {};
};
} // namespace basalt::gfx
| true |
486735c05729fd52b0d6237c1825d7d81dcd8ed1 | C++ | KyleLeongZ/Operating-System | /lock_and_multithreading/p2_threads.cpp | UTF-8 | 7,142 | 2.8125 | 3 | [] | no_license | #include "p2_threads.h"
#include "utils.h"
extern pthread_cond_t cond;
extern pthread_mutex_t mutex;
extern int gender_in_que[2];
extern int size_each;
extern int queue_num;
extern int room_gender;
extern int man_used;
extern int woman_used;
extern int man_in_room;
extern int woman_in_room;
extern int occupied_room;
extern long start_time;
extern struct timeval t_global_start;
extern ListNode *head;
extern RoomListNode *room_head;
extern void removeNode(ListNode *preNode);
void displayList(ListNode *node);
char* gender_names[] = {"man", "woman"};
char* gender_states[] = {"MenPresent", "WomenPresent"};
void *roomThreadfunc(void *param){
RoomListNode *cur_room = room_head;
int status;
while(1){
if(head->next != NULL){
ListNode *cur = head;
if(room_gender != -1){
while(cur->next != NULL && cur->next->person.get_gender() != room_gender){
cur = cur->next;
}
}
if(cur->next != NULL){
// printf("Found a dude\n");
// displayRoomList(room_head);
while(cur_room != NULL && cur_room->restroom.status != 0){
if(cur_room->next != NULL)
cur_room = cur_room->next;
else
cur_room = room_head->next;
}
Person p = cur->next->person;
int gender = p.get_gender();
// printf("A good person: %d\n", cur_room->restroom.status);
// displayRoomList(room_head);
if(room_gender != -1 && room_gender != gender)
continue;
removeNode(cur);
if(gender == 0)
man_wants_to_enter(cur_room);
else
woman_wants_to_enter(cur_room);
gettimeofday(&t_global_start, NULL);
int cur_time = (t_global_start.tv_usec - start_time) / 1000;
int delay = rand()%7 + 3;
p.set_time(delay);
int woman_num = woman_in_room;
int man_num = man_in_room;
printf("[%d ms][Queue], Send (%s) into the fitting room (Stay %d ms), Status: Total: %d (Men: %d, Women: %d)\n",
cur_time, gender_names[gender], p.get_time(), occupied_room, man_num, woman_num);
printf("[%d ms][fitting room] (%s) goes into the fitting room, State is (%s): Total: %d (Men: %d, Women: %d)\n",
cur_time, gender_names[gender], gender_states[gender], occupied_room, man_num, woman_num);
// printf("room status changed %d\n", cur_room->restroom.status);
pthread_t room_thread;
threadParam *tp = (threadParam *) malloc(sizeof(threadParam));;
tp->rr = &(cur_room->restroom);
tp->person = &p;
if(pthread_create(&room_thread, NULL, roomThread, tp)) {
fprintf(stderr, "Error creating thread\n");
}
}
}
if(man_used <= 0 && woman_used <= 0){
printf("All people used\n");
break;
}
}
}
void *roomThread(void *param)
{
// threadParam *thread_args = (threadParam *) malloc(sizeof(threadParam));
threadParam *p = (threadParam*)param;
int gender = p->person->get_gender();
int wait_time = p->person->get_time();
usleep(MSEC(wait_time));
pthread_mutex_lock(&mutex);
p->rr->status = 0;
pthread_mutex_unlock(&mutex);
if(gender == 0)
man_leaves();
else
woman_leaves();
// gettimeofday(&t_global_start, NULL);
// cur_time = (t_global_start.tv_usec - start_time) / 1000;
// printf("[%d ms][fitting rooms], (%s) has left the fitting room, Status: Total: %d (Men: %d, Women: %d)\n",
// cur_time, gender_names[gender], man_used + woman_used,man_used, woman_used);
// printf("Set status %d\n", p->rr->status);
// displayRoomList(room_head);
}
void *queueThreadfunc(void *param){
ListNode *pointer = head;
int status;
srand(time(0));
while(gender_in_que[0] < size_each || gender_in_que[1] < size_each){
int gender = rand() % 2;
Person p;
if(gender_in_que[gender] >= size_each)
gender = (gender == 0) ? 1 : 0;
p.set_gender(gender);
status = pthread_mutex_lock(&mutex);
add_node(p);
gender_in_que[gender]++;
status = pthread_mutex_unlock(&mutex);
gettimeofday(&t_global_start, NULL);
int cur_time = (t_global_start.tv_usec - start_time) / 1000;
printf("[%d ms][Input] A person (%s) goes into the queue\n", cur_time, gender_names[gender]);
// displayList(head);
int wait_time = rand() % 3 + 1;
// for (int i = 0; i < wait_time; ++i)
// {
// /* code */
// usleep(MSEC(100));
// }
usleep(MSEC(wait_time));
}
}
void displayList(ListNode *node){
if(node == NULL)
return;
ListNode *pt = node->next;
cout<<"Display:"<<endl;
int i = 0;
while(pt != NULL){
cout<< pt->person.get_gender() <<", ";
pt = pt->next;
}
cout<<"\n"<<endl;
return;
}
void displayRoomList(RoomListNode *node){
if(node == NULL)
return;
RoomListNode *pt = node->next;
cout<<"Display:"<<endl;
int i = 0;
while(pt != NULL){
cout<< pt->restroom.status <<", ";
pt = pt->next;
}
cout<<"\n"<<endl;
return;
}
void man_wants_to_enter(RoomListNode *cur_room){
pthread_mutex_lock(&mutex);
occupied_room ++;
if(room_gender == -1){
room_gender = 0;
}
man_in_room++;
gettimeofday(&t_global_start, NULL);
int cur_time = (t_global_start.tv_usec - start_time) / 1000;
cur_room->restroom.status = 1;
pthread_mutex_unlock(&mutex);
return;
}
void woman_wants_to_enter(RoomListNode *cur_room){
pthread_mutex_lock(&mutex);
occupied_room ++;
if(room_gender == -1){
room_gender = 1;
}
woman_in_room++;
cur_room->restroom.status = 1;
pthread_mutex_unlock(&mutex);
return;
}
void man_leaves(){
printf("wome number %d\n", woman_in_room);
pthread_mutex_lock(&mutex);
gettimeofday(&t_global_start, NULL);
int cur_time = (t_global_start.tv_usec - start_time) / 1000;
// printf("man number %d\n", man_in_room);
occupied_room--;
man_in_room--;
char* state;
man_used--;
pthread_mutex_unlock(&mutex);
if(occupied_room == 0){
room_gender = -1;
state = "empty";
printf("[%d ms][fitting rooms], (Man) has left the fitting room, Status is changed, status is %s Total: %d (Men: %d, Women: %d)\n",
cur_time, state, occupied_room, 0, 0);
}else{
// int temp = occupied_room;
printf("[%d ms][fitting rooms], (Man) has left the fitting room, Status: %s, Total: %d (Men: %d, Women: 0)\n",
cur_time, gender_states[room_gender], occupied_room, occupied_room);
}
return;
}
void woman_leaves(){
// printf("wome number %d\n", woman_in_room);
pthread_mutex_lock(&mutex);
int temp = occupied_room - 1;
occupied_room--;
woman_in_room--;
int women_num = woman_in_room - 1;
int man_num = man_in_room;
char* state;
gettimeofday(&t_global_start, NULL);
int cur_time = (t_global_start.tv_usec - start_time) / 1000;
woman_used--;
pthread_mutex_unlock(&mutex);
if(occupied_room == 0){
room_gender = -1;
state = "empty";
printf("[%d ms][fitting rooms], (Woman) has left the fitting room, Status is changed, status is %s, Total: %d (Men: %d, Women: %d)\n",
cur_time, state, occupied_room, 0, 0);
}else{
cout <<"["<< cur_time <<"ms][fitting rooms], (Woman) has left the fitting room, Status:"<< gender_states[room_gender]<<", Total: "<< occupied_room <<" (Men: 0, Women:"<< occupied_room <<")"<<endl;
}
return;
}
void add_node(Person p){
ListNode *cur = head;
while(cur->next != NULL){
cur = cur->next;
}
cur->next = new ListNode;
cur->next-> person = p;
}
| true |
6f2b6a64225456d94eb1c52f83b4ab010aaade36 | C++ | AlexLiuyuren/Graphics | /Graphics/point.h | UTF-8 | 359 | 2.609375 | 3 | [] | no_license | #pragma once
#include "gl/glut.h"
#include "common.h"
class Point {
public:
int x;
int y;
Point(int x, int y) : x(x), y(y) {};
Point() {};
void draw(int color = -1);
Point add(int dx, int dy) const;
Point rotate(const Point &p, double theta) const;
Point scale(const Point &p, double frac) const;
bool valid();
};
typedef std::vector<Point> Points; | true |
1c7801088fcc678c24f32e158afe53b20c1ced1a | C++ | Ritikkumar992/DSA-Fundamental- | /C++ Code With Harry/tut15.cpp | UTF-8 | 775 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
//Function prototype
//type function_name(arguments);
// int sum(int a, int b);---->> Acceptable
// int sum(int a, b);---->>not acceptacle
// int sum(int,int);---->>Acceptable
int sum(int a, int b);
void g (void);
int main(){
int num1,num2;
cout<<"Enter first number"<<endl;
cin>>num1;
cout<<"Enter second number "<<endl;
cin>>num2;
cout<<"The sum is "<<sum(num1,num2);
//num1 and num2 are actaul parameter
//g();
return 0;
}
int sum(int a, int b){
//formal parameter a & b will be taking
// values from acual parameter num1 &num2.
int c = a+b;
return c;
}
void g(){
cout<<"\n Hello, Good morning ";
}
| true |
bdfbfc6fed9845bc66226e590b905cc66290d823 | C++ | shubhamguptaji/CPP | /try_throw.cpp | UTF-8 | 200 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
main()
{
int x,y,z;
cin>>x>>y>>z;
try
{
if(x-y!=0)
{
cout<<"Result :"<<z/(x-y);
}
else
throw(x-y);
}
catch(int i)
{
cout<<"Exception Caught\n";
}
cout<<"end";
} | true |
beb19e3b22c91bce0eb9a9a8b87f411c21acbdd7 | C++ | 3232731490/CPP | /数组/输入一个字符串,逆序打印.cpp | UTF-8 | 788 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
//字符数组。。。。。
/*char str[80];
cout << "请输入您要输入几个字符:" << endl;
int n;
cin >> n;
cout<<"请输入一个有"<<n<<"个字符的字符串:"<<endl;
for (int i = 0; i < n; i++)
cin >> str[i];
cout << "逆序排列前为:" << endl;
for (int i = 0; i < n; i++)
cout << str[i];
for (int i = 0, j = n - 1; i < j; i++,j--)
{
char temp = str[i];
str[i] = str[j];
str[j]=temp;
}
cout << "逆序排列后为:" << endl;
for (int i = 0; i < n; i++)
cout << str[i];*/
//string
char str[80];
cout << "请输入一个字符串" << endl;
cin >> str;
int a = strlen(str);
for (int i = a - 1; i >= 0; i--)
cout << str[i];
system("pause");
return 0;
}
| true |
1ba0c3f9d69bc7a05f32af6d9d21aa85cfd7cab0 | C++ | BalitskyIvan/CPP-modules | /module 05/ex03/RobotomyRequestForm.cpp | UTF-8 | 737 | 2.71875 | 3 | [] | no_license | //
// Created by Lonmouth Mallador on 1/20/21.
//
#include "RobotomyRequestForm.hpp"
RobotomyRequestForm::RobotomyRequestForm(const std::string &name) : Form(name, 72, 45) {}
Form *RobotomyRequestForm::clone(std::string &name) const {
return new RobotomyRequestForm(name);
}
bool RobotomyRequestForm::beSigned(Bureaucrat &bureaucrat) {
if (bureaucrat.getGrade() > getSignGrade())
throw GradeTooLowException();
else if (!getIsSigned()) {
if (std::rand() % 2 == 1) {
std::cout << getName() + " has been robotomized successfully" << std::endl;
Form::beSigned(bureaucrat);
return true;
} else
std::cout << getName() + " wasn't robotomized :(" << std::endl;
}
return false;
}
RobotomyRequestForm::~RobotomyRequestForm() {
}
| true |
7590564fe7055d506958548dfd4585696997a077 | C++ | Matt-Ceck63/GestureControlledCar | /CarReceiverCode/CarReceiverCode.ino | UTF-8 | 6,883 | 2.53125 | 3 | [] | no_license | #include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(7, 8);
const uint64_t writing_pipe = 0xF0F0F0F0E1LL;
//DRV-8833 inputs
// Left motor
int in1 = 3;
int in2 = 5;
// Right motor
int in3 = 6;
int in4 = 9;
int speedLeft = 0;
int speedRight = 0;
void setup() {
Serial.begin(9600);
printf_begin();
Serial.println("ROLE: receive\n\r");
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
radio.begin();
//radio.setAutoAck(false);
radio.setRetries(15, 15);
radio.openReadingPipe(1, writing_pipe);
radio.setPALevel(RF24_PA_LOW);
radio.startListening();
radio.printDetails();
}
void loop() {
if (radio.available())
{
float yprDegrees[3];
bool done = false;
while (!done)
{
done = radio.read(&yprDegrees, sizeof(yprDegrees));
//Serial.println("Received data");
float pitch = yprDegrees[1];
float roll = yprDegrees[2];
bool moving = false;
bool forward = false;
bool inplace = false;
// Serial.print("ypr\t");
// Serial.print(yprDegrees[0]);
// Serial.print("\t");
// Serial.print(yprDegrees[1]);
// Serial.print("\t");
// Serial.println(yprDegrees[2]);
//uint16_t t1 = micros();
if ( pitch < -10 ) // Forward
{
moving = true;
forward = true;
speedLeft = map(pitch, -10, -30, 0, 255);
speedRight = map(pitch, -10, -30, 0, 255);
}
else if ( pitch > 10 )
{
moving = true;
forward = false;
speedLeft = map(pitch, 10, 30, 0, 255);
speedRight = map(pitch, 10, 30, 0, 255);
}
else
{
moving = false; // Redundant but helps understand
speedLeft = 0;
speedRight = 0;
}
if ( roll > 20 ) // Right
{
moving = true;
int turn = map(roll, 20, 50, 0, 255);
speedLeft = speedLeft + turn;
speedRight = speedRight - turn;
if ( speedLeft > 255 ) speedLeft = 255;
if ( speedRight < 0 ) speedRight = 0;
}
else if ( roll < -20 ) // Left
{
moving = true;
int turn = map(roll, -20, -50, 0, 255);
speedLeft = speedLeft - turn;
speedRight = speedRight + turn;
if ( speedLeft < 0 ) speedLeft = 0;
if ( speedRight > 255 ) speedRight = 255;
}
if ( pitch > -10 && pitch < 10 ) inplace = true;
if ( speedLeft < 80 && moving ) speedLeft = 80;
if ( speedRight < 80 && moving ) speedRight = 80;
if ( speedLeft > 255 ) speedLeft = 255;
if ( speedRight > 255) speedRight = 255;
if ( inplace )
{
if ( roll > 0 )
{
digitalWrite(in1, LOW);
analogWrite(in2, speedLeft);
digitalWrite(in3, LOW);
analogWrite(in4, speedRight);
}
else
{
analogWrite(in1, speedLeft);
digitalWrite(in2, LOW);
analogWrite(in3, speedRight);
digitalWrite(in4, LOW);
}
}
else
{
if ( forward )
{
digitalWrite(in1, LOW);
analogWrite(in2, speedLeft);
analogWrite(in3, speedRight);
digitalWrite(in4, LOW);
}
else
{
analogWrite(in1, speedLeft);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
analogWrite(in4, speedRight);
}
}
//uint16_t t2 = micros();
//Serial.println(t2-t1);
Serial.println(speedLeft);
Serial.println(speedRight);
//Serial.println(turn);
//delay(50);
}
//delay(150);
}
}
//if ((pitch < 10) && (pitch > -10))
// {
// if (roll > 20) {
// forward = false; backwards = false, right_in_place = true, left_in_place = false;
// turnLeft = map(roll, 20, 50, 0, 255);
// turnRight = map(roll, 20, 50, 0, 255);; //map(roll, 20, 50, 0, -255);
// }
// else if (roll < -20) {
// forward = false; backwards = false, right_in_place = false, left_in_place = true;
// turnLeft = map(roll, -20, -50, 0, 255); //map(roll, 20, 50, 0, -255);
// turnRight = map(roll, -20, -50, 0, 255);
// }
// }
// else if (roll > 60 || roll < -60)
// {
// if(forward)
// {
// if (roll > 0) {
// turnLeft = 255;
// turnRight = 0; //map(roll, 20, 50, 0, -255);
// }
// else if (roll < 0) {
// turnLeft = 0; //map(roll, 20, 50, 0, -255);
// turnRight = 255;
// }
// }
// else if (backwards)
// {
// if (roll > 0) {
// turnLeft = 0; //map(roll, 20, 50, 0, -255);
// turnRight = 255;
// }
// else if (roll < 0) {
// turnLeft = 255;
// turnRight = 0; //map(roll, 20, 50, 0, -255);
// }
// }
// }
// else if (roll > 20 && roll < 60) // Right
// {
// forward = true; // Overwritten if its not turning in place
// turnLeft = map(roll, 20, 50, 0, 125);
// turnRight = -turnLeft; //map(roll, 20, 50, 0, -255);
// }
// else if (roll > -60 && roll < -20) //Left
// {
// forward = true; // Overwritten if its not turning in place
// turnRight = map(roll, -20, -50, 0, 125);
// turnLeft = -turnRight; //map(roll, 20, 50, 0, -255);
// }
//
// if (pitch > 60 || pitch < -60)
// {
// if (pitch > 0) {forward = true; backwards = false; right_in_place = false, left_in_place = false;}
// else if (pitch < 0) {forward = false; backwards = true; right_in_place = false, left_in_place = false;}
// speed = 125;
// }
// else if (pitch > 10 && pitch < 60) // Forward
// {
// forward = true;
// backwards = false;
// speed = map(pitch, 10, 60, 0, 125);
// }
// else if (pitch < -10 && pitch > -60) // Backward
// {
// forward = false;
// backwards = true;
// speed = map(pitch, -10, -60, 0, 125);
// }
//
// if (forward)
// {
// analogWrite(in2, speed + turnRight); // Left motor
// analogWrite(in3, speed + turnLeft); // Right motor
// }
// else if (backwards)
// {
// analogWrite(in1, speed + turnRight); // Left motor
// analogWrite(in4, speed + turnLeft); // Right motor
// }
// else if (right_in_place)
// {
// analogWrite(in2, speed + turnRight); // Left motor forwards
// analogWrite(in4, speed + turnLeft); // Right motor backwards
// }
// else if (left_in_place)
// {
// analogWrite(in1, speed + turnRight); // Left motor backwards
// analogWrite(in3, speed + turnLeft); // Right motor forwards
// }
| true |
18d1d2e43ddc788294e1b2f6c58f24675ab26459 | C++ | IFlowLikeH2O/Johnbui | /Ping_Pong.ino | UTF-8 | 2,632 | 2.875 | 3 | [] | no_license | #include <LedControl.h>
#include <Timer.h>
/* LED board set up */
int DIN = 11, CLK = 9, CS = 10, devices = 1;
LedControl lc = LedControl(DIN, CLK, CS, devices);
/* Definitions */
#define controlPin A2
#define debug 1
/* Creates an instance or event of time */
Timer timer;
/* Variable delcarations */
byte ball_direction;
int xball;
int yball;
int yball_prev;
int ball_timer;
byte bar;
/* Initial set up */
void setup()
{
Serial.begin(9600);
startUp();
animationSequence();
}
/* Repeats all functions */
void loop()
{
moveBar();
DEBUG("pong");
}
/* Intro animation for start of every game */
void animationSequence()
{
lc.clearDisplay(0);
for(int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
lc.setLed(0, r, c, HIGH);
delay(50);
}
}
delay(1500);
centerOut();
lc.clearDisplay(0);
}
/* Clears the animation sequence starting from the center going outwards */
void centerOut()
{
for(int r = 3; r <= 4; r++)
{
for(int c = 3; c <= 4; c++)
{
lc.setLed(0, r, c, 0);
}
}
delay(150);
for(int r = 2; r <= 5; r++)
{
for(int c = 2; c <= 5; c++)
{
lc.setLed(0, r, c, 0);
}
}
delay(150);
for(int r = 0; r <= 7; r++)
{
for(int c = 0; c <= 7; c++)
{
lc.setLed(0, r, c, 0);
}
}
delay(150);
}
/* Sets up the LED board */
void startUp()
{
lc.shutdown(0, false);
lc.setIntensity(0,3);
}
/* Allows the pong bar to move */
void moveBar()
{
/* 0xFF is 11111111 and B111 is 00000111 */
byte pos[2] = {0xFF, B111};
/* Scales the min and max values of the potentiometer down to 5-0. If the potentiometer reads
* zero, then bar will equal 5. If it reads 1000, then var will equal 0. */
bar = map(analogRead(controlPin), 0, 1000, 5, 0);
/* pad is set equal to pos[0]. pos [0] starts out as 11111111. Then it is shifted to the right by 5.
* Giving 00000111. Afterwards, 00000111 is shifted to the left by bar units. Bar is controled by the
* control pin, or potentiometer. */
byte pad = pos[0] >> 5 << bar;
lc.setRow(0, 7, pad);
}
/* Displays values if debug is defined. (const char *desc) means whatever is typed
* within DEBUG() is read only, cannot be changed, and whatever is typed is a character. */
void DEBUG(const char* desc)
{
#ifdef debug
Serial.print(desc);
Serial.print(" XY: (");
Serial.print(xball);
Serial.print(", ");
Serial.print(yball);
Serial.print(") bar: ");
Serial.print(bar);
Serial.print(" ball direction: ");
Serial.println(ball_direction);
#endif
}
| true |
7b2b325d7ea2a54f16c7557560a0dddd01a37fb4 | C++ | 19and99/ImagenomicProject1 | /BWConverter.cpp | UTF-8 | 557 | 2.890625 | 3 | [] | no_license | #include "stdafx.h"
#include "BWConverter.h"
BWConverter::BWConverter()
{
}
BWConverter::BWConverter(GenericImage* image_)
:GenericFilter(image_)
{
}
void BWConverter::filter() {
pixel pixel;
unsigned char gray = 0;
for (int i = 0; i < image->GetWidth(); ++i) {
for (int j = 0; j < image->GetHeight(); ++j) {
pixel = image->GetPixel(i,j);
gray = (pixel.a + pixel.b + pixel.c) / 3;
pixel.a = pixel.b = pixel.c = gray;
image->SetPixel(i,j,pixel);
}
}
image->Unlock();
}
BWConverter::~BWConverter()
{
}
| true |
4b5329010f8ac086b22552bf357fa415ad16ea02 | C++ | KANAIHIROYUKI/STM32 | /ふるい/F103_CanNode_rev1.1/user/user_app/inc/canNodeEncoder.cpp | UTF-8 | 961 | 2.625 | 3 | [] | no_license | #include "canNodeEncoder.h"
int16_t CanNodeEncoder::setup(TIM &enc,CAN &can,uint16_t address){
this->canEnc_can = &can;
this->canEnc_enc = &enc;
canEnc_address = address;
canEnc_can->filterAdd(canEnc_address);
return 0;
}
void CanNodeEncoder::cycle(){
if(canEnc_intervalTimer != 0){
if(canEnc_intervalTimer < millis()){
uint8_t canData[8];
uint32_t encValue = canEnc_enc->read();
canEnc_intervalTimer = millis() + canEnc_interval;
canData[0] = encValue & 0xFF;
canData[1] = (encValue >> 8) & 0xFF;
canData[2] = (encValue >> 16) & 0xFF;
canData[3] = (encValue >> 24) & 0xFF;
canEnc_can->send(canEnc_address,4,canData);
}
}
}
void CanNodeEncoder::interrupt(CanRxMsg rxMessage){
if(rxMessage.StdId == canEnc_address){
if(rxMessage.Data[0] == 0){
canEnc_enc->reset();
}else if(rxMessage.Data[0] == 1){
canEnc_interval = (rxMessage.Data[2] << 8) + rxMessage.Data[1];
}
}
return;
}
| true |
7a7ece7562688a154e7dfd8c825797bf7bea5a44 | C++ | LukasGrudtner/iotAuth | /utils.cpp | UTF-8 | 2,885 | 3.703125 | 4 | [] | no_license | #include "utils.h"
/* Char to Uint_8t
Converte um array de chars para um array de uint8_t.
*/
void CharToUint8_t(char* charArray, uint8_t* byteArray, int size)
{
for (int i = 0; i < size; i++) {
byteArray[i] = uint8_t(charArray[i]);
}
}
/* Uint8_t to Hex String
Converte um array de uint8_t em uma string codificada em hexadecimal.
*/
string Uint8_tToHexString(uint8_t* i, int quant){
string saida = "";
for(int j = 0; j < quant; j++){
char buffer [3];
sprintf(buffer,"%02X",i[j]);
saida += buffer;
}
return saida;
}
/* Hex String to Char Array
Converte uma string codificada em hexadecimal para um array de chars.
*/
void HexStringToCharArray(string* hexString, int sizeHexString, char* charArray)
{
char hexStringChar[sizeHexString];
strncpy(hexStringChar, hexString->c_str(), sizeHexString);
uint8_t byteArray[sizeHexString/2];
HexStringToByteArray(hexStringChar, sizeHexString, byteArray, sizeHexString/2);
ByteToChar(byteArray, charArray, sizeHexString/2);
}
/* Byte Array to Hex String
Converte um array de bytes em uma string codificada em hexadecimal.
*/
int ByteArrayToHexString(uint8_t *byte_array, int byte_array_len, char *hexstr, int hexstr_len)
{
int off = 0;
int i;
for (i = 0; i < byte_array_len; i ++) {
off += snprintf(hexstr + off, hexstr_len - off,
"%02x", byte_array[i]);
}
hexstr[off] = '\0';
return off;
}
/* Hex String to Byte Array
Converte uma string codificada em hexadecimal para um array de bytes.
*/
void HexStringToByteArray(char *hexstr, int hexstr_len, uint8_t *byte_array, int byte_array_len)
{
string received_hexa (hexstr);
vector<unsigned char> bytes_vector = hex_to_bytes(received_hexa);
std::copy(bytes_vector.begin(), bytes_vector.end(), byte_array);
}
/* Char to Byte
Converte um array de chars para um array de bytes.
*/
void CharToByte(unsigned char* chars, byte* bytes, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
bytes[i] = (byte)chars[i];
}
/* Byte to Char
Converte um array de bytes para um array de char.
*/
void ByteToChar(byte* bytes, char* chars, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
chars[i] = (char)bytes[i];
}
/* Função auxiliar utilizada na função 'Hex String to Byte Array'.
Recebe uma string codificada em hexadecimal e retorna um vetor de chars.
*/
std::vector<unsigned char> hex_to_bytes(std::string const& hex)
{
std::vector<unsigned char> bytes;
bytes.reserve(hex.size() / 2);
for (std::string::size_type i = 0, i_end = hex.size(); i < i_end; i += 2)
{
unsigned byte;
std::istringstream hex_byte(hex.substr(i, 2));
hex_byte >> std::hex >> byte;
bytes.push_back(static_cast<unsigned char>(byte));
}
return bytes;
}
| true |
6f46b167e9121473dd961c051e1336e6741592e6 | C++ | sandesh32/DSA-Problems-and-Solutions | /leetcode171.cpp | UTF-8 | 1,062 | 3.484375 | 3 | [] | no_license | /** Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Example 4:
Input: columnTitle = "FXSHRXW"
Output: 2147483647
Constraints:
1 <= columnTitle.length <= 7
columnTitle consists only of uppercase English letters.
columnTitle is in the range ["A", "FXSHRXW"].
**/
class Solution {
public:
int titleToNumber(string columnTitle) {
int l=columnTitle.length();
int num = 0;
for(int i=0;i<l;i++){
num+=int(columnTitle[l-i-1]-64)*pow(26,i);
}
return num;
}
};
/**
Python SOLUTION
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
l=len(columnTitle)
num=0
for i in range(l):
num+=(ord(columnTitle[l-i-1])-64)*(26**i)
return num
| true |
19086eaf8aadacc2594bdaacc1c6a54aa4f76af0 | C++ | DhaliwalX/copta | /include/jast/ir/instruction.h | UTF-8 | 6,070 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef INSTRUCTION_H_
#define INSTRUCTION_H_
#include "jast/types/type.h"
#include "jast/ir/value.h"
#include "jast/ir/function.h"
#include "jast/types/type-system.h"
namespace jast {
class BasicBlock;
class Function;
enum class OpCode {
#define R(I, _) k##I,
#include "instructions.h"
};
static inline std::string IrToString(OpCode op) {
switch (op) {
#define R(I, S) case OpCode::k##I: return S;
#include "instructions.h"
default:
return "unknown";
}
}
class Instruction : public Value {
public:
Instruction(OpCode op, const std::string &name)
: op_{ op }, name_{ name }
{ }
virtual ~Instruction() = default;
virtual void print(std::ostream &os) const;
const OpCode &opCode() const { return op_; }
std::vector<Ref<Value>> &operands() { return operands_; }
bool IsInstruction() const override { return true; }
Instruction *AsInstruction() override { return this; }
Ref<Value> GetNthOperand(int i) {
return operands_[i];
}
void SetName(std::string &name) {
name_ = name;
}
void ShortPrint(std::ostream &os) const;
protected:
void AddOperand(Ref<Value> value) {
operands_.push_back(value);
if (value)
value->AddUser(this);
}
OpCode op_;
std::vector<Ref<Value>> operands_;
protected:
std::string name_;
};
template <OpCode op>
class BinaryInstruction : public Instruction {
public:
BinaryInstruction(Ref<Value> first, Ref<Value> second, const std::string &name)
: Instruction(op, name)
{
AddOperand(first);
AddOperand(second);
}
Ref<Value> GetFirstOperand() {
return GetNthOperand(0);
}
Ref<Value> GetSecondOperand() {
return GetNthOperand(1);
}
Type *getType() override {
return (GetNthOperand(0)->getType());
}
};
#define B(I, _) using I##Instruction = BinaryInstruction<OpCode::k##I>;
#include "instructions.h"
class AllocInstruction : public Instruction {
public:
AllocInstruction(Type *type, const std::string &name)
: Instruction(OpCode::kAlloc, name), type_{type}
{ }
Type *getType() override {
return TypeSystem::getPointerType(type_);
}
void print(std::ostream &os) const override;
private:
Type *type_;
};
class LoadInstruction : public Instruction {
public:
LoadInstruction(Ref<Value> value, const std::string &name)
: Instruction(OpCode::kLoad, name)
{
AddOperand(value);
}
Type *getType() override {
assert(GetOperand()->getType()->IsPointerType());
return GetOperand()->getType()->AsPointerType();
}
Ref<Value> GetOperand() {
return GetNthOperand(0);
}
};
class StoreInstruction : public Instruction {
public:
StoreInstruction(Ref<Value> value, Ref<Value> target, const std::string &name)
: Instruction(OpCode::kStore, name)
{
AddOperand(value);
AddOperand(target);
}
Ref<Value> GetSource() {
return GetNthOperand(0);
}
Ref<Value> GetTarget() {
return GetNthOperand(1);
}
Type *getType() override {
return TypeSystem::getUndefinedType();
}
};
class BrkInstruction : public Instruction {
public:
BrkInstruction(Ref<Value> cond, Ref<BasicBlock> bb, const std::string &name)
: Instruction(OpCode::kBrk, name)
{
AddOperand(cond);
AddOperand(bb);
}
Ref<Value> GetCondition() {
return GetNthOperand(0);
}
Ref<BasicBlock> GetBlock() {
return GetNthOperand(1)->AsBasicBlock();
}
Type *getType() override {
return TypeSystem::getUndefinedType();
}
};
class JmpInstruction : public Instruction {
public:
JmpInstruction(Ref<BasicBlock> bb, const std::string &name = "")
: Instruction(OpCode::kJmp, name)
{
AddOperand(bb);
}
Ref<BasicBlock> GetBlock() {
return GetNthOperand(0)->AsBasicBlock();
}
Type *getType() override {
return TypeSystem::getUndefinedType();
}
};
class AddrOfInstruction : public Instruction {
public:
AddrOfInstruction(Ref<Value> base, const std::string &name)
: Instruction(OpCode::kAddrOf, name)
{
AddOperand(base);
}
Ref<Value> GetBase() {
return GetNthOperand(0);
}
Type *getType() override {
return TypeSystem::getPointerType(GetBase()->getType());
}
};
class GeaInstruction : public Instruction {
public:
GeaInstruction(Ref<Value> base, Ref<ConstantStr> element, const std::string &name)
: Instruction(OpCode::kGea, name)
{
AddOperand(base);
AddOperand(element);
}
Ref<Value> GetBase() {
return GetNthOperand(0);
}
std::string GetElement() {
return GetNthOperand(1)->AsConstant()->AsStr();
}
Type *getType() override {
assert(GetBase()->getType()->IsObjectType());
return GetBase()->getType()->AsObjectType()->getMember(GetElement());
}
};
class IdxInstruction : public Instruction {
public:
IdxInstruction(Ref<Value> base, Ref<Value> idx, const std::string &name)
: Instruction(OpCode::kIdx, name)
{
AddOperand(base);
AddOperand(idx);
}
Ref<Value> GetBase() {
return GetNthOperand(0);
}
Ref<Value> GetIndex() {
return GetNthOperand(1);
}
Type *getType() override {
assert(GetBase()->getType()->IsArrayType());
return GetBase()->getType()->AsArrayType()->getBaseElementType();
}
};
class RetInstruction : public Instruction {
public:
RetInstruction(Ref<Value> value, const std::string &name)
: Instruction(OpCode::kRet, name)
{
AddOperand(value);
}
Ref<Value> GetValue() {
return GetNthOperand(0);
}
Type *getType() override {
return TypeSystem::getUndefinedType();
}
};
class InvokeInstruction : public Instruction {
public:
InvokeInstruction(Ref<Function> function, std::vector<Ref<Value>> args,
const std::string &name)
: Instruction(OpCode::kInvoke, name), function_{function}
{
for (auto &arg : args) {
AddOperand(arg);
}
}
Ref<Function> GetFunction() {
return function_;
}
Ref<Value> GetNthArg(int i) {
return GetNthOperand(i);
}
Type *getType() override {
return function_->getReturnType();
}
void print(std::ostream &os) const override;
private:
Ref<Function> function_;
};
}
#endif
| true |
b8705993bf4b595e4d5211132d95468f18631c3d | C++ | johnhany/leetcode | /714-Best-Time-to-Buy-and-Sell-Stock-with-Transaction-Fee/solution.cpp | UTF-8 | 532 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include "solution.hpp"
static auto x = []() {
// turn off sync
std::ios::sync_with_stdio(false);
// untie in/out streams
cin.tie(NULL);
return 0;
}();
// https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/solution/zui-jian-dan-2-ge-bian-liang-jie-jue-suo-71fe/
int Solution::maxProfit(vector<int>& prices, int fee) {
int buy = INT_MIN, sell = 0;
for (auto& p : prices)
{
int buynow = max(buy, sell - p - fee);
int sellnow = max(sell, buy + p);
buy = buynow;
sell = sellnow;
}
return sell;
}
| true |
9d23d05561b2716311274da78287f6dbf8637db9 | C++ | salgotrav/my_progs_for_IS-HR | /triquery.cpp | UTF-8 | 1,567 | 2.859375 | 3 | [] | no_license | #include<iostream>
//#include<utility>
//#include<vector>
#include<cstdio>
using namespace std;
//#define DEBUG_MODE
int main()
{
int num_points, queries;
//cin>>num_points>>queries;
scanf("%d%d",&num_points,&queries);
//pair<int, int> xy; //coordinates of point
struct xy_pair {
int first;
int second;
}xy;
//vector< pair<int,int> > array_points;
struct xy_pair *array_points = new xy_pair[num_points];
for (int i=0; i<num_points; i++) {
//cin>>xy.first>>xy.second;
scanf("%d%d",&xy.first,&xy.second);
//array_points.push_back(xy);
array_points[i]=xy;
}//end of for loop
#ifdef DEBUG_MODE
for (int i=0; i<num_points; i++) {
//xy=*iter;
cout<<array_points[i].first<<"\t"<<array_points[i].second<<"\n";
}
#endif
int x,y,d, xd,yd, count; //xd is x+d
while(queries--) {
//cin>>x>>y>>d;
scanf("%d%d%d",&x,&y,&d);
xd=x+d;
yd=y+d;
count=0;
// for (vector< pair<int,int> >::iterator iter=array_points.begin(); iter!=array_points.end(); iter++) {
for(int i=0;i<num_points;i++) {
//xy=*iter;
if(array_points[i].first<x)
continue;
else if(array_points[i].first>xd)
continue;
else if(array_points[i].second<y)
continue;
else if(array_points[i].second>yd)
continue;
else {
if( (array_points[i].second-y)*(-d)-(array_points[i].first-x-d)*d >=0 )
count++;
}//end of last else of ifelse ladder
}//end of for loop
//cout<<count<<endl;
printf("%d\n",count);
}//end of queries while loop
delete[] array_points;
}//end of main
| true |
7b578c04d00ce78a9bb73f5afd82e021c01e1505 | C++ | amir5200fx/Tonb | /TnbPtdModel/TnbLib/PtdModel/FormMaker/PtdModel_FormMaker.cxx | UTF-8 | 1,719 | 2.515625 | 3 | [] | no_license | #include <PtdModel_FormMaker.hxx>
#include <PtdModel_Par.hxx>
#include <TnbError.hxx>
#include <OSstream.hxx>
std::shared_ptr<tnbLib::PtdModel_Par>
tnbLib::PtdModel_FormMaker::Parameter(const word & name) const
{
auto iter = theParameters_.find(name);
if (iter IS_EQUAL theParameters_.end())
{
Info << "parameters: " << endl;
for (const auto& x : theParameters_)
{
Info << " - " << x.first << endl;
}
FatalErrorIn(FunctionSIG)
<< "unable to find the parameter!" << endl
<< " -name: " << name << endl
<< abort(FatalError);
}
return iter->second;
}
std::vector<tnbLib::word>
tnbLib::PtdModel_FormMaker::RetrieveParameters() const
{
std::vector<word> parameters;
parameters.reserve(NbParameters());
for (size_t i = 0; i < NbParameters(); i++)
{
parameters.push_back(Parameter(i));
}
return std::move(parameters);
}
void tnbLib::PtdModel_FormMaker::SetParameter
(
const word & name,
const std::shared_ptr<PtdModel_Par>& par
)
{
par->SetName(name);
auto paired = std::make_pair(name, par);
auto insert = theParameters_.insert(std::move(paired));
if (NOT insert.second)
{
FatalErrorIn(FunctionSIG)
<< "duplicate data has been detected during parameter registration!" << endl
<< "-name: " << name << endl
<< abort(FatalError);
}
}
void tnbLib::PtdModel_FormMaker::SetParameter
(
const word & name,
std::shared_ptr<PtdModel_Par>&& par
)
{
par->SetName(name);
auto paired = std::make_pair(name, std::move(par));
auto insert = theParameters_.insert(std::move(paired));
if (NOT insert.second)
{
FatalErrorIn(FunctionSIG)
<< "duplicate data has been detected during parameter registration!" << endl
<< "-name: " << name << endl
<< abort(FatalError);
}
} | true |
3b85532a6084e4ccb327171332c272e7abbe404b | C++ | TarunSinghania/Algorithms | /Dynammic Programming standard problems/boxstacking.cpp | UTF-8 | 1,680 | 2.671875 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int maxHeight(int height[],int width[],int length[],int n);
int main()
{
int n;
cin>>n;
int A[1000],B[1000],C[10001];
for(int i=0;i<n;i++)
{
int a,b,c;
cin>>a>>b>>c;
A[i]=a;
B[i]=b;
C[i]=c;
}
cout<<maxHeight(A,B,C,n)<<endl;
}
bool cmp(const pair<int,pair<int,int> > &a,const pair<int,pair<int,int> > &b){
if (a.second.first*a.second.second==b.second.first*b.second.second)
return a.first>b.first;
else
return a.second.first*a.second.second>b.second.first*b.second.second;
}
int maxHeight(int height[],int width[],int length[],int n)
{
vector<pair<int,pair<int,int> > > b;
for(int i =0;i<n;i++){
b.push_back(make_pair(height[i],make_pair(width[i],length[i])));
b.push_back(make_pair(height[i],make_pair(length[i],width[i])));
b.push_back(make_pair(length[i],make_pair(height[i],width[i])));
b.push_back(make_pair(length[i],make_pair(width[i],height[i])));
b.push_back(make_pair(width[i],make_pair(height[i],length[i])));
b.push_back(make_pair(width[i],make_pair(length[i],height[i])));
}
sort(b.begin(),b.end(),cmp);
int lise[6*n] ={0};
for(int i =0;i<6*n;i++)
lise[i]=0;
lise[0]=b[0].first;
int mx = 1;
for(int i = 1 ; i < 6*n;i++)
{ mx =0;
for(int j =0;j<i;j++)
{
if(b[j].second.first>b[i].second.first && b[j].second.second>b[i].second.second)
mx = max(mx,lise[j]);
}
lise[i] = mx + b[i].first;
}
for(int i =0;i<6*n;i++)
{
mx = max(lise[i],mx);
}
return mx;
} | true |
265f290000b00014c287b8e186016db1f0c7889d | C++ | albertoubedamunoz/UncleOwen | /UncleOwenFarm/uncleOwen-p3.cc | UTF-8 | 967 | 3.046875 | 3 | [] | no_license |
#include <iostream>
#include <cstdlib>
using namespace std;
#include "Farm.h"
#include "Util.h"
void menu(int hour)
{
cout << "-----========== Farm manager ==========-----" << endl
<< "1- List farm info" << endl
<< "2- Add field" << endl
<< "3- Add android" << endl
<< "4- Start working hour ("<< hour << ")" << endl
<< "q- Quit" << endl
<< "Option: " ;
}
int main()
{
Farm farm("west farm");
char option;
int hour=1;
do {
menu(hour);
cin >> option; cin.get();
switch (option) {
case '1': cout << farm;
break;
case '2': farm.createField();
break;
case '3': farm.createAndroid();
break;
case '4': farm.startWorkingHour(hour);
break;
case 'q':
break;
default: Util::error(ERR_UNKNOWN_OPTION);
}
} while (option != 'q');
}
| true |
7f6db0550bbd7c49afab06d41615962219e66d21 | C++ | KrissKry/p2p-proto | /include/TCPConnector.h | UTF-8 | 1,567 | 2.796875 | 3 | [] | no_license | #ifndef TIN_TCPHANDLER
#define TIN_TCPHANDLER
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
#include <sys/socket.h>
#include "Constants.h"
#include "Resource.h"
#include "RandomGenerator.h"
class TCPConnector {
public:
/* used when creating a client */
explicit TCPConnector(int socket, unsigned short port, const char* address);
/* used when creating a server*/
explicit TCPConnector(int socket, const struct sockaddr_in &addr);
~TCPConnector() {}
/* connects() client to remote addr */
int setupClient();
/* begins tcp server listening */
int serverListen();
/*
* accept incoming connection on server socket from any IP
* returns file descriptor for the connection or -1 on error
*/
int serverAccept();
/*
* send >data_size< bytes from memory @ptr on >sockfd<
* returns 0 on success, -1 on error
*/
int sendData(int sockfd, void *ptr, unsigned long long data_size);
/*
* receive >data_size< bytes into memory @ptr from socket >fd<
*/
int receiveData(int fd, void *ptr, unsigned long long data_size);
private:
int socket;
unsigned short port;
const char* address;
sockaddr_in addr;
RandomGenerator rg;
void printError() {
std::cout << "[ERR] " << strerror(errno) << "\n";
}
};
#endif | true |
9aee1dee7ef906c845340446fd4e77c603634877 | C++ | chriswong604/MineSenseAssignment | /Source/filereader.cpp | UTF-8 | 892 | 3.203125 | 3 | [] | no_license | /**
* Class: FileReader
* Purpose: The FileReader class opens a file and stores every line of the file.
*/
#include "filereader.h"
/**
* FileReader Contructor
* @param source - the file to be read
*/
FileReader::FileReader(QString source)
{
readFile(source);
}
/**
* Method: readFile() - Reads the source file and saves every line of the file.
* @param source - the file to be read
*/
void FileReader::readFile(QString source)
{
QFile sourceFile(source);
if(sourceFile.open(QFile::ReadOnly | QFile::Text)){
QTextStream in(&sourceFile);
while(!in.atEnd()){
allText << in.readLine();
}
}
else{
qDebug() << "Could not open the file for reading";
}
sourceFile.close();
}
/**
* Method: getText()
* @return - Returns the List of data by lines.
*/
QStringList FileReader::getText()
{
return allText;
}
| true |
f6f74b2218cc065e07155a9236f517fc86f87167 | C++ | Brukols/Epitech-Arcade | /lib/sdl/src/ListLibraries/ListLibraries.cpp | UTF-8 | 6,420 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
** EPITECH PROJECT, 2020
** OOP_arcade_2019
** File description:
** ListLibraries
*/
#include "sdl/ListLibraries.hpp"
#include "sdl/Utility.hpp"
arc::ListLibraries::ListLibraries()
{
initRects();
}
arc::ListLibraries::~ListLibraries()
{
}
void arc::ListLibraries::setFont(const std::string &path)
{
_font = path;
}
void arc::ListLibraries::setEventList(const std::function<void (const std::string &)> &fct)
{
_eventList = fct;
}
void arc::ListLibraries::changeColor()
{
int i = 0;
std::for_each(_buttonsList.begin(), _buttonsList.end(), [&i](std::pair<ButtonRect, std::string> &button) {
if (i % 2) {
button.first.setColor(Utility::getColor(Utility::BUTTON_LIST));
button.first.setColorHover(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
button.first.setColorSelect(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
} else {
button.first.setColor(Utility::getColor(Utility::BUTTON_LIST));
button.first.setColorHover(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
button.first.setColorSelect(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
}
i++;
});
}
void arc::ListLibraries::setNameList(const std::string &nameList)
{
arc::Text *text = new arc::Text();
text->setFont(_font, 30);
text->setText(nameList);
text->setPosition(250 - text->getWidth() / 2, 30);
text->setColor({255, 255, 255, 255});
_texts.push_back(std::shared_ptr<Text>(text));
}
static arc::ButtonRect initButtonList(int y, const std::string &name)
{
arc::ButtonRect button;
arc::Rectangle rect;
arc::Text *text = new arc::Text();
rect.setColor({2, 148, 165, 255});
rect.setSize(498, 80);
text->setColor({255, 255, 255, 255});
text->setFont(FONT, 20);
text->setText(name);
button.setRect(rect);
button.setText(text);
button.setPosition(1, y);
button.setColorHover(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
button.setColorSelect(arc::Utility::getColor(arc::Utility::BUTTON_LIST_HOVER));
return (button);
}
void arc::ListLibraries::eventListButtons(const std::string &name)
{
_eventList(name);
}
void arc::ListLibraries::setNameLibraries(const std::vector<std::string> &list, int chosen)
{
_buttonsList.clear();
int i = 0;
std::for_each(list.begin(), list.end(), [this, &i, &chosen](const std::string &name) {
_buttonsList.push_back(std::make_pair(initButtonList(i * 80 + 89, name), name));
if (i == chosen)
_buttonsList[_buttonsList.size() - 1].first.setSelect(true);
if (i % 2) {
_buttonsList[_buttonsList.size() - 1].first.setColor(Utility::getColor(Utility::BUTTON_LIST));
} else {
_buttonsList[_buttonsList.size() - 1].first.setColor(Utility::getColor(Utility::BUTTON_LIST_2));
}
i++;
});
}
void arc::ListLibraries::display(SDL_Renderer *window)
{
std::for_each(_rects.begin(), _rects.end(), [&window](Rectangle &rect) {
rect.display(window);
});
std::for_each(_texts.begin(), _texts.end(), [&window](std::shared_ptr<Text> &text) {
text->display(window);
});
int i = 0;
std::for_each(_buttonsList.begin(), _buttonsList.end(), [this, &window, &i](std::pair<ButtonRect, std::string> &button) {
if (i > 6 + _begin)
return;
if (i < _begin) {
i++;
return;
}
button.first.display(window);
i++;
});
}
void arc::ListLibraries::setPosition(int x, int y)
{
std::for_each(_rects.begin(), _rects.end(), [&x, &y](Rectangle &rect) {
rect.setPosition(rect.getRect().x + x, rect.getRect().y + y);
});
std::for_each(_texts.begin(), _texts.end(), [&x, &y](std::shared_ptr<Text> &text) {
text->setPosition(text->getPosX() + x, text->getPosY() + y);
});
std::for_each(_buttonsList.begin(), _buttonsList.end(), [&x, &y](std::pair<ButtonRect, std::string> &button) {
button.first.setPosition(button.first.getPosX() + x, button.first.getPosY() + y);
});
}
void arc::ListLibraries::resetButtonsList()
{
std::for_each(_buttonsList.begin(), _buttonsList.end(), [](std::pair<ButtonRect, std::string> &button) {
button.first.setSelect(false);
});
}
void arc::ListLibraries::eventScrollUp()
{
if (_begin == 0)
return;
_begin--;
std::for_each(_buttonsList.begin(), _buttonsList.end(), [this](std::pair<ButtonRect, std::string> &button) {
button.first.setPosition(button.first.getPosX(), button.first.getPosY() + 80);
});
}
void arc::ListLibraries::eventScrollDown()
{
if (_buttonsList.size() <= 6)
return;
if (static_cast<long unsigned int>(_begin + 1) == _buttonsList.size() - 6)
return;
_begin++;
std::for_each(_buttonsList.begin(), _buttonsList.end(), [this](std::pair<ButtonRect, std::string> &button) {
button.first.setPosition(button.first.getPosX(), button.first.getPosY() - 80);
});
}
bool arc::ListLibraries::hasASelectButton() const
{
return (!(_buttonsList.end() == std::find_if(_buttonsList.begin(), _buttonsList.end(), [](const std::pair<ButtonRect, std::string> &button) -> bool {
return (button.first.isSelect());
})));
}
bool arc::ListLibraries::event(const arc::Event::Type &actualEventType, const arc::Event::Key &actualKeyPress, const SDL_Event &event)
{
(void)actualKeyPress;
int x;
int y;
SDL_GetMouseState(&x, &y);
if (actualEventType == arc::Event::Type::MOUSE_WHEEL) {
if (!_rects[0].isMouseHover(x, y))
return (false);
if (event.wheel.y > 0) {
eventScrollUp();
} else if (event.wheel.y < 0) {
eventScrollDown();
}
return (false);
}
if (actualEventType != arc::Event::Type::MOUSE_RELEASED)
return (false);
bool hasEvent = false;
std::for_each(_buttonsList.begin(), _buttonsList.end(), [&x, &y, this, &hasEvent](std::pair<ButtonRect, std::string> &button) {
if (button.first.isSelect()) {
return;
}
if (button.first.isMouseHover(x, y)) {
resetButtonsList();
eventListButtons(button.second);
button.first.setSelect(true);
hasEvent = true;
}
});
return (hasEvent);
} | true |
c0940c2175a69d77888aba127a538d5333d11846 | C++ | linkenwild/CPPlearn | /EssentialCPP/CH2_Ex5.cc | UTF-8 | 1,183 | 3.484375 | 3 | [] | no_license | //Essential CPP Ch2_Ex5
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
template <typename Type>
inline Type max_( Type t1, Type t2 )
{
return t1 > t2 ? t1 : t2;
}
template <typename elemType>
inline elemType max_( const vector<elemType> &vec )
{
return *max_element( vec.begin(), vec.end() );
}
template <typename arrayType>
inline arrayType max_( const arrayType *parray, int size )
{
return *max_element( parray, parray+size );
}
void ex2_5()
{
string sarray[]={ "weeree","her","weere", "priidede", "of", "teeen" };
vector<string> svec( sarray, sarray+6 );
int iarray[]={ 12, 70, 2, 169, 1, 5, 29 };
vector<int> ivec( iarray, iarray+7 );
float farray[]={ 2.5, 24.8, 18.7, 4.1, 23.9 };
vector<float> fvec( farray, farray+5 );
int imax = max_( max_( ivec ), max_( iarray, 7 ));
float fmax = max_( max_( fvec ), max_( farray, 5 ));
string smax = max_( max_( svec ), max_( sarray, 6 ));
cout << "imax should be 169 -- found: " << imax << "\n"
<< "fmax should be 24.8 -- found: " << fmax << "\n"
<< "smax should be were -- found: " << smax << "\n";
}
int main()
{
ex2_5();
} | true |
cdeaee7a5b7e27a9f2de19f3a67a91192cee9f4d | C++ | baluselva-ts/Algorithms | /Graph/FloydWarshall.cpp | UTF-8 | 2,040 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <map>
#include <stack>
#include <set>
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define ll long long
using namespace std;
void getEdges(vector< vector<int> > &adjacencyMatrix, int numberOfEdges) {
cout << "Enter source, destination (0 indexed) and weight of edges:" << endl;
for (int i = 0, source, dest, weight; i < numberOfEdges; i++) {
cin >> source >> dest >> weight;
adjacencyMatrix[source][dest] = weight;
}
}
void print2DVector(vector< vector<int> > adjacencyMatrix, int numberOfVertices) {
for (int i = 0; i < numberOfVertices; i++) {
cout << i << " -> ";
for (int j = 0; j < numberOfVertices; j++) {
cout << adjacencyMatrix[i][j] << " ";
}
cout << endl;
}
}
vector< vector<int> > runFloydWarshallAlgorithm(vector< vector<int> > adjacencyMatrix, int numberOfVertices) {
vector< vector<int> > allPairShortestPath = adjacencyMatrix;
for (int i = 0 ; i < numberOfVertices; i++)
for (int j = 0; j < numberOfVertices; j++)
for (int k = 0; k < numberOfVertices; k++)
if (j != k && allPairShortestPath[j][i] != INT_MAX && allPairShortestPath[i][k] != INT_MAX)
allPairShortestPath[j][k] = MIN(allPairShortestPath[j][k], allPairShortestPath[j][i] + allPairShortestPath[i][k]);
return allPairShortestPath;
}
int main() {
int numberOfVertices = 0, numberOfEdges = 0;
cout << "Enter number of vertices: ";
cin >> numberOfVertices;
cout << "Enter number of Edges: ";
cin >> numberOfEdges;
vector< vector<int> > adjacencyMatrix(numberOfVertices, vector<int>(numberOfVertices, INT_MAX));
getEdges(adjacencyMatrix, numberOfEdges);
for (int i = 0; i < numberOfVertices; i++)
adjacencyMatrix[i][i] = 0;
cout << "Input:" << endl;
print2DVector(adjacencyMatrix, numberOfVertices);
cout << endl;
cout << "All Pair Shortest Path:" << endl;
vector< vector<int> > allPairShortestPath = runFloydWarshallAlgorithm(adjacencyMatrix, numberOfVertices);
print2DVector(allPairShortestPath, numberOfVertices);
return 0;
} | true |
198b9366cf0c8ec3188bbfa1e6f5c70fae312b93 | C++ | darksidersstrife/RayTracer | /src/rendering/camera.h | UTF-8 | 1,723 | 3.25 | 3 | [] | no_license | //
// Created by vvlla on 22.03.2021.
//
#ifndef RAYTRACER_CAMERA_H
#define RAYTRACER_CAMERA_H
#include "../geometry/vector.h"
#include "../geometry/point.h"
//template<typename T, size_t size, size_t alignment = alignof(T)>
struct Camera
{
Vec3f up, direction, left ;
Point3f position;
Camera() : direction(0, 0, 1), up(0, 1, 0), left(cross(direction, up)), position(0, 0, 0) {}
Camera& rotate(float toLeft, float toUp)
{
rotateAgainstVector(toLeft, up);
rotateAgainstVector(toUp, left);
return *this;
}
private:
void rotateAgainstVector(float angle, const Vec3f& vec)
{
auto c = cos(angle);
auto s = sin(angle);
float r[3][3];
r[0][0] = c + (1 - c) * vec[0] * vec[0];
r[0][1] = (1 - c) * vec[0] * vec[1] - s * vec[2];
r[0][2] = (1 - c) * vec[0] * vec[2] + s * vec[1];
r[1][0] = (1 - c) * vec[0] * vec[1] + s * vec[2];
r[1][1] = c + (1 - c) * vec[1] * vec[1];
r[1][2] = (1 - c) * vec[1] * vec[2] - s * vec[0];
r[2][0] = (1 - c) * vec[0] * vec[2] - s * vec[1];
r[2][1] = (1 - c) * vec[1] * vec[2] + s * vec[0];
r[2][2] = c + (1 - c) * vec[2] * vec[2];
multiplyVector(up, r);
multiplyVector(left, r);
multiplyVector(direction, r);
}
void multiplyVector(Vec3f& vec, float r[3][3])
{
float x = 0.0, y = 0.0, z = 0.0;
x = r[0][0] * vec[0] + r[0][1] * vec[1] + r[0][2] * vec[2];
y = r[1][0] * vec[0] + r[1][1] * vec[1] + r[1][2] * vec[2];
z = r[2][0] * vec[0] + r[2][1] * vec[1] + r[2][2] * vec[2];
vec[0] = x;
vec[1] = y;
vec[2] = z;
}
};
#endif //RAYTRACER_CAMERA_H
| true |
f4c93264a38303b923875a7fc7eb1c4b39e3cc00 | C++ | hhool/ilias_async | /test/threadpool_intf/instantiate.cc | UTF-8 | 1,416 | 2.96875 | 3 | [] | no_license | #include <ilias/threadpool_intf.h>
#include <utility>
class mock_client
{
public:
class threadpool_client
: public virtual ilias::threadpool_client_intf
{
public:
mock_client* m_self;
threadpool_client(mock_client* self) noexcept
: m_self(self)
{
/* Empty body. */
}
bool
has_work() noexcept
{
return false;
}
bool
do_work() noexcept
{
return false;
}
void
on_service_detach() noexcept
{
return;
}
};
ilias::threadpool_client_ptr<threadpool_client> m_client;
void
attach(ilias::threadpool_client_ptr<threadpool_client> client)
{
this->m_client = std::move(client);
}
mock_client*
threadpool_client_arg() noexcept
{
return this;
}
};
class mock_service
{
public:
class threadpool_service
: public virtual ilias::threadpool_service_intf
{
public:
mock_service* m_self;
threadpool_service(mock_service* self) noexcept
: m_self(self)
{
/* Empty body. */
}
unsigned int
wakeup(unsigned int) noexcept
{
return 0;
}
void
on_client_detach() noexcept
{
return;
}
};
ilias::threadpool_service_ptr<threadpool_service> m_service;
void
attach(ilias::threadpool_service_ptr<threadpool_service> service)
{
this->m_service = std::move(service);
}
mock_service*
threadpool_service_arg() noexcept
{
return this;
}
};
int
main()
{
mock_client c;
mock_service s;
ilias::threadpool_attach(c, s);
}
| true |
518641bec4f04fc0a7f10297b92d0e8d3408cedb | C++ | Vaur/Raytracer | /src/MsgBox.cpp | UTF-8 | 5,857 | 2.921875 | 3 | [] | no_license | //
// MsgBox.cpp for raytracer in /home/vaur/epitech/inprogress/B-VPP-042/vpp_raytracer
//
// Made by vaur
// Login <vaur@epitech.net>
//
// Started on Sat May 24 13:44:59 2014 vaur
// Last update Mon Jun 23 14:32:48 2014 vaur
//
/** \file MsgBox.cpp
* Functions for class MsgBox
*/
/*
** Include
*/
#include <map>
#include <sstream>
#include "DecorateBracket.hpp"
#include "MsgBox.hpp"
#include "StringColorise.hpp"
/*
** Functions
*/
/*
** CTOR
*/
/**
* Constructor takes as parameter the name of the program.
*/
MsgBox::MsgBox(const std::string &progname)
{
this->_mode = MsgBox::INFO;
this->_progname = progname;
this->_colorEnabled = true;
if (DEBUG_ == 1)
this->_debugEnabled = true;
else
this->_debugEnabled = false;
}
/*
** DTOR
*/
MsgBox::~MsgBox()
{
}
/*
** Setter
*/
/**
* Set the mode for the messages that are coming.
*/
void MsgBox::setMode(MsgBox::t_mode mode)
{
this->_mode = mode;
}
/**
* Return a MsgHandler that will get the messages and return them to the MsgBox
*/
MsgBox::MsgHandler MsgBox::msg()
{
MsgHandler handler(*this);
return (handler);
}
/** Switch the mode of the MsgBox and return a MsgHandler that will take care of the message */
MsgBox::MsgHandler MsgBox::msg(MsgBox::t_mode mode)
{
MsgHandler handler(*this);
setMode(mode);
return (handler);
}
/** Return a MsgHandler that will get the messages and return them to the MsgBox
* MsgHandler receive in CTOR addtionnal information
*
*/
MsgBox::MsgHandler MsgBox::msg(const char *func, int line)
{
if (_debugEnabled == true)
return (MsgHandler(*this, func, line));
return (MsgHandler(*this));
}
/**
* Switch the mode of the MsgBox and return a MsgHandler that will take care of the message
* MsgHandler receive in CTOR addtionnal information about the context of the call
*/
MsgBox::MsgHandler MsgBox::msg(const char *func, int line, MsgBox::t_mode mode)
{
setMode(mode);
if (_debugEnabled == true)
return (MsgHandler(*this, func, line));
return (MsgHandler(*this));
}
/*
**
** Private
**
*/
/**
* Decoration that is put before the message to display
* @return reference to MsgBox object for operator overload.
*/
MsgBox &MsgBox::decorateIn()
{
DecorateBracket decorate;
std::string mode_str;
std::string progname_str;
mode_str = ModeToString();
progname_str = _progname;
colorise_string(progname_str);
colorise_string(mode_str);
decorate << progname_str;
decorate << mode_str;
*this << progname_str << " " << mode_str << "\t";
return (*this);
}
/**
* \copydoc decorateIn
* @param[in] tmp_mode temporary mode in which the messgae is displayed
*
* display a message with a temporary mode in release mode
*/
MsgBox &MsgBox::decorateIn(MsgBox::t_mode tmp_mode)
{
MsgBox::t_mode bk_mode;
bk_mode = this->_mode;
this->_mode = tmp_mode;
decorateIn();
this->_mode = bk_mode;
return (*this);
}
/**
* \copydoc decorateIn
* @param[in] func the name of the function where MsgBox is called
* @param[in] line the line where MsgBox is called
*
* Both parameters are defined by compilator.
* This function is called when program is compiled in debug mode \see MSG
* @done 01/06/2014: line is now displayed properly
*/
MsgBox &MsgBox::decorateIn(const char *func, int line)
{
DecorateBracket decorate;
std::string mode_str;
std::string func_str;
std::stringstream line_strstream;
std::string line_str;
std::string progname_str;
mode_str = ModeToString();
func_str = func;
line_strstream << line;
line_str = line_strstream.str();
progname_str = _progname;
colorise_string(progname_str);
colorise_string(mode_str);
colorise_string(func_str);
colorise_string(line_str);
decorate << progname_str;
decorate << mode_str;
decorate << func_str;
decorate << line_str;
*this << progname_str << " " << mode_str << "\t";
*this << func_str << "\t" << line_str << " ";
return (*this);
}
/**
* \copydoc decorateIn
* @param[in] tmp_mode temporary mode in which the messgae is displayed
* @param[in] func the name of the function where MsgBox is called
* @param[in] line the line where MsgBox is called
*
* display a message with a temporary mode in debug mode
*
* as decorateIn(const char *func, int line) func and line are defined by compilator.
* This function is called when program is compiled in debug mode \see MSG
*/
MsgBox &MsgBox::decorateIn(MsgBox::t_mode tmp_mode, const char *func, int line)
{
MsgBox::t_mode bk_mode;
bk_mode = this->_mode;
this->_mode = tmp_mode;
decorateIn(func, line);
this->_mode = bk_mode;
return (*this);
}
/**
* Decoration that is put after the message to display, usually `std::endl` but might be subject to change.
*/
void MsgBox::decorateOut()
{
if (_mode != DEBUG || _debugEnabled == true)
std::cout << std::endl;
}
/**
* Return a `std::string` that describe the current mode.
*/
std::string MsgBox::ModeToString()
{
DecorateBracket decorate;
std::map<MsgBox::t_mode, std::string> map_mode;
std::string ret;
map_mode[MsgBox::ERROR] = "error";
map_mode[MsgBox::INFO] = "info";
map_mode[MsgBox::WARNING] = "warning";
map_mode[MsgBox::DEBUG] = "debug";
ret = map_mode[this->_mode];
return (ret);
}
/**
* @param[in] str take a string and colorize it according to msgmode
* @return return a reference to that string
*/
std::string &MsgBox::colorise_string(std::string &str)
{
StringColorise coloriser;
std::map<MsgBox::t_mode, StringColorise::e_Color> map_mode;
map_mode[MsgBox::ERROR] = StringColorise::RED;
map_mode[MsgBox::INFO] = StringColorise::GREEN;
map_mode[MsgBox::WARNING] = StringColorise::MAGENTA;
map_mode[MsgBox::DEBUG] = StringColorise::YELLOW;
if (_colorEnabled == true)
return (coloriser.colorise(map_mode[this->_mode], str));
return (str);
}
| true |
711110caab04ca5e4924a599ddc09b39b97bb96e | C++ | Doryaakobi/messageboard-b | /Test.cpp | UTF-8 | 2,056 | 3.171875 | 3 | [
"MIT"
] | permissive | #include "doctest.h"
#include "Board.hpp"
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
using namespace ariel;
const int max_message = 100;
const int max_rows = 500;
const int max_column = 500;
const int test = 100;
string gen_random()
{
const int ascii_s = 26;
const int ascii_e = 126;
string randString;
int message_length = rand() % max_message;
for (int i = 0; i < message_length; ++i)
randString += rand()%(ascii_e-ascii_s)+ascii_s;
return randString;
}
TEST_CASE("Test 1 Post & Read")
{
Board board;
srand((unsigned)time(0));
Direction orientation;
for (uint i = 0; i < test; i++)
{
uint rand_row = rand() % max_rows;
uint rand_col = rand() % max_column;
string rand_message = gen_random();
if ((rand() % 2+1) == 0)
{
orientation = Direction::Horizontal;
}
else
{
orientation = Direction::Vertical;
}
CHECK_NOTHROW(board.post(rand_row, rand_col, orientation, rand_message));
CHECK(board.read(rand_row, rand_col, orientation, rand_message.size()) == rand_message);
}
}
TEST_CASE("Test 2 Overlap messages")
{
Board board;
board.post(0, 0, Direction::Horizontal, "Dor311557425");
CHECK(board.read(0, 0, Direction::Horizontal, 11) == "Dor311557425");
board.post(0, 1, Direction::Vertical, "0502151255");
CHECK(board.read(0, 1, Direction::Horizontal, 10) == "0502151255");
CHECK(board.read(0, 0, Direction::Horizontal, 3) == "D0r");
board.post(0, 2, Direction::Horizontal, "aaaaa");
CHECK(board.read(0, 1, Direction::Vertical, 3) == "0a0");
board.post(0, 2, Direction::Vertical, "ddddd");
CHECK(board.read(0, 0, Direction::Horizontal, 7) == "D0d3115");
board.post(0, 0, Direction::Vertical, "HELLO");
CHECK(board.read(0, 0, Direction::Horizontal, 3) == "H0d");
board.post(0, 4, Direction::Vertical, "World");
CHECK(board.read(0, 0, Direction::Horizontal, 7) == "H0d3W15");
}
| true |
4fdd39990cca252d540edb145913a03d2dea9732 | C++ | josejovian/algorithm-practice | /520A.cpp | UTF-8 | 342 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
int main() {
int L;
scanf("%d",&L);
getchar();
int x = 0;
char c;
int letter[26] = {0};
int unique = 0;
while(c = getchar()) {
if(c == '\n') break;
if(c >= 'a' && 'z' >= c) c -= 32;
letter[c-'A']++;
if(letter[c-'A']==1) unique++;
}
if(unique==26) printf("YES\n");
else printf("NO\n");
return 0;
}
| true |
9582cc7b62e9df89834a3cd511c4ac684c7cea43 | C++ | CM4all/libcommon | /src/spawn/Mount.hxx | UTF-8 | 3,853 | 2.578125 | 3 | [] | no_license | // SPDX-License-Identifier: BSD-2-Clause
// Copyright CM4all GmbH
// author: Max Kellermann <mk@cm4all.com>
#pragma once
#include "translation/Features.hxx"
#include "io/FileDescriptor.hxx"
#include "util/IntrusiveForwardList.hxx"
#include <cstdint>
class AllocatorPtr;
class MatchData;
class VfsBuilder;
struct Mount : IntrusiveForwardListHook {
const char *source;
const char *target;
/**
* If this is defined, then it is used instead of #source.
* This is useful for instances inside #PreparedChildProcess
* where the caller may want to prepare mounting. The file
* descriptor is owned by the caller.
*
* This is only supported by the following types: BIND,
* BIND_FILE, NAMED_TMPFS.
*/
FileDescriptor source_fd = FileDescriptor::Undefined();
enum class Type : uint_least8_t {
/**
* Bind-mount the directory #source onto #target.
*/
BIND,
/**
* Bind-mount the file #source onto #target.
*/
BIND_FILE,
/**
* Mount an empty tmpfs on #target.
*/
TMPFS,
/**
* Mount the tmpfs with the gviven name (#source) on
* #target. If a tmpfs with that name does not exist,
* an empty one is created and will remain for some
* time even after the last child process using it
* exits.
*/
NAMED_TMPFS,
/**
* Write #source to the read-only file #target. This
* either creates a new file in tmpfs (if #target is
* located in a tmpfs) or bind-mounts a tmpfs file to
* the given #target (which must already exist as a
* regular file).
*/
WRITE_FILE,
} type = Type::BIND;
#if TRANSLATION_ENABLE_EXPAND
bool expand_source = false;
#endif
bool writable;
/**
* Omit the MS_NOEXEC flag?
*/
bool exec;
/**
* Ignore ENOENT?
*/
bool optional = false;
constexpr Mount(const char *_source, const char *_target,
bool _writable=false,
bool _exec=false) noexcept
:source(_source), target(_target),
writable(_writable), exec(_exec) {
}
struct Tmpfs {};
constexpr Mount(Tmpfs, const char *_target, bool _writable) noexcept
:source(nullptr), target(_target),
type(Type::TMPFS),
writable(_writable), exec(false) {}
struct NamedTmpfs {};
constexpr Mount(NamedTmpfs, const char *_name, const char *_target,
bool _writable) noexcept
:source(_name), target(_target),
type(Type::NAMED_TMPFS),
writable(_writable), exec(false) {}
struct WriteFile {};
constexpr Mount(WriteFile, const char *path,
const char *contents) noexcept
:source(contents), target(path),
type(Type::WRITE_FILE),
writable(false), exec(false) {}
Mount(AllocatorPtr alloc, const Mount &src) noexcept;
#if TRANSLATION_ENABLE_EXPAND
bool IsExpandable() const noexcept {
return expand_source;
}
[[gnu::pure]]
static bool IsAnyExpandable(const IntrusiveForwardList<Mount> &list) noexcept {
for (const auto &i : list)
if (i.IsExpandable())
return true;
return false;
}
void Expand(AllocatorPtr alloc, const MatchData &match_data);
static void ExpandAll(AllocatorPtr alloc,
IntrusiveForwardList<Mount> &list,
const MatchData &match_data);
#endif
private:
void ApplyBindMount(VfsBuilder &vfs_builder) const;
void ApplyBindMountFile(VfsBuilder &vfs_builder) const;
void ApplyTmpfs(VfsBuilder &vfs_builder) const;
void ApplyNamedTmpfs(VfsBuilder &vfs_builder) const;
void ApplyWriteFile(VfsBuilder &vfs_builder) const;
public:
/**
* Throws std::system_error on error.
*/
void Apply(VfsBuilder &vfs_builder) const;
static IntrusiveForwardList<Mount> CloneAll(AllocatorPtr alloc,
const IntrusiveForwardList<Mount> &src) noexcept;
/**
* Throws std::system_error on error.
*/
static void ApplyAll(const IntrusiveForwardList<Mount> &m,
VfsBuilder &vfs_builder);
char *MakeId(char *p) const noexcept;
static char *MakeIdAll(char *p, const IntrusiveForwardList<Mount> &m) noexcept;
};
| true |
9dc2ad8fe7ec6ed00a630d34fdcf6208a9108800 | C++ | abeaumont/competitive-programming | /kattis/pot.cc | UTF-8 | 367 | 2.6875 | 3 | [
"WTFPL",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // https://open.kattis.com/problems/pot
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
int n;
cin >> n;
ll sum = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
int p = x % 10;
x = x / 10;
ll prod = 1;
for (int j = 0; j < p; j++) {
prod *= x;
}
sum += prod;
}
cout << sum << endl;
}
| true |
62156e2ccfe7e502389e0e29569ebea1be352a4c | C++ | chaimaj/Mini-RLM | /RLM_Application/Frame.cpp | UTF-8 | 955 | 3.421875 | 3 | [] | no_license | /*
* File: Frame.cpp
* Author: PC-Z510
*
* Created on 4 mars 2015, 17:38
*/
#include "Frame.h"
Frame::Frame() {
width = 0;
height = 0;
frame_str = "";
}
/// Create frame of indicated width and height with string.
Frame::Frame(int new_width, int new_height, string frame_str) {
width = new_width;
height = new_height;
this->frame_str = frame_str;
}
/// Set width of frame.
void Frame::setWidth(int new_width) {
width = new_width;
}
/// Get width of frame.
int Frame::getWidth() const {
return width;
}
/// Set height of frame.
void Frame::setHeight(int new_height) {
height = new_height;
}
/// Get height of frame.
int Frame::getHeight() const {
return height;
}
/// Set frame characters (stored as string).
void Frame::setString(string new_frame_str) {
frame_str = new_frame_str;
}
/// Get frame characters (stored as string).
string Frame::getString() const {
return frame_str;
}
| true |
da458f9dd255a2951a2c4cceaac9877989969b6f | C++ | KinglittleQ/cs144 | /tests/byte_stream_many_writes.cc | UTF-8 | 1,343 | 2.765625 | 3 | [] | no_license | #include "byte_stream.hh"
#include "byte_stream_test_harness.hh"
#include "util.hh"
#include <exception>
#include <iostream>
using namespace std;
int main() {
try {
auto rd = get_random_generator();
const size_t NREPS = 1000;
const size_t MIN_WRITE = 10;
const size_t MAX_WRITE = 200;
const size_t CAPACITY = MAX_WRITE * NREPS;
{
ByteStreamTestHarness test{"many writes", CAPACITY};
size_t acc = 0;
for (size_t i = 0; i < NREPS; ++i) {
const size_t size = MIN_WRITE + (rd() % (MAX_WRITE - MIN_WRITE));
string d(size, 0);
generate(d.begin(), d.end(), [&] { return 'a' + (rd() % 26); });
test.execute(Write{d}.with_bytes_written(size));
acc += size;
test.execute(InputEnded{false});
test.execute(BufferEmpty{false});
test.execute(Eof{false});
test.execute(BytesRead{0});
test.execute(BytesWritten{acc});
test.execute(RemainingCapacity{CAPACITY - acc});
test.execute(BufferSize{acc});
}
}
} catch (const exception &e) {
cerr << "Exception: " << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| true |
3b0e0cab4811a60f95a561bb6c93d070108ec2b0 | C++ | gurnoorsingh8/Pepcoding-Basics | /Foundation/Arrays/rotate.cpp | UTF-8 | 672 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
void reverse(vector<int>& arr, int i, int j)
{
while(i < j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
void rotate(vector<int>& arr, int k)
{
int n = arr.size();
k = (k % n + n) % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
for(int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
int k;
cin >> k;
rotate(arr, k);
return 0;
} | true |
96a786037ceba42e2a83b5141b3c46d644dd46ae | C++ | Samm07/Code-Library | /longest_increasing_subsequence.cpp | UTF-8 | 627 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
FILE *fp;
fp=fopen("input.txt", "r");
int n;
fscanf(fp, "%d\n", &n);
int arr[n];
int i,j;
for(i=0;i<n;i++)
fscanf(fp,"%d ",&arr[i]);
int lis[n];
for(i=0;i<n;i++)
lis[i]=1;
for(i=0;i<n;i++)
{
for(j=0;j<i;j++)
{
if(arr[i]>arr[j] && lis[j]+1>lis[i])
lis[i]=lis[j]+1;
}
}
int max=1;
for(i=0;i<n;i++)
{
if(lis[i]>max)
max=lis[i];
}
cout<<max;
}
| true |
b901cf149bd3ee4e2e532232516f3468772b872f | C++ | personalrobotics/chimera | /test/examples/06_template_class/template_class.h | UTF-8 | 397 | 2.59375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include <vector>
namespace chimera_test
{
template <typename T>
class Vector
{
public:
Vector() = default;
void resize(int dim)
{
m_data.resize(dim);
}
int size() const
{
return m_data.size();
}
private:
std::vector<T> m_data;
};
// Explicit instantiation declaration
template class Vector<double>;
} // namespace chimera_test
| true |
58a994546730dd7b066cda80b4782154db3ba0af | C++ | zhongxinghong/LeetCode | /submissions/1442-连通网络的操作次数-88874063.cpp | UTF-8 | 1,616 | 3.140625 | 3 | [
"MIT"
] | permissive | /**
* Submission ID: 88874063
* Question ID: 1442
* Question Title: 连通网络的操作次数
* Question URL: https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/
* Solution Time: 2020-07-18 02:29:03
* Solution Test Result: 36 / 36
* Solution Status: Accepted
* Solution Memory: 59.1 MB
* Solution Runtime: 280 ms
*/
class Solution {
public:
void visitConnectedComponent(
const std::vector<std::vector<int>> &g,
std::vector<bool> &vis,
const int &n,
int node)
{
int i;
std::stack<int> st;
st.push(node);
vis[node] = true;
while (!st.empty())
{
node = st.top();
st.pop();
for (i = 0; i < g[node].size(); ++i)
{
if (vis[g[node][i]])
continue;
st.push(g[node][i]);
vis[g[node][i]] = true;
}
}
}
int makeConnected(int n, vector<vector<int>>& connections)
{
if (connections.size() < n - 1)
return -1;
int i, cnt = 0;
std::vector<std::vector<int>> g(n);
std::vector<bool> vis(n, false);
for (i = 0; i < connections.size(); ++i)
{
g[connections[i][0]].push_back(connections[i][1]);
g[connections[i][1]].push_back(connections[i][0]);
}
for (i = 0; i < n; ++i)
{
if (vis[i])
continue;
cnt++;
visitConnectedComponent(g, vis, n, i);
}
return cnt - 1;
}
};
| true |
9da20200b449ee178816a98785394aa94eadd125 | C++ | DimaKolt/github_hw3 | /whatsup_tests/part1test.cpp | UTF-8 | 1,254 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include "PCQueue.hpp"
#include "Semaphore.hpp"
#define N 10
Semaphore s(10);
int x=0;
PCQueue<int>* q = new PCQueue<int>;
void* print_msg(void* i){
s.down();
x++;
for (long j = 0; j <100000000 ; ++j) {
}
if(x > 10)
cout << x << endl;
/*cout << *(int*)i << " and x = " << x << endl;*/
x--;
s.up();
return nullptr;
}
void* writer(void* data) {
q->push(*(int*)data);
cout << "I pushed something " << *(int*)data << endl;
return nullptr;
}
void* reader(void* nothing) {
int res = q->pop();
cout << res << endl;
return nothing;
}
int main() {
pthread_t a[N];
/* int id[N];
for (int k = 0; k <N ; ++k) {
id[k]=k+1;
}
for (int i = 0; i < N; ++i) {
pthread_create(&a[i], nullptr, print_msg, (void*)&id[i]);
}
for (int j = 0; j < N; ++j) {
pthread_join(a[j], nullptr);
}*/
int data[N/2];
for (int j = 0; j < N/2; ++j)
data[j] = j;
for (int i = 0; i <N ; i++) {
pthread_create(&a[i++], nullptr, writer, (void*)&data[i/2]);
pthread_create(&a[i], nullptr, reader, nullptr);
}
for (int j = 0; j < N; ++j) {
pthread_join(a[j], nullptr);
}
return 0;
}
| true |
a888a8a4c6493e9eec04183e442e5f16cdcf8e9a | C++ | qazwsxedc121/leetcode | /cpp/substring_with_concatenation_of_all_words.cpp | UTF-8 | 1,225 | 2.75 | 3 | [] | no_license | class Solution {
private:
bool eq(map<string, int>& m1, map<string, int>& m2){
for(map<string, int>::iterator it = m1.begin(); it != m1.end(); ++it){
if(m2[it->first] != it->second){
return false;
}
}
return true;
}
public:
vector<int> findSubstring(string s, vector<string>& words) {
int n = words.size();
int wl = words[0].length();
map<string,int> histogram0;
for(int i = 0; i < n; i += 1){
histogram0[words[i]] += 1;
}
vector<int> res;
int sn = s.length();
for(int i = 0; i < sn - (wl * n) + 1; i += 1){
map<string, int> histogram1;
bool flag = false;
for(int j = i; j < i + (wl * n); j += wl){
string word = s.substr(j, wl);
histogram1[word] += 1;
if(histogram1[word] > histogram0[word]){
flag = true;
break;
}
}
if(flag) continue;
if(eq(histogram0, histogram1)){
res.push_back(i);
}
}
return res;
}
};
| true |
be3556c1840a77ca387aec015af4b08da4946132 | C++ | HypED-prototyping/navigation | /demo-vector.cpp | UTF-8 | 851 | 3.25 | 3 | [] | no_license | #include "vector.hpp"
#include <iostream>
template <typename T,int N>
void print(Vector<T,N> &v)
{
for(int i=0;i<N;i++)
std::cout << v[i] << '\t';
std::cout << '\n';
}
int main()
{
Vector<int,10> vector1;
Vector<int,10> vector2;
Vector<int,10> vector3;
Vector<double,10> vector4;
print(vector1);
print(vector2);
print(vector3);
for(int i=0;i<10;i++)
vector1[i] = i+1,
vector4[i] = 1.1;
print(vector4);
vector2 += 1;
vector3 = vector1 + vector2;
vector2 = vector2 - 2;
vector3 = vector1 - vector2;
vector3 = vector1 * 5.0;
vector3 = vector1 / 5.0;
vector4 = vector4 + vector1;
vector4 = vector4 - vector1;
(vector1 == vector3) ? std::cout << "False" :
std::cout << "True"; std :: cout << '\n';
print(vector1);
print(vector2);
print(vector3);
print(vector4);
}
| true |
d98afb4abc97540b28c761627ef4c624b6edcf40 | C++ | JayantGoel001/CodeChef | /Coldplay.cpp | UTF-8 | 187 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include <cmath>
using namespace std;
int main(){
int t;
cin>>t;
while (t--){
float m,s;
cin>>m>>s;
cout<<floor(m/s)<<"\n";
}
} | true |
9565a71962726af7ebf7d53544c34a551f4445e9 | C++ | RaiSW/Crc2Hex2 | /Crc2Hex/CRC16.h | UTF-8 | 242 | 2.578125 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class CRC16
{
private:
#define GENERATOR_POLYNOM ((0x8005 / 4) | 0x8000)
public:
uint16_t uiSum;
CRC16(void);
CRC16(uint16_t);
uint16_t Add(uint8_t* pucStart, uint8_t* pucEnd);
};
| true |
36f59d8752cfcb49cef890b11db4d9ccc0f759cc | C++ | reichlab/bayesian_non_parametric | /SIR/.SIR/build_openmp_sse/src/bi/stopper/MinimumESSStopper.hpp | UTF-8 | 2,438 | 2.875 | 3 | [] | no_license | /**
* @file
*
* @author Anthony Lee
* @author Lawrence Murray <lawrence.murray@csiro.au>
*/
#ifndef BI_STOPPER_MINIMUMESSSTOPPER_HPP
#define BI_STOPPER_MINIMUMESSSTOPPER_HPP
#include "../math/constant.hpp"
#include "../math/function.hpp"
namespace bi {
/**
* Stopper based on ESS criterion.
*
* @ingroup method_stopper
*/
class MinimumESSStopper {
public:
/**
* @copydoc Stopper::Stopper()
*/
MinimumESSStopper();
/**
* @copydoc Stopper::stop
*/
bool stop(const int T, const double threshold, const double maxlw = BI_INF);
#ifdef ENABLE_MPI
/**
* @copydoc Stopper::stop
*/
bool distributedStop(const int T, const double threshold, const double maxlw = BI_INF);
#endif
/**
* @copydoc Stopper::add(const double, const double)
*/
void add(const double lw, const double maxlw = BI_INF);
/**
* @copydoc Stopper::add()
*/
template<class V1>
void add(const V1 lws, const double maxlw = BI_INF);
/**
* @copydoc Stopper::reset()
*/
void reset();
private:
/**
* Sum of weights.
*/
double sumw;
/**
* Sum of squared weights.
*/
double sumw2;
};
}
#include "../mpi/mpi.hpp"
inline bi::MinimumESSStopper::MinimumESSStopper() :
sumw(0.0), sumw2(0.0) {
//
}
inline bool bi::MinimumESSStopper::stop(const int T,
const double threshold, const double maxlw) {
double ess = (sumw * sumw) / sumw2;
double minsumw = bi::exp(maxlw) * (threshold - 1.0) / 2.0;
return (sumw >= minsumw && ess >= threshold);
}
#ifdef ENABLE_MPI
inline bool bi::MinimumESSStopper::distributedStop(const int T, \
const double threshold, const double maxlw) {
boost::mpi::communicator world;
double sumw1 = boost::mpi::all_reduce(world, sumw, std::plus<double>());
double sumw21 = boost::mpi::all_reduce(world, sumw2, std::plus<double>());
double ess = (sumw1 * sumw1) / sumw21;
double minsumw = bi::exp(maxlw) * (threshold - 1.0) / 2.0;
return (sumw1 >= minsumw && ess >= threshold);
}
#endif
inline void bi::MinimumESSStopper::add(const double lw, const double maxlw) {
/* pre-condition */
BI_ASSERT(lw <= maxlw);
sumw += bi::exp(lw);
sumw2 += bi::exp(2.0*lw);
}
template<class V1>
void bi::MinimumESSStopper::add(const V1 lws, const double maxlw) {
/* pre-condition */
BI_ASSERT(max_reduce(lws) <= maxlw);
sumw += sumexp_reduce(lws);
sumw2 += sumexpsq_reduce(lws);
}
inline void bi::MinimumESSStopper::reset() {
sumw = 0.0;
sumw2 = 0.0;
}
#endif
| true |
41af3a50b0618fb448e7a23098436ada79352af8 | C++ | SrinivasuluCharupally/expert_programming | /module-6/6-13.cpp | UTF-8 | 762 | 3.65625 | 4 | [] | no_license | Question: The probability of a car passing a certain intersection in a 20 minute windows is 0.9. What is the probability of a car passing the intersection in a 5 minute window? (Assuming a constant probability throughout)
Answer: This is one of the basic probability question asked in a software interview. Let’s start by creating an equation. Let x be the probability of a car passing the intersection in a 5 minute window.
Probability of a car passing in a 20 minute window = 1 – (probability of no car passing in a 20 minute window)
Probability of a car passing in a 20 minute window = 1 – (1 – probability of a car passing in a 5 minute window)^4
0.9 = 1 – (1 – x)^4
(1 – x)^4 = 0.1
1 – x = 10^(-0.25)
x = 1 – 10^(-0.25) = 0.4377 | true |
44af1916d43b68af4dea85a0697a8255a9381185 | C++ | ca-l-eb/networking | /src/http_response.h | UTF-8 | 1,164 | 2.640625 | 3 | [
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL"
] | permissive | #ifndef CMD_HTTP_RESPONSE_H
#define CMD_HTTP_RESPONSE_H
#include <map>
#include <string>
#include <vector>
#include "stream.h"
namespace cmd
{
class http_response
{
public:
http_response();
explicit http_response(cmd::stream &stream);
int status_code();
std::string status_message();
std::string body();
std::multimap<std::string, std::string> &headers();
std::string version();
private:
int status;
std::string http_version;
std::string status_message_str;
std::string body_str;
std::multimap<std::string, std::string> headers_map;
size_t length;
enum class body_type { NONE, CHUNKED, LENGTH, ALL } type;
void read_response(cmd::stream &s);
void process_headers(cmd::stream &s);
void check_response_status(const std::string &status_line);
void add_header_to_map(const std::string &line);
void check_body_method();
void check_content_length();
void check_transfer_encoding();
void do_chunked(cmd::stream &s);
void do_content_length(cmd::stream &s);
void do_read_all(cmd::stream &s);
void check_connection_close(cmd::stream &s);
};
} // namespace cmd
#endif
| true |
3a0ae8f152ef16a9f0631f438a5bf724d1e22fde | C++ | vicutrinu/pragma-studios | /src/pragma/data/data.cpp | UTF-8 | 13,683 | 2.875 | 3 | [
"MIT"
] | permissive | /*
* data.cpp
* pragma
*
* Created by Victor on 26/12/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#include <pragma/types.h>
#include "data.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
namespace pragma
{
//------------------------------------------------------------------------------------------------------------------
// FloatToVoidPointer
//------------------------------------------------------------------------------------------------------------------
inline void* FloatToVoidPointer(float aFloat)
{
union TUnion
{
void* mVoid;
float mFloat;
};
TUnion lData;
lData.mFloat = aFloat;
return lData.mVoid;
}
//------------------------------------------------------------------------------------------------------------------
// VoidPointerToFloat
//------------------------------------------------------------------------------------------------------------------
inline float VoidPointerToFloat(void* aPointer)
{
union TUnion
{
void* mVoid;
float mFloat;
};
TUnion lData;
lData.mVoid = aPointer;
return lData.mFloat;
}
//------------------------------------------------------------------------------------------------------------------
// Value
//------------------------------------------------------------------------------------------------------------------
Value::Value(const Value& aValue)
: mIsOk(false)
, mType(eString)
, mIsArray(false)
, mCount(0)
, mData(0)
{
if(aValue.IsOk())
{
if(aValue.IsArray())
{
if(aValue.mType == eString)
{
Set("");
SetAsArray(true);
for(size_t i = 0; i < aValue.GetCount(); ++i)
{
const char* lString;
aValue.GetAt(i, lString);
SetAt(i, lString);
}
}
else if(aValue.mType == eFloat)
{
Set(0.f);
SetAsArray(true);
for(size_t i = 0; i < aValue.GetCount(); ++i)
{
float lFloat;
aValue.GetAt(i, lFloat);
SetAt(i, lFloat);
}
}
}
else
{
if(aValue.mType == eString)
{
const char* lString;
aValue.Get(lString);
Set(lString);
}
else if(aValue.mType == eFloat)
{
float lFloat;
aValue.Get(lFloat);
Set(lFloat);
}
}
}
}
//------------------------------------------------------------------------------------------------------------------
// Clear
//------------------------------------------------------------------------------------------------------------------
void Value::Clear()
{
if(IsOk())
{
if(!IsArray())
ClearAt(&mData);
else
{
void** lArray = (void**)mData;
for (size_t i = 0; i < mCount; ++i)
ClearAt(&lArray[i]);
free(mData);
}
}
mData = 0;
mType = eString;
mCount = 0;
mIsArray = false;
mIsOk = false;
}
//------------------------------------------------------------------------------------------------------------------
// SetAsArray
//------------------------------------------------------------------------------------------------------------------
void Value::SetAsArray(bool aIsArray)
{
if(!IsOk())
return;
if(aIsArray)
{
if(!IsArray())
{
void** lNew = (void**)malloc(sizeof(void*));
memcpy(lNew, &mData, sizeof(void*));
mData = (void*)lNew;
mCount = 1;
}
}
else
{
if(IsArray() && mCount > 0)
{
switch (mType)
{
case eString:
{
const char* lString;
GetAt(0, lString);
Value lVal;
lVal.Set(lString);
lVal.Get(lString);
Clear();
mIsArray = false;
Set(lString);
break;
}
case eFloat:
{
float lFloat;
GetAt(0, lFloat);
Clear();
mIsArray = false;
Set(lFloat);
break;
}
default:
break;
}
}
}
mIsArray = aIsArray;
}
//------------------------------------------------------------------------------------------------------------------
// ClearAt
//------------------------------------------------------------------------------------------------------------------
void Value::ClearAt(void** aPtr)
{
switch (mType)
{
case eString:
{
char* lString = (char*)*aPtr;
if(lString)
{
free((void*)lString);
}
break;
}
case eFloat:
break;
default:
break;
}
}
//------------------------------------------------------------------------------------------------------------------
// Set
//------------------------------------------------------------------------------------------------------------------
void Value::Set(const char* aValue)
{
if(IsArray())
return;
if(IsOk())
Clear();
mType = eString;
if(aValue)
{
SetAt(&mData, aValue);
mIsOk = true;
}
}
//------------------------------------------------------------------------------------------------------------------
// Get
//------------------------------------------------------------------------------------------------------------------
bool Value::Get(const char*& aString) const
{
if(IsOk() && !IsArray() && mType == eString)
{
return GetAt((void**)&mData, aString);
}
else
{
aString = 0;
return false;
}
}
//------------------------------------------------------------------------------------------------------------------
// Set
//------------------------------------------------------------------------------------------------------------------
void Value::Set(float aValue)
{
if(IsOk())
{
Clear();
}
mType = eFloat;
mIsArray = false;
SetAt(&mData, aValue);
mIsOk = true;
}
//------------------------------------------------------------------------------------------------------------------
// Get
//------------------------------------------------------------------------------------------------------------------
bool Value::Get(float& aFloat) const
{
if(IsOk() && !IsArray() && mType == eFloat)
{
return GetAt((void**)&mData, aFloat);
}
else
{
aFloat = 0;
return false;
}
}
//------------------------------------------------------------------------------------------------------------------
// SetAt
//------------------------------------------------------------------------------------------------------------------
void Value::SetAt(int aPosition, const char* aValue)
{
if(!IsOk())
return;
if(!IsArray())
return;
if(mType != eString)
return;
if(aPosition == mCount)
{ // resize pointers table
void* lNew = (void*)malloc(sizeof(void*) * (mCount + 1));
memcpy(lNew, mData, sizeof(void*) * mCount);
free(mData);
mData = lNew;
void** lArray = (void**)mData;
SetAt(&lArray[mCount], aValue);
mCount++;
}
else if(mCount > 0 && aPosition >= 0 && aPosition < mCount)
{
void** lArray = (void**)mData;
SetAt(&lArray[aPosition], aValue);
}
}
//------------------------------------------------------------------------------------------------------------------
// GetAt
//------------------------------------------------------------------------------------------------------------------
bool Value::GetAt(int aPosition, const char*& aValue) const
{
if(!IsArray())
return false;
if(mCount > 0 && aPosition >= 0 && aPosition < mCount)
{
void** lArray = (void**)mData;
return GetAt(&lArray[aPosition], aValue);
}
else
return false;
}
//------------------------------------------------------------------------------------------------------------------
// SetAt
//------------------------------------------------------------------------------------------------------------------
void Value::SetAt(int aPosition, float aValue)
{
if(!IsOk())
return;
if(!IsArray())
return;
if(mType != eFloat)
return;
if(aPosition == mCount)
{ // resize pointers table
void* lNew = (void*)malloc(sizeof(void*) * (mCount + 1));
memcpy(lNew, mData, sizeof(void*) * mCount);
free(mData);
mData = lNew;
void** lArray = (void**)mData;
SetAt(&lArray[mCount], aValue);
mCount++;
}
else if(mCount > 0 && aPosition >= 0 && aPosition < mCount)
{
void** lArray = (void**)mData;
SetAt(&lArray[aPosition], aValue);
}
}
//------------------------------------------------------------------------------------------------------------------
// GetAt
//------------------------------------------------------------------------------------------------------------------
bool Value::GetAt(int aPosition, float& aValue) const
{
if(!IsArray())
return false;
if(mCount > 0 && aPosition >= 0 && aPosition < mCount)
{
void** lArray = (void**)mData;
return GetAt(&lArray[aPosition], aValue);
}
else
return false;
}
//------------------------------------------------------------------------------------------------------------------
// SetAt
//------------------------------------------------------------------------------------------------------------------
void Value::SetAt(void** aPtr, const char* aValue)
{
char* lString;
lString = (char*)malloc(strlen(aValue) + 1);
strcpy(lString, aValue);
*aPtr = (void*)lString;
}
//------------------------------------------------------------------------------------------------------------------
// GetAt
//------------------------------------------------------------------------------------------------------------------
bool Value::GetAt(void** aPtr, const char*& aString) const
{
aString = (char*)*aPtr;
return true;
}
//------------------------------------------------------------------------------------------------------------------
// SetAt
//------------------------------------------------------------------------------------------------------------------
void Value::SetAt(void** aPtr, float aValue)
{
*aPtr = FloatToVoidPointer(aValue);
}
//------------------------------------------------------------------------------------------------------------------
// GetAt
//------------------------------------------------------------------------------------------------------------------
bool Value::GetAt(void** aPtr, float& aFloat) const
{
aFloat = VoidPointerToFloat(*aPtr);
return true;
}
//------------------------------------------------------------------------------------------------------------------
// PropertyList_UnitTest
//------------------------------------------------------------------------------------------------------------------
bool PropertyList_UnitTest()
{
Value lVal;
lVal.Set("mierda");
lVal.SetAsArray(true);
lVal.SetAt(1, "es");
lVal.SetAt(2, "caca");
lVal.SetAt(2, 1234); // ignore
for(size_t i = 0; i < 3; ++i)
{
const char* lStr;
lVal.GetAt(i, lStr);
printf("%s\n", lStr);
}
PropertyList lList;
lList.Set(string("HolaArray"), lVal);
lVal.SetAsArray(false);
const char* lStr;
lVal.Get(lStr);
printf("%s\n", lStr);
lList.Set(string("HolaStr"), lVal);
lVal.Clear();
lVal.Set(1234);
float lFloat;
lVal.Get(lFloat);
printf("%f\n", lFloat);
lList.Set(string("HolaFloat"), lVal);
lList.Log();
printf("%f\n", lList.GetFloat(string("HolaFloat"), -1));
printf("%s\n", lList.GetString(string("HolaStr"), string("caca")).c_str());
return true;
}
void PropertyList::Set(const string& aKey, const Value& aValue)
{
std::pair<string, Value> lPair(aKey, aValue);
mList.push_back(lPair);
}
Value PropertyList::Get(const string& aKey, const Value& aDefault)
{
for(size_t i = 0; i < mList.size(); ++i)
{
if(mList[i].first == aKey)
{
return mList[i].second;
}
}
return aDefault;
}
void PropertyList::SetString(const string& aKey, const string& aString)
{
Value lDefault;
lDefault.Set(aString.c_str());
Set(aKey, lDefault);
}
void PropertyList::SetFloat(const string& aKey, const float aFloat)
{
Value lDefault;
lDefault.Set(aFloat);
Set(aKey, lDefault);
}
string PropertyList::GetString(const string& aKey, const string& aDefault /*= string::Empty*/)
{
Value lDefault;
lDefault.Set(aDefault.c_str());
Value lRetVal = Get(aKey, lDefault);
const char* lStr;
lRetVal.Get(lStr);
return(string(lStr));
}
float PropertyList::GetFloat(const string& aKey, float aDefault /*= 0*/)
{
Value lDefault;
lDefault.Set(aDefault);
Value lRetVal = Get(aKey, lDefault);
float lFloat;
lRetVal.Get(lFloat);
return lFloat;
}
void PropertyList::Log()
{
for(size_t i = 0; i < mList.size(); ++i)
{
printf("Key: %s\n", mList[i].first.c_str());
printf("Value:");
if(mList[i].second.IsArray())
{
switch( mList[i].second.GetType() )
{
case Value::eString:
{
for(size_t j = 0; j < mList[i].second.GetCount(); ++j)
{
const char* lString;
mList[i].second.GetAt(j, lString);
printf("%s", lString);
if(j < mList[i].second.GetCount() - 1)
printf(", ");
else
printf("\n");
}
break;
}
case Value::eFloat:
{
for(size_t j = 0; j < mList[i].second.GetCount(); ++j)
{
float lFloat;
mList[i].second.GetAt(j, lFloat);
printf("%f", lFloat);
if(j < mList[i].second.GetCount() - 1)
printf(", ");
else
printf("\n");
}
break;
}
default:
break;
}
}
else
{
switch( mList[i].second.GetType() )
{
case Value::eString:
{
const char* lString;
mList[i].second.Get(lString);
printf("%s\n", lString);
break;
}
case Value::eFloat:
{
float lFloat;
mList[i].second.Get(lFloat);
printf("%f\n", lFloat);
break;
}
default:
break;
}
}
}
}
}
| true |
a97abec3635e440106a64f02c8ecbaa8cfb45246 | C++ | dundunnp/answers-to-C-Primer-Plus | /chapter 12 exercise/c12_2/string_c12_2.cpp | UTF-8 | 1,917 | 3.296875 | 3 | [] | no_license | #include "c12_2.h"
#include <cstring>
#include <cctype>
using std::cin;
using std::cout;
String::String(const char* ch)
{
len = strlen(ch);
str = new char[len + 1];
strcpy(str, ch);
}
String::String()
{
len = 0;
str = nullptr;
}
String::String(const String& s)
{
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
}
String::~String()
{
delete[] str;
}
void String::stringup()
{
for (int i = 0; i < len; i++)
str[i] = toupper(str[i]);
}
void String::stringlow()
{
for (int i = 0; i < len; i++)
str[i] = tolower(str[i]);
}
int String::has(char ch) const
{
int count = 0;
for (int i = 0; i < len; i++)
{
if (str[i] == ch)
count++;
}
return count;
}
String& String::operator=(const String& s)
{
if (this == &s)
return *this;
delete[] str;
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
return *this;
}
String& String::operator=(const char* s)
{
delete[] str;
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
return *this;
}
ostream& operator<<(ostream& os, const String& s)
{
if (s.str)
os << s.str;
else
os << "nothing";
return os;
}
istream& operator>>(istream& is, String& s)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
s = temp;
while (is && is.get() != '\n')
continue;
return is;
}
String operator+(const String& s1, const String& s2)
{
String temp;
temp.len = s1.len + s2.len;
temp.str = new char[temp.len + 1];
strcpy(temp.str, s1.str);
strcat(temp.str, s2.str);
return temp;
}
String operator+(const char* ch, const String& s)
{
String temp;
temp.len = strlen(ch) + s.len;
temp.str = new char[temp.len + 1];
strcpy(temp.str, ch);
strcat(temp.str, s.str);
return temp;
}
bool operator==(const String& s1, const String& s2)
{
return (strcmp(s1.str, s2.str) == 0);
} | true |
f321a52a2b11a1b37e4d4f50757d70be6d0c9037 | C++ | KirilPanika/HardWorkCpp | /...Square.Fibonacci.Maximum.Factorial.cpp | UTF-8 | 1,084 | 3.953125 | 4 | [] | no_license | #include <iostream>
using namespace std;
float square1(float num){
return num * num;
}
float square2(float *num){
return *num * *num;
}
void Fibonacci(int n, int i = 0, int f1 = 0, int f2 = 1){
if (i <= n ) {
if (i == 0) {
cout << 0 << ' ';
Fibonacci(n, i+1, 0, 1);
}
else if (i == 1) {
cout << 1 << ' ';
Fibonacci(n, i+1, 0, 1);
}
else {
cout << f1 + f2 << ' ';
Fibonacci(n, i+1, f2, f1 + f2);
}
}
}
void Maximum(){
float a, b, c;
cin >> a;
cin >> b;
cin >> c;
float max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
cout << max << endl;
}
int factorial (int x) {
if (x > 1) {
return factorial(x - 1) * x;
}
else {
return 1;
}
}
int main() {
// Maximum();
float num = 2.5;
// cout << square1(num) << endl;
// cout << square2(&num) << endl;
// Fibonacci(10);
cout << factorial(4);
return 0;
}
| true |
87820533fa482a8ef58c440030212f168c393476 | C++ | feannyn/NAF90_DS2017 | /Assignment_2/List.hpp | UTF-8 | 12,919 | 3.234375 | 3 | [] | no_license | //Nicholas Feanny; Naf16b;
using namespace std;
//helper const iterator constructor (1 parameter)
template<typename T>
List<T>::const_iterator::const_iterator(Node* p )
{
current = p;
}
//helper function retrieve
template<typename T>
T& List<T>::const_iterator::retrieve() const
{
//if I understand this correctly all this does is retrieve the data from the current
//Node
return this->current->data;
}
template<typename T>
List<T>::const_iterator::const_iterator()// default zero parameter constructor
{
current = nullptr;
}
template<typename T>
const T& List<T>::const_iterator::operator*() const // operator*() to return element
{
return retrieve();
}
// increment/decrement operators
template<typename T>//pre increment
typename List<T>::const_iterator& List<T>::const_iterator::operator++()
{
this->current = this->current->next;//set calling object current to current's next
return *this;//dereferenced current to access next
//which is a node pointer and is holding an address
// of the next node
// it must be dereferenced to access it's data
}
template<typename T>//post increment
typename List<T>::const_iterator List<T>::const_iterator::operator++(int)
{
auto temp = *this;//auto is representative of the return value
//so you do not have to type it out
this->current = this->current->next;
return temp ;
}
template<typename T>//pre decrement
typename List<T>::const_iterator& List<T>::const_iterator::operator--()
{
this->current = this->current->prev;//set calling object current to current's next
return *this;//dereferenced current to access next
//which is a node pointer and is holding an address
// of the next node
// it must be dereferenced to access it's data
}
template<typename T>//post decrement
typename List<T>::const_iterator List<T>::const_iterator::operator--(int)
{
auto temp = *this;//auto is representative of the return value
//so you do not have to type it out
//List<T>::const_iterator& (the return)
this->current = this->current->prev;//alternatively --(*this)
return temp ;
}
// comparison operators
template<typename T>
bool List<T>::const_iterator::operator==(const const_iterator &rhs) const
{
//compare the data of the calling object and the argument object passed in
if(current == rhs.current)
{
return true;
}
return false;
}
template<typename T>
bool List<T>::const_iterator::operator!=(const const_iterator &rhs) const
{
//compare the data of the calling object and the argument object passed in
if(current != rhs.current)
{
return true;
}
return false;
//return !(this->current->data == rhs.current ->rhs.data);
}
//Iterator class function definitions
template<typename T>
List<T>::iterator::iterator() : const_iterator()
{
}
//protected 1-parameter constructor (iterator class)
template<typename T>
List<T>::iterator::iterator(Node *p) : const_iterator(p)
{
}
template<typename T>
T& List<T>::iterator::operator*()
{
//use the scoper resolution mechanics to clarify where the retrieve function is
//coming from
//scope resoluton operator is used by a derived class
//in order to determine the specific class a method/ memeber data belongs to
return const_iterator::retrieve();
}
template<typename T>
const T& List<T>::iterator::operator*() const
{
return const_iterator::operator*();
}
// increment/decrement operators
template<typename T>
typename List<T>::iterator& List<T>::iterator::operator++()
{
this->current = this->current->next;
return *this;
}
template<typename T>
typename List<T>::iterator List<T>::iterator::operator++(int)
{
auto temp = this->current;
this->current = this->current->next;
return temp;
}
template<typename T>
typename List<T>::iterator& List<T>::iterator::operator--()
{
this->current = this->current->prev;
return this->current;
}
template<typename T>
typename List<T>::iterator List<T>::iterator::operator--(int)
{
auto temp = this->current;
this->current = this->current->next;
return temp;
}
//LIST CLASS DEFINITIONS
// constructor, desctructor, copy constructoList();
//init() helper function definition
template<typename T>
void List<T>::init()
{
theSize = 0;
head = new Node;
tail = new Node;
head->next = tail;
tail->prev = head;
tail->next = nullptr;
head->prev = nullptr;
}
template<typename T>
List<T>::List() // default zero parameter constructor
{
init();
}
template<typename T>
List<T>::List(const List &rhs) // copy constructor
{
if(this != &rhs)
{
Node* holder = head->next;
Node* rhsHolder = rhs.head->next;
theSize = rhs.theSize;
head = rhs.head;
tail = rhs.tail;
for(int i = 0; i < theSize; i++)
{
holder = rhsHolder;
holder = holder->next;
rhsHolder = rhsHolder->next;
}
}
}
template<typename T>
List<T>::List(List && rhs) // move constructor
{
theSize = rhs.theSize;
head = rhs.head;
tail = rhs.tail;
rhs.theSize = 0;
rhs.head = nullptr;
rhs.tail = nullptr;
}
// num elements with value of val
template<typename T>
List<T>::List(int num, const T& val)
{
init();
for(int i = 0; i < num; i++)
{
push_back(val);
}
}
// constructs with elements [start, end)
template<typename T>
List<T>::List(const_iterator start, const_iterator end)
{
init();
for(start; start != end; ++start)
{
push_back(*start);
}
// tail->next = nullptr;
}
// constructs with a copy of each of the elements in the initalizer_list
template<typename T>
List<T>::List (std::initializer_list<T> iList)
{
init();
int i = 0;
for(T x : iList)
{
push_back(x);
}
}
template<typename T>
List<T>::~List() // destructor
{
clear();
delete head;
delete tail;
}
// copy assignment operator
template<typename T>
const List<T>& List<T>::operator=(const List &rhs)
{
if(this != &rhs)
{
Node* holder = head->next;
Node* rhsHolder = rhs.head->next;
theSize = rhs.theSize;
head = rhs.head;
tail = rhs.tail;
for(int i = 0; i < theSize; i++)
{
holder = rhsHolder;
holder = holder->next;
rhsHolder = rhsHolder->next;
}
}
return *this;
}
// move assignment operator
template<typename T>
List<T>& List<T>::operator=(List && rhs)
{
//create temp variables to hold the address/values of calling object
int tempSize = theSize;
Node* tempHead = head;
Node* tempTail = tail;
// assign data of right side to left side
theSize = rhs.theSize;
head = rhs.head;
tail = rhs.tail;
//assign right side garabage data
rhs.theSize = tempSize;
rhs.head = tempHead;
rhs.tail = tempTail;
return *this;
}
// sets list to the elements of the initializer_list
template<typename T>
List<T>& List<T>::operator=(std::initializer_list<T> iList)
{
clear();
int i = 0;
for(T x: iList)
{
push_back(x);
}
return *this;
}
// member functions
template<typename T>
int List<T>::size() const // number of elements
{
return theSize;
}
template<typename T>
bool List<T>::empty() const // check if list is empty
{
if(theSize == 0)
{
return true;
}
else
{
return false;
}
}
template<typename T>
void List<T>::clear() // delete all elements
{
if(!empty())
{
while(!empty())
{
pop_back();
}
}
}
template<typename T>
void List<T>::reverse() // reverse the order of the elements
{
Node* current;
Node* holder;
Node* spike;
current = head;
while(current != head->next)
{
holder = current->next;
current->next = current->prev;
current->prev = holder;
current = holder;
}
spike = head;
head = tail;
tail = spike;
}
//FOR THE NEXT 4 FUNCTION DO WE
template<typename T>
T& List<T>::front() // reference to the first element
{
return head->next;
}
template<typename T>
const T& List<T>::front() const
{
return head->next;
}
template<typename T>
T& List<T>::back() // reference to the last element
{
return tail->prev;
}
template<typename T>
const T& List<T>::back() const
{
return tail->prev;
}
template<typename T>
void List<T>::push_front(const T & val) // insert to the beginning
{
iterator iter(head);
insert(iter, val);
}
template<typename T>
void List<T>::push_front(T && val) // move version of insert
{
insert(begin() ,std::move(val));
}
template<typename T>
void List<T>::push_back(const T & val) // insert to the end
{
iterator itr(tail->prev);
insert(itr, val);
}
template<typename T>
void List<T>::push_back(T && val) // move version of insert
{
iterator itr(tail->prev);
insert(itr, std::move(val));
}
template<typename T>
void List<T>::pop_front() // delete first element
{
iterator iter(head->next);
erase(iter);
}
template<typename T>
void List<T>::pop_back() // delete last element
{
iterator iter(tail->prev);
erase(iter);
}
template<typename T>
void List<T>::remove(const T &val) // remove all elements with value = val
{
for(auto itr = begin(); itr != end();)
{
if(*itr == val)
{
itr = erase(itr);
}
else
itr++;
}
}
//This is weird.......
template <typename T>
template <typename PREDICATE>
void List<T>::remove_if(PREDICATE pred) // remove all elements for which Predicate pred
// returns true. pred can take in a function object
{
// typename List<T>::iterator itr;
for(auto itr = begin(); itr != end();)
{
if(pred(*itr))
{
itr = erase(itr);
}
else
{
itr++;
}
}
}
// print out all elements. ofc is deliminitor
template<typename T>
void List<T>::print(std::ostream& os, char ofc) const
{
iterator itr(head->next);
while(itr != end())
{
os << *itr << ofc;
itr++;
}
}
template<typename T>
typename List<T>::iterator List<T>::begin() // iterator to first element
{
iterator itr(head->next);
// itr.current = head->next;
return itr;
}
template<typename T>
typename List<T>::const_iterator List<T>::begin() const
{
const_iterator itr(head->next);
// itr.current = head->next;
return itr;
}
template<typename T>
typename List<T>::iterator List<T>::end() // end marker iterator
{
iterator itr;
itr.current = tail;
return itr;
}
template<typename T>
typename List<T>::const_iterator List<T>::end() const
{
const_iterator itr;
itr.current = tail;
// cout << *itr << "tail value" << endl;
// cout << "TAIL PRINTED FAIL" << endl;
return itr;
}
template<typename T>
typename List<T>::iterator List<T>::insert(iterator itr, const T& val) // insert val ahead of itr
{
//create new node
Node* newNode = new Node;
Node* actual = itr.current;
iterator x(actual);
//set the value
newNode->data = val;
//set the new Node's next and prev to the appropriate positions
newNode->next = actual->next;
newNode->prev = actual->next->prev;
//now set the pointers of the already existing nodes to the new new appropriately
actual->next = newNode;
newNode->next->prev = newNode;
//increment size
++theSize;
return x;
}
template<typename T>
typename List<T>::iterator List<T>::insert(iterator itr, T && val) // move version of insert
{
//create new node
Node* newNode = new Node;
Node* actual = itr.current;
iterator x(actual);
//set the value using std::swap
std::swap(newNode->data, val);
//set the new Node's next and prev to the appropriate positions
newNode->next = actual->next;
newNode->prev = actual->next->prev;
//now set the pointers of the already existing nodes to the new new appropriately
actual->next = newNode;
newNode->next->prev = newNode;
//increment size
++theSize;
return x;
}
template<typename T>
typename List<T>::iterator List<T>::erase(iterator itr) // erase one element
{
//declare new Node and return
Node* actual = itr.current;
iterator x(actual->next);
//set the previous and next node of itr equal to each other
actual->prev->next = actual->next;
actual->next->prev = actual->prev;
//set current's pointers to null
actual->next = nullptr;
actual->prev = nullptr;
//remove the node
delete itr.current;
//decrement size;
--theSize;
;
return x;
}
template<typename T>
typename List<T>::iterator List<T>::erase(iterator start, iterator end) // erase [start, end)
{
iterator x;
for(x = start; x != end;)//why no increment here ????
{
x = erase(x);
}
return end;
}
// overloading comparison operators
template <typename T>
bool operator==(const List<T> & lhs, const List<T> &rhs)
{
//instantiate the iterators here(figure out the syntax)
auto rIter = rhs.begin();
auto lIter = lhs.begin();
if(lhs.size() != rhs.size())
{
return false;
}
else
{
for(rIter; rIter != rhs.end(); rIter++)
{
if(*rIter != *lIter)
{
return false;
}
lIter++;
}
}
return true;
}
template <typename T>
bool operator!=(const List<T> & lhs, const List<T> &rhs)
{
return !(lhs == rhs);
}
// overloading output operator
template <typename T>
std::ostream & operator<<(std::ostream &os, const List<T> &l)
{
l.print(os);
return os;
}
| true |
ff04c7eb6ca1c8bc3b87e3371c979ef1343d2e65 | C++ | 1kzpro/international | /Kazybek/COMP 2710/P1/src/project1_Mizam_kzm0099.cpp | UTF-8 | 5,141 | 3.640625 | 4 | [] | no_license | /*
Project 1
@author Kazybek Mizam
@version 08/25/20
Documentation for Pointers: https://www.tutorialspoint.com/cprogramming/c_pointers.htm
Documentation for Prototype: http://www.cplusplus.com/articles/yAqpX9L8/
Documentation for Formatting: https://thispointer.com/c-convert-double-to-string-and-manage-precision-scientific-notation/
*/
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
int input(double *, float *, double *);
int calculate(double *, float *, double *, std::string *, int *, double *);
void output(std::string *, int *, double *);
std::string format_precision_2(double);
std::string format_precision_2(float);
int main()
{
// Declaring input variables
double loanAmount;
float interestRate;
double monthlyPayment;
// Declaring private use variables
std::string calculatedOutput = "";
int months = 0;
double totalInterest = 0.0;
short int status_input = input(&loanAmount, &interestRate, &monthlyPayment);
if (status_input != 0)
{
return 0;
}
short int status_calculate = calculate(&loanAmount, &interestRate, &monthlyPayment, &calculatedOutput, &months, &totalInterest);
if (status_calculate == 0)
{
output(&calculatedOutput, &months, &totalInterest);
}
else
{
std::cout << "Your monthly payment is not enough to pay loan.";
}
return 0;
}
int input(double *loanAmount, float *interestRate, double *monthlyPayment)
{
std::cout << "Loan Amount: ";
std::cin >> *loanAmount;
while(*loanAmount <= 0) {
std::cout << "Loan amount should be positive number: ";
std::cin >> *loanAmount;
}
std::cout << "Interest Rate(% per year): ";
std::cin >> *interestRate;
while(*interestRate < 0) {
std::cout << "Interest rate % per year should be non-negative number: ";
std::cin >> *interestRate;
}
std::cout << "Monthly Payments: ";
std::cin >> *monthlyPayment;
while(*monthlyPayment <= 0) {
std::cout << "Monthly payments should be positive number: ";
std::cin >> *monthlyPayment;
}
return 0;
}
int calculate(double *loanAmount, float *interestRate, double *monthlyPayment, std::string *calculatedOutput, int *months, double *totalInterest)
{
double balance = *loanAmount;
float monthlyInterestRate = *interestRate / 12;
for (int month = 0; balance > 0.00; month++)
{
double interest = balance * monthlyInterestRate / 100;
double principial = *monthlyPayment - interest;
double payment = interest + principial;
if (principial < 0)
{
return 1;
}
if (month == 0)
{
*calculatedOutput += std::to_string(month) + "\t$" + format_precision_2(balance) + "\tN/A\tN/A\tN/A\t\tN/A\n";
continue;
}
if (balance < principial)
{
principial = balance;
}
balance -= principial;
// Formatting issue solving
if (balance < 1000) {
*calculatedOutput += std::to_string(month) + "\t$" + format_precision_2(balance) + "\t\t$" + format_precision_2(payment) + "\t$" + format_precision_2(monthlyInterestRate) + "\t$" + format_precision_2(interest) + "\t\t$" + format_precision_2(principial) + "\n";
} else {
*calculatedOutput += std::to_string(month) + "\t$" + format_precision_2(balance) + "\t$" + format_precision_2(payment) + "\t$" + format_precision_2(monthlyInterestRate) + "\t$" + format_precision_2(interest) + "\t\t$" + format_precision_2(principial) + "\n";
}
(*months)++;
*totalInterest += interest;
}
return 0;
}
void output(std::string *calculatedOutput, int *months, double *totalInterest)
{
std::cout << "**********************************************************\n";
std::cout << "\tAmortization Table\n";
std::cout << "**********************************************************\n";
std::cout << "Month\tBalance\t\tPayment\tRate\tInterest\tPrincipal\n";
std::cout << *calculatedOutput;
std::cout << "**********************************************************\n";
std::cout << "\n";
std::cout << "It takes " << *months << " months to pay off the loan.\n";
std::cout << "Total interest paid is: $" << format_precision_2(*totalInterest);
}
std::string format_precision_2(double number)
{
// Create an output string stream
std::ostringstream streamObj;
// Set Fixed -Point Notation
streamObj << std::fixed;
// Set precision to 2 digits
streamObj << std::setprecision(2);
//Add double to stream
streamObj << number;
// Get string from output string stream
return streamObj.str();
}
std::string format_precision_2(float number)
{
// Create an output string stream
std::ostringstream streamObj;
// Set Fixed -Point Notation
streamObj << std::fixed;
// Set precision to 2 digits
streamObj << std::setprecision(2);
//Add double to stream
streamObj << number;
// Get string from output string stream
return streamObj.str();
} | true |
5375544244aa0f53f13a9a6dc54c958b98e0d87c | C++ | amansaini7999/Data-Structure-and-Algorithms | /fbPrep/interpretations.cpp | UTF-8 | 462 | 3.0625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void printAllInterpretations(vector<int> v, int pos, string result){
if(pos==v.size()){
cout<<result<<"\n";
return;
}
printAllInterpretations(v, pos+1, result+char(v[pos]+'a'-1));
if(pos+1<v.size() && v[pos]*10+v[pos+1]<=26)
printAllInterpretations(v, pos+2, result+char(v[pos]*10+v[pos+1]+'a'-1));
}
int main()
{
vector<int> v{9, 1, 8};
printAllInterpretations(v, 0, "");
return 0;
}
| true |
59c69405fbec131e7102b03bbde3e4a4611a662e | C++ | Karan-MUJ/InterviewBit-Solutions | /Brackets.cpp | UTF-8 | 854 | 3.375 | 3 | [] | no_license | /*#include <iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
// your code goes here
string str = "])";
int n = str.size();
stack <char> S;
for (int i = 0; i < n; i++)
{
if (str[i] == '[' || str[i] == '{' || str[i] == '(')
{
S.push(str[i]);
}
else
{
if (S.empty())
{
return 0;
}
if (str[i] == ']')
{
if (S.top() != '[')
{
cout << 0 << endl;
break;
}
else
{
S.pop();
}
}
else if (str[i] == '}')
{
if (S.top() != '{')
{
cout << 0 << endl;
break;
}
else
{
S.pop();
}
}
else if (str[i] == ')')
{
if (S.top() != '(')
{
cout << 0 << endl;
break;
}
else
{
S.pop();
}
}
}
}
if (!S.empty())
cout << 0 << endl;
else
cout << 1 << endl;
return 0;
}*/ | true |
cdb4b1b3e46931cc91cd0c1cba2611d7d0edbcf9 | C++ | Takagi1/Retribution | /Retribution/Engine/Math/Physics2D.h | UTF-8 | 1,307 | 2.640625 | 3 | [
"MIT",
"BSL-1.0"
] | permissive | #ifndef PHYSICS2D_H
#define PHYSICS2D_H
#include "../Rendering/Component.h"
#include <glm/glm.hpp>
#include <vector>
#include <memory>
class GameObject;
class Physics2D : public Component {
public:
Physics2D(GameObject* parent_);
virtual ~Physics2D();
void Update(const float deltaTime_) override;
//Getters
glm::vec2 GetVelocity() const;
glm::vec2 GetAcceleration() const;
float GetTorque() const;
bool GetRigidBody() const;
bool GetStaticObj() const;
//Setters
void SetVelocity(glm::vec2 velocity_);
void SetAcceleration(glm::vec2 acceleration_);
void SetTorque(float torque_);
void ApplyForce(glm::vec2 force_);
void SetRigidBody(const bool body_);
void SetStaticObj(const bool type_);
//Apply gravity to object
void ApplyGravity(bool state_);
void ApplyDrag(bool state_);
//Section for Collision
void CollisionResponse(std::vector<std::weak_ptr<GameObject>> obj);
private:
glm::vec2 velocity, acceleration, gravity;
float torque, mass, rotationalInertia, angularVel, angularAcc;
bool rigidBody; //Does the object have collision with other objects of rigidBody?
bool staticObj; //Skips the update function
glm::vec2 drag;
bool applyDrag;
void Drag();
//Non used
bool FindContainingPoint() override;
void Draw() override;
};
#endif // !PHYSICS2D_H | true |
960f3e56f80b6d6d381828178db1995b1647c8b9 | C++ | FangLiu68/OldCode2016 | /LaiOffer/Invert Binary Tree.cpp | UTF-8 | 1,600 | 3.53125 | 4 | [] | no_license | //
// Invert Binary Tree.cpp
// LaiOffer
//
// Created by Fang Liu on 6/18/15.
// Copyright (c) 2015 Fang Liu. All rights reserved.
//
/* invert a binary tree
4
/ \
2 7
/ \ / \
1 3 6 9
invert to
4
/ \
7 2
/ \ / \
9 6 3 1
从最底层向上传值,每次都把current node的左右孩子对调
是后序遍历
*/
#include "BinaryTree.h"
#include <iostream>
#include <vector>
using namespace std;
BinaryTreeNode* invertTree(BinaryTreeNode* root) {
if(root == NULL){
return NULL;
}
// what do you want from your left and right child
BinaryTreeNode* left = invertTree(root->left);
BinaryTreeNode* right = invertTree(root->right);
// what do you want to do in current level
root->left = right;
root->right = left;
// what do you want to report to your parent
return root;
}
/*
int main(){
BinaryTreeNode* root = new BinaryTreeNode(4);
BinaryTreeNode* node2 = new BinaryTreeNode(2);
BinaryTreeNode* node7 = new BinaryTreeNode(7);
BinaryTreeNode* node1 = new BinaryTreeNode(1);
BinaryTreeNode* node3 = new BinaryTreeNode(3);
BinaryTreeNode* node6 = new BinaryTreeNode(6);
BinaryTreeNode* node9 = new BinaryTreeNode(9);
root->left = node2;
root->right = node7;
node2->left = node1;
node2->right = node3;
node7->left = node6;
node7->right = node9;
BinaryTreeNode* res = invertTree(root);
vector<int> val = inOrder_iter(res);
for(int i=0; i<val.size(); ++i){
cout << val[i] << " ";
}return 0;
}*/ | true |
2e6b333b9adcfd008e460d443eb1aa8c5b8e50ed | C++ | constantineg1/Moby | /include/Moby/GeneralizedCCDPlugin.h | UTF-8 | 2,372 | 2.625 | 3 | [] | no_license | /****************************************************************************
* Copyright 2009 Evan Drumwright
* This library is distributed under the terms of the GNU General Public
* License (obtainable from http://www.apache.org/licenses/LICENSE-2.0).
****************************************************************************/
#ifndef _GENERALIZED_CCD_PLUGIN_H
#define _GENERALIZED_CCD_PLUGIN_H
#include <vector>
#include <Moby/Types.h>
#include <Moby/OBB.h>
namespace Moby {
/// A plugin for the generalized continuous collision detector
class GeneralizedCCDPlugin
{
public:
/// Returns the root bounding volume for intersection testing
virtual BVPtr get_BVH_root() = 0;
/// Gets vertices corresponding to the bounding volume
virtual void get_vertices(BVPtr bv, std::vector<Point3d>& vertices) = 0;
/// Determines whether a point is inside/on the geometry
/**
* \param gs_BV the bounding volume in which the point resides
* \param p the query point
* \param normal the normal to the query point, if the point is inside/on
* the geometry
* \return <b>true</b> if the point is inside or on the geometry,
* <b>false</b> otherwise
*/
virtual bool point_inside(BVPtr bv, const Point3d& p, Ravelin::Vector3d& normal) = 0;
/// Determines whether a line segment and the shape intersect
/**
* \param bv a bounding volume (to speed intersection testing)
* \param seg the line segment
* \param isect the point of intersection, on return (if any)
* \param normal the normal to the shape at the point of intersection,
* on return (if any)
* \return the parameter,t, of the intersection seg.first + seg.second*t
* or -1 if no intersection
*/
virtual double intersect_seg(BVPtr bv, const LineSeg3& seg, Point3d& isect, Ravelin::Vector3d& normal) = 0;
/// Gets mesh data for the geometry with the specified bounding volume
/**
* \param bv the bounding data from which the corresponding mesh data will
* be taken
* \return a pair consisting of an IndexedTriArray and a list of triangle
* indices encapsulated by bv
*/
virtual std::pair<boost::shared_ptr<const IndexedTriArray>, std::list<unsigned> >& get_mesh(BVPtr bv) = 0;
}; // end class
} // end namespace
#endif
| true |
424caee68b0e731ce9f065b45480818b12e174d2 | C++ | mohammadabdullahjawwad/DSAcpp | /BST/flattenBst.cpp | UTF-8 | 2,002 | 3.9375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
node* insert(node* root, int data) {
if(root == NULL) {
return new node(data);
}
if(data <= root->data) {
root->left = insert(root->left, data);
}
else {
root->right = insert(root->right, data);
}
return root;
}
node* create() {
int data;
cin >> data;
node* root = NULL;
while(data != -1) {
root = insert(root, data);
cin >> data;
}
return root;
}
class linkedList {
public:
node* head;
node* tail;
};
linkedList flatten(node* root) {
linkedList l;
if(root == NULL) {
l.head = NULL;
l.tail = NULL;
return l;
}
// Case 1 - Leaf node
if(root->left == NULL && root->right == NULL){
l.head = root;
l.tail = root;
return l;
}
// Case 2 - LST is not NULL and RST is NULL
if(root->right == NULL) {
linkedList left = flatten(root->left);
left.tail->right = root;
l.head = left.head;
l.tail = root;
return l;
}
// Case 3 - RST is not NULL and LST is NULL
if(root->left == NULL) {
linkedList right = flatten(root->right);
root->right = right.head;
l.head = root;
l.tail = right.tail;
return l;
}
// Case 4 - LST ans RST are both not NULL. Postorder traversal
linkedList left = flatten(root->left);
linkedList right = flatten(root->right);
left.tail->right = root;
root->right = right.head;
l.head = left.head;
l.tail = right.tail;
return l;
}
void print(node* head) {
while(head != NULL) {
cout << head->data << "->";
head = head->right;
}
cout << "NULL\n";
}
int main() {
node* root = create();
linkedList ans = flatten(root);
print(ans.head);
return 0;
} | true |
42188ca8cfe17c4eb80ec4d759f56a66d366709e | C++ | eLRuLL/LeetCode | /maximum-depth-of-binary-tree/a.cpp | UTF-8 | 631 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxDepth(TreeNode *root) {
if(root == NULL){
return 0;
}else{
return 1+ max(maxDepth(root->left),maxDepth(root->right));
}
}
int main(){
TreeNode* root = new TreeNode(10);
TreeNode* root1 = new TreeNode(10);
TreeNode* root2 = new TreeNode(10);
TreeNode* root3 = new TreeNode(10);
root->left = root1;
root1->right = root2;
root1->right = root3;
cout<<maxDepth(root)<<endl;
return 0;
} | true |
aea089cae23a0485e933751f40e5f03f9dfb720f | C++ | Oureyelet/Chapter-7-Control-Flow-and-Error-Handling--vsCode- | /7.4 — Switch statement basics (vsCode)/first.h | UTF-8 | 2,304 | 4.09375 | 4 | [] | no_license | #include <iostream>
#ifndef FISRT_H
#define FISRT_H
void printDigitName(int x)
{
if(x == 1)
std::cout << "One\n";
else if(x == 2)
std::cout << "Two\n";
else if(x == 3)
std::cout << "Three\n";
else
std::cout << "Unknown\n";
}
/*
C++ provides an alternative conditional statement called a switch statement
that is specialized for this purpose. Here is the same program as above using a switch:
*/
namespace wee//i created my own namespace 'wee' for possibility same name function 'printDigitName'
{
void printDigitName(int x)
{
switch (x)
{
case 1:
std::cout << "One\n";
return;
case 2:
std::cout << "Two\n";
return;
case 3:
std::cout << "Three\n";
return;
default:
std::cout << "Unknown\n";
}
}
}
/*----------------------------------------------------
Taking a break
-----------------------------------------------------*/
/*
In the above examples, we used return statements to stop execution of the statements after our labels.
However, this also exits the entire function.
A break statement (declared using the break keyword) tells the compiler that we are done
executing statements within the switch, and that execution should continue with
the statement after the end of the switch block. This allows us to exit a switch statement
without exiting the entire function.
Here’s a slightly modified example rewritten using break instead of return:
*/
namespace voo
{
void printDigitName(int x)
{
switch (x)// x evaluates to 3
{
case 1:
std::cout << "One\n";
break;
case 2:
std::cout << "Two\n";
break;
case 3:
std::cout << "Three\n";// execution starts here
break;// jump to the end of the switch block
default:
std::cout << "Unknown\n";
break;
}
// execution continues here
std::cout << "I am still here\n";
}
}
#endif /// end FISRT_H | true |
dfe6f8b82e5bb4cc1027b0e81a3394b491681263 | C++ | F1483823457/G5 | /c4/第四章10/第四章10.cpp | UTF-8 | 565 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include<stdio.h>
int main(int argc, char* argv[])
{
int c;
double a;
double b,b1,b2,b3,b4,b5;
scanf("%lf",&a);
b1=100000*0.1;
b2=b1+100000*0.075;
b3=b2+200000*0.05;
b4=b3+200000*0.03;
b5=b4+400000*0.015;
c=a/100000;
if(c>10) c=10;
switch(c)
{
case 0:b=a*0.1;break;
case 1:b=b1+(a-100000)*0.075;break;
case 2:
case 3:b=b2+(a-200000)*0.05;break;
case 4:
case 5:b=b3+(a-400000)*0.03;break;
case 6:
case 7:
case 8:
case 9:b=b4+(a-600000)*0.015;break;
case 10:b=b5+(a-1000000)*0.01;break;
}
printf("%.2lf",b);
return 0;
}
| true |
31fc1a5276eb896649ec40f9a30d229a2a3387b4 | C++ | RazrFalcon/ttf-parser | /testing-tools/font-view/ttfparserfont.cpp | UTF-8 | 3,876 | 2.78125 | 3 | [
"Apache-2.0",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <QTransform>
#include <QFile>
#include <QDebug>
#include "ttfparserfont.h"
struct Outliner
{
static void moveToFn(float x, float y, void *user)
{
auto self = static_cast<Outliner *>(user);
self->path.moveTo(double(x), double(y));
}
static void lineToFn(float x, float y, void *user)
{
auto self = static_cast<Outliner *>(user);
self->path.lineTo(double(x), double(y));
}
static void quadToFn(float x1, float y1, float x, float y, void *user)
{
auto self = static_cast<Outliner *>(user);
self->path.quadTo(double(x1), double(y1), double(x), double(y));
}
static void curveToFn(float x1, float y1, float x2, float y2, float x, float y, void *user)
{
auto self = static_cast<Outliner *>(user);
self->path.cubicTo(double(x1), double(y1), double(x2), double(y2), double(x), double(y));
}
static void closePathFn(void *user)
{
auto self = static_cast<Outliner *>(user);
self->path.closeSubpath();
}
QPainterPath path;
};
TtfParserFont::TtfParserFont()
{
}
void TtfParserFont::open(const QString &path, const quint32 index)
{
if (isOpen()) {
m_face.reset();
}
QFile file(path);
file.open(QFile::ReadOnly);
m_fontData = file.readAll();
m_face.reset((ttfp_face*)malloc(ttfp_face_size_of()));
const auto res = ttfp_face_init(m_fontData.constData(), m_fontData.size(), index, m_face.get());
if (!res) {
throw tr("Failed to open a font.");
}
}
bool TtfParserFont::isOpen() const
{
return m_face != nullptr;
}
FontInfo TtfParserFont::fontInfo() const
{
if (!isOpen()) {
throw tr("Font is not loaded.");
}
return FontInfo {
ttfp_get_ascender(m_face.get()),
ttfp_get_height(m_face.get()),
ttfp_get_number_of_glyphs(m_face.get()),
};
}
Glyph TtfParserFont::outline(const quint16 gid) const
{
if (!isOpen()) {
throw tr("Font is not loaded.");
}
Outliner outliner;
ttfp_outline_builder builder;
builder.move_to = outliner.moveToFn;
builder.line_to = outliner.lineToFn;
builder.quad_to = outliner.quadToFn;
builder.curve_to = outliner.curveToFn;
builder.close_path = outliner.closePathFn;
ttfp_rect rawBbox;
const bool ok = ttfp_outline_glyph(
m_face.get(),
builder,
&outliner,
gid,
&rawBbox
);
if (!ok) {
return Glyph {
QPainterPath(),
QRect(),
};
}
const QRect bbox(
rawBbox.x_min,
-rawBbox.y_max,
rawBbox.x_max - rawBbox.x_min,
rawBbox.y_max - rawBbox.y_min
);
// Flip outline around x-axis.
QTransform ts(1, 0, 0, -1, 0, 0);
outliner.path = ts.map(outliner.path);
outliner.path.setFillRule(Qt::WindingFill);
return Glyph {
outliner.path,
bbox,
};
}
QVector<VariationInfo> TtfParserFont::loadVariations()
{
if (!isOpen()) {
throw tr("Font is not loaded.");
}
QVector<VariationInfo> variations;
for (uint16_t i = 0; i < ttfp_get_variation_axes_count(m_face.get()); ++i) {
ttfp_variation_axis axis;
ttfp_get_variation_axis(m_face.get(), i, &axis);
variations.append(VariationInfo {
Tag(axis.tag).toString(),
{ static_cast<quint32>(axis.tag) },
static_cast<qint16>(axis.min_value),
static_cast<qint16>(axis.def_value),
static_cast<qint16>(axis.max_value),
});
}
return variations;
}
void TtfParserFont::setVariations(const QVector<Variation> &variations)
{
if (!isOpen()) {
throw tr("Font is not loaded.");
}
for (const auto &variation : variations) {
ttfp_set_variation(m_face.get(), variation.tag.value, variation.value);
}
}
| true |
1c71c6f9bb5b9020c4cccba1d7a82e8501ad603c | C++ | mukeshkharita/compiler | /left_recursion_&_fectoring.cpp | UTF-8 | 4,129 | 3.34375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
Given Grammar:
S -> Aa | b
A -> Ac | Sd | ^
*/
#define R 10
vector < string > prod_rules [R]; // stores grammar
map < char, int > rule_no;
int usedChar[26]; // characters already used
int num; // curr num of prod
bool isTerminal(char a)
{
if(a >= 65 && a <= 90)
return false;
return true;
}
bool isNonTerminal(char a)
{
if(a >= 65 && a <= 90)
return true;
return false;
}
bool isNull(char a)
{
if (a == '^')
return true;
return false;
}
void define_grammar()
{
//S -> Aa | b
fill(usedChar, usedChar+26, 0);
rule_no['S'] = 0;
prod_rules[0].push_back("S");
prod_rules[0].push_back("Aa");
prod_rules[0].push_back("b");
// A -> Ac | Sd | ^
rule_no['A'] = 1;
prod_rules[1].push_back("A");
prod_rules[1].push_back("Ac");
prod_rules[1].push_back("Sd");
prod_rules[1].push_back("^");
num = 2;
usedChar[65 - 'A'] = 1;
usedChar[65 - 'S'] = 1;
}
/*
void define_grammar()
{
//S -> Aa | b
fill(usedChar, usedChar+26, 0);
rule_no['E'] = 0;
prod_rules[0].push_back("E");
prod_rules[0].push_back("E+T");
prod_rules[0].push_back("T");
num = 1;
usedChar[65 - 'E'] = 1;
}
*/
/*
bool ifTendsNull(int pn) // if production ultimately tends to null
{
bool success = false;
for(int j=1; j<prod_rules[pn].size(); j++)
{
string pr = prod_rules[pn][j];
if(isNull(pr[0]))
{
success = true;
break;
}
if (isNonTerminal(pr[0]) && ifTendsNull(rule_no[pr[0]]) == false)
{
success = false;
break;
}
else
continue;
}
return success;
}
*/
void directRec()
{
vector <string> alpha;
vector <string> beta;
int numrules = num;
for(int i=0; i<numrules; i++)
{
char a = prod_rules[i][0][0];
for(int j = 1; j < prod_rules[i].size(); j++)
{
char b = prod_rules[i][j][0];
if(a == b)
{
alpha.push_back(prod_rules[i][j].substr(1));
}
else
{
beta.push_back(prod_rules[i][j]);
}
}
if(alpha.size() > 0)
{
cout << "alpha" << endl;
for(int k=0 ;k<alpha.size(); k++)
cout << alpha[k] << " ";
cout << endl << "beta" << endl;
for(int k=0 ;k<beta.size(); k++)
cout << beta[k] << " ";
cout << endl;
char p; // next character to be used
for(int k=0; k<26; k++)
if(usedChar[k] == 0)
{
p = k + 65;
break;
}
string newrule(1, p);
prod_rules[num].push_back(newrule);
string rule = prod_rules[i][0];
prod_rules[i].clear();
prod_rules[i].push_back(rule);
if(beta.size() == 0)
{
prod_rules[i].push_back(newrule);
}
else
{
for(int k=0; k<beta.size();k++)
{
if(isNull(beta[k][0]))
prod_rules[i].push_back("^");
else
prod_rules[i].push_back(beta[k] + newrule);
}
}
beta.clear();
for(int k=0; k<alpha.size(); k++)
{
prod_rules[num].push_back(alpha[k]+newrule);
}
prod_rules[num].push_back("^");
alpha.clear();
rule_no[p] = num;
num++;
}
beta.clear();
}
}
void indirectRec()
{
stack <string> temp;
int numrules = 0;
for(int i=1; i<num; i++)
{
char a = prod_rules[i][0][0];
for(int j = 1; j < prod_rules[i].size(); j++)
{
char b = prod_rules[i][j][0];
if(isTerminal(b))
{
cout << "Inside Production " << a << "->" << b << endl;
string alpha = prod_rules[i][j].substr(1);
int rule = rule_no[b];
if(rule < i)
{
for(int k=prod_rules[i].size()-1; k>i; k--)
{
temp.push(prod_rules[i][k]);
cout << "pushing " << prod_rules[i][k] << endl;
}
int lim = prod_rules[i].size();
for(int k=lim-1; k>=i; k--)
{
prod_rules[i].pop_back();
}
for(int k=0; k<prod_rules[rule].size(); k++)
{
prod_rules[i].push_back(prod_rules[rule][k] + alpha);
}
while(!temp.empty())
{
prod_rules[i].push_back(temp.top());
temp.pop();
}
}
}
}
}
}
void printGrammar()
{
for(int i=0; i<num; i++)
{
for(int j=0; j<prod_rules[i].size(); j++)
cout << prod_rules[i][j] << " ";
cout << endl;
}
cout << endl;
}
void debug()
{
}
int main()
{
define_grammar();
//debug();
indirectRec();
printGrammar();
return 0;
} | true |
595c8ea8165d1b5124340614e8697cb6666470ee | C++ | lzhpku/leetcode | /round1pass/49. Group Anagrams.cpp | UTF-8 | 521 | 3.015625 | 3 | [] | no_license | class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, multiset<string>> m;
for(int i = 0; i < strs.size(); i ++) {
string s = strs[i];
sort(s.begin(), s.end());
m[s].insert(strs[i]);
}
vector<vector<string>> ret;
for(auto item : m) {
vector<string> temp(item.second.begin(), item.second.end());
ret.push_back(temp);
}
return ret;
}
}; | true |
373b9ba3c72d3f229ba07c0dad386a9b8bc920b4 | C++ | SKliaznyka/KS.UIP.Cpp.HomeWork | /KS.UIP.Cpp.HomeWork.HW11.CharEnumArrayTask02/KS.UIP.Cpp.HomeWork.HW11.CharEnumArrayTask02.cpp | UTF-8 | 3,029 | 3.1875 | 3 | [] | no_license | // KS.UIP.Cpp.HomeWork.HW11.CharEnumArrayTask02.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
//HomeWork 11. Task 02.
//Generate a Password.
//Password rule:
// - 12 symbols;
// - regular letters;
// - capital letters;
// - digits.
//Ask user enter a password. Ask user to enter a password until it match the generated one.
#include "pch.h"
#include <iostream>
#include <string>
void passwordGen(char Password[], int PasswordSize);
void outputGenPassword(char Password[], int PasswordSize);
void checkPassword(char GenPassword[], char UserPassword[], int PasswordSize);
enum eGroups { capitalLetter, regularLetter, Digits };
int main()
{
const int iPasswordSize(7);
std::cout << "Homework 11. Task 02" << std::endl;
std::cout << "Have a generated password. User should enter correct Password.";
std::cout << std::endl << std::endl;
char cGenPassword[iPasswordSize] = { '\0' };
passwordGen(cGenPassword, iPasswordSize);
outputGenPassword(cGenPassword, iPasswordSize);
char cUserPassword[15] = { '\0' };
do
{
std::cout << "Enter the password:" << std::endl;
std::cin >> cUserPassword;
checkPassword(cGenPassword, cUserPassword, iPasswordSize);
} while (strcmp(cGenPassword, cUserPassword) != 0);
return 0;
}
void passwordGen(char Password[], int PasswordSize)
{
int nGroup;
for (int i = 0; i < PasswordSize; ++i)
{
//Password[i] = rand() % 26 + 97;
nGroup = rand() % 3;
switch (nGroup)
{
case regularLetter:
{
Password[i] = rand() % 26 + 97;
break;
}
case capitalLetter:
{
Password[i] = rand() % 26 + 65;
break;
}
case Digits:
{
Password[i] = rand() % 10 + 48;
break;
}
}
}
Password[PasswordSize - 1] = '\0';
}
void outputGenPassword(char Password[], int PasswordSize)
{
std::cout << "Generated Password:" << std::endl;
for (int i = 0; i < PasswordSize; ++i)
{
std::cout << Password[i];
}
std::cout << std::endl << std::endl;
}
void checkPassword(char GenPassword[], char UserPassword[], int PasswordSize)
{
if (strcmp(GenPassword, UserPassword) == 0)
{
std::cout << std::endl << "Password is correct.";
}
else
{
std::cout << std::endl << "ERROR. Password is incorrect. Try Again.";
}
std::cout << std::endl;
std::cout << "----------------------------------------" << std::endl << std::endl;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
6e38d95c2b579c53a8fc3489f424f610b620cb1f | C++ | ChonQuan/NguyenChonQuan | /PHAN MEM QUAN LY THU VIEN/LibraryObjectData/BorrowReturnData.cpp | UTF-8 | 2,199 | 2.84375 | 3 | [] | no_license | #include "BorrowReturnData.h"
BorrowReturnData::BorrowReturnData() {
_maxID = 0;
_dataBorrowReturn.resize(0);
}
vector<BorrowReturn> BorrowReturnData::GetDataBorrowReturn() {
return _dataBorrowReturn;
}
LibraryObject* BorrowReturnData::GetPointer(int i) {
return &_dataBorrowReturn[i];
}
int BorrowReturnData::GetMaxID() {
return _maxID;
}
int BorrowReturnData::GetSize() {
return _dataBorrowReturn.size();
}
int BorrowReturnData::Create(BorrowReturn& BorrowReturn) {
_maxID++;
BorrowReturn.SetID(_maxID);
_dataBorrowReturn.push_back(BorrowReturn);
return _maxID;
}
void BorrowReturnData::Read(string filename) {
_maxID = 0;
_dataBorrowReturn.resize(0);
ifstream infile(filename);
int datanumber;
infile >> datanumber;
int id;
int BorrowReturnID;
int MemberID;
int BookID;
string Date;
int borrowreturncheck;
for(int i = 0; i < datanumber; i++ ) {
infile >> id;
infile >> BorrowReturnID;
infile >> MemberID;
infile >> BookID;
infile.ignore();
getline(infile,Date);
infile >> borrowreturncheck;
BorrowReturn borrowreturn(BorrowReturnID, MemberID, BookID, Date, borrowreturncheck);
borrowreturn.SetID(id);
_dataBorrowReturn.push_back(borrowreturn);
}
infile.close();
}
void BorrowReturnData::Update(int& i, BorrowReturn& BorrowReturn) {
BorrowReturn.SetID(i);
_dataBorrowReturn[i-1] = BorrowReturn;
}
void BorrowReturnData::Delete(int& i) {
_dataBorrowReturn.erase(_dataBorrowReturn.begin()+i-1);
for(int j = i-1; j < _maxID; j++ ) {
_dataBorrowReturn[j].SetID(j+1);
}
}
void BorrowReturnData::ExportToFile(string filename) {
ofstream outfile(filename);
outfile << _maxID;
for(BorrowReturn BorrowReturn:_dataBorrowReturn) {
outfile << BorrowReturn.GetID() << endl;
outfile << BorrowReturn.GetBorrowReturnID() << endl;
outfile << BorrowReturn.GetMemberID() << endl;
outfile << BorrowReturn.GetBookID() << endl;
outfile << BorrowReturn.GetDate() << endl;
outfile << BorrowReturn.GetBorrowReturn() << endl;
}
outfile.close();
} | true |
52d1f1b486b01470b313a9882b21b4b21f40b9b4 | C++ | CodeOpsTech/DesignPatternsCpp | /cpp/opensourcesrcs/qtchat/src/0.9.7/libwc/wc.h | UTF-8 | 1,867 | 3.109375 | 3 | [] | no_license | #ifndef _WC_H
#define _WC_H
class Word {
public:
Word(const char *str);
Word(const Word &w);
Word(const Word *w);
virtual ~Word();
operator const char *();
bool operator==(const Word &w);
Word& operator=(const Word &w);
bool isNull() const {
return word==0;
}
private:
char *word;
};
extern const Word NullWord;
class WordList {
public:
WordList();
WordList(Word *words, int n);
WordList(const char *words[], int n);
WordList(const char *line);
WordList(Word word);
WordList(const WordList &wl);
virtual ~WordList();
int count() const {
return n;
}
void add(Word word);
WordList suggest(Word partial) const;
private:
Word **words;
int n;
template<class T>
void WordList::init(T _words[], int _n);
};
class SortedWordList : public WordList {
public:
SortedWordList();
SortedWordList(Word *words, int n);
SortedWordList(const char *words[], int n);
SortedWordList(const char *line);
SortedWordList(Word word);
SortedWordList(const WordList &wl);
};
class WordCompleter {
public:
WordCompleter();
virtual ~WordCompleter();
void setLine(const char *line, int cursor_pos);
Word getWordAt(int cursor_pos); // return word at cursor_pos
Word getWordAt(); // return word at current cursor position
SortedWordList getSuggestionsAt(int cursor_pos); // get list of suggestions at cursor_pos
SortedWordList getSuggestionsAt(); // get list of suggestions at current cursor
// Iterator Methods
Word getFirstSuggestionAt(int cursor_pos);
Word getFirstSuggestionAt();
Word getNextSuggestionAt(int cursor_pos);
Word getNextSuggestionAt();
Word getPrevSuggestionAt(int cursor_pos);
Word getPrevSuggestionAt();
private:
#define MAX_WORDLISTS 256
SortedWordList *lists[MAX_WORDLISTS];
SortedWordList *default_list;
char *line;
int cursor_pos;
};
#endif // _WC_H
| true |
241e05fd7c53c1280d23f40fc1e1841781f7fdf2 | C++ | kophyogyi12/Exercise2.2 | /Exercise 2.cpp | UTF-8 | 848 | 3.578125 | 4 | [] | no_license | #include <iostream>
class Shape{
protected:
double length, height;
public:
Shape(double l,double h) :length(l), height(h) {}
};
class Rectangle:public Shape {
public:
void GetArea2() {
double Area_rect;
Area_rect = length * height;
std::cout << "Area of Rectangle:" << Area_rect;
}
Rectangle();
};
class triangle :public Shape {
public:
void GetArea() {
double Area_tri;
double a = 1;
double b = 2;
Area_tri = (a / b) * length * height;
std::cout << "Area of triangle :" << Area_tri << std::endl;
}
triangle();
};
int main() {
double x;
double y;
std::cout << "Enter the length:";
std::cin >> x;
std::cout << "Enter the height:";
std::cin >> y;
Shape s(x, y);
triangle t;
t.GetArea();
Rectangle r;
r.GetArea2();
}
| true |
06d71a1bbf2089c0444cf756d1ffe820eecb33c0 | C++ | tgittos/breakout | /src/Paddle.cpp | UTF-8 | 981 | 2.8125 | 3 | [] | no_license | #include "Paddle.hpp"
#include "Dimension.hpp"
#include "Collidable.hpp"
Paddle::Paddle():
_velocity(0.f) {
AddFeature(new Dimension());
AddFeature(new Collidable(this));
};
void Paddle::MoveLeft(const float timestep) {
if (_velocity > 0.f) {
_velocity = 0.f;
}
_velocity -= Paddle::ACCELERATION * timestep;
}
void Paddle::MoveRight(const float timestep) {
if (_velocity < 0.f) {
_velocity = 0.f;
}
_velocity += Paddle::ACCELERATION * timestep;
}
void Paddle::Idle(const float timestep) {
if (_velocity == 0.f) {
return;
}
// handle deceleration from movement left
if (_velocity < 0.f) {
_velocity += Paddle::DECELERATION * timestep;
if (_velocity > 0.f) {
_velocity = 0.f;
}
}
// handle deceleration from movement right
if (_velocity > 0.f) {
_velocity -= Paddle::DECELERATION * timestep;
if (_velocity < 0.f) {
_velocity = 0.f;
}
}
}
const float Paddle::GetVelocity() {
return _velocity;
}
| true |
96d08e73af6862b8ee883ca87d2d8945ac3f73ed | C++ | playdougher/coding_interviews | /q4_find.cpp | UTF-8 | 806 | 3.421875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool Find(int target, vector<vector<int>> array) {
if (array.empty() || array[0].size() == 0 ) {
return false;
}
int row = array.size();
int col = array[0].size();
int row_i = 0;
int col_j = col-1;
while(row_i < row and col_j >=0){
if(target == array[row_i][col_j]) return true;
else if (target < array[row_i][col_j]) col_j--;
else row_i++;
}
return false;
}
};
int main(){
Solution s;
vector<vector<int>> array = {{1, 2, 8, 9},{2, 4, 9, 12},{4, 7, 10, 13},{6, 8, 11, 15}};
bool ans = s.Find(3,array);
if(ans) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
| true |
a24df9022a623d4744e75f7d20d0017799f69e4a | C++ | tonyatpeking/SmuSpecialTopic | /Engine/Code/Engine/Renderer/SpriteAnim.cpp | UTF-8 | 2,075 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "Engine/Renderer/SpriteAnim.hpp"
#include "Engine/Math/MathUtils.hpp"
#include "Engine/Renderer/SpriteSheet.hpp"
#include "Engine/Renderer/SpriteAnimDefinition.hpp"
SpriteAnim::SpriteAnim( const SpriteAnimDefinition* definition )
: m_definition( definition )
{
}
void SpriteAnim::Update( float deltaSeconds )
{
if( !m_isPlaying )
return;
m_elapsedSeconds += deltaSeconds;
if( m_elapsedSeconds > GetDurationSeconds() )
{
if( Definition()->m_playbackMode == SpriteAnimMode::PLAY_TO_END )
{
m_isPlaying = false;
m_isFinished = true;
}
if( Definition()->m_playbackMode == SpriteAnimMode::LOOPING )
{
SetFractionElapsed( 0.f );
}
}
}
AABB2 SpriteAnim::GetCurrentUVs() const
{
return GetSpriteSheet()->GetUVsForSpriteIndex( GetCurrentSpriteIdx() );
}
SpriteAnimType SpriteAnim::GetAnimType() const
{
return Definition()->m_animType;
}
const Texture* SpriteAnim::GetTexture() const
{
return GetSpriteSheet()->GetTexture();
}
void SpriteAnim::Reset()
{
m_elapsedSeconds = 0.f;
}
float SpriteAnim::GetSecondsRemaining() const
{
return GetDurationSeconds() - m_elapsedSeconds;
}
float SpriteAnim::GetFractionElapsed() const
{
if( GetDurationSeconds() == 0.f )
return 0.f;
return m_elapsedSeconds / GetDurationSeconds();
}
float SpriteAnim::GetFractionRemaining() const
{
return 1.f - GetFractionElapsed();
}
void SpriteAnim::SetFractionElapsed( float fractionElapsed )
{
m_elapsedSeconds = GetDurationSeconds() * fractionElapsed;
}
float SpriteAnim::GetDurationSeconds() const
{
return Definition()->m_duration;
}
float SpriteAnim::GetFPS() const
{
return Definition()->m_fps;
}
const SpriteSheet* SpriteAnim::GetSpriteSheet() const
{
return Definition()->m_spriteSheet;
}
int SpriteAnim::GetCurrentSpriteIdx() const
{
int IdxOfSpriteIdx = Lerp( 0, (int) Definition()->m_spriteIndices.size() - 1, GetFractionElapsed() );
return Definition()->m_spriteIndices[IdxOfSpriteIdx];
}
| true |
accdf0ca8b1fc33cad17ef444e640db737f6e233 | C++ | aNeutrino/livegrep | /src/radix_sorter.h | UTF-8 | 1,852 | 2.796875 | 3 | [
"BSD-2-Clause"
] | permissive | /********************************************************************
* livegrep -- radix_sorter.h
* Copyright (c) 2011-2013 Nelson Elhage
*
* This program is free software. You may use, redistribute, and/or
* modify it under the terms listed in the COPYING file.
********************************************************************/
#ifndef CODESEARCH_RADIX_SORTER_H
#define CODESEARCH_RADIX_SORTER_H
#include <algorithm>
using std::min;
class radix_sorter {
public:
radix_sorter(const unsigned char *data, int size) : data_(data), size_(size) { }
~radix_sorter() { }
void sort(uint32_t *l, uint32_t *r);
struct cmp_suffix {
radix_sorter &sort;
cmp_suffix(radix_sorter &s) : sort(s) {}
bool operator()(uint32_t lhs, uint32_t rhs) {
const unsigned char *l = &sort.data_[lhs];
const unsigned char *r = &sort.data_[rhs];
unsigned ll = static_cast<const unsigned char*>
(memchr(l, '\n', sort.size_ - lhs)) - l;
unsigned rl = static_cast<const unsigned char*>
(memchr(r, '\n', sort.size_ - rhs)) - r;
int cmp = memcmp(l, r, min(ll, rl));
if (cmp < 0)
return true;
if (cmp > 0)
return false;
return ll < rl;
}
};
struct indexer {
radix_sorter &sort;
indexer(radix_sorter &s) : sort(s) {}
unsigned operator()(uint32_t off, int i) {
return sort.index(off, i);
}
};
private:
unsigned index(uint32_t off, int i) {
if (data_[off + i] == '\n')
return 0;
return (unsigned)(unsigned char)data_[off + i];
}
const unsigned char *data_;
ssize_t size_;
radix_sorter(const radix_sorter&);
radix_sorter operator=(const radix_sorter&);
};
#endif
| true |
d97df0d41071982214e7ab4d871c01b1cf2a4b83 | C++ | Mostafa-At-GitHub/Educational-Management-System | /assignment_manager.cpp | UTF-8 | 2,739 | 3.21875 | 3 | [] | no_license | #include "assignment_manager.h"
#include "assignment.h"
namespace ES{
assignment_manager::assignment_manager() {}
assignment_manager::assignment_manager(string a,int b) :assignment_inf(a),max_grade(b) { }
void assignment_manager::view_assignment(){
cout << "Please choose one of the following option:" << '\n';
int option;
cout << "\t1 - Show Info" << '\n';
cout << "\t2 - Show grades Report" << '\n';
cout << "\t3 - List Solutions" << '\n';
cout << "\t4 - View Solution" << '\n';
cout << "\t5 - Back" << '\n';
cout << "Enter your choice: " ;
cin >> option;
// ignore invalid input such as char instead of int
while (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid Choice, Please try again\n";
cout << "Enter your choice: ";
cin >> option;
}
if (option == 1){
cout << assignment_inf << "\n\n\n";
}
else if (option == 2){
grades_report();
}
else if (option == 3){
list_students_solutions();
}
else if (option == 4){
view_student_solution();
}
else if (option == 5){
return;
}
else{
cout << "Invalid Option ... Taking you back to your Menu\n\n\n";
}
view_assignment();
return;
}
void assignment_manager::grades_report(){
cout << "Student Grades:\n";
for (auto _assignment : assignment_submissions)
cout << "Student id: " << _assignment->owner << " Grade: " << _assignment->grade << "\n";
cout << "\n\n\n\n";
}
void assignment_manager::list_students_solutions(){
cout << "Student Solutions:\n";
for (auto _assignment : assignment_submissions)
cout << "Student id: " << _assignment->owner << " Solution: " << _assignment->solution << "\n";
cout << "\n\n\n\n";
}
void assignment_manager::view_student_solution(){
list_students_solutions();
string _id;
cout << "Please enter student id: ";
cin >> _id;
for (auto _assignment:assignment_submissions)
if (_assignment->owner == _id){
int option;
cout << "Please choose ine of the following options:\n";
cout << "\t1 - Set-grade\n";
cout << "\t2 - back";
cout << "Enter your choice: " << '\n';
cin >> option;
// ignore invalid input such as char instead of int
while (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid Choice, Please try again\n";
cout << "Enter your choice: ";
cin >> option;
}
if (option == 1){
cout << "Please enter student grade: ";
cin >> _assignment->grade;
}else{
cout << "Invalid Option, Please try again \n\n\n\n";
view_student_solution();
}
return;
}
cout << "Invalid id, Please try again \n\n\n\n";
view_student_solution();
}
} | true |
c3d3ba31749760b2bee3db5a9bc0eba253e3bdf4 | C++ | SimulPiscator/goldstard | /src/Player.cpp | UTF-8 | 6,670 | 2.5625 | 3 | [] | no_license | #include "Player.h"
#include "SlaveProcess.h"
#include <atomic>
#include <map>
#include <thread>
#include <signal.h>
static const char* sQueryProperties[] =
{
"file_name",
"audio_samples",
"audio_bitrate",
"audio_codec",
"time_pos",
};
enum { idle, playPending, playing, terminating, };
enum { none, MPlayer, Audiocast };
struct Player::Private
{
Player* mpSelf;
SlaveProcess mProcess;
std::atomic<int> mProcessKind;
std::thread* mpThread = nullptr;
std::mutex mMutex;
std::atomic<int> mState;
bool mPosPending = false, mPaused = false;
std::map<std::string, std::string> mProperties;
int mUpdateIntervalMs = 500;
static void ThreadFunc( Private* );
};
void
Player::Private::ThreadFunc( Private* p )
{
while( true )
{
bool changed = false;
if(p->mProcessKind == MPlayer)
{
if( !p->mProcess.WaitForOutputMs( p->mUpdateIntervalMs ) )
{
std::lock_guard<std::mutex> lock(p->mMutex);
if(!p->mProcess.Running())
{
p->mProcessKind = none;
p->mPosPending = false;
p->mState = idle;
p->mProperties.clear();
changed = true;
}
else if( p->mState == playing && !p->mPosPending )
{
p->mProcess.Input() << "get_time_pos" << std::endl;
p->mPosPending = true;
}
}
else
{
std::string line;
if( std::getline( p->mProcess.Output(), line ) )
{
static const std::string tag = "ANS_";
size_t pos = line.find("=");
if( line.find( tag ) == 0 && pos != std::string::npos )
{
std::string name = line.substr( tag.length(), pos - tag.length() ),
value = line.substr( pos + 1 );
if( !value.empty() && value.front() == '\'' && value.back() == '\'' )
value = value.substr( 1, value.length() - 2 );
for( auto& c : name )
c = ::tolower(c);
std::lock_guard<std::mutex> lock(p->mMutex);
p->mProperties[name] = value;
if( name == "time_position" )
{
p->mPosPending = false;
if( p->mState == playPending )
p->mState = playing;
changed = true;
}
}
}
}
}
else if(p->mProcessKind == Audiocast)
{
static const int audiocastUpdateIntervalMs = 1000;
if(!p->mProcess.WaitForOutputMs(audiocastUpdateIntervalMs))
{
std::lock_guard<std::mutex> lock(p->mMutex);
if(!p->mProcess.Running())
{
p->mProcessKind = none;
p->mPosPending = false;
p->mState = idle;
p->mProperties.clear();
changed = true;
}
else if( p->mState == playing && !p->mPosPending )
{
p->mProcess.Input() << "get_statistics" << std::endl;
p->mPosPending = true;
}
}
else
{
p->mPosPending = false;
if( p->mState == playPending )
p->mState = playing;
changed = true;
std::string line;
while(p->mProcess.WaitForOutputMs(0))
{
if(std::getline(p->mProcess.Output(), line))
{
std::lock_guard<std::mutex> lock(p->mMutex);
size_t pos = line.find('=');
if(pos < line.length())
{
std::string key = line.substr(0, pos);
p->mProperties[key] = line.substr(pos + 1);
}
}
}
}
}
else if( p->mState == terminating )
return;
else
p->mProcess.WaitForOutputMs(250);
if( changed )
p->mpSelf->Broadcast();
}
}
Player*
Player::Instance()
{
static Player sPlayer;
return &sPlayer;
}
Player::Player()
: p( new Private )
{
p->mpSelf = this;
p->mProcessKind = none;
p->mState = idle;
p->mpThread = new std::thread( &Private::ThreadFunc, p );
}
Player::~Player()
{
Stop();
if( p->mpThread && p->mpThread->joinable() )
p->mpThread->join();
delete p->mpThread;
delete p;
}
int
Player::UpdateIntervalMs() const
{
std::lock_guard<std::mutex> lock(p->mMutex);
return p->mUpdateIntervalMs;
}
void
Player::SetUpdateIntervalMs( int interval )
{
std::lock_guard<std::mutex> lock(p->mMutex);
p->mUpdateIntervalMs = interval;
}
void
Player::Play( const std::string& file )
{
Stop();
std::string audiocast_tag = "audiocast://";
if(file.find(audiocast_tag) == 0)
{
std::vector<std::string> args =
{ "/usr/local/bin/audiocast_client", "--quiet", "--stdin-control" };
std::istringstream iss(file);
iss.ignore(audiocast_tag.length());
std::string s;
std::getline(iss, s, '/');
args.push_back("--server=" + s);
if(iss.peek() == '?')
iss.ignore();
while(std::getline(iss, s, '&'))
args.push_back("--" + s);
if( !p->mProcess.Exec(args) )
{
Wt::log("error") << "Could not run " << args[0] << ": " << ::strerror(errno);
return;
}
std::lock_guard<std::mutex> lock(p->mMutex);
p->mProcessKind = Audiocast;
p->mState = playing;
}
else if(!file.empty())
{
std::vector<std::string> args =
{ "/usr/bin/mplayer", "-idle", "-slave", "-quiet", "-ao", "alsa" };
if( !p->mProcess.Exec(args) )
{
Wt::log("error") << "Could not run " << args[0] << ": " << ::strerror(errno);
return;
}
std::lock_guard<std::mutex> lock(p->mMutex);
p->mProcessKind = MPlayer;
p->mState = playPending;
p->mProcess.Input() << "loadfile " << file << std::endl;
for( const auto& s : sQueryProperties )
p->mProcess.Input() << "get_" << s << std::endl;
}
}
void
Player::Pause()
{
switch(p->mProcessKind)
{
case MPlayer:
p->mProcess.Input() << "pause" << std::endl;
break;
case none:
break;
default:
p->mProcess.Raise(p->mPaused ? SIGCONT : SIGSTOP);
}
p->mPaused = !p->mPaused;
}
void
Player::Stop()
{
if( p->mPaused )
Pause(); // continue
std::lock_guard<std::mutex> lock( p->mMutex );
switch(p->mProcessKind)
{
case none:
break;
case MPlayer:
p->mProcess.Input() << "quit" << std::endl;
break;
default:
p->mProcess.Kill();
}
}
bool
Player::IsPlaying() const
{
std::lock_guard<std::mutex> lock(p->mMutex);
return p->mState == playing;
}
bool
Player::IsIdle() const
{
std::lock_guard<std::mutex> lock(p->mMutex);
return p->mState == idle;
}
std::string
Player::StreamProperty( const std::string& name ) const
{
std::lock_guard<std::mutex> lock(p->mMutex);
auto i = p->mProperties.find( name );
if( i == p->mProperties.end() )
return "";
return i->second;
}
| true |
524f9c25c25e845be3fff900d49059f38b31275d | C++ | A1b1on/Kursovaya_rabota_1_kurs | /Source/myiterator.h | UTF-8 | 879 | 3.34375 | 3 | [] | no_license | #ifndef MYITERATOR_H
#define MYITERATOR_H
#include <stdlib.h>
#include <iterator>
template <typename ValueType>
class MyIterator : public std::iterator<std::input_iterator_tag, ValueType> {
template <typename>
friend class MyContainer;
ValueType* p;
public:
MyIterator(ValueType* p) : p(p){}
MyIterator() : p(nullptr){}
MyIterator(const MyIterator &it): p(it.p){}
bool operator != (MyIterator const& other) const
{ return p != other.p; }
bool operator == (MyIterator const& other) const
{ return p == other.p; }
typename MyIterator::reference operator*() const
{ return *p; }
typename MyIterator::pointer operator->() const
{ return &*p; }
MyIterator& operator++() {
++p;
return *this;
}
MyIterator& operator--() {
--p;
return *this;
}
};
#endif // MYITERATOR_H
| true |
ad6ec2f1e0fdaecd2698ba0aec46b288b58ceb1c | C++ | PranabSarker10/CPlusPlus | /44 to 57.Inheritance/44 to 57.INHERITANCE PROGRAMMING/48.2INHERIT PROTECTED MEMBER.cpp | UTF-8 | 454 | 3.609375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Student
{
protected:
int roll;
int mark;
};
class Result : public Student
{
public:
void set(){cin>>roll>>mark;}
void print(){cout<<roll<<" "<<mark<<endl;}
};
///If we inherit protected members in public or protected mode it will be protected. But if we inherit protected members in private mode it will be private.
int main()
{
Result ob;
ob.set();
ob.print();
return 0;
}
| true |