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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a29c2ac8bbe4cf9f456fff82cb5c8b6efb08fa68 | C++ | hurmawee/- | /Building.h | UTF-8 | 1,039 | 2.828125 | 3 | [] | no_license | #pragma once
#include <string>
#include < iostream>
using namespace std;
class Build
{
private:
string color;
string floor;
string number;
string area;
string address;
string year;
public:
Build() : color(""), floor(""), number(""), area(""), address(""), year("") {}
~Build(){}
void set_color(string c) { color = c; }
void set_floor(string f) { floor = f; }
void set_number(string n) { number = n; }
void set_area(string a) { area = a; }
void set_address(string ad) { address = ad; }
void set_year(string y) { year = y; }
string get_color() { return color ; }
string get_floor() { return floor ; }
string get_number() { return number ; }
string get_area() { return area ; }
string get_address() { return address ; }
string get_year() { return year; }
virtual void modify(int ch, string inf);
virtual void set_inf();
virtual void show_inf();
virtual void write_inf();
virtual void house() = 0;
virtual int Gethouse() = 0;
virtual string House() = 0;
}; | true |
e62a74b1378d11753f5b6c62c2ab73b81084bd81 | C++ | ppearson/ImaginePartial | /utils/matrix.h | UTF-8 | 3,773 | 2.875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
Imagine
Copyright 2011-2017 Peter Pearson.
Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---------
*/
#ifndef MATRIX_H
#define MATRIX_H
#include <stdio.h>
#include <string.h>
#include "tagged_pointer.h"
namespace Imagine
{
template<typename T> class Matrix;
template<typename T>
class Row
{
public:
explicit Row(class Matrix<T>* matrix, unsigned int row) : m_pMatrix(matrix), m_row(row) { }
inline T& operator[](int col)
// inline T& Row<T>::operator[](int row)
{
return m_pMatrix->item(col, m_row);
}
protected:
Matrix<T>* m_pMatrix;
unsigned int m_row;
};
template<typename T>
class Matrix
{
public:
Matrix() : m_width(0), m_height(0)
{
}
Matrix(unsigned int width, unsigned int height, bool initValues = true) : m_width(width), m_height(height)
{
// use a tagged pointer to keep track of how the memory was allocated in order to delete it appropriately later
if (initValues)
{
m_data.setBoth(new T[width * height], 0);
}
else
{
m_data.setBoth(static_cast<T*>(::operator new(sizeof(T) * width * height)), 1);
}
}
~Matrix()
{
if (m_data.getPtr())
{
unsigned int tag = m_data.getTag();
// work out which delete to call based on if it was operator newed when allocated.
if (tag == 0)
{
delete [] m_data.getPtr();
}
else
{
delete m_data.getPtr();
}
}
}
Matrix<T>& operator=(const Matrix<T>& rhs)
{
copy(rhs);
return *this;
}
void initialise(unsigned int width, unsigned int height, bool initValues)
{
// use a tagged pointer to keep track of how the memory was allocated in order to delete it appropriately later
if (initValues)
{
m_data.setBoth(new T[width * height], 0);
}
else
{
m_data.setBoth(static_cast<T*>(::operator new(sizeof(T) * width * height)), 1);
}
m_width = width;
m_height = height;
}
T* rowPtr(unsigned int row)
{
return m_data.getPtr() + (row * m_width);
}
T* rawData()
{
return m_data.getPtr();
}
// Note: the assumption here is that the dimensions match - in current usages this is the case,
// but this is likely to change in the future, so this will need to be made more robust...
void copy(const Matrix<T>& source)
{
memcpy(m_data.getPtr(), source.m_data.getPtr(), m_width * m_height * sizeof(T));
}
void copy(const Matrix<T>* source)
{
memcpy(m_data.getPtr(), source->m_data.getPtr(), m_width * m_height * sizeof(T));
}
// only usable for ints or float 0.0f
void setAll(T val)
{
memset(m_data.getPtr(), val, m_width * m_height * sizeof(T));
}
void setZero()
{
memset(m_data.getPtr(), 0, m_width * m_height * sizeof(T));
}
T& item(unsigned int x, unsigned int y)
{
return m_data.getPtr()[x + m_width * y];
}
const T& item(unsigned int x, unsigned int y) const
{
return m_data.getPtr()[x + m_width * y];
}
T* itemPtr(unsigned int x, unsigned int y)
{
return &m_data.getPtr()[x + m_width * y];
}
const T* itemPtr(unsigned int x, unsigned int y) const
{
return &m_data.getPtr()[x + m_width * y];
}
Row<T>& operator[](unsigned int row)
{
return Row<T>(this, row);
}
protected:
// tagged pointer is used to track how we allocated the original memory...
TaggedPointer<T, 2> m_data;
unsigned int m_width;
unsigned int m_height;
};
} // namespace Imagine
#endif
| true |
9474d625d27dad1a78d99aedc4082ea5fcc27d74 | C++ | powerslider/ovgu-magdeburg | /cpp/ex6/src/valuenode.cpp | UTF-8 | 562 | 2.71875 | 3 | [] | no_license | #include "valuenode.hpp"
Node* Value::clone() const
{
// Create a new instance with the same type and data. As you can see we
// need to know the type �Value� that is why we cannot implement it
// elsewhere.
return new Value(m_val);
}
// TODO: evaluate implementation using string to int conversation functions
int Value::evaluate(const VariableMap *_varMap) const
{
auto p = _varMap->find(m_val);
if (p != _varMap->end())
{
return p->second;
}
return (int) atol(m_val.c_str());
}
Value::~Value() {
delete m_val;
}
| true |
7b44c553d48c2397ac5c9476a7f722d68b3a7868 | C++ | inirion/PUM_Project | /EarthDefender/jni/MainMenu.hpp | UTF-8 | 2,442 | 2.828125 | 3 | [] | no_license | #ifndef MAINMENU_HPP_
#define MAINMENU_HPP_
#include <SFML/Graphics.hpp>
#include <map>
#include <string>
#include "Lang.hpp"
#include "MenuView.hpp"
#include "Listener.hpp"
#include "S.hpp"
class MainMenu: public sf::Drawable{
private:
std::map<std::string, MenuView> mvmap;
MenuView *selected;
sf::Vector2f firstPos;
sf::Vector2f moveStep;
sf::Vector2f miniStep;
sf::Vector2f defBtnSiz;
sf::Vector2f defCbSiz;
sf::Vector2f bigBtnSiz;
sf::Vector2f minBtnSiz;
sf::Vector2f vzero;
sf::Vector2f texS;
sf::Vector2f moveRight;
sf::Vector2f moveLeft;
sf::Vector2f defTextShift;
sf::Vector2f cbTextShift;
int defFontSize;
int bigFontSize;
int minFontSize;
public:
MainMenu();
inline void resetGsLabel(){char gsbuf[16]; std::sprintf(gsbuf,"%.3f",Conf::gs); mvmap[S::menu_graphics].getButtonMap()[S::btn_gui_scale_label].setText(gsbuf);};//metoda resetująca game scale label;
inline void resetMSoundLabel(){char msndbuf[16]; std::sprintf(msndbuf,"%.0f",Conf::menuSoundVolume); mvmap[S::menu_sound].getButtonMap()[S::btn_menu_sound_label].setText(msndbuf);}//metoda resetująca music sound label;
inline void resetGSoundLabel(){char gsndbuf[16]; std::sprintf(gsndbuf,"%.0f",Conf::gameSoundVolume); mvmap[S::menu_sound].getButtonMap()[S::btn_game_sound_label].setText(gsndbuf);}//metoda resetująca game sound label;
inline MenuView* getSelected(){return selected;}// metoda zwracająca wskaźnik aktualnego MenuView.
inline void setSelected(std::string id){if(mvmap.find(id)!=mvmap.end()){selected=&mvmap.at(id);}else{selected=&mvmap[S::menu_empty];}}// metoda ustawiająca MenuViev na podany w parametrze.
inline std::map<std::string, MenuView>& getMap(){return mvmap;}// metoda zwracająca referencję na mapę MenuView.
void update(sf::RenderWindow &rw);// metoda odświeżająca dany obiekt.
virtual void draw(sf::RenderTarget &target, sf::RenderStates states)const;// metoda draw wymagana przy implementacji sf::Drawable(rysowanie obiektów).
inline void listenAllViews(Listener *l){ for(auto &mv: mvmap) mv.second.listenAllButtons(l); }// metoda nasłuchująca wszystkie View.
inline void unlistenAllViews(Listener *l){ for(auto &mv: mvmap) mv.second.unlistenAllButtons(l);}//metoda kończąca nasłuchiwanie wszystkich View.
inline void refreshAllViewsTexture(){for(auto &mv: mvmap) mv.second.refreshAllButtonsTexture();}// metoda odświeżająca wszystkie tekstury w MenuView.
};
#endif /* MAINMENU_HPP_ */
| true |
462f5d24cb8e8f061042fefddc228d8c346562ac | C++ | Goutham-AR/GEngine | /GEngine/src/events/Event.hh | UTF-8 | 1,826 | 3 | 3 | [] | no_license | #pragma once
#include <common.hh>
#include <string>
#include <functional>
#include <ostream>
namespace GE
{
enum class EventType
{
None = 0,
WindowClose,
WindowResize,
WindowFocus,
WindowMoved,
AppTick,
AppUpdate,
AppRender,
KeyPressed,
KeyReleased,
KeyTyped,
MouseButtonPressed,
MouseButtonReleased,
MouseMoved,
MouseScrolled
};
#define TO_STRING(eventType) #eventType
enum EventCategory
{
EC_None = 0,
EC_App = BIT(0),
EC_Input = BIT(1),
EC_KeyBoard = BIT(2),
EC_Mouse = BIT(3),
EC_MouseButton = BIT(4)
};
class GE_PUBLIC Event
{
friend class EventDispatcher;
public:
[[nodiscard]] virtual EventType getEventType() const = 0;
[[nodiscard]] virtual const char* getName() const = 0;
[[nodiscard]] virtual int getCategoryFlags() const = 0;
[[nodiscard]] virtual std::string toString() const { return getName(); }
[[nodiscard]] inline bool isInCategory(EventCategory category) const
{
return getCategoryFlags() & category;
}
[[nodiscard]] bool isHandled() const { return m_handled; }
void setHandled(bool value) { m_handled = value; }
protected:
bool m_handled = false;
};
class EventDispatcher
{
template <typename T>
using EventFn = std::function<bool(T&)>;
public:
explicit EventDispatcher(Event& event)
: m_event{event}
{
}
template <typename T>
bool dispatchEvent(EventFn<T> func)
{
if (m_event.getEventType() == T::getStaticType())
{
m_event.m_handled = func(*reinterpret_cast<T*>(&m_event));
return true;
}
return false;
}
private:
Event& m_event;
};
inline std::ostream& operator<<(std::ostream& os, const Event& event)
{
return os << event.toString();
}
} | true |
b1f4d1737b30bb1e7319421f3d98afe28579d4b7 | C++ | EvgeneDudkin/HomeworkC- | /simuni/9/5/5/main.cpp | UTF-8 | 1,727 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class shape{
public:
double x;
double y;
shape(double x1, double y1):
x(x1),y(y1)
{}
virtual double area()
= 0;
virtual bool contains(double a, double b)
= 0;
};
class pryam:public shape{
public:
double st1;
double st2;
pryam::pryam(double a,double b, double u, double o):
shape(a,b)
{
st1 = u;
st2 = o;
}
double area();
bool contains(double a, double b);
};
bool pryam::contains(double p1, double p2)
{
return (p1 <= x + (st2/2) && p1 >= x - (st2 /2) && p2 >= y - (st1/2) && p2 <= y + (st1/2));
}
double pryam::area(){
return st1*st2;
}
class krug:public shape{
public:
double r;
krug::krug(double a,double b, double rad):
shape(a,b)
{
r = rad;
}
double area();
bool contains(double a, double b);
};
bool krug::contains(double p1, double p2)
{
return ((p1-x)*(p1-x) + (p2-y)*(p2-y) <= r*r);
}
double krug::area(){
return 3.14*r*r;
}
class shapeCollection
{
public:
vector<shape*> v;
shapeCollection()
{
}
void add(shape* s)
{
v.push_back(s);
}
double area();
bool contains(double p1, double p2);
};
double shapeCollection::area()
{
double res = 0;
for (int i = 0; i < v.size(); i++)
{
res += v[i]->area();
}
return res;
}
bool shapeCollection::contains(double p1, double p2)
{
return any_of(v.begin(), v.end(), [p1,p2] (shape* s) {return s->contains(p1,p2);});
}
int main()
{
shapeCollection coll;
coll.add(new krug(0,0,5));
coll.add(new pryam(0,0,5,5));
coll.add(new pryam(0,0,2,4));
cout << coll.area() << endl;
pryam pr(0,0,5,6);
cout << pr.contains(3,2.6) << endl;
krug kr(1,1,4);
cout << kr.contains(3,3) << endl;
cout << coll.contains(1,1);
return 0;
} | true |
8b803ab30f8530cb3a564b9092abbe95d134c5ad | C++ | gari3008ma/Algo-Wiki | /Algos/deletnode.cpp | UTF-8 | 1,261 | 3.734375 | 4 | [] | no_license | #include <bits/stdc++.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
void deletenode(struct node **tmp,int v)
{
struct node *vmp=*tmp,*prev=*tmp;
if(tmp==NULL)
return ;
if(vmp->data==v)
{
*tmp=vmp->next;
free(vmp);
}
while(vmp!=NULL)
{
if(vmp->data==v)
{
prev->next=vmp->next;
free(vmp);
}
prev=vmp;
vmp=vmp->next;
}
if(vmp==NULL)
return;
}
int main()
{
struct node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
puts("Created Linked List: ");
printList(head);
deletenode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
| true |
e7e858fd0efc34ea739c5a66d501a0ff320ca805 | C++ | opendarkeden/server | /src/server/gameserver/EffectShrineShield.h | UHC | 1,285 | 2.921875 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : EffectShrineShield.h
// Written by :
// Description : Doom ϰ effect
//////////////////////////////////////////////////////////////////////////////
#ifndef __EFFECT_SHRINE_SHIELD__
#define __EFFECT_SHRINE_SHIELD__
#include "Effect.h"
//////////////////////////////////////////////////////////////////////////////
// class EffectShrineShield
//////////////////////////////////////////////////////////////////////////////
// 뿡 ٴ Ʈ̴.
class EffectShrineShield : public Effect
{
public:
EffectShrineShield(Creature* pCreature) ;
EffectShrineShield(Item* pItem) ;
public:
EffectClass getEffectClass() const { return EFFECT_CLASS_SHRINE_SHIELD; }
void affect() {}
void affect(Creature* pCreature) ;
void affect(Item* pItem) ;
void unaffect(Creature* pCreature) ;
void unaffect(Item* pItem) ;
void unaffect() ;
string toString() const ;
public:
int getTick(void) const { return m_Tick; }
void setTick(Turn_t Tick) { m_Tick = Tick; }
int getShrineID() const { return m_ShrineID; }
void setShrineID(int id) { m_ShrineID = id; }
private:
int m_ShrineID;
Turn_t m_Tick;
};
#endif // __EFFECT_DOOM__
| true |
e5fe4e774bf7741533c1b159d4e653fa23f8c865 | C++ | allegraadams/CS_C- | /main-1.cpp | UTF-8 | 1,476 | 3.390625 | 3 | [] | no_license | //implementation file for the EmpProd class
#include <iostream>
#include <string>
#include <iomanip>
#include "productionworker.h"
using namespace std;
void getEmpInfo(ProductionWorker &);
void displayInfo(const ProductionWorker &);
int main()
{
void getEmpInfo(productionworker &);
void displayInfo(const ProductionWorker &);
//create productionworker object for employee
ProductionWorker emp("John Jones", 123, "1/1/2006", 2, 18.00);
getEmpInfo(emp);
//display employee info
displayInfo(emp);
cin.get();
cin.ignore();
return 0;
}
//this function demonstrates the ProductionWorker class which is derived from the Employee class
void getEmpInfo(ProductionWorker &emp)
{
string na = "";
int nu = 0;
string d = "";
int s = 0;
double r = 0.0;
cout << "Name: ";
getline(cin, na);
emp.setName(na);
cout << "Employee ID: ";
cin >> nu;
emp.setNumber(nu);
cout << "Hire Date: ";
cin >> d;
emp.setDate(d);
cout << "Shift (1 for Day and 2 for Night:) ";
cin >> s;
emp.setShift(s);
cout << "Hourly Rate: ";
cin >> r;
emp.setRate(r);
}
void displayInfo(const ProductionWorker &emp)
{
cout << "Name: " << getName() << "\n";
cout << "Employee Number: " << getNumber() << "\n";
cout << "Hire Date: " << getHireDate() << "\n";
cout << "Shift: " << getShift();
{ If(Shift == 1)
Cout << "Day\n";
Else
cout << "Night\n"; }
cout << "Pay Rate: " << getRate() << "\n";
}
| true |
3cb13479b23c17500636bbc8d24c9c594ed760a7 | C++ | jPHU/CP3 | /Introduction/LinearDS/STLQueue/11034.cpp | UTF-8 | 1,708 | 3 | 3 | [] | no_license | #include <cstdio>
#include <queue>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
int n;
cin >> n;
while(n--)
{
queue<long> left;
queue<long> right;
int l, m;
cin >> l >> m;
for(int i = 0; i < m; ++i)
{
string inp;
int val;
cin >> val >> inp;
if(inp == "left")
{
left.push(val);
}
else
{
right.push(val);
}
}
int numberCrosses = 0;
bool leftBank = true;
while(m > 0)
{
int curSpace = l*100;
if(leftBank)
{
while(!left.empty())
{
if(curSpace - left.front() > 0)
{
curSpace -= left.front();
left.pop();
m--;
}
else
{
break;
}
}
}
else
{
while(!right.empty())
{
if(curSpace - right.front() > 0)
{
curSpace -= right.front();
right.pop();
m--;
}
else
{
break;
}
}
}
numberCrosses++;
leftBank = !leftBank;
}
cout << numberCrosses << endl;
}
return 0;
}
| true |
9aa5f149471280a1f9c1bb1117ebf3f9619a5e50 | C++ | dtbinh/M1S2 | /TraitementImage/TP6/main.cpp | UTF-8 | 2,891 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "image_ppm.h"
int calculMoyenne(OCTET* image, int position, int nW){
int result = 0;
int nb = 0;
for(int i = -1; i<2; i++){
for(int j =-1; j<2; j++){
if(image[(i + position)*nW+j] != 0){
result += image[(i + position)*nW+j];
nb++;
}
}
}
return result / nb;
}
void reconstructionParMoyenne(char* nomImageLue, char* nomImageSortie){
int nH, nW, nTaille;
OCTET *ImgIn, *ImgOut;
lire_nb_lignes_colonnes_image_pgm(nomImageLue, &nH, &nW);
nTaille = nH * nW;
allocation_tableau(ImgIn, OCTET, nTaille);
lire_image_pgm(nomImageLue, ImgIn, nH * nW);
allocation_tableau(ImgOut, OCTET, nTaille);
for (int i=0; i < nH; i++){
for (int j=0; j < nW; j++){
if(ImgIn[i*nW+j] < 30){
ImgIn[i*nW+j] = 0;
}
if( ImgIn[i*nW+j] == 0){
ImgOut[i*nW+j] = calculMoyenne(ImgIn,i,nW);
}else{
ImgOut[i*nW+j] = ImgIn[i*nW+j];
}
}
}
ecrire_image_pgm(nomImageSortie, ImgOut, nH, nW);
free(ImgIn);
free(ImgOut);
}
void reconstructionParDilatation(char* entre,char* sortie){
int nH, nW, nTaille;
std::vector<int> listeValeur;
OCTET *ImgIn, *ImgOut;
lire_nb_lignes_colonnes_image_pgm(entre, &nH, &nW);
nTaille = nH * nW;
//allocation_tableau(ImgIn, OCTET, nTaille);
//lire_image_pgm(entre, ImgIn, nH * nW);
allocation_tableau(ImgOut, OCTET, nTaille);
lire_image_pgm(entre, ImgOut, nH * nW);
bool fin = false;
while(!fin){
fin = true;
for (int i=1; i < nH-1; i++){
for (int j=1; j < nW-1; j++){
if(ImgOut[i*nW+j] < 15){
fin = false;
for(int k=-1; k<2; k++){
for(int l=-1; l<2; l++){
if(ImgOut[(i + k)*nW+(j+l)] > 15 ){
listeValeur.push_back(ImgOut[(i + k)*nW+(j+l)]);
}
}
}
if(!listeValeur.empty()){
int max = 0;
for(int i=0; i<listeValeur.size(); i++){
if(listeValeur.at(i) > max){
max = listeValeur.at(i);
}
}
ImgOut[i*nW+j] = max;
listeValeur.clear();
}/*else{
ImgOut[i*nW+j] = ImgOut[i*nW+j];
}*/
}/*else{
ImgOut[i*nW+j] = ImgOut[i*nW+j];
}*/
}
}
/*
for (int i=0; i < nH; i++){
for (int j=0; j < nW; j++){
ImgIn[i*nW+j] = ImgOut[i*nW+j];
}
}*/
}
ecrire_image_pgm(sortie, ImgOut, nH, nW);
//free(ImgIn);
free(ImgOut);
}
int main(int argc, char* argv[]){
char* cNomImgLue = new char[256];
char* cNomImgEcrite = new char[256];
sscanf (argv[1],"%s",cNomImgLue) ;
sscanf (argv[2],"%s",cNomImgEcrite);
//reconstructionParMoyenne(cNomImgLue,cNomImgEcrite);
reconstructionParDilatation(cNomImgLue,cNomImgEcrite);
return 1;
}
| true |
f50ca9e913d4ffce1432790678273c6ddd5f1299 | C++ | ramonjunquera/GlobalEnvironment | /RPi/Qt/02 Qt C/demos/08 constructorVar/constructorVar/point.cpp | UTF-8 | 317 | 2.6875 | 3 | [] | no_license | #include "point.h"
void Point::show()
{
//Muestra las variables privadas
cout << "x=" << _x << ",y=" << _y << endl;
}
Point::Point(int x,int y):_x(x),_y(y)
{
//Nada especial que hacer aquí porque los parámetros se han
//asignado a las variables privadas en las definición del
//constructor
}
| true |
3bca62a3d669c13e7a97cce9d42777d9b3b4c0d8 | C++ | katalist5296/Graph | /CPM/CPM/main.cpp | WINDOWS-1251 | 2,477 | 2.78125 | 3 | [] | no_license | #include <iostream>
#define INF -1 //
#define MatrixLen 8
int matrix[MatrixLen][MatrixLen] =
{
// 1 2 3 4 5 6 7 8
{0, 4, 6, 7, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 8, 0, 0},
{0, 0, 0, 0, 5, 0, 0, 0},
{0, 0, 0, 0, 9, 6, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 14},
{0, 0, 0, 0, 0, 0, 10, 12},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
};
void printSolution(int dist[], int n, int time)
{
printf("Path [ ");
for (int i = 0; i < n; i++)
{
if(dist[i] == 0)
printf("%d ", i + 1);
}
printf(" ]\nTime: %d\n", time);
}
//===================================
int minDistance(int dist[], bool shortest[])
{
int min = INF, min_index;
for (int v = 0; v < MatrixLen; v++)
{
if (shortest[v] == false && dist[v] >= min)
{
min = dist[v], min_index = v;
}
}
return min_index;
}
void solution()
{
int dist_max[MatrixLen],
dist_relation[MatrixLen],
dist_solve[MatrixLen];
bool shortestPath[MatrixLen];
for (int i = 0; i < MatrixLen; i++)
{
dist_max[i] = INF, shortestPath[i] = false;
}
dist_max[0] = 0;
for (int count = 0; count < MatrixLen; count++)
{
int u = minDistance(dist_max, shortestPath);
shortestPath[u] = true;
for (int v = 0; v < MatrixLen; v++)
{
if (!shortestPath[v] && matrix[u][v]
&& dist_max[u] + matrix[u][v] > dist_max[v])
dist_max[v] = dist_max[u] + matrix[u][v];
}
}
for (int i = 0; i < MatrixLen; i++)
{
dist_relation[i] = INF, shortestPath[i] = false;
}
dist_relation[0] = dist_max[MatrixLen - 1];
dist_relation[MatrixLen - 1] = 0;
int temp;
for (int i = 0; i < MatrixLen; ++i)
{
for (int j = 0; j < i; ++j)
{
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int count = 0; count < MatrixLen; count++)
{
int u = minDistance(dist_relation, shortestPath);
shortestPath[u] = true;
for (int v = 0; v < MatrixLen; v++)
{
if (!shortestPath[v] && matrix[u][v]
&& dist_relation[u] + matrix[u][v] > dist_relation[v])
dist_relation[v] = dist_relation[u] + matrix[u][v];
}
if (dist_relation[count] == INF)
dist_relation[count] = 0;
dist_solve[count] = dist_max[MatrixLen - 1] - dist_relation[count];
dist_solve[count] = dist_max[count] - dist_solve[count];
//printf("%d = %d - %d\n", dist_solve[count], dist_relation[count], dist_max[MatrixLen - 1]);
}
printSolution(dist_solve, MatrixLen, dist_max[MatrixLen - 1]);
}
int main()
{
solution();
system("pause");
return 1;
} | true |
99e1b0ee6b3848e2f3b1a2caa702c42472a2a678 | C++ | akiirokaede/Solutions_CPP_Primer_5th | /chapter 10/10_13.cc | UTF-8 | 408 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool tooLong(const string &s)
{
return (s.length()>=5?true:false);
}
int main(){
vector<string> vec{"trump","and","trump","and","trump","are","friends","of","chinese"};
auto ed=partition(vec.begin(),vec.end(),tooLong);
vec.erase(ed,vec.end());
for(auto i:vec)cout<<i<<" ";
return 0;
} | true |
5dd6ccdb0af696402fb8e7fd6a5e3f1f20eaf9bc | C++ | NicoleAlexandraLaraAnago/3685-BackSquad | /Deberes/Arboles AVL/TreeCalculator/opstack.h | UTF-8 | 9,535 | 3.015625 | 3 | [] | no_license | /**
* UNIVERSIDAD DE LAS FUERZAS ARMADAS ESPE
* Departamento de ciencias de la computacion
* Estructura de datos
* Docente: Ing. Fernando Solis
* Tema: Convertir notacion infija a postfija, prefija y funcional
*
* @date 05/07/2021
* @author Diego Jimenez
*/
#pragma once
#include "stack.h"
#include "opstr.h"
#include <math.h>
#include <string>
#include <cstring>
#include <iostream>
// bool isOperator(char c){
// return (c == '+' || c == '-' || c == '*' || c == '/');
// }
bool isReal(char c){
return (c == '0' || c == '1' || c == '2' || c == '3' || c == '4'
|| c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '.');
}
bool isReal(std::string c){
return (c == "0" || c == "1" || c == "2" || c == "3" || c == "4"
|| c == "5" || c == "6" || c == "7" || c == "8" || c == "9" || c == ".");
}
int precedencia(std::string c){
return (c == "+" || c == "-") ? 1 :
(c == "*") ? 2 :
(c == "/") ? 3 :
(c == "^") ? 4 : 0;
}
bool isFuntion(std::string c){
return (c == "sin" || c == "cos" || c == "tan" || c == "exp" || c == "log");
}
Stack<std::string> inToStack(std::string chain){
char* str = new char;
std::strcpy(str,chain.c_str());
Stack<std::string> outcome;
int i = 0;
while(*(str + i) != '\0'){
if(!isReal(*(str+i))){
if(isOperator(*(str+i))){
outcome.push_(chain.substr(i,1));
}else if(*(str+i) !='(' && *(str+i) !=')'){
int j = i;
while(!isReal(*(str+i)) && *(str+i) != '('){
i++;
}
outcome.push_(chain.substr(j,i-j));
i--;
}else if(*(str+i) =='(' || *(str+i) ==')'){
outcome.push_(chain.substr(i,1));
}
else{
i++;
continue;
}
}else{
int k = i;
while (isReal(*(str+i))){
i++;
}
outcome.push_(chain.substr(k,i-k));
i--;
}
i++;
}
return outcome;
}
Stack<std::string> inToPost(Stack<std::string> str){
Stack<std::string> operators;
Stack<std::string> outcome;
Node<std::string>* tmp = str.getCursor();
while(tmp->getNext() != nullptr){
if(isOperator(tmp->getDat()) || isFuntion(tmp->getDat())){
int current = precedencia(tmp->getDat());
int st = 0;
operators.isEmpty()? st =0 : st= precedencia(operators.peak());
bool aux;
operators.isEmpty()? aux = false : aux = !isFuntion(operators.peak());
while( !operators.isEmpty() &&
st > current && !isFuntion(tmp->getDat())){
outcome.push_(operators.peak());
operators.pop();
operators.isEmpty()? st =0 : st= precedencia(operators.peak());
}
operators.push_(tmp->getDat());
}else if (tmp->getDat() =="("){
operators.push_(tmp->getDat());
}else if (tmp->getDat() == ")"){
while(operators.peak() != "("){
outcome.push_(operators.peak());
operators.pop();
}
operators.pop();
if(!operators.isEmpty() && isFuntion(operators.peak())){
outcome.push_(operators.peak());
operators.pop();
}
}else{
outcome.push_(tmp->getDat());
if(!operators.isEmpty() && isFuntion(operators.peak())){
outcome.push_(operators.peak());
operators.pop();
}
}
tmp = tmp->getNext();
}
////////////////////////////////////////
if(isOperator(tmp->getDat()) || isFuntion(tmp->getDat())){
int current = precedencia(tmp->getDat());
int st = 0;
operators.isEmpty()? st =0 : st= precedencia(operators.peak());
while( !operators.isEmpty() &&
st > current && !isFuntion(operators.peak())){
outcome.push_(operators.peak());
operators.pop();
operators.isEmpty()? st =0 : st= precedencia(operators.peak());
}
operators.push_(tmp->getDat());
}else if (tmp->getDat() =="("){
operators.push_(tmp->getDat());
}else if (tmp->getDat() == ")"){
while(operators.peak() != "("){
outcome.push_(operators.peak());
operators.pop();
}
operators.pop();
}else{
outcome.push_(tmp->getDat());
if(!operators.isEmpty() && isFuntion(operators.peak())){
outcome.push_(operators.peak());
operators.pop();
}
}
/////////////////////////////////////////
while (!operators.isEmpty())
{
outcome.push_(operators.peak());
operators.pop();
}
return outcome;
}
double operateBinary(double left, double right, std::string operators){
if(operators == "+"){
return left + right;
}else if(operators == "-"){
return left - right;
}else if(operators == "*"){
return left * right;
}else if(operators == "/"){
return left / right;
}else if(operators == "^"){
return pow(left,right);
}else
return 0;
}
double operateUnary(double operand, std::string fun){
if(fun == "sin"){
return sin(operand);
}else if(fun == "cos"){
return cos(operand);
}else if(fun == "tan"){
return tan(operand);
}else if(fun == "exp"){
return exp(operand);
}else if(fun == "log"){
return log(operand);
}else
return 0;
}
double calculateReversePolac(Stack<std::string> str){
Stack<double> operands;
Node<std::string>* tmp = str.getCursor();
do{
if(!isOperator(tmp->getDat()) && !isFuntion(tmp->getDat())){
operands.push_(std::stod(tmp->getDat()));
}
else if(isOperator(tmp->getDat())){
double right = operands.peak();
operands.pop();
double left = operands.peak();
operands.pop();
operands.push_(operateBinary(left, right,tmp->getDat()));
}else if(isFuntion(tmp->getDat())){
double operand = operands.peak();
operands.pop();
operands.push_(operateUnary(operand,tmp->getDat()));
}
tmp = tmp->getNext();
}while(tmp->getNext() != nullptr);
if(isOperator(tmp->getDat())){
double right = operands.peak();
operands.pop();
double left = operands.peak();
operands.pop();
operands.push_(operateBinary(left, right,tmp->getDat()));
}else if(isFuntion(tmp->getDat())){
double operand = operands.peak();
operands.pop();
operands.push_(operateUnary(operand,tmp->getDat()));
}
return operands.peak();
}
std::string inToPre(Stack<std::string> str){
if( str.getSize() == 0 ) // end condtion to stop recursion
return "";
Node<std::string>* tmp = str.getLast();
std::string tmpString = tmp->getDat();
str.pop();
return tmpString + " " + inToPre(str);
}
std::string getStringOperator(std::string op){
if(op == "+"){
return "suma";
}else if(op == "-"){
return "resta";
}else if(op == "*"){
return "multiplicacion";
}else if(op == "/"){
return "division";
}else if(op == "^"){
return "potenciacion";
}else
return "";
}
std::string postToFuntional(Stack<std::string> str){
Stack<std::string> operands;
Node<std::string>* tmp = str.getCursor();
std::string outcome = "";
do{
if(!isOperator(tmp->getDat()) && !isFuntion(tmp->getDat())){
operands.push_(tmp->getDat());
}
else if(isOperator(tmp->getDat())){
std::string right;
operands.peak() == outcome ? right = outcome : right = operands.peak();
operands.pop();
std::string left;
operands.peak() == outcome ? left = outcome : left = operands.peak();
operands.pop();
// operands.push_(operateBinary(left, right,tmp->getDat()));
outcome = getStringOperator(tmp->getDat()) + "(" + left + ", " + right + ")";
operands.push_(outcome);
}else if(isFuntion(tmp->getDat())){
std::string operand;
operands.peak() == outcome ? operand = outcome : operand = operands.peak();
operands.pop();
// operands.push_(operateUnary(operand,tmp->getDat()));
outcome = tmp->getDat() + "(" + operand + ")";
operands.push_(outcome);
}
tmp = tmp->getNext();
}while(tmp->getNext() != nullptr);
if(isOperator(tmp->getDat())){
std::string right;
operands.peak() == outcome ? right = outcome : right = operands.peak();
operands.pop();
std::string left;
operands.peak() == outcome ? left = outcome : left = operands.peak();
operands.pop();
// operands.push_(operateBinary(left, right,tmp->getDat()));
outcome = getStringOperator(tmp->getDat()) + "(" + left + ", " + right + ")";
operands.push_(outcome);
}else if(isFuntion(tmp->getDat())){
std::string operand;
operands.peak() == outcome ? operand = outcome : operand = operands.peak();
operands.pop();
// operands.push_(operateUnary(operand,tmp->getDat()));
outcome = tmp->getDat() + "(" + operand + ")";
operands.push_(outcome);
}
return outcome;
} | true |
bfd0601138ac4e6fae4e39746f9b872c3b915baa | C++ | taqu/sampling | /Sampling.cpp | UTF-8 | 24,324 | 2.640625 | 3 | [
"Unlicense",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | /**
@file Sampling.cpp
@author t-sakai
@date 2019/09/15 create
*/
#include "Sampling.h"
#if LRAY_STANDALONE
#include <Windows.h>
#include "Sort.h"
#endif
namespace lray
{
#if LRAY_STANDALONE
u32 bitreverse(u32 x)
{
#if defined(__GNUC__)
x = __builtin_bswap32(x);
#elif defined(__clang__)
x = __builtin_bswap32(x);
#else
x = (x << 16) | (x >> 16);
x = ((x & 0x00FF00FFU) << 8) | ((x & 0xFF00FF00U) >> 8);
#endif
x = ((x & 0x0F0F0F0FU) << 4) | ((x & 0xF0F0F0F0U) >> 4);
x = ((x & 0x33333333U) << 2) | ((x & 0xCCCCCCCCU) >> 2);
x = ((x & 0x55555555U) << 1) | ((x & 0xAAAAAAAAU) >> 1);
return x;
}
namespace
{
static const u32 WELL_N = 16;
u32 WELL_state[WELL_N];
u32 WELL_index = 0;
}
f32 rand()
{
u32 a, b, c, d;
a = WELL_state[WELL_index];
c = WELL_state[(WELL_index + 13) & 15];
b = a ^ c ^ (a << 16) ^ (c << 15);
c = WELL_state[(WELL_index + 9) & 15];
c ^= c >> 11;
a = WELL_state[WELL_index] = b ^ c;
d = a ^ ((a << 5) & 0xDA442D24UL);
WELL_index = (WELL_index + 15) & 15;
a = WELL_state[WELL_index];
WELL_state[WELL_index] = a ^ b ^ d ^ (a << 2) ^ (b << 18) ^ (c << 28);
u32 x = WELL_state[WELL_index];
static const u32 m0 = 0x3F800000U;
static const u32 m1 = 0x007FFFFFU;
x = m0 | (x & m1);
return (*(f32*)&x) - 1.000000000f;
}
void srand(u32 seed)
{
WELL_state[0] = seed;
for(u32 i=1; i<WELL_N; ++i){
WELL_state[i] = (1812433253 * (WELL_state[i-1]^(WELL_state[i-1] >> 30)) + i);
}
}
u32 cryptRandom()
{
#if _WIN32
u32 buffer = 0;
HMODULE handle = LoadLibraryA("Advapi32.dll");
if(NULL != handle){
FARPROC procAddress = GetProcAddress(handle, "SystemFunction036");
BOOLEAN result = (*(BOOLEAN (*)(PVOID, ULONG))procAddress)(&buffer, sizeof(u32));
FreeLibrary(handle);
if(!result){
return 1234567U;
}
}
#else
s32 fd = open("/dev/random", O_RDONLY);
if(fd<0){
return 1234567U;
}
u32 buffer = 0;
read(fd, &buffer, sizeof(u32));
close(fd);
#endif
return buffer;
}
#endif
s32 gcd(s32 a, s32 b)
{
while(0!=b){
s32 tmp = a%b;
a = b;
b = tmp;
}
return a;
}
void extended_euclid(s32& d, s32& x, s32& y, s32 a, s32 b)
{
if(0 == b){
d = a;
x = 1;
y = 0;
}else{
s32 td, tx,ty;
extended_euclid(td, tx, ty, b, a%b);
d = td;
x = ty;
y = tx - (a/b) * ty;
}
}
void gaussianBasisReduction(s64& b1x, s64& b1y, s64& b2x, s64& b2y, s32 gx, s32 gy, s32 n)
{
if(1==gx){
b1x = gx;
b1y = gy;
b2x = 0;
b2y = n;
}else if(1==gy){
b1x = gx;
b1y = gy;
b2x = n;
b2y = 0;
}else{
s32 egx0, egx1, egx2;
extended_euclid(egx0, egx1, egx2, n, gx);
s32 egy0, egy1, egy2;
extended_euclid(egy0, egy1, egy2, egx0, gy);
s32 b1 = (n/egx0) * egy2;
s32 b2 = (-gx/egx0) * egy2;
b1x = egx2 * gx + egx1*n;
b1y = egx2 * gy;
b2x = b1 * gx + b2 * n;
b2y = b1 * gy + egy1 * n;
}
s64 ib1 = b1x*b1x + b1y*b1y;
s64 ib2 = b2x*b2x + b2y*b2y;
for(;;){
if(ib2<ib1){
swap(b1x, b2x);
swap(b1y, b2y);
}
f32 t = static_cast<f32>(b1x*b2x + b1y*b2y)/(b1x*b1x + b1y*b1y);
s32 mu = static_cast<s32>(floorf(t+0.5f));
b2x -= mu*b1x;
b2y -= mu*b1y;
ib1 = b1x*b1x + b1y*b1y;
ib2 = b2x*b2x + b2y*b2y;
if(ib1<=ib2){
break;
}
}
}
void searchExhausitiveR1Lattice(s32& x, s32& y, s32 n)
{
s64 maxMin = 0;
x=1;
y=1;
for(s32 j=1; j<n; ++j){
for(s32 i=1; i<j; ++i){
if(1 == gcd(gcd(i,j), n)){
s64 b1x,b1y,b2x,b2y;
gaussianBasisReduction(b1x, b1y, b2x, b2y, i, j, n);
s64 distance = b1x*b1x + b1y*b1y;
if(maxMin<distance){
maxMin = distance;
x=i;
y=j;
}
}
}
}
}
//---------------------------------------------------------
//--- R2
//---------------------------------------------------------
const f64 R2::G[3] = {
1.0/1.61803398874989484820458683436563,
1.0/1.32471795724474602596090885447809,
1.0/1.22074408460575947536168534910883,
};
f32 R2::generate1(s32 index)
{
f32 a1 = static_cast<f32>(G[0]);
f32 x = (0.5f + a1*index);
return x-floorf(x);
}
Sample2 R2::generate2(s32 index)
{
f32 a1 = static_cast<f32>(G[1]);
f32 a2 = static_cast<f32>(G[1]*G[1]);
f32 x = (0.5f + a1*index);
f32 y = (0.5f + a2*index);
return {x-floorf(x), y-floorf(y)};
}
//---------------------------------------------------------
//--- JitteredR2
//---------------------------------------------------------
JitteredR2::JitteredR2(s32 maxSamples)
:a_(LRAY_NULL)
,s_(LRAY_NULL)
,c_(LRAY_NULL)
{
size_t maxSize = sizeof(s32) * maxSamples * 3;
a_ = reinterpret_cast<s32*>(LRAY_MALLOC(maxSize));
s_ = reinterpret_cast<s32*>(LRAY_MALLOC(maxSize));
c_ = reinterpret_cast<s32*>(LRAY_MALLOC(maxSize));
}
JitteredR2::~JitteredR2()
{
LRAY_FREE(c_);
LRAY_FREE(s_);
LRAY_FREE(a_);
}
f32 JitteredR2::fractionalPowerX(s32 x, s32 y)
{
s32 n = x * y;
size_t size = sizeof(s32) * n;
memset(a_, 0, size);
memset(s_, 0, size);
a_[0] = 1;
for(s32 j = 0; j < y; ++j){
memset(c_, 0, size);
s_[0] = a_[0];
for(s32 i = 0; i < (n - 1); ++i){
f32 z = static_cast<f32>(a_[i + 1] + a_[i] + c_[i]);
c_[i + 1] = static_cast<s32>(z / x);
s_[i + 1] = static_cast<s32>(z - c_[i + 1] * x); //z%x
}
memcpy(a_, s_, size);
}
f32 f = 0.0f;
for(s32 i = 0; i < y; ++i){
f += a_[i] * powf(x, i - y);
}
return f;
}
Sample2 JitteredR2::getU(s32 index)
{
static const f32 pi = 3.14159265359f;
f32 v[2] = {fractionalPowerX(2, index + 1), fractionalPowerX(3, index + 1)};
return {sqrtf(v[0]) * cosf(2.0f * pi * v[1]), sqrtf(v[0]) * sinf(2.0f * pi * v[1])};
}
Sample2 JitteredR2::generate2(s32 index, f32 lamda)
{
static const f32 delta0 = 0.76f;
static const f32 i0 = 0.7f;
static const f32 sqrt_pi = 1.77245385091f;
Sample2 p = R2::generate2(index);
Sample2 u = getU(index);
f32 k = lamda * delta0 * sqrt_pi / (4.0f * sqrtf(static_cast<f32>(index) + i0));
p.x_ += k*u.x_;
p.y_ += k*u.y_;
p.x_ -= floorf(p.x_);
p.y_ -= floorf(p.y_);
return p;
}
Sample2 JitteredR2::generateRandom2(s32 index, f32 lamda)
{
static const f32 delta0 = 0.76f;
static const f32 i0 = 0.7f;
static const f32 sqrt_pi = 1.77245385091f;
Sample2 p = R2::generate2(index);
f32 ux = lray::rand();
f32 uy = lray::rand();
f32 k = lamda * delta0 * sqrt_pi / (4.0f * sqrtf(static_cast<f32>(index) + i0));
p.x_ += k*ux;
p.y_ += k*uy;
p.x_ -= floorf(p.x_);
p.y_ -= floorf(p.y_);
return p;
}
void hammersley(f32& x0, f32& x1, s32 index, s32 numPoints)
{
LRAY_ASSERT(0<=index && index<numPoints);
x0 = static_cast<f32>(index)/numPoints;
x1 = radicalInverseVanDerCorput(index);
}
//---------------------------------------------------------
//--- ProgressiveJittered
//---------------------------------------------------------
void ProgressiveJittered::generate(s32 M, Sample2* samples)
{
LRAY_ASSERT(0==(M%4));
LRAY_ASSERT(LRAY_NULL != samples);
samples[0].x_ = lray::rand();
samples[0].y_ = lray::rand();
s32 N = 1;
while(N<M){
extendSequence(N, samples);
N <<= 2;
}
}
void ProgressiveJittered::extendSequence(s32 N, Sample2* samples)
{
f32 n = sqrtf(static_cast<f32>(N));
f32 invn = 1.0f/n;
for(s32 s=0; s<N; ++s){
Sample2 old = samples[s];
s32 i = static_cast<s32>(n * old.x_);
s32 j = static_cast<s32>(n * old.y_);
s32 xhalf = static_cast<s32>(2.0f * (n*old.x_ - i));
s32 yhalf = static_cast<s32>(2.0f * (n*old.y_ - j));
xhalf = 1-xhalf;
yhalf = 1-yhalf;
samples[N+s] = generateSamplePoint(i, j, xhalf, yhalf, invn);
if(0.5f<rand()){
xhalf = 1-xhalf;
}else{
yhalf = 1-yhalf;
}
samples[2*N+s] = generateSamplePoint(i, j, xhalf, yhalf, invn);
xhalf = 1-xhalf;
yhalf = 1-yhalf;
samples[3*N+s] = generateSamplePoint(i, j, xhalf, yhalf, invn);
}
}
Sample2 ProgressiveJittered::generateSamplePoint(s32 i, s32 j, s32 xhalf, s32 yhalf, f32 invn)
{
f32 x = (i + 0.5f * (xhalf + rand())) * invn;
f32 y = (j + 0.5f * (yhalf + rand())) * invn;
return {x, y};
}
//---------------------------------------------------------
//--- Stratified
//---------------------------------------------------------
Stratified::Stratified(s32 maxSamples)
:maxSamples_(maxSamples)
{
LRAY_ASSERT(0<=maxSamples_);
s32 resolution = static_cast<s32>(ceilf(sqrtf(maxSamples_)));
maxSamples_ = resolution*resolution;
samples_ = LRAY_MALLOC_TYPE(Sample2, sizeof(Sample2)*resolution*resolution);
}
Stratified::~Stratified()
{
LRAY_FREE(samples_);
}
s32 Stratified::getResolution(s32 N) const
{
LRAY_ASSERT(0<=N && N<=maxSamples_);
return static_cast<s32>(ceilf(sqrtf(N)));
}
void Stratified::generate(s32 N, Sample2* samples)
{
LRAY_ASSERT(LRAY_NULL != samples);
s32 resolution = getResolution(N);
f32 span = 1.0f/resolution;
for(s32 i=0; i<resolution; ++i){
f32 sy = static_cast<f32>(i)*span;
for(s32 j=0; j<resolution; ++j){
f32 x = static_cast<f32>(j)*span + span*rand();
f32 y = sy + span*rand();
samples_[resolution*i + j] = {x, y};
}
}
shuffle(resolution);
for(s32 i=0; i<N; ++i){
samples[i] = samples_[i];
}
}
void Stratified::shuffle(s32 resolution)
{
for(s32 i=0; i<resolution; ++i){
s32 r = i*resolution;
for(s32 j=2; j<resolution; ++j){
s32 k = static_cast<s32>(rand()*j);
swap(samples_[r+j], samples_[r+k]);
}
}
//swap along rows
for(s32 j = 0; j < resolution; ++j){
for(s32 i = 2; i < resolution; ++i){
s32 i0 = i*resolution + j;
s32 i1 = static_cast<s32>(rand() * i) * resolution + j;
swap(samples_[i0], samples_[i1]);
}
}
}
#if 0
//---------------------------------------------------------
//--- ProgressiveMultiJittered
//---------------------------------------------------------
ProgressiveMultiJittered::ProgressiveMultiJittered(s32 maxSamples)
:numSamples_(0)
,xhalves_(LRAY_NULL)
,yhalves_(LRAY_NULL)
,occupied1Dx_(LRAY_NULL)
,occupied1Dy_(LRAY_NULL)
{
xhalves_ = reinterpret_cast<f32*>(LRAY_MALLOC(sizeof(f32)*maxSamples));
yhalves_ = reinterpret_cast<f32*>(LRAY_MALLOC(sizeof(f32)*maxSamples));
occupied1Dx_ = reinterpret_cast<bool*>(LRAY_MALLOC(sizeof(bool)*maxSamples*2));
occupied1Dy_ = reinterpret_cast<bool*>(LRAY_MALLOC(sizeof(bool)*maxSamples*2));
}
ProgressiveMultiJittered::~ProgressiveMultiJittered()
{
LRAY_FREE(occupied1Dy_);
LRAY_FREE(occupied1Dy_);
LRAY_FREE(yhalves_);
LRAY_FREE(xhalves_);
}
void ProgressiveMultiJittered::generate(s32 M, Sample2* samples)
{
LRAY_ASSERT(0==(M%4));
LRAY_ASSERT(LRAY_NULL != samples);
numSamples_ = 0;
samples[0] = {rand(), rand()};
s32 N = 1;
while(N<M){
extendSequenceEven(N, samples);
extendSequenceOdd(2*N, samples);
N <<= 2;
}
}
void ProgressiveMultiJittered::extendSequenceEven(s32 N, Sample2* samples)
{
s32 n = static_cast<s32>(sqrtf(N));
markOccupiedStrata(N, samples);
for(s32 s=0; s<N; ++s){
Sample2 oldpt = samples[s];
f32 i = floorf(n*oldpt.x_);
f32 j = floorf(n*oldpt.y_);
f32 xhalf = 1.0f - floorf(2.0f*(n*oldpt.x_-i));
f32 yhalf = 1.0f - floorf(2.0f*(n*oldpt.y_-j));
samples[numSamples_++] = generateSamplePoint(i, j, xhalf, yhalf, n, N, samples);
}
}
void ProgressiveMultiJittered::extendSequenceOdd(s32 N, Sample2* samples)
{
s32 n = static_cast<s32>(sqrtf(N));
markOccupiedStrata(N, samples);
s32 halfN = N>>1;
for(s32 s=0; s<halfN; ++s){
Sample2 oldpt = samples[s];
f32 i = floorf(n*oldpt.x_);
f32 j = floorf(n*oldpt.y_);
f32 xhalf = floorf(2.0f*(n*oldpt.x_-i));
f32 yhalf = floorf(2.0f*(n*oldpt.y_-j));
if(0.5f<rand()){
xhalf = 1.0f-xhalf;
}else{
yhalf = 1.0f-yhalf;
}
xhalves_[s] = xhalf;
yhalves_[s] = yhalf;
samples[numSamples_++] = generateSamplePoint(i, j, xhalf, yhalf, n, N, samples);
}
for(s32 s=0; s<halfN; ++s){
Sample2 oldpt = samples[s];
f32 i = floorf(n*oldpt.x_);
f32 j = floorf(n*oldpt.y_);
f32 xhalf = 1.0f - xhalves_[s];
f32 yhalf = 1.0f - yhalves_[s];
samples[numSamples_++] = generateSamplePoint(i, j, xhalf, yhalf, n, N, samples);
}
}
void ProgressiveMultiJittered::markOccupiedStrata(s32 N, Sample2* samples)
{
s32 NN = N<<1;
for(s32 i=0; i<NN; ++i){
occupied1Dx_[i] = false;
occupied1Dy_[i] = false;
}
for(s32 s=0; s<N; ++s){
s32 xstratum = static_cast<s32>(NN*samples[s].x_);
s32 ystratum = static_cast<s32>(NN*samples[s].y_);
occupied1Dx_[xstratum] = true;
occupied1Dy_[ystratum] = true;
}
}
Sample2 ProgressiveMultiJittered::generateSamplePoint(f32 i, f32 j, f32 xhalf, f32 yhalf, s32 n, s32 N, const Sample2* samples)
{
s32 NN = N<<1;
f32 bestDist = 0.0f;
s32 numCand = 10;
s32 xstratum;
s32 ystratum;
Sample2 pt = {};
Sample2 candpt;
for(s32 t=1; t<numCand; ++t){
do{
candpt.x_ = (i+0.5f * (xhalf + rand()))/n;
xstratum = static_cast<s32>(NN*candpt.x_);
}while(occupied1Dx_[xstratum]);
do{
candpt.y_ = (j+0.5f * (yhalf + rand()))/n;
ystratum = static_cast<s32>(NN*candpt.y_);
}while(occupied1Dy_[ystratum]);
f32 d = minDist(candpt, numSamples_, samples);
if(bestDist<d){
bestDist = d;
pt = candpt;
}
}
xstratum = static_cast<s32>(NN*pt.x_);
ystratum = static_cast<s32>(NN*pt.y_);
occupied1Dx_[xstratum] = true;
occupied1Dy_[ystratum] = true;
return pt;
}
f32 ProgressiveMultiJittered::minDist(const Sample2& candidate, s32 numSamples, const Sample2* samples)
{
f32 x = candidate.x_ - samples[0].x_;
f32 y = candidate.y_ - samples[0].y_;
f32 sqrDistance = x*x + y*y;
for(s32 i=1; i<numSamples; ++i){
f32 tx = candidate.x_ - samples[i].x_;
f32 ty = candidate.y_ - samples[i].y_;
f32 d = tx*tx + ty*ty;
if(sqrDistance<d){
sqrDistance = d;
}
}
return sqrtf(sqrDistance);
}
//---------------------------------------------------------
//--- CCVT
//---------------------------------------------------------
f32 CCVT::sqrDistance(const Sample2& x0, const Sample2& x1)
{
f32 dx = x0.x_ - x1.x_;
f32 dy = x0.y_ - x1.y_;
return dx*dx + dy*dy;
}
f32 CCVT::sqrDistance(const Point& x0, const Sample2& x1)
{
f32 dx = x0.x_ - x1.x_;
f32 dy = x0.y_ - x1.y_;
return dx*dx + dy*dy;
}
void CCVT::generate(s32 N, s32 M, Sample2* samples)
{
//create a point set
Point* points = reinterpret_cast<Point*>(LRAY_MALLOC(sizeof(Point)*N*M));
Site* sites = reinterpret_cast<Site*>(LRAY_MALLOC(sizeof(Site) * N));
generateInitialSites(N, M, sites, points);
Criterion* h0 = reinterpret_cast<Criterion*>(LRAY_MALLOC(sizeof(Criterion)*M));
Criterion* h1 = reinterpret_cast<Criterion*>(LRAY_MALLOC(sizeof(Criterion)*M));
bool stable;
do{
stable = true;
for(s32 j = 1; j < N; ++j){
Site& site1 = sites[j];
Point* x1 = points + site1.top_;
for(s32 i = 0; i < j; ++i){
Site& site0 = sites[i];
Point* x0 = points + site0.top_;
for(s32 k = 0; k < M; ++k){
h0[k].index_ = k;
h0[k].value_ = sqrDistance(x0[k], site0.central_) - sqrDistance(x0[k], site1.central_);
h1[k].index_ = k;
h1[k].value_ = sqrDistance(x1[k], site1.central_) - sqrDistance(x1[k], site0.central_);
}
introsort(M, h0, [](const Criterion& x0, const Criterion& x1){return x0.value_<x1.value_;});
introsort(M, h1, [](const Criterion& x0, const Criterion& x1){return x0.value_<x1.value_;});
s32 m = M-1;
while(0<=m && 0.0f<(h0[m].value_ + h1[m].value_)){
s32 k = h0[m].index_;
s32 l = h1[m].index_;
swap(x0[k], x1[l]);
--m;
stable = false;
}
if(!stable){
site0.central_ = updateCenter(i, M, points);
site1.central_ = updateCenter(j, M, points);
}
}
}
} while(!stable);
for(s32 i=0; i<N; ++i){
samples[i] = sites[i].central_;
}
LRAY_FREE(h1);
LRAY_FREE(h0);
LRAY_FREE(points);
LRAY_FREE(sites);
}
void CCVT::generateInitialSites(s32 N, s32 M, Site* sites, Point* points)
{
s32 top = 0;
for(s32 i=0; i<N; ++i){
sites[i].top_ = top;
Point* s = points + top;
for(s32 j=0; j<M; ++j){
s[j].x_ = rand();
s[j].y_ = rand();
}
sites[i].central_ = updateCenter(i, M, points);
top += M;
}
}
Sample2 CCVT::updateCenter(s32 n, s32 M, Point* points)
{
s32 top = n * M;
Point* s = points + top;
Sample2 total = {};
for(s32 i = 0; i < M; ++i){
total.x_ += s[i].x_;
total.y_ += s[i].y_;
}
f32 inv = 1.0f/M;
Sample2 center = {total.x_*inv, total.y_*inv};
return center;
}
namespace
{
class BitArray
{
public:
static const s32 Max = 1024;
BitArray();
~BitArray();
void clear();
bool get(s32 index) const;
void set(s32 index);
void reset(s32 index);
private:
u32 bits_[32];
};
BitArray::BitArray()
:bits_{}
{}
BitArray::~BitArray()
{}
void BitArray::clear()
{
memset(bits_, 0, sizeof(u32)*32);
}
bool BitArray::get(s32 index) const
{
LRAY_ASSERT(0<=index && index<Max);
s32 n = index>>5;
s32 m = index - (n<<5);
return (bits_[n] & (0x01U<<m)) == m;
}
void BitArray::set(s32 index)
{
LRAY_ASSERT(0<=index && index<Max);
s32 n = index>>5;
s32 m = index - (n<<5);
bits_[n] &= ~(0x01U<<m);
}
void BitArray::reset(s32 index)
{
LRAY_ASSERT(0<=index && index<Max);
s32 n = index>>5;
s32 m = index - (n<<5);
bits_[n] |= (0x01U<<m);
}
class StratifiedTree
{
public:
static const s32 MaxBitCount = 10;
struct Node
{
//BitArray occupied_;
bool occupied_;
};
StratifiedTree(s32 bitCount);
~StratifiedTree();
void add(f32 x);
bool getValidOffsets(Sample2& offset, s32 x, s32 y, const Sample2& sample);
private:
StratifiedTree(const StratifiedTree&) = delete;
StratifiedTree(StratifiedTree&&) = delete;
StratifiedTree& operator=(const StratifiedTree&) = delete;
StratifiedTree& operator=(StratifiedTree&&) = delete;
void add(s32 node, f32 x, s32 nx);
s32 bitCount_;
s32 numNodes_;
s32 leavesStart_;
Node* nodes_;
};
StratifiedTree::StratifiedTree(s32 bitCount)
:bitCount_(bitCount)
,numNodes_(0)
,leavesStart_(0)
,nodes_(LRAY_NULL)
{
LRAY_ASSERT(0<bitCount_ && bitCount_<=MaxBitCount);
s32 start=(bitCount_>>1);
for(s32 i=start; i<bitCount_; ++i){
numNodes_ += 0x01U<<(i-start);
}
leavesStart_ = numNodes_;
numNodes_ += 0x01U<<(bitCount_-start);
size_t size = numNodes_ * sizeof(Node);
nodes_ = LRAY_MALLOC_TYPE(Node, size);
memset(nodes_, 0, size);
}
StratifiedTree::~StratifiedTree()
{
LRAY_FREE(nodes_);
}
void StratifiedTree::add(f32 x)
{
s32 xbits = (bitCount_ >> 1);
s32 wx = 0x01<<xbits;
x = wx * x;
s32 nx = static_cast<s32>(x);
add(0, x, nx);
}
void StratifiedTree::add(s32 node, f32 x, s32 nx)
{
if(leavesStart_<=node){
if(static_cast<s32>(x) == nx){
nodes_[node].occupied_ = true;
}
}else{
s32 left = (node+1)<<1;
s32 right = left + 1;
add(left, 2*x, 2*nx);
add(right, 2*x+1, 2*nx);
nodes_[node].occupied_ = nodes_[left].occupied_ || nodes_[right].occupied_;
}
}
}
#endif
//---------------------------------------------------------
//---
//---------------------------------------------------------
f32 radicalInverseVanDerCorput(u32 index)
{
index = bitreverse(index);
return static_cast<f32>(index) / static_cast<f32>(0x100000000L);
}
}
| true |
f707383000a1b8e9828ad976f7044169f7dcd92c | C++ | Night-Voyager/A-Calculator-for-Linear-Algebra | /functions/transpose/transpose.cpp | UTF-8 | 560 | 2.84375 | 3 | [] | no_license | #ifndef TRANSPOSE
#define TRANSPOSE
#include "../matrixio/matrixio.h"
float **transpose(float **);
#ifndef MAIN_FUNTION
void main()
{
putmatrix( transpose( getmatrix() ) );
}
#endif
float **transpose(float **A)
{
float **B;
int m, n, i, j;
m = (int)A[0][0];
n = (int)A[0][1];
B = (float **)malloc( (n+1)*sizeof(float) );
for (i=0; i<=n; i++)
{
B[i] = (float *)malloc( (m+1)*sizeof(float) );
}
B[0][0] = (float)n;
B[0][1] = (float)m;
for (i=1; i<=n; i++)
{
for (j=1; j<=m; j++)
{
B[i][j] = A[j][i];
}
}
return (B);
}
#endif | true |
b20e72bdc369e5f1cd9723e4e5a65e09165d31bd | C++ | huangjiahua/cppLearningFiles | /9_23.cpp | UTF-8 | 695 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
using namespace std;
int main()
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
vector<int> vi(ia, end(ia));
list<int> li(vi.begin(), vi.end());
auto il = li.begin();
while (il != li.end()) {
if (*il % 2)
il = li.erase(il);
else
++il;
}
auto iv = vi.begin();
while (iv != vi.end()) {
if (!(*iv % 2))
iv = vi.erase(iv);
else
++iv;
}
for (const auto &i : li)
cout << i << " " << flush;
cout << endl;
for (const auto &i : vi)
cout << i << " " << flush;
cout << endl;
return 0;
}
| true |
cbb3e2d12d3285f6b079a6f9bf35e942a5371419 | C++ | KeiHasegawa/ISO_IEC_14882 | /10_Derived_classes/2_Member_name_lookup/2_error/test002.cpp | UTF-8 | 797 | 3.625 | 4 | [] | no_license | /*
* When virtual base classes are used, a hidden declaration can be reached
* along a path through the sub-object lattice that does not pass through the
* hiding declaration. This is not an ambiguity. The identical use with
* nonvirtual base classes is an ambiguity; in that case there is no unique
* instance of the name that hides all the others.
*/
class V { public: int f(); int x; };
class W { public: int g(); int y; };
class B : public virtual V, public W
{
public:
int f(); int x;
int g(); int y;
};
class C : public virtual V, public W { };
class D : public B, public C { void glorp(); };
void D::glorp()
{
x++; //OK: B::x hides V::x
f(); //OK: B::f() hides V::f()
y++; //error: B::y and C's W::y
g(); //error: B::g() and C's W::g()
}
| true |
fb364a62aab1745481a7fac01b9d9f051b9a03f9 | C++ | kokakola1994/VSStudent | /source/repos/Laborka 3/Laborka 3/Ulamek.h | UTF-8 | 1,593 | 2.671875 | 3 | [] | no_license | #pragma once
#include <iostream>
# pragma one
using namespace std;
class Ulamek
{
int licz, mian;
void reduce();
public:
Ulamek();
Ulamek(int, int);
void print() const;
int getLicz() const {
return licz;
}
int getMian() const {
return mian;
}
void setLicz(int a) {
licz = a;
}
void setMian(int b) {
if (b == 0) b = 1;
mian = b;
}
friend Ulamek Dodaj(const Ulamek&, const Ulamek&);
friend Ulamek operator+(const Ulamek&, const Ulamek&);
friend Ulamek operator-(const Ulamek&, const Ulamek&);
friend Ulamek operator*(const Ulamek&, const Ulamek&);
friend Ulamek operator/(const Ulamek&, const Ulamek&);
Ulamek& Dodaj(const Ulamek&);
Ulamek& operator+=(const Ulamek&);
Ulamek& operator-=(const Ulamek&);
Ulamek& operator*=(const Ulamek&);
Ulamek& operator/=(const Ulamek&);
friend std::ostream& operator << (std::ostream & stream, const Ulamek & b);
friend std::istream& operator >> (std::istream & stream, Ulamek & b);
Ulamek operator-() const;
Ulamek& operator++ (void);
Ulamek& operator++ (int);
Ulamek& operator-- (void);
Ulamek& operator-- (int);
friend bool operator == (const Ulamek & f, const Ulamek & t);
friend bool operator != (const Ulamek & f, const Ulamek & t);
friend bool operator <= (const Ulamek & f, const Ulamek & t);
friend bool operator > (const Ulamek & f, const Ulamek & t);
friend bool operator >= (const Ulamek & f, const Ulamek & t);
friend bool operator < (const Ulamek & f, const Ulamek & t);
explicit operator double() { return (double)licz / mian; }
explicit operator int() { return licz / mian; }
~Ulamek();
};
| true |
49f34409eae533c0ab3e2855888219a836ff982a | C++ | robot-head/Party-Scarf | /party_scarf-button_board/dot_beat.ino | UTF-8 | 815 | 2.984375 | 3 | [] | no_license | // Define variables used by the sequences.
int thisdelay = 10; // A delay value for the sequence(s)
uint8_t count = 0; // Count up to 255 and then reverts to 0
uint8_t fadeval = 20;
void dot_beat() {
uint8_t inner = beatsin8(bpmAvg/4, NUM_LEDS/4, NUM_LEDS/4*3);
uint8_t outer = beatsin8(bpmAvg/4, 0, NUM_LEDS-1);
uint8_t middle = beatsin8(bpmAvg/4, NUM_LEDS/3, NUM_LEDS/3*2);
leds[middle] = CRGB::Purple;
leds[inner] = CRGB::Blue;
leds[outer] = CRGB::Aqua;
//nscale8(leds,NUM_LEDS,fadeval); // Fade the entire array. Or for just a few LED's, use nscale8(&leds[2], 5, fadeval);
fadeToBlackBy(leds, NUM_LEDS, 16); // 8 bit, 1 = slow, 255 = fast
} // dot_beat() | true |
e8c4c42d8b225f1f3a7352674085231564e8e692 | C++ | filimonov/ClickHouse | /dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.h | UTF-8 | 2,472 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Common/typeid_cast.h>
#include <Interpreters/Context.h>
#include <Parsers/DumpASTNode.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/ASTFunction.h>
namespace DB
{
/// Visitors consist of functions with unified interface 'void visit(Casted & x, ASTPtr & y)', there x is y, successfully casted to Casted.
/// Both types and fuction could have const specifiers. The second argument is used by visitor to replaces AST node (y) if needed.
/** Replace subqueries that return exactly one row
* ("scalar" subqueries) to the corresponding constants.
*
* If the subquery returns more than one column, it is replaced by a tuple of constants.
*
* Features
*
* A replacement occurs during query analysis, and not during the main runtime.
* This means that the progress indicator will not work during the execution of these requests,
* and also such queries can not be aborted.
*
* But the query result can be used for the index in the table.
*
* Scalar subqueries are executed on the request-initializer server.
* The request is sent to remote servers with already substituted constants.
*/
class ExecuteScalarSubqueriesVisitor
{
public:
ExecuteScalarSubqueriesVisitor(const Context & context_, size_t subquery_depth_, std::ostream * ostr_ = nullptr)
: context(context_),
subquery_depth(subquery_depth_),
visit_depth(0),
ostr(ostr_)
{}
void visit(ASTPtr & ast) const
{
if (!tryVisit<ASTSubquery>(ast) &&
!tryVisit<ASTTableExpression>(ast) &&
!tryVisit<ASTFunction>(ast))
visitChildren(ast);
}
private:
const Context & context;
size_t subquery_depth;
mutable size_t visit_depth;
std::ostream * ostr;
void visit(const ASTSubquery & subquery, ASTPtr & ast) const;
void visit(const ASTFunction & func, ASTPtr & ast) const;
void visit(const ASTTableExpression &, ASTPtr &) const;
void visitChildren(ASTPtr & ast) const
{
for (auto & child : ast->children)
visit(child);
}
template <typename T>
bool tryVisit(ASTPtr & ast) const
{
if (const T * t = typeid_cast<const T *>(ast.get()))
{
DumpASTNode dump(*ast, ostr, visit_depth, "executeScalarSubqueries");
visit(*t, ast);
return true;
}
return false;
}
};
}
| true |
ca9ac62e1b0b373390091e241292767f2264edbf | C++ | Jochen0x90h/LedControl | /Emulator/Widget.h | UTF-8 | 877 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <glad/glad.h>
#include "types.h"
class Widget {
public:
// bounding box
float x1;
float y1;
float x2;
float y2;
Widget(const char *fragmentShaderSource);
virtual ~Widget();
///
/// check if widget contains the given point
bool contains(float x, float y);
///
/// called when the widget is "touched" at given position (mouse is pressed/dragged)
virtual void touch(float x, float y);
///
/// draw component
virtual void draw();
protected:
void setTextureIndex(char const * name, int index);
// derived classes can set additional opengl state
virtual void setState();
// derived classes can reset additional opengl state
virtual void resetState();
static GLuint createShader(GLenum type, const char* code);
GLuint program;
GLuint scaleLocation;
GLuint offsetLocation;
GLuint vertexBuffer;
GLuint vertexArray;
};
| true |
b08106e12b8008d471f704810c69815ad17a31f1 | C++ | Liuhao-bupt/my-leetcode | /my_107_Binary Tree Level Order Traversal II.cpp | UTF-8 | 1,404 | 3.21875 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if(!root)
return {};
vector<vector<int>> result = {};
vector<int> cur = {};
queue<TreeNode *> nodequeue;
nodequeue.push(root);
TreeNode *p, *q;
TreeNode *last = root;
while(!nodequeue.empty()){
p=nodequeue.front();
nodequeue.pop();
cur.push_back(p->val);
if(p == last){
result.push_back(cur);
cur = {};
if(p->left){
nodequeue.push(p->left);
last = p->left;}
if(p->right){
nodequeue.push(p->right);
last = p->right;}
if(!p->left && !p->right)
last = q;
}
else
{
if(p->left){
nodequeue.push(p->left);
q = p->left;}
if(p->right){
nodequeue.push(p->right);
q = p->right;}
}
}
vector<int>::size_type index;
for (index = 0; index != result.size() / 2; ++index) {
auto temp = result[index];
result[index] = result[result.size()-1-index];
result[result.size() - 1 - index] = temp;
}
return result;
}
};
| true |
3a3e3d5eb1aa8b8d858f86f68a4a0b4ce1a4872d | C++ | SamirAroudj/BaseProject | /Graphics/Camera3D.h | UTF-8 | 7,836 | 3.015625 | 3 | [
"BSD-3-Clause",
"MIT",
"Zlib",
"Libpng",
"X11"
] | permissive | /*
* Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#ifndef _CAMERA_3D_H_
#define _CAMERA_3D_H_
#include "Graphics/BaseCamera3D.h"
namespace Graphics
{
/// This virtual camera representation is designed for view and projection matrix computation.
/** Represents a virtual camera to easily manage view and projection transformation matrices. */
class Camera3D : public BaseCamera3D
{
public:
/** Returns the currently active camera or NULL if there is none.
@return Returns the camera that is currently active or NULL if none is currently set. */
static Camera3D *getActiveCamera();
public:
/** Initializes the camera to be at world origin and its projection matrix with the entered values.
@param fovY This is the vertical opening angle of the camera view frustum along its y-Axis in radians. Must be positive.
@param aspectRatio This is the ratio of width to height of the camera's image plane. Must be positive.
@param zNear Defines the distance between projection center (= camera origin) and beginning of the view frustum (= near view frustum or clipping plane) in floating point units.
Must be positive as it is interpreted as absolute value.
Everything in front of zNear plane (lower absolute value) is not visible by this camera.
@param zFar Defines the distance between projection center (= camera origin) and the end of the view frustum (= far view frustum or clipping plane) in floating point units.
Must be positive since it is interpreted as absolute value..
Everything behind zFar plane (larger absolute value) is not visible by this camera. */
Camera3D(Real fovY, Real aspectRatio, Real zNear, Real zFar);
/** Destroys the camera. */
virtual ~Camera3D();
/** Computes and returns a matrix P^-1 that
maps normalized homogenous device coordinates (x, y, z) with z = 1 (after viewport transformation - not in pixels) to non-normalized view space camera ray directions.
@return Computes and returns a matrix P^-1 that maps normalized homogenous device coordinates (x, y, z) with z = 1 to non-normalized view space camera ray directions. */
virtual Math::Matrix3x3 computeInverseProjectionMatrix() const;
/** Computes a matrix that converts a homogenous pixel position (px, py, z = 1) \in ([0, viewport width], [0, viewport height], 1) to a
non-normalized ray direction in world space coordinates.
@param viewportSize Set this to the viewport width and height in pixels (number of pixels in a row and column).
@param addPixelCenterOffset If this is set to true then integer pixel coordinates refer to pixel centers since an offset of half a pixel is added to the coordinates.
If the parameter is set to false then rays for the upper left pixel corner are returned.
@return Returns a matrix M which converts homogeneours (3D) pixel coordinates to non-normalized ray directions (||rayDir|| is not necessarily 1) posHPS * M = rayDirWS. */
virtual Math::Matrix3x3 computeHPSToNNRayDirWS(const Utilities::ImgSize &viewportSize, const bool addPixelCenterOffset = true) const;
/** Computes and returns the matrix which transforms coordinates relative to the world space coordinate system into the pixel coordinate system of this camera for some resolution.
The pixel coordinates are not normalized! You must perform the perspective division after the matrix has been applied.
@param viewportSize Set this to the viewport width and height in pixels (number of pixels in a row and column).
@param considerPixelCenterOffset Set this to true if you want to get coordinates refering to pixel centers instead of lower left corners.
E.g., a point at the lower left camera frustum edge is mapped to the pixel coordinates (0.5, 0.5) if this is set to true (instead of (0, 0)).
@return Returns a matrix which transforms world space coordiantes into non normalized pixel coordinates relative to the camera's viewport of resolution imageSize.*/
virtual Math::Matrix4x4 computeWorldSpaceToPixelSpaceMatrix(const Utilities::ImgSize &viewportSize, const bool considerPixelCenterOffset = true) const;
/** Returns the absolute distance (w.r.t the camera center) of the far clipping plane used for the projection matrix of the camera.
@param Returns the absolute distance (w.r.t the camera center) of the far clipping plane used for the projection matrix of the camera.*/
inline Real getFarClippingPlane() const;
/** Returns the angular extent of this View object along the y-axis. (field of view w.r.t. to the cameras up axis).
@return Returns the angular extent of this View object along the y-axis. (field of view w.r.t. to the cameras up axis). */
inline Real getFoVY() const;
/** Returns the absolute distance (w.r.t the camera center) of the near clipping plane used for the projection matrix of the camera.
@param Returns the absolute distance (w.r.t the camera center) of the near clipping plane used for the projection matrix of the camera.*/
inline Real getNearClippingPlane() const;
/** This camera becomes the active camera so that it can be obtained by getActiveCamera(). */
inline void setAsActiveCamera();
/** Set camera's image plane aspect ratio, aspect ratio = width / height.
@param aspectRatio This is the ratio of width to height of the camera image plane. Must be positive.*/
virtual void setAspectRatio(const Real aspectRatio);
/** Recomputes the camera projection matrix according to the entered data
@param fovY This is the vertical opening angle of the camera view frustum along its y - Axis in radians.Must be positive.
@param aspectRatio This is the ratio of width to height of the camera's image plane. Must be positive.
@param zNear Defines the distance between projection center(= camera origin) and beginning of the view frustum(= near view frustum or clipping plane) in floating point units.
Must be positive.
Everything in front of zNear plane is not visible by this camera.
@param zFar Defines the distance between projection center(= camera origin) and the end of the view frustum(= far view frustum or clipping plane) in floating point units.
Must be positive.
Everything behind zFar plane is not visible by this camera.*/
void setProjectionProperties(Real fovY, Real aspectRatio, Real zNear, Real zFar);
private:
static Camera3D *msActiveCamera; /// points to the currently active camera or is set to NULL
private:
Real mFoVY; /// vertical opening angle of the camera view frustum along its y-Axis in radians
Real mZFar; /// absolute distance between projection center (= camera origin) and the end of the view frustum (= far view frustum or clipping plane) in floating point units
Real mZNear; /// absolute distance between projection center (= camera origin) and beginning of the view frustum (= near view frustum or clipping plane) in floating point units
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// inline function definitions ////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline Camera3D *Camera3D::getActiveCamera()
{
return msActiveCamera;
}
inline Real Camera3D::getFarClippingPlane() const
{
return mZFar;
}
inline Real Camera3D::getFoVY() const
{
return mFoVY;
}
inline Real Camera3D::getNearClippingPlane() const
{
return mZNear;
}
inline void Camera3D::setAsActiveCamera()
{
msActiveCamera = this;
}
}
#endif // _CAMERA_3D_H_
| true |
ff5149c9b532ffbb4718fda092a569b885a60456 | C++ | tiannian/DNSet | /src/utils.h | UTF-8 | 532 | 3.015625 | 3 | [] | no_license | #ifndef _UTILS_H
#define _UTILS_H
#include <string>
#include <sstream>
#include <vector>
std::string& trim(std::string &s) {
if (s.empty()) {
return s;
}
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
std::vector<std::string> split(const std::string& s,const char flag = ' ') {
std::vector<std::string> sv;
std::istringstream iss(s);
std::string temp;
while (getline(iss, temp, flag)) {
sv.push_back(temp);
}
return sv;
}
#endif | true |
4abc1d202ef228b780c746a7ef66a353206c1553 | C++ | Z-maple/CodeInterviewGuide | /CH7 Bit Operations/7.5/main.cc | UTF-8 | 965 | 3.734375 | 4 | [] | no_license | ///整数的二进制表达中有多少个1
#include <assert.h>
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
///输入数组中有一个只出现过一次的数
///其余都出现过两次
///返回出现过两次的数
int func(vector<int> &input){
int ret = 0;
for(int i = 0; i < input.size(); ++i){
ret ^= input[i];
}
return ret;
}
///输入数组中有两个只出现过一次的数
///其余都出现过两侧
///输出出现过一次的两个数
void func2(vector<int> &input){
int ret = 0, ret1 = 0;
for(int i = 0; i < input.size(); ++i){
ret ^= input[i];
}
int rightMost = ret & (~ret + 1);
for(int i = 0; i < input.size(); ++i){
if(rightMost & input[i]){
ret1 ^= input[i];
}
}
cout<<ret1<<" "<<(ret1 ^ ret)<<endl;
}
int main(){
vector<int> input({1, 2, 3, 4, 5, 3, 4, 5});
func2(input);
//cout<<ret<<endl;
} | true |
94fbc2454dfa9c536d61cf95886d4dd931c20185 | C++ | davidklaftenegger/qd_library | /queues/entry_queue.hpp | UTF-8 | 3,865 | 3.359375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef qd_entry_queue_hpp
#define qd_entry_queue_hpp qd_entry_queue_hpp
#include<algorithm>
#include<array>
#include<atomic>
#include<iostream>
#include<typeinfo>
/**
* @brief a buffer-based tantrum queue with fixed-size entries
* @tparam ENTRIES the number of entries
*/
template<long ENTRIES, int BUFFER_SIZE>
class entry_queue {
/** type for the size field for queue entries, loads must not be optimized away in flush */
typedef std::atomic<long> sizetype;
/** type for function pointers to be stored in this queue */
typedef void(*ftype)(char*);
struct entry_t {
std::atomic<ftype> fun;
char buf[BUFFER_SIZE];
};
void forwardall(long, long) {};
template<typename P, typename... Ts>
void forwardall(long idx, long offset, P&& p, Ts&&... ts) {
auto ptr = reinterpret_cast<P*>(&entry_array[idx].buf[offset]);
new (ptr) P(std::forward<P>(p));
forwardall(idx, offset+sizeof(p), std::forward<Ts>(ts)...);
}
public:
/** constants for current state of the queue */
enum class status : long { OPEN=0, SUCCESS=0, FULL, CLOSED };
entry_queue() : counter(ENTRIES), closed(status::CLOSED) {}
/** opens the queue */
void open() {
counter.store(0, std::memory_order_relaxed);
closed.store(status::OPEN, std::memory_order_relaxed);
}
/**
* @brief enqueues an entry
* @tparam P return type of associated function
* @param op wrapper function for associated function
* @return SUCCESS on successful storing in queue, FULL if the queue is full and CLOSED if the queue is closed explicitly
*/
template<typename... Ps>
status enqueue(void (*op)(char*), Ps*... ps) {
auto current_status = closed.load(std::memory_order_relaxed);
if(current_status != status::OPEN) {
return current_status;
}
/* entry size = size of size + size of wrapper functor + size of promise + size of all parameters*/
constexpr long size = sumsizes<Ps...>::size;
/* get memory in buffer */
long index = counter.fetch_add(1, std::memory_order_relaxed);
if(index < ENTRIES) {
static_assert(size <= BUFFER_SIZE, "entry_queue buffer per entry too small.");
/* entry available: move op, p and parameters to buffer, then set size of entry */
forwardall(index, 0, std::move(*ps)...);
entry_array[index].fun.store(op, std::memory_order_release);
return status::SUCCESS;
} else {
return status::FULL;
}
}
/** execute all stored operations, leave queue in closed state */
void flush() {
long todo = 0;
bool open = true;
while(open) {
long done = todo;
todo = counter.load(std::memory_order_relaxed);
if(todo == done) { /* close queue */
todo = counter.exchange(ENTRIES, std::memory_order_relaxed);
closed.store(status::CLOSED, std::memory_order_relaxed);
open = false;
}
if(todo >= static_cast<long>(ENTRIES)) { /* queue closed */
todo = ENTRIES;
closed.store(status::CLOSED, std::memory_order_relaxed);
open = false;
}
for(long index = done; index < todo; index++) {
/* synchronization on entry size field: 0 until entry available */
ftype fun = nullptr;
do {
fun = entry_array[index].fun.load(std::memory_order_acquire);
} while(!fun);
/* call functor with pointer to promise (of unknown type) */
fun(&entry_array[index].buf[0]);
/* cleanup: call destructor of (now empty) functor and clear buffer area */
// fun->~ftype();
entry_array[index].fun.store(nullptr, std::memory_order_relaxed);
}
}
}
private:
/** counter for how many entries are already in use */
std::atomic<long> counter;
char pad[128];
/** optimization flag: no writes when queue in known-closed state */
std::atomic<status> closed;
char pad2[128];
/** the buffer for entries to this queue */
std::array<entry_t, ENTRIES> entry_array;
};
#endif /* qd_buffer_queue_hpp */
| true |
a2ab43626a710c6871e57e96a840ab8153e70582 | C++ | danielmoraes/prog-contests | /codility/src/passing_cars/answer.cc | UTF-8 | 674 | 3.8125 | 4 | [
"MIT"
] | permissive | /*
* Codility - Count the number of passing cars on the road.
*
* Lesson: 5 (PrefixSums)
* Problem code: PassingCars
*/
#include <vector>
#include <iostream>
using namespace std;
// @include
const int LIMIT = 1000000000;
int passing_cars(vector<int> &A) {
int ones_so_far = 0, passing_cars = 0;
for (int i = A.size() - 1; i >= 0; --i) {
if (A[i] == 1) {
ones_so_far++;
} else {
passing_cars += ones_so_far;
if (passing_cars > LIMIT) {
return -1;
}
}
}
return passing_cars;
}
// @exclude
int main(int argc, char* argv[]) {
vector<int> cars = {0, 1, 0, 1, 1};
cout << passing_cars(cars) << endl;
return 0;
}
| true |
2941cd92c9559e7630013f2d557bcc58d1b11378 | C++ | 15529343201/C-Data-Structure | /数据结构-王道/第2章 线性表/2.3-9.cpp | GB18030 | 2,509 | 4.03125 | 4 | [] | no_license | /*һͷĵ,headΪͷָ,ĽṹΪ(data,next),dataΪԪ,nextΪָ
д㷨:иԪ,ͷŽռĴ洢ռ(Ҫ:ʹ
Ϊռ)*/
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{ //嵥
ElemType data; //
struct LNode *next; //ָ
}LNode,*LinkList;
void print(LinkList L){
while(L->next){
printf("%d ",L->next->data);
L=L->next;
}
}
//β巨
LinkList CreatList2(LinkList &L){
//ӱͷβL,ÿξڱβԪ
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s,*r=L; //rΪβָ
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s; //rָµıβ
scanf("%d",&x);
}
r->next=NULL; //βָÿ
return L;
}
/*㷨˼:б,ÿ˱вҳСֵԪ,ͷŽ
ռռ;ٲҴСֵԪ,ͷſռ,ȥ,ֱΪ,ͷͷ
ռ洢ռ,㷨ʱ临ӶΪO(n^2)*/
void Min_Delete(LinkList &head){
//headǴͷĵͷָ,㷨˳еԪ
LinkList pre,u,p;
while(head->next!=NULL){ //ѭʣͷ
pre=head; //preΪԪСֵǰָ
p=pre->next; //pΪָ
while(p->next!=NULL){
if(p->next->data<pre->next->data){
pre=p; //סǰСֵǰ
}
p=p->next;
}
/*
ͷ 1 2 3 4 5
pre p
ͷ 1 2 3 4 5
p
*/
/*
ͷ 5 4 3 2 1
pre p
pre p
pre p
pre p
pre p
*/
printf("%d",pre->next->data); //ԪСֵ
u=pre->next; //ɾԪֵСĽ,ͷŽռ
pre->next=u->next;
free(u);
}
free(head); //ͷͷ
}
int main(void){
int min,max;
LinkList l,q;
l=CreatList2(q);
printf("еԪ:\n");
print(l);
printf("\n");
Min_Delete(l);
return 0;
}
/*
1 2 3 4 5 9999
еԪ:
1 2 3 4 5
12345
5 4 3 2 1 9999
еԪ:
5 4 3 2 1
12345
*/
| true |
3f182759b626913976b677a41efaddf877b43075 | C++ | andrew-pa/bicycle | /src/tokenizer.cpp | UTF-8 | 2,831 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "token.h"
#include <istream>
token tokenizer::next_in_stream() {
if (!_in) return token(token::eof, 0);
auto ch = _in->get();
if (ch < 0)
return token(token::eof, 0);
while (isspace(ch)) {
if (ch == '\n') line_number++;
ch = _in->get();
if (ch < 0)
return token(token::eof, 0);
}
switch (ch) {
case '{': return token(symbol_type::open_brace);
case '}': return token(symbol_type::close_brace);
case '(': return token(symbol_type::open_paren);
case ')': return token(symbol_type::close_paren);
case '[': return token(symbol_type::open_sq);
case ']': return token(symbol_type::close_sq);
case ':':
if (_in->peek() == ':') {
_in->get();
return token(symbol_type::double_colon);
}
return token(symbol_type::colon);
case ';': return token(symbol_type::semicolon);
case ',': return token(symbol_type::comma);
case '$': return token(symbol_type::dollar);
case '=': if (_in->peek() == '>') {
_in->get();
return token(symbol_type::thick_arrow);
}
}
if (isdigit(ch) || (ch == '-' && isdigit(_in->peek()))) {
int sign = 1;
if (ch == '-') {
ch = _in->get();
sign = -1;
}
intptr_t value = ch - '0';
while (_in && isdigit(_in->peek())) {
value = value * 10 + (_in->get() - '0');
}
return token(token::number, value*sign);
}
else if (ch == '"') {
std::string str;
while (_in && _in->peek() != '"') {
ch = _in->get();
if (ch == '\\') {
auto nch = _in->get();
if (nch < 0) break;
else if (nch == '\\') ch = '\\';
else if (nch == 'n') ch = '\n';
else if (nch == 't') ch = '\t';
else if (nch == '"') ch = '"';
str += ch;
}
else if (ch > 0) str += ch;
else break;
}
_in->get();
auto id = string_literals.size();
string_literals.push_back(str);
return token(token::str, id);
}
else if (!isalnum(ch) && ch != '_') {
std::string op;
op += ch;
while (_in && !isalnum(_in->peek()) && !isspace(_in->peek()) && _in->peek() != ';') {
ch = _in->get();
if (ch > 0) op += ch;
else break;
}
auto opt = operators.find(op);
if (opt != operators.end()) {
return token(opt->second);
}
else {
throw std::runtime_error("unknown operator " + op);
}
}
else {
std::string id;
id += ch;
while (_in && (isalnum(_in->peek()) || _in->peek() == '_')) {
ch = _in->get();
if (ch > 0) id += ch;
else break;
}
auto kwd = keywords.find(id);
if (kwd != keywords.end()) {
return token(token::keyword, (size_t)kwd->second);
}
else {
auto idc = std::find(this->identifiers.begin(), this->identifiers.end(), id);
size_t index;
if (idc != this->identifiers.end()) {
index = std::distance(this->identifiers.begin(), idc);
}
else {
index = this->identifiers.size();
this->identifiers.push_back(id);
}
return token(token::identifer, index);
}
}
} | true |
56c03872009865f5dbea2e3f6e787f116740fb7d | C++ | vkacharaya/SourceCodeRepository | /Repository/NoSqlDb-Bkp/NoSqlDb/CheckOut/CheckOut.cpp | WINDOWS-1252 | 3,871 | 2.671875 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////////////
// CheckOut.cpp - retrieves package files, removing version information from //
// their filenames. Retrieved files will be copied to a //
// specified directory. //
// ver 1.0 //
// ----------------------------------------------------------------------- //
// copyright Vishnu Karthik Ravindran, 2018 //
// All rights granted provided that this notice is retained //
// ----------------------------------------------------------------------- //
// Language: Visual C++, Visual Studio 2010 //
// Platform: HP Laptop , Core i5, Windows 10 //
// Application: Course Projects, 2018 //
// Author: Vishnu Karthik Ravindran, Syracuse University //
// //
/////////////////////////////////////////////////////////////////////////////
/*
* Module Operations:
* ==================
* This module provides class, CheckOut
*
* The CheckOut class supports retrieves package files, removing version information
* from their filenames. Retrieved files will be copied to a specified directory.
*
* Required Files:
* ===============
* CheckOut.h, CheckOut.cpp, Versioning.h, Versioning.cpp, FileSystemDemo.h
* FileNameParser.h,Graph.h
*
* Maintenance History:
* ====================
* ver 1.0 : 10 Mar 2018
* Initial Implementation
*/
#include "CheckOut.h"
using namespace GraphProcessing;
namespace LocalSVN
{
/////////////////////////////////////////////////////////
// Function used to get the latest version files
void CheckOut::getLatestVersionFile(const std::string & fileKey, const std::string & namespaceKey, const bool & dependencyNeeded)
{
std::string latestVersion = _vs.getCurrentKeyVersion(namespaceKey + "." + fileKey);
checkOutDependencyOp(latestVersion, dependencyNeeded);
}
/////////////////////////////////////////////////////////
// Function used to get the particular version files
void CheckOut::getParticularFile(const std::string & fileKey, const std::string & namespaceKey, const bool & dependencyNeeded)
{
std::string version = namespaceKey + "." + fileKey;
checkOutDependencyOp(version, dependencyNeeded);
}
////////////////////////////////////////////////////////
// Dependency file checkout
void CheckOut::checkOutDependencyOp(const std::string& latestVersion, const bool & dependencyNeeded)
{
std::vector<std::string> filePaths;
GraphUtils gh;
std::unordered_map<std::string, std::string > idMap;
if (dependencyNeeded)
{
gh.createGraph(_map, idMap);
auto proc = [&filePaths, this](Sptr pNode) {
filePaths.push_back(pNode->name());
};
using P = decltype(proc);
using V = std::string;
Sptr pNode = gh.getGraphInstance().find(latestVersion);
gh.getGraphInstance().walker(DFS_r_ltr<V, P>, pNode, proc);
}
else filePaths.push_back(latestVersion);
FileHandler fh;
for (auto fn : filePaths)
{
const std::string& sourceCodeFilePath = Path::getFullFileSpec(_map[fn].payLoad().getFilePath());
const std::string& localFilePath = ApplicationConstants::getLocalPath() + "/" + _vs.trimExtension(fh.trimNameSpace(fn));
fh.fileSave(sourceCodeFilePath, localFilePath);
}
}
}
#ifdef TEST_CHECKOUT
int main()
{
DbCore<PayLoad> db;
DbElement<PayLoad> elemdb;
elemdb.name("DbCore.h.0").payLoad().setFilePath("../DbCore/DbCore.h");
db.insert("DbCore.h.0", elemdb);
Query<PayLoad> query(db);
CheckOut ch(db);
ch.getLatestVersionFile("DbCore.h", "NoSqlDb", true);
std::cout << "Copies all dependencies";
ch.getLatestVersionFile("DbCore.h.0", "NoSqlDb", true);
std::cout << "Copies specific file";
}
#endif TEST_CHECKOUT
| true |
40a9f84e9748e470ad0c81eec70f77e5aded632a | C++ | mast1ren/mPracCodes | /C++/PAT乙级/1078 字符串压缩与解压.cpp | UTF-8 | 1,405 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
string title;
// 压缩
void zip()
{
getline(cin, title);
bool flag = false;
char x = title[0];
int num = 0;
// 循环判断
for (int i = 0; i < title.size(); ++i)
// 如果读取字符与选择字符相同 num++
if (title[i] == x)
{
num++;
flag = true; // 标为true
}
else
{
if (num > 1)
cout << num << x;
else
cout << x;
x = title[i];
num = 1;
flag = false;
}
// 如果结束循环时字符连续
if (flag)
if (num > 1)
cout << num << x;
else
cout << x;
else
cout << title[title.size() - 1];
cout << endl;
}
// 解压
void unzip()
{
getline(cin, title);
string n;
int cnt = 1;
for (int i = 0; i < title.size(); ++i)
// 判断是否是数字
if (isdigit(title[i]))
n += title[i];
else
{
if (n.size())
cnt = stoi(n);
while (cnt--)
cout << title[i];
n = "";
cnt = 1;
}
cout << endl;
}
int main()
{
char ch;
cin >> ch;
getchar();
if (ch == 'C')
zip();
else
unzip();
system("pause");
return 0;
} | true |
2103d5496737c56b698ca1820e92b8e4419dc3d5 | C++ | ivanmanan/Algorithms | /palindromePairs.cpp | UTF-8 | 1,227 | 3.5625 | 4 | [] | no_license | class Solution {
public:
bool isPalindrome(string s) {
for (int i = 0, j = s.length() - 1; i < j; j--, i++) {
if (s[j] != s[i]) {
return false;
}
}
return true;
}
// Time Complexity: O(N^2 * S)
// Space complexity: O(N) --> Every pair is a palindrome; O(2*N) but drop constant term
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> solution;
// Iterators named after indexing pair (first, second)
for (auto first = words.begin(); first != words.end(); first++) {
for (auto second = words.begin(); second != words.end(); second++) {
// Avoid doing identical indexes
if (first == second) {
continue;
}
string s = (*first) + (*second);
if (isPalindrome(s)) {
vector<int> pair;
pair.push_back(first - words.begin());
pair.push_back(second - words.begin());
solution.push_back(pair);
pair.clear();
}
}
}
return solution;
}
}; | true |
a73c0a1a963f325cb4475e11e86168a7f3511413 | C++ | Ravi3191/MLP | /src/read_csv.cpp | UTF-8 | 2,270 | 2.984375 | 3 | [] | no_license | #include "read_csv.h"
void Read_data::fill_col(){
std::string line,name;
std::ifstream file(_file_name);
if(file.is_open()){
std::getline(file, line);
std::replace(line.begin(), line.end(), ',', ' ');
std::istringstream linestream(line);
while(linestream >> name){
_col_names.push_back(name);
}
}
file.close();
}
void Read_data::fill_matrix(){
int col{0},iters{0};
std::string line;
std::ifstream file(_file_name);
double num;
if(file.is_open()){
while(std::getline(file, line)){
std::replace(line.begin(), line.end(), ',', ' ');
std::istringstream linestream(line);
if(iters > 0){
linestream >> num;
col = 0;
while(linestream>>num){
_data(iters-1,col) = num;
_mean[col] += num;
_variance[col] += num*num;
col++;
}
//std::cout << std::endl;
}
iters++;
}
}
file.close();
for(int i = 0; i <_n_cols; i++){
_mean[i]=_mean[i]/_n_rows;
}
for(int i = 0; i<_n_cols; i++){
_variance[i] = _variance[i]/_n_rows - _mean[i]*_mean[i];
}
std::cout << "Data has been read and processed for the " << _file_name << ". " << std::endl;
}
void Read_data::normalize(std::vector<double> mean,std::vector<double> variance){
for(int i = 0; i<_n_cols; i++){
Eigen::MatrixXd ones(_n_rows,1);
ones.fill(1.0);
_data.col(i) -= ones*mean[i];
_data.col(i) /= variance[i];
}
}
void Read_data::normalize(){
for(int i = 0; i<_n_cols; i++){
Eigen::MatrixXd ones(_n_rows,1);
ones.fill(1.0);
_data.col(i) -= ones*_mean[i];
_data.col(i) /= _variance[i];
}
}
Read_data::Read_data(const std::string name, const int rows, const int cols) : _file_name{name}, _n_rows{rows}, _n_cols{cols}, _mean(cols,0),_variance(cols,0){
_data.resize(_n_rows,_n_cols);
Read_data::fill_col();
Read_data::fill_matrix();
}
Eigen::MatrixXd Read_data::get_data(){
return _data;
}
std::vector<std::string> Read_data::get_names(){
return _col_names;
} | true |
c5a8ec972d9d901c129ab4aad1273be7e03eef12 | C++ | irtefa/algo | /topcoder/srm577/two/EllysNewNickname.cc | UTF-8 | 566 | 3.109375 | 3 | [] | no_license | #include <string>
using namespace std;
class EllysNewNickname {
public:
int getLength(string);
};
int EllysNewNickname::getLength(string nickname) {
int ans = 0;
bool flag = 0;
for (int i=0; i < nickname.size(); i++) {
if (nickname[i] == 'a' || nickname[i]=='e' || nickname[i]=='i' || nickname[i] == 'o' || nickname[i] == 'u' || nickname[i] == 'y') {
if (flag==0) {
ans++;
}
flag = 1;
} else {
flag = 0;
ans++;
}
}
return ans;
}
| true |
a05884768651ef648e585d26b72bd0a0925784da | C++ | yuex1994/iw_imdb | /uncores/Piton-pmesh/src/pmesh_util.cc | UTF-8 | 1,257 | 2.625 | 3 | [
"MIT"
] | permissive | /// \file Utility function for constructing the AES model
/// Hongce Zhang (hongcez@princeton.edu)
#include "pmesh_l15_ila.h"
#include <cmath>
#include <string>
ExprRef PMESH_L15::unknown_range(unsigned low, unsigned high) {
unsigned width = (unsigned)std::ceil(std::log2(high + 1));
auto val = unknown(width)();
model.AddInit((val >= low) & (val <= high));
return val;
}
ExprRef PMESH_L15::unknown_choice(const ExprRef& a, const ExprRef& b) {
return Ite(unknown(1)() == 1, a, b);
}
ExprRef PMESH_L15::lConcat(const std::vector<ExprRef> & l) {
assert(l.size() >= 1);
auto ret = l[0];
for(auto beg = l.begin()+1; beg != l.end(); ++ beg )
ret = Concat(ret, *beg);
return ret;
}
/// build a map relation
ExprRef PMESH_L15::Map(const std::string & name, unsigned retLen, const ExprRef & val) {
return FuncRef(name, SortRef::BV(retLen), SortRef::BV(val.bit_width()) )( val );
}
/// build a map relation
ExprRef PMESH_L15::NewMap(const std::string & name, unsigned inLen, unsigned outLen) {
return ExprRef(NULL); //model.NewMemState(name+"_mapmem", inLen, outLen);
}
unsigned nondet_counter = 0;
FuncRef PMESH_L15::unknown(unsigned width) {
return FuncRef("unknown" + std::to_string(nondet_counter++),
SortRef::BV(width));
} | true |
d2ff2b9a8373559edb2dff506b8fd3f194860df2 | C++ | 1choitaek/thuat-toan-attt | /bai8 ex_euclid.cpp | UTF-8 | 646 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
void extended_Euclid(int a, int b)
{
int d ,x, y;
if(b == 0)
{
d = a; x = 1; y = 0;
cout << "d = " << d << "\nx = " << x << "\ny = " << y;
}
int x1, x2, y1, y2;
x2 = 1; x1 = 0;
y2 = 0; y1 = 1;
while(b > 0)
{
int r;
int q;
q = a/b;
r = a-q*b;
x = x2 - q*x1;
y = y2 - q*y1;
a = b;
b = r;
x2 = x1; x1 = x;
y2 = y1; y1 = y;
}
d = a; x = x2; y = y2;
cout << "d = " << d << "\nx = " << x << "\ny = " << y << endl;
}
int main()
{
int a, b;
cout << "2 so a va b la: ";
cin >> a >> b;
extended_Euclid(a, b);
return 0;
}
| true |
dd72545c38480ddbf849bc4d86006413b7a3b981 | C++ | jorgerodrigar/Sistema-de-Integracion-Continua | /ProyectosSDL/Moonace/src/SoundManager.h | UTF-8 | 880 | 2.6875 | 3 | [] | no_license | #ifndef SRC_SOUNDMANAGER_H_
#define SRC_SOUNDMANAGER_H_
#include "Resources.h"
#include "GameObject.h"
#include "Observer.h"
#include <queue>
/*
*
*/
class SoundManager : public Observer {
public:
SoundManager() {}
SoundManager(SDLApp* game);
virtual ~SoundManager();
virtual void receive(Mensaje* msg);
virtual void update();
void changeMute();
inline bool const getMute() { return mute; };
bool isAlreadySounding(Resources::MusicId m) { return actualMusicId == m && stopMusic; }
private:
struct PlayMessage {
PlayMessage(Resources::SoundEffectId id, int num) : id_(id), num_(num) {};
Resources::SoundEffectId id_; //id del sonido a reproducir
int num_;
};
queue<PlaySoundE> eventQueue;
SDLApp* app;
SoundEffect* actualSoundEffect = nullptr;
Resources::MusicId actualMusicId;
bool stopMusic = false;
bool mute = false;
};
#endif /* SRC_SOUNDMANAGER_H_ */ | true |
387221bdff2fee513aa5221e8140eca70a24e20f | C++ | hhoshino0421/MultiThreadTestApp | /PthreadTestApp/PthreadMain.cpp | UTF-8 | 1,103 | 3.109375 | 3 | [] | no_license | /*
* PthreadMain.cpp
*
* Created on: 2016/05/08
* Author: Hoshino Hitoshi
*/
#include <stdio.h>
#include <pthread.h>
#define NUM_RECTS 1000000
#define NUM_THREADS 4
double gArea = 0.0;
pthread_mutex_t gLock;
void *threadFunction(void *pArg);
/*
* エントリポイント
*/
int main() {
pthread_t tHandles[NUM_THREADS];
int tNum[NUM_THREADS];
pthread_mutex_init(&gLock,NULL);
for (int i = 0; i < NUM_THREADS; i++) {
tNum[i] = i;
pthread_create(&tHandles[i],NULL,threadFunction,(void *)&tNum[i]);
}
for (int j=0;j<NUM_THREADS;j++) {
pthread_join(tHandles[j],NULL);
}
pthread_mutex_destroy(&gLock);
printf("Completed value of PI: %f¥n",gArea);
}
/*
* pi近似値計算処理関数
*/
void *theradFunction(void *pArg) {
int myNum = *((int *)pArg);
double partialHeight = 0.0,lWidth = 1.0 / NUM_RECTS,x;
for (int i = myNum; i < NUM_RECTS; i += NUM_THREADS) {
x = (i + 0.5f) / NUM_RECTS;
partialHeight += 4.0f / (1.0f + x * x);
}
//スレッド排他処理区間
pthread_mutex_lock(&gLock);
gArea += partialHeight * lWidth;
pthread_mutex_lock(&gLock);
}
| true |
a6696e1c8d19592405a9a18f54eda6ed9f6e3768 | C++ | plusminus34/Interactive_thin_shells_Bachelor_thesis | /OptimizationLib/include/OptimizationLib/SQPFunctionMinimizer_BFGS.h | UTF-8 | 1,233 | 2.515625 | 3 | [] | no_license | #pragma once
#include <OptimizationLib/ConstrainedObjectiveFunction.h>
#include <OptimizationLib/ObjectiveFunction.h>
#include <OptimizationLib/SQPFunctionMinimizer.h>
#include <OptimizationLib/BFGSHessianApproximator.h>
/**
Use the Sequential Quadratic Programming method to optimize a function, subject to constraints. However, a BFGS solver is used to solve the quadratic objective part,
instead of computing the Hessian. This can be useful if the Hessian is difficult to compute, or if it is not positive-definite.
*/
class SQPFunctionMinimizer_BFGS : public SQPFunctionMinimizer {
protected:
virtual void computeGradient(ConstrainedObjectiveFunction *function, const dVector& pi);
virtual void computeHessian(ConstrainedObjectiveFunction *function, const dVector& pi);
BFGSHessianApproximator bfgsApproximator;
public:
SQPFunctionMinimizer_BFGS(int maxIterations = 2000,
double solveResidual = 0.0001,
double regularizer = 0.0,
int maxLineSearchIterations = 0,
double solveFunctionValue = -DBL_MAX,
bool printOutput = false,
bool checkConstraints = false) : SQPFunctionMinimizer(maxIterations, solveResidual, regularizer, maxLineSearchIterations, solveFunctionValue, printOutput, checkConstraints) {}
};
| true |
fcdefa0a2256b4f00b924670e26753f27a5a4694 | C++ | Luckyblock233/OI-code | /Luogu/P2910 [USACO08OPEN]寻宝之路Clear And Present Danger.cpp | GB18030 | 981 | 2.75 | 3 | [] | no_license | //֪ʶ:Floyd,·
/*
ģ
ע
*/
#include<cstdio>
#include<cstring>
using namespace std;
//===========================================================
int road[10010];//Ҫ·
int danger[105][105];//Σն
int n,m,minn;
//===========================================================
signed main()
{
memset(danger,0xfffff,sizeof(danger));//ʼֵ
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++) scanf("%d",&road[i]);//Ԥ·
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&danger[i][j]);//ÿ㵽Σն
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)//FloydԴ·
if(danger[i][j] > danger[i][k] + danger[k][j])
danger[i][j]=danger[i][k] + danger[k][j];
for(int i=1;i<m;i++)//Ԥ·Сֵ֮
minn+=danger[road[i]][road[i+1]];
printf("%d",minn);
}
| true |
669c0ec001093486d6453b45d57c178f478d545e | C++ | braph/edev | /lib/curses/curs.hpp | UTF-8 | 41,136 | 2.515625 | 3 | [] | no_license | // This file was generated by: ['./curs.py']
#include <ncurses.h>
#include <climits> // INT_MAX
#include <utility>
#undef NCURSES_OK_ADDR
#define NCURSES_OK_ADDR(WIN) TRUE
namespace NCursesCPP_Implementation {
// Return a char*/wchar_t*/... from std::string/char*/...
template<class T> inline T* NC_cstr(T* s) { return s; }
template<class T> inline auto NC_cstr(T& s) -> decltype(std::declval<T>().c_str()) { return s.c_str(); }
// For INPUT functions (*inchstr, *getstr).
template<class T, size_t N> inline int capacity(T(&s)[N]) { return N; }
template<class T> inline int capacity(T& s) { return s.capacity(); }
// For OUTPUT functions (*addstr, *insstr).
// Returning INT_MAX instead of T.size() is a little bit faster, but assumes
// that T.c_str() will be NUL-terminated.
template<class T, size_t N> inline int len(const T(&s)[N]) { return N; }
template<class T> inline int len(const T&) { return INT_MAX; }
// OUTPUT functions
inline int waddnstr_generic(WINDOW* w, const char* s, int n) { return waddnstr(w, s, n); }
inline int waddnstr_generic(WINDOW* w, const wchar_t* s, int n) { return waddnwstr(w, s, n); }
inline int winsnstr_generic(WINDOW* w, const char* s, int n) { return winsnstr(w, s, n); }
inline int winsnstr_generic(WINDOW* w, const wchar_t* s, int n) { return wins_nwstr(w, s, n); }
// INPUT functions
inline int wgetnstr_generic(WINDOW* w, char* s, int n) { return wgetnstr(w, s, n); }
inline int wgetnstr_generic(WINDOW* w, wint_t* s, int n) { return wgetn_wstr(w, s, n); }
inline int winnstr_generic(WINDOW* w, char* s, int n) { return winnstr(w, s, n); }
inline int winnstr_generic(WINDOW* w, chtype* s, int n) { return winchnstr(w, s, n); }
namespace Public {
inline int (NC_move)(WINDOW* win, int y, int x) { return wmove(win, y, x); }
inline int (NC_move)(int y, int x) { return wmove(stdscr, y, x); }
inline int (NC_erase)(WINDOW* win) { return werase(win); }
inline int (NC_erase)() { return werase(stdscr); }
inline int (NC_clear)(WINDOW* win) { return wclear(win); }
inline int (NC_clear)() { return wclear(stdscr); }
inline int (NC_clrtobot)(WINDOW* win) { return wclrtobot(win); }
inline int (NC_clrtobot)() { return wclrtobot(stdscr); }
inline int (NC_clrtoeol)(WINDOW* win) { return wclrtoeol(win); }
inline int (NC_clrtoeol)() { return wclrtoeol(stdscr); }
inline int (NC_standend)(WINDOW* win) { return wstandend(win); }
inline int (NC_standend)() { return wstandend(stdscr); }
inline int (NC_standout)(WINDOW* win) { return wstandout(win); }
inline int (NC_standout)() { return wstandout(stdscr); }
template<class Attr> inline int (NC_attron)(WINDOW* win, Attr attrs) { return wattron(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attron)(Attr attrs) { return wattron(stdscr, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attroff)(WINDOW* win, Attr attrs) { return wattroff(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attroff)(Attr attrs) { return wattroff(stdscr, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attrset)(WINDOW* win, Attr attrs) { return wattrset(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attrset)(Attr attrs) { return wattrset(stdscr, static_cast<int>(attrs)); }
inline int (NC_attr_on)(WINDOW* win, attr_t attrs, void* opts = NULL) { return wattr_on(win, attrs, opts); }
inline int (NC_attr_on)(attr_t attrs, void* opts = NULL) { return wattr_on(stdscr, attrs, opts); }
inline int (NC_attr_off)(WINDOW* win, attr_t attrs, void* opts = NULL) { return wattr_off(win, attrs, opts); }
inline int (NC_attr_off)(attr_t attrs, void* opts = NULL) { return wattr_off(stdscr, attrs, opts); }
inline int (NC_attr_set)(WINDOW* win, attr_t attrs, NCURSES_PAIRS_T pair, void* opts = NULL) { return wattr_set(win, attrs, pair, opts); }
inline int (NC_attr_set)(attr_t attrs, NCURSES_PAIRS_T pair, void* opts = NULL) { return wattr_set(stdscr, attrs, pair, opts); }
inline int (NC_attr_get)(const WINDOW* win, attr_t* attrs, NCURSES_PAIRS_T* pair = NULL, void* opts = NULL) { return wattr_get(win, attrs, pair, opts); }
inline int (NC_attr_get)(attr_t* attrs, NCURSES_PAIRS_T* pair = NULL, void* opts = NULL) { return wattr_get(stdscr, attrs, pair, opts); }
inline int (NC_chgat)(WINDOW* win, int n, attr_t attr, short pair, const void *opts = NULL) { return wchgat(win, n, attr, pair, opts); }
inline int (NC_chgat)(int n, attr_t attr, short pair, const void *opts = NULL) { return wchgat(stdscr, n, attr, pair, opts); }
inline int (NC_color_set)(WINDOW* win, short pair, void* opts = NULL) { return wcolor_set(win, pair, opts); }
inline int (NC_color_set)(short pair, void* opts = NULL) { return wcolor_set(stdscr, pair, opts); }
inline bool (NC_is_cleared)(const WINDOW* win) { return is_cleared(win); }
inline bool (NC_is_cleared)() { return is_cleared(stdscr); }
inline bool (NC_is_idcok)(const WINDOW* win) { return is_idcok(win); }
inline bool (NC_is_idcok)() { return is_idcok(stdscr); }
inline bool (NC_is_idlok)(const WINDOW* win) { return is_idlok(win); }
inline bool (NC_is_idlok)() { return is_idlok(stdscr); }
inline bool (NC_is_immedok)(const WINDOW* win) { return is_immedok(win); }
inline bool (NC_is_immedok)() { return is_immedok(stdscr); }
inline bool (NC_is_keypad)(const WINDOW* win) { return is_keypad(win); }
inline bool (NC_is_keypad)() { return is_keypad(stdscr); }
inline bool (NC_is_leaveok)(const WINDOW* win) { return is_leaveok(win); }
inline bool (NC_is_leaveok)() { return is_leaveok(stdscr); }
inline bool (NC_is_nodelay)(const WINDOW* win) { return is_nodelay(win); }
inline bool (NC_is_nodelay)() { return is_nodelay(stdscr); }
inline bool (NC_is_notimeout)(const WINDOW* win) { return is_notimeout(win); }
inline bool (NC_is_notimeout)() { return is_notimeout(stdscr); }
inline bool (NC_is_pad)(const WINDOW* win) { return is_pad(win); }
inline bool (NC_is_pad)() { return is_pad(stdscr); }
inline bool (NC_is_scrollok)(const WINDOW* win) { return is_scrollok(win); }
inline bool (NC_is_scrollok)() { return is_scrollok(stdscr); }
inline bool (NC_is_subwin)(const WINDOW* win) { return is_subwin(win); }
inline bool (NC_is_subwin)() { return is_subwin(stdscr); }
inline bool (NC_is_syncok)(const WINDOW* win) { return is_syncok(win); }
inline bool (NC_is_syncok)() { return is_syncok(stdscr); }
inline int (NC_wgetdelay)(const WINDOW* win) { return wgetdelay(win); }
inline int (NC_wgetdelay)() { return wgetdelay(stdscr); }
inline WINDOW* (NC_wgetparent)(const WINDOW* win) { return wgetparent(win); }
inline WINDOW* (NC_wgetparent)() { return wgetparent(stdscr); }
inline int (NC_wgetscrreg)(const WINDOW* win, int* top, int* bottom) { return wgetscrreg(win, top, bottom); }
inline int (NC_wgetscrreg)(int* top, int* bottom) { return wgetscrreg(stdscr, top, bottom); }
inline int (NC_getattrs)(const WINDOW* win) { return getattrs(win); }
inline int (NC_getattrs)() { return getattrs(stdscr); }
inline int (NC_getcurx)(const WINDOW* win) { return getcurx(win); }
inline int (NC_getcurx)() { return getcurx(stdscr); }
inline int (NC_getcury)(const WINDOW* win) { return getcury(win); }
inline int (NC_getcury)() { return getcury(stdscr); }
inline int (NC_getbegx)(const WINDOW* win) { return getbegx(win); }
inline int (NC_getbegx)() { return getbegx(stdscr); }
inline int (NC_getbegy)(const WINDOW* win) { return getbegy(win); }
inline int (NC_getbegy)() { return getbegy(stdscr); }
inline int (NC_getmaxx)(const WINDOW* win) { return getmaxx(win); }
inline int (NC_getmaxx)() { return getmaxx(stdscr); }
inline int (NC_getmaxy)(const WINDOW* win) { return getmaxy(win); }
inline int (NC_getmaxy)() { return getmaxy(stdscr); }
inline int (NC_getparx)(const WINDOW* win) { return getparx(win); }
inline int (NC_getparx)() { return getparx(stdscr); }
inline int (NC_getpary)(const WINDOW* win) { return getpary(win); }
inline int (NC_getpary)() { return getpary(stdscr); }
inline void (NC_getyx)(const WINDOW* win, int& y, int& x) { getyx(win, y, x); }
inline void (NC_getyx)(int& y, int& x) { getyx(stdscr, y, x); }
inline void (NC_getbegyx)(const WINDOW* win, int& y, int& x) { getbegyx(win, y, x); }
inline void (NC_getbegyx)(int& y, int& x) { getbegyx(stdscr, y, x); }
inline void (NC_getmaxyx)(const WINDOW* win, int& y, int& x) { getmaxyx(win, y, x); }
inline void (NC_getmaxyx)(int& y, int& x) { getmaxyx(stdscr, y, x); }
inline void (NC_getparyx)(const WINDOW* win, int& y, int& x) { getparyx(win, y, x); }
inline void (NC_getparyx)(int& y, int& x) { getparyx(stdscr, y, x); }
template<typename... T> inline int (NC_printw)(WINDOW* win, const char* fmt, T... args) { return wprintw(win, fmt, args...); }
template<typename... T> inline int (NC_printw)(const char* fmt, T... args) { return wprintw(stdscr, fmt, args...); }
template<typename... T> inline int (NC_printw)(WINDOW* win, int y, int x, const char* fmt, T... args) { return wmove(win, y, x), wprintw(win, fmt, args...); }
template<typename... T> inline int (NC_printw)(int y, int x, const char* fmt, T... args) { return wmove(stdscr, y, x), wprintw(stdscr, fmt, args...); }
inline int (NC_printw)(WINDOW* win, const char* fmt, va_list args) { return vw_printw(win, fmt, args); }
inline int (NC_printw)(const char* fmt, va_list args) { return vw_printw(stdscr, fmt, args); }
inline int (NC_printw)(WINDOW* win, int y, int x, const char* fmt, va_list args) { return wmove(win, y, x), vw_printw(win, fmt, args); }
inline int (NC_printw)(int y, int x, const char* fmt, va_list args) { return wmove(stdscr, y, x), vw_printw(stdscr, fmt, args); }
template<typename... T> inline int (NC_scanw)(WINDOW* win, const char* fmt, T... args) { return wscanw(win, fmt, args...); }
template<typename... T> inline int (NC_scanw)(const char* fmt, T... args) { return wscanw(stdscr, fmt, args...); }
template<typename... T> inline int (NC_scanw)(WINDOW* win, int y, int x, const char* fmt, T... args) { return wmove(win, y, x), wscanw(win, fmt, args...); }
template<typename... T> inline int (NC_scanw)(int y, int x, const char* fmt, T... args) { return wmove(stdscr, y, x), wscanw(stdscr, fmt, args...); }
inline int (NC_scanw)(WINDOW* win, const char* fmt, va_list args) { return vw_printw(win, fmt, args); }
inline int (NC_scanw)(const char* fmt, va_list args) { return vw_printw(stdscr, fmt, args); }
inline int (NC_scanw)(WINDOW* win, int y, int x, const char* fmt, va_list args) { return wmove(win, y, x), vw_printw(win, fmt, args); }
inline int (NC_scanw)(int y, int x, const char* fmt, va_list args) { return wmove(stdscr, y, x), vw_printw(stdscr, fmt, args); }
inline int (NC_addch)(WINDOW* win, chtype ch) { return waddch(win, ch); }
inline int (NC_addch)(chtype ch) { return waddch(stdscr, ch); }
inline int (NC_addch)(WINDOW* win, int y, int x, chtype ch) { return wmove(win, y, x), waddch(win, ch); }
inline int (NC_addch)(int y, int x, chtype ch) { return wmove(stdscr, y, x), waddch(stdscr, ch); }
inline int (NC_addch)(WINDOW* win, const cchar_t* ch) { return wadd_wch(win, ch); }
inline int (NC_addch)(const cchar_t* ch) { return wadd_wch(stdscr, ch); }
inline int (NC_addch)(WINDOW* win, int y, int x, const cchar_t* ch) { return wmove(win, y, x), wadd_wch(win, ch); }
inline int (NC_addch)(int y, int x, const cchar_t* ch) { return wmove(stdscr, y, x), wadd_wch(stdscr, ch); }
template<class Str> inline int (NC_addstr)(WINDOW* win, const Str& s) { return waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(const Str& s) { return waddnstr_generic(stdscr, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(WINDOW* win, int y, int x, const Str& s) { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(int y, int x, const Str& s) { return wmove(stdscr, y, x), waddnstr_generic(stdscr, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(WINDOW* win, const Str& s, int n) { return waddnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_addstr)(const Str& s, int n) { return waddnstr_generic(stdscr, NC_cstr(s), n); }
template<class Str> inline int (NC_addstr)(WINDOW* win, int y, int x, const Str& s, int n) { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_addstr)(int y, int x, const Str& s, int n) { return wmove(stdscr, y, x), waddnstr_generic(stdscr, NC_cstr(s), n); }
inline int (NC_insch)(WINDOW* win, chtype ch) { return winsch(win, ch); }
inline int (NC_insch)(chtype ch) { return winsch(stdscr, ch); }
inline int (NC_insch)(WINDOW* win, int y, int x, chtype ch) { return wmove(win, y, x), winsch(win, ch); }
inline int (NC_insch)(int y, int x, chtype ch) { return wmove(stdscr, y, x), winsch(stdscr, ch); }
inline int (NC_insch)(WINDOW* win, const cchar_t* ch) { return wins_wch(win, ch); }
inline int (NC_insch)(const cchar_t* ch) { return wins_wch(stdscr, ch); }
inline int (NC_insch)(WINDOW* win, int y, int x, const cchar_t* ch) { return wmove(win, y, x), wins_wch(win, ch); }
inline int (NC_insch)(int y, int x, const cchar_t* ch) { return wmove(stdscr, y, x), wins_wch(stdscr, ch); }
template<class Str> inline int (NC_insstr)(WINDOW* win, const Str& s) { return winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(const Str& s) { return winsnstr_generic(stdscr, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(WINDOW* win, int y, int x, const Str& s) { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(int y, int x, const Str& s) { return wmove(stdscr, y, x), winsnstr_generic(stdscr, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(WINDOW* win, const Str& s, int n) { return winsnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_insstr)(const Str& s, int n) { return winsnstr_generic(stdscr, NC_cstr(s), n); }
template<class Str> inline int (NC_insstr)(WINDOW* win, int y, int x, const Str& s, int n) { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_insstr)(int y, int x, const Str& s, int n) { return wmove(stdscr, y, x), winsnstr_generic(stdscr, NC_cstr(s), n); }
inline int (NC_delch)(WINDOW* win) { return wdelch(win); }
inline int (NC_delch)() { return wdelch(stdscr); }
inline int (NC_delch)(WINDOW* win, int y, int x) { return wmove(win, y, x), wdelch(win); }
inline int (NC_delch)(int y, int x) { return wmove(stdscr, y, x), wdelch(stdscr); }
inline int (NC_getch)(WINDOW* win) { return wgetch(win); }
inline int (NC_getch)() { return wgetch(stdscr); }
inline int (NC_getch)(WINDOW* win, int y, int x) { return wmove(win, y, x), wgetch(win); }
inline int (NC_getch)(int y, int x) { return wmove(stdscr, y, x), wgetch(stdscr); }
inline int (NC_getch)(WINDOW* win, wint_t* ch) { return wget_wch(win, ch); }
inline int (NC_getch)(wint_t* ch) { return wget_wch(stdscr, ch); }
inline int (NC_getch)(WINDOW* win, int y, int x, wint_t* ch) { return wmove(win, y, x), wget_wch(win, ch); }
inline int (NC_getch)(int y, int x, wint_t* ch) { return wmove(stdscr, y, x), wget_wch(stdscr, ch); }
template<class Str> inline int (NC_getstr)(WINDOW* win, Str& s) { return wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(Str& s) { return wgetnstr_generic(stdscr, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(WINDOW* win, int y, int x, Str& s) { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(int y, int x, Str& s) { return wmove(stdscr, y, x), wgetnstr_generic(stdscr, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(WINDOW* win, Str& s, int n) { return wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_getstr)(Str& s, int n) { return wgetnstr_generic(stdscr, NC_cstr(s), n); }
template<class Str> inline int (NC_getstr)(WINDOW* win, int y, int x, Str& s, int n) { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_getstr)(int y, int x, Str& s, int n) { return wmove(stdscr, y, x), wgetnstr_generic(stdscr, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(WINDOW* win, Str& s) { return winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(Str& s) { return winnstr_generic(stdscr, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(WINDOW* win, int y, int x, Str& s) { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(int y, int x, Str& s) { return wmove(stdscr, y, x), winnstr_generic(stdscr, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(WINDOW* win, Str& s, int n) { return winnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(Str& s, int n) { return winnstr_generic(stdscr, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(WINDOW* win, int y, int x, Str& s, int n) { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(int y, int x, Str& s, int n) { return wmove(stdscr, y, x), winnstr_generic(stdscr, NC_cstr(s), n); }
inline int (NC_inch)(WINDOW* win, cchar_t* ch) { return win_wch(win, ch); }
inline int (NC_inch)(cchar_t* ch) { return win_wch(stdscr, ch); }
inline int (NC_inch)(WINDOW* win, int y, int x, cchar_t* ch) { return wmove(win, y, x), win_wch(win, ch); }
inline int (NC_inch)(int y, int x, cchar_t* ch) { return wmove(stdscr, y, x), win_wch(stdscr, ch); }
inline chtype (NC_inch)(WINDOW* win) { return winch(win); }
inline chtype (NC_inch)() { return winch(stdscr); }
inline chtype (NC_inch)(WINDOW* win, int y, int x) { return wmove(win, y, x), winch(win); }
inline chtype (NC_inch)(int y, int x) { return wmove(stdscr, y, x), winch(stdscr); }
#if defined(USE_C_VARIADIC_ARGS) && (defined(__GNUC__) || defined(__clang__))
__attribute__((__format__(__printf__, 2, 3)))
int __wprintw(const char* fmt, ...) noexcept {
va_list ap;
va_start(ap, fmt);
int ret = vw_printw(win, fmt, ap);
va_end(ap);
return ret;
}
__attribute__((__format__(__printf__, 4, 5)))
int __mvwprintw(int y, int x, const char* fmt, ...) noexcept {
int ret = ERR;
if (OK == wmove(win, y, x)) {
va_list ap;
va_start(ap, fmt);
ret = vw_printw(win, fmt, ap);
va_end(ap);
}
return ret;
}
#endif
struct CursesWindow {
WINDOW* win;
CursesWindow() : win(NULL) {}
CursesWindow(WINDOW* w_) : win(w_) {}
using K = CursesWindow;
template<class S>
inline K& operator<<(const S& s) noexcept { NC_addstr(s); return *this; }
inline K& operator<<(char c) noexcept { waddnstr(win, &c, 1); return *this; } // XXX don't use waddch, because, eh...
inline K& operator<<(wchar_t c) noexcept { waddnwstr(win, &c, 1); return *this; }
inline K& operator<<(int i) noexcept { wprintw(win, "%d", i); return *this; }
inline K& operator<<(size_t s) noexcept { wprintw(win, "%zu", s); return *this; }
inline K& operator<<(float f) noexcept { wprintw(win, "%f", f); return *this; }
inline K& operator<<(double d) noexcept { wprintw(win, "%f", d); return *this; }
inline int (move)(int y, int x) noexcept { return wmove(win, y, x); }
inline int (NC_move)(int y, int x) noexcept { return wmove(win, y, x); }
inline int (erase)() noexcept { return werase(win); }
inline int (NC_erase)() noexcept { return werase(win); }
inline int (clear)() noexcept { return wclear(win); }
inline int (NC_clear)() noexcept { return wclear(win); }
inline int (clrtobot)() noexcept { return wclrtobot(win); }
inline int (NC_clrtobot)() noexcept { return wclrtobot(win); }
inline int (clrtoeol)() noexcept { return wclrtoeol(win); }
inline int (NC_clrtoeol)() noexcept { return wclrtoeol(win); }
inline int (standend)() noexcept { return wstandend(win); }
inline int (NC_standend)() noexcept { return wstandend(win); }
inline int (standout)() noexcept { return wstandout(win); }
inline int (NC_standout)() noexcept { return wstandout(win); }
template<class Attr> inline int (attron)(Attr attrs) noexcept { return wattron(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attron)(Attr attrs) noexcept { return wattron(win, static_cast<int>(attrs)); }
template<class Attr> inline int (attroff)(Attr attrs) noexcept { return wattroff(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attroff)(Attr attrs) noexcept { return wattroff(win, static_cast<int>(attrs)); }
template<class Attr> inline int (attrset)(Attr attrs) noexcept { return wattrset(win, static_cast<int>(attrs)); }
template<class Attr> inline int (NC_attrset)(Attr attrs) noexcept { return wattrset(win, static_cast<int>(attrs)); }
inline int (attr_on)(attr_t attrs, void* opts = NULL) noexcept { return wattr_on(win, attrs, opts); }
inline int (NC_attr_on)(attr_t attrs, void* opts = NULL) noexcept { return wattr_on(win, attrs, opts); }
inline int (attr_off)(attr_t attrs, void* opts = NULL) noexcept { return wattr_off(win, attrs, opts); }
inline int (NC_attr_off)(attr_t attrs, void* opts = NULL) noexcept { return wattr_off(win, attrs, opts); }
inline int (attr_set)(attr_t attrs, NCURSES_PAIRS_T pair, void* opts = NULL) noexcept { return wattr_set(win, attrs, pair, opts); }
inline int (NC_attr_set)(attr_t attrs, NCURSES_PAIRS_T pair, void* opts = NULL) noexcept { return wattr_set(win, attrs, pair, opts); }
inline int (attr_get)(attr_t* attrs, NCURSES_PAIRS_T* pair = NULL, void* opts = NULL) const noexcept { return wattr_get(win, attrs, pair, opts); }
inline int (NC_attr_get)(attr_t* attrs, NCURSES_PAIRS_T* pair = NULL, void* opts = NULL) const noexcept { return wattr_get(win, attrs, pair, opts); }
inline int (chgat)(int n, attr_t attr, short pair, const void *opts = NULL) noexcept { return wchgat(win, n, attr, pair, opts); }
inline int (NC_chgat)(int n, attr_t attr, short pair, const void *opts = NULL) noexcept { return wchgat(win, n, attr, pair, opts); }
inline int (color_set)(short pair, void* opts = NULL) noexcept { return wcolor_set(win, pair, opts); }
inline int (NC_color_set)(short pair, void* opts = NULL) noexcept { return wcolor_set(win, pair, opts); }
inline bool (is_cleared)() const noexcept { return is_cleared(win); }
inline bool (NC_is_cleared)() const noexcept { return is_cleared(win); }
inline bool (is_idcok)() const noexcept { return is_idcok(win); }
inline bool (NC_is_idcok)() const noexcept { return is_idcok(win); }
inline bool (is_idlok)() const noexcept { return is_idlok(win); }
inline bool (NC_is_idlok)() const noexcept { return is_idlok(win); }
inline bool (is_immedok)() const noexcept { return is_immedok(win); }
inline bool (NC_is_immedok)() const noexcept { return is_immedok(win); }
inline bool (is_keypad)() const noexcept { return is_keypad(win); }
inline bool (NC_is_keypad)() const noexcept { return is_keypad(win); }
inline bool (is_leaveok)() const noexcept { return is_leaveok(win); }
inline bool (NC_is_leaveok)() const noexcept { return is_leaveok(win); }
inline bool (is_nodelay)() const noexcept { return is_nodelay(win); }
inline bool (NC_is_nodelay)() const noexcept { return is_nodelay(win); }
inline bool (is_notimeout)() const noexcept { return is_notimeout(win); }
inline bool (NC_is_notimeout)() const noexcept { return is_notimeout(win); }
inline bool (is_pad)() const noexcept { return is_pad(win); }
inline bool (NC_is_pad)() const noexcept { return is_pad(win); }
inline bool (is_scrollok)() const noexcept { return is_scrollok(win); }
inline bool (NC_is_scrollok)() const noexcept { return is_scrollok(win); }
inline bool (is_subwin)() const noexcept { return is_subwin(win); }
inline bool (NC_is_subwin)() const noexcept { return is_subwin(win); }
inline bool (is_syncok)() const noexcept { return is_syncok(win); }
inline bool (NC_is_syncok)() const noexcept { return is_syncok(win); }
inline int (wgetdelay)() const noexcept { return wgetdelay(win); }
inline int (NC_wgetdelay)() const noexcept { return wgetdelay(win); }
inline WINDOW* (wgetparent)() const noexcept { return wgetparent(win); }
inline WINDOW* (NC_wgetparent)() const noexcept { return wgetparent(win); }
inline int (wgetscrreg)(int* top, int* bottom) const noexcept { return wgetscrreg(win, top, bottom); }
inline int (NC_wgetscrreg)(int* top, int* bottom) const noexcept { return wgetscrreg(win, top, bottom); }
inline int (getattrs)() const noexcept { return getattrs(win); }
inline int (NC_getattrs)() const noexcept { return getattrs(win); }
inline int (getcurx)() const noexcept { return getcurx(win); }
inline int (NC_getcurx)() const noexcept { return getcurx(win); }
inline int (getcury)() const noexcept { return getcury(win); }
inline int (NC_getcury)() const noexcept { return getcury(win); }
inline int (getbegx)() const noexcept { return getbegx(win); }
inline int (NC_getbegx)() const noexcept { return getbegx(win); }
inline int (getbegy)() const noexcept { return getbegy(win); }
inline int (NC_getbegy)() const noexcept { return getbegy(win); }
inline int (getmaxx)() const noexcept { return getmaxx(win); }
inline int (NC_getmaxx)() const noexcept { return getmaxx(win); }
inline int (getmaxy)() const noexcept { return getmaxy(win); }
inline int (NC_getmaxy)() const noexcept { return getmaxy(win); }
inline int (getparx)() const noexcept { return getparx(win); }
inline int (NC_getparx)() const noexcept { return getparx(win); }
inline int (getpary)() const noexcept { return getpary(win); }
inline int (NC_getpary)() const noexcept { return getpary(win); }
inline void (getyx)(int& y, int& x) const noexcept { getyx(win, y, x); }
inline void (NC_getyx)(int& y, int& x) const noexcept { getyx(win, y, x); }
inline void (getbegyx)(int& y, int& x) const noexcept { getbegyx(win, y, x); }
inline void (NC_getbegyx)(int& y, int& x) const noexcept { getbegyx(win, y, x); }
inline void (getmaxyx)(int& y, int& x) const noexcept { getmaxyx(win, y, x); }
inline void (NC_getmaxyx)(int& y, int& x) const noexcept { getmaxyx(win, y, x); }
inline void (getparyx)(int& y, int& x) const noexcept { getparyx(win, y, x); }
inline void (NC_getparyx)(int& y, int& x) const noexcept { getparyx(win, y, x); }
template<typename... T> inline int (printw)(const char* fmt, T... args) noexcept { return wprintw(win, fmt, args...); }
template<typename... T> inline int (NC_printw)(const char* fmt, T... args) noexcept { return wprintw(win, fmt, args...); }
template<typename... T> inline int (printw)(int y, int x, const char* fmt, T... args) noexcept { return wmove(win, y, x), wprintw(win, fmt, args...); }
template<typename... T> inline int (NC_printw)(int y, int x, const char* fmt, T... args) noexcept { return wmove(win, y, x), wprintw(win, fmt, args...); }
inline int (printw)(const char* fmt, va_list args) noexcept { return vw_printw(win, fmt, args); }
inline int (NC_printw)(const char* fmt, va_list args) noexcept { return vw_printw(win, fmt, args); }
inline int (printw)(int y, int x, const char* fmt, va_list args) noexcept { return wmove(win, y, x), vw_printw(win, fmt, args); }
inline int (NC_printw)(int y, int x, const char* fmt, va_list args) noexcept { return wmove(win, y, x), vw_printw(win, fmt, args); }
template<typename... T> inline int (scanw)(const char* fmt, T... args) noexcept { return wscanw(win, fmt, args...); }
template<typename... T> inline int (NC_scanw)(const char* fmt, T... args) noexcept { return wscanw(win, fmt, args...); }
template<typename... T> inline int (scanw)(int y, int x, const char* fmt, T... args) noexcept { return wmove(win, y, x), wscanw(win, fmt, args...); }
template<typename... T> inline int (NC_scanw)(int y, int x, const char* fmt, T... args) noexcept { return wmove(win, y, x), wscanw(win, fmt, args...); }
inline int (scanw)(const char* fmt, va_list args) noexcept { return vw_printw(win, fmt, args); }
inline int (NC_scanw)(const char* fmt, va_list args) noexcept { return vw_printw(win, fmt, args); }
inline int (scanw)(int y, int x, const char* fmt, va_list args) noexcept { return wmove(win, y, x), vw_printw(win, fmt, args); }
inline int (NC_scanw)(int y, int x, const char* fmt, va_list args) noexcept { return wmove(win, y, x), vw_printw(win, fmt, args); }
inline int (addch)(chtype ch) noexcept { return waddch(win, ch); }
inline int (NC_addch)(chtype ch) noexcept { return waddch(win, ch); }
inline int (addch)(int y, int x, chtype ch) noexcept { return wmove(win, y, x), waddch(win, ch); }
inline int (NC_addch)(int y, int x, chtype ch) noexcept { return wmove(win, y, x), waddch(win, ch); }
inline int (addch)(const cchar_t* ch) noexcept { return wadd_wch(win, ch); }
inline int (NC_addch)(const cchar_t* ch) noexcept { return wadd_wch(win, ch); }
inline int (addch)(int y, int x, const cchar_t* ch) noexcept { return wmove(win, y, x), wadd_wch(win, ch); }
inline int (NC_addch)(int y, int x, const cchar_t* ch) noexcept { return wmove(win, y, x), wadd_wch(win, ch); }
template<class Str> inline int (addstr)(const Str& s) noexcept { return waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(const Str& s) noexcept { return waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (addstr)(int y, int x, const Str& s) noexcept { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_addstr)(int y, int x, const Str& s) noexcept { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (addstr)(const Str& s, int n) noexcept { return waddnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_addstr)(const Str& s, int n) noexcept { return waddnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (addstr)(int y, int x, const Str& s, int n) noexcept { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_addstr)(int y, int x, const Str& s, int n) noexcept { return wmove(win, y, x), waddnstr_generic(win, NC_cstr(s), n); }
inline int (insch)(chtype ch) noexcept { return winsch(win, ch); }
inline int (NC_insch)(chtype ch) noexcept { return winsch(win, ch); }
inline int (insch)(int y, int x, chtype ch) noexcept { return wmove(win, y, x), winsch(win, ch); }
inline int (NC_insch)(int y, int x, chtype ch) noexcept { return wmove(win, y, x), winsch(win, ch); }
inline int (insch)(const cchar_t* ch) noexcept { return wins_wch(win, ch); }
inline int (NC_insch)(const cchar_t* ch) noexcept { return wins_wch(win, ch); }
inline int (insch)(int y, int x, const cchar_t* ch) noexcept { return wmove(win, y, x), wins_wch(win, ch); }
inline int (NC_insch)(int y, int x, const cchar_t* ch) noexcept { return wmove(win, y, x), wins_wch(win, ch); }
template<class Str> inline int (insstr)(const Str& s) noexcept { return winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(const Str& s) noexcept { return winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (insstr)(int y, int x, const Str& s) noexcept { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (NC_insstr)(int y, int x, const Str& s) noexcept { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), len(s)); }
template<class Str> inline int (insstr)(const Str& s, int n) noexcept { return winsnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_insstr)(const Str& s, int n) noexcept { return winsnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (insstr)(int y, int x, const Str& s, int n) noexcept { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_insstr)(int y, int x, const Str& s, int n) noexcept { return wmove(win, y, x), winsnstr_generic(win, NC_cstr(s), n); }
inline int (delch)() noexcept { return wdelch(win); }
inline int (NC_delch)() noexcept { return wdelch(win); }
inline int (delch)(int y, int x) noexcept { return wmove(win, y, x), wdelch(win); }
inline int (NC_delch)(int y, int x) noexcept { return wmove(win, y, x), wdelch(win); }
inline int (getch)() noexcept { return wgetch(win); }
inline int (NC_getch)() noexcept { return wgetch(win); }
inline int (getch)(int y, int x) noexcept { return wmove(win, y, x), wgetch(win); }
inline int (NC_getch)(int y, int x) noexcept { return wmove(win, y, x), wgetch(win); }
inline int (getch)(wint_t* ch) noexcept { return wget_wch(win, ch); }
inline int (NC_getch)(wint_t* ch) noexcept { return wget_wch(win, ch); }
inline int (getch)(int y, int x, wint_t* ch) noexcept { return wmove(win, y, x), wget_wch(win, ch); }
inline int (NC_getch)(int y, int x, wint_t* ch) noexcept { return wmove(win, y, x), wget_wch(win, ch); }
template<class Str> inline int (getstr)(Str& s) noexcept { return wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(Str& s) noexcept { return wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (getstr)(int y, int x, Str& s) noexcept { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_getstr)(int y, int x, Str& s) noexcept { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (getstr)(Str& s, int n) noexcept { return wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_getstr)(Str& s, int n) noexcept { return wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (getstr)(int y, int x, Str& s, int n) noexcept { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_getstr)(int y, int x, Str& s, int n) noexcept { return wmove(win, y, x), wgetnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (instr)(Str& s) noexcept { return winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(Str& s) noexcept { return winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (instr)(int y, int x, Str& s) noexcept { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (NC_instr)(int y, int x, Str& s) noexcept { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), capacity(s)); }
template<class Str> inline int (instr)(Str& s, int n) noexcept { return winnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(Str& s, int n) noexcept { return winnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (instr)(int y, int x, Str& s, int n) noexcept { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), n); }
template<class Str> inline int (NC_instr)(int y, int x, Str& s, int n) noexcept { return wmove(win, y, x), winnstr_generic(win, NC_cstr(s), n); }
inline int (inch)(cchar_t* ch) noexcept { return win_wch(win, ch); }
inline int (NC_inch)(cchar_t* ch) noexcept { return win_wch(win, ch); }
inline int (inch)(int y, int x, cchar_t* ch) noexcept { return wmove(win, y, x), win_wch(win, ch); }
inline int (NC_inch)(int y, int x, cchar_t* ch) noexcept { return wmove(win, y, x), win_wch(win, ch); }
inline chtype (inch)() noexcept { return winch(win); }
inline chtype (NC_inch)() noexcept { return winch(win); }
inline chtype (inch)(int y, int x) noexcept { return wmove(win, y, x), winch(win); }
inline chtype (NC_inch)(int y, int x) noexcept { return wmove(win, y, x), winch(win); }
};
} // namespace Public
} // namespace NCursesCPP_Implementation
#undef clear
#undef erase
#undef move
#undef clrtobot
#define clrtobot NC_clrtobot
#undef clrtoeol
#define clrtoeol NC_clrtoeol
#undef standend
#define standend NC_standend
#undef standout
#define standout NC_standout
#undef attron
#define attron NC_attron
#undef attroff
#define attroff NC_attroff
#undef attrset
#define attrset NC_attrset
#undef attr_on
#define attr_on NC_attr_on
#undef attr_off
#define attr_off NC_attr_off
#undef attr_set
#define attr_set NC_attr_set
#undef attr_get
#define attr_get NC_attr_get
#undef chgat
#define chgat NC_chgat
#undef color_set
#define color_set NC_color_set
#undef is_cleared
#define is_cleared NC_is_cleared
#undef is_idcok
#define is_idcok NC_is_idcok
#undef is_idlok
#define is_idlok NC_is_idlok
#undef is_immedok
#define is_immedok NC_is_immedok
#undef is_keypad
#define is_keypad NC_is_keypad
#undef is_leaveok
#define is_leaveok NC_is_leaveok
#undef is_nodelay
#define is_nodelay NC_is_nodelay
#undef is_notimeout
#define is_notimeout NC_is_notimeout
#undef is_pad
#define is_pad NC_is_pad
#undef is_scrollok
#define is_scrollok NC_is_scrollok
#undef is_subwin
#define is_subwin NC_is_subwin
#undef is_syncok
#define is_syncok NC_is_syncok
#undef wgetdelay
#define wgetdelay NC_wgetdelay
#undef wgetparent
#define wgetparent NC_wgetparent
#undef wgetscrreg
#define wgetscrreg NC_wgetscrreg
#undef getattrs
#define getattrs NC_getattrs
#undef getcurx
#define getcurx NC_getcurx
#undef getcury
#define getcury NC_getcury
#undef getbegx
#define getbegx NC_getbegx
#undef getbegy
#define getbegy NC_getbegy
#undef getmaxx
#define getmaxx NC_getmaxx
#undef getmaxy
#define getmaxy NC_getmaxy
#undef getparx
#define getparx NC_getparx
#undef getpary
#define getpary NC_getpary
#undef getyx
#define getyx NC_getyx
#undef getbegyx
#define getbegyx NC_getbegyx
#undef getmaxyx
#define getmaxyx NC_getmaxyx
#undef getparyx
#define getparyx NC_getparyx
#undef printw
#define printw NC_printw
#undef scanw
#define scanw NC_scanw
#undef addch
#define addch NC_addch
#undef addstr
#define addstr NC_addstr
#undef insch
#define insch NC_insch
#undef insstr
#define insstr NC_insstr
#undef delch
#define delch NC_delch
#undef getch
#define getch NC_getch
#undef getstr
#define getstr NC_getstr
#undef instr
#define instr NC_instr
#undef inch
#define inch NC_inch
#undef mvwaddch
#define mvwaddch NC_addch
#undef mvaddch
#define mvaddch NC_addch
#undef waddch
#define waddch NC_addch
#undef mvwaddnwstr
#define mvwaddnwstr NC_addstr
#undef mvwaddnstr
#define mvwaddnstr NC_addstr
#undef mvwaddwstr
#define mvwaddwstr NC_addstr
#undef mvwaddstr
#define mvwaddstr NC_addstr
#undef mvaddnwstr
#define mvaddnwstr NC_addstr
#undef mvaddnstr
#define mvaddnstr NC_addstr
#undef mvaddwstr
#define mvaddwstr NC_addstr
#undef mvaddstr
#define mvaddstr NC_addstr
#undef waddnwstr
#define waddnwstr NC_addstr
#undef waddnstr
#define waddnstr NC_addstr
#undef waddwstr
#define waddwstr NC_addstr
#undef waddstr
#define waddstr NC_addstr
#undef addnwstr
#define addnwstr NC_addstr
#undef addnstr
#define addnstr NC_addstr
#undef addwstr
#define addwstr NC_addstr
#undef mvwgetch
#define mvwgetch NC_getch
#undef mvwget_wch
#define mvwget_wch NC_getch
#undef mvgetch
#define mvgetch NC_getch
#undef mvget_wch
#define mvget_wch NC_getch
#undef wgetch
#define wgetch NC_getch
#undef wget_wch
#define wget_wch NC_getch
#undef get_wch
#define get_wch NC_getch
#undef mvwgetnstr
#define mvwgetnstr NC_getstr
#undef mvwget_nwstr
#define mvwget_nwstr NC_getstr
#undef mvwget_wstr
#define mvwget_wstr NC_getstr
#undef mvgetnstr
#define mvgetnstr NC_getstr
#undef mvget_nwstr
#define mvget_nwstr NC_getstr
#undef mvget_wstr
#define mvget_wstr NC_getstr
#undef wgetnstr
#define wgetnstr NC_getstr
#undef wget_nwstr
#define wget_nwstr NC_getstr
#undef wget_wstr
#define wget_wstr NC_getstr
#undef getnstr
#define getnstr NC_getstr
#undef get_nwstr
#define get_nwstr NC_getstr
#undef get_wstr
#define get_wstr NC_getstr
#undef mvwinsch
#define mvwinsch NC_insch
#undef mvwins_wch
#define mvwins_wch NC_insch
#undef mvinsch
#define mvinsch NC_insch
#undef mvins_wch
#define mvins_wch NC_insch
#undef winsch
#define winsch NC_insch
#undef wins_wch
#define wins_wch NC_insch
#undef ins_wch
#define ins_wch NC_insch
#undef mvwinsnstr
#define mvwinsnstr NC_insstr
#undef mvwins_nwstr
#define mvwins_nwstr NC_insstr
#undef mvwins_wstr
#define mvwins_wstr NC_insstr
#undef mvinsnstr
#define mvinsnstr NC_insstr
#undef mvins_nwstr
#define mvins_nwstr NC_insstr
#undef mvins_wstr
#define mvins_wstr NC_insstr
#undef winsnstr
#define winsnstr NC_insstr
#undef wins_nwstr
#define wins_nwstr NC_insstr
#undef wins_wstr
#define wins_wstr NC_insstr
#undef insnstr
#define insnstr NC_insstr
#undef ins_nwstr
#define ins_nwstr NC_insstr
#undef ins_wstr
#define ins_wstr NC_insstr
#undef mvwinch
#define mvwinch NC_inch
#undef mvwin_wch
#define mvwin_wch NC_inch
#undef mvinch
#define mvinch NC_inch
#undef mvin_wch
#define mvin_wch NC_inch
#undef winch
#define winch NC_inch
#undef win_wch
#define win_wch NC_inch
#undef in_wch
#define in_wch NC_inch
#undef mvwinchstr
#define mvwinchstr NC_instr
#undef mvwinstr
#define mvwinstr NC_instr
#undef mvinchstr
#define mvinchstr NC_instr
#undef mvinstr
#define mvinstr NC_instr
#undef winchstr
#define winchstr NC_instr
#undef winstr
#define winstr NC_instr
#undef inchstr
#define inchstr NC_instr
using namespace NCursesCPP_Implementation::Public;
| true |
65a99d6680305f6a5261a833e0e9481475061db8 | C++ | NITROGENousFish/clp-core | /src/VariableDictionaryWriter.hpp | UTF-8 | 1,415 | 3.078125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef VARIABLEDICTIONARYWRITER_HPP
#define VARIABLEDICTIONARYWRITER_HPP
// Project headers
#include "Defs.h"
#include "DictionaryWriter.hpp"
#include "VariableDictionaryEntry.hpp"
/**
* Class for performing operations on variable dictionaries and writing them to disk
*/
class VariableDictionaryWriter : public DictionaryWriter<variable_dictionary_id_t, VariableDictionaryEntry> {
public:
// Types
class OperationFailed : public TraceableException {
public:
// Constructors
OperationFailed (ErrorCode error_code, const char* const filename, int line_number) : TraceableException (error_code, filename, line_number) {}
// Methods
const char* what () const noexcept override {
return "VariableDictionaryWriter operation failed";
}
};
// Methods
/**
* Opens dictionary, loads entries, and then sets it up for writing
* @param dictionary_path
* @param segment_index_path
* @param max_id
*/
void open_and_preload (const std::string& dictionary_path, const std::string& segment_index_path, variable_dictionary_id_t max_id);
/**
* Adds an entry to the dictionary if it doesn't exist, or increases its occurrence count if it does
* @param value
* @param id
*/
bool add_occurrence (const std::string& value, variable_dictionary_id_t& id);
};
#endif // VARIABLEDICTIONARYWRITER_HPP
| true |
2b3666d91a9dbec6f584560de41151974d660c2c | C++ | Fanny94/ParticleEditorExport | /Gear/staticNonModels.h | UTF-8 | 2,905 | 2.859375 | 3 | [] | no_license | #pragma once
#include "BaseIncludes.h"
#include "ShaderProgram.h"
#include "TextureAsset.h"
class staticNonModels {
GLuint VBO, iVBO;
int nrDiffValues;
int* dataSizes;
int dataStride;
int iVBOsize;
ShaderType shader;
ShaderProgram* programRef;
glm::mat4* worldMatRef;
public:
/*
VBO = Vertex Buffer Object
iVBO = index Vertex Buffer Object
nrDiffValues = Diffrent in values ex: (1=Positions, 2= Positions, UV)
dataSizes = Array with sizes of the nrDiffValues, ex: (for position an normal:
[0]=3, [1] = 2
//iVBOsize = index Buffer Size / data type
//What shader u want to draw this model in
*/
GEAR_API staticNonModels(GLuint VBO, GLuint iVBO,
int nrDiffValues, int* dataSizes,
int iVBOsize, ShaderType shader,
glm::mat4 *worldMat) {
this->VBO = VBO;
this->iVBO = iVBO;
this->nrDiffValues = nrDiffValues;
this->dataSizes = dataSizes;
this->iVBOsize = iVBOsize;
this->shader = shader;
this->worldMatRef = worldMat;
this->dataStride = 0;
for (size_t i = 0; i < nrDiffValues; i++)
{
this->dataStride += dataSizes[i];
}
}
GEAR_API staticNonModels(GLuint VBO, GLuint iVBO,
int nrDiffValues, int* dataSizes,
int iVBOsize, ShaderType shader) {
this->VBO = VBO;
this->iVBO = iVBO;
this->nrDiffValues = nrDiffValues;
this->dataSizes = dataSizes;
this->iVBOsize = iVBOsize;
this->shader = shader;
this->dataStride = 0;
for (size_t i = 0; i < nrDiffValues; i++)
{
this->dataStride += dataSizes[i];
}
}
GEAR_API ~staticNonModels() {
delete dataSizes;
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &iVBO);
}
GEAR_API ShaderType getShaderType() {
return this->shader;
}
GEAR_API glm::mat4 getWorldMat() {
return *this->worldMatRef;
}
GEAR_API void addShaderProgramRef(ShaderProgram* refProg) {
this->programRef = refProg;
}
GEAR_API ShaderProgram* getShaderProgram() {
return this->programRef;
}
GEAR_API void drawAsLines() {
glBindBuffer(GL_ARRAY_BUFFER, VBO);
for (size_t i = 0; i < nrDiffValues; i++)
{
glEnableVertexAttribArray(i);
int dataSize = dataSizes[i];
int offset = ((i > 0) ? dataSizes[i - 1] : 0);
glVertexAttribPointer(i, dataSize, GL_FLOAT, GL_FALSE, sizeof(float) * dataStride, (void*)(sizeof(float) *offset));
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iVBO);
glDrawElements(GL_LINES, iVBOsize, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
GEAR_API void draw() {
glBindBuffer(GL_ARRAY_BUFFER, VBO);
for (size_t i = 0; i < nrDiffValues; i++)
{
glEnableVertexAttribArray(i);
int dataSize = dataSizes[i];
int offset = ((i > 0) ? dataSizes[i - 1] : 0);
glVertexAttribPointer(i, dataSize, GL_FLOAT, GL_FALSE, sizeof(float) * dataStride, (void*)(sizeof(float) *offset));
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iVBO);
glDrawElements(GL_TRIANGLES, iVBOsize, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
}; | true |
66a7c7321f118e9c5eed4a2ecfe89a2b1743ec19 | C++ | xushangning/sjtu-oj-ans | /src/1214.cpp | UTF-8 | 15,470 | 3.65625 | 4 | [] | no_license | #include <iostream>
template <typename T>
class forward_list
{
private:
struct node
{
T key;
node * next;
};
int var_size;
node * head, * tail;
public:
class const_iterator
{
private:
const node * p;
public:
const_iterator() = default;
const_iterator(const node * p_) noexcept : p(p_) {}
const_iterator operator++() noexcept { return p = p->next; }
const_iterator operator++(int) noexcept
{
node * temp = p;
p = p->next;
return temp;
}
const T & operator*() const noexcept { return p->key; }
};
forward_list() noexcept : var_size(0), head(nullptr), tail(nullptr) {}
~forward_list();
int size() const noexcept { return var_size; }
bool empty() const noexcept { return !var_size; }
T& front() noexcept { return head->key; }
const T& front() const noexcept { return head->key; }
T& back() noexcept { return tail->key; }
const T& back() const noexcept { return tail->key; }
void push_back(const T& value);
void push_back(T&& value);
void pop_front();
};
template <typename T>
forward_list<T>::~forward_list()
{
node * temp;
while (head) {
temp = head;
head = head->next;
delete temp;
}
}
template <typename T>
void forward_list<T>::push_back(const T& value)
{
if (head)
tail = tail->next = new node {value, nullptr};
else
head = tail = new node {value, nullptr};
++var_size;
}
template <typename T>
void forward_list<T>::push_back(T&& value)
{
if (head)
tail = tail->next = new node {value, nullptr};
else
head = tail = new node {value, nullptr};
++var_size;
}
template <typename T>
void forward_list<T>::pop_front()
{
// assume list non-empty
node * temp = head;
if (head == tail)
head = nullptr;
else
head = head->next;
delete temp;
--var_size;
}
template <typename T, typename Container = forward_list<T>>
class queue
{
protected:
Container c;
public:
T& front() { return c.front(); }
const T& front() const { return c.front(); }
T& back() { return c.back(); }
const T& back() const { return c.back(); }
bool empty() const { return c.empty(); }
int size() const { return c.size(); }
void push(const T& value) { c.push_back(value); }
void push(T&& value) { c.push_back(value); }
void pop() { c.pop_front(); }
};
template <typename T>
class rforward_list
{
private:
struct node
{
T data;
node * next;
};
int var_size;
node * tail;
public:
class const_iterator
{
private:
const node * p;
public:
const_iterator() = default;
const_iterator(const node * p_) noexcept : p(p_) {}
const_iterator operator++() noexcept { return p = p->next; }
const_iterator operator++(int) noexcept
{
node * temp = p;
p = p->next;
return temp;
}
const T & operator*() const noexcept { return p->data; }
};
rforward_list() noexcept : var_size(0), tail(nullptr) {}
~rforward_list();
int size() const noexcept { return var_size; }
bool empty() const noexcept { return !var_size; }
T& back() noexcept { return tail->data; }
const T& back() const noexcept { return tail->data; }
void push_back(const T& value);
void push_back(T&& value);
void pop_back();
};
template <typename T>
rforward_list<T>::~rforward_list()
{
node * temp;
while (tail)
{
temp = tail;
tail = tail->next;
delete temp;
}
}
template <typename T>
void rforward_list<T>::push_back(const T& value)
{
if (empty())
tail = new node {value, nullptr};
else
tail = new node {value, tail};
++var_size;
}
template <typename T>
void rforward_list<T>::push_back(T&& value)
{
if (empty())
tail = new node {value, nullptr};
else
tail = new node {value, tail};
++var_size;
}
template <typename T>
void rforward_list<T>::pop_back()
{
if (!empty()) {
if (tail->next) {
node * temp = tail;
tail = tail->next;
delete temp;
}
else {
delete tail;
tail = nullptr; // must be set to the null pointer
}
--var_size;
}
}
template <typename T, typename Container = rforward_list<T>>
class stack
{
public:
const T& top() const { return c.back(); }
T& top() { return c.back(); }
bool empty() const { return c.empty(); }
int size() const { return c.size(); }
void push(const T& value) { return c.push_back(value); }
void push(T&& value) { return c.push_back(value); }
void pop() { return c.pop_back(); }
protected:
Container c;
};
template <typename T>
class linked_binary_tree
{
public:
class node
{
private:
T key;
node * p, * left, * right;
public:
node() noexcept : p(nullptr), left(nullptr), right(nullptr) {}
node(const T& key_, node * left_ = nullptr, node * right_ = nullptr) noexcept
: key(key_), left(left_), right(right_) {}
int degree() const noexcept { return bool(left) + bool(right); }
friend class linked_binary_tree;
};
enum class traversal_order {pre, in, level};
private:
node * root;
/**
* An interface for iterators that iterate on nodes
*/
class node_iterator
{
public:
virtual ~node_iterator() = default;
virtual node_iterator& operator++() = 0;
virtual node * operator*() const noexcept = 0;
};
/**
* A preorder iterator
*/
class node_iterator_preorder : public node_iterator
{
private:
stack<node *> s;
public:
node_iterator_preorder(node * root)
{
if (root)
s.push(root);
}
node_iterator_preorder& operator++();
node * operator*() const noexcept { return s.top(); }
bool operator==(const node_iterator_preorder& ni) const noexcept
{
// Two preorder iterators are equal if and only if
// their stacks both are empty.
return s.empty() && ni.s.empty();
}
};
class node_iterator_inorder : public node_iterator
{
private:
stack<node *> s;
public:
node_iterator_inorder(node * root);
node * operator*() const noexcept { return s.top(); }
node_iterator_inorder& operator++();
bool operator==(const node_iterator_inorder& ni) const noexcept
{
// Two inorder iterators are equal if and only if
// their stacks both are empty.
return s.empty() && ni.s.empty();
}
};
/**
* A level-order iterator for trees with more than two branches
*/
class node_iterator_levelorder : public node_iterator
{
private:
queue<node *> q;
public:
node_iterator_levelorder(node * root)
{
if (root)
q.push(root);
}
node * operator*() const noexcept { return q.front(); }
node_iterator_levelorder& operator++();
bool operator==(const node_iterator_levelorder& ni) const noexcept
{
// Two level-order iterators are equal if and only if
// their queues both are empty.
return q.empty() && ni.q.empty();
}
};
public:
/**
* An iterator class that iterates on keys. Internally, there is a pointer
* to node_iterator, ni, that decides which node_iterator to use. The
* iterator iterates on nodes and returns keys if deferenced.
*
* Static iterators like preorder_end indicate past-the-end. They are
* returned by reference by linked_binary_tree::end().
*/
class iterator
{
private:
traversal_order order;
node_iterator * ni;
public:
iterator(node * root, traversal_order order_ = traversal_order::pre);
iterator(const iterator& i);
~iterator() { delete ni; }
iterator& operator++()
{
++*ni;
return *this;
}
T& operator*() const noexcept { return (**ni)->key; }
bool operator==(const iterator& i) const noexcept;
bool operator!=(const iterator& i) const noexcept { return !(*this == i); }
// for indicating past-the-end
static iterator preorder_end;
static iterator inorder_end;
static iterator levelorder_end;
};
linked_binary_tree(node * root_) noexcept : root(root_) {}
iterator begin(traversal_order order = traversal_order::pre) { return iterator(root, order); }
iterator& end(traversal_order order = traversal_order::pre) noexcept;
static node * link_nodes(node * nodes, int arr_size, bool read_key = true);
};
template <typename T>
typename linked_binary_tree<T>::node_iterator_preorder&
linked_binary_tree<T>::node_iterator_preorder::operator++()
{
node * n = s.top();
s.pop();
if (n->right)
s.push(n->right);
if (n->left)
s.push(n->left);
return *this;
}
template <typename T>
linked_binary_tree<T>::node_iterator_inorder::node_iterator_inorder(node * root)
{
// find and put the leftmost node at top
while (root) {
s.push(root);
root = root->left;
}
}
template <typename T>
typename linked_binary_tree<T>::node_iterator_inorder&
linked_binary_tree<T>::node_iterator_inorder::operator++()
{
// The left subtree of the node at the top of the stack must have been
// traversed, so we only deal with the right subtree.
node * n = s.top();
s.pop();
// if right not null, traverse the right subtree
if (n->right) {
s.push(n = n->right);
while (n->left) // find the leftmost node in the right subtree
s.push(n = n->left);
}
// else, having popped the node, get back to its parent
return *this;
}
template <typename T>
typename linked_binary_tree<T>::node_iterator_levelorder&
linked_binary_tree<T>::node_iterator_levelorder::operator++()
{
node * n = q.front();
if (n->left)
q.push(n->left); // enqueue next level
if (n->right)
q.front() = n->right; // modify the front element
else
q.pop(); // go down one level
return *this;
}
template <typename T>
linked_binary_tree<T>::iterator::iterator(node * root, traversal_order order_)
: order(order_)
{
switch (order)
{
case traversal_order::pre:
ni = new node_iterator_preorder(root);
break;
case traversal_order::in:
ni = new node_iterator_inorder(root);
break;
case traversal_order::level:
ni = new node_iterator_levelorder(root);
break;
}
}
template <typename T>
linked_binary_tree<T>::iterator::iterator(const iterator& i) : order(i.order)
{
switch (order)
{
case traversal_order::pre:
ni = new node_iterator_preorder(* dynamic_cast<const node_iterator_preorder *>(i.ni));
break;
case traversal_order::in:
ni = new node_iterator_inorder(* dynamic_cast<const node_iterator_inorder *>(i.ni));
break;
case traversal_order::level:
ni = new node_iterator_levelorder(* dynamic_cast<const node_iterator_levelorder *>(i.ni));
break;
}
}
template <typename T>
bool linked_binary_tree<T>::iterator::operator==(const iterator& i) const noexcept
{
if (order != i.order)
return false;
else
switch (order)
{
case traversal_order::pre:
return * dynamic_cast<const node_iterator_preorder *>(ni)
== * dynamic_cast<const node_iterator_preorder *>(i.ni);
case traversal_order::in:
return * dynamic_cast<const node_iterator_inorder *>(ni)
== * dynamic_cast<const node_iterator_inorder *>(i.ni);
case traversal_order::level:
return * dynamic_cast<const node_iterator_levelorder *>(ni)
== * dynamic_cast<const node_iterator_levelorder *>(i.ni);
}
}
template <typename T>
typename linked_binary_tree<T>::iterator
linked_binary_tree<T>::iterator::preorder_end(nullptr);
template <typename T>
typename linked_binary_tree<T>::iterator
linked_binary_tree<T>::iterator::inorder_end(nullptr, traversal_order::in);
template <typename T>
typename linked_binary_tree<T>::iterator
linked_binary_tree<T>::iterator::levelorder_end(nullptr, traversal_order::level);
template <typename T>
typename linked_binary_tree<T>::iterator&
linked_binary_tree<T>::end(traversal_order order) noexcept
{
switch (order)
{
case traversal_order::pre:
return iterator::preorder_end;
case traversal_order::in:
return iterator::inorder_end;
case traversal_order::level:
return iterator::levelorder_end;
}
}
/**
* Link nodes in an array together to form a tree based on input in the form
* <node-index> <node-index> <key>
* from standard input.
*
* nodes: the array of nodes
* arr_size: the size of the array
* read_key: read <key> if true. true by default.
*
* return: the root in the array of nodes
*/
template <typename T>
typename linked_binary_tree<T>::node *
linked_binary_tree<T>::link_nodes(node * nodes, int arr_size, bool read_key)
{
int left, right;
// <node-index> == 0 for no child
// == i (i = 1, ..., arr_size) for node[i]
if (read_key)
for (int i = 0; i < arr_size; ++i) {
std::cin >> left >> right >> nodes[i].key;
if (left) {
nodes[i].left = &nodes[left - 1];
nodes[left - 1].p = &nodes[i];
}
if (right) {
nodes[i].right = &nodes[right - 1];
nodes[right - 1].p = &nodes[i];
}
}
else
for (int i = 0; i < arr_size; ++i) {
std::cin >> left >> right;
if (left) {
nodes[i].left = &nodes[left - 1];
nodes[left - 1].p = &nodes[i];
}
if (right) {
nodes[i].right = &nodes[right - 1];
nodes[right - 1].p = &nodes[i];
}
}
// find the root in the array of nodes
node * root;
for (root = nodes; root->p; root = root->p);
return root;
}
int main()
{
std::ios_base::sync_with_stdio(false);
int tree_size;
std::cin >> tree_size;
linked_binary_tree<int>::node nodes[tree_size];
linked_binary_tree<int> t(linked_binary_tree<int>::link_nodes(nodes, tree_size));
for (linked_binary_tree<int>::iterator i = t.begin(); i != t.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
for (linked_binary_tree<int>::iterator i = t.begin(linked_binary_tree<int>::traversal_order::in);
i != t.end(linked_binary_tree<int>::traversal_order::in); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
for (linked_binary_tree<int>::iterator i = t.begin(linked_binary_tree<int>::traversal_order::level);
i != t.end(linked_binary_tree<int>::traversal_order::level); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
return 0;
}
| true |
7be8a89dca1babc0df7a378c34bf1e0e4cc2d641 | C++ | ioqoo/PS | /sublime/3653_fenwick_applied.cpp | UTF-8 | 1,496 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pdd pair<double, double>
#define piii pair<pair<int, int>, int>
#define pddi pair<pair<double, double>, int>
#define plll pair<pair<ll, ll>, ll>
#define vb vector<bool>
#define vi vector<int>
#define vl vector<ll>
#define vpii vector<pii>
#define vpdd vector<pdd>
#define fi first
#define se second
#define INF 1000000000000000000LL
#define MAX 987654321
using namespace std;
//https://www.acmicpc.net/problem/3653
//아이디어 : 숫자가 n개, 빼서 맨 앞에 두는 횟수가 m -> n+m+1개의 배열 준비
//ind 배열로 k번이 n+m+1 배열에서 ind를 뭘로 가지는지 저장
ll sum(vector<ll> &tree, int i){
ll ans = 0LL;
while(i > 0){
ans += tree[i];
i -= (i & -i);
}
return ans;
}
void update(vector<ll> &tree, int i, int diff){
while(i < tree.size()){
tree[i] += diff;
i += (i & -i);
}
}
int main() {
int T;
scanf("%d", &T);
for (int x=0;x<T;x++){
int n, m;
scanf("%d %d", &n, &m);
vb check(n+m+1);
vl f_tree(n+m+1);
vl ind(n+1);
for (int i=1;i<=n;i++){
ind[i] = i+m;
}
for (int i=m+1;i<=n+m;i++){
check[i] = true;
update(f_tree, i, 1);
}
for (int i=0;i<m;i++){
int temp;
scanf("%d", &temp);
printf("%lld ", sum(f_tree, ind[temp]-1) - sum(f_tree, m-i));
check[ind[temp]] = false;
check[m-i] = true;
update(f_tree, ind[temp], -1);
update(f_tree, m-i, 1);
ind[temp] = m-i;
}
printf("\n");
}
}
| true |
7e236ec11de990d0ae01f5fead7f5afb3b17f896 | C++ | r0cket007/450_DSA_Question | /Search & Sort/find_pair_given_difference.cpp | UTF-8 | 1,334 | 3.296875 | 3 | [] | no_license | /*
Find Pair Given Difference
Link: https://practice.geeksforgeeks.org/problems/find-pair-given-difference1559/1#
Expected Time Complexity: O(L*Log(L)).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ L ≤ 104
1 ≤ Arr[i], N ≤ 105
*/
#include<bits/stdc++.h>
#define int long long
using namespace std ;
//--------------------------------------------------------------------
bool findPair(int arr[], int size, int n)
{
sort(arr, arr + size);
for(int i = 0; i < size - 1; i ++)
{
int target = n + arr[i];
int l = i + 1;
int r = size - 1;
while(l <= r)
{
int mid = l + (r - l) / 2;
if(arr[mid] == target)
{
return true;
}
if(arr[mid] > target)
{
r = mid - 1;
}
else
l = mid + 1;
}
}
return false;
}
//--------------------------------------------------------------------
signed main()
{
int testcases = 1 ;
// cin >> testcases ;
while( testcases -- )
{
int size = 6, n = 78;
int arr[] = {5, 20, 3, 2, 5, 80};
cout << (findPair(arr, size, n) ? 1 : -1);
cout << endl ;
}
return 0 ;
} | true |
b1db7e30697a8a6a1360dffe84ed5f1a1aeb3461 | C++ | raphsbeans/CudaPDE | /PDE_Solver/BulletOption.h | UTF-8 | 1,278 | 2.640625 | 3 | [] | no_license | #pragma once
#include "Payoff.h"
#include <vector>
class BulletOption : public Payoff {
public:
BulletOption(float strike, size_t daysToMaturity, float barrier, size_t P1, size_t P2, const std::vector<size_t>& scheduleDays);
void setCurrPosition(float currSpot, size_t currState);
virtual void initPayoff(float* payoff, ParamsLocation paramsLocation = ParamsLocation::DEVICE);
virtual void interStep(float* payoff, size_t timeIdx);
virtual float applySolution(float* sol);
virtual void getSpotRange(float& sMin, float& sMax);
virtual void getGridSizes(size_t& spotGridSize, size_t& timeGridSize, size_t& stateSize);
float currentPrice;
private:
// current position
float currSpot; // Current Spot
size_t currState; // Current State Variable
// Payoff related
size_t daysToMaturity; //Only working days
float strike; //Strike
float P1; //Minimum Times heating Barrier
float P2; //Maximum Times heating Barrier
float barrier;
std::vector<bool> isSchedule;
size_t scheduleCounter;
// Grid related
size_t spotGridSize;
size_t timeGridSize;
size_t stateSize;
float Smin; //Minimum value in the spot grid
float Smax; //Maximum value in the spot grid
float dx; //infinitesimal value for the spot grid
float dt; //infinitesimal -> grid time
};
| true |
4134b67bd8b5042ef4959dfadfa04242a2446431 | C++ | BramGiesen/guitarSynth | /zerox.cpp | UTF-8 | 710 | 2.75 | 3 | [] | no_license | //
// zerox.cpp
// GuitarSynth_2
//
// Created by Bram Giesen on 05-06-18.
//
#include "zerox.hpp"
Zerox::Zerox()
{
}
Zerox::~Zerox()
{
}
void Zerox::calculate(double aSignal)
{
//it compares the current signal with the previous signal. If one is positif and the other negatif it detects a
//zero crossing
if(count < signalVectorSize){
if((aSignal >= 0.0 && previousSignal <= 0.0)||(aSignal <= 0.0 && previousSignal >= 0.0))
{
zeroxRate += 1.0;
previousSignal = aSignal;
}
count++;
} else {
zeroxOut = (zeroxRate >= 2.0) ? 2 : 1;
zeroxRate = 0.0;
count = 0;
}
}
int Zerox::getZerox()
{
return zeroxOut;
}
| true |
bb2963ea48610125d65ae214f3990b656101d210 | C++ | carlberyeur/HellowGlengine | /Source/CommonUtilities/SerializerSaver.h | UTF-8 | 1,111 | 2.53125 | 3 | [] | no_license | #pragma once
#include "Serializer.h"
namespace CU
{
class CSerializerSaver : public ISerializer
{
public:
CSerializerSaver();
CSerializerSaver(const unsigned int aBufferStartSize);
virtual ~CSerializerSaver();
void Init(const unsigned int aBufferStartSize);
virtual void Cerealize(unsigned char& aChar) override;
virtual void Cerealize(unsigned short& aShort) override;
virtual void Cerealize(unsigned int& aUInt) override;
virtual void Cerealize(int& aInt) override;
virtual void Cerealize(float& aFloat) override;
virtual void Cerealize(double& aDouble) override;
virtual void Cerealize(CU::Vector2f& aVector2f) override;
virtual void Cerealize(CU::Vector3f& aVector3f) override;
virtual void Cerealize(CU::Vector4f& aVector4f) override;
virtual void Cerealize(CU::Matrix33f& aMatrix33f) override;
virtual void Cerealize(CU::Matrix44f& aMatrix44f) override;
virtual void Cerealize(std::string& aString) override;
const CU::GrowingArray<char>& GetBuffer() const;
bool WriteFile(const std::string& aFilePath) const;
private:
CU::GrowingArray<char> myBuffer;
};
}
| true |
6295c83b1ede19aeaff82894241426238d693b4a | C++ | lxyzzzZZZ/practice | /C++ class code/4.20/4.20/源.cpp | UTF-8 | 909 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
//void Size()
//{
// size_t count = 0;
//for (const auto& e : *this)
//{
// count++;
//}
// pNode ret = _head->next;
// while (ret != _head)
// {
// count++;
// ret = _head->next;
// }
// return count;
//}
//void clear()
//{
// pNode ret = _head->next;
// while (ret != _head)
// {
// _head->next = ret->next;
// delete ret;
// ret = _head->next;
// }
// _head->next = _head;
// _head->prev = _head;
//}
//void PopBack()
//{
// erase(--end());
//}
//void PopFront()
//{
// erase(begin());
//}
//List<T>& operator=(const List<T>& l)
//{
// if (this != l)
// {
// List<T> tmp(l);
// this->swap(tmp);
// }
// return *this;
//}
//List(const List<T>& L)
//{
// _head = new Node();
// _head->next = _head;
// _head->prev = _head;
//
// List<T> tmp(L.begin(),L.end());
// swap(_head,tmp._head);
// while(const auto& e : L)
// {
// PushBack(e._val);
// }
//}
| true |
a068c625c53a8e5acd06ef433cf1c342c18483ac | C++ | simranbal04/MarkingitusApp | /InternetButton.ino | UTF-8 | 2,390 | 2.734375 | 3 | [] | no_license | // This #include statement was automatically added by the Particle IDE.
#include <InternetButton.h>
// Make an InternetButton object
InternetButton button = InternetButton();
void setup()
{
button.begin();
Particle.function("Time",second);
for ( int i = 0; i < 3; i++)
{
button.allLedsOn(255,0,0);
delay(250);
button.allLedsOff();
delay(250);
}
}
int DELAY = 1000;
int second(String cmd)
{
int sec = cmd.toInt();
// if(sec>0 && sec<6)
if(sec == 0)
{
// button.ledOff(11);
button.ledOn(1,165,42,42);
button.ledOn(11,165,42,42);
for( int i = 3; i <= 9; i++)
{
button.ledOn(i,165,42,42);
// button.ledOn(4,165,42,42);
}
delay(DELAY);
// to turn off all the leds
button.allLedsOff();
delay(DELAY);
}
if(sec>=1 && sec<=4)
{
// button.ledOff(3);
// button.ledOff(9);
button.ledOn(1,201,255,229);
button.ledOn(11,201,255,229);
for(int i = 4; i <= 8; i++)
{
button.ledOn(i,201,255,229);
}
delay(DELAY);
button.allLedsOff();
delay(DELAY);
}
if(sec>=5 && sec<=9)
{
button.ledOn(1,196,98,16);
button.ledOn(11,196,98,16);
for(int i = 5; i <= 7; i++)
{
button.ledOn(i,196,98,16);
}
delay(DELAY);
button.allLedsOff();
delay(DELAY);
// delay(DELAY);
}
if(sec>=10 && sec<=14)
{
button.ledOn(1,59,122,87);
button.ledOn(11,59,122,87);
button.ledOn(6,59,122,87);
// for(int i = 6; i <= 6; i++)
// {
// button.ledOn(i,201,255,229);
// }
delay(DELAY);
button.allLedsOff();
delay(DELAY);
// delay(DELAY);
}
if(sec>=15 && sec<=19)
{
button.ledOn(1,0,48,143);
button.ledOn(11,0,48,143);
// button.ledOn(6,201,255,229);
delay(DELAY);
button.allLedsOff();
delay(DELAY);
// delay(DELAY);
}
if(sec == 20)
{
button.allLedsOn(255,0,0);
delay(DELAY);
button.allLedsOff();
delay(DELAY);
// delay(DELAY);
}
}
void loop() {
}
| true |
dda5fd741bb7abfb126ce9f37d7abed0e2d1d632 | C++ | nkonjeti/pool | /include/player.h | UTF-8 | 3,725 | 3.375 | 3 | [] | no_license | //
// Created by neha konjeti on 5/4/21.
//
#pragma once
#include "ball.h"
#include "cinder/gl/gl.h"
namespace pool {
using pool::Ball;
using std::vector;
/**
* Class to keep track of player stats during game.
*/
class Player {
public:
/**
* Constructor to initialize player of game, such as default type of ball they
* can hit, and state of game to indicate player is playing.
*/
Player();
/**
* Enum to keep track of player game state.
* won : if they got all the balls needed to win.
* lost : hit eight ball or wrong type of ball into hole.
* playing: in progress of playing game.
*/
enum GameState { won, lost, playing };
/**
* Adds one to total count of balls scored,
* when player scores 7 balls of same type and eight ball
* they win.
*/
void AddBallScore();
/**
* Displays balls scored by player above game board
* so they remember which ones they need to win.
* @param images to draw each ball player scored.
*/
void DisplayBalls(vector<ci::gl::Texture2dRef> images) const;
/**
* Adds the number of the ball that the player scored to vector
* which keeps track of these numbers to display above game board.
* @param ball_number represents number of the ball scored
* and used for the index of the images vector.
*/
void AddBallNumberScored(size_t ball_number);
/**
* Get vector of all the ball numbers that the player hit into hole,
* should be empty at start of game.
* @return vector of ball numbers the player scored.
*/
vector<size_t> GetBallNumbers() const;
/**
* The ball type that is determined when the player first scores
* stripes or solid, player needs to score all balls of same type to win.
* @return
*/
Ball::Type GetBallTypeToScore() const;
/**
* Sets the ball type the player can hit in the game, determined by the first
* ball the player scores.
* @param type : striped or solid.
*/
void SetBallTypeToScore(Ball::Type type);
/**
* Get the number of balls the player has scored, to know if the player has
* won after hitting the eight ball, or lost if player hasn't gotten all balls
* of same type before hitting eight ball.
* @return
*/
size_t GetPlayerScore() const;
/**
* Set the game state of the player, used to change game state of player after
* winning or losing.
* @param state representing if player is playing, or has won or lost.
*/
void SetGameState(GameState state);
/**
* Get the current game state of the game to determine what is displayed in
* the game.
* @return GameState if player is playing or has lost or won.
*/
GameState GetGameState() const;
/**
* Resets player information such as type of ball they can score, number of
* balls they scored, and the ball numbers they hit into the hole for new
* game.
*/
void ResetPlayer();
private:
// how many balls the player had scored of the same type
// player needs to score all the ball of the same type to win
size_t num_balls_scored_ = 0;
// the type of the ball the player can hit, determined by the first shot
// if player hits wrong type of ball into hole, they lose the game
Ball::Type type_;
// keeps track of the ball numbers so the balls the player scored can be
// displayed and the images vector uses the ball numbers as indices.
vector<size_t> ball_numbers_scored_ = {};
// stores current state of game : playing, lost, won
// so player can play again after losing/ winning
// and have access to controls when in playing state
GameState state_;
// set space between balls the player scored in display above pool board
double const kSpaceBetweenBalls = 100;
};
} // namespace pool | true |
9f9ca4e7b4095e5df29fb132170af88035225057 | C++ | brenthompson2/Compiler-Construction | /Project 8/CompilerCommands/tSUBP.cpp | UTF-8 | 14,572 | 2.609375 | 3 | [] | no_license | /*
==============================================================================
File: tSUBP.cpp
Author: Brendan Thompson
Updated: 10/29/17
Description: Implementation of Functions for processing SUBP command for Compiler object made for Transylvania University University Fall Term 2017 Compiler Construction class
==============================================================================
*/
#include "tSUBP.h"
/* ==============================================================================
Constructor & Destructor
============================================================================== */
tSUBP::tSUBP(){
return;
}
tSUBP::~tSUBP(){
return;
}
/* ==============================================================================
Public Manipulator Methods
============================================================================== */
// Connects local pointer to FileManager and SymbolTable with the parent's (compiler's) versions
void tSUBP::prepareSUBP(FileManager *parentFileManager, SymbolTable *parentMemoryManager){
currentFileManager = parentFileManager;
currentMemoryManager = parentMemoryManager;
}
// calls the functions necessary to parse the line, sync the variables with the SymbolTable, and print the object code to the file while counting errors
// returns num errors
int tSUBP::handleSUBP(string currentLine, int correspondingLineNumber){
globalCurrentLine = currentLine;
// cout << "\t\t[SUBP]: Compiling Line: " << globalCurrentLine << endl;
globalNumErrors = 0;
parseParameters();
// printVariableArray();
syncVariablesToSymbolTable();
if (globalNumErrors == 0){
outputSUBPCommand();
// cout << "\t\t[SUBP]: Successfully completed SUBP command\n";
}
else {
cout << "\t\t[SUBP]: Failed to complete SUBP command with " << globalNumErrors << " errors\n";
}
return globalNumErrors;
}
/* ==============================================================================
Private Methods
============================================================================== */
// tells the memoryManager to conditionally add the global memoryTableObject arguments to the symbol table
void tSUBP::syncVariablesToSymbolTable(){
// cout << "\t\t[SUBP]: Attempting to Add Arguments to Lookup Table...\n";
globalVariable.isArray = false;
globalVariable.size = 1;
secondID.isArray = false;
secondID.size = 1;
(*currentMemoryManager).manageMemoryTableObject(&globalVariable);
(*currentMemoryManager).manageMemoryTableObject(&secondID);
// (*currentMemoryManager).printSymbolTable();
return;
}
// tells the FileManager to print the object code for the command, which includes the command op code and the variable memoryLocations
void tSUBP::outputSUBPCommand(){
// cout << "\t\t[SUBP]: Attempting to Print Object code to .obj...\n";
(*currentFileManager).writeStringToObj(SUBP_OP_CODE);
(*currentFileManager).writeStringToObj(" ");
(*currentFileManager).writeNumToObj(globalOperation);
(*currentFileManager).writeStringToObj(" ");
(*currentFileManager).writeNumToObj((double) globalVariable.memoryLocation);
(*currentFileManager).writeStringToObj(" ");
(*currentFileManager).writeNumToObj((double) secondID.memoryLocation);
(*currentFileManager).writeStringToObj("\n");
return;
}
/* ==============================================================================
Private Parsing Methods
============================================================================== */
// conditionally calls parseVariable(), parseConstant(), and parseLineLabelName()
void tSUBP::parseParameters(){
bool continueParsingParameters = true;
int currentCharIterator = INDEX_FIRST_CHAR_AFTER_SUBP_COMMAND;
string currentArrayName;
char currentChar = globalCurrentLine[currentCharIterator];
// Parse Operation
parseOperation(¤tCharIterator);
// Handle First "("
currentChar = globalCurrentLine[currentCharIterator];
if (currentChar != '('){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting (<variable>, <id>) : " << globalCurrentLine << endl;
globalNumErrors++;
continueParsingParameters = false; // comment out to continue checking rest of line for errors
}
currentCharIterator++;
// Get Variable
if (!continueParsingParameters){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting A Variable: " << globalCurrentLine << endl;
globalNumErrors++;
}
else {
continueParsingParameters = parseVariable(¤tCharIterator, VARIABLE_ID_CODE);
}
// Get Second ID
if (!continueParsingParameters){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting Second Condition: " << globalCurrentLine << endl;
globalNumErrors++;
}
else {
currentChar = globalCurrentLine[currentCharIterator];
if ((isdigit(currentChar)) || (currentChar == '.') || (currentChar == '-')){
continueParsingParameters = parseConstant(¤tCharIterator, OTHER_ID_CODE);
}
else {
continueParsingParameters = parseVariable(¤tCharIterator, OTHER_ID_CODE);
}
}
// Should be end of line
if (continueParsingParameters){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting End Of Line: " << globalCurrentLine << endl;
globalNumErrors++;
}
return;
}
// parses through a line one character at a time, manages the global member variable associated with the parameterNumber, and returns whether or not there are any more parameters to parse
bool tSUBP::parseVariable(int *currentCharIterator, int parameterNumber){
// cout << "\t\t\t[SUBP]: Parsing Variable...\n";
char currentChar;
string currentVariableName = "";
int numCharactersInVarName = 0;
bool continueParsingVariable = true;
bool isNotLastParameter = false;
bool isValidVariableName = true;
bool caseFound;
while (continueParsingVariable){
currentChar = globalCurrentLine[(*currentCharIterator)];
caseFound = false;
// cout << "\t\t\t[SUBP]: Current Character: " << currentChar << endl;
// Alphabetic
if (isalpha(currentChar)){
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// Digit
if (isdigit(currentChar)){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Variable names can not start with a digit: " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// Underscore
if (currentChar == '_'){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Variables can not start with an underscore: " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// Comma
if (currentChar == ','){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting (<variable>, <ID>): " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
if (parameterNumber == OTHER_ID_CODE){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting ) instead of , : " << globalCurrentLine << endl;
globalNumErrors++;
}
continueParsingVariable = false;
isNotLastParameter = true;
(*currentCharIterator)++;
caseFound = true;
}
// End Parenthesis
if (currentChar == ')'){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting (<variable>, <ID>): " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
if (parameterNumber == VARIABLE_ID_CODE){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting , before ) : " << globalCurrentLine << endl;
globalNumErrors++;
}
continueParsingVariable = false;
isNotLastParameter = true;
(*currentCharIterator)++;
if (globalCurrentLine[(*currentCharIterator)] == '\0'){
isNotLastParameter = false;
}
caseFound = true;
}
// End Of Line
if (currentChar == '\0'){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting (<variable>, <ID>): " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
else {
if (parameterNumber == VARIABLE_ID_CODE){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting , before End of Line: " << globalCurrentLine << endl;
globalNumErrors++;
}
if (parameterNumber == OTHER_ID_CODE){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting ) before End of Line : " << globalCurrentLine << endl;
globalNumErrors++;
}
}
continueParsingVariable = false;
isNotLastParameter = false;
caseFound = true;
}
if (!caseFound){
cout << "\t\t\t[SUBP]: Invalid Syntax: Unknown Character ->" << currentChar << "<- in line: " << globalCurrentLine << endl;
(*currentCharIterator)++;
globalNumErrors++;
}
}
// Assign to Global Parameter Name
if (isValidVariableName){
switch (parameterNumber){
case VARIABLE_ID_CODE:
globalVariable.variableName = currentVariableName;
break;
case OTHER_ID_CODE:
secondID.variableName = currentVariableName;
secondID.isConstant = false;
break;
}
}
return isNotLastParameter;
}
// parses through a line one character at a time, manages the global member variable associated with the parameterNumber, and returns whether or not there are any more parameters to parse
bool tSUBP::parseConstant(int *currentCharIterator, int parameterNumber){
// cout << "\t\t[SUBP]: Parsing Constant...\n";
char currentChar;
string currentVariableName = "";
int numCharactersInVarName = 0;
bool continueParsingVariable = true;
bool isNotLastParameter = false;
bool isValidVariableName = true;
bool readingDecimal = false;
bool caseFound;
// Handle Negatives
currentChar = globalCurrentLine[(*currentCharIterator)];
if (currentChar == '-'){
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
// cout << "\t\t\t[CDUMP]: Current Variable Name: " << currentVariableName << endl;
}
while (continueParsingVariable){
currentChar = globalCurrentLine[(*currentCharIterator)];
caseFound = false;
// cout << "\t\t\t[SUBP]: Current Character: " << currentChar << endl;
// Alphabetic
if (isalpha(currentChar)){
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// Digit
if (isdigit(currentChar)){
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// Decimal Point
if (currentChar == '.'){
if (readingDecimal){
cout << "\t\t\t[SUBP]: Invalid Syntax: Multiple Decimal Points in One Constant: " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
isNotLastParameter = true;
}
else {
readingDecimal = true;
currentVariableName += currentChar;
numCharactersInVarName++;
(*currentCharIterator)++;
}
caseFound = true;
// cout << "\t\t\t[SUBP]: Current Variable Name: " << currentVariableName << endl;
}
// End Parenthesis
if (currentChar == ')'){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting an ID instead of ) " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
continueParsingVariable = false;
isNotLastParameter = true;
(*currentCharIterator)++;
if (globalCurrentLine[(*currentCharIterator)] == '\0'){
isNotLastParameter = false;
}
caseFound = true;
}
// End Of Line
if (currentChar == '\0'){
if (numCharactersInVarName == 0){
cout << "\t\t\t[SUBP]: Invalid Syntax: Expecting ID before End of Line: " << globalCurrentLine << endl;
isValidVariableName = false;
globalNumErrors++;
}
continueParsingVariable = false;
isNotLastParameter = false;
caseFound = true;
}
if (!caseFound){
cout << "\t\t\t[SUBP]: Invalid Syntax: Unknown Character ->" << currentChar << "<- in line: " << globalCurrentLine << endl;
(*currentCharIterator)++;
globalNumErrors++;
}
}
// Assign to Global Parameter Name
if (isValidVariableName){
secondID.variableName = currentVariableName;
secondID.isConstant = true;
}
return isNotLastParameter;
}
// parses through a line one character at a time, manages the global globalOperation
void tSUBP::parseOperation(int *currentCharIterator){
// cout << "\t\t[SUBP]: Parsing Test Cond...\n";
string operationString;
bool caseFound = false;
operationString = globalCurrentLine.substr(4, 3);
caseFound = false;
// cout << "\t\t\t[SUBP]: Matching Operation: " << operationString << "...\n";
if (operationString == "SIN"){
// cout << "\t\t\t[SUBP]: Found SIN Command\n";
caseFound = true;
globalOperation = SIN_CODE;
}
if (operationString == "COS"){
// cout << "\t\t\t[SUBP]: Found COS Command\n";
caseFound = true;
globalOperation = COS_CODE;
}
if (operationString == "EXP"){
// cout << "\t\t\t[SUBP]: Found EXP Command\n";
caseFound = true;
globalOperation = EXP_CODE;
}
if (operationString == "ABS"){
// cout << "\t\t\t[SUBP]: Found ABS Command\n";
caseFound = true;
globalOperation = ABS_CODE;
}
if (operationString == "ALG"){
// cout << "\t\t\t[SUBP]: Found ALG Command\n";
caseFound = true;
globalOperation = ALG_CODE;
}
if (operationString == "ALN"){
// cout << "\t\t\t[SUBP]: Found ALN Command\n";
caseFound = true;
globalOperation = ALN_CODE;
}
if (operationString == "LOG"){
// cout << "\t\t\t[SUBP]: Found LOG Command\n";
caseFound = true;
globalOperation = LOG_CODE;
}
if (operationString == "SQR"){
// cout << "\t\t\t[SUBP]: Found SQR Command\n";
caseFound = true;
globalOperation = SQR_CODE;
}
if (!caseFound){
cout << "\t\t\t[SUBP]: Invalid Syntax: Unknown Operation: " << operationString << endl;
globalNumErrors++;
}
(*currentCharIterator) += 3;
return;
}
/* ==============================================================================
Private Accessor Methods
============================================================================== */ | true |
f6c56a48bf669d26984fc79f63d16de87f2b7fc5 | C++ | quantity123/CppExamples | /BaseTutorial/constructionFunction/constructionFunction/main.cpp | UTF-8 | 443 | 3.5625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class book
{
public:
explicit book(string aTitle = "Book1"); //有参数的构造函数要加explicit,防止隐式创建对象 book b = "C++";
string getTitle();
private:
string mTitle;
};
book::book(string aTitle)
{
mTitle = aTitle;
}
string book::getTitle()
{
return mTitle;
}
int main()
{
//book b;
book b("Book2");
cout << b.getTitle() << endl;
return 0;
}
| true |
93171380797d3333d2e097bae45182881a466bf5 | C++ | zotvent/competitive-programming | /leetcode/algorithms/260 - Single Number III.cpp | UTF-8 | 343 | 2.84375 | 3 | [] | no_license | class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
unordered_set<int> seen;
for (auto& i: nums) {
if (seen.count(i) > 0) {
seen.erase(i);
}
else seen.insert(i);
}
return vector<int>(seen.begin(), seen.end());
}
}; | true |
39d7b04aad1cf30e6bf259b197697de7413f99df | C++ | tvxr5/Projects | /cs3130/b.cpp | UTF-8 | 572 | 3.84375 | 4 | [] | no_license | #include<iostream>
using namespace std;
// iterative version
int Fibonacci_I(int n)
{
int fib[] = {0,1,1};
for(int i=2; i<=n; i++)
{
fib[i%3] = fib[(i-1)%3] + fib[(i-2)%3];
cout << "fib(" << i << ") = " << fib[i%3] << endl;
}
return fib[n%3];
}
int main(void)
{
int a;
cout << "a = ";
cin>>a;
cout << "From iterative function" << endl;
Fibonacci_I(a);
cout << endl << "From recursive function" << endl;
return 0;
}
| true |
b82c768e43cd5b1682c2962ee567dcc3e70c0e3d | C++ | Nitrooos/Projectizer | /src/parser/COption.cpp | UTF-8 | 6,013 | 2.59375 | 3 | [] | no_license | #include "COption.hpp"
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QCheckBox>
#include <QLineEdit>
#include <QRadioButton>
#include <QButtonGroup>
#include <QComboBox>
#include <QGroupBox>
const QMap<QString, COption::EType> COption::mapping = {
{"checkbox", COption::EType::CHECKBOX},
{"text", COption::EType::TEXT},
{"radio", COption::EType::RADIO},
{"selectbox", COption::EType::SELECT}
};
void COption::fill(const QDomNode &node) {
if (node.isElement()) {
QDomNodeList names = node.toElement().elementsByTagName("name"),
ids = node.toElement().elementsByTagName("id");
if (names.size() > 0) {
_name = names.item(0).toElement().text();
}
if (ids.size() > 0) {
_id = ids.item(0).toElement().text();
}
}
}
COption *COption::getOptionPerType(const QString &type_name) {
if (COption::mapping.find(type_name) != COption::mapping.end()) {
EType type = COption::mapping[type_name];
switch (type) {
case EType::CHECKBOX:
return new COptionCheckbox();
case EType::TEXT:
return new COptionTextInput();
case EType::RADIO:
return new COptionRadioGroup();
case EType::SELECT:
return new COptionSelectBox();
}
}
return nullptr;
}
QList<QWidget*> COption::render(QWidget *parent) {
this->_widgets.clear();
if (this->_name != "") {
this->_widgets.push_back(new QLabel(this->_name, parent));
}
return this->_widgets;
}
void COptionCheckbox::fill(const QDomNode &node) {
COption::fill(node);
if (node.isElement()) {
QDomNodeList labels = node.toElement().elementsByTagName("label");
if (labels.size() > 0) {
_label = labels.item(0).toElement().text();
QDomAttr is_checked = node.attributes().namedItem("checked").toAttr();
if (!is_checked.isNull() && is_checked.value() == "true") {
_is_checked = true;
} else {
_is_checked = false;
}
}
}
}
QList<QWidget *> COptionCheckbox::render(QWidget *parent) {
this->_widgets = COption::render(parent);
QCheckBox *checkbox = new QCheckBox(this->_label, parent);
if (this->_is_checked) {
checkbox->setChecked(true);
}
this->_created_checkbox = checkbox;
this->_widgets.push_back(checkbox);
return this->_widgets;
}
QString COptionCheckbox::value() const {
if (this->_created_checkbox == nullptr) {
return "";
}
QString val = this->_created_checkbox->isChecked() ? "1" : "0";
return QString("--" + this->_id + "=" + val);
}
QList<QWidget *> COptionTextInput::render(QWidget *parent) {
this->_widgets = COption::render(parent);
auto input = new QLineEdit(parent);
this->_created_input = input;
this->_widgets.append(input);
return this->_widgets;
}
QString COptionTextInput::value() const {
if (this->_created_input == nullptr) {
return "";
}
return QString("--" + this->_id + "=\"" + this->_created_input->text() + "\"");
}
void COptionSelectable::fill(const QDomNode &node) {
COption::fill(node);
if (node.isElement()) {
QDomNodeList values_tag = node.toElement().elementsByTagName("values");
if (values_tag.size() > 0) {
QDomNodeList values = values_tag.item(0).toElement().elementsByTagName("value");
for (int i = 0; i < values.size(); ++i) {
fillValue(values.item(i));
}
}
}
}
void COptionSelectable::fillValue(const QDomNode &node) {
QDomElement value_element = node.toElement();
if (value_element.attributes().contains("id")) {
QString id = value_element.attributes().namedItem("id").toAttr().value(),
label = value_element.toElement().text();
bool is_default = false;
if (value_element.attributes().contains("default") &&
value_element.attributes().namedItem("default").toAttr().value() == "true")
{
is_default = true;
}
_values.insert(label, CValue(id, label, is_default));
}
}
QList<QWidget *> COptionRadioGroup::render(QWidget *parent) {
this->_widgets = QList<QWidget*>();
auto container = new QGroupBox(this->_name, parent);
container->setLayout(new QVBoxLayout(container));
container->layout()->setContentsMargins(0, 5, 0, 0);
auto *btn_group = new QButtonGroup(container);
for (auto radio_option : this->_values) {
auto radio = new QRadioButton(radio_option._label, container);
radio->setObjectName(radio_option._id);
btn_group->addButton(radio);
container->layout()->addWidget(radio);
if (radio_option._is_default) {
radio->setChecked(true);
}
}
this->_created_group = btn_group;
this->_widgets.push_back(container);
return this->_widgets;
}
QString COptionRadioGroup::value() const {
if (this->_created_group == nullptr) {
return "";
}
return QString("--" + this->_id + "=" + this->_created_group->checkedButton()->objectName());
}
QList<QWidget *> COptionSelectBox::render(QWidget *parent) {
this->_widgets = COption::render(parent);
auto *combo = new QComboBox(parent);
for (auto combo_option : this->_values) {
if (combo_option._is_default) {
combo->insertItem(0, combo_option._label);
combo->setCurrentIndex(0);
} else {
combo->addItem(combo_option._label);
}
}
this->_created_select = combo;
this->_widgets.push_back(combo);
return this->_widgets;
}
QString COptionSelectBox::value() const {
if (this->_created_select == nullptr) {
return "";
}
QString option_id = this->_values[this->_created_select->currentText()]._id;
return QString("--" + this->_id + "=" + option_id);
}
| true |
65e78006f45be6bd6898e33799532fae76a621f3 | C++ | souravchk/competitive-coding-2017 | /topcoder/badNeighbors.cpp | UTF-8 | 970 | 2.75 | 3 | [] | no_license | /*
* Author: Sourav Chakraborty
* <mail.souravchk@gmail.com>
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include <set>
#include <map>
#define LL long long
#define INF 1e18
#define pb push_back
#define mp make_pair
#define max(a,b) (a) > (b) ? (a): (b)
#define min(a,b) (a) < (b) ? (a): (b)
using namespace std;
/*
{ 10, 3, 2, 5, 7, 8 }
Returns: 19
*/
vector <int> donations;
int dp[]
class BadNeighbors {
public:
int SZ;
int maxDonations(vector <int> d);
int solve(int, int);
};
int BadNeighbors::solve(int i, int f) {
if (i >= SZ) return 0;
if (dp[i][f] == -1) {
int res = solve(i + 1, f);
if (!(f && i == (SZ - 1))) {
res = max(res, donations[i] + solve(i + 2, f));
}
} else {
return dp[i][f];
}
}
int BadNeighbors::maxDonations(vector <int> d) {
donations = d;
SZ = donations.size();
int res = max(solve(1, 0), solve(0, 1));
return res;
}
/*
int main() {
return 0;
}
*/
| true |
6693986bfecc92364c707639940b47e2b07f0c0e | C++ | electronicarts/EASTL | /include/EASTL/allocator_malloc.h | UTF-8 | 3,730 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_ALLOCATOR_MALLOC_H
#define EASTL_ALLOCATOR_MALLOC_H
#include <EABase/eahave.h>
#include <EASTL/allocator.h>
#include <stddef.h>
// EASTL_ALIGNED_MALLOC_AVAILABLE
//
// Identifies if the standard library provides a built-in aligned version of malloc.
// Defined as 0 or 1, depending on the standard library or platform availability.
// None of the viable C functions provides for an aligned malloc with offset, so we
// don't consider that supported in any case.
//
// Options for aligned allocations:
// C11 aligned_alloc http://linux.die.net/man/3/aligned_alloc
// glibc memalign http://linux.die.net/man/3/posix_memalign
// Posix posix_memalign http://pubs.opengroup.org/onlinepubs/000095399/functions/posix_memalign.html
// VC++ _aligned_malloc http://msdn.microsoft.com/en-us/library/8z34s9c6%28VS.80%29.aspx This is not suitable, since it has a limitation that you need to free via _aligned_free.
//
#if !defined EASTL_ALIGNED_MALLOC_AVAILABLE
#if defined(EA_PLATFORM_POSIX) && !defined(EA_PLATFORM_APPLE)
// memalign is more consistently available than posix_memalign, though its location isn't consistent across
// platforms and compiler libraries. Typically it's declared in one of three headers: stdlib.h, malloc.h, or malloc/malloc.h
#include <stdlib.h> // memalign, posix_memalign.
#define EASTL_ALIGNED_MALLOC_AVAILABLE 1
#if EA_HAS_INCLUDE_AVAILABLE
#if EA_HAS_INCLUDE(<malloc/malloc.h>)
#include <malloc/malloc.h>
#elif EA_HAS_INCLUDE(<malloc.h>)
#include <malloc.h>
#endif
#elif defined(EA_PLATFORM_BSD)
#include <malloc/malloc.h>
#elif defined(__clang__)
#if __has_include(<malloc/malloc.h>)
#include <malloc/malloc.h>
#elif __has_include(<malloc.h>)
#include <malloc.h>
#endif
#else
#include <malloc.h>
#endif
#else
#define EASTL_ALIGNED_MALLOC_AVAILABLE 0
#endif
#endif
namespace eastl
{
///////////////////////////////////////////////////////////////////////////////
// allocator_malloc
//
// Implements an EASTL allocator that uses malloc/free as opposed to
// new/delete or PPMalloc Malloc/Free.
//
// Example usage:
// vector<int, allocator_malloc> intVector;
//
class allocator_malloc
{
public:
allocator_malloc(const char* = NULL)
{ }
allocator_malloc(const allocator_malloc&)
{ }
allocator_malloc(const allocator_malloc&, const char*)
{ }
allocator_malloc& operator=(const allocator_malloc&)
{ return *this; }
bool operator==(const allocator_malloc&)
{ return true; }
bool operator!=(const allocator_malloc&)
{ return false; }
void* allocate(size_t n, int /*flags*/ = 0)
{ return malloc(n); }
void* allocate(size_t n, size_t alignment, size_t alignmentOffset, int /*flags*/ = 0)
{
#if EASTL_ALIGNED_MALLOC_AVAILABLE
if((alignmentOffset % alignment) == 0) // We check for (offset % alignmnent == 0) instead of (offset == 0) because any block which is aligned on e.g. 64 also is aligned at an offset of 64 by definition.
return memalign(alignment, n); // memalign is more consistently available than posix_memalign.
#else
if((alignment <= EASTL_SYSTEM_ALLOCATOR_MIN_ALIGNMENT) && ((alignmentOffset % alignment) == 0))
return malloc(n);
#endif
return NULL;
}
void deallocate(void* p, size_t /*n*/)
{ free(p); }
const char* get_name() const
{ return "allocator_malloc"; }
void set_name(const char*)
{ }
};
} // namespace eastl
#endif // Header include guard
| true |
8cd42aef0c920e6df0d64919b4b95b1ccd6b2085 | C++ | CHOcho-quan/OJ-Journey | /LeetCode/Leetcode300_最长递增子序列.cpp | UTF-8 | 549 | 2.71875 | 3 | [] | no_license | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(), 1);
dp[0]= 1;
for (int i = 1; i < nums.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) dp[i] = max(dp[j] + 1, dp[i]);
}
// for (auto& d : dp) std::cout << d << ' ';
// std::cout << '\n';
}
int result = 0;
for (auto& d : dp) {
result = max(d, result);
}
return result;
}
};
| true |
4a43ee233ee680d654ea99b07bd258c201fa3c06 | C++ | rawanalaa/PACMAN-game-using-C-and-SFML | /ghosts.cpp | UTF-8 | 948 | 2.984375 | 3 | [] | no_license | #include "ghosts.h"
ghosts::ghosts(double radius, int initialrow, int initialcolumn, string filename)
{
circle.setRadius(radius);
circle.setPosition(90 + 15 * initialcolumn, 90 + 15 * initialrow);
texture.loadFromFile(filename);
circle.setTexture(&texture);
row = initialrow;
column = initialcolumn;
}
void ghosts::move(vector<int> p, int arr[][COLUMNS])
{
for (int i = p.size() - 1; i >= 0; i--)
{
if (c.getElapsedTime() > seconds(0.26))
if (p[i] == arr[row][column - 1]) //comparing the path with the board
{
circle.move(-15, 0);
column--;
c.restart();
}
else if (p[i] == arr[row][column + 1])
{
circle.move(15, 0);
column++;
c.restart();
}
else if (p[i] == arr[row + 1][column])
{
circle.move(0, 15);
row++;
c.restart();
}
else if (p[i] == arr[row - 1][column])
{
circle.move(0, -15);
row--;
c.restart();
}
}
} | true |
cc07b4d04f4bc9b83cffb93ba8fcf648b902d98d | C++ | FoxGriVer/Programming | /1st Semestr/lab5/lab5/Source.cpp | UTF-8 | 2,347 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Pair
{
protected :
int first, second;
public:
Pair(int fst = 0, int sec = 0)
{
first = fst;
second = sec;
}
void Compar(int fst, int sec)
{
if (fst > sec)
{
cout << fst << " > " << sec << endl;
}
else if (fst == sec)
{
cout << fst << " = " << sec << endl;
}
else
{
cout << sec << " > " << fst << endl;
}
}
void Mult(int fst, int sec)
{
int result;
result = fst * sec;
cout << fst << " * " << sec << " = " << result << endl;
}
void VichPair(int fst1, int sec1, int fst2, int sec2)
{
int res_fst, res_sec;
res_fst = fst1 - sec1;
res_sec = fst2 - sec2;
cout << "(" << fst1 << ", " << sec1 << ") - (" << fst2
<< ", " << sec2 << ") = (" << res_fst << ", " << res_sec << ")" << endl;
}
};
class Rational : public Pair
{
protected:
int fstint, secint;
public :
Rational(int a, int b) : Pair(a, b)
{
fstint = a;
secint = b;
}
void SummRat(int fst1, int sec1, int fst2, int sec2)
{
int res_fst, res_sec;
res_fst = (fst1 * sec2) + ( sec1 * fst2);
res_sec = sec1 * sec2;
cout << "(" << fst1 << ", " << sec1 << ") + (" << fst2
<< ", " << sec2 << ") = (" << res_fst << ", " << res_sec << ")" << endl;
}
void DivRat(int fst1, int sec1, int fst2, int sec2)
{
int res_fst, res_sec;
res_fst = fst1 * sec2;
res_sec = sec1 * fst2;
cout << "(" << fst1 << ", " << sec1 << ") / (" << fst2
<< ", " << sec2 << ") = (" << res_fst << ", " << res_sec << ")" << endl;
}
};
int main()
{
int number1, number2, number3, number4;
cout << " Vvedite chisla " << endl;
cin >> number1 >> number2 >> number3 >> number4;
cout << endl;
Pair OurObjComp(number1, number2);
Rational OurObjRat(number1, number2);
cout << " Bazovii class : " << endl;
OurObjComp.Compar(number1, number2);
OurObjComp.Mult(number1, number2);
OurObjComp.VichPair(number1, number2, number3, number4);
cout << endl;
cout << " Proizvodnii class : " << endl;
OurObjRat.Compar(number1, number2);
OurObjRat.Mult(number1, number2);
OurObjRat.VichPair(number1, number2, number3, number4);
OurObjRat.SummRat(number1, number2, number3, number4);
OurObjRat.DivRat(number1, number2, number3, number4);
cout << endl;
system("pause");
} | true |
4017678cda97a5279ae7d3419d607152d670e3ee | C++ | azzalan/dca1202-poligonos | /ponto.cpp | UTF-8 | 912 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
Ponto::Ponto(float x, float y){
// armazena coordenadas do ponto
this->x = x;
this->y = y;
}
void Ponto::setX(float nx){
x = nx;
}
void Ponto::setY(float ny){
y = ny;
}
void Ponto::setXY(float nx, float ny){
x = nx;
y = ny;
}
float Ponto::getX(void){
return x;
}
float Ponto::getY(void){
return y;
}
void Ponto::add(Ponto p1){
x += p1.x;
y += p1.y;
}
void Ponto::sub(Ponto p1){
x -= p1.x;
y -= p1.y;
}
void Ponto::norma(void){
float c1, c2;
c1 = pow(x, 2);
c2 = pow(y, 2);
cout << "Norma:" << sqrt(c1 + c2) << endl;
}
void Ponto::translada(float a, float b){
x += a;
y += b;
}
void Ponto::imprime(void) {
cout << "(" << x << ", " << y << ")";
}
bool Ponto::igual(Ponto p1) {
if (x==p1.x && y==p1.y){
return true;
} else {
return false;
}
}
| true |
5d9bb1570bf0b05b2983556270f6d7886e70b733 | C++ | fridobansho/GameEngine | /GameEngine/GameEngine/SpriteBatch.cpp | UTF-8 | 6,665 | 3.015625 | 3 | [] | no_license | #include "SpriteBatch.h"
#include <algorithm>
using namespace GameEngine;
Glyph::Glyph(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint Texture, float Depth, const ColourRGBA8 & colour) :
texture(Texture),
depth(Depth)
{
topLeft.setColour(colour);
topLeft.setPosition(destRect.x, destRect.y + destRect.w);
topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
bottomLeft.setColour(colour);
bottomLeft.setPosition(destRect.x, destRect.y);
bottomLeft.setUV(uvRect.x, uvRect.y);
bottomRight.setColour(colour);
bottomRight.setPosition(destRect.x + destRect.z, destRect.y);
bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
topRight.setColour(colour);
topRight.setPosition(destRect.x + destRect.z, destRect.y + destRect.w);
topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
}
Glyph::Glyph(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint Texture, float Depth, const ColourRGBA8 & colour, float angle) :
texture(Texture),
depth(Depth)
{
glm::vec2 halfDims(destRect.z / 2.0f, destRect.w / 2.0f);
glm::vec2 tl(-halfDims.x, halfDims.y);
glm::vec2 bl(-halfDims.x, -halfDims.y);
glm::vec2 br(halfDims.x, -halfDims.y);
glm::vec2 tr(halfDims.x, halfDims.y);
tl = rotatePoint(tl, angle) + halfDims;
bl = rotatePoint(bl, angle) + halfDims;
br = rotatePoint(br, angle) + halfDims;
tr = rotatePoint(tr, angle) + halfDims;
topLeft.setColour(colour);
topLeft.setPosition(destRect.x + tl.x, destRect.y + tl.y);
topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
bottomLeft.setColour(colour);
bottomLeft.setPosition(destRect.x + bl.x, destRect.y + bl.y);
bottomLeft.setUV(uvRect.x, uvRect.y);
bottomRight.setColour(colour);
bottomRight.setPosition(destRect.x + br.x, destRect.y + br.y);
bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
topRight.setColour(colour);
topRight.setPosition(destRect.x + tr.x, destRect.y + tr.y);
topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
}
glm::vec2 GameEngine::Glyph::rotatePoint(glm::vec2 point, float angle)
{
glm::vec2 newV;
newV.x = point.x * cos(angle) - point.y * sin(angle);
newV.y = point.x * sin(angle) + point.y * cos(angle);
return newV;
}
SpriteBatch::SpriteBatch() : m_vbo(0), m_vao(0)
{
}
SpriteBatch::~SpriteBatch()
{
}
void GameEngine::SpriteBatch::init()
{
createVertexArray();
}
void GameEngine::SpriteBatch::begin(GlyphSortType sortType)
{
m_sortType = sortType;
m_renderBatches.clear();
m_glyphs.clear();
}
void GameEngine::SpriteBatch::end()
{
m_glyphPointers.resize(m_glyphs.size());
for (size_t i = 0; i < m_glyphs.size(); i++)
{
m_glyphPointers[i] = &m_glyphs[i];
}
sortGlyphs();
createRenderBatches();
}
void GameEngine::SpriteBatch::draw(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint texture, float depth, const ColourRGBA8 & colour)
{
m_glyphs.emplace_back(destRect, uvRect, texture, depth, colour);
}
void GameEngine::SpriteBatch::draw(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint texture, float depth, const ColourRGBA8 & colour, float angle)
{
m_glyphs.emplace_back(destRect, uvRect, texture, depth, colour, angle);
}
void GameEngine::SpriteBatch::draw(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint texture, float depth, const ColourRGBA8 & colour, const glm::vec2 & direction)
{
const glm::vec2 right(1.0f, 0.0f);
float angle = acos(glm::dot(right, direction));
if (direction.y < 0.0f) angle = -angle;
m_glyphs.emplace_back(destRect, uvRect, texture, depth, colour, angle);
}
void GameEngine::SpriteBatch::renderBatch()
{
glBindVertexArray(m_vao);
for (size_t i = 0; i < m_renderBatches.size(); i++)
{
glBindTexture(GL_TEXTURE_2D, m_renderBatches[i].m_texture);
glDrawArrays(GL_TRIANGLES, m_renderBatches[i].m_offset, m_renderBatches[i].m_numVertices);
}
glBindVertexArray(0);
}
void GameEngine::SpriteBatch::createRenderBatches()
{
if (m_glyphPointers.empty()) return;
std::vector<Vertex> vertices;
vertices.resize(m_glyphPointers.size() * 6);
int offset = 0;
int cv = 0;
m_renderBatches.emplace_back(offset, 6, m_glyphPointers[0]->texture);
vertices[cv++] = m_glyphPointers[0]->topLeft;
vertices[cv++] = m_glyphPointers[0]->bottomLeft;
vertices[cv++] = m_glyphPointers[0]->bottomRight;
vertices[cv++] = m_glyphPointers[0]->bottomRight;
vertices[cv++] = m_glyphPointers[0]->topRight;
vertices[cv++] = m_glyphPointers[0]->topLeft;
offset += 6;
for (size_t cg = 1; cg < m_glyphPointers.size(); cg++)
{
if (m_glyphPointers[cg]->texture != m_glyphPointers[cg - 1]->texture)
{
m_renderBatches.emplace_back(offset, 6, m_glyphPointers[cg]->texture);
}
else
{
m_renderBatches.back().m_numVertices += 6;
}
vertices[cv++] = m_glyphPointers[cg]->topLeft;
vertices[cv++] = m_glyphPointers[cg]->bottomLeft;
vertices[cv++] = m_glyphPointers[cg]->bottomRight;
vertices[cv++] = m_glyphPointers[cg]->bottomRight;
vertices[cv++] = m_glyphPointers[cg]->topRight;
vertices[cv++] = m_glyphPointers[cg]->topLeft;
offset += 6;
}
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(Vertex), vertices.data());
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void GameEngine::SpriteBatch::createVertexArray()
{
if (m_vao == 0)
{
glGenVertexArrays(1, &m_vao);
}
glBindVertexArray(m_vao);
if (m_vbo == 0)
{
glGenBuffers(1, &m_vbo);
}
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, colour));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, uv));
glBindVertexArray(0);
}
void GameEngine::SpriteBatch::sortGlyphs()
{
switch (m_sortType)
{
case GlyphSortType::BACK_TO_FRONT:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareBackToFront);
break;
case GlyphSortType::FRONT_TO_BACK:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareFrontToBack);
break;
case GlyphSortType::TEXTURE:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareTexture);
break;
}
}
bool GameEngine::SpriteBatch::compareFrontToBack(Glyph * a, Glyph * b)
{
return (a->depth < b->depth);
}
bool GameEngine::SpriteBatch::compareBackToFront(Glyph * a, Glyph * b)
{
return (a->depth > b->depth);
}
bool GameEngine::SpriteBatch::compareTexture(Glyph * a, Glyph * b)
{
return (a->texture < b->texture);
}
| true |
0fbbe5fa5d77e8a51a1fe0e3493d5083356787f0 | C++ | Anirudh8841/CAD_VSC | /src/Transformation/Matrix.h | UTF-8 | 361 | 2.53125 | 3 | [] | no_license | #include <vector>
class Matrix{
public:
// vector<matMul(vector< vector<int> > a, vector< vector<int> > b);
// crossProduct(vector< vector<int> > a, vector< vector<int> > b);
std::vector<std::vector<float> matMul ( std::vector<float> v1, std::vector<float> f2);
std::vector<std::vector<float> crossProduct( std::vector<float> v1, std::vector<float> f2);
} | true |
b2c33db05116ccd4438c9fb7951fa9494dba45b3 | C++ | VB6Hobbyst7/CNC-Plotter-Art-Machine | /previousVersions/srcOLD/imageDrawing/imageDrawing.ino | UTF-8 | 6,410 | 3 | 3 | [] | no_license | //////NEWWWWWW////////
#include <Stepper.h>
#include <Servo.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
const int stepsPerRevolution = 20;
const int servoPin = 6;//pin servo is connected to
//Hardware Initialization
Servo penServo;//initiates servo
Stepper xAxis(stepsPerRevolution, 2, 3, 10, 11); //pins x axis motor are connected to
Stepper yAxis(stepsPerRevolution, 4, 5, 8, 9); //pins y axis motor are connected to
//Dynamic Memory Initialization
bool drawBool = true;
int xstep;
int ystep;
int xold;
int yold;
//Function Declarations
void penUp();
void penDown();
void drawX(int n);
void drawY(int n);
void blockingRead(int currentX[], int currentY[]);
void convertSerialStrInputToInt(int currentX[], int currentY[]);
void setup()
{
xAxis.setSpeed(100);
yAxis.setSpeed(100);
penServo.attach(servoPin);//attach servo to arduino
Serial.begin(9600);
}
void loop()
{
while (drawBool == true)
{
int currentX[49];
int currentY[49];
delay (3000);
int numCoords = 1608;
xold = 0;
yold = 0;
int iters = 5;
for (int i = 0; i < numCoords; i = i + 9)
/* Outer for-loop keeps track of number of coordinates to go through, which overlaps with inner for-loop
which reads in 49 coordinates at the same time. Hence to merge the for-loops, the i counter of the outer
for-loop must be iterated along with the inner for-loop.
*/
{
Serial.print("\n");
Serial.print("@GetNext"); //gives order to imageProcessing.py
Serial.flush();
//python sends in next 49 coords
blockingRead(currentX, currentY);
delay(5000);
for (int i = 0; i < 5; i++) {
Serial.print("current move ");
Serial.print(currentX[i]);
Serial.print(" ");
Serial.print(currentY[i]);
Serial.print("\n");
}
Serial.flush();
delay(5000);
for (int k = 0; k < iters; k++)
{
if (currentX[k] == -1) //end of file (not 49 full coords), blocked read returns -1 instead of a coordinate
{
iters = k;
break;
}
}
for (int k = 0; k < iters; k++)
{
//calculate difference
xstep = currentX[k] - xold;
ystep = currentY[k] - yold;
if (fabs(xstep) > 10 || fabs(ystep) > 10 ) //if points are too far apart from eachother to be continuous
{ //move to location
penUp();
drawX((int)xstep);
drawY((int)ystep);
penDown();
}
else
{ //actually draw line
drawX((int)xstep);
drawY((int)ystep);
}
xold = currentX[k];
yold = currentY[k];
}
}
penUp();
drawBool = false;
}
}
void penUp()
{
penServo.write(70);//pulls pen up
delay(1000);
}
void penDown()
{
penServo.write(0);//pulls pen up
delay(1000);
}
void drawX(int stepsToMove)
{
int steps;
if (stepsToMove > 0)
{
steps = 1;
}
else
{
stepsToMove *= -1;
steps = -1;
}
for (int i = 0; i < (int)stepsToMove; i++)
{
xAxis.step(steps);
delay(10);
}
}
void drawY(int stepsToMove)
{
int steps;
if (stepsToMove > 0)
{
steps = 1;
}
else
{
stepsToMove *= -1;
steps = -1;
}
for (int i = 0; i < (int)stepsToMove; i++)
{
yAxis.step(1);
delay(10);
}
}
void blockingRead(int currentX[], int currentY[] )
{
while (!Serial.available())
{
delay(100);
}
convertSerialStrInputToInt(currentX, currentY);
}
void convertSerialStrInputToInt(int currentX[], int currentY[])
{ //only called when serial.available
Serial.print("inside convertInputToInt function");
Serial.flush();
String resultStr;
int resultInt;
String inputString = "";
String tempCharX = "";
char tempCharY;
int l;
//Serial.setTimeout(1500);
int i = 0;
int h = 0;
while (Serial.available())
{
tempCharX = Serial.readString();
h++;
}
///for (int i = 0; i < 50; i++)
//{
Serial.print("do you even go here???\n");
Serial.print(tempCharX);
Serial.flush();
Serial.print("testing char: ");
Serial.print(tempCharX[0]);
Serial.print("\n");
Serial.flush();
l = tempCharX.length() - 1;
Serial.print("length char: ");
Serial.print(l);
Serial.print("\n");
for (int n = 0; n < l; n++)
{
if (tempCharX[n] == '!') //end of entire coordinates to be sent from python
{
resultInt = -1;
currentX[i] = resultInt;
break;
}
Serial.print(n);
Serial.print("getting X\n");
Serial.flush();
while (tempCharX[n] != ' ') //python inputs coordinates in a string separated by spaces & on diff lines
{
inputString += (char)tempCharX[n];
n++;
}
n++;
for (int j = 0; j < inputString.length(); j++)
{
if (inputString[j] == '.') //python puts integers as floats into input fmor serial.read(), we just want it as an int
{
break;
}
else if (inputString[j] >= 48 && inputString[j] <= 57) //is an integer 0 to 9
{
resultStr += inputString[j];
}
}
resultInt = resultStr.toInt();
resultStr = "";
inputString = "";
currentX[i] = resultInt;
while (tempCharX[n] != ' ') //python inputs coordinates in a string separated by spaces & on diff lines
{
inputString += (char)tempCharX[n];
n++;
}
Serial.print(inputString);
Serial.print("\n");
Serial.flush();
for (int j = 0; j < inputString.length(); j++)
{
if (inputString[j] == '.') //python puts integers as floats into input fmor serial.read(), we just want it as an int
{
Serial.print("found dot!!!");
Serial.print("\n");
Serial.flush();
break;
}
else if (inputString[j] >= 48 && inputString[j] <= 57) //is an integer 0 to 9
{
resultStr += inputString[j];
}
}
Serial.print("result string is :");
Serial.print(resultStr);
Serial.print("\n");
Serial.flush();
resultInt = resultStr.toInt();
resultStr = "";
inputString = "";
currentY[i] = resultInt;
i++;
//}
}
Serial.print("got all 50\n");
for (int i = 0; i < 5; i++) {
Serial.print("current point ");
Serial.print(currentX[i]);
Serial.print(" ");
Serial.print(currentY[i]);
Serial.print("\n");
}
Serial.flush();
}
| true |
c32c4d75c13a84f0f715d19d44eb3e517e836b5d | C++ | silenke/my-leetcode | /problems/剑指 Offer 32 - III. 从上到下打印二叉树 III/1.cc | UTF-8 | 1,227 | 3.109375 | 3 | [] | no_license | #include "..\..\leetcode.h"
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
deque<TreeNode*> dq;
if (root) dq.emplace_back(root);
bool rl = true; // 下一层从右往左打印
while (!dq.empty()) {
int n = dq.size();
res.emplace_back(n);
for (int i = 0; i < n; i++) {
if (rl) {
root = dq.front(); dq.pop_front();
res.back()[i] = root->val;
if (root->left) dq.emplace_back(root->left);
if (root->right) dq.emplace_back(root->right);
}
else {
root = dq.back(); dq.pop_back();
res.back()[i] = root->val;
if (root->right) dq.emplace_front(root->right);
if (root->left) dq.emplace_front(root->left);
}
}
rl ^= 1;
}
return res;
}
}; | true |
7a02278eea18848ee5418ba2274eb0f6a055fb3b | C++ | jsyeh/uva | /not_verified/uva11332.cpp | UTF-8 | 331 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
int f(int n)
{
int sum=0;
while(n>0){
sum+=n%10;
n/=10;
}
return sum;
}
int g(int n)
{
while(n>=10){
n=f(n);
}
return n;
}
int main()
{
int n;
while(scanf("%d", &n)==1){
if(n==0)break;
int ans=g(n);
printf("%d\n", ans);
}
}
| true |
b5014f24f4c56558150556e38c88e69ab31aaa56 | C++ | brunexgeek/markdowntown | /modules/markdowntown/source/Token.hh | UTF-8 | 429 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef TOKEN_HH
#define TOKEN_HH
#include <sstream>
#include <string>
class Token
{
public:
int id;
int counter;
std::string value;
Token(
int id,
const std::string &value) : id(id), counter(0), value(value)
{
}
operator std::string()
{
std::stringstream ss;
ss << "[id: " << id << "; counter: " << counter << "; value: " << value << "]" << this;
return ss.str();
}
};
#endif // TOKEN_HH | true |
315ea7b14061cf1024f923d8dfa6e522c8638d67 | C++ | buyno/CodingInterview2 | /66/main.cc | UTF-8 | 1,245 | 3.921875 | 4 | [
"Apache-2.0"
] | permissive | // 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B 中的元素 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
//两个循环,第一个从前往后,得到截止A[i-1]的乘积,保存在B[i]中。
// 第二个循环从后往前,得到后半部的乘积在累乘到B[]对应位置
#include <vector>
#include <iostream>
using namespace std;
class Solution
{
public:
vector<int> constructArr(vector<int> &a)
{
if (a.size() == 0)
{
return {};
}
else if (a.size() == 1)
{
return {1};
}
vector<int> result(a.size());
int temp = 1;
result[0] = 1;
for (int i = 1; i < a.size(); i++)
{
temp *= a[i - 1];
result[i] = temp;
}
temp = 1;
for (int i = a.size() - 2; i >= 0; i--)
{
temp = temp * a[i + 1];
result[i] = result[i] * temp;
}
return result;
}
};
int main()
{
{
Solution s;
vector<int> data = {1, 2, 3, 4, 5};
auto res = s.constructArr(data);
for (auto x : res)
{
cout << x << endl;
}
}
} | true |
91003f72ac2807b5f1a629dadc5e7b2bf712f361 | C++ | taiseiKMC/md5 | /md5.cpp | UTF-8 | 2,679 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <functional>
#include <vector>
#include <cmath>
#include <iomanip>
#include "md5.hpp"
void print_word(const word w)
{
//cout<<hex;
for(int j=0;j<4;j++)
{
/*unsigned short c=(w>>(j*8))&0xff;
cout<<c;*/
}
std::cout<<w<<" ";
std::cout<<std::endl;
}
void print(const block b)
{
std::cout<<std::setw(8)<<std::setfill('0')<<std::hex;
for(int j=0;j<BLOCK_SIZE;j++)
for(int i=0;i<WORDS_SIZE;i++)
std::cout<<std::setw(8)<<std::setfill('0')<<b[j][i]<<" ";
std::cout<<std::endl;
}
void print_hash(const words w)
{
std::cout<<std::hex;
for(int i=0;i<WORDS_SIZE;i++)
{
//cout<<w[i];
for(int j=0;j<4;j++)
{
unsigned short c=(w[i]>>(j*8))&0xff;
std::cout<<std::setw(2)<<std::setfill('0')<<c;
}
//cout<<" ";
}
std::cout<<std::endl;
}
const words MD5::IV=
words{ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476};
const int MD5::ROUND=4;
const int MD5::STEP=16;
const std::function<word(const word,const word,const word)> MD5::func[]={ff,gg,hh,ii};
std::vector<std::vector<int>> MD5::block_index(ROUND, std::vector<int>(STEP));
std::vector<std::vector<word>> MD5::k(ROUND, std::vector<word>(STEP));
std::vector<std::vector<int>> MD5::s(ROUND, std::vector<int>(STEP));
void MD5::init()
{
for(int i=0;i<STEP;i++)
{
block_index[0][i]=i;
block_index[1][i]=(i*5+1)%16;
block_index[2][i]=(i*3+5)%16;
block_index[3][i]=(i*7)%16;
}
int ss[][4]={
{7,12,17,22},
{5,9,14,20},
{4,11,16,23},
{6,10,15,21}
};
for(int j=0;j<ROUND;j++)
for(int i=0;i<4;i++)
s[j][i]=ss[j][i];
for(int j=0;j<ROUND;j++)
for(int i=4;i<STEP;i++)
s[j][i]=s[j][i%4];
for(int i=0;i<ROUND*STEP;i++)
k[i/STEP][i%STEP]=std::floor(std::abs(sin(i+1))*((long long)(1)<<32));
}
words MD5::md5_compute(words v, const block b)
{
words vv(v);
for(int i=0;i<4;i++)
md5_round(v, b, i);
for(int i=0;i<WORDS_SIZE;i++)
vv[i]+=v[i];
return vv;
}
void MD5::md5_round(words &v, const block b, const int rnd)
{
for(int i=0;i<16;i++)
md5_step(v, b, rnd, i);
}
void MD5::md5_step(words &v, const block b, const int rnd, const int step)
{
int a=(16-step)%4,bb=(17-step)%4;
int bi=block_index[rnd][step];
v[a]+=func[rnd](v[bb], v[(18-step)%4], v[(19-step)%4]);
v[a]+=b[bi/4][bi%4];
v[a]+=k[rnd][step];
v[a]=rotate(v[a], s[rnd][step]);
v[a]+=v[bb];
//print_hash(v);
}
//static変数の初期化
MD5 initializer=MD5();
| true |
c47b82a404cfaee4c03bc11f21fbb97fa40f6e54 | C++ | HarshaIndukuri/Lab6 | /lab6_q7_b.cpp | UTF-8 | 245 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
char toLower(char x){
x=x+32;
cout<<"Your character in lowercase is:"<<x<<endl;
}
int main() {
char a;
cout<<"Enter an uppercase letter. ";
cin>>a;
cout<<endl;
toLower(a);
}
| true |
9c12f9b68246328d72d83146ba2da9965ccfe3fc | C++ | orcchg/CppCourse | /Lesson_13/client/solutions/client_2_2.cpp | UTF-8 | 6,359 | 2.578125 | 3 | [] | no_license | #include <chrono>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <thread>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include "logger.h"
#include "protocol_0.h"
#define MESSAGE_SIZE 4096
#define END_STRING "!@#$\0"
bool is_stopped = false;
/* Tools */
// ----------------------------------------------------------------------------
static void usage() {
printf("client_2 <server.cfg>\n");
}
static long long hash(const std::string& str) {
srand(clock());
// Java String hash code: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
int prime = 7;
long long hash = 0;
int power = str.length() - 1;
for (auto it = str.begin(); it != str.end(); ++it, --power) {
hash += static_cast<long long>(*it) * std::pow(prime, power) + rand() % 100 + 1;
}
return hash;
}
static std::string enterName() {
printf("Enter name: ");
std::string name;
std::cin >> name;
return name;
}
long long getCurrentTime() {
auto now = std::chrono::system_clock::now();
auto duration = now.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
return millis;
}
struct ClientException {};
/* Worker thread */
// ----------------------------------------------------------------------------
static void receiverThread(int sockfd) {
while (true) {
char buffer[MESSAGE_SIZE];
recv(sockfd, buffer, MESSAGE_SIZE, 0);
// check for termination
if (strncmp(buffer, END_STRING, strlen(END_STRING)) == 0) {
INF("Server: connection closed");
is_stopped = true; // stop main loop
return; // Server has sent end signal
}
Protocol proto = deserialize(buffer);
std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::ostringstream oss;
oss << std::ctime(&end_time);
printf("%s :: %s: %s\n", oss.str().c_str(), proto.name.c_str(), proto.message.c_str());
}
}
/* Client */
// ----------------------------------------------------------------------------
class Client {
public:
Client(long long id, const std::string& name);
~Client();
void init(const std::string& config_file);
void run();
private:
long long m_id;
std::string m_name;
std::string m_ip_address;
std::string m_port;
int m_socket;
bool m_is_connected;
bool readConfiguration(const std::string& config_file);
};
Client::Client(long long id, const std::string& name)
: m_id(id), m_name(name) {
MSG("Initialized client with name %s and id %lli", name.c_str(), id);
}
Client::~Client() {
close(m_socket);
}
void Client::init(const std::string& config_file) {
if (!readConfiguration(config_file)) {
throw ClientException();
}
// prepare address structure
addrinfo hints;
addrinfo* server_info;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(m_ip_address.c_str(), m_port.c_str(), &hints, &server_info);
if (status != 0) {
ERR("Failed to prepare address structure: %s", gai_strerror(status)); // see error message
throw ClientException();
}
// establish connection
addrinfo* ptr = server_info;
for (; ptr != nullptr; ptr = ptr->ai_next) { // loop through all the results
if ((m_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
continue; // failed to get connection socket
}
if (connect(m_socket, server_info->ai_addr, server_info->ai_addrlen) == -1) {
close(m_socket);
continue; // failed to connect to a particular server
}
break; // connect to the first particular server we can
}
if (ptr == nullptr) {
ERR("Failed to connect to Server");
m_is_connected = false;
} else {
m_is_connected = true;
}
freeaddrinfo(server_info); // release address stucture and remove from linked list
if (m_is_connected) {
// register to Server
Protocol proto;
proto.src_id = m_id;
proto.name = m_name;
char* raw_proto = serialize(proto);
send(m_socket, raw_proto, strlen(raw_proto), 0);
delete [] raw_proto;
}
}
void Client::run() {
if (!m_is_connected) {
ERR("No connection established to Server");
throw ClientException();
}
// get response from Server
char buffer[256];
recv(m_socket, buffer, 256, 0);
INF("Server response: %s", buffer);
// run message receiver thread
std::thread t(receiverThread, m_socket);
t.detach();
// send messages loop
std::string message;
while (!is_stopped && getline(std::cin, message)) {
Protocol proto;
proto.src_id = m_id;
proto.timestamp = getCurrentTime();
proto.name = m_name;
proto.message = message;
char* raw_proto = serialize(proto);
send(m_socket, raw_proto, strlen(raw_proto), 0);
delete [] raw_proto;
}
}
// ----------------------------------------------
bool Client::readConfiguration(const std::string& config_file) {
bool result = true;
std::fstream fs;
fs.open(config_file, std::fstream::in);
if (fs.is_open()) {
std::string line;
// ip address
std::getline(fs, line);
int i1 = line.find_first_of(' ');
m_ip_address = line.substr(i1 + 1);
DBG("IP address: %s", m_ip_address.c_str());
// port
std::getline(fs, line);
int i2 = line.find_first_of(' ');
m_port = line.substr(i2 + 1);
DBG("Port: %s", m_port.c_str());
fs.close();
} else {
ERR("Failed to open configure file: %s", config_file.c_str());
result = false;
}
return result;
}
/* Main */
// ----------------------------------------------------------------------------
int main(int argc, char** argv) {
DBG("[Lesson 13]: Client 2.2");
std::string config_file = "../data/server.cfg";
if (argc >= 2) {
char buffer[256];
strncpy(buffer, argv[1], strlen(argv[1]));
config_file = std::string(buffer);
}
DBG("Configuration from file: %s", config_file.c_str());
std::string name = enterName();
long long id = hash(name);
Client client(id, name);
client.init(config_file);
client.run();
DBG("[Lesson 13]: Client 2.2 END");
return 0;
}
| true |
ddf4a6db74a779969e119fe0c723b3ca2f3796a4 | C++ | danielbaud/NeuralNetwork | /src/network/layer.hxx | UTF-8 | 989 | 2.6875 | 3 | [] | no_license | #include "layer.hh"
Layer::Layer(size_t size, size_t syn)
{
neurons = std::vector<Neuron>(size, Neuron(syn));
}
void Layer::update(const Layer& prev)
{
for (size_t i = 0; i < neurons.size(); ++i)
{
neurons[i].set_sum(neurons[i].bias);
for (size_t j = 0; j < prev.size(); ++j)
neurons[i].add_sum(prev[j].get_val()*neurons[i][j]);
neurons[i].activate();
}
}
void Layer::updateE(const Layer& next)
{
for (size_t i = 0; i < neurons.size(); ++i)
{
neurons[i].set_delta(0);
for (size_t j = 0; j < next.size(); ++j)
neurons[i].add_delta(next[j][i] * next[j].get_delta());
}
}
void Layer::updateS(const Layer& prev)
{
for (size_t i = 0; i < neurons.size(); ++i)
{
for (size_t j = 0; j < prev.size(); ++j)
{
neurons[i][j] += neurons[i].get_delta() * ATOM * prev[j].get_val()
* activation_d(neurons[i].get_sum());
}
neurons[i].bias += neurons[i].get_delta() * ATOM
* activation_d(neurons[i].get_sum());
}
}
| true |
c56d7971ff7b773d266c0f0c4179390a80fe10b0 | C++ | marromlam/lhcb-software | /Phys/Phys/DaVinciMCKernel/Kernel/IMCParticleTupleTool.h | UTF-8 | 1,508 | 2.609375 | 3 | [] | no_license | // $Id$
// ============================================================================
#ifndef DECAYTUPLE_IMCPARTICLETUPLETOOL_H
#define DECAYTUPLE_IMCPARTICLETUPLETOOL_H 1
// ============================================================================
// Include files
// from STL
#include <string>
// from Gaudi
#include "GaudiKernel/IAlgTool.h"
static const InterfaceID IID_IMCParticleTupleTool ( "IMCParticleTupleTool", 1, 0 );
namespace Tuples{
class Tuple;
}
namespace LHCb {
class MCParticle;
}
/** @class IMCParticleTupleTool
*
* Fill some mc-particle related variables into a tuple.
*
* \sa IEventTupleTool
* \sa IParticleTupleTool
*
* @author patrick.koppenburg@cern.ch
* @date 19 January 2009
*/
class IMCParticleTupleTool : virtual public IAlgTool
{
public:
virtual ~IMCParticleTupleTool(){};
// Return the interface ID
static const InterfaceID& interfaceID() { return IID_IMCParticleTupleTool; }
//! Fill the tuple.
//! - \b top : may be used to provide additional information about \b part, like the top particle of the decay.
//! - \b part : the particle about which some info are filled.
//! - \b head : prefix for the tuple column name.
//! - \b tuple: the tuple to fill
virtual StatusCode fill( const LHCb::MCParticle* top ,
const LHCb::MCParticle* part ,
const std::string& head ,
Tuples::Tuple& tuple ) = 0 ;
};
#endif // DECAYTUPLE_IMCPARTICLETUPLETOOL_H
| true |
7e463cafa4505653a78b41c2518ef0c79faa342e | C++ | JArandaIzquierdo/FundamentosDeProgramacion | /Ejercicios/EjerciciosRelacion2/Ejercicio16.cpp | UTF-8 | 2,407 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
using namespace std;
int main(){
int precio_inicial = 150;
double km, precio_adicional, km1, precio_final, rebaja, precio_rebajado;
char respuesta;
bool es_cliente = false;
cout << "Introduzca el numero de kilometros hasta el destino final: ";
cin >> km;
cout << "Indique si es usted un cliente previo de esta empresa: ";
cin >> respuesta;
if(respuesta == 'SI' || respuesta == 'si'){
es_cliente = true;
if(es_cliente){
if (km <= 200){
rebaja = (precio_inicial * 5) / 100;
precio_final = precio_inicial - rebaja;
cout << "El precio del billete es de: " << precio_final << " euros" << endl;
}
else{
precio_adicional = (km - 200) * 0.1;
precio_final = precio_inicial + precio_adicional;
rebaja = (precio_final * 5) / 100;
precio_rebajado = precio_final - rebaja;
cout << "El precio del billete es de: " << precio_rebajado << " euros" << endl;
}
}
}
else{
if (km <= 200)
cout << "El precio del billete es de: " << precio_inicial << " euros" << endl;
else{
if(km <= 600){
precio_adicional = (km - 200) * 0.1;
precio_final = precio_inicial + precio_adicional;
cout << "El precio del billete es de: " << precio_final << " euros" << endl;
}
else{
if(km <= 1100){
precio_adicional = (km - 200) * 0.1;
precio_final = precio_inicial + precio_adicional;
rebaja = (precio_final * 3) / 100;
precio_rebajado = precio_final - rebaja;
cout << "El precio del billete es de: " << precio_rebajado << " euros" << endl;
}
else{
precio_adicional = (km - 200) * 0.1;
precio_final = precio_inicial + precio_adicional;
rebaja = (precio_final * 4) / 100;
precio_rebajado = precio_final - rebaja;
cout << "El precio del billete es de: " << precio_rebajado << " euros" << endl;
}
}
}
}
return 0;
}
| true |
834f1fc9e1a9e5cdeb226e89c468000b2d3e5a97 | C++ | csquaredcoding/CST136 | /Final Lab/Airline Management System/baseiterator.cpp | UTF-8 | 503 | 2.734375 | 3 | [] | no_license | #include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include "baseiterator.h"
BaseIterator::BaseIterator()
{
cout << "Default BaseIterator c'tor" << endl;
m_cursor = nullptr;
CityList = nullptr;
}
BaseIterator::BaseIterator(TLList<City> * citylist)
{
cout << "1 arg BaseIterator c'tor" << endl;
this->CityList = citylist; //assigns pointer
m_cursor = CityList->GetHead();
}
BaseIterator::~BaseIterator()
{
cout << "BaseIterator d'tor" << endl;
}
| true |
86bd2d82b75f78e81342ede8c6c0056254f54a47 | C++ | Allegra42/GirlsDayExample | /lib/effects/effects.cpp | UTF-8 | 1,050 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "effects.h"
uint32_t Farbrad(Adafruit_NeoPixel* pixel, byte position) {
position = 255 - position;
if (position < 85) {
return pixel->Color(255 - position * 3, 0, position * 3);
}
if (position < 170) {
position -= 85;
return pixel->Color(0, position * 3, 255 - position *3);
}
position -= 170;
return pixel->Color(position * 3, 255 - position * 3, 0);
}
void Regenbogen(Adafruit_NeoPixel* pixel, unsigned long wartezeit) {
for (uint16_t j = 0; j < 256; j++) {
for (uint16_t i = 0; i < pixel->numPixels(); i++) {
uint32_t c = Farbrad(pixel, ((i+j) & 255));
pixel->setPixelColor(i, c);
}
pixel->show();
delay(wartezeit);
}
}
void Blinken(Adafruit_NeoPixel* pixel, uint8_t pixelNummer, uint32_t farbe1, uint32_t farbe2, unsigned long wartezeit) {
pixel->setPixelColor(pixelNummer, farbe1);
pixel->show();
delay(wartezeit);
pixel->setPixelColor(pixelNummer, farbe2);
pixel->show();
delay(wartezeit);
} | true |
66065e0866300f9c5b171b4b99b3440339c25ff4 | C++ | Quitomos/CSAPP | /Homework/_2.68.cpp | UTF-8 | 291 | 3.015625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int lower_one_mask(int n) {
return ((1 << (n - 1)) << 1) - 1;
}
int main() {
int x = 1;
cout << "End with input 0" << endl;
while ( x != 0) {
cin >> x;
cout << hex << lower_one_mask(x) << endl;
}
return 0;
} | true |
8957f9b13387bf8bc2b6243a44bbe285977ca12d | C++ | fmi-lab/oop-group8-seminars | /week2/construct_destruct.cpp | UTF-8 | 4,087 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <cstring>
class String {
char* data;
int len;
int capacity;
public:
// default constructor
String();
// constructor with parameters
String(const char*);
// constructor from number in a specified base
// if the base argument is skipped, it will be 10 by default
String(int number, int base=10);
// copy constructor
String(const String&);
// destructor
~String();
};
String::String() {
// default capacity
this->capacity = 10;
this->data = new char[this->capacity];
// empty string by default
this->data[0] = 0;
this->len = 0;
std::cout << "Default constructed string" << std::endl;
}
String::String(const char* data) {
int len = strlen(data);
this->capacity = len + 1;
this->len = len;
this->data = new char[this->capacity];
// copy the data
strcpy(this->data, data);
std::cout << "Constructed string from char*: " << this->data << std::endl;
}
String::String(int number, int base) {
// first calculate number of digits
// so that we can allocate enough memory
int numDigits = 0, temp = number;
do {
numDigits++;
temp /= base;
} while (temp != 0);
this->capacity = numDigits + 1;
this->data = new char[this->capacity];
// a standard function to convert a number to a char*
itoa(number, this->data, base);
this->len = numDigits;
std::cout << "Constructed string from number: " << this->data << std::endl;
}
String::String(const String& other) {
this->capacity = other.capacity;
this->len = other.len;
// Do NOT write this->data = other.data
// It will create shared memory - when one string is changed, the other will be changed too.
// We want the strings to be independent, so allocate new memory and copy all the values
this->data = new char[this->capacity];
strcpy(this->data, other.data);
std::cout << "Constructed string from other string: " << this->data << std::endl;
}
String::~String() {
std::cout << "Destructing string " << this->data << std::endl;
delete [] this->data;
}
void testConstructors () {
// default construct
// on the heap
String *s1 = new String();
// on the stack
String s2;
// construct with parameters
// on the heap
String *s3 = new String("Hello"), *s4 = new String(255, 16);
// on the stack
String s5 = "World", s6 = 1234;
// construct from another string
String *s7 = new String(s6);
String s8 = *s3;
std::cout << "End creating objects" << std::endl << std::endl;
// everything allocated on the heap should be manually deleted
std::cout << "Deleting objects on the heap" << std::endl;
delete s7;
delete s4;
delete s3;
delete s1;
std::cout << std::endl << "Now deleting automatically objects allocated on the stack: "<< std::endl;
}
void fByRef (String& t) {
std::cout << "In f" << std::endl;
std::cout << "Exiting f" << std::endl;
}
void fByVal (String t) {
std::cout << "In f" << std::endl;
std::cout << "Exiting f" << std::endl;
}
void testPassByValueAndRef() {
String testString = "Test";
std::cout << "Before fByVal" << std::endl;
// testString will now be copied
// and the copied value will be used in fByVal
fByVal(testString);
// the copy of testString is destroyed upon exiting fByVal
std::cout << "After fByVal" << std::endl;
std::cout << "Before fByRef" << std::endl;
// no copying when calling fByRef
fByRef(testString);
std::cout << "After fByRef" << std::endl;
}
void displayExampleStart (const char* exampleId) {
std::cout << std::endl;
std::cout << "---------------" << std::endl;
std::cout << "Start example " << exampleId << std::endl;
std::cout << "---------------" << std::endl;
std::cout << std::endl;
}
int main()
{
displayExampleStart("Test Constructors and Destructors");
testConstructors();
displayExampleStart("Test function calling");
testPassByValueAndRef();
return 0;
}
| true |
1f8b8267b34f305a92b4150a24543442d1e36bde | C++ | idleyui/CppPrimer_5th | /Chapter7/ex_52.cpp | UTF-8 | 245 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
struct Sales_data{
string bookNo;
unsigned units_sold;
double revenue;
};
int main(){
Sales_data item = { "978", 25, 15.99 };
Sales_data ite = {};
cout << ite.revenue;
getchar();
} | true |
79849613f532be15c6d5751bcab24c6b355ceb3a | C++ | dotnet/dotnet-api-docs | /snippets/cpp/VS_Snippets_CLR_System/system.Byte.ToString/CPP/newbytemembers2.cpp | UTF-8 | 2,448 | 3.59375 | 4 | [
"MIT",
"CC-BY-4.0"
] | permissive | // Byte.ToString2.cpp : main project file.
using namespace System;
using namespace System::Globalization;
// Byte.ToString()
void Byte1()
{
// <Snippet2>
array<Byte>^ bytes = gcnew array<Byte> {0, 1, 14, 168, 255};
for each (Byte byteValue in bytes)
Console::WriteLine(byteValue);
// The example displays the following output to the console if the current
// culture is en-US:
// 0
// 1
// 14
// 168
// 255
// </Snippet2>
}
// Byte.ToString(String)
void Byte2()
{
// <Snippet4>
array<String^>^ formats = gcnew array<String^> {"C3", "D4", "e1", "E2", "F1", "G", "N1",
"P0", "X4", "0000.0000"};
Byte number = 240;
for each (String^ format in formats)
Console::WriteLine("'{0}' format specifier: {1}",
format, number.ToString(format));
// The example displays the following output to the console if the
// current culture is en-us:
// 'C3' format specifier: $240.000
// 'D4' format specifier: 0240
// 'e1' format specifier: 2.4e+002
// 'E2' format specifier: 2.40E+002
// 'F1' format specifier: 240.0
// 'G' format specifier: 240
// 'N1' format specifier: 240.0
// 'P0' format specifier: 24,000 %
// 'X4' format specifier: 00F0
// '0000.0000' format specifier: 0240.0000
// </Snippet4>
}
// ToString(String, IFormatProvider)
void Byte3()
{
// <Snippet5>
Byte byteValue = 250;
array<CultureInfo^>^ providers = gcnew array<CultureInfo^> { gcnew CultureInfo("en-us"),
gcnew CultureInfo("fr-fr"),
gcnew CultureInfo("es-es"),
gcnew CultureInfo("de-de")};
for each (CultureInfo^ provider in providers)
Console::WriteLine("{0} ({1})",
byteValue.ToString("N2", provider), provider->Name);
// The example displays the following output to the console:
// 250.00 (en-US)
// 250,00 (fr-FR)
// 250,00 (es-ES)
// 250,00 (de-DE)
// </Snippet5>
}
void main()
{
Byte1();
Console::WriteLine();
Byte2();
Console::WriteLine();
Byte3();
Console::WriteLine();
Console::ReadLine();
}
| true |
ee01d57a635010e8931f369a0ad3dc786f330e87 | C++ | HubertBraun/CheckersEngine | /CheckersEngine/CheckersEngine.cpp | UTF-8 | 737 | 2.609375 | 3 | [] | no_license | //Checkers Engine using minmax alghoritm with alpha-beta cutoff
//
//
#include <iostream>
#include"Engine/Tree.h"
#include"Engine/AI.h"
#include"Engine/BoardUtilities.h"
#include"Tests/Tests.h"
#include<chrono>
#define debug 0 // 0 - release, 1 -debug
int main()
{
#ifdef debug
#if debug == 0
AI ai;
bool player = true;
sboard::print(ai.tree_.board_);
while (!ai.win(player)) //test of the alghoritm
{
ai.getBestMove(player, 8); // 8 - depth
getchar();
sboard::print(ai.tree_.board_);
player = !player;
}
std::cout << "Winner: " << ((player) ? ("red") : ("blue")) << std::endl;
#else
Tests t;
std::cout << "Elapsed time: " << t.performanceTest() / 1000.0 << "s" << std::endl;
#endif
#endif
return 0;
} | true |
919e7e66ad94037197bc9f1cfb34c4a37895736a | C++ | Shubhamag12/Data-Structures-and-Algorithms | /LEETCODE/MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.cpp | UTF-8 | 1,011 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Solution{
public:
#define mod 1000000007
#define ll long long
int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) {
horizontalCuts.push_back(0);
horizontalCuts.push_back(h);
verticalCuts.push_back(0);
verticalCuts.push_back(w);
sort(horizontalCuts.begin(),horizontalCuts.end());
sort(verticalCuts.begin(),verticalCuts.end());
ll n1=horizontalCuts.size();
ll n2=verticalCuts.size();
ll res1=horizontalCuts[1]-horizontalCuts[0];
ll res2=verticalCuts[1]-verticalCuts[0];
for(int i=1;i<n1;i++){
res1=max(res1,(ll)horizontalCuts[i]-horizontalCuts[i-1]);
}
for(int i=1;i<n2;i++){
res2=max(res2,(ll)verticalCuts[i]-verticalCuts[i-1]);
}
return (res1*res2)%mod;
}
};
int main(){
vector<int>v1={1,3};
vector<int>h1={1,2,4};
Solution s;
cout<<s.maxArea(5,4,h1,v1)<<endl;
} | true |
5a7aba69582866543d580a34929c661174ed9e11 | C++ | ailyanlu/ACM_Templates-1 | /图论/KM.cpp | GB18030 | 2,440 | 2.90625 | 3 | [] | no_license | /*
Name: KM 㷨
Author: ASEMBL
Date: 01/08/12 14:24
Description: ͼȨƥ N^3
Note: 㷨ִйеһʱ̣һ(i,j), A[i] + B[j] >= w[i,j]ʼճ
㣺 AţBţʹöһ· value = min{ A[i]+B[j]-w[i][j] | iͼڣjͼ }
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std ;
const int MAXN = 301;
const int inf = 1000000000 ;
int N , M ;
int g[MAXN][MAXN] , from[MAXN];
int A[MAXN] , B[MAXN] , visx[MAXN] , visy[MAXN] , visnumber , slack[MAXN] ;
int dfs( int u )
{
if ( visx[u] == visnumber )
return 0;
visx[u] = visnumber ;
for ( int v = 0 ; v < N ; ++v )
if ( A[u] + B[v] == g[u][v] )
{
visy[v] = visnumber ;
if ( from[v] == -1 || dfs( from[v] ) )
{
from[v] = u ;
return 1 ;
}
}
else
slack[v] = min( slack[v] , A[u] + B[v] - g[u][v] );
return 0;
}
void KM()
{
memset( from , -1 , sizeof from );
for ( int i = 0 ; i < N ; ++i )
{
A[i] = B[i] = 0 ;
for ( int j = 0 ; j < N ; ++j )
A[i] = max( A[i] , g[i][j] ) ;
}
for ( int i = 0 ; i < N ; ++i )
{
while ( 1 )
{
++visnumber ;
for ( int j = 0 ; j < N ; ++j )
slack[j] = inf ;
if ( dfs(i) )
break ;
int less = inf ;
for ( int j = 0 ; j < N ; ++j )
if ( from[j] == -1 || visx[ from[j] ] != visnumber )
if ( slack[j] < less )
less = slack[j] ;
for ( int j = 0 ; j < N ; ++j )
{
if ( visx[j] == visnumber )
A[j] -= less ;
if ( from[j] != -1 && visx[ from[j] ] == visnumber )
B[j] += less ;
}
}
}
}
int main()
{
visnumber = 0 ;
while ( scanf("%d",&N) == 1 )
{
for ( int i = 0 ; i < N ; ++i )
for ( int j = 0 ; j < N ; ++j )
scanf("%d",&g[i][j]);
KM();
int ans = 0 ;
for ( int i = 0 ; i < N ; ++i )
ans += A[i] + B[i] ;
printf("%d\n",ans);
}
return 0;
}
| true |
fda9f7309fb22ba141e7cbbb04131d8f914fd8cd | C++ | schips21/cpp | /cpp_04/ex00/Victim.hpp | UTF-8 | 410 | 2.96875 | 3 | [] | no_license | #ifndef VICTIM_HPP
# define VICTIM_HPP
#include <iostream>
class Victim {
protected:
std::string _name;
Victim();
public:
Victim(std::string name);
Victim(const Victim& other);
virtual ~Victim();
Victim & operator=( const Victim& other );
std::string get_name() const;
virtual void getPolymorphed() const;
};
std::ostream &operator<<(std::ostream &oper, const Victim & victim_to_introduce);
#endif | true |
54136509c2f725cffdd5d2bd8732c97a1510e7e0 | C++ | coding-cat-cosmo/game-gallery | /header/videogame.hpp | UTF-8 | 4,286 | 3.25 | 3 | [] | no_license | #ifndef VIDEOGAME_HPP
#define VIDEOGAME_HPP
#include <iostream>
using namespace std;
static unsigned int newID = 1;
/**
* @brief: the class that has all the data related to VideoGames in the database
*
*/
class VideoGame {
private:
string name;
unsigned int year;
string publisher;
string system;
string genre;
string rating;
string size;
unsigned int cost;
unsigned int players;
unsigned int id;
public:
/**
* @brief: basic constructor that initializes a basic videogame
*
* @param: None
* @return: VideoGame Object
*/
VideoGame() : name("Galaga"), year(1999), publisher("ATARI"), system("Arcade Machine"),
genre("shooter"), rating("E"), size("2.5 GB"), cost(35), players(1) { id = newID++; }
/**
* @brief: constructor that initializes a basic videogame with passed in arguments
*
* @param: nam: string, yr: int, sys: string, gen: string, rat: string, mem: string, value: int, play: int
* @return: VideoGame Object
*/
VideoGame(string nam, int yr, string pub, string sys, string gen, string rat, string mem,
int value, int play) : name(nam), year(yr), publisher(pub), system(sys), genre(gen),
rating(rat), size(mem), cost(value), players(play) { id = newID++;}
/**
* @brief: VideoGame destructor
*
* @param: None
* @return: None
*/
~VideoGame() {newID--;}
/**
* @brief: basic print function that prints out all the video game data
*
* @param: None
* @return: None
*/
string getjsonstring();
void print() const;
/**
* @brief: returns VideoGame id
*
* @param: None
* @return: int id of the VideoGame class
*/
int getId() const;
/**
* @brief: returns VideoGame name
*
* @param: None
* @return: string name of the VideoGame class
*/
string getName() const;
/**
* @brief: returns VideoGame year
*
* @param: None
* @return: int year of the VideoGame class
*/
int getYear() const;
/**
* @brief: returns VideoGame publisher
*
* @param: None
* @return: string publisher of the VideoGame class
*/
string getPub() const;
/**
* @brief: returns VideoGame system
*
* @param: None
* @return: string system of the VideoGame class
*/
string getSystem() const;
/**
* @brief: returns VideoGame genre
*
* @param: None
* @return: string genre of the VideoGame class
*/
string getGenre() const;
/**
* @brief: returns VideoGame rating
*
* @param: None
* @return: string rating of the VideoGame class
*/
string getRating() const;
/**
* @brief: returns VideoGame size
*
* @param: None
* @return: string size of the VideoGame class
*/
string getSize() const;
/**
* @brief: returns VideoGame cost
*
* @param: None
* @return: int cost of the VideoGame class
*/
int getCost() const;
/**
* @brief: returns VideoGame players
*
* @param: None
* @return: int players of the VideoGame class
*/
int getPlayer() const;
/**
* @brief: sets VideoGame name
*
* @param: string representing name of the VideoGame
* @return: None
*/
void setName(string);
/**
* @brief: sets VideoGame year
*
* @param: string representing year of the VideoGame
* @return: None
*/
void setYear(int);
/**
* @brief: sets VideoGame publisher
*
* @param: string representing publisher of the VideoGame
* @return: None
*/
void setPub(string);
/**
* @brief: sets VideoGame system
*
* @param: string representing system of the VideoGame
* @return: None
*/
void setSystem(string);
/**
* @brief: sets VideoGame genre
*
* @param: string representing genre of the VideoGame
* @return: None
*/
void setGenre(string);
/**
* @brief: sets VideoGame rating
*
* @param: string representing rating of the VideoGame
* @return: None
*/
void setRating(string);
/**
* @brief: sets VideoGame size
*
* @param: string representing size of the VideoGame
* @return: None
*/
void setSize(string);
/**
* @brief: sets VideoGame cost
*
* @param: string representing cost of the VideoGame
* @return: None
*/
void setCost(int);
/**
* @brief: sets VideoGame players
*
* @param: string representing players of the VideoGame
* @return: None
*/
void setPlayer(int);
};
#endif //VIDEOGAME_HPP
| true |
30ff4f4de27fcee1d8e1d3f3e371fd20f3b6e91a | C++ | vxl/vxl | /contrib/mul/vil3d/tests/test_algo_binary_erode.cxx | UTF-8 | 2,637 | 2.875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | // This is mul/vil3d/tests/test_algo_binary_erode.cxx
#include <iostream>
#include "testlib/testlib_test.h"
#ifdef _MSC_VER
# include "vcl_msvc_warnings.h"
#endif
#include <vil3d/algo/vil3d_binary_erode.h>
inline void print_binary_image(const vil3d_image_view<bool>& im)
{
for (unsigned j=0;j<im.nj();++j)
{
for (unsigned k=0;k<im.nk();++k)
{
// Concatenate rows
for (unsigned i=0;i<im.ni();++i)
if (im(i,j,k)) std::cout<<'X';
else std::cout<<'.';
std::cout<<" ";
}
std::cout<<std::endl;
}
}
static void test_algo_binary_erode()
{
std::cout << "****************************\n"
<< " Testing vil3d_binary_erode\n"
<< "****************************\n";
vil3d_image_view<bool> image0;
image0.set_size(10,10,3);
image0.fill(false);
image0(5,4,1)=true; // Central pixel
image0(5,5,1)=true; // Central pixel
image0(5,6,1)=true; // Central pixel
image0(3,0,1)=true; // Edge pixel
image0(4,0,1)=true; // Edge pixel
image0(5,0,1)=true; // Edge pixel
std::cout<<"Original image\n";
print_binary_image(image0);
vil3d_structuring_element element_i,element_j,element_k;
element_i.set_to_line_i(-1,1);
element_j.set_to_line_j(-1,1);
element_k.set_to_line_k(-1,1);
std::cout<<"Structuring element: "<<element_i<<std::endl;
vil3d_image_view<bool> image1;
vil3d_binary_erode(image0,image1,element_i);
std::cout<<"Result of one erosion in i\n";
print_binary_image(image1);
TEST("image1(5,4,1)",image1(5,4,1),false);
TEST("image1(5,5,1)",image1(5,5,1),false);
TEST("image1(5,6,1)",image1(5,6,1),false);
TEST("image1(3,0,1)",image1(3,0,1),false);
TEST("image1(4,0,1)",image1(4,0,1),true);
TEST("image1(5,0,1)",image1(5,0,1),false);
image1.fill(true);
vil3d_binary_erode(image0,image1,element_j);
std::cout<<"Result of one erosion in j\n";
print_binary_image(image1);
TEST("image1(5,4,1)",image1(5,4,1),false);
TEST("image1(5,5,1)",image1(5,5,1),true);
TEST("image1(5,6,1)",image1(5,6,1),false);
TEST("image1(3,0,1)",image1(3,0,1),false);
TEST("image1(4,0,1)",image1(4,0,1),false);
TEST("image1(5,0,1)",image1(5,0,1),false);
image1.fill(true);
vil3d_binary_erode(image0,image1,element_k);
std::cout<<"Result of one erosion in k\n";
print_binary_image(image1);
TEST("image1(5,4,1)",image1(5,4,1),false);
TEST("image1(5,5,1)",image1(5,5,1),false);
TEST("image1(5,6,1)",image1(5,6,1),false);
TEST("image1(3,0,1)",image1(3,0,1),false);
TEST("image1(4,0,1)",image1(4,0,1),false);
TEST("image1(5,0,1)",image1(5,0,1),false);
}
TESTMAIN(test_algo_binary_erode);
| true |
714caf30eb0dee81fbb7f124eaa1880d8606f9df | C++ | bastlirna/lora-probulator | /fw/lib/display/display.cpp | UTF-8 | 409 | 2.875 | 3 | [
"MIT"
] | permissive | #include "display.h"
void Display::sendBufferOnSerial() {
Serial.println("\n");
uint8_t x,y;
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
Serial.print((unsigned char)buffer[pos], HEX);
Serial.print(" ");
}
yield();
}
Serial.println("\n");
} | true |
6781901280716cc1579ac5eba5fdc74215569f2d | C++ | UESTCzhouyuchuan/Algorithmic | /ACM算法题/book/chapterTwo/积水问题.cpp | UTF-8 | 785 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define MAX_N 100
#define MAX_M 100
using namespace std;
char field[MAX_N][MAX_M + 1];
int M, N;
void dfs(int x, int y)
{
int nx, ny;
field[x][y] = '.';
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
nx = x + dx, ny = y + dy;
if (0 <= nx && nx < N && ny >= 0 && ny < M && field[nx][ny] == 'W')
dfs(nx, ny);
}
}
void solve()
{
int res = 0; //水哇个数
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (field[i][j] == 'W')
{
dfs(i, j);
res++;
}
}
}
printf("%d\n", res);
}
int main(void)
{
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%s", field[i]);
field[i][M] = '\0';
}
solve();
return 0;
} | true |
46262c1c85321c5902e08309a58e00793b83ffc0 | C++ | HugoCa11/Analisis-y-Modelacion-de-Sistemas-de-Software | /Computadora.cpp | UTF-8 | 2,319 | 3.375 | 3 | [] | no_license | #include<iostream>
#include<string>
class Desktop {
private:
std::string name;
public:
void create(std::string nombre) {
setName(nombre);
std::cout << nombre << " creada" << std::endl;
std::cout << "Seleccion de componentes. Completado" << std::endl;
std::cout << "Ensamblado de componentes. Completado" << std::endl;
std::cout << "instalacion y configuracion de Software. Completado" << std::endl;
std::cout << "Empaquetado del computador. Completado" << std::endl;
}
void setName(std::string _nombre) {
name = _nombre;
}
std::string getNamee() {
return name;
}
};
class Laptop {
private:
std::string name;
public:
void create(std::string nombre) {
setName(nombre);
std::cout << nombre << " creada" << std::endl;;
std::cout << "Seleccion de componentes. Completado" << std::endl;
std::cout << "Ensamblado de componentes. Completado" << std::endl;
std::cout << "instalacion y configuracion de Software. Completado" << std::endl;
std::cout << "Empaquetado del computador. Completado" << std::endl;
}
void setName(std::string _nombre) {
name = _nombre;
}
std::string getNamee() {
return name;
}
};
class Netbook {
private:
std::string name;
public:
void create(std::string nombre) {
setName(nombre);
std::cout << nombre << " creada" << std::endl;
std::cout << "Seleccion de componentes. Completado" << std::endl;
std::cout << "Ensamblado de componentes. Completado" << std::endl;
std::cout << "instalacion y configuracion de Software. Completado" << std::endl;
std::cout << "Empaquetado del computador. Completado" << std::endl;
}
void setName(std::string _nombre) {
name = _nombre;
}
std::string getNamee() {
return name;
}
};
class Tablet {
private:
std::string name;
public:
void create(std::string nombre) {
setName(nombre);
std::cout << nombre << " creada" << std::endl;
std::cout << "Seleccion de componentes. Completado" << std::endl;
std::cout << "Ensamblado de componentes. Completado" << std::endl;
std::cout << "instalacion y configuracion de Software. Completado" << std::endl;
std::cout << "Empaquetado del computador. Completado" << std::endl;
}
void setName(std::string _nombre) {
name = _nombre;
}
std::string getNamee() {
return name;
}
};
int main() {
Laptop desk;
desk.create("Laptop");
return 0;
} | true |
e9afe8e98745ffe07e2b9675cc7a0bf22ed251d6 | C++ | Ixox/NeoPixel-Projects | /NeoLampe/src/main.cpp | UTF-8 | 1,751 | 2.640625 | 3 | [] | no_license | /*
Copyright © 2018, Xavier Hosxe
Free license, do what you want with these files
*/
#include "LedSpot.h"
#include "LedControl.h"
// Neopixel D2
#define PIN_NEOPIXEL A5
// Pushbutton D3
#define PIN_PUSHBUTTON A4
// analog input
#define PIN_POT A0
#define NUMPIXELS 7
#define EEPROM_SPOT_ADDRESS 0
// initialize led spot !
LedSpot ledSpot = LedSpot(NUMPIXELS, PIN_NEOPIXEL);
LedControl ledControl = LedControl(PIN_PUSHBUTTON, PIN_POT);
/*
Initialize pin mode
*/
void setup()
{
// Pin Mode for Pot (GND and 5V) and button GND
pinMode(A1, OUTPUT);
pinMode(A2, OUTPUT);
pinMode(A3, OUTPUT);
digitalWrite(A1, LOW);
digitalWrite(A2, HIGH);
digitalWrite(A3, LOW);
// START !
ledSpot.loadStateFromEEPROM(EEPROM_SPOT_ADDRESS);
ledSpot.acknowledge(Adafruit_NeoPixel::Color(0, 150, 0));
ledControl.init();
}
bool memorySaved = false;
void loop()
{
unsigned long time = millis();
ledControl.updateValues();
// animation
ledSpot.animationNextStep();
if (ledControl.hasNewPotValue())
{
ledSpot.setAnimationSpeed(ledControl.getPotValue());
}
// Set Brightness if button pushed for more than 1 sec
if (ledControl.hasNewPotValueButtonPushed())
{
ledSpot.setBrightness(ledControl.getPotValue());
}
if (ledControl.buttonClick())
{
ledSpot.nextAnimation();
ledControl.reinitPotThreshold();
}
if (ledControl.buttonClick1Second() && !memorySaved)
{
ledSpot.saveStateToEEPROM(EEPROM_SPOT_ADDRESS);
ledSpot.acknowledge(Adafruit_NeoPixel::Color(150, 150, 0));
ledControl.reinitPotThreshold();
}
ledSpot.show();
// Wait for 20 ms
while (millis() < (time + 20))
;
}
| true |
f2fcd0625424ba3666c0a8f663dc3eab6b663dda | C++ | esteban-andrade/projects | /pfms-2019a-Johnson15177-master/scratch/tutorial/week6/main.cpp | UTF-8 | 1,067 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <queue>
using namespace std;
void sumQueue(queue<int> &numbers, mutex &mtx, int total) {
mtx.lock();
while (!numbers.empty()) {
//Use mutex
total += numbers.front();
numbers.pop();
//unlock so the other class
mtx.unlock();
mtx.lock();
}
mtx.unlock();
}
int main ()
{
/* part 1 */
queue<int> numbers;
for (int i =1; i< 500000; i++)
{
numbers.push(i);
numbers.push(-i);
}
// We will use this mutex to synchonise access to num
mutex mtx;
int sub_total1=0;
int sub_total2=0;
// Create the threads
thread t1(sumQueue,ref(numbers),ref(mtx), ref(sub_total1));
thread t2(sumQueue,ref(numbers),ref(mtx), ref(sub_total2));
// Wait for the threads to finish (they wont)
t1.join();
t2.join();
cout<< "Subtotals " << sub_total1 << " " << sub_total2 << endl;
cout<< "Combined total = " << sub_total1 + sub_total2 << endl;
return 0;
}
| true |
74fe2284e79c3d1419a1c34b32fadb71888354d5 | C++ | DerekCresswell/Thoth | /src/RenderElement.cpp | UTF-8 | 2,421 | 3.359375 | 3 | [
"MIT"
] | permissive |
#include <Thoth/RenderElement.hpp>
namespace Thoth {
/* Public */
// Constructs a RenderElement
RenderElement::RenderElement(const std::string& tag)
: tag(tag) {}
// Constructs a RenderElement with content
RenderElement::RenderElement(const std::string& tag, const contentType& content)
: tag(tag), content(content) {}
/* Protected */
// Renders the Element as HTML
std::stringstream RenderElement::RenderOutput(IndentData indentData) {
// the stream to render into
std::stringstream strm;
// Setup indents
std::string tagIndent = GetIndent(indentData);
indentData.depth++;
std::string contentIndent = GetIndent(indentData);
// Apply tag
strm << tagIndent << "<" << tag;
// Format attributes
if(attributes.size() > 0) {
strm << " ";
// Last attribute must be isolated to prevent the last space being added
auto lastIt = attributes.end();
lastIt--;
// Loop through every attribute except the last
for(auto it = attributes.begin(); it != lastIt; it++) {
strm << (*it)->Format() << " ";
}
strm << (*lastIt)->Format();
}
// Close the tag
strm << ">";
// Insert content
bool hasContent = true;
if(std::string* contentStr = std::get_if<std::string>(&content)) {
// If there is no content 'contentStr' will be an empty string
if(hasContent = !contentStr->empty()) {
strm << "\n" << contentIndent << *contentStr << "\n";
}
} else if(RenderElement **contentElm = std::get_if<RenderElement*>(&content)) {
// A new line must be added since no content is only detected
// as a string
strm << "\n";
(*contentElm)->RenderOutput(strm, indentData);
} else {
hasContent = false;
}
// Close tag
if(hasContent)
strm << tagIndent;
strm << "</" << tag << ">\n";
return strm;
}
// Renders the Element as HTML
void RenderElement::RenderOutput(std::stringstream& strm, IndentData indentData) {
// Calls RenderOutput to generate stringstream to insert
strm << RenderOutput(indentData).str();
}
} // namespace Thoth | true |
f69e07969524e2632acfbfd7e8d287c58d597172 | C++ | bhattsachin/falcon | /src/parser/BaseParser.cpp | UTF-8 | 5,145 | 2.640625 | 3 | [] | no_license | /*
* BaseParser.cpp
*
* Created on: Sep 23, 2011
* Author: Zhiliang SU
*/
#include "BaseParser.h"
BaseParser::BaseParser() {
}
void BaseParser::initParser(string stwFileUrl){
stwListPath = stwFileUrl;
if (stwList.size() == 0 || charExclude.size() == 0) {baseParserInit();}
}
BaseParser::~BaseParser() {
flushMe();
// TODO Auto-generated destructor stub
}
void BaseParser::baseParserInit(){
//create stop word list
ifstream* ifsPt = new ifstream();
ifsPt->open(stwListPath.c_str(), ios::in);
string currentTerm;
while(*ifsPt >> currentTerm){
stwList.push_back(currentTerm);
}
ifsPt->close();
//char define not punctuation
charExclude.push_back(45);
for(int i=48; i<=57; i++){charExclude.push_back(i);}
for(int i=65; i<=90; i++){charExclude.push_back(i);}
for(int i=97; i<=122; i++){charExclude.push_back(i);}
}
void BaseParser::baseParseProc(vector<string> inputTerms){
// TODO complete base parsing process
for(int i=0; (unsigned int)i<inputTerms.size(); i++){
inputTerms[i] = basePunc(inputTerms[i]);
inputTerms[i] = baseHyphen(inputTerms[i]);
}
// merge
semwiki.baseParsedTerms.insert(semwiki.baseParsedTerms.end(), inputTerms.begin(), inputTerms.end());
semwiki.baseParsedTerms.insert(semwiki.baseParsedTerms.end(), addTerms.begin(), addTerms.end());
// stop word removal
baseSTW();
// cases and numbers
for(int i=0; (unsigned int)i<semwiki.baseParsedTerms.size(); i++){
semwiki.baseParsedTerms[i] = baseCase(semwiki.baseParsedTerms[i]);
semwiki.baseParsedTerms[i] = baseNum(semwiki.baseParsedTerms[i]);
}
//stemming proc
for (int i=0; (unsigned int)i<semwiki.baseParsedTerms.size(); i++){
semwiki.baseParsedTerms[i] = baseStem(semwiki.baseParsedTerms[i]);
}
//sort and unique
sort(semwiki.baseParsedTerms.begin(), semwiki.baseParsedTerms.end());
semwiki.baseParsedTerms.erase(unique(semwiki.baseParsedTerms.begin(), semwiki.baseParsedTerms.end()), semwiki.baseParsedTerms.end());
//remove empty terms
if (semwiki.baseParsedTerms[0] == ""){
semwiki.baseParsedTerms.erase(semwiki.baseParsedTerms.begin());
}
}
string BaseParser::baseCase(string inTerm){
// TODO normalize all letter cases into lower-case
for(unsigned int i=0; i<inTerm.length(); i++){
if(inTerm[i]>=65 && inTerm[i]<=90){
inTerm[i] = inTerm[i] + 32;
}
}
return inTerm;
}
string BaseParser::baseNum(string inTerm){
// TODO nothing
return inTerm;
}
void BaseParser::baseSTW(){
//TODO remove stop-words
for(int i=0; (unsigned int)i < stwList.size(); i++){
semwiki.baseParsedTerms.erase(remove( semwiki.baseParsedTerms.begin(),semwiki.baseParsedTerms.end() , stwList[i] ) ,semwiki.baseParsedTerms.end());
}
}
string BaseParser::basePunc(string inTerm){
// TODO remove punctuation characters
vector<int>::iterator it;
string separateItem="";
/*
for(int i=0; (unsigned int)i<inTerm.size(); i++){
it = find(charExclude.begin(), charExclude.end(), (int)inTerm[i]);
if (it == charExclude.end()){
inTerm[i] = ' ';
}
}*/
for (int i=0; (unsigned int)i<inTerm.size(); i++){
if((inTerm[i]>=48&&inTerm[i]<=57)||(inTerm[i]>=65&&inTerm[i]<=90)||(inTerm[i]>=97&&inTerm[i]<=122)||(inTerm[i]==45)){
//do nothing to word/num/hyphens
}else{
inTerm[i]=' ';
}
}
string combStr = "";
string delimar = " ";
vector<string> token;
const string& inputT = inTerm;
const string& deli = delimar;
vector<string>& outputT = token;
baseToolSplit(inputT, deli, outputT);
for (int i=0; (unsigned int)i<token.size(); i++){
combStr += token[i];
}
return combStr;
}
string BaseParser::baseHyphen(string inTerm){
// TODO remove hyphens and return combined term and store divided terms into 'addTerms' vector
string comStr = "";
string delimar = "-";
vector<string> token;
const string& inputT = inTerm;
const string& deli = delimar;
vector<string>& outputT = token;
baseToolSplit(inputT, deli, outputT);
addTerms.insert(addTerms.end(),token.begin(),token.end());
for(unsigned int i=0 ; i<token.size(); i++){
if (i==0){
comStr += token[i];
}else{
comStr += deli + token[i];
}
}
return comStr;
}
string BaseParser::baseStem(string inTerm){
// TODO do nothing dummy foo...
return inTerm;
}
void BaseParser::baseToolSplit(const string& str, const string& delim, vector<string>& parts) {
size_t start, end = 0;
while (end < str.size()) {
start = end;
while (start < str.size() && (delim.find(str[start]) != string::npos)) {
start++; // skip initial whitespace
}
end = start;
while (end < str.size() && (delim.find(str[end]) == string::npos)) {
end++; // skip to end of word
}
if (end-start != 0) { // just ignore zero-length strings.
parts.push_back(string(str, start, end-start));
}
}
}
void BaseParser::flushMe(){
// TODO clean base parser variance
semwiki.baseParsedTerms.clear();
semwiki.baseParsedTerms.erase(semwiki.baseParsedTerms.begin(),semwiki.baseParsedTerms.end());
addTerms.clear();
addTerms.erase(addTerms.begin(),addTerms.end());
}
BaseParser::SemWiki BaseParser::parse(string filename){
vector<string> vec;
vec.push_back("foo");
vec.push_back("bar");
semwiki.baseParsedTerms = vec;
return semwiki;
}
| true |
48dcd0b979fb080bbfee1b4399d4a284a16f1402 | C++ | HOLINHED/coding-challenges | /cppclasses/player.cpp | UTF-8 | 520 | 3.375 | 3 | [] | no_license | #include "player.h"
Player::Player(int lev, int h, std::string n) {
level = lev;
health = h;
name = n;
printf("HALLO!!! [Constructor]\n");
}
void Player::damage(int amount) {
health -= amount;
}
void Player::heal(int amount) {
health += amount;
}
void Player::levelUp() {
level += 1;
}
void Player::greet() {
printf("Hi! I'm %s!\n", name.c_str());
}
void Player::stats() {
printf("[%s] Level: %d | %d\n", name.c_str(), level, health);
}
Player::~Player() {
printf("Bye bye! [Destructor]\n");
} | true |
0451b76dabc2ad562425634adc3a6a5203847e47 | C++ | dfinch-vlk/dfinch | /cpp_modules/cpp_module02/ex01/Fixed.hpp | UTF-8 | 446 | 2.828125 | 3 | [] | no_license | #ifndef FIXED_CPP
# define FIXED_CPP
# include <iostream>
class Fixed
{
public:
int getRawBits(void) const;
void setRawBits(int const raw);
Fixed & operator=(const Fixed &n);
int toInt(void) const;
float toFloat(void) const;
Fixed(const int n);
Fixed(const float n);
Fixed(const Fixed &n);
Fixed();
~Fixed();
private:
int value;
static const int bits = 8;
};
std::ostream &operator<<(std::ostream &out, Fixed const &value);
#endif | true |
8557b8aa2d4512013dc5ef00269839560243b8ac | C++ | triffon/oop-2019-20 | /exercises/5/ex08/samples/polymorph_vector.cpp | UTF-8 | 2,388 | 3.515625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <cstring>
#include "vector.cpp"
using std::cout;
using std::endl;
/*
Vector<T> Object (print, ++)
| / | | \
PolyVector Int Double Char
*/
// Object
class Object {
public:
virtual void print() = 0;
virtual Object & operator++() = 0;
};
// Int
class Int : public Object {
public:
Int(int);
void print();
Int & operator++();
Int operator++(int);
private:
int x;
};
Int::Int(int _x) : x(_x) {}
void Int::print() {
cout << x << endl;
}
Int & Int::operator++() {
++x;
return *this;
}
Int Int::operator++(int) {
Int ret(*this);
++x;
return ret;
}
// Double
class Double : public Object {
public:
Double(double);
void print();
Double & operator++();
private:
double x;
};
Double::Double(double _x) : x(_x) {
++x;
}
void Double::print() {
cout << x << endl;
}
Double & Double::operator++() {}
// Char
class Char : public Object {
public:
Char(char);
void print();
Char & operator++();
private:
char x;
};
Char::Char(char _x) : x(_x) {
++x;
}
void Char::print() {
cout << x << endl;
}
Char & Char::operator++() {}
//typedef Vector<Object *> PolyVector;
// PolyVector
class PolyVector : public Vector<void *>, public Object {
public:
void print();
PolyVector & operator++();
};
void PolyVector::print() {
for (int i = 0; i < size(); ++i) {
Object * ptr;
//ptr = (Object *)(get(i));
ptr = (Object *)((*this)[i]);
ptr->print();
}
}
PolyVector & PolyVector::operator++() {
// TODO: increment all data in vector
}
// Main
int main() {
/*
Vector<int> vi;
vi.push(10);
vi.push(11);
vi.push(12);
for (int i = 0; i < vi.size(); ++i) {
cout << vi[i] << endl;
}
*/
/*
Vector<Object *> vo;
vo.push(new Int(10));
vo.push(new Char('z'));
vo.push(new Double(2.5));
for (int i = 0; i < vo.size(); ++i) {
vo[i]->print();
}
*/
PolyVector vo;
vo.push(new Int(10));
vo.push(new Char('z'));
vo.push(new Double(2.5));
for (int i = 0; i < vo.size(); ++i) {
((Object *)vo[i])->print();
}
vo.print();
Int i1(10);
i1.print();
++i1;
i1.print();
i1++;
i1.print();
(i1++).print();
(++i1).print();
return 0;
}
| true |