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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f4f5a36189abf7c7adb709fe272f68533462da1f | C++ | ajbajb/ARTTECH3135-fall2018 | /code_day05/05_01_BouncingBallClass/src/Ball.cpp | UTF-8 | 1,474 | 3.15625 | 3 | [] | no_license | #include "Ball.h"
Ball::Ball()
{
// this is our contructor
// we give default values to our Ball object
// when it is created
px = ofGetWidth()/2;
py = ofGetHeight()/2;
topSpeed = 20;
vx = topSpeed;
vy = topSpeed;
ax = -0.09;
ay = -0.09;
dx = 1;
dy = -1;
radius = 20;
c = ofColor::fromHsb(ofRandom(255), 255, 255);
}
Ball::~Ball()
{
// reallocating memory
// (What do we we do with the memory of our destroyed object?)
// we are not going to worry about this
}
void Ball::setup()
{
// we can setup our individual object here
// if we want
}
void Ball::update()
{
// updating all the position variables
// velocity decreases with acceleration
if (vx > 0)
{
vx += ax;
}
if (vy > 0)
{
vy += ay;
}
// update position with velocity
px += vx * dx;
py += vy * dy;
// check out walls!
if (px < radius) // left wall
{
px = radius;
dx *= -1;
vx = topSpeed;
vy = topSpeed - 3;
}
if (px > ofGetWidth() - radius) // right wall
{
px = ofGetWidth() - radius;
dx *= -1;
vx = topSpeed;
vy = topSpeed - 3;
}
if (py < radius) // top wall
{
py = radius;
dy *= -1;
vx = topSpeed - 3;
vy = topSpeed;
}
if (py > ofGetHeight() - radius) // bottom wall
{
py = ofGetHeight() - radius;
dy *= -1;
vx = topSpeed - 3;
vy = topSpeed;
}
}
void Ball::draw()
{
ofSetColor(c);
ofFill();
ofDrawCircle(px, py, radius);
ofSetColor(255);
ofDrawLine(px, py, px + radius, py);
}
| true |
c9d1e6b5edcaa775bf37ea6b7a965b6a4b89946d | C++ | zsc1993916/AcmTemplate | /Math/常用.cpp | UTF-8 | 2,223 | 2.84375 | 3 | [] | no_license | /*
筛素数 O(n)
*/
const int N=100;
bool isPrime[N] ; //数组定义该数字是否为素数
int prime[N] ; // 存下素数
int total = 0 ; //第几个素数
void seive(){
memset( isPrime , true , sizeof( isPrime ));
memset( prime , 0 , sizeof( prime ));
isPrime[0 ] = false ;
isPrime[1] = false ;
for ( int i = 2 ; i <= N ; i++ ){
if ( isPrime[i] ) prime[ ++ total ] = i ;
for ( int j = 1 ; j <= total && i * prime[j] <= N ; j++) {
isPrime[ i * prime[j] ] = false ;
if (!( i % prime[j])) break;
}
}
}
/*
反素数就是满足对于任意i(0<i<x),都有g(i)<g(x),(g(x)是x的因子个数),则x为一个反素数
*/
const int antiprime[]={1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,
7560,10080,15120,20160,25200,27720,45360,50400,55440,83160,110880,
166320,221760,277200,332640,498960,554400,665280,720720,1081080};
/*
下面是反素数表打印的代码
*/
LL bestNum; //约数最多的数
LL bestSum; //约数最多的数的约数数
const int M=1000; //反素数的个数
LL Maxn=1000000;// 求n以内的 所有反素数
LL rprim[M][2]; // rprim 代表反素数
LL prim[]={2,3,5,7,11,13,17,19,23,29,31,33,37};
void getNum(LL num,LL k,LL sum,LL limit) {
if(num>Maxn)return;
if(sum>bestSum)
bestSum = sum, bestNum = num;
else if(sum == bestSum && num < bestNum)
bestNum = num;
if(k>=9) return;
for(LL i=1,p=1;i<=limit;i++){
p*=prim[k];
getNum(num*p,k+1,sum*(i+1),i);
}
}
LL log2(LL n){ //求大于等于log2(n)的最小整数
LL i = 0, p = 1;
while(p<n) p*=2, i++;
return i;
}
int getrprim(){//反素数的个数
int i = 0;
while(Maxn>0){
bestNum = 1, bestSum = 1;
getNum(1,0,1,log2(Maxn));
Maxn = bestNum - 1;
rprim[i][0]=bestNum;
rprim[i][1]=bestSum;
i++;
}
return i;
}
int main(){
int tot = getrprim();
printf("%d\n",tot);
for(int i=tot-1; i>=0; i--) printf("%d : %I64d %I64d\n", i, rprim[i][0], rprim[i][1] );
return 0;
}
| true |
badf5c1f6a52e807724811501251912c5fc9baf4 | C++ | enfortune/OrcsMustDie | /D3D_base/cRay.cpp | UTF-8 | 896 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "cRay.h"
cRay::cRay()
: m_vPos(0, 0, 0)
, m_vDir(0, 0, 0)
{
}
cRay::~cRay()
{
}
cRay cRay::RayAtViewSpace(int nScreenX, int nScreenY)
{
D3DVIEWPORT9 vp;
g_pD3DDevice->GetViewport(&vp);
D3DXMATRIXA16 matProj;
g_pD3DDevice->GetTransform(D3DTS_PROJECTION, &matProj);
cRay r;
r.m_vDir.x = ((2.0 * nScreenX) / vp.Width - 1.0f) / matProj._11;
r.m_vDir.y = ((-2.0 * nScreenY) / vp.Height + 1.0f) / matProj._22;
r.m_vDir.z = 1.0f;
return r;
}
cRay cRay::RayAtWorldSpace(int nScreenX, int nScreenY)
{
cRay r = RayAtViewSpace(nScreenX, nScreenY);
D3DXMATRIXA16 matView, matInvView;
g_pD3DDevice->GetTransform(D3DTS_VIEW, &matView);
D3DXMatrixInverse(&matInvView, 0, &matView);
D3DXVec3TransformCoord(&r.m_vPos, &r.m_vPos, &matInvView);
D3DXVec3TransformNormal(&r.m_vDir, &r.m_vDir, &matInvView);
D3DXVec3Normalize(&r.m_vDir, &r.m_vDir);
return r;
}
| true |
12c0999d1c14e7a4b3d2969d818cdbf1a4b7c5c7 | C++ | shabre/load_balancing | /ldServer_static partitioning/ldServer/map.hpp | UTF-8 | 678 | 2.65625 | 3 | [] | no_license | //
// map.hpp
// dynamic partitioning
//
// Created by Shabre on 2017. 10. 27..
// Copyright © 2017년 Shabre. All rights reserved.
//
#ifndef map_hpp
#define map_hpp
#include <iostream>
#include <list>
struct position{
float x;
float y;
float z;
};
class zone{
private:
int numOfMember;
struct position *playerPos;
bool *online;
std::list<int> playerList;
public:
zone();
};
class map{
private:
zone *myZone;
int zoneNum;
int serverNum;
int *zoneServer;
public:
map(int zoneNum, int serverNum);
void serverShift(zone myZone, int beforeServer, int afterServer);
void playerShift();
};
#endif /* map_hpp */
| true |
b1e9c7ba1adbedec597834d06996cc61b8f3e4e2 | C++ | ritik005/DataStructure-Implement | /Algorithm/Sorting/InsertionSort.cpp | UTF-8 | 531 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void insertionSort(int arr[], int n){
int i,no,j;
for(i = 1; i < n; i++){
j = i - 1;
no = arr[i];
while(j >= 0 && arr[j] > no){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = no;
}
}
void print(int arr[], int n){
int i;
for(i = 0; i < n; i++){
printf("%d", arr[i]);
printf("\n");
}
}
int main(void) {
int arr[1000007], n,i;
cin >> n;
for(i = 0; i < n; i++){
cin >> arr[i];
}
insertionSort(arr,n);
print(arr,n);
return 0;
} | true |
16e0dd7d16acaa6c62ccd56c22aed1254e54eb0e | C++ | xumenger/xumenger.github.shit | /乱七八糟的实验性的代码/141118/duotai.cpp | UTF-8 | 752 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class TradesPerson{
public:
virtual void sayHi(){
cout<< "Just Hi" <<endl;
}
};
class Tinker : public TradesPerson{
public:
virtual void sayHi(){
cout<< "Hi, I Tinker!" <<endl;
}
};
class Tailor : public TradesPerson{
public:
virtual void sayHi(){
cout<< "Hi, I Tailor!" <<endl;
}
};
int main(){
srand(time(0));
TradesPerson* ptrs[10];
unsigned which, i;
for(i=0; i<10; i++){
which = 1 + rand()%3;
switch(which){
case 1:
ptrs[i] = new TradesPerson;
break;
case 2:
ptrs[i] = new Tinker;
break;
case 3:
ptrs[i] = new Tailor;
break;
}
}
for(i=0; i<10; i++){
ptrs[i]->sayHi();
delete ptrs[i];
}
return 0;
}
| true |
e9dc923bea1146a0462cd7f6532efabf8f068711 | C++ | salisbury-robotics/jks-ros-pkg | /teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/VolumeRenderer.h | UTF-8 | 3,755 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef VOLUMERENDERER_H
#define VOLUMERENDERER_H
#include "Common/Volume.h"
#include "Common/Labelling.h"
#include "ProxyGeometry.h"
#include "TransferFunction.h"
#include <cml/mathlib/typedef.h>
#include <QGLShaderProgram>
typedef QGLShaderProgram ShaderProgram;
class VolumeRenderer
{
public:
enum VolumeRole { vrPrimary, vrSecondary, vrLabels, vrMask, vrSentinel };
protected:
bool m_initialized;
ShaderProgram *m_rayCastShader;
// store different shaders that can be used... (TODO: unify these?)
enum ShaderMode { smRayCast, smRayCastLabels, smSentinel };
ShaderProgram *m_shaders[smSentinel];
// volume properties
static const int k_volumes = 4;
Volume *m_volumes[k_volumes];
GLuint m_volumeTextures[k_volumes];
// the scale factor between world space 0-1 and volume texture space
cml::vector3f m_textureScale;
// the scale factor between world space 0-1 and physical space (in mm)
float m_physicalScale;
// coordinates of the center of the volume (nominally .5, .5, .5)
cml::vector3f m_volumeCenter;
// transfer function properties
static const int k_tfTextureSize = 4096;
TransferFunction m_transferFunctions[k_volumes];
GLuint m_transferTextures[k_volumes];
unsigned char m_transferBytes[k_tfTextureSize*4];
// isosurface rendering properties
float m_isosurfaceValue;
cml::vector4f m_isosurfaceColor;
// renderer parameters
float m_rayStep;
float m_gradientDelta;
// helper functions
cml::vector3f currentViewPosition();
void uploadVolumeTexture(VolumeRole vr, int z0 = -1, int z1 = -1);
void uploadTransferFunction(VolumeRole vr);
public:
VolumeRenderer();
virtual ~VolumeRenderer();
virtual void initialize();
virtual void render(ProxyGeometry *proxy, GLuint distanceTexture);
// re-uploads part of the mask volume between z0 and z1 to reflect changes
virtual void updateMask(int z0, int z1) { uploadVolumeTexture(vrMask, z0, z1); }
virtual void resetMask();
Volume *getMask() { return m_volumes[vrMask]; }
virtual void setVolume(Volume *v, VolumeRole role = vrPrimary)
{
m_volumes[role] = v;
if (m_initialized) uploadVolumeTexture(role);
}
// need a special case for the labels volume, the way it's done now
// TODO: can we refactor to fix this?
virtual void setLabels(Volume *v, Volume *m, Labelling *lab);
virtual void setTransferFunction(const TransferFunction &tf,
VolumeRole role = vrPrimary)
{
m_transferFunctions[role] = tf;
if (m_initialized) uploadTransferFunction(role);
}
// accessors for isosurface parameters
float isosurfaceValue() { return m_isosurfaceValue; }
cml::vector4f isosurfaceColor() { return m_isosurfaceColor; }
// mutators for isosurface parameters
void setIsosurfaceValue(float value)
{ m_isosurfaceValue = value; }
void setIsosurfaceColor(const cml::vector4f &color)
{ m_isosurfaceColor = color; }
// mutators for renderer parameters
void setRayStep(float step) { m_rayStep = step; }
void setGradientDelta(float delta) { m_gradientDelta = delta; }
// accessor for scale factor from world to physical size (in mm)
float physicalScale() const { return m_physicalScale; }
// accessor for the center point of the current volume
cml::vector3f volumeCenter() const { return m_volumeCenter; }
};
#endif // VOLUMERENDERER_H
| true |
c5a49b385d16f7ab85a0600e629cf41a0ba4b942 | C++ | malin666/MyProject | /Default_Delete/main.cpp | UTF-8 | 1,662 | 3.703125 | 4 | [] | no_license | // defaultDelete.cpp
// Methoden aktivieren oder deaktivieren.
// -----------------------------------------------------
// Achtung: Die neue Syntax von C++11 zum Aktivieren und
// Deaktivieren von Methoden mit default und delete wird
// von vielen Compilern noch nicht unterstütz!
// -----------------------------------------------------
#include <iostream>
using namespace std;
class DefaultDeleteDemo
{
double val;
public:
// Default-Konstruktor aktivieren:
DefaultDeleteDemo() = default;
// Konstruktor mit einem Parameter für val:
DefaultDeleteDemo( double x) { val = x; }
// Kein ganzzahliges Argument zulassen:
DefaultDeleteDemo( int x) = delete;
// Kopierkonstruktor und Zuweisung nicht zulassen:
DefaultDeleteDemo( const DefaultDeleteDemo& n) = delete;
DefaultDeleteDemo& operator=( const DefaultDeleteDemo& n) = delete;
// Zugriffsmethoden:
double getVal() const { return val; }
void setVal( double x) { val = x; }
// Kein ganzzahliges Argument zulassen:
void setVal( int x) = delete;
};
int main()
{
DefaultDeleteDemo ddObj1, // Default-Konstruktor.
ddObj2(2.2); // double-Konstruktor.
ddObj1.setVal(1.1);
cout << "Werte: \n"
<< ddObj1.getVal() << " " << ddObj2.getVal() << endl;
// Folgende Anweisungen erzeugen Fehlermeldungen des Compilers:
/*
ddObj1 = ddObj2; // Keine Zuweisung.
DefaultDeleteDemo ddObj3(ddObj2), // Kein Kopierkonstruktor.
ddObj4(100); // Kein int-Konstruktor.
ddObj1.setVal(200); // Keine int-Version.
*/
return 0;
} | true |
a66e4244ab77b4a6e32c4b665da1be833de2da9c | C++ | olsonadr/16x-work | /cs162/local/labs/lab-6-olsonadr/application.cpp | UTF-8 | 843 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include "Rectangle.hpp"
#include "Square.hpp"
#include "Circle.hpp"
int main()
{
Square square("Red", 5);
Circle circle("Blue", 3);
Rectangle rect("Green", 5, 10);
std::cout << "square is a "<< square.get_name()
<< ", is " << square.get_color()
<< ", has side length of " << square.get_side_length()
<< ", and has an area of " << square.area()
<< std::endl;
std::cout << "circle is a " << circle.get_name()
<< ", is " << circle.get_color()
<< ", has radius of " << circle.get_radius()
<< ", and has an area of " << circle.area()
<< std::endl;
std::cout << "rect is a " << rect.get_name()
<< ", is " << rect.get_color()
<< ", has width of " << rect.get_width()
<< ", has height of " << rect.get_height()
<< ", and has an area of " << rect.area()
<< std::endl;
return 0;
}
| true |
8774cd0b5ba3644d3d597dacefcfa0f9707cc4ce | C++ | hellosuzie/SuzieDeadByDaylight | /SSDEngine/DXHeader.cpp | UHC | 20,000 | 2.890625 | 3 | [] | no_license | #include"DXHeader.h"
const float _tagVEC2::Cross(const _tagVEC2& _Other)
{
return DirectX::XMVector2Cross(*this, _Other).m128_f32[0];
}
const float _tagVEC2::Dot(const _tagVEC2& _Other)
{
return DirectX::XMVector2Dot(*this, _Other).m128_f32[0];
}
_tagVEC2 _tagVEC2::operator=(const _tagVEC2& _Other)
{
x = _Other.x;
y = _Other.y;
return *this;
}
_tagVEC2 _tagVEC2::operator+(const _tagVEC2& _Other) const
{
_tagVEC2 Result;
Result.x = x + _Other.x;
Result.y = y + _Other.y;
return Result;
}
_tagVEC2 _tagVEC2::operator+=(const _tagVEC2& _Other)
{
x += _Other.x;
y += _Other.y;
return *this;
}
_tagVEC2 _tagVEC2::operator-(const _tagVEC2& _Other) const
{
_tagVEC2 Result;
Result.x = x - _Other.x;
Result.y = y - _Other.y;
return Result;
}
_tagVEC2 _tagVEC2::operator-=(const _tagVEC2& _Other)
{
x -= _Other.x;
y -= _Other.y;
return *this;
}
_tagVEC2 _tagVEC2::operator*(const _tagVEC2& _Other) const
{
_tagVEC2 Result;
Result.x = x * _Other.x;
Result.y = y * _Other.y;
return Result;
}
_tagVEC2 _tagVEC2::operator*=(const _tagVEC2& _Other)
{
x *= _Other.x;
y *= _Other.y;
return *this;
}
_tagVEC2 _tagVEC2::operator*(const float& _Scala) const
{
return _tagVEC2(x*_Scala, y*_Scala);
}
_tagVEC2 _tagVEC2::operator*=(const float& _Scala)
{
x *= _Scala;
y *= _Scala;
return *this;
}
_tagVEC2 _tagVEC2::operator/(const float& _Scala) const
{
return _tagVEC2(x*_Scala, y*_Scala);
}
_tagVEC2 _tagVEC2::operator/=(const float& _Scala)
{
x *= _Scala;
y *= _Scala;
return *this;
}
_tagVEC2 _tagVEC2::operator*(const struct _tagMAT& _Mat) const
{
Vec2 Result = *this;
for (size_t i = 0; i < 2; i++)
Result.pf[i] = x * _Mat.M[0][i] + y * _Mat.M[1][i];
return Result;
}
_tagVEC2 _tagVEC2::operator*=(const struct _tagMAT& _Mat)
{
_tagVEC2 Temp = *this;
for (size_t i = 0; i < 2; i++)
pf[i] = Temp.x * _Mat.M[0][i] + Temp.y * _Mat.M[1][i];
return *this;
}
const bool _tagVEC2::operator==(const _tagVEC2& _Other) const
{
return (x == _Other.x )&& (y == _Other.y);
}
const bool _tagVEC2::operator!=(const _tagVEC2& _Other) const
{
return (x != _Other.x) || (y != _Other.y);
}
const float _tagVEC2::Length() const
{
if (*this == _tagVEC2(1.f, 0.f) || *this == _tagVEC2(0.f, 1.f) )
return 1.f;
//return sqrtf((x*x) + (y*y));
return DirectX::XMVector2Length(*this).m128_f32[0];
}
_tagVEC2 _tagVEC2::GetNormalizeVec() const
{
float Len = this->Length();
// ̰ 0 Ͱ ȯѴ.
if (0.f == Len)
return *this;
if (1.f == Len)
return *this;
//return _tagVEC2(this->x / Len, this->y / Len);
return Vec2(DirectX::XMVector2Normalize(*this));
}
void _tagVEC2::Normalize()
{
float Len = this->Length();
// ̰ 0 ȭ ʴ´.
if (0.f == Len)
return;
if (1.f == Len)
return;
//this->x /= Len;
//this->y /= Len;
*this = DirectX::XMVector2Normalize(*this);
}
/////////////////////////////////////////////// Vec3 /////////////////////////////
_tagVEC3 _tagVEC3::Zero3{ 0.f,0.f,0.f };
_tagVEC3 _tagVEC3::One3{ 1.f,1.f,1.f };
_tagVEC3 _tagVEC3::Right3{ 1.f,0.f,0.f };
_tagVEC3 _tagVEC3::Left3{ -1.f,0.f,0.f };
_tagVEC3 _tagVEC3::Up3{ 0.f,1.f,0.f };
_tagVEC3 _tagVEC3::Down3{ 0.f, -1.f,0.f };
_tagVEC3 _tagVEC3::Forward3{ 0.f,0.f,1.f };
_tagVEC3 _tagVEC3::Back3{ 0.f,0.f,-1.f };
_tagVEC3 _tagVEC3::operator=(const _tagVEC3& _Other)
{
x = _Other.x;
y = _Other.y;
z = _Other.z;
return *this;
}
_tagVEC3 _tagVEC3::operator=(const _tagVEC2& _Other)
{
x = _Other.x;
y = _Other.y;
z = 0.f;
return *this;
}
_tagVEC3 _tagVEC3::operator=(const DirectX::XMVECTOR& _XMVec)
{
DirectX::XMStoreFloat3(&XMF3, _XMVec);
return *this;
}
_tagVEC3 _tagVEC3::operator+(const _tagVEC3& _Other) const
{
_tagVEC3 Result;
Result.x = x + _Other.x;
Result.y = y + _Other.y;
Result.z = z + _Other.z;
return Result;
}
_tagVEC3 _tagVEC3::operator+=(const _tagVEC3& _Other)
{
x += _Other.x;
y += _Other.y;
z += _Other.z;
return *this;
}
_tagVEC3 _tagVEC3::operator-(const _tagVEC3& _Other) const
{
_tagVEC3 Result;
Result.x = x - _Other.x;
Result.y = y - _Other.y;
Result.z = z - _Other.z;
return Result;
}
_tagVEC3 _tagVEC3::operator-=(const _tagVEC3& _Other)
{
x -= _Other.x;
y -= _Other.y;
z -= _Other.z;
return *this;
}
_tagVEC3 _tagVEC3::operator*(const _tagVEC3& _Other) const
{
_tagVEC3 Result;
Result.x = x * _Other.x;
Result.y = y * _Other.y;
Result.z = z * _Other.z;
return Result;
}
_tagVEC3 _tagVEC3::operator*=(const _tagVEC3& _Other)
{
x *= _Other.x;
y *= _Other.y;
z *= _Other.z;
return *this;
}
_tagVEC3 _tagVEC3::operator*(const struct _tagMAT& _Mat) const
{
Vec3 Result = *this;
for (size_t i = 0; i < 3; i++)
Result.pf[i] = x * _Mat.M[0][i] + y * _Mat.M[1][i] + z * _Mat.M[2][i];
return Result;
}
_tagVEC3 _tagVEC3::operator*=(const struct _tagMAT& _Mat)
{
Vec3 Temp = *this;
for (size_t i = 0; i < 3; i++)
pf[i] = Temp.x * _Mat.M[0][i] + Temp.y * _Mat.M[1][i] + Temp.z * _Mat.M[2][i];
return *this;
}
const _tagVEC4 _tagVEC3::GetVec4_Normal() const
{
return _tagVEC4(x, y, z, 0.f);
}
const _tagVEC4 _tagVEC3::GetVec4_Coord() const
{
return _tagVEC4(x, y, z, 1.f);
}
const float _tagVEC3::Length() const
{
if (*this == _tagVEC3::Right3 || *this == _tagVEC3::Up3 || *this == _tagVEC3::Forward3
|| *this == _tagVEC3::Left3 || *this == _tagVEC3::Down3 || *this == _tagVEC3::Back3)
return 1.f;
//return sqrtf((x*x) + (y*y) + (z*z));
return DirectX::XMVector3Length(*this).m128_f32[0];
}
const float _tagVEC3::Length_Square() const
{
if (*this == _tagVEC3::Right3 || *this == _tagVEC3::Up3 || *this == _tagVEC3::Forward3
|| *this == _tagVEC3::Left3 || *this == _tagVEC3::Down3 || *this == _tagVEC3::Back3)
return 1.f;
return ((x * x) + (y * y) + (z * z));
}
_tagVEC3 _tagVEC3::GetNormalizeVec() const
{
float Len = this->Length();
// ̰ 0 Ͱ ȯѴ.
if (0.f == Len)
return *this;
if (1.f == Len)
return *this;
//return _tagVEC3(this->x / Len, this->y / Len, this->z / Len);
return Vec3(DirectX::XMVector3Normalize(*this));
}
void _tagVEC3::Normalize()
{
float Len = this->Length();
// ̰ 0 ȭ ʴ´.
if (0.f == Len)
return;
if (1.f == Len)
return;
//this->x /= Len;
//this->y /= Len;
//this->z /= Len;
*this = DirectX::XMVector3Normalize(*this);
}
_tagVEC3::_tagVEC3(const DirectX::XMVECTOR& _XMVector)
{
DirectX::XMStoreFloat3(&XMF3,_XMVector);
}
/////////////////////////////////////////////////// Vec4 ///////////////////////////////////
_tagVEC4 _tagVEC4::Zero = _tagVEC4(0.f, 0.f, 0.f, 0.f);
_tagVEC4 _tagVEC4::One = _tagVEC4(1.f, 1.f, 1.f, 1.f);
_tagVEC4 _tagVEC4::White = _tagVEC4(1.f, 1.f, 1.f, 1.f);
_tagVEC4 _tagVEC4::Black = _tagVEC4(0.f, 0.f, 0.f, 1.f);
_tagVEC4 _tagVEC4::Red = _tagVEC4(1.f, 0.f, 0.f, 1.f);
_tagVEC4 _tagVEC4::Green = _tagVEC4(0.f, 1.f, 0.f, 1.f);
_tagVEC4 _tagVEC4::Blue = _tagVEC4(0.f, 0.f, 1.f, 1.f);
_tagVEC4 _tagVEC4::Yellow = _tagVEC4(1.f, 1.f, 0.f, 1.f);
_tagVEC4 _tagVEC4::Cyan = _tagVEC4(0.f, 1.f, 1.f, 1.f);
_tagVEC4 _tagVEC4::Magenta = _tagVEC4(1.f, 0.f, 1.f, 1.f);
_tagVEC4 _tagVEC4::Pink = _tagVEC4(0.94f, 0.72f, 0.78f, 1.f);
_tagVEC4 _tagVEC4::PastelRed = _tagVEC4(1.f, 0.43f, 0.43f, 1.f);
_tagVEC4 _tagVEC4::Mint = _tagVEC4(0.81f, 1.f, 0.89f, 1.f);
_tagVEC4 _tagVEC4::LightYellow = _tagVEC4(1.f, 0.89f, 0.45f, 1.f);
_tagVEC4 _tagVEC4::PastelGreen = _tagVEC4(0.71f, 1.f, 0.61f, 1.f);
_tagVEC4 _tagVEC4::Lavender = _tagVEC4(0.58f, 0.62f, 0.74f, 1.f);
_tagVEC4 _tagVEC4::PastelMag = _tagVEC4(0.90f, 0.68f, 0.9f, 1.f);
_tagVEC4 _tagVEC4::PastelBlue = _tagVEC4(0.28f, 0.64f, 1.f, 1.f);
_tagVEC4 _tagVEC4::operator-() const
{
_tagVEC4 ReturnVec;
ReturnVec.x = -x;
ReturnVec.y = -y;
ReturnVec.z = -z;
ReturnVec.w = -w;
return ReturnVec;
}
_tagVEC4 _tagVEC4::operator=(const _tagVEC4& _Other)
{
x = _Other.x;
y = _Other.y;
z = _Other.z;
w = _Other.w;
return *this;
}
_tagVEC4 _tagVEC4::operator=(const _tagVEC3& _Vec3)
{
x = _Vec3.x;
y = _Vec3.y;
z = _Vec3.z;
w = 0.f;
return *this;
}
_tagVEC4 _tagVEC4::operator=(const _tagVEC2& _Vec2)
{
x = _Vec2.x;
y = _Vec2.y;
z = 0.f;
w = 0.f;
return *this;
}
_tagVEC4 _tagVEC4::operator=(const DirectX::XMVECTOR& _XMVec)
{
DirectX::XMStoreFloat4(&XMF4, _XMVec);
return *this;
}
_tagVEC4 _tagVEC4::operator+(const _tagVEC4& _Other) const
{
_tagVEC4 Result;
Result.x = x + _Other.x;
Result.y = y + _Other.y;
Result.z = z + _Other.z;
Result.w = w + _Other.w;
return Result;
}
_tagVEC4 _tagVEC4::operator+=(const _tagVEC4& _Other)
{
x += _Other.x;
y += _Other.y;
z += _Other.z;
w += _Other.w;
return *this;
}
_tagVEC4 _tagVEC4::operator-(const _tagVEC4& _Other) const
{
_tagVEC4 Result;
Result.x = x - _Other.x;
Result.y = y - _Other.y;
Result.z = z - _Other.z;
Result.w = w - _Other.w;
return Result;
}
_tagVEC4 _tagVEC4::operator-=(const _tagVEC4& _Other)
{
x -= _Other.x;
y -= _Other.y;
z -= _Other.z;
w -= _Other.w;
return *this;
}
_tagVEC4 _tagVEC4::operator*(const _tagVEC4& _Other) const
{
_tagVEC4 Result;
Result.x = x * _Other.x;
Result.y = y * _Other.y;
Result.z = z * _Other.z;
Result.w = w * _Other.w;
return Result;
}
_tagVEC4 _tagVEC4::operator*=(const _tagVEC4& _Other)
{
x *= _Other.x;
y *= _Other.y;
z *= _Other.z;
w *= _Other.w;
return *this;
}
_tagVEC4 _tagVEC4::operator*(const float& _Scala) const
{
return _tagVEC4(x*_Scala, y*_Scala, z*_Scala, w*_Scala);
}
_tagVEC4 _tagVEC4::operator*=(const float& _Scala)
{
x *= _Scala;
y *= _Scala;
z *= _Scala;
w *= _Scala;
return *this;
}
_tagVEC4 _tagVEC4::operator/(const float& _Scala) const
{
return _tagVEC4(x / _Scala, y / _Scala, z / _Scala, w / _Scala);
}
const bool _tagVEC4::operator==(const _tagVEC4& _Other) const
{
return (_Other.x == x && _Other.y == y && _Other.z == z && _Other.w == w);
}
const bool _tagVEC4::operator!=(const _tagVEC4& _Other) const
{
return (_Other.x != x || _Other.y != y || _Other.z != z || _Other.w != w);
}
_tagVEC4 _tagVEC4::operator*(const struct _tagMAT& _Mat) const
{
_tagVEC4 Result;
for (size_t i = 0; i < 4; i++)
Result.pf[i] =
x * _Mat.M[0][i]
+ y * _Mat.M[1][i]
+ z * _Mat.M[2][i]
+ w * _Mat.M[3][i];
if (1.f != Result.w && 0.f != Result.w)
{
for (size_t i = 0; i < 3; i++)
Result.pf[i] /= Result.w;
Result.w = 1.f;
}
return Result;
}
_tagVEC4 _tagVEC4::operator*=(const struct _tagMAT& _Mat)
{
_tagVEC4 Temp = *this;
for (size_t i = 0; i < 4; i++)
pf[i] = Temp.x * _Mat.M[0][i]
+ Temp.y * _Mat.M[1][i]
+ Temp.z * _Mat.M[2][i]
+ Temp.w * _Mat.M[3][i];
if (1.f != w && 0.f != w)
{
for (size_t i = 0; i < 3; i++)
pf[i] /= w;
w = 1.f;
}
return *this;
}
const _tagMAT _tagVEC4::GetQuatRotationMat()
{
_tagMAT ReturnMat;
DirectX::XMStoreFloat4x4(&ReturnMat.XMF4x4, DirectX::XMMatrixRotationQuaternion(DirectX::XMLoadFloat4(&XMF4) ));
return ReturnMat;
}
IVEC4 _tagVEC4::GetIVec4() const
{
IVEC4 Result;
Result.ix = (int)x;
Result.iy = (int)y;
Result.iz = (int)z;
Result.iw = (int)w;
return Result;
}
IVEC4 _tagVEC4::ConversionIVec4()
{
ix = (int)x;
iy = (int)y;
iz = (int)z;
iw = (int)w;
return *this;
}
const float _tagVEC4::Length_Vec3() const
{
return DirectX::XMVector3Length(*this).m128_f32[0];
}
const Vec3 _tagVEC4::GetNormalize_Vec3() const
{
return Vec3(DirectX::XMVector3Normalize(*this));
}
void _tagVEC4::Normalize_Vec3()
{
*this = Vec3(DirectX::XMVector3Normalize(*this));
}
const float _tagVEC4::Length() const
{
return DirectX::XMVector4Length(*this).m128_f32[0];
}
const Vec4 _tagVEC4::GetNormalizeVec() const
{
return Vec4(DirectX::XMVector4Normalize(*this));
}
void _tagVEC4::Normalize()
{
*this = DirectX::XMVector4Normalize(*this);
}
const POINT _tagVEC4::GetPoint() const
{
return POINT{ (LONG)x,(LONG)y };
}
const int _tagVEC4::GetARGB() const
{
IVEC4 Color = IVEC4((int)(r*255), (int)(g * 255), (int)(b * 255), (int)(a * 255));
return Color.ia << 24 | Color.ir << 16 | Color.ig << 8 | Color.ib ;
}
const int _tagVEC4::GetRGBA() const
{
IVEC4 Color = IVEC4((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255));
return Color.ir << 24 | Color.ig << 16 | Color.ib << 8 | Color.ia;
}
const int _tagVEC4::GetABGR() const
{
IVEC4 Color = IVEC4((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255));
return Color.ia << 24 | Color.ib << 16 | Color.ig << 8 | Color.ir;
}
_tagVEC4::_tagVEC4(const DirectX::XMVECTOR& _XMVec)
{
DirectX::XMStoreFloat4(&XMF4, _XMVec);
}
_tagVEC4::_tagVEC4(const _tagVEC3& _Axis, const float& _Angle)
{
DirectX::XMStoreFloat4(&XMF4, DirectX::XMQuaternionRotationNormal(_Axis, _Angle));
//DirectX::XMStoreFloat4(&XMF4, DirectX::XMVector3Normalize(_Axis.GetXMVector()));
//(*this) *= sinf(_Angle*0.5f);
//w = cosf(_Angle*0.5f);
}
_tagVEC4::_tagVEC4(const _tagVEC3& _Vec3)
:x(_Vec3.x), y(_Vec3.y), z(_Vec3.z), w(0.f)
{
}
_tagVEC4::_tagVEC4(const _tagVEC2& _Vec2)
: x(_Vec2.x), y(_Vec2.y), z(0.f), w(0.f)
{
}
//////////////////////////////////////////// Matrix ////////////////////////////////////////////
void _tagMAT::DivisionWorldMat(DirectX::XMVECTOR* _Scale, DirectX::XMVECTOR* _Rot, DirectX::XMVECTOR* _Pos, const _tagMAT& _World)
{
DirectX::XMMatrixDecompose(_Scale, _Rot, _Pos, _World);
}
void _tagMAT::DivisionWorldMat(_tagVEC3* _Scale, _tagVEC4* _Rot, _tagVEC3* _Pos, const _tagMAT& _World)
{
*_Scale = _World.GetScaleFactor().vec3;
*_Rot = _World.GetAxisQuaternion();
*_Pos = _World.Row[3].vec3;
}
const bool _tagMAT::operator==(const _tagMAT& _Other)
{
for (size_t j = 0; j < 4; j++)
{
for (size_t i = 0; i < 4; i++)
{
if (M[j][i] != _Other.M[j][i])
return false;
}
}
return true;
}
void _tagMAT::operator=(const _tagMAT& _Other)
{
memcpy_s(M, sizeof(M), _Other.M, sizeof(_Other.M));
}
void _tagMAT::operator=(const DirectX::XMFLOAT4X4& _Mat)
{
XMF4x4 = _Mat;
}
const _tagMAT _tagMAT::operator*(const _tagMAT& _Other) const
{
_tagMAT Result;
for (size_t j = 0; j < 4; j++)
{
for (size_t i = 0; i < 4; i++)
{
Result.M[j][i] =
M[j][0] * _Other.M[0][i]
+ M[j][1] * _Other.M[1][i]
+ M[j][2] * _Other.M[2][i]
+ M[j][3] * _Other.M[3][i];
}
}
return Result;
}
const _tagMAT _tagMAT::operator*=(const _tagMAT& _Other)
{
_tagMAT Temp;
for (size_t j = 0; j < 4; j++)
{
for (size_t i = 0; i < 4; i++)
{
Temp.M[j][i] =
M[j][0] * _Other.M[0][i]
+ M[j][1] * _Other.M[1][i]
+ M[j][2] * _Other.M[2][i]
+ M[j][3] * _Other.M[3][i];
}
}
(*this) = Temp;
return *this;
}
const Vec3 _tagMAT::Mul_Normal(const Vec3& _Vec) const
{
return Vec4(_Vec.x, _Vec.y, _Vec.z, 0.f) * (*this);
}
const Vec3 _tagMAT::Mul_Coord(const Vec3& _Vec)const
{
return Vec4(_Vec.x, _Vec.y, _Vec.z, 1.f) * (*this);
}
const Vec4 _tagMAT::MulVec4(const Vec4& _Vec) const
{
_tagVEC4 Result;
for (size_t i = 0; i < 4; i++)
Result.pf[i] = _Vec.x *M[0][i]
+ _Vec.y *M[1][i]
+ _Vec.z * M[2][i]
+ _Vec.w * M[3][i];
return Result;
}
void _tagMAT::SetZeroMat()
{
memset(M, 0, sizeof(_tagMAT));
}
void _tagMAT::SetIdentityMat()
{
// XMMARIX Ŭο ״
// ش Ŭ 16Ʈ ؾѴ.
// SIMD ̿Ͽ 4Ʈ Ʈ ȯ
// Ѵ.
DirectX::XMStoreFloat4x4(&XMF4x4,DirectX::XMMatrixIdentity());
}
void _tagMAT::SetScalingMat(const float& _X, const float& _Y, const float& _Z)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixScaling(_X, _Y, _Z));
}
void _tagMAT::SetScalingMat(const _tagVEC4& _Scale)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixScaling(_Scale.x, _Scale.y, _Scale.z));
}
void _tagMAT::SetScalingMat(const _tagVEC3& _Scale)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixScaling(_Scale.x, _Scale.y, _Scale.z));
}
void _tagMAT::SetRotateXMat(const float& _Rad)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationX(_Rad));
}
void _tagMAT::SetRotateYMat(const float& _Rad)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationY(_Rad));
}
void _tagMAT::SetRotateZMat(const float& _Rad)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationZ(_Rad));
}
void _tagMAT::SetRotateXMat_ForDegree(const float& _Deg)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationX(_Deg*D2R));
}
void _tagMAT::SetRotateYMat_ForDegree(const float& _Deg)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationY(_Deg*D2R));
}
void _tagMAT::SetRotateZMat_ForDegree(const float& _Deg)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixRotationZ(_Deg*D2R));
}
void _tagMAT::SetPosMat(const float& _X, const float& _Y, const float& _Z)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixTranslation(_X,_Y,_Z));
}
void _tagMAT::SetPosMat(const _tagVEC4& _Pos)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixTranslation(_Pos.x, _Pos.y, _Pos.z));
}
void _tagMAT::SetPosMat(const _tagVEC3& _Pos)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixTranslation(_Pos.x, _Pos.y, _Pos.z));
}
void _tagMAT::SetViewAtMat(const _tagVEC4& _EyePos, const _tagVEC4& _AtPos, const _tagVEC4& _UpDir)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixLookAtLH(_EyePos,_AtPos,_UpDir));
}
void _tagMAT::SetViewAtMat(const DirectX::XMVECTOR& _EyePos, const DirectX::XMVECTOR& _AtPos, const DirectX::XMVECTOR& _UpDir)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixLookAtLH(_EyePos, _AtPos, _UpDir));
}
void _tagMAT::SetViewToMat(const _tagVEC4& _EyePos, const _tagVEC4& _AtDir, const _tagVEC4& _UpDir)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixLookToLH(_EyePos, _AtDir, _UpDir));
}
void _tagMAT::SetViewToMat(const DirectX::XMVECTOR&& _Eye, const DirectX::XMVECTOR&& _AtDir, const DirectX::XMVECTOR&& _UpDir)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixLookToLH(_Eye, _AtDir, _UpDir));
}
void _tagMAT::SetOrthoProjMat(const float& _Width,const float& _Height,const float& _Near,const float& _Far)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixOrthographicLH(_Width, _Height, _Near, _Far));
}
void _tagMAT::SetFovPersProjMat(const float& _Fovy, const float& _Aspect, const float& _Near, const float& _Far)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixPerspectiveFovLH(_Fovy, _Aspect, _Near, _Far));
}
void _tagMAT::SetFovPersProjMat_Angle(const float& _FovAng, const float& _Aspect, const float& _Near, const float& _Far)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixPerspectiveFovLH(_FovAng * D2R, _Aspect, _Near, _Far));
}
void _tagMAT::SetPersProjMat(const float& _Width, const float& _Height, const float& _Near, const float& _Far)
{
DirectX::XMStoreFloat4x4(&XMF4x4, DirectX::XMMatrixPerspectiveLH(_Width, _Height, _Near, _Far));
}
const _tagVEC4 _tagMAT::GetColmVec(const int& _Colm) const
{
switch (_Colm)
{
case 0:
return _tagVEC4(_11, _21, _31, _41);
case 1:
return _tagVEC4(_12, _22, _32, _42);
case 2:
return _tagVEC4(_13, _23, _33, _43);
case 3:
return _tagVEC4(_14, _24, _34, _44);
}
return _tagVEC4(MAXINT32, MAXINT32, MAXINT32, MAXINT32);
}
//const _tagVEC4 _tagMAT::GetBasisVec4(const AXIS_TYPE& Axis) const
//{
// switch (Axis)
// {
// case AXIS_TYPE::AXIS_X:
// return _tagVEC4(_11, _21, _31, 0.f);
// case AXIS_TYPE::AXIS_Y:
// return _tagVEC4(_12, _22, _32, 0.f);
// case AXIS_TYPE::AXIS_Z:
// return _tagVEC4(_13, _23, _33, 0.f);
// default :
// return _tagVEC4(MAXINT32, MAXINT32, MAXINT32, MAXINT32);
// }
//
// return _tagVEC4(MAXINT32, MAXINT32, MAXINT32, MAXINT32);
//}
//
//const _tagVEC3 _tagMAT::GetBasisVec(const AXIS_TYPE& Axis) const
//{
// switch (Axis)
// {
// case AXIS_TYPE::AXIS_X:
// return _tagVEC3(_11, _21, _31);
// case AXIS_TYPE::AXIS_Y:
// return _tagVEC3(_12, _22, _32);
// case AXIS_TYPE::AXIS_Z:
// return _tagVEC3(_13, _23, _33);
// default:
// return _tagVEC3(MAXINT32, MAXINT32, MAXINT32);
// }
//
// return _tagVEC3(MAXINT32, MAXINT32, MAXINT32);
//} | true |
d8d9876cfe8455596f5067419ad5b05542bce2a2 | C++ | ANoob0w0/CppPrimer | /StrBlob.h | UTF-8 | 3,770 | 3.140625 | 3 | [] | no_license | #ifndef STRBLOB_H
#define SRTBLOB_H
#include <string>
#include <iostream>
#include <memory>
#include <vector>
class StrBlobPtr;
class ConstStrBlobPtr;
class StrBlob
{
friend class StrBlobPtr;
// friend class ConstStrBlobPtr;
public:
typedef std::vector<std::string>::size_type size_type;
StrBlob() : data(std::make_shared<std::vector<std::string>>()){};
StrBlob(std::initializer_list<std::string> il)
: data(std::make_shared<std::vector<std::string>>(il)){};
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
void push_back(const std::string &t) { data->push_back(t); }
void pop_back();
std::string &front();
std::string &back();
const std::string &front() const;
const std::string &back() const;
StrBlobPtr begin();
StrBlobPtr end();
StrBlobPtr cbegin() const;
StrBlobPtr cend() const;
long getCount() const {return data.use_count();}
~StrBlob() {}
private:
std::shared_ptr<std::vector<std::string>> data;
void check(size_type i, const std::string &msg) const;
};
class StrBlobPtr
{
private:
std::shared_ptr<std::vector<std::string>> check(std::size_t, const std::string &) const;
std::weak_ptr<std::vector<std::string>> wptr;
std::size_t curr;
public:
StrBlobPtr() : curr(0){};
StrBlobPtr(StrBlob &a, std::size_t sz = 0) : wptr(a.data), curr(sz) {}
StrBlobPtr(const StrBlob &a, std::size_t sz = 0) : wptr(a.data), curr(sz) {}
std::string &deref() const;
StrBlobPtr &incr();
bool equal(const StrBlobPtr &) const;
~StrBlobPtr() {}
};
// class ConstStrBlobPtr
// {
// private:
// std::weak_ptr<std::vector<std::string>> wptr;
// std::size_t curr;
// public:
// ConstStrBlobPtr() : curr(0) {}
// ConstStrBlobPtr(const StrBlob &a, std::size_t sz = 0) : wptr(a.data), curr(sz) {}
// std::string &deref() const;
// ~ConstStrBlobPtr() {}
// };
inline void StrBlob::check(size_type i, const std::string &msg) const
{
if (i >= data->size())
throw std::out_of_range(msg);
}
inline void StrBlob::pop_back()
{
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
inline std::string &StrBlob::front()
{
check(0, "front on empty StrBlob");
return data->front();
}
inline std::string &StrBlob::back()
{
check(0, "back on empty StrBlob");
return data->back();
}
inline const std::string &StrBlob::front() const
{
check(0, "front on empty StrBlob");
return data->front();
}
inline const std::string &StrBlob::back() const
{
check(0, "back on empty StrBlob");
return data->back();
}
inline std::shared_ptr<std::vector<std::string>> StrBlobPtr::check(std::size_t i, const std::string &msg) const
{
auto ret = wptr.lock();
if (!ret)
throw std::runtime_error("unbound StrBlobPtr");
if (i > ret->size())
throw std::out_of_range(msg);
return ret;
};
inline std::string &StrBlobPtr::deref() const
{
auto p = check(curr, "dereference past end");
return p->at(curr);
}
inline StrBlobPtr &StrBlobPtr::incr()
{
check(curr, "increment past end of StrBlobPtr");
++curr;
return *this;
}
StrBlobPtr StrBlob::begin() { return StrBlobPtr(*this); }
StrBlobPtr StrBlob::end() { return StrBlobPtr(*this, data->size()); }
StrBlobPtr StrBlob::cbegin() const { return StrBlobPtr(*this); }
StrBlobPtr StrBlob::cend() const { return StrBlobPtr(*this, data->size()); }
bool StrBlobPtr::equal(const StrBlobPtr &p) const
{
if (this->wptr.lock() == p.wptr.lock() && this->curr == p.curr)
return true;
return false;
}
#endif | true |
e435c143680f2545670186b8f9d82fdbb6645046 | C++ | Hyodar/jogo-tecprog | /jogo/src/utils/classes/collision_list.hpp | UTF-8 | 1,686 | 2.515625 | 3 | [
"MIT"
] | permissive |
#ifndef COLLISION_LIST_HPP_
#define COLLISION_LIST_HPP_
#include <vector>
#include <map>
#include <deque>
#include <game_config.hpp>
#include "collision_detecter.hpp"
namespace bardadv::core {
class LevelManager;
}
namespace bardadv::obstacles {
class Obstacle;
}
namespace bardadv::characters {
class Enemy;
class Bardo;
class FielEscudeiro;
}
namespace bardadv::projectiles {
class Projectile;
}
namespace bardadv::map {
class GameMap;
class Tile;
}
namespace bardadv::lists {
using bardadv::obstacles::Obstacle;
using bardadv::characters::Enemy;
using bardadv::characters::Bardo;
using bardadv::characters::FielEscudeiro;
using bardadv::projectiles::Projectile;
using bardadv::map::GameMap;
using bardadv::map::Tile;
class CollisionList {
private:
// containers STL para preencher requisitos,
// como sugerido pelo professor
std::vector<Enemy*> enemies;
std::map<int, Obstacle*> obstacles;
std::deque<Projectile*> projectiles;
Bardo* bardo;
FielEscudeiro* fielEscudeiro;
bardadv::collision::CollisionDetecter collisionDetecter;
public:
CollisionList();
~CollisionList();
void add(Enemy* e);
void add(Obstacle* e);
void add(Projectile* e);
void add(Bardo* e);
void add(FielEscudeiro* e);
void remove(Enemy* e);
void remove(Obstacle* e);
void remove(Projectile* e);
void deallocate();
void testCollisionX();
void testCollisionY();
void testBardoX();
void testBardoY();
void testFielEscudeiroX();
void testFielEscudeiroY();
void testEnemiesX();
void testEnemiesY();
void testProjectiles();
void testHitPoints();
};
}
#endif // COLLISION_LIST_HPP_
| true |
5245f888e895fa85e9fe7f96f7283f2613239db3 | C++ | pcx229/OpensslWrapper | /src/encoder/hex.h | UTF-8 | 948 | 2.890625 | 3 | [] | no_license |
#ifndef _HEX_H_
#define _HEX_H_
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
#include "encoder.h"
namespace crypto {
class Hex : public BlockEncoder {
public:
~Hex();
/**
* a wrapper for Encode() block function
* @param data a bytes object to encode
* @returns a hex bytes representing the data
*/
bytes Encode(const bytes& data);
/**
* encode a raw data to a hex bytes
* @param data an array of characters to encode
* @param length size of the data array
* @returns a hex bytes representing the data
*/
bytes Encode(const unsigned char *data, size_t length);
/**
* decode a hex bytes to the original raw data
* @param data a hex bytes
* @returns the original raw data the this hex bytes representing
* @throw invalid_argument exception if the data is not a valid hex string
*/
bytes Decode(const bytes& data);
};
}
#endif
| true |
0f966fcc90e0bab5cc545a123da2a7448dd6d84f | C++ | dcamvik2020/Full-code-base | /Coursera C++/White/week 4/Files/PrintToBinFileFromSS/main.cpp | UTF-8 | 3,886 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void PrintToBinFileFromSS(ofstream& output, stringstream& SS) {
char c; /// only '0' and '1'
char tmp = 0;
char cnt; /// counter of bits 0/1
for (cnt = 0; 1; ++cnt) {
SS >> c;
if (SS.fail() == false) {
//cout << "Char : " << c << endl;
if (cnt < 8) {
/// 2*63+1 = 127 (max char)
tmp = 2 * tmp + (c - '0');
} else {
cout << tmp;
output << tmp;
tmp = 0;
cnt = 0;
}
} else {
break;
}
}
cout << tmp;
output << tmp;
}
void Reverse(string& s) {
for (unsigned i = 0; i < s.size() / 2; ++i) {
swap(s[i], s[s.size() - i - 1]);
}
}
int my_strncmp(const string& s1, const string& s2 ,unsigned len) {
if (s1.size() < len || s2.size() < len) {
return s1.size() - s2.size();
} else {
for (unsigned i = 0; i < len; ++i) {
if (s1[i] != s2[i]) {
return s1[i] - s2[i];
}
}
}
return 0;
}
void PrintFromBinFileToSS(ifstream& input, stringstream& SS, vector<string> codes) {
char c; /// c --> string of '0', '1'
string buf = ""; /// buffer for not used parts
while (1) {
input >> c;
if (input.fail() == false) {
string s = buf;
/// get string of '0', '1' from "c" -- code
while (c) {
s += '0' + c % 2;
c /= 2;
}
Reverse(s);
/// now, find code or save it in buf
bool read_all = false;
while (s.size() && read_all == false) {
unsigned how_many_read = 0;
for (unsigned i = 0; i < codes.size(); ++i, ++how_many_read) {
//cout << " codes[i] : " << codes[i]
// << " s.size() = " << s.size()
// << " s = " << s;
int res = my_strncmp(s, codes[i], codes[i].size());
if (res == 0) {
/// they equal -->
SS << (char)('a' + i);
for (unsigned j = codes[i].size(); j < s.size(); j++) {
s[j - codes.size()] = s[j];
}
s.resize(s.size() - codes[i].size());
if (buf.size() >= codes[i].size()) {
buf.resize(buf.size() - codes[i].size());
}
/*for (unsigned j = codes[i].size(); j < buf.size(); j++) {
buf[j - codes.size()] = buf[j];
}
buf[buf.size() - codes[i].size()] = 0;
*/
//cout << " buf = " << buf << endl;
break;
}
//cout << endl;
}
if (how_many_read == codes.size()) {
read_all = true;
}
}
/// the rest we ssave in buf
buf += s;
} else {
break;
}
}
//cout << SS.str() << endl;
}
int main()
{
// string line;
// cin >> line; /// 0 and 1
vector<string> codes;
codes.push_back("10");
codes.push_back("11");
/* ofstream output;
output.open("output.txt", ios::binary | ios::out);
stringstream SS(line);
PrintToBinFileFromSS(output, SS);
output.close();
*/
ifstream input;
input.open("output.txt", ios::binary | ios::in);
stringstream SS1;
PrintFromBinFileToSS(input, SS1, codes);
cout << "str = " << SS1.str() << endl;
return 0;
}
| true |
02c423c37fdb680741b3455a13d616294cc636d5 | C++ | pokevii/GrizzellJoshua_CSC17A_43396 | /Hmwk/Gaddis Chapter 13 Classes/Ga9EdC13P7/TestScores.cpp | UTF-8 | 595 | 2.8125 | 3 | [] | no_license | class TestScores{
private:
int test1;
int test2;
int test3;
public:
TestScores(int t1, int t2, int t3){
test1 = t1;
test2 = t2;
test3 = t3;
}
TestScores(){
test1 = 0;
test2 = 0;
test3 = 0;
}
void setTest1(int t1) { test1 = t1; }
void setTest2(int t2) { test2 = t2; }
void setTest3(int t3) { test3 = t3; }
int getTest1() { return test1; }
int getTest2() { return test2; }
int getTest3() { return test3; }
float getAvg(){
float avg = (test1 + test2 + test3) / 3;
return avg;
}
}; | true |
1bb5be1fa40e4a3d98aa681f511b48676595bb1e | C++ | Andres-Alvarez-V/sintax-reader | /binario.cpp | UTF-8 | 372 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "arbol.h"
#include "operador.h"
#include "binario.h"
using namespace std;
Binario::Binario(Operador oper, Arbol izq, Arbol der){
this->oper= &oper;
this->izq= &izq;
this->der= &der;
}
Operador* Binario::getOper(){
return oper;
}
Arbol* Binario::getIzq(){
return izq;
}
Arbol* Binario::getDer(){
return der;
}
| true |
772c6868269a05179e8543e732a457a2d21b46c0 | C++ | kennyrkun/Atraxian | /Atraxian/Filesystem.cpp | UTF-8 | 3,353 | 3.3125 | 3 | [
"MIT"
] | permissive | #include "logger.hpp"
#include <filesystem>
#include <fstream>
namespace environment {
namespace filesystem
{
namespace fs = std::experimental::filesystem;
bool exists(std::string thing_that_may_or_may_not_be_real)
{
if (fs::exists(thing_that_may_or_may_not_be_real))
return true;
else
return false;
}
bool create_dir(std::string name, std::string dir)
{
logger::INFO("Creating directory '" + name + "' in '" + dir + "'...");
if (!exists(dir + "\\" + name)) // doesn't already exist
{
fs::create_directory(dir + "\\" + name);
// make sure it was created.
if (exists(name))
{
logger::INFO("Success!");
return true;
}
else // something fucked up.
{
logger::INFO("Failed.");
return false;
}
}
else // is already a thing, skip.
{
logger::WARNING("Directory '" + name + "' already exists in '" + dir + "', skipping.");
return false;
}
}
bool create_file(std::string name, std::string dir)
{
logger::INFO("Creating file '" + name + "' in '" + dir + "'...");
if (exists(dir + "\\" + name)) // if the file already exists
{
logger::WARNING("File '" + name + "' already exists in '" + dir + "', skipping.");
return false;
}
else // does not exist, create it.
{
if (!exists(dir))
{
logger::WARNING("Specified directory does not exist, skipping.");
return false;
}
else // directory exists, continue.
{
std::ofstream file_created(dir + "\\" + name);
file_created.close();
if (exists(dir + "\\" + name)) // file was created successfully.
{
logger::INFO("Success!");
return true;
}
else // something fucked up.
{
logger::INFO("Failed.");
return false;
}
}
}
}
bool move(std::string file_or_dir, std::string to)
{
logger::INFO("Moving '" + file_or_dir + "' to '" + to + "'...");
if (!exists(file_or_dir))
{
logger::ERROR("Specified file or directory does not exist.");
return false;
}
else
{
if (exists(to))
{
if (exists(to + "\\" + file_or_dir))
{
fs::copy(file_or_dir, to);
fs::remove(file_or_dir);
logger::INFO("Success!");
return true;
}
else // already exists
{
logger::INFO("Specified file or directory already exists in destination directory.");
return false;
}
}
else // destination does not exits
{
logger::ERROR("Specified destination directory does not exist.");
return false;
}
}
}
bool remove(std::string thing_to_remove)
{
logger::INFO("Removing '" + thing_to_remove + "'.");
if (exists(thing_to_remove))
{
fs::remove(thing_to_remove);
if (!exists(thing_to_remove))
{
logger::INFO("Success!");
return true;
}
else
{
logger::ERROR("Failed.");
return false;
}
}
else
{
logger::ERROR("Specified file does not exist.");
return false;
}
}
bool rename(std::string dir, std::string file, std::string newname)
{
logger::INFO("Renaming '" + file + "' to '" + newname + "'.");
if (exists(dir + "\\" + file))
{
if (std::rename(file.c_str(), newname.c_str()) == 0)
{
logger::INFO("Success!");
return true;
}
else
{
logger::ERROR("Failed.");
return false;
}
}
else
{
logger::ERROR("Specified file does not exist.");
return false;
}
}
} // filesystem
} | true |
803e8794be70e23d325d873c38232facd89bfbb2 | C++ | cies96035/CPP_programs | /TOJ/已註解,整碼/toj513.cpp | UTF-8 | 695 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
//record a time
struct CLOCK
{
int h;
int m;
}a,b,c={24,00};
//if A earlier than B
bool clockcompare(CLOCK A,CLOCK B)
{
if(A.h!=B.h)return A.h<B.h;
return A.m<B.m;
}
//two times' delta
CLOCK dclock(CLOCK A,CLOCK B)
{
CLOCK C;
//make A bigger than B
if(clockcompare(A,B))
swap(A,B);
C.m=A.m-B.m;
C.h=A.h-B.h;
if(C.m<0)
{
C.m+=60;
C.h-=1;
}
return C;
}
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cin>>a.h>>a.m>>b.h>>b.m;
//if(b<a) than they cross differant days
if(clockcompare(b,a))
c=dclock(c,dclock(a,b));
else
c=dclock(a,b);
cout<<"totally "<<c.h<<" hours and "<<c.m<<" minutes."<<'\n';
return 0;
}
| true |
c592f260be86c2f0f54ec7d71f073c36a9761195 | C++ | nNbSzxx/ACM | /cf/18.11.12 ed54 div2/C.cpp | UTF-8 | 709 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int MAX = 1005;
int d;
int main()
{
int t;
scanf("%d", &t);
while (t --) {
scanf("%d", &d);
double l = d / 2.0, r = d;
for (int i = 0; i < MAX; i ++) {
double a = (l + r) / 2.0;
double b = d - a;
if (a * b < d) {
r = a;
} else {
l = a;
}
}
if (abs(l * (d - l) - d) > 1e-6) {
puts("N");
continue;
} else {
printf("Y ");
printf("%.9f %.9f\n", l, d - l);
}
}
return 0;
}
| true |
482891008e88c4eeea5448740cfb79c92be50cff | C++ | slashvar/algolia-back-to-school | /DataStructures/lists/lists.h | UTF-8 | 1,396 | 3.640625 | 4 | [
"BSD-2-Clause"
] | permissive | /*
* lists.h: classical linked lists implementation
*/
#pragma once
template <typename T>
struct list
{
list() = default;
struct cell
{
cell* next = nullptr;
T value;
};
size_t size()
{
size_t s = 0;
for (auto cur = head.next; cur != nullptr; cur = cur->next, ++s) {
continue;
}
return s;
}
void push_front(cell* elm)
{
elm->next = head.next;
head.next = elm;
if (tail == &head) {
tail = elm;
}
}
cell* front()
{
return head.next;
}
cell* pop()
{
cell* res = head.next;
if (head.next != nullptr) {
head.next = head.next->next;
}
if (head.next == nullptr) {
tail = &head;
}
return res;
}
struct iterator
{
iterator& operator++()
{
if (cur != nullptr) {
cur = cur->next;
}
return *this;
}
T& operator*()
{
return cur->next->value;
}
const T& operator*() const
{
return cur->next->value;
}
cell* cur;
};
iterator begin()
{
return { &head };
}
iterator end()
{
return { tail };
}
cell head;
cell* tail = &head;
};
| true |
c055586fc6eb63c6d1de8cdcd4a4573b0bdb76a6 | C++ | noorsingh/ds_library | /Cases_Graph.cpp | UTF-8 | 3,444 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// function used for i/o in sublime text
void input() {
#ifndef ONLINE_JUDGE
freopen("C:/Users/noor/Documents/Sublime/input.txt", "r", stdin);
freopen("C:/Users/noor/Documents/Sublime/output.txt", "w", stdout);
#endif
}
vector<array<int, 3>> generate_graph(bool IS_DIRECTED, bool IS_CONNECTED, int BASE, int nodes, int MAX_WEIGHT) {
int MIN_EDGES = nodes - 1;
int MAX_EDGES = (nodes * (nodes - 1));
if (!IS_DIRECTED) MAX_EDGES /= 2;
int edges_count = MIN_EDGES + rand() % (MAX_EDGES - MIN_EDGES + 1);
vector<array<int, 3>> edges(edges_count); // final selected edges
vector<array<int, 3>> possible_edges(MAX_EDGES); // possible edges
set<pair<int, int>> present; // already included edges
// List of all unique possible edges except self edge
for (int i = BASE, ind = 0; i < BASE + nodes; i++)
for (int j = (IS_DIRECTED) ? BASE : i + 1; j < BASE + nodes; j++)
if (i != j) possible_edges[ind++] = {i, j, 1 + rand() % MAX_WEIGHT};
unsigned seed = std::chrono::system_clock:: now().time_since_epoch().count();
shuffle(possible_edges.begin(), possible_edges.end(), default_random_engine(seed));
int index = edges_count; // index variable for final selected edges
// For connected graph, n-1 minimum edges for connecting the graph randomly at first
if (IS_CONNECTED) {
int size_connec = 1, size_single = nodes - 1;
vector<int> single(size_single, BASE); // to be connected nodes
vector<int> connec(nodes); // connected nodes
connec[0] = BASE + nodes - 1;
for (int i = 0; i < size_single; i++)
single[i] += i;
unsigned seed = 0;
shuffle(single.begin(), single.end(), default_random_engine(seed));
for (int i = 1; i < nodes; i++) {
int x = connec[rand() % size_connec];
int y = single[--size_single];
connec[size_connec++] = y;
if (!IS_DIRECTED and x > y) swap(x, y);
edges[--index] = {x, y, 1 + rand() % MAX_WEIGHT};
present.insert({x, y});
}
}
// If connected, select remaining edges randomly from possible edges
// Else, select all edges randomly from possible edges
int remaining = (IS_CONNECTED ? edges_count - nodes + 1 : edges_count);
for (int i = 0; index--; i++) {
if (IS_CONNECTED)
while (present.count({possible_edges[i][0], possible_edges[i][1]}))
i++;
edges[index] = possible_edges[i];
}
sort(edges.begin(), edges.end());
return edges;
}
// Can also be done by: select a vertex x randomly(or iterate) & select y randomly and join them
// But Eg: n=1000 and edges = n*(n-1) - 10, Then at last, {x,y} will be already existing and it would take very long to complete
int main() {
input();
ios_base::sync_with_stdio(false); cin.tie(0);
srand(time(0));
int BASE = 1; // nodes starting from 0 or 1 // 0 or 1 (or even higher)
int MAX_CASES = 1;
int MAX_NODES = 10;
int MAX_WEIGHT = 100;
bool IS_WEIGHTED = 0;
bool IS_DIRECTED = 0;
bool IS_CONNECTED = 1;
int test_cases;
test_cases = 1 + rand() % MAX_CASES;
// cout << test_cases << "\n";
while (test_cases--) {
int nodes = 1 + rand() % MAX_NODES;
auto graph = generate_graph(IS_DIRECTED, IS_CONNECTED, BASE, nodes, MAX_WEIGHT);
// cout << "Total Nodes: ";
cout << nodes << "\n";
// cout << "Total Edges: ";
cout << graph.size() << "\n";
for (auto edge : graph) {
cout << edge[0] << " " << edge[1];
if (IS_WEIGHTED) cout << " " << edge[2];
cout << "\n";
}
cout << "\n";
}
return 0;
} | true |
188a08bd1bfb6220481232484930fe3113332ce6 | C++ | SuhasChandrashekar/Order-Management-System | /FrontOfficeUser.cpp | UTF-8 | 14,447 | 2.75 | 3 | [] | no_license | #include "stdafx.h"
#include<PkFramework.h>
#include<DAL.h>
#include"FrontOfficeUser.h"
#include"Order.h"
#include"OMSException.h"
#include<fstream>
#include<string>
#include<iostream>
using namespace std;
Order *orderObj[25];
int orderCount;
std::ofstream ErrorFile("ErrorFile.txt",std::ofstream::out);
bool CheckItemInDb(DALTransaction& trans,char* itemId);
bool CheckOrderInDb(DALTransaction& trans,int index);
bool CheckWhetherShipped(DALTransaction& trans,int index);
bool CheckWhetherCancelled(DALTransaction& trans,int index);
void FrontOfficeUser::Menu(DALTransaction& trans)
{
int choice;
do
{
cout<<"\n\n==========Front Office User Menu=========="<<endl;
cout<<"\n\n1.Supply batch file\n2.Change Password\n3.Log Out\n4.Exit\n"<<endl;
cout<<"\nEnter your choice"<<endl;
cin>>choice;
switch(choice)
{
case 1:SupplyBatchFile(trans);
break;
case 2:ChangePassword(trans);
break;
case 3:break;
case 4:exit(0);
default:cout<<"Invalid input";
}
}while(choice!=3);
}
void FrontOfficeUser::SupplyBatchFile(DALTransaction& trans)
{
char fileName[20],orderId[20],shipTo[20],orderStatus[20],createTime[20],modifyTime[20],temp[20],itemId[20],itemQuantity[20];
orderCount=0;
LineItem *itemObj;
cout<<"\nEnter the file name"<<endl;
cin>>fileName;
ifstream myfile(fileName);
try
{
//throw an exception if file cannot be opened
if(!myfile.is_open())
{
throw OMSException("File cannot be opened");
}
while(!myfile.eof())
{
myfile.getline(orderId,20,'~');
myfile.getline(shipTo,20,'~');
myfile.getline(orderStatus,20,'~');
myfile.getline(createTime,20,'~');
myfile.getline(modifyTime,20,'~');
myfile.getline(temp,20,'~');
//create an order obj for each order
orderObj[orderCount]=new Order(orderId,shipTo,orderStatus,createTime,modifyTime);
//$ specifies the end of items in an order in my batch file
while(strcmp(temp,"$")!=0)
{
myfile.getline(itemId,20,'~');
myfile.getline(itemQuantity,20,'~');
myfile.getline(temp,20,'~');
//create a lineItem Obj for each item and link it the order Obj
LineItem *itemObj=new LineItem(itemId,itemQuantity);
orderObj[orderCount]->AddNewLineItem(itemObj);
if(myfile.eof())
break;
}
//orderObj[orderCount]->DisplayOrderDetails();
orderCount++;
}
cout<<"\n\nBatch file successfully submitted"<<endl;
validate(trans);
}
catch(OMSException& exceptionObj)
{
cout<<exceptionObj.ErrorText()<<endl;
}
}
void FrontOfficeUser::validate(DALTransaction& trans)
{
int counter;
bool valid,orderExists,shipped,cancelled;
char itemId[20],itemQuantity[20];
//validate for each order
for(counter=0;counter<orderCount;counter++)
{
valid=true;
if(orderObj[counter]->GetItemList()!=NULL)
{
for(LineItem* temp=orderObj[counter]->GetItemList();temp!=NULL && valid==1;temp=temp->GetNextItem())
{
strcpy(itemId,temp->GetItemId());
strcpy(itemQuantity,temp->GetItemQuantity());
//check for valid quantity and write in errorfile if invalid
if(atoi(itemQuantity)<0)
{
valid=false;
ErrorFile<<"Quantity of Item "<<temp->GetItemId()<<" in Order "<<orderObj[counter]->GetOrderId()<<" is invalid!!! Order discarded"<<endl;
}
//check for valid item and write in errorfile if invalid
else if(!CheckItemInDb(trans,itemId))
{
valid=false;
ErrorFile<<"Item "<<temp->GetItemId()<<" in Order "<<orderObj[counter]->GetOrderId()<<" is invalid!!! Order discarded"<<endl;
}
}
}
if(valid)
{
//for insert
if(strcmp(orderObj[counter]->GetOrderStatus(),"1")==0)
{
orderExists=CheckOrderInDb(trans,counter);
cancelled=CheckWhetherCancelled(trans,counter);
shipped=CheckWhetherShipped(trans,counter);
if(!orderExists)
InsertOrder(trans,counter);
else
ErrorFile<<"Order "<<orderObj[counter]->GetOrderId()<<" Already Present...Cannot Insert"<<endl;
}
//for update
else if(strcmp(orderObj[counter]->GetOrderStatus(),"2")==0)
{
orderExists=CheckOrderInDb(trans,counter);
cancelled=CheckWhetherCancelled(trans,counter);
shipped=CheckWhetherShipped(trans,counter);
if(orderExists)
{
if(!cancelled)
{
if(!shipped)
UpdateOrder(trans,counter);
else
ErrorFile<<"Update Failed...Order "<<orderObj[counter]->GetOrderId()<<" already shipped"<<endl;
}
else
ErrorFile<<"Update Failed...Order "<<orderObj[counter]->GetOrderId()<<" already cancelled"<<endl;
}
else
ErrorFile<<"Update Failed...Order "<<orderObj[counter]->GetOrderId()<<" Not Present"<<endl;
}
//for cancel
else if(strcmp(orderObj[counter]->GetOrderStatus(),"3")==0)
{
orderExists=CheckOrderInDb(trans,counter);
cancelled=CheckWhetherCancelled(trans,counter);
shipped=CheckWhetherShipped(trans,counter);
if(orderExists)
{
if(!cancelled)
{
if(!shipped)
CancelOrder(trans,counter);
else
ErrorFile<<"Cancellation Failed...Order "<<orderObj[counter]->GetOrderId()<<" already shipped"<<endl;
}
else
ErrorFile<<"Cancellation Failed...Order "<<orderObj[counter]->GetOrderId()<<" already cancelled"<<endl;
}
else
ErrorFile<<"Cancellation Failed...Order "<<orderObj[counter]->GetOrderId()<<" Not Present"<<endl;
}
}
}
}
void FrontOfficeUser::InsertOrder(DALTransaction& trans,int index)
{
cout<<"Inserting..."<<endl;
char orderId[20],shipTo[20],orderStatus[20],createDateTime[20],modifyDateTime[20],orderId1[20],itemId[20],itemQuantity[20],createDay[5],createMonth[5],createYear[5],modifyDay[5],modifyMonth[5],modifyYear[5];
int createDd,createMm,createYy,modDd,modMm,modYy;
strcpy(orderId,orderObj[index]->GetOrderId());
strcpy(shipTo,orderObj[index]->GetShipTo());
strcpy(orderStatus,"1");
strcpy(createDateTime,orderObj[index]->GetCreateDateTime());
strcpy(modifyDateTime,orderObj[index]->GetModifyDateTime());
sscanf(createDateTime,"%[^-]-%[^-]-%[^-]",createDay,createMonth,createYear);
createDd=atoi(createDay);
createMm=atoi(createMonth);
createYy=atoi(createYear);
sscanf(modifyDateTime,"%[^-]-%[^-]-%[^-]",modifyDay,modifyMonth,modifyYear);
modDd=atoi(modifyDay);
modMm=atoi(modifyMonth);
modYy=atoi(modifyYear);
try
{
DALInsert insertObj(trans);
DALTable OrderHdrTableObj(DALTables::OrderHdr);
insertObj.set_table(OrderHdrTableObj);
DALDate createDate(createDd,createMm,createYy);
DALDate modifiedDate(modDd,modMm,modYy);
RWTString rwtorderId(orderId),rwtshipTo(shipTo),rwtorderStatus(orderStatus);
DALInputHostVar IHVorderId(rwtorderId),IHVshipTo(rwtshipTo),IHVorderStatus(rwtorderStatus),IHVcreateDateTime(createDate),IHVmodifyDateTime(modifiedDate);
DALColumn orderIdColumn=OrderHdrTableObj[DbOrderHdr::OrderId];
DALColumn shipToColumn=OrderHdrTableObj[DbOrderHdr::ShipTo];
DALColumn orderStatusColumn=OrderHdrTableObj[DbOrderHdr::OrderStatus];
DALColumn createDateTimeColumn=OrderHdrTableObj[DbOrderHdr::CreateDateTime];
DALColumn modifyDateTimeColumn=OrderHdrTableObj[DbOrderHdr::ModDateTime];
DALColumnList columns;
columns.append(&orderIdColumn);
columns.append(&shipToColumn);
columns.append(&orderStatusColumn);
columns.append(&createDateTimeColumn);
columns.append(&modifyDateTimeColumn);
DALVarList values;
values.append(&IHVorderId);
values.append(&IHVshipTo);
values.append(&IHVorderStatus);
values.append(&IHVcreateDateTime);
values.append(&IHVmodifyDateTime);
insertObj.set_columns(columns);
insertObj.set_values(values);
insertObj.execute();
trans.save();
trans.commit();
}
catch(DALException exceptionObj)
{
_tcout<<exceptionObj.message();
}
try
{
strcpy(orderId1,orderObj[index]->GetOrderId());
if(orderObj[index]->GetItemList()!=NULL)
{
for(LineItem* temp=orderObj[index]->GetItemList();temp!=NULL;temp=temp->GetNextItem())
{
DALInsert insertObj(trans);
DALTable OrderDtlTableObj(DALTables::OrderDtl);
insertObj.set_table(OrderDtlTableObj);
strcpy(itemId,temp->GetItemId());
strcpy(itemQuantity,temp->GetItemQuantity());
RWTString rwtitemId(itemId),rwtitemQuantity(itemQuantity),rwtorderId1(orderId1);
DALInputHostVar IHVitemId(rwtitemId),IHVitemQuantity(rwtitemQuantity),IHVorderId1(rwtorderId1);
DALColumn orderId1Column=OrderDtlTableObj[DbOrderDtl::OrderId];
DALColumn itemIdColumn=OrderDtlTableObj[DbOrderDtl::SkuId];
DALColumn itemQuantityColumn=OrderDtlTableObj[DbOrderDtl::OrdQty];
DALColumnList columns;
columns.append(&orderId1Column);
columns.append(&itemIdColumn);
columns.append(&itemQuantityColumn);
DALVarList values;
values.append(&IHVorderId1);
values.append(&IHVitemId);
values.append(&IHVitemQuantity);
insertObj.set_columns(columns);
insertObj.set_values(values);
insertObj.execute();
trans.save();
trans.commit();
}
}
}
catch(DALException exceptionObj)
{
_tcout<<exceptionObj.message();
}
}
void FrontOfficeUser::UpdateOrder(DALTransaction& trans,int index)
{
cout<<"Updating.."<<endl;
char orderId[20],itemId[20],itemQuantity[20],modifyDate[20],modifyDay[50],modifyMonth[50],modifyYear[5];
int modDd,modMm,modYy;
strcpy(orderId,orderObj[index]->GetOrderId());
strcpy(modifyDate,orderObj[index]->GetModifyDateTime());
sscanf(modifyDate,"%[^-]-%[^-]-%[^-]",modifyDay,modifyMonth,modifyYear);
modDd=atoi(modifyDay);
modMm=atoi(modifyMonth);
modYy=atoi(modifyYear);
try
{
DALUpdate updateObj1(trans);
DALTable OrderHdrTableObj(DALTables::OrderHdr);
updateObj1.set_table(OrderHdrTableObj);
DALDate modifiedDate(modDd,modMm,modYy);
RWTString rwtorderId(orderId);
DALInputHostVar IHVorderId(rwtorderId),IHVmodifyDate(modifiedDate);
updateObj1.where(OrderHdrTableObj[DbOrderHdr::OrderId]==IHVorderId);
DALAssignment updateAssignmentObj(OrderHdrTableObj[DbOrderHdr::ModDateTime],IHVmodifyDate);
updateObj1.addAssignment(updateAssignmentObj);
updateObj1.execute();
trans.save();
trans.commit();
}
catch(DALException exceptionObj)
{
_tcout<<exceptionObj.message();
}
try
{
if(orderObj[index]->GetItemList()!=NULL)
{
for(LineItem* temp=orderObj[index]->GetItemList();temp!=NULL;temp=temp->GetNextItem())
{
DALUpdate updateObj(trans);
DALTable OrderDtlTableObj(DALTables::OrderDtl);
updateObj.set_table(OrderDtlTableObj);
strcpy(itemId,temp->GetItemId());
strcpy(itemQuantity,temp->GetItemQuantity());
RWTString rwtitemId(itemId),rwtitemQuantity(itemQuantity),rwtorderId(orderId);
DALInputHostVar IHVitemId(rwtitemId),IHVitemQuantity(rwtitemQuantity),IHVorderId(rwtorderId);
updateObj.where(OrderDtlTableObj[DbOrderDtl::OrderId]==IHVorderId && OrderDtlTableObj[DbOrderDtl::SkuId]==IHVitemId);
DALAssignment updateAssignmentObj(OrderDtlTableObj[DbOrderDtl::OrdQty],IHVitemQuantity);
updateObj.addAssignment(updateAssignmentObj);
updateObj.execute();
//check for invalid item in update record
int updated=updateObj.get_rowCount();
if(!updated)
{
ErrorFile<<"Item "<<temp->GetItemId()<<" in Order "<<orderObj[index]->GetOrderId()<<" is invalid!!! Item discarded"<<endl;
}
trans.save();
trans.commit();
}
}
}
catch(DALException exceptionObj)
{
_tcout<<exceptionObj.message();
}
}
void FrontOfficeUser::CancelOrder(DALTransaction& trans,int index)
{
DALUpdate updateObj(trans);
cout<<"Cancelling.."<<endl;
char orderId[20],orderStatus[20];
strcpy(orderId,orderObj[index]->GetOrderId());
strcpy(orderStatus,"3");
try
{
RWTString rwtorderId(orderId),rwtorderStatus(orderStatus);
DALInputHostVar IHVorderId(rwtorderId),IHVorderStatus(rwtorderStatus);
DALTable OrderHdrTableObj(DALTables::OrderHdr);
updateObj.set_table(OrderHdrTableObj);
updateObj.where(OrderHdrTableObj[DbOrderHdr::OrderId]==IHVorderId);
DALAssignment updateAssignmentObj(OrderHdrTableObj[DbOrderHdr::OrderStatus],IHVorderStatus);
updateObj.addAssignment(updateAssignmentObj);
updateObj.execute();
trans.save();
trans.commit();
}
catch(DALException exceptionObj)
{
_tcout<<exceptionObj.message();
}
}
bool CheckItemInDb(DALTransaction& trans,char* itemId)
{
DALSelect selectObj(trans);
DALTable ItemMasterObj(DALTables::ItemMaster);
RWTString rwtItemId;
DALHostVar HVItemId(rwtItemId);
selectObj.addSelect(ItemMasterObj[DbItemMaster::SkuId],HVItemId);
char itemId1[20];
selectObj.execute();
while(selectObj.next())
{
wcstombs(itemId1,rwtItemId,20);
if(strcmp(itemId,itemId1)==0)
return true;
}
return false;
}
bool CheckOrderInDb(DALTransaction& trans,int index)
{
char orderId[20];
DALSelect selectObj(trans);
DALTable OrderHdrObj(DALTables::OrderHdr);
RWTString rwtorderId;
DALHostVar HVorderId(rwtorderId);
strcpy(orderId,orderObj[index]->GetOrderId());
selectObj.addSelect(OrderHdrObj[DbOrderHdr::OrderId],HVorderId);
char orderId1[20];
selectObj.execute();
while(selectObj.next())
{
wcstombs(orderId1,rwtorderId,20);
if(strcmp(orderId,orderId1)==0)
return true;
}
return false;
}
bool CheckWhetherShipped(DALTransaction& trans,int index)
{
DALSelect selectObj(trans);
DALTable OrderHdrObj(DALTables::OrderHdr);
char orderId[20],orderId1[20];
int orderStatus1,orderStatus=2;
RWTString rwtorderId;
DALHostVar HVorderId(rwtorderId),HVorderStatus(orderStatus1);
strcpy(orderId,orderObj[index]->GetOrderId());
selectObj.addSelect(OrderHdrObj[DbOrderHdr::OrderId],HVorderId);
selectObj.addSelect(OrderHdrObj[DbOrderHdr::OrderStatus],HVorderStatus);
selectObj.execute();
while(selectObj.next())
{
wcstombs(orderId1,rwtorderId,20);
if(orderStatus1==orderStatus && strcmp(orderId1,orderId)==0)
return true;
}
return false;
}
bool CheckWhetherCancelled(DALTransaction& trans,int index)
{
DALSelect selectObj(trans);
DALTable OrderHdrObj(DALTables::OrderHdr);
char orderId[20],orderId1[20];
int orderStatus1,orderStatus=3;
RWTString rwtorderId;
DALHostVar HVorderId(rwtorderId),HVorderStatus(orderStatus1);
strcpy(orderId,orderObj[index]->GetOrderId());
selectObj.addSelect(OrderHdrObj[DbOrderHdr::OrderId],HVorderId);
selectObj.addSelect(OrderHdrObj[DbOrderHdr::OrderStatus],HVorderStatus);
selectObj.execute();
while(selectObj.next())
{
wcstombs(orderId1,rwtorderId,20);
if(orderStatus1==orderStatus && strcmp(orderId1,orderId)==0)
return true;
}
return false;
}
| true |
fe6db72cb0be4be83200053b058b0fc3224f8009 | C++ | PAL-ULL/software-metco | /oplink/algorithms/team/src/plugins/algorithms/SPEA/SPEA.h | ISO-8859-2 | 4,925 | 2.96875 | 3 | [] | no_license | /***********************************************************************************
* AUTHORS
* - Ofelia Gonzlez Prez
* - Gara Miranda Valladares
* - Carlos Segura Gonzlez
*
* DATE
* November 2007
*
* DESCRIPTION
* This class inherits from EA, in order the implement the evolutionary algorithm
* SPEA (Strength Pareto Evolutionary Algorithm) proposed by Zitzler and Thiele:
* -> E. Zitzler, L. Thiele
* An evolutionary algorithm for multiobjective optimization:
* The strength Pareto Approach.
* Technical Report 43, Zrich, Switzerland: Computer Engineering and Networks Laboratory (TIK),
* Swiss Federal Institute of Technology (ETH).
*
* The algorithm introduce the concept of external archive, very popular now in multi-objetive EAs.
* It introduce elitism, maintaing an external archive P' with size N', storing non-dominated
* individuals. In each generation, such set in updated.
* If |P'| > N' the set size is reduced to N', using a clustering technique, selecting in each
* cluster the chromosome with smallest distance to the remaining chromosomes (the nearest to the
* center).
* fitness is calculatted as Fitness(i) = Strength(i)
* Strength of individual i in P: S_i = n_i / (N+1)
* n_i es el number of dominated solutions by i in P
*
* SPEA Algorithm
* Step 1. Generate initial population P. Empty P'.
* Step 2. Copy non-dominated individuals of P to P'.
* Step 3. Remove from P' dominated individuals.
* Step 4. if |P'| > N', reduce the size of the set to N', using clustering techniques.
* Step 5. Calculate fitness in P and P'.
* Step 6. Selects N individuals from P and P' using binary tournament
* Step 7. Apply variation operators.
* Step 8. Return to step 2.
*
* Clustering Algorithm
* Step 1. Initially each element constitutes a cluster. if |P'| <= N' then go to Step 5
* Step 2. For each pair of clusters calculate the distance between them. It is calculated as
* teh average distance of all the elements.
* Step 3. Combine the 2 clusters with smallest distance.
* Step 4. If |P'| <= N', finallize. Otherwise, go to Step 2.
* Step 5. Select a solution in each cluster, the one with minimum distance to the remaining
* elements in the cluster.
*
* Fitness Assignation
* In P':
* f_i = Strength_i = n_i / (N+1),
* n_i is the number of dominated solutions by i in P
* N = |P|
* In P:
* f_i = 1 + (Strength_j foreach j in P', which dominantes i)
*
************************************************************************************/
#ifndef __SPEA_H__
#define __SPEA_H__
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include "MOFront.h"
#include "Individual.h"
#include "EA.h"
class SPEA : public EA {
public:
// Constructor
SPEA ();
// Destructor
virtual ~SPEA (void);
// Define una generacin de bsqueda del algoritmo
void runGeneration();
// Inicializa los parmetros iniciales del algoritmo
bool init(const vector<string> ¶ms);
// Rellena un frente con las soluciones actuales
void getSolution(MOFront *p) ;
// Muestra la informacin relativa al algoritmo
void printInfo(ostream &os) const;
string getName() const { return "SPEA"; }
private:
int aSize; // Archive size
float pm; // Mutation probability
float pc; // Crossover probability
vector<Individual*>* archive; // Archive pool
vector<Individual*> mating; // Mating pool
// Selection of the mating pool (binary tournament)
void matingSelection (void);
// Evaluation of the individuals in the population
void evaluation (void);
//Mutation & crossover. From the manting pool to the new population
void variation (void);
// Evaluation all element in the population
void fitness (void);
// Marks all nondominated individuals according to the population with fitness 0
void markNondominated (void);
// Remove solutions within the external set which are covered by any other set member
void updateExternalNondominatedSet (void);
// Calculate the dist between individuals
double calcDistance (const Individual* i1, const Individual* i2);
// Calcula la distancia entre dos elementos del cluster
double clusterDistance (vector<Individual*> *nonDominatedSet, vector<int> *clusters, vector<int> *clusterList,
int cluster1, int cluster2);
// Join two clusters
void joinClusters(vector<int> *clusters, vector<int> *clusterList, int cluster1, int cluster2, int& numOfClusters);
// Calculate the point with minimal average distance to all other points in the cluster
int clusterCentroid(vector<Individual*> *nonDominatedSet, vector<int> *clusters, vector<int> *clusterList, int cluster);
// Reduce the external set by means of clustering
void clustering (vector<Individual*> *nonDominatedSet, const int maxSize);
};
#endif
| true |
1aee30e064a9c197d46448d0ce4d13164ba497fe | C++ | Barush/IPK3 | /rdtclient.cpp | UTF-8 | 5,838 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <string>
#include <vector>
#include <time.h>
#include <sstream>
//soubor obsahujici funkce pro vyuziti udt prenosu
#include "udt.h"
//konstanty pro nastaveni vlastnosti programu
#define PACK_DATA_SIZE 300
using namespace std;
void usage(){
cerr << "Program rdtclient" << endl;
cerr << "Barbora Skrivankova, xskriv01@stud.fit.vutbr.cz" << endl;
cerr << "Pouziti: ./rdtclient -s source_port -d dest_port" << endl;
}
string convertInt(int number)
{
stringstream ss;
ss << number;
return ss.str();
}
int getPackId(string packet){
unsigned pos, endpos;
int ret = 0;
pos = packet.find("sn");
endpos = packet.find("ack");
if((pos != string::npos) && (endpos != string::npos)){
ret = atoi(packet.substr(pos + 4, endpos - 2).c_str());
}
return ret;
}
int getTack(string packet){
unsigned pos, endpos;
int ret = 0;
pos = packet.find("tack");
endpos = packet.substr(pos).find(">");
if(pos != string::npos){
ret = atoi(packet.substr(pos + 6, endpos-1).c_str());
}
return ret;
}
string createXMLPacket(int sn, string data, int window_size, int time){
string value = "<rdt-segment id=\"xskriv01\">\n<header sn=\"";
value.append(convertInt(sn));
value.append( "\" ack=\"potvrzeni\" win=\"");
value.append(convertInt(window_size));
value.append("\" tack=\"");
value.append(convertInt(time));
value.append("\"> </header> \n<data>");
value.append(data);
value.append("\n</data>\n</rdt-segment>");
return value;
}
int readPacket(string *data){
int count = 0;
char c;
*data = "";
while((count < PACK_DATA_SIZE) && ((c = getchar()) != EOF)){
*data += c;
count++;
}
//cout << *data << endl;
if(c == EOF)
return 1;
return 0;
}
int main(int argc, char **argv){
in_port_t source_port = 0, dest_port = 0;
in_addr_t dest_address = 0x7f000001; //localhost
int sel;
vector<string> XMLpackets;
vector<int> timers;
vector<int> acks;
if (argc != 5) {
cerr << "Zadan chybny pocet parametru!" << endl << endl;
usage();
return EXIT_FAILURE;
}
for(int i = 1; i < 5; i += 2){
if (!strcmp(argv[i],"-s")){
source_port = atol(argv[i + 1]);
}
else if (!strcmp(argv[i], "-d")){
dest_port = atol(argv[i + 1]);
}
else{
cerr << "Zadan chybny parametr " << argv[i] << "!" << endl << endl;
usage();
return EXIT_FAILURE;
}
}
if(!dest_port){
cerr << "Nezadan parametr dest port!" << endl;
usage();
return EXIT_FAILURE;
}
if(!source_port){
cerr << "Nezadan parametr source port!" << endl;
usage();
return EXIT_FAILURE;
}
//tato fce vraci handler pro udt connection
int udt = udt_init(source_port);
//nastaveni neblokujiciho cteni ze stdin
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
//sdruzeni stdin a zdrojoveho portu do sady deskriptoru
fd_set udt_stdin;
FD_ZERO(&udt_stdin);
FD_SET(udt, &udt_stdin);
FD_SET(STDIN_FILENO, &udt_stdin);
//casovac pro maximalni delku cekani na vstup
timeval tv;
tv.tv_sec = 100;
tv.tv_usec = 0;
//promenne potrebne uvnitr while cyklu
int packet_id = 0, acked, to_send = 0;
char tempstr[500];
string packet = "";
int end = 0, lastSend = 0, acking = 0;
int window_size = 1;
timeval timer;
int tack;
int timeout1 = 10000, timeout2 = 1000, timeout3 = 1000, timeout;
while((sel = select(udt + 1, &udt_stdin, NULL, NULL, &tv)) && !end){
if(sel < 0){
cerr << "Nastala chyba pri volani select!";
return EXIT_FAILURE;
}
//posilani paketu
if(!lastSend && !acking){
for(int i = to_send; i < to_send + window_size; i++){
//posledni posilani se zdarilo
if(packet_id == i){
lastSend = readPacket(&packet);
gettimeofday(&timer, NULL);
tack = timer.tv_usec / 1000;
timeout = (tack + ((2*timeout1 + timeout2 + timeout3) / 4) )/2;
timeout *= 1.3;
packet = createXMLPacket(packet_id, packet, window_size, timeout);
XMLpackets.push_back(packet);
timers.push_back(timeout);
acks.push_back(0);
packet_id++;
}
//cout << "Pack id: " << packet_id << " to_send: " << to_send << " i:" << i << endl;
cerr << "ze struktury: " << i << ":" << endl << XMLpackets.at(i);
if(!udt_send(udt, dest_address, dest_port, (void *)XMLpackets.at(i).c_str(), XMLpackets.at(i).size())){
//cerr << "Nastala chyba pri volani udt_send!" << endl;
//return EXIT_FAILURE;
}
cerr << "Something send" << endl;
acking = 1;
timers.at(i) = tack;
if(lastSend)
break;
}
}
//prijimani acks
if(udt_recv(udt, tempstr, 500, &dest_address, &dest_port)){
cerr << "Tramtadaaaaa" << endl;
packet = "";
packet.append(tempstr);
gettimeofday(&timer, NULL);
tack = timer.tv_usec / 1000;
timeout3 = timeout2;
timeout2 = timeout1;
timeout1 = tack - getTack(packet);
acked = getPackId(packet);
acks.at(acked) = 1;
for(; acked < acks.size(); acked++){
if(acks.at(acked) == 0)
break;
}
to_send = acked;
window_size++;
acking = 0;
}
//vyprsel casovac
gettimeofday(&timer, NULL);
tack = timer.tv_usec / 1000;
if(acking){
for(unsigned i = 0; i < acks.size(); i++){
if( (acks.at(i) == 0) && (tack > timers.at(i)) ){
to_send = i;
window_size /= 3;
if(window_size < 1)
window_size = 1;
lastSend = 0;
acking = 0;
cerr << "Here..." << i << "window: " << window_size << endl;
cerr << tack << ">" << timers.at(i) << endl;
break;
}
}
}
//prisly nam vsechny acks - pokud je potvrzen posledni, potvrzuje tim i vsechny predchazejici
if(lastSend && (acks.at(acks.size() - 1) == 1))
end = 1;
}
/*for(int i = 0; i < acks.size(); i++){
cout << i << ". ack:" << acks[i] << endl;
}*/
return 0;
}
| true |
10ea5e812b256b58c395182dbc8160251e2e623c | C++ | suNrisEinMyeYes/hash | /Hash/hashTable.cpp | UTF-8 | 1,662 | 3.203125 | 3 | [] | no_license | #include "stdafx.h"
#include <iostream>
#include "hashFunction.h"
#include "fileReader.h"
#include "comparator.h"
#include "hashTable.h"
#include <list>
#include <iterator>
using std::list;
using namespace std;
template <typename T>
hashTable<T>::hashTable() {
table = new list<T>[100];
}
/*int getKey(string * elem){
return(hasher.hash(elem));
}*/
template <typename T>
void hashTable<T>::add() {
ifstream file = fileReader::read();
string reader;
while (!file.eof())
{
file >> reader;
int index = hasher.hash(reader);
table[index].push_back(reader);
}
file.close();
/*for (int i = 0; i < 100; i++)
{
//if (table[i]!=NULL)
//{
sorter.sort(table[i]);
//}
}*/
}
template <typename T>
void hashTable<T>::remove(string * elemToDelete) {
it = find(elemToDelete);
int index = hasher.hash(*elemToDelete);
if (it == table[index].end())
{
cout << "nothing to remove" << endl;
return;
}
table[index].erase(it);
cout << "removed!" << endl;
}
template <typename T>
list<string>::iterator hashTable<T>::find(string * elemToFind) {
int index = hasher.hash(*elemToFind);
cout << "hash key:" << index << endl;
int numbInList = 0;
for (it = table[index].begin(); it != table[index].end(); it++) {
if (*it == *elemToFind)
{
return it;
}
numbInList++;
}
cout << "Not found: " << elemToFind << endl;
//cout << *it << endl;
//cout << it << endl;
return it;
}
template <typename T>
void hashTable<T>::print() {
for (size_t i = 0; i < 100; i++)
{
cout << i << ": ";
copy(table[i].begin(), table[i].end(), ostream_iterator<T>(cout, " "));
cout << endl;
}
}
| true |
0bd7e43f185ee969625a3a107e5f164d89b41443 | C++ | kickflip0/injector | /injector/injector.h | UTF-8 | 3,368 | 2.859375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <cstdint>
#include <filesystem>
#include <windows.h>
#include <TlHelp32.h>
#include <Dbghelp.h>
namespace util
{
inline DWORD get_pid(const char* process_name)
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
if (!Process32First(hSnap, &pe32))
return NULL;
do {
if (!strcmp(pe32.szExeFile, process_name))
{
CloseHandle(hSnap);
return pe32.th32ProcessID;
}
} while (Process32Next(hSnap, &pe32));
CloseHandle(hSnap);
return NULL;
}
std::string random_string(const size_t length)
{
std::string r;
static const char bet[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyzZ1234567890" };
srand((unsigned)time(NULL) * 5);
for (int i = 0; i < length; ++i)
r += bet[rand() % (sizeof(bet) - 1)];
return r;
}
}
class Injector
{
public:
Injector(DWORD pid, const char* dllpath);
~Injector();
public:
void* inject();
bool file_exists(const char* sz_path);
auto resolve_function(std::string, std::string);
HANDLE entry(std::uintptr_t);
private:
void* alloc_base;
HANDLE target_handle;
DWORD pid;
const char* dllpath;
void write(void* addr, const char* buffer, std::size_t size);
};
Injector::Injector(DWORD processID, const char* path)
{
this->pid = processID;
this->dllpath = path;
};
Injector::~Injector()
{
VirtualFreeEx(target_handle, alloc_base, strlen(dllpath) + 1, MEM_RELEASE);
CloseHandle(target_handle);
};
bool Injector::file_exists(const char* sz_path)
{
DWORD dwAttrib = GetFileAttributes(sz_path);
return (dwAttrib != INVALID_FILE_ATTRIBUTES and
not(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
auto Injector::resolve_function(std::string module_base, std::string module_name)
{
return reinterpret_cast<std::uintptr_t>(GetProcAddress(GetModuleHandle(module_base.c_str()), module_name.c_str()));
}
void* Injector::inject()
{
if ((dllpath != NULL) and (dllpath[0] == '\0'))
{
std::printf("[-] Don't receive DLLpath\n");
}
std::printf("[+] DLL PATH : %s\n", dllpath);
std::printf("[+] SIZE : %i\n", strlen(dllpath) + 1);
std::printf("[+] pid : %i\n", pid);
target_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // change permissions
if (!target_handle)
{
return NULL;
}
alloc_base = VirtualAllocEx(
target_handle,
NULL,
strlen(dllpath) + 1,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE
);
if (alloc_base)
{
std::printf("Allocated memory in : %p\n", alloc_base);
}
write(alloc_base, dllpath, strlen(dllpath) + 1 );
auto ep = resolve_function("kernel32.dll", "LoadLibraryA");
HANDLE load_thread = entry(ep);
if (!load_thread)
{
std::printf("[+] Problem handle thread: %i\n", GetLastError());
return 0;
}
else
{
std::printf("Handle: %p\n", load_thread);
}
WaitForSingleObject(load_thread, INFINITE);
}
HANDLE Injector::entry(std::uintptr_t const entry_point)
{
SECURITY_ATTRIBUTES sec_attr{};
return CreateRemoteThread(
target_handle, &sec_attr, NULL, (LPTHREAD_START_ROUTINE)(entry_point), alloc_base, NULL, 0);
}
void Injector::write(void* addr, const char* buffer, std::size_t size)
{
SIZE_T bytes_written;
::WriteProcessMemory(
target_handle,
addr,
buffer,
size,
&bytes_written
);
}
| true |
c2134e5c4095082a3bddcfdce97616c2bef3a6a8 | C++ | hu-zhiyu/cpp-interview-prep | /Algorithm/LeetCode/3.无重复字符的最长子串.cpp | UTF-8 | 725 | 3.21875 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=3 lang=cpp
*
* [3] 无重复字符的最长子串
*/
// @lc code=start
class Solution {
// 时间复杂度:O(n), 左右指针会分别遍历一次字符串
public:
int lengthOfLongestSubstring(string s) {
unordered_set<int> us;
int result = 0;
int lptr = 0, rptr = 0;
for(int i = 0; i < s.size(); i++) {
lptr = i;
if(i != 0) {
us.erase(s[i - 1]);
}
while(rptr < s.size() && us.find(s[rptr]) == us.end()) {
us.insert(s[rptr]);
rptr++;
}
result = max(result, rptr - lptr);
}
return result;
}
};
// @lc code=end
| true |
84b3fd1b15ddccae8fa3f1f57a1ddccbd8b4345c | C++ | AndrewDTodd/SFML-Memory-Game | /MemoryGame/MemoryGame/Card.cpp | UTF-8 | 2,226 | 3.046875 | 3 | [] | no_license | //
// Card.cpp
// MemoryGame
//
// Created by Andrew Todd on 2/14/19.
// Copyright © 2019 Andrew Todd. All rights reserved.
//
#include "Card.hpp"
#include <SFML/Graphics.hpp>
std::string Card::cardNames[] = {"Ace of Clubs", "Two of CLubs", "Three of CLubs", "Four of Clubs", "Five of Clubs", "Six of Clubs", "Seven of Clubs", "Eight of Clubs", "Nine of Clubs", "Ten of CLubs", "Jack of CLubs", "Queen of Clubs", "King of Clubs",
"Ace of Diamonds", "Two of Diamonds", "Three of Diamonds", "Four of Diamonds", "Five of Diamonds", "Six of Diamonds", "Seven of Diamonds", "Eight of Diamonds", "Nine of Diamonds", "Ten of Diamonds", "Jack of Diamonds", "Queen of Diamonds", "King of Diamonds",
"Ace of Hearts", "Two of Hearts", "Three of Hearts", "Four of Hearts", "Five of Hearts", "Six of Hearts", "Seven of Hearts", "Eight of Hearts", "Nine of Hearts", "Ten of Hearts", "Jack of Hearts", "Queen of Hearts", "King of Hearts",
"Ace of Spades", "Two of Spades", "Three of Spades", "Four of Spades", "Five of Spades", "Six of Spades", "Seven of Spades", "Eight of Spades", "Nine of Spades", "Ten of Spades", "Jack of Spades", "Queen of Spades", "King of Spades"
};
Card::Card(sf::IntRect cardTexRec, std::string* cardName)
{
this->cardSprite.setTextureRect(Card::cardBackTextureRect);
this->cardFrontTexture = cardTexRec;
this->cardName = cardName;
}
Card::~Card()
{
}
void Card::InitializeClass()
{
Card::cardsTexture.loadFromFile("Cards.png");
int i = 0;
for(int y = 0; y < 492; y+123)
{
for(int x = 0; x < 948; x+79)
{
Card::deck[i] = Card(sf::IntRect(x,y,79,123), &Card::cardNames[i]);
i++;
}
}
Card::cardBackTextureRect = sf::IntRect(158,492,79,123);
}
void Card::FlipCard()
{
if(this->fliped)
{
this->cardSprite.setTextureRect(Card::cardBackTextureRect);
}
else
{
this->cardSprite.setTextureRect(this->cardFrontTexture);
}
this->fliped = !this->fliped;
}
std::ostream& operator<<(std::ostream& stream, Card card)
{
stream << *card.cardName;
return stream;
}
void Card::QueForDraw(sf::RenderWindow* win)
{
win->draw(this->cardSprite);
}
| true |
477814e2b42780e369c968a2abd01e44d8a4258d | C++ | valeriaconde/competitive-programming | /unclassified/stack reverse string.cpp | UTF-8 | 487 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <queue>
using namespace std;
string pinchesPutaFuncion(string putaString) {
string tuPincheRespuesta = "";
stack<char> reversazo;
for(int i = 0; i < putaString.size(); i++) {
reversazo.push(putaString[i]);
}
while (!reversazo.empty()) {
tuPincheRespuesta += reversazo.top();
reversazo.pop();
}
return tuPincheRespuesta;
}
// la princessval
int main() {
string s;
cin >> s;
cout << pinchesPutaFuncion(s) << endl;
}
| true |
9a8458357b314b78ec9f5664d366dcc4db80f6b3 | C++ | cuongcb/snekageam | /snake.h | UTF-8 | 769 | 2.796875 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <memory>
#include <vector>
namespace snake {
class Pixel;
class Snake {
public:
Snake();
// motion
void MoveLeft(uint32_t leftborder);
void MoveRight(uint32_t rightborder);
void MoveUp(uint32_t topborder);
void MoveDown(uint32_t bottomborder);
// action
void Eat();
private:
static constexpr uint32_t kVelocity = 1;
static constexpr uint32_t kDefaultX = 1;
static constexpr uint32_t kDefaultY = 1;
typedef std::unique_ptr<Pixel> Snake_Part_t;
typedef std::vector<Snake_Part_t> Snake_t;
Snake_Part_t make_head(uint32_t x, uint32_t y, char symbol = 'o') const;
Snake_Part_t make_body(uint32_t x, uint32_t y, char symbol = '.') const;
Snake_t snake_;
};
}
| true |
3364887c01773e3e8a2302a2625155c05d3d9d70 | C++ | Pimmez/Break-Out | /Break-out/Breakout/StartMenu.h | UTF-8 | 1,185 | 3.21875 | 3 | [] | no_license | #pragma once
#ifndef STARTMENU_H
#define STARTMENU_H
#define MAX_NUMBER_OF_ITEMS 3 //Maximum Number Of Items In The Array
#include <SFML/Graphics.hpp> //Required for variables with 'sf'
#include <iostream> //Required for use of std::cout, std::endl and more
class StartMenu
{
public:
StartMenu(); //Constructor
~StartMenu(); //Destructor
void DrawTo(sf::RenderWindow &window); //Draws to the Window for rendering
void MoveLeft(); //Method to circulate to the left
void MoveRight(); //Method to circulate to the right
int GetPressedItem(); //Method to get the pressed menu item
private:
int selectedItemIndex; //Int to check what number gets pressed
int screenWidth = 1000; //The screen width
int screenHeight = 500; //The screen Height
sf::Texture tMenuBackground; //tMenu -> TextureMenu
sf::Sprite sMenuBackground; //sMenu -> SpriteMenu
sf::Font font; //Variable of font
sf::String loadFile = "images/startmenu.png"; //String with the path to the .png
sf::String loadFont = "fonts/opensans.ttf"; //String with the path to the .ttf
sf::Text menuItems[MAX_NUMBER_OF_ITEMS]; //Array of texts, with the maximum number of menu items in it
};
#endif //!STARTMENU_H | true |
9287c173dee8f1b50ea9abccecb08a5205425aef | C++ | ahorak8/CPP_Bootcamp | /day06/ex00/main.cpp | UTF-8 | 2,764 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
void isDouble(char** argv){
double d = static_cast<double>(atof(argv[1]));
std::cout << "double: " << d << std::endl;
if (!d)
std::cout << "double: impossible" << std::endl;
}
void isFloat(char** argv, int x){
int z = 0;
if(!argv[1][x])
z = 1;
for (; argv[1][x]; x++){
if (!isdigit(argv[1][x])){
if (argv[1][x] == 'f')
x++;
if(!argv[1][x])
break;
else
z = 1;
}
}
if (z == 0)
{
float f = static_cast<float>(atof(argv[1]));
std::cout << "float: " << f << 'f' << std::endl;
}
if (z == 1)
std::cout << "float: impossible" << std::endl;
isDouble(argv);
}
void isChar(char** argv){
if (isalpha(argv[1][0]) && !argv[1][1])
{
char c = static_cast<char>(argv[1][0]);
std::cout << "char: " << c << std::endl;
return;
}
else if (atoi(argv[1]) || argv[1][0] == '0')
{
int j = atoi(argv[1]);
char a = static_cast<char>(j);
if (isprint(j))
std::cout << "char: " << '\'' << a << '\'' << std::endl;
else
std::cout << "char: Non displayable" << std::endl;
}
else
std::cout << "char: impossible" << std::endl;
}
void isInt(char** argv){
int y = 0;
int x = 0;
if (argv[1][x] == '-')
x++;
for (; argv[1][x]; x++){
if (!isdigit(argv[1][x])){
if(argv[1][x] == '.' && argv[1][0] != '.')
{
x++;
if(argv[1][x] != '0')
{
y = 2;
isFloat(argv, x);
break;
}
while(argv[1][x] == '0')
x++;
if(!argv[1][x])
break;
if (argv[1][x] == 'f')
x++;
if(!argv[1][x])
break;
}
y = 1;
break;
}
}
if (y == 0)
{
int i = static_cast<int>(atoi(argv[1]));
std::cout << "int: " << i << std::endl;
}
else if (y == 1 || y == 2)
std::cout << "int: impossible" << std::endl;
if (y != 2){
float f = static_cast<float>(atof(argv[1]));
std::cout << "float: " << f << 'f' << std::endl;
double d = static_cast<double>(atof(argv[1]));
std::cout << "double: " << d << std::endl;
}
}
int main(int argc, char** argv){
std::cout << std::fixed << std::showpoint;
std::cout << std::setprecision(1);
if (argc == 2){
isChar(argv);
isInt(argv);
}
return 0;
} | true |
ab634e9c0d3514356cd807c7303a76da6bc66621 | C++ | themicp/Project-Euler-Problems | /problem82/problem82.cpp | UTF-8 | 3,135 | 2.796875 | 3 | [] | no_license | #include <cstdio>
#include <stack>
using namespace std;
const int N = 80;
const bool debug = false;
const int UP = 0;
const int RIGHT = 1;
const int DOWN = 2;
long long int min( long long int a, long long int b ) {
if ( a < b ) {
return a;
}
return b;
}
void W( long long int w[ N ][ N ], long long int matrix[ N ][ N ], int i, int j ) {
int k, l = 0, minPath = 0, sum;
while ( l < N ) {
sum = w[ l ][ j - 1 ];
if ( l < i ) {
for ( k = l; k < i; ++k ) {
sum += matrix[ k ][ j ];
}
}
else if ( l > i ) {
for ( k = l; k > i; --k ) {
sum += matrix[ k ][ j ];
}
}
minPath = ( minPath == 0 ? sum : min( sum, minPath ) );
++l;
}
w[ i ][ j ] = minPath + matrix[ i ][ j ];
}
int i, j, x, y;
long long minim;
long long matrix[ N ][ N ], w[ N ][ N ], solution;
FILE *in = fopen( "problem82.in", "r" ), *out = fopen( "problem82.out", "w" );
stack< int > p;
int main() {
for ( i = 0; i < N; ++i ) {
for ( j = 0; j < N; ++j ) {
fscanf( in, "%lli,", &matrix[ i ][ j ] );
if ( j == 0 ) {
w[ i ][ j ] = matrix[ i ][ j ];
}
}
}
for ( j = 1; j < N; ++j ) {
for ( i = 0; i < N; ++i ) {
W( w, matrix, i, j );
}
}
if ( debug ) {
for ( i = 0; i < N; ++i ) {
for ( j = 0; j < N; ++j ) {
printf( "%lli ", w[ i ][ j ] );
}
printf( "\n" );
}
}
solution = w[ N - 1 ][ N - 1 ];
for ( i = 0; i < N; ++i ) {
if ( w[ i ][ N - 1 ] < solution ) {
solution = w[ i ][ N - 1 ];
y = i;
}
}
x = N - 1;
while ( x > 0 ) {
if ( y == 0 ) {
if ( w[ y + 1 ][ x ] < w[ y ][ x - 1 ] ) {
p.push( UP );
++y;
}
else {
p.push( RIGHT );
--x;
}
}
else if ( y == N - 1 ) {
if ( w[ y - 1 ][ x ] < w[ y ][ x - 1 ] ) {
p.push( DOWN );
--y;
}
else {
p.push( RIGHT );
--x;
}
}
else {
minim = min( w[ y - 1 ][ x ], min( w[ y ][ x - 1 ], w[ y + 1 ][ x ] ) );
if ( minim == w[ y - 1 ][ x ] ) {
p.push( DOWN );
--y;
}
if ( minim == w[ y ][ x - 1 ] ) {
p.push( RIGHT );
--x;
}
if ( minim == w[ y + 1 ][ x ] ) {
p.push( UP );
++y;
}
}
}
while ( !p.empty() ) {
switch ( p.top() ) {
case RIGHT:
printf( "Right\n" );
break;
case DOWN:
printf( "Down\n" );
break;
case UP:
printf( "UP\n" );
break;
}
p.pop();
}
fprintf( out, "%lli\n", solution );
}
| true |
bf0ebbc633ebaebded599ec5b0f70064d714d836 | C++ | Jas03x/cdep | /src/ascii.hpp | UTF-8 | 346 | 2.65625 | 3 | [] | no_license | #ifndef ASCII_HPP
#define ASCII_HPP
inline bool is_space(char c) { return (c == ' ') || (c == '\t'); }
inline bool is_text (char c) { return ((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_'); }
inline bool is_path (char c) { return is_text(c) || (c == ' ') || (c == '/'); }
#endif // ASCII_HPP | true |
076cfe0f85dac86352d61d22f9b6ddc4069b9593 | C++ | danielphil/epi | /src/dutch_national_flag_6.1.cpp | UTF-8 | 3,763 | 3.015625 | 3 | [] | no_license | #include "common.h"
#include "dutch_national_flag_6.1.h"
#include "test.h"
namespace Flag
{
static void ensure_next_indexes_valid(unsigned int next[4]);
std::vector<int> Partition(const std::vector<int>& input_elements, unsigned int partition_index) {
std::vector<int> result = input_elements;
unsigned int current = 0;
unsigned int write_low = 0;
unsigned int write_high = static_cast<unsigned int>(result.size()) - 1;
int pivot_value = result.at(partition_index);
while (current < write_high) {
const auto current_value = result.at(current);
if (current_value > pivot_value) {
std::swap(result[current], result[write_high]);
write_high--;
} else if (current_value < pivot_value) {
if (current != write_low) {
result[write_low] = result[current];
}
write_low++;
current++;
} else {
current++;
}
}
for (auto i = write_low; i < write_high; i++) {
result[i] = pivot_value;
}
return result;
}
void ensure_next_indexes_valid(unsigned int next[4]) {
next[1] = std::max(next[0], next[1]);
next[2] = std::max(next[1], next[2]);
}
std::vector<int> Partition4(const std::vector<int>& input_elements) {
std::vector<int> result = input_elements;
unsigned int next[4] = { 0, 0, 0, static_cast<unsigned int>(result.size()) };
unsigned int current = 0;
while (current < next[3]) {
const auto value = result.at(current);
if (value == 3) {
std::swap(result[current], result[--next[3]]);
} else {
if (current == next[value]) {
current++;
} else {
std::swap(result[current], result[next[value]]);
}
next[value]++;
ensure_next_indexes_valid(next);
}
}
return result;
}
void test() {
const std::vector<int> input = { 1, 100, 12, 19, 2, 33, 45, 78, -1, 19 };
const int pivot_index = 3;
const int pivot_value = input[pivot_index];
auto result = Partition(input, pivot_index);
TEST_EQ(input.size(), result.size());
int before_pivot = 0;
int pivot = 0;
int after_pivot = 0;
auto it = result.begin();
while (it != result.end()) {
// Values less than pivot
if ((*it) == pivot_value) {
break;
}
it++;
before_pivot++;
}
TEST_EQ(4, before_pivot);
while (it != result.end()) {
// Pivot values
if ((*it) > pivot_value) {
break;
}
it++;
pivot++;
}
TEST_EQ(2, pivot);
while (it != result.end()) {
// Values greater than pivot
it++;
after_pivot++;
}
TEST_EQ(4, after_pivot);
}
void test4() {
const std::vector<int> input = { 0, 0, 1, 1, 1, 2, 3, 1, 2, 2, 3, 0, 0, 3, 0, 1, 2, 3, 0, 3 };
auto result = Partition4(input);
TEST_EQ(input.size(), result.size());
auto it = result.begin();
int count = 0;
for (auto val : {0, 1, 2, 3}) {
while ((*it) == val) {
count++;
it++;
}
}
TEST_EQ(static_cast<int>(result.size()), count);
}
}
| true |
5fee413f8766b6eed97ef9b9d8bd48e129d9ce64 | C++ | ArtyomAdov/learning_sibsutis | /learning/thirdparty/САОД/Двор/laba12.cpp | UTF-8 | 5,344 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
struct spis {
spis *next;
char el;
};
struct tle {
spis *head;
spis *tail;
};
void Fillocheredrand(spis *head,int n){
srand((unsigned int) time(NULL));
int k=n; spis *p,*tail=head;
while (n){
p=new spis;
p->el=char(65+rand()%17);
n--;
p->next=tail->next;
tail->next=p;}
}
void PrintSpis(spis *head) {
spis *p;
for(p = head; p; p = p->next)
printf("%c ", p->el);
printf("\n\n");
}
void priamoe(int m, char str[], tle array[]) {
int H;
for (int i = 0; i < m; ++i) {
array[i].head = new spis;
array[i].head->next = NULL;
array[i].tail = array[i].head;
}
int length = strlen(str);
for (int i = 0; i < length; ++i) {
H = int(str[i]) % m;
spis *p = new spis;
p->el = str[i];
p->next = NULL;
array[H].tail->next = p;
array[H].tail = p;
}
for(int i = 0; i < m; ++i) {
printf("Spis %d: ", i);
PrintSpis(array[i].head->next);
}
}
void priamoesearch(int m, char key, tle array[]) {
int H;
H = int(key) % m;
spis *p = array[H].head;
int i=-1;
while (p) {
if (p->el == key) {
printf("Key found = %c nomer pozicii v %d spiske %d \n", p->el,H,i);
break;
}
p = p->next;i++;
}
if (p == NULL) printf("Key not found\n");
}
int priamaialinins(int m, char *arr, char ch) {
int i = 1, count = 0;
while (i != m) {
int j = (int(ch) + i) % m;
if (arr[j] != 0) {
count++;
}
if (arr[j] == ch) break;
if (arr[j] == 0) {
arr[j] = ch;
break;
}
++i;
}
if (i==m){printf("perepolnenieline ");}
return count;
}
void priamaialin(int t, char *array, char string[]) {
int length = strlen(string);
for (int i = 0; i < length; ++i) {
char ch = string[i];
priamaialinins(t, array, ch);
}
for (int i = 0; i < t; ++i) {
printf("%d ", i);printf("%c ", array[i]);printf("\n");
}
printf("\n");
printf("\n");
}
int poiskpopriamoilin(int m, char array[], char key) {
int i = int(key) % m;
while (i != m) {
if (array[i] == key) {
printf("nashli simvol = %c v meste %d\n", key,i);
return i;
}
i++;
}
printf("ne nashli simvol\n");
}
int priamaia4ins(int m, char *arr, char ch) {
int count = 0;
int h = int(ch) % m;
int d = 1;
while (1) {//printf("%d ",d);
if (arr[h] != 0) {count++;//printf("%d %d ",arr[h],ch);
}/////
if (arr[h] == ch) {break;}
if (arr[h] == 0) {arr[h] = ch;{break;}}
if (d >= m) {{printf("perepolnenie");break;}}
h = h + d;
if (h >= m) {h = h - m;}
d=d+2;
}
return count;
}
void priamaia4(int t, char *array, char string[]) {
int length = strlen(string);
for (int i = 0; i < length; ++i) {
char ch = string[i];
priamaia4ins(t, array, ch);
}
for (int i = 0; i < t; ++i) {
printf("%d ", i);printf("%c ", array[i]);printf("\n");
}
printf("\n");
printf("\n");
}
int poiskpriamaia4(int m, char *array, char ch) {
int h = int(ch) % m;
int d = 1;
while (1) {
if (array[h] == ch) {
printf("nashli simvol = %c v meste %d\n", ch,h);
break;
}
if (array[h] == 0) {
printf("ne nashli \n");
break;
}
if (d >= m) {
break;
}
h = h + d;
if (h >= m) h = h - m;
d = d + 2;
}
}
void Print_Table(int t, char *arr, char *arr_2, char *str) {
int length = strlen(str);
int S_1 = 0, S_2 = 0;
length = strlen(str);
for (int n = 0; n < length; ++n) {
char ch = str[n];
int count_1 = priamaialinins(t, arr, ch);
S_1 += count_1;
int count_2 = priamaia4ins(t, arr_2, ch);
S_2 += count_2;
}
printf("%d %d \n", S_1, S_2);
}
int main(){
int n=11;
tle c[n];
int i;
spis* p;
char array[n];
char array1[n];
for (i = 0; i < n; i++) {
c[i].tail = (spis *) &c[i].head;
}
spis *S=NULL;
S=new spis;
S->next=NULL;
Fillocheredrand(S,n);
p=S->next;
char string[] = "DVORNIKOVBCDEF";
char st[] = "bewithlonkymarz";
for (int i = 0; i < n; ++i) {
array[i] = 0;
array1[i] = 0;
}
//priamaialin(n, array, string);
//poiskpopriamoilin(n, array, 'R');
priamaia4(n, array1, string);
poiskpriamaia4(n, array1, 'R');
Print_Table(n, array, array1, string);
//priamoe(n,st,c);
//priamoesearch(n, 'r', c);
//for(int e=0;e<17;e++){
//PrintSpis(c[e].head->next);
//}
system("PAUSE");
}
| true |
ae2a0f34a6bb95b0fa5c05c34fe157e4c53759ee | C++ | Pandey-SaurabhP/Tic-Tac-Toe-Game | /main.cpp | UTF-8 | 7,284 | 3.1875 | 3 | [] | no_license | // This game is completely made by Saurabh Pandey alone...
#include <iostream>
#include <string>
#include <cstdlib>
#define p(x) std::cout << x << std::endl;
using namespace std;
string check(char board[9], string P1, string P2)
{
for (int i = 0; i < 3; ++i)
{
if (board[i] == 'X' &&
board[i] == board[i+3] &&
board[i] == board[i+6])
{
return P1;
}
}
for (int i = 0; i < 9; i = i + 3)
{
if (board[i] == 'X' &&
board[i] == board[i + 1] &&
board[i] == board[i + 2])
{
return P1;
}
}
if (board[0] == 'X' &&
board[0] == board[4] &&
board[4] == board[8] ||
board[6] == 'X' &&
board[6] == board[4] &&
board[6] == board[2])
{
return P1;
}
for (int i = 0; i < 3; ++i)
{
if (board[i] == 'O' &&
board[i] == board[i+3] &&
board[i] == board[i+6])
{
return P2;
}
}
for (int i = 0; i < 9; i = i + 3)
{
if (board[i] == 'O' &&
board[i] == board[i + 1] &&
board[i] == board[i + 2])
{
return P2;
}
}
if (board[0] == 'O' &&
board[0] == board[4] &&
board[4] == board[8] ||
board[6] == 'O' &&
board[6] == board[4] &&
board[6] == board[2])
{
return P2;
}
return "0";
}
void print_board(char board[9])
{
cout << "\n\n";
cout << " | | " << endl;
cout << " " << board[0] << " | " << board[1] << " | " << board[2] << " \n";
cout << " _____|_____|_____\n";
cout << " | | " << endl;
cout << " " << board[3] << " | " << board[4] << " | " << board[5] << " \n";
cout << " _____|_____|_____\n";
cout << " | | " << endl;
cout << " " << board[6] << " | " << board[7] << " | " << board[8] << " \n";
cout << " | | \n\n";
cout << "_ __ _ __ _ __ _ __ _ __ _\n";
}
int invalid_move(int cell)
{
if (cell >= 0 && cell < 9)
{
return 0;
}
else
{
cout << "Invalid Move..Try again\n";
cout << "Your turn again:";
cin >> cell;
cell--;
return invalid_move(cell);
}
}
int invalid_move_2(char board[9], int cell)
{
if(board[cell] != ' ')
{
cout << "The cell is already taken by another player...\n";
cout << "Please try again:";
cin >> cell;
cell--;
return invalid_move_2(board, cell);
}
else
{
return cell;
}
}
int invalid_move_C(char board[9], int cell)
{
if(board[cell] != ' ')
{
cell = (rand() % 9) + 1;
cell--;
return invalid_move_C(board, cell);
}
else
{
return cell;
}
}
void help()
{
system("cls");
p("Hello Everyone")
p("Its the basic Tic-Tac-Toe game noooo..")
p("")
p("Here, you have to insert a number from 1 to 9.")
p("And an X or O will get inserted in the blocks using the following rule..")
p(" | | ")
p(" 1 | 2 | 3 ")
p("_____|_____|_____")
p(" | | ")
p(" 4 | 5 | 6 ")
p("_____|_____|_____")
p(" | | ")
p(" 7 | 8 | 9 ")
p(" | | ")
p("Press Enter for Main Menu...")
cin.get();
cin.get();
system("cls");
}
int main()
{
char inp, a = 'A';
while (a == 'A' || a == 'a')
{
char board[9] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
cout << "This game is entirely made by Saurabh Pandey...\n";
cout << "Welcome to Tic-Tac-toe...\n\n";
cout << "Press S for Single-Player..." << endl;
cout << "Press M for Multiplayer..." << endl;
cout << " or " << endl;
cout << "Press H for Help.." << endl;
cout << " or " << endl;
cout << "Press X to Exit..." << endl;
cout << "Enter your key:";
cin >> inp;
if (inp == 'H' || inp == 'h')
{
help();
continue;
}
if (inp == 'X' || inp == 'x')
{
break;
}
if(inp == 'S' || inp == 's')
{
system("cls");
string P1, P2 = "Computer";
cout << "Please Enter your name:";
cin >> P1;
system("cls");
int cell;
for (int i = 1; i <= 4; i++)
{
print_board(board);
cout << endl;
cout << P1 << "'s turn::Enter the cell:";
cin >> cell;
cell--;
invalid_move(cell);
cell = invalid_move_2(board, cell);
board[cell] = 'X';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
cin.get();
goto end2;
}
system("cls");
cin.get();
system("cls");
print_board(board);
cout << endl;
cout << "Please Wait...";
int cell = (rand() % 9) + 1;
cell--;
cell = invalid_move_C(board, cell);
board[cell] = 'O';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
goto end2;
}
system("cls");
}
system("cls");
print_board(board);
cout << "\n" << P1 << "'s turn::Enter the cell:";
cin >> cell;
cell--;
invalid_move(cell);
cell = invalid_move_2(board, cell);
system("cls");
board[cell] = 'X';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
cin.get();
}
end2:
print_board(board);
cout << "\nFinal board is here...\nPress Enter...";
cin.get();
system("cls");
}
if (inp == 'M' || inp == 'm')
{
system("cls");
string P1, P2;
cout << "Player 1 name is:";
cin >> P1;
cout << "Player 2 name is:";
cin >> P2;
system("cls");
int cell;
for (int i = 1; i <= 4; i++)
{
print_board(board);
cout << endl;
cout << P1 << "'s turn::Enter the cell:";
cin >> cell;
cell--;
invalid_move(cell);
cell = invalid_move_2(board, cell);
board[cell] = 'X';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
cin.get();
goto end1;
}
cin.get();
system("cls");
print_board(board);
cout << endl;
cout << P2 << "'s turn::Enter the cell:";
cin >> cell;
cell--;
invalid_move(cell);
cell = invalid_move_2(board, cell);
board[cell] = 'O';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
cin.get();
goto end1;
}
cin.get();
system("cls");
}
print_board(board);
cout << "\n" << P1 << "'s turn::Enter the cell:";
cin >> cell;
cell--;
invalid_move(cell);
cell = invalid_move_2(board, cell);
system("cls");
board[cell] = 'X';
if (check(board, P1, P2) != "0")
{
system("cls");
cout << check(board, P1, P2) << " wins";
cin.get();
}
end1:
print_board(board);
cout << "\nFinal board is here...\nPress Enter...";
cin.get();
system("cls");
}
end:
cout << "Thanks for playing...\n\n\n";
cout << "Press A to play again...\n";
cout << "Any other key to exit...";
cin >> a;
system("cls");
}
system("cls");
cout << "Thanks for playing...\nBye-Bye...\n\n";
cin.get();
return 0;
}
| true |
31762c7967d5066bd73db6f1ad66e0c40ddd848d | C++ | brianzarzuela/CPP | /ContactList/ContactList.h | UTF-8 | 1,359 | 2.859375 | 3 | [] | no_license | // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Title : ContactList.h
// Course : Computational Problem Solving II (CPET-321)
// Developer : Brian Zarzuela
// Date : Fall 2019 (2191)
// Description : Header file for ContactList.cpp containing all the
// prototypes for the functions in ContactList_functions.cpp
// as well as the contact struct definition.
//
// Last Modified : 19 September 2019
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#ifndef CONTACTLIST_H_
#define CONTACTLIST_H_
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
// Contact struct for storing each contact's four (4) data fields.
// Note: ice stands for In-Case-of-Emergency and is a flag that indicates
// that the contact should be called in case of an emergency.
// More than one contact can have the ICE flag.
struct contact
{
string name;
string cell_number;
string email_address;
bool ICE;
contact *next_addr;
};
contact *Read();
void Show(contact *head);
contact *Delete(contact *head, int position);
contact *Insert(contact *head, int position);
contact *Update(contact *head, int position);
void Toggle(contact *head, int position);
void Write(contact *head);
#endif /* CONTACTLIST_H_ */
| true |
0322b59dcc4e080ca308e50e457cbdd0bdf6730b | C++ | mandalsudipti/competitive_programming | /codeforces/Dominant Piranha.cpp | UTF-8 | 724 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int n ;
cin>>n;
vector<int>arr(n);
int maximum = 0 ;
for(int i=0;i<n;i++)
{
cin>>arr[i];
maximum = max( maximum , arr[i]);
}
int freq = 0 , idx = -1;
for(int i=0;i<n;i++)
{
if(arr[i]==maximum)
{
freq++;
if((i>0 && arr[i-1]<maximum) || (i<n-1 && arr[i+1]<maximum))
idx = i ;
}
}
if(freq == n)
cout<<"-1"<<endl;
else
cout<<idx + 1 <<endl;
}
return 0;
} | true |
1648c6e3069319137b5522416561f3a69b62f89a | C++ | firstep710/coding-test | /프로그래머스/Level_1/45.cpp | UTF-8 | 922 | 2.9375 | 3 | [] | no_license | #include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(pair<int, float> a, pair<int, float> b)
{
if (a.second == b.second)
return a.first < b.first;
else
return a.second > b.second;
}
vector<int> solution(int N, vector<int> stages) {
vector<int> answer(N);
vector<int> all(N);
vector<int> success(N);
vector<pair<int, float>> temp(N);
for (int i = 0; i < stages.size(); i++)
{
for (int j = 0; j < stages[i] && j < N; j++)
all[j]++;
for (int j = 0; j < stages[i] - 1; j++)
success[j]++;
}
for (int i = 0; i < N; i++)
{
float fail = (all[i] == 0? 0 : (all[i] - success[i]) / (float)all[i]);
temp[i] = make_pair(i + 1, fail);
}
sort(temp.begin(), temp.end(), compare);
for (int i = 0; i < N; i++)
answer[i] = temp[i].first;
return answer;
} | true |
cc155657749aefbe26d235d6f92b7782d0972191 | C++ | mln-lchs/Moteur3D | /Moteur3D/CollisionData.h | UTF-8 | 478 | 2.796875 | 3 | [] | no_license | #ifndef COLLISIONDATA_H
#define COLLISIONDATA_H
#include "Contact.h"
class CollisionData
{
public:
CollisionData(int contactsLeft);
CollisionData(Contact *contacts, int contactsLeft);
virtual ~CollisionData();
Contact* getContacts();
void setContacts(Contact *contacts);
int getSize();
int getContactsLeft();
void setContactsLeft(int contactsLeft);
void addContact(Contact contact);
private:
Contact *contacts;
int size;
int contactsLeft;
};
#endif | true |
e605376e751ceb585f5540f2d9221557c0097eb8 | C++ | QtWorks/SmartHome | /model/power.h | UTF-8 | 674 | 2.5625 | 3 | [] | no_license | #ifndef POWER_H
#define POWER_H
#include <QObject>
#include <QVector>
#include "singleton.h"
class Power : public QObject
{
Q_OBJECT
friend class Singleton<Power>;
QVector<bool> m_enabled{ true, false, false, false, false, true, false, true, true, true, false, true, false, false, false, false};
QVector<int> m_watt{10, 100, 50, 100, 300, 500, 500, 500, 1000, 500, 500, 300, 100, 50, 100, 50};
Power() : QObject(nullptr)
{
}
public:
int getMax() const;
int getTotal() const;
int getPower(int index) const;
bool enabled(int index) const;
void setEnabled(int index, bool enabled);
signals:
void update();
};
#endif
| true |
b903005bca0dcd5969424525b535ab86219c335b | C++ | pratyushsetu28/socket | /server.cpp | UTF-8 | 4,833 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
int main()
{
int ssock,csock;
// creating server and client socket discriptor
int a,b,c;
unsigned int len;
struct sockaddr_in server,client;
// creating server & client socket object
if((ssock=socket(AF_INET,SOCK_STREAM,0))==-1)
// creating socket
{
perror("socket: ");
exit(-1);
}
server.sin_family=AF_INET;
server.sin_port=htons(10000);
// initializing server socket parameters.
server.sin_addr.s_addr=INADDR_ANY;
bzero(&server.sin_zero,0);
// appending 8 byte zeroes to 'struct sockaddr_in', to make it equal in size with 'struct sockaddr'.
len=sizeof(struct sockaddr_in);
if((bind(ssock,(struct sockaddr *)&server,len))==-1)
// binding port & IP
{
perror("bind error: ");
exit(-1);
}
if((listen(ssock,5))==-1)
// listening for client
{
perror("listen error: ");
exit(-1);
}
if((csock=accept(ssock,(struct sockaddr *)&client,&len))==-1)
// accepting connection
{
perror("accept error: ");
exit(-1);
}
int row,col,x;
ofstream file;
char filename[7];
recv(csock,&filename,sizeof(filename),0);
cout<<"Recieving file "<<filename<<endl;
file.open("copyfile.txt");
recv(csock,&row,sizeof(row),0);
recv(csock,&col,sizeof(col),0);
file<<row<<" "<<col<<"\n";
int mat[row][col];
int i=0,choice;
while (i<row){
int j=0;
while (j<col){
recv(csock,&x,sizeof(x),0);
mat[i][j]=x;
file<<x<<" ";
j++;
}
file<<"\n";
i++;
}
cout<<"Recieved file successfully"<<endl;
file.close();
cout<<"Enter a choice: "<<endl;
cout<<"1. Sum of all elements of matrix"<<endl<<"2. Show row-wise sum of matrix"<<endl<<"3. Show maximum and minimum element row-wise"<<endl<<"4. Show column-wise sum of matrix"<<endl<<"5. Show max and min element column-wise"<<endl<<"6. Show left-diagonal and right-diagonal sum"<<endl<<"7. Create transpose of matrix"<<endl<<"8. Show max and min element in matrix"<<endl;
while (1){
recv(csock,&choice,sizeof(choice),0);
cout<<"choice "<<choice<<" recieved"<<endl;
if (choice==1){
int sum=0;
for (int i=0;i<row;i++){
for (int j=0;j<col;j++){
sum+=mat[i][j];
}
}
send(csock,&sum,sizeof(sum),0);
cout<<"Sum of matrix sent: "<<sum<<endl;
}
else if (choice==2){
int i=0;
while (i<row){
int sum=0;
for (int j=0;j<col;j++){
sum+=mat[i][j];
}
send(csock,&sum,sizeof(sum),0);
cout<<"Sum of row "<<i+1<<" sent: "<<sum<<endl;
i++;
}
}
else if (choice==3){
for (int i=0;i<row;i++){
int maxx=-1,minn=999999;
for (int j=0;j<col;j++){
maxx=max(maxx,mat[i][j]);
minn=min(minn,mat[i][j]);
}
send(csock,&maxx,sizeof(maxx),0);
send(csock,&minn,sizeof(minn),0);
cout<<"Maximum element of row "<<i+1<<" sent: "<<maxx<<endl;
cout<<"Minimum element of row "<<i+1<<" sent: "<<minn<<endl;
}
}
else if (choice==4){
for (int i=0;i<col;i++){
int sum=0;
for (int j=0;j<row;j++){
sum+=mat[j][i];
}
send(csock,&sum,sizeof(sum),0);
cout<<"Sum of column "<<i+1<<" sent: "<<sum<<endl;
}
}
else if (choice==5){
for (int i=0;i<col;i++){
int maxx=-1,minn=999999;
for (int j=0;j<row;j++){
maxx=max(maxx,mat[j][i]);
minn=min(minn,mat[j][i]);
}
send(csock,&maxx,sizeof(maxx),0);
send(csock,&minn,sizeof(minn),0);
cout<<"Maximum element of col "<<i+1<<" sent: "<<maxx<<endl;
cout<<"Minimum element of col "<<i+1<<" sent: "<<minn<<endl;
}
}
else if (choice==6){
int notpossible=-1;
if (row!=col){
send(csock,¬possible,sizeof(notpossible),0);
cout<<"Not possible to compute left and right diagonal"<<endl;
}
else{
int left=0,right=0;
for (int i=0;i<row;i++){
for (int j=0;j<col;j++){
if (i==j) left+=mat[i][j];
if (col-i-1==j) right+=mat[i][j];
}
}
send(csock,&left,sizeof(left),0);
send(csock,&right,sizeof(right),0);
cout<<"Left diagonal sum sent: "<<left<<endl;
cout<<"Right diagonal sum sent: "<<right<<endl;
}
}
else if (choice==7){
int transpose[col][row];
for (int i=0;i<row;i++){
for (int j=0;j<col;j++){
transpose[j][i]=mat[i][j];
}
}
for (int i=0;i<col;i++){
for (int j=0;j<row;j++){
send(csock,&transpose[i][j],sizeof(transpose[i][j]),0);
}
}
cout<<"TRanspose of matrix sent!"<<endl;
}
else{
int maxx=-1,minn=99999;
for (int i=0;i<row;i++){
for (int j=0;j<col;j++){
maxx=max(maxx,mat[i][j]);
minn=min(minn,mat[i][j]);
}
}
send(csock,&maxx,sizeof(maxx),0);
cout<<"Maximum element of matrix sent:"<<maxx<<endl;
send(csock,&minn,sizeof(minn),0);
cout<<"Minimum element of matrix sent:"<<minn<<endl;
}
char letter;
recv(csock,&letter,sizeof(letter),0);
if (letter=='n' || letter=='N') break;
}
close(ssock);
}
| true |
60f2f1f3576a14a5696712f0a0d0842a1c905667 | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/23/150.c | UTF-8 | 337 | 2.5625 | 3 | [] | no_license | void main()
{
char c,a[400],b[40][20];
int i=0,j,k=0,t=0;
c=getchar();
while(c!='\n')
{
a[i]=c;
i++;
c=getchar();
}
a[i]=' ';
for(j=0;j<=i;j++)
{
b[k][t]=a[j];
t++;
if(a[j]==' ')
{
b[k][t-1]='\0';
k++;
t=0;
}
}
for(i=k-1;i>0;i--)
printf("%s ",b[i]);
printf("%s\n",b[0]);
} | true |
a212f7356dee35d35a74a7c48995bc845ab3452d | C++ | principal6/DoubleBufferedConsole | /DoubleBufferedConsole/dbc.cpp | UTF-8 | 1,562 | 3.3125 | 3 | [] | no_license | #include "DoubleBufferedConsole.h"
#include <string>
#include <thread>
#include <atomic>
int main()
{
CDoubleBufferedConsole Console{ 130, 30, "Console" };
Console.SetClearBackground(EBackgroundColor::Black);
Console.SetDefaultForeground(EForegroundColor::LightYellow);
std::atomic<short> X{};
std::atomic<short> Y{};
std::thread ThrInput{
[&]()
{
while (true)
{
if (Console.IsTerminated()) break;
if (Console.HitKey())
{
if (Console.IsHitKey(EArrowKeys::Right)) ++X;
else if (Console.IsHitKey(EArrowKeys::Left)) --X;
else if (Console.IsHitKey(EArrowKeys::Down)) ++Y;
else if (Console.IsHitKey(EArrowKeys::Up)) --Y;
else if (Console.IsHitKey(VK_RETURN))
{
if (Console.ReadCommand())
{
if (Console.IsLastCommand("/quit"))
{
Console.Terminate();
}
}
}
}
}
}
};
while (true)
{
if (Console.IsTerminated()) break;
Console.Clear();
Console.FillBox(5, 5, 7, 10, '~', EBackgroundColor::Cyan, EForegroundColor::White);
Console.PrintBox(0, 0, 70, 29, ' ', EBackgroundColor::DarkGray, EForegroundColor::Black);
Console.PrintBox(70, 0, 40, 29, ' ', EBackgroundColor::DarkGray, EForegroundColor::Black);
Console.PrintCommandLog(70, 0, 40, 29);
Console.PrintCommand(0, 29);
Console.PrintChar(X, Y, '@', EForegroundColor::LightYellow);
Console.PrintChar(112, 1, 'X');
Console.PrintChar(112, 2, 'Y');
Console.PrintHString(114, 1, X);
Console.PrintHString(114, 2, Y);
Console.Render();
}
ThrInput.join();
return 0;
} | true |
a6de75f8491fac855900e198b71d239b1305b31a | C++ | lenfien/LenOS | /src/LenOS/Screen/screen.h | GB18030 | 4,708 | 2.65625 | 3 | [] | no_license |
/*
ʾⲿû֮Ľӿ, ǰʾʹõSSD1289
Screenֻͼṩӵĺ, Щͼֱӵ
ScreenṩĻͼֺǺŻ
ƾ bitmap, .
ScreenṩӲصϢ, width()ʾĻ߶
ScreenԺõṩⲿ, ΪĽӿ, ûṩĺ㽫
Ӧ÷, ΪǶû
2013.3.30 lenfien
*/
#ifndef __SCREEN__
#define __SCREEN__
#define __CPlusPlus
#include "com.h"
#include "color.h"
#include "ssd1289.h"
#include "datas.h"
class Screen: public SSD1289
{
public:
class Point
{
public:
Point() {}
S16 x,y;
Point(S16 _x, S16 _y):x(_x), y(_y) {}
bool operator==(const Point& p) {return x == p.x && y == p.y;}
Point operator+(const Point& p)
{
Point tp(x + p.x, y + p.y);
return tp;
}
Point operator-(const Point& p)
{
Point tp(x - p.x, y - p.y);
return tp;
}
};
class RectType
{
public:
RectType(){}
RectType(Point p, int _xSize, int _ySize):position(p), xSize(_xSize), ySize(_ySize){}
Point position;
int xSize;
int ySize;
bool operator==(const RectType & r)
{
return (position == r.position) && (xSize == r.xSize) && (ySize == r.ySize);
}
}; //
public:
/******************************************************/
Screen();
Screen(
Color::ColorValue backColor,
Oritation oritation = ORITATION_320_240,
Color::ColorQuality colorQuality = Color::COLOR_262K,
bool light = 1);
/************************ʾ״̬************************/
public:
using SSD1289::width;
using SSD1289::high;
static Oritation oritation();
static Color::ColorQuality color_quality();
static U8 back_light();
static Color::ColorValue background_color();
/******************************************************/
static RectType window;
static RectType set_vwindow(RectType window);
static RectType reset_vwindow(RectType window);
static RectType set_full_vwindow();
static RectType get_vwindow() {return window;}
static void restore_vwindow(RectType w);
/************************ͼδ************************/
//ͼ
protected:
static void draw_bitmap(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, const unsigned char *pPic);
static void draw_bitmap(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, Datas<Color::ColorType>&);
static Color::ColorValue
draw_point(Point p, Color::ColorValue color); //
static void draw_line(S16 xStart, S16 yStart, S16 xEnd, S16 yEnd, Color::ColorValue color); //
static void draw_rectangle(S16 xStart, S16 yStart, S16 xLen, S16 yLen, Color::ColorValue color); //ʵľ
private:
static void draw_bitmap_262K(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, const unsigned char *pPic);
static void draw_bitmap_262K(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, Datas<Color::ColorType >&);
static void draw_bitmap_65K(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, Datas<Color::ColorType>&);
static void draw_bitmap_65K(S16 xStart, S16 yStart, S16 bitMapWidth, S16 bitMapHigh, const unsigned char *pPic);
/**************************ִ***********************/
protected:
static void draw_font(U16 fontWidth, U16 fontHigh,
U16 xStart, U16 yStart, U32 color,
U32 backColor, const unsigned char *pFont);
protected:
static void draw_font_left_align(U16 fontWidth, U16 fontHigh, U16 xStart, U16 yStart,
U32 color, U32 backColor, const unsigned char *pFont);
static void draw_font_right_align(U16 fontWidth,U16 fontHigh, U16 xStart, U16 yStart,
U32 color, U32 backColor, const unsigned char *pFont);
/***********************ײ**************************/
public:
static void set_point(U32 color);
static Color::ColorValue get_point(U16 x, U16 y);
static U32 get_points(S16 xStart, S16 yStart, S16 xLen, S16 yLen, Datas<Color::ColorType>&);
static U32 get_points(S16 xStart, S16 yStart, S16 xLen, S16 yLen, unsigned char*);
static void clear_screen(U32 color);
using SSD1289::set_window;
using SSD1289::set_full_window;
};
#endif
| true |
b455929d55ba6c42d4e5e467cbe8d19a02bf130b | C++ | alok27a/CSE2011-Data-Structures-Algorithm | /Lab/Module 2/Assignment/Assignment 2/Practice/Q4.cpp | UTF-8 | 2,582 | 3.875 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct node
{
int age;
char name[20];
char disease[30];
char doctor_assigned[30];
struct node *next;
} *head = NULL;
int choice;
void enqueue();
void dequeue();
void display();
void enqueue()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
cout<<"Enter patient's name: ";
cin>>temp->name;
cout<<"Enter patient's age: ";
cin>>temp->age;
cout<<"Enter disease of patient: ";
cin>>temp->disease;
cout<<"Enter doctor assigned to patient: ";
cin>>temp->doctor_assigned;
if (head == NULL)
{
head = temp;
head->next = NULL;
}
else if (head->next == NULL)
{
if (head->age > temp->age)
{
head->next = temp;
temp->next = NULL;
}
else
{
temp->next = head;
head = temp;
}
}
else
{
struct node *r;
r = head;
while (r->next != NULL)
{
if (r->next->age > temp->age)
{
r = r->next;
}
else
{
break;
}
}
if (r == head)
{
temp->next = head;
head = temp;
}
else
{
temp->next = r->next;
r->next = temp;
}
}
}
void dequeue ()
{
struct node *ptr;
if(head == NULL)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
ptr = head;
head = head -> next;
free(ptr);
}
}
void display()
{
int c = 0;
struct node *r;
r = head;
while (r != NULL)
{
c++;
printf("%d.%s(%d) , Disease: %s , Doctor Assigned: %s \n", c, r->name, r->age,r->disease,r->doctor_assigned);
r = r->next;
}
}
int main()
{
while (choice != 4)
{
printf("\n1.Insert a patient\n");
printf("2.Discharge Patient \n");
printf("3.Display\n");
printf("4.Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("Exiting..\n");
break;
default:
printf("Invalid input\n");
};
}
return 1;
} | true |
80fea92c2f1c42807e62610b8c55a75c2802d36c | C++ | greenfox-zerda-sparta/Ak0s | /Week-02/day-3/02.cpp | UTF-8 | 480 | 3.40625 | 3 | [] | no_license | //============================================================================
// Name : 02.cpp
// Author : Ak0s
//============================================================================
// print the value of number using the "number_pointer"
#include <iostream>
using namespace std;
int main() {
int number = 1234;
int* number_pointer = &number;
cout << "The value stored at memory address of 'number_pointer' is: " << *number_pointer;
return 0;
}
| true |
b1803085eac13df34b17db5d17796e00c0b9975f | C++ | SofianeHamlaoui/Cours-Informatique | /IUT-Lyon-1/UML/C++/Parc Vehicules/vehicule.h | UTF-8 | 592 | 2.703125 | 3 | [] | no_license | #pragma once
class Vehicule
{
protected :
char Matricule[9];
int Annee;
int Km;
int Puissance;
public :
Vehicule();
Vehicule (char Unmatricule[], int UneAnnee, int UnKm, int UnePuissance);
~Vehicule();
virtual void affiche();
char* get_Unmatricule();
int get_UneAnnee();
int get_UnKm();
int get_UnePuissance();
void set_Unmatricule(char Unmatricule[]);
void set_UneAnnee(int UneAnnee);
void set_UnKm(int UnKm);
void set_UnePuissance(int UnePuissance);
};
| true |
e61baf3d52b766ea11ac0bcadaa7dc3197424105 | C++ | biggoka/prac | /src/interface/Interface.cpp | UTF-8 | 1,506 | 3.125 | 3 | [] | no_license | #include "Interface.hpp"
#include "RequestMaker.hpp"
#include "Request.hpp"
#include <iostream>
#include <string>
#include <sstream>
void Interface::list_rooms() const {
std::cout << "Rooms: " << std::endl;
for (auto &room: bank->get_rooms()) {
std::cout << room << std::endl;
}
std::cout << std::endl;
}
void Interface::list_groups() const {
std::cout << "Groups: " << std::endl;
for (auto &group: bank->get_groups()) {
std::cout << group << std::endl;
}
std::cout << std::endl;
}
void Interface::list_subjects() const {
std::cout << "Subjects: " << std::endl;
for (auto &subject: bank->get_subjects()) {
std::cout << subject << std::endl;
}
std::cout << std::endl;
}
void Interface::list_requests() const {
std::cout << "Requests: " << std::endl;
int i = 0;
for (auto &req: requests) {
std::cout << i++ << ": " << req->representation<< std::endl;
}
std::cout << std::endl;
}
void Interface::add_request() {
std::cout << "Input your request in format \"group subject professor logic_expression\": \n";
std::string str;
std::stringstream ss;
std::getline(std::cin, str);
ss.str(str);
try {
requests.push_back(RequestMaker::make_request(str, bank));
} catch (std::invalid_argument &ex) {
std::cout << "Incorrect expression, try again" << std::endl;
} catch (...) {
std::cout << "Something went wrong, try again" << std::endl;
}
}
| true |
aeb74ff5898a4dc7333d931162f167541f68f3e8 | C++ | ryandcyu/phosphor-net-ipmid | /integrity_algo.cpp | UTF-8 | 2,070 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #include <openssl/hmac.h>
#include <openssl/sha.h>
#include "integrity_algo.hpp"
#include "message_parsers.hpp"
namespace cipher
{
namespace integrity
{
Interface::Interface(const Buffer& sik, const Key& addKey, size_t authLength)
{
unsigned int mdLen = 0;
// Generated K1 for the integrity algorithm with the additional key keyed
// with SIK.
if (HMAC(EVP_sha1(), sik.data(), sik.size(), addKey.data(),
addKey.size(), K1.data(), &mdLen) == NULL)
{
throw std::runtime_error("Generating Key1 for integrity "
"algorithm failed");
}
authCodeLength = authLength;
}
Buffer AlgoSHA1::generateHMAC(const uint8_t* input, const size_t len) const
{
Buffer output(SHA_DIGEST_LENGTH);
unsigned int mdLen = 0;
if (HMAC(EVP_sha1(), K1.data(), K1.size(), input, len,
output.data(), &mdLen) == NULL)
{
throw std::runtime_error("Generating integrity data failed");
}
// HMAC generates Message Digest to the size of SHA_DIGEST_LENGTH, the
// AuthCode field length is based on the integrity algorithm. So we are
// interested only in the AuthCode field length of the generated Message
// digest.
output.resize(authCodeLength);
return output;
}
bool AlgoSHA1::verifyIntegrityData(const Buffer& packet,
const size_t length,
Buffer::const_iterator integrityData) const
{
auto output = generateHMAC(
packet.data() + message::parser::RMCP_SESSION_HEADER_SIZE,
length);
// Verify if the generated integrity data for the packet and the received
// integrity data matches.
return (std::equal(output.begin(), output.end(), integrityData));
}
Buffer AlgoSHA1::generateIntegrityData(const Buffer& packet) const
{
return generateHMAC(
packet.data() + message::parser::RMCP_SESSION_HEADER_SIZE,
packet.size() - message::parser::RMCP_SESSION_HEADER_SIZE);
}
}// namespace integrity
}// namespace cipher
| true |
c78031ef7a38a4f8edab8885121b9aebd816ff65 | C++ | ickowzcy/paranoia | /include/netlink/error.h | UTF-8 | 547 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef PARANOIA_ERROR_H
#define PARANOIA_ERROR_H
#include <sys/errno.h>
#include <cstring>
#include <stdexcept>
#include "util/concat.h"
using Errno = int;
struct ErrnoException : public std::runtime_error {
template <typename... Args>
ErrnoException(Errno err, Args... args) : std::runtime_error(concat(args...)) {
this->err = err;
this->msg = concat(std::runtime_error::what(), ": ", strerror(err));
}
const char* what() const noexcept override;
Errno err;
private:
std::string msg;
};
#endif // PARANOIA_ERROR_H
| true |
4174fbe5ea6c733ad07dc66ce189e071b937c508 | C++ | nmessa/CPP-2021 | /Lab Exercise 2.1.2021/Demo 3/Demo 3/main.cpp | UTF-8 | 831 | 3.203125 | 3 | [] | no_license | //Switch Demo
//Author: nmessa
//Date: 1/30/2021
#include <iostream>
using namespace std;
int main()
{
int score;
cout << "Enter a test score (1 - 100): ";
cin >> score;
if (score < 0 || score > 100)
{
cout << "Invalid score entered" << endl;
return 0;
}
score = score / 10;
switch (score)
{
case 10:
cout << "A" << endl;
break;
case 9:
cout << "A" << endl;
break;
case 8:
cout << "B" << endl;
break;
case 7:
cout << "C" << endl;
break;
case 6:
cout << "D" << endl;
break;
default:
cout << "F" << endl;
//break;
}
return 0;
} | true |
fcb3721d6680bfe8e852ff5190f1c3fd45561979 | C++ | novikov-ilia-softdev/thinking_cpp | /tom_1/chapter_16/22/main.cpp | UTF-8 | 424 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include "tvector.h"
int main()
{
TVector<std::string> vector;
vector.push_back( new std::string( "hello, "));
vector.push_back( new std::string( "wonderful "));
vector.push_back( new std::string( "world!"));
for( int i = 0; i < vector.size(); i++)
{
std::cout << *vector[ i];
}
std::cout << std::endl;
for( int i = 0; i < vector.size(); i++)
{
delete vector[ i];
}
vector.clear();
}
| true |
d92b09acb75ed9f0459ad83fee104b029a932e82 | C++ | ssfehlberg/MCC9_Validation_Codes | /CCInclusive_validation_Sep2018/CCInclusive_stuff/CCInclusive_validation_test/localProducts_larsoft_v06_26_01_10_e10_prof/uboonecode/v06_26_01_13/source/uboone/UBXSec/HitCosmicTag/Base/BaseDqDsSmootherAlgo.h | UTF-8 | 904 | 2.6875 | 3 | [] | no_license | /**
* \file BaseDqDsSmootherAlgo.h
*
* \ingroup Base
*
* \brief Class def header for a class BaseDqDsSmootherAlgo
*
* @author Marco Del Tutto
*/
/** \addtogroup Base
@{*/
#ifndef HITCOSMICTAG_BASEDQDSSMOOTHERALGO_H
#define HITCOSMICTAG_BASEDQDSSMOOTHERALGO_H
#include "BaseAlgorithm.h"
namespace cosmictag {
/**
\class BaseDqDsSmootherAlgo
Algorithm base class for prohibiting the match
between a charge cluster and a flash \n
*/
class BaseDqDsSmootherAlgo : public BaseAlgorithm{
public:
/// Default constructor
BaseDqDsSmootherAlgo(const std::string name="noname")
: BaseAlgorithm(kDqDsSmoother,name)
{}
/// Default destructor
virtual ~BaseDqDsSmootherAlgo(){}
/**
* @brief CORE FUNCTION: order the hits
*/
virtual int SmoothDqDs(SimpleCluster&) const = 0;
};
}
#endif
/** @} */ // end of doxygen group
| true |
b175a427061459210753199fc5f69031624d6120 | C++ | ytchhh/code_of_me | /DataStruct/Tree/BTree/Tree.h | UTF-8 | 8,788 | 3.625 | 4 | [] | no_license | //二叉树头结点
#ifndef _TREE_H
#define _TREE_H
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;
template<class T>
struct BinTreeNode //二叉树结点类定义
{
T data; //数据域
BinTreeNode<T> *leftChild,*rightChild; //左子女,右子女链域
BinTreeNode():leftChild(NULL),rightChild(NULL) //无参构造函数
{}
BinTreeNode(T x,BinTreeNode<T> *l = NULL,BinTreeNode<T> *r = NULL):data(x),leftChild(l),rightChild(r) //带参构造函数
{}
friend bool equal(BinTreeNode<T> *a,BinTreeNode<T> *b)
{ //如果a 和b的子树相等 则返回false 否则返回true
if(a == NULL && b == NULL)
return true;
if(a != NULL && b == NULL && a->data == b->data && equal(a->leftChild,b->leftChild) && equal(a->rightChild,b->rightChild))
return true;
else
return false;
}
//BinTreeNode<T>* createBinaryTree(T *VLR,T *LVR,int n);//利用前序和中序序列构造二叉树
};
template<class T>
BinTreeNode<T>* createBinaryTree(T *VLR,T *LVR,int n)
{//根据前序和中序序列构造二叉树
if(n == 0)
return NULL;
int k = 0;
while(VLR[0] != LVR[k]) //在中序遍历中找根
++k;
BinTreeNode<T> *t = new BinTreeNode<T>(VLR[0]); //创建根结点
t->leftChild = createBinaryTree(VLR+1,LVR,k);
//从前序VLR+1开始对中序的0~k-1左子序列的k个元素递归建立左子树
t->rightChild = createBinaryTree(VLR+k+1,LVR+k+1,n-k-1);
//从前序VLR+1+k开始对中序的k+!~n-1右子序列的n-k-1个元素建立右子树
return t;
}
template<class T>
class BinaryTree
{
public:
public:
BinaryTree():root(NULL) //构造函数
{}
BinaryTree(T value):RefValue(value),root(NULL)
{
}
BinaryTree(BinaryTree<T> &s) //拷贝构造函数
{
root = Copy(s.root);
}
~BinaryTree() //析构函数
{
destroy(root);
}
void CreateBinTree()
{
root - new BinTreeNode<T>;
CreateBinTree(root);
}
bool IsEmpty() //判二叉树是否为空
{
return (root == NULL) ? true : false;
}
BinTreeNode<T>* Parent(BinTreeNode<T> *current) //返回父节点
{
return (root == NULL || root == current) ? NULL : Parent(root,current);
}
BinTreeNode<T>* LeftChild(BinTreeNode<T> *current) //返回左子女
{
return (current != NULL) ? current->leftChild : NULL;
}
BinTreeNode<T>* RightChild(BinTreeNode<T> *current) //返回右子女
{
return (current != NULL) ? current->rightChild : NULL;
}
int Height() //返回树的高度
{
return Height(root);
}
int Size() //返回树的结点数
{
return Size(root);
}
BinTreeNode<T>* getRoot()const //取根
{
return root;
}
void preOrder() //前序遍历
{
preOrder(root);
}
void inOrder() //中序遍历
{
inOrder(root);
}
void postOrder() //后序遍历
{
postOrder(root);
}
bool operator==(BinaryTree<T> &t)
{ //判断两颗二叉树是否相等
return (equal(this->root,t.root));
}
void levelOrder(void (*visit) (BinTreeNode<T> *p)); //层次序遍历
int Insert(const T& item); //插入新元素
BinTreeNode<T>* Find(T &item)const; //搜索
protected:
BinTreeNode<T> *root; //二叉树的根指针
T RefValue; //数据停止输入停止标志
void CreateBinTree(BinTreeNode<char> *& BT); //从文件读入建树
bool Insert(BinTreeNode<T> *& subTree,const T &x); //插入
void destroy(BinTreeNode<T> *& subTree); //删除
bool Find(BinTreeNode<T> *subTree,const T& x)const; //查找
BinTreeNode<T>* Copy(BinTreeNode<T> *orignode); //复制
int Height(BinTreeNode<T> *subTree); //返回树高度
int Size(BinTreeNode<T> *subTree); //返回结点数
BinTreeNode<T> *Parent(BinTreeNode<T> *subTree,BinTreeNode<T> *current); //返回父结点
BinTreeNode<T> *Find(BinTreeNode<T> *subTree,const T& x); //搜寻x
void Traverse(BinTreeNode<T> *subTree,ostream& out); //前序遍历输出
void preOrder(BinTreeNode<T>* subTree); //前序遍历
void inOrder(BinTreeNode<T>* subTree); //中序遍历
void postOrder(BinTreeNode<T>* subTree); //后序遍历
friend istream& operator >> (istream& in,BinaryTree<T>& Tree); //重载操作 输入
friend ostream& operator << (ostream& out,BinaryTree<T>& Tree); //重载操作 输出
};
template<class T>
void BinaryTree<T>::destroy(BinTreeNode<T> *& subTree)
{ //若指针subTree不为空,则删除根为subTree的子树
if(subTree != NULL)
{
destroy(subTree->leftChild); //递归删除subTree的左子树
destroy(subTree->rightChild); //递归删除subTree的右子树
delete subTree; //删除subTree
}
}
template<class T>
BinTreeNode<T>* BinaryTree<T>::Parent(BinTreeNode<T> *subTree,BinTreeNode<T> *current)
{ //从节点subTree开始,搜索结点current的父结点。若找到结点current的父结点,咋函数返回父结点地址,否则函数返回NULL
if(subTree == NULL)
return NULL;
if(subTree->leftChild == current || subTree->rightChild == current)
return subTree; //找到返回父结点subTree
BinTreeNode<T> *p;
if(p = Parent(subTree->leftChild,current) != NULL)
return p; //递归在左子树中搜索
else
return Parent(subTree->rightChild,current); //递归在右子树中搜索
}
template<class T>
void BinaryTree<T>::Traverse(BinTreeNode<T> *subTree,ostream& out)
{ //搜索并输出根为subTree的二叉树
if(subTree != NULL) //subTree为空则返回 否则
{
out<<subTree->data<<" "; //输出subTree的数据值
Traverse(subTree->leftChild,out); //递归搜索并输出subTree的左子树
Traverse(subTree->rightChild,out); //递归搜索并输出subTree的右子树
}
}
template<class T>
istream& operator >> (istream& in,BinaryTree<T>& Tree)
{ //重载操作 输入并建立一颗二叉Tree in是输入流对象
CreateBinTree(in,Tree.root); //建立二叉树
return in;
}
template<class T>
ostream& operator << (ostream& out,BinaryTree<T>& Tree)
{ //重载操作 输出一颗二叉树Tree, out是输出流对象
out<<"二叉树的前序遍历\n"; //提示:搜索二叉树
Tree.Traverse(Tree.root,out); //从根开始输出
out<<endl;
return out;
}
template<class T>
void BinaryTree<T>::CreateBinTree(BinTreeNode<char> *&BT) //*&是对指针的引用
{
stack<BinTreeNode<char> * > s;
BT = NULL; //置空二叉树
BinTreeNode<char> *p,*t;
int k; //用k作为处理左右子树标记
char ch;
cin>>ch; //从in顺序读入一个字符
while(ch != RefValue) //逐个字符处理
{
switch(ch)
{
case '(':s.push(p); k = 1; break; //进入子树
case ')':s.pop();break; //退出子树
case ',':k = 2;break;
default:p = new BinTreeNode<T>(ch);
if(BT == NULL)
BT = p;
else if(k == 1)
{
t = s.top();
t->leftChild = p; //链入*t的左子女
}
else
{
t = s.top();
t->rightChild = p; //链入*t的右子女
}
}
cin>>ch;
}
}
template<class T>
void BinaryTree<T>::preOrder(BinTreeNode<T>* subTree)
{ //递归算法 按照前序次序遍历以subTree为根的二叉树
if(subTree != NULL)
{
cout<<(subTree)->data; //访问根结点
preOrder(subTree->leftChild); //前序遍历根的左子树
preOrder(subTree->rightChild); //前序遍历根的右子树
}
}
template<class T>
void BinaryTree<T>::inOrder(BinTreeNode<T>* subTree)
{ //递归函数 按照中序次序遍历以subTree为根的子树
if(subTree != NULL)
{
inOrder(subTree->leftChild); //中序遍历根的左子树
cout<<(subTree)->data; //访问根结点
inOrder(subTree->rightChild); //中序遍历根的右子树
}
}
template<class T>
void BinaryTree<T>::postOrder(BinTreeNode<T>* subTree)
{ //递归函数 按照前序次序遍历subTree为根的子树
if(subTree != NULL)
{
postOrder(subTree->leftChild);
postOrder(subTree->rightChild);
cout<<(subTree)->data;
}
}
template<class T>
int BinaryTree<T>::Height(BinTreeNode<T> *subTree)
{ //计算以subTree为根的二叉树的高度或深度
if(subTree == NULL)
return 0; //递归结束 空树高度为0
else
{
int i = Height(subTree->leftChild);
int j = Height(subTree->rightChild);
return (i < j) ? j+1 : i+1;
}
}
template<class T>
int BinaryTree<T>::Size(BinTreeNode<T> *subTree)
{ //计算以subTree为根结点的二叉树的结点个数
if(subTree == NULL) //递归结束 空树的结点个数为0
return 0;
else
return 1 + Size(subTree->leftChild) + Size(subTree->rightChild);
}
template<class T>
BinTreeNode<T>* BinaryTree<T>::Copy(BinTreeNode<T> *orignode)
{ //这个函数返回一个指针,他给出一个以orignode为根的二叉树的副本
if(orignode == NULL) //根为空 返回空指针
return NULL;
BinTreeNode<T>* temp = new BinTreeNode<T>; //创建根结点
temp->data = orignode->data; //传送数据
temp->leftChild = Copy(orignode->leftChild); //拷贝左子树
temp->rightChild = Copy(orignode->rightChild); //拷贝右子树
return temp; //返回根指针
}
#endif
| true |
3a68ed3ba7b6984ce1242660dc6b4488c06b91af | C++ | watashi/AlgoSolution | /codeforces/ac/0/025/E.cpp | UTF-8 | 1,100 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
string comb(const string& lhs, const string& rhs) {
static int fail[1 << 20];
fail[(int)lhs.length() - 1] = lhs.length();
for (int i = (int)lhs.length() - 2; i >= 0; --i) {
fail[i] = fail[i + 1];
while (fail[i] < (int)lhs.length() && lhs[i] != lhs[fail[i] - 1]) {
fail[i] = fail[fail[i]];
}
if (lhs[i] == lhs[fail[i] - 1]) {
--fail[i];
}
}
int pos = (int)lhs.length() - 1;
for (int i = (int)rhs.length() - 1; i >= 0; --i) {
if (lhs[pos] == rhs[i]) {
if (--pos == -1) {
return rhs;
}
} else if (pos + 1 < (int)lhs.length()) {
pos = fail[pos + 1] - 1;
++i;
}
}
return lhs.substr(0, pos + 1) + rhs;
}
int main() {
int ans;
string v[3];
cin >> v[0] >> v[1] >> v[2];
sort(v, v + 3);
ans = 1 << 20;
do {
ans = min(ans, (int)comb(comb(v[0], v[1]), v[2]).length());
} while (next_permutation(v, v + 3)) ;
cout << ans << endl;
return 0;
}
//# When Who Problem Lang Verdict Time Memory
//219525 Dec 15, 2010 7:15:48 PM watashi E - Test GNU C++ Accepted 110 ms 6648 KB
| true |
2cf0501d548d9baf03afab0623cfc5dc90f445c2 | C++ | rohithv1997/C- | /Class12/prac20.CPP | UTF-8 | 810 | 4.0625 | 4 | [] | no_license | #include<iostream.h>
/*
Program #20:
To swap 2 pointers allocated dynamically
*/
int *a=new int;
int *b=new int;
int *p=new int;
int *q=new int;
int *tmp=new int;
void swap(int*p, int*q)
{ if(p && q && tmp)
{ *tmp=*p;
*p=*q;
*q=*tmp;
}
else
cout<<"Error in creating memory"<<endl;
}
void main()
{ if(a && b)
{ cout<<"Enter 2 Numbers"<<endl;
cin>>*a>>*b;
cout<<"Before Swapping"<<endl;
cout<<"*a : \t"<<*a<<endl;
cout<<"*b : \t"<<*b<<endl;
swap(a,b);
cout<<"After Swapping"<<endl;
cout<<"*a : \t"<<*a<<endl;
cout<<"*b : \t"<<*b<<endl;
}
else
cout<<"Error in creating memory"<<endl;
delete a;
delete b;
delete tmp;
delete p;
delete q;
}
/*Sample Input/Output:
Enter 2 Numbers
123
456
Before Swapping
*a : 123
*b : 456
After Swapping
*a : 456
*b : 123
*/
| true |
4c4834ff99d8103b26abba691d3353b520557dd5 | C++ | mlomb/problems | /SPOJ/MST1 - Minimum Step To One/main.cpp | UTF-8 | 576 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
using namespace std;
typedef long long int lli;
#define MAX 10000000 * 2 + 10
lli dp[MAX];
int main() {
// precompute
dp[1] = 0;
for(lli i = 2; i < MAX; i++){
lli steps = dp[i - 1];
if(i % 2 == 0 && dp[i / 2] < steps)
steps = dp[i / 2];
if(i % 3 == 0 && dp[i / 3] < steps)
steps = dp[i / 3];
dp[i] = steps + 1;
}
//ifstream cin("input.in");
int T;
cin >> T;
lli n;
for(int i = 0; i < T; i++){
cin >> n;
cout << "Case " << (i + 1) << ": " << dp[n] << endl;
}
return 0;
}
| true |
bd0597273ba74681017cabaeff5ee97fc82dd1df | C++ | thianhe/assignment | /C++/105590050_HW6/105590050_HW6/Vector2D.cpp | UTF-8 | 367 | 3.078125 | 3 | [] | no_license | #include "Vector2D.h"
Vector2D::Vector2D()
{
_x = 0;
_y = 0;
}
Vector2D::Vector2D(int x, int y)
{
_x = x;
_y = y;
}
void Vector2D::SetXY(int x, int y)
{
_x = x;
_y = y;
}
int Vector2D::GetX()
{
return _x;
}
int Vector2D::GetY()
{
return _y;
}
int Vector2D::operator* (const Vector2D& v)
{
return (_x * v._x) + (_y * v._y);
}
| true |
818dc24e509d3ae22331bc59bfdf318a14864c5e | C++ | SantiagoGiraldo/Taller-1-Estruc-II | /2 valores nxm.cpp | UTF-8 | 601 | 3.21875 | 3 | [] | no_license | //Ejercicio 3/B Ingresar dos valores para un resultado de 0 Y 1
#include <iostream>
#include <conio.h>
int main(int argc, char *argv[])
{
int i,n,m,fin,j,k,band=0,band1=0;
printf("ingrese el primer valor: ");
scanf("%d",&n);
printf("ingrese el segundo valor: ");
scanf("%d",&m);
fin=n * m;
int x[fin];
for(i=0;i<=fin;i++)
{
if(band==0&&band1==0)
{
x[i]=0;
band=1;
band1=1;
}
else
{
x[i]=1;
band=0;
band1=0;
}
}
for(j=0;j<fin;j++)
{
printf("%d ",x[j]);
}
return 0;
}
| true |
09c1d288c18a27aef94278b2766bed078a000948 | C++ | seanbaxter/circle | /examples/scopes/scopes.cxx | UTF-8 | 774 | 2.71875 | 3 | [] | no_license | // circle -filetype=ll
#include <cstdio>
// Meta statements work in global scope.
@meta printf("%s:%d I'm in global scope.\n", __FILE__, __LINE__);
namespace ns {
// Or in namespace scope.
@meta printf("%s:%d Hello namespace.\n", __FILE__, __LINE__);
struct foo_t {
// Also in class definitions.
@meta printf("%s:%d In a class definition!\n", __FILE__, __LINE__);
enum my_enum {
// Don't forget enums.
@meta printf("%s:%d I'm in your enum.\n", __FILE__, __LINE__);
};
void func() const {
// And naturally in function/block scope.
// Ordinary name lookup finds __func__ in this function's
// declarative region.
@meta printf("%s ... And block scope.\n", __func__);
}
};
}
int main() {
return 0;
} | true |
b3d67368ffaf9c3dc676bd0b43aaa31748e655fe | C++ | Ananasty11/git1 | /z5p4.cpp | WINDOWS-1251 | 822 | 3 | 3 | [] | no_license | // https://github.com/AnastasiaPugacheva/git1
// 4
#include <stdio.h>
#include <math.h>
#include <locale.h> //
int main() {
setlocale (LC_ALL, "Rus");
float x1, y1, x2, y2, d1, d2, p, s; //
scanf("%f", &x1);
scanf("%f", &y1);
scanf("%f", &x2);
scanf("%f", &y2); //
d1 = sqrt((y2 - y1) * (y2 - y1));
d2 = sqrt((x2 - x1) * (x2 - x1));
p = 2 * (d1 + d2);
s = d1 * d2; //
printf(" = %f\n = %f", p, s); //
return 0;
}
| true |
91100390e414c3b8c8d8e9f834957471fd3086a8 | C++ | fenshitianyue/socketPracticce | /socket_cpp/tcp_server.hpp | UTF-8 | 1,466 | 3.046875 | 3 | [] | no_license | ///////////////////////////////////////////////////////
// 这是一个TCP通用服务器框架
///////////////////////////////////////////////////////
#pragma once
#include <iostream>
#include <functional>
#include "tcp_socket.hpp"
using Handler = std::function<void(const std::string& req, std::string* resp)>;
class TcpServer{
public:
TcpServer(const std::string& ip, uint16_t port) : _ip(ip),_port(port){}
bool Start(Handler handler){
//创建 socket
CHECK_RET(_listen_sock.Socket());
//绑定端口号
CHECK_RET(_listen_sock.Bind(_ip, _port));
//进行监听
CHECK_RET(_listen_sock.Listen(5));
//进入事件循环
while(true){
//进行accept
TcpSocket new_sock;
std::string ip;
uint16_t port = 0;
if(!_listen_sock.Accept(&new_sock, &ip, &port)){
continue;
}
std::cout << "[client " << ip.data() << ":" << port << "] connect!" << std::endl;
//循环读写
while(true){
std::string req;
if(!new_sock.Recv(&req)){
std::cout << "[client " << ip.data() << ":" << port << "] disconnect!" << std::endl;
new_sock.Close();
break;
}
//计算响应
std::string resp;
handler(req, &resp);
//发送响应
if(!new_sock.Send(resp)){
return false;
}
}
}
return true;
}
private:
TcpSocket _listen_sock;
std::string _ip;
uint64_t _port;
};
| true |
b80698f1c45b96d4eb1438b2df8fe9485f648f56 | C++ | Kazwyrm/AsteroidTanks | /AsteroidTanks/AsteroidTanks/Asteroids.cpp | UTF-8 | 868 | 2.78125 | 3 | [] | no_license | #include "Asteroids.h"
#include <Renderer2D.h>
#include <Texture.h>
#include <Input.h>
Asteroids::Asteroids()
{
}
Asteroids::Asteroids(glm::vec2 * pos)
{
m_texture = new aie::Texture("../bin/textures/rock_medium.png");
a_pos = pos;
}
Asteroids::~Asteroids()
{
delete m_texture;
}
float Asteroids::getPosX()
{
return a_pos->x;
}
float Asteroids::getPosY()
{
return a_pos->y;
}
bool Asteroids::IsCollision(float a_x, float a_y, float p_x, float p_y)
{
float xDist = a_x - p_x;
float yDist = a_y - p_y;
if (yDist <= 50 && yDist >= -50 && xDist >= -50 && xDist <= 50)
{
return true;
}
else
{
return false;
}
}
void Asteroids::Update(float deltaTime)
{
a_pos->y--;
}
void Asteroids::Draw(aie::Renderer2D * spriteBatch)
{
spriteBatch->drawSprite(m_texture, a_pos->x, a_pos->y);
}
| true |
a286f317380d75fc5c80646cb7e94baffc25262a | C++ | Uchihabo/OJ | /字母金字塔.cpp | GB18030 | 518 | 3.59375 | 4 | [] | no_license | #include<iostream>
using namespace std;
/*
ĸ
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
*/
int main()
{
for(int i=0; i<5; i++)
{
//ƿո
for(int s=8-i; s>0; s--) //s:space
cout<<" ";
//ǰ
for(int f=0; f<=i;f++) //f:forward
cout<<(char)('A'+f);
//ƺ
for(int b=i-1; b>=0;b--) //b:back
cout<<(char)('A'+b);
cout<<endl;
}
return 0;
}
| true |
a03327d7b185c9c393755fb572898a3018fd75e9 | C++ | IntelligentRoboticsLab/DNT2013 | /NaoTH2011-light/NaoTHSoccer/Source/Core/Representations/Perception/GoalPercept.cpp | UTF-8 | 3,347 | 2.640625 | 3 | [] | no_license | /**
* @file GoalPercept.cpp
*
* Definition of class GoalPercept
*/
#include "GoalPercept.h"
#include "Messages/Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
void Serializer<GoalPercept>::serialize(const GoalPercept& representation, std::ostream& stream)
{
naothmessages::GoalPercept g;
// angleToSeenGoal
g.set_angletoseengoal(representation.angleToSeenGoal);
// goalCentroid
g.mutable_goalcentroid()->set_x(representation.goalCentroid.x);
g.mutable_goalcentroid()->set_y(representation.goalCentroid.y);
g.mutable_goalcentroid()->set_z(representation.goalCentroid.z);
// numberOfSeenPosts
g.set_numberofseenposts(representation.numberOfSeenPosts);
// post
for(unsigned int i=0; i < representation.numberOfSeenPosts && i < representation.MAXNUMBEROFPOSTS; i++)
{
naothmessages::GoalPost* p = g.add_post();
const GoalPercept::GoalPost& post = representation.post[i];
// basePoint
p->mutable_basepoint()->set_x(post.basePoint.x);
p->mutable_basepoint()->set_y(post.basePoint.y);
// topPoint
// TODO
// color
p->set_color((naothmessages::Color) post.color);
// type
p->set_type((naothmessages::GoalPost_PostType) post.type);
// positionReliable
p->set_positionreliable(post.positionReliable);
// seenHeight
p->set_seenheight(post.seenHeight);
// position
p->mutable_position()->set_x(post.position.x);
p->mutable_position()->set_y(post.position.y);
}//end for
google::protobuf::io::OstreamOutputStream buf(&stream);
g.SerializeToZeroCopyStream(&buf);
}//end serialize
void Serializer<GoalPercept>::deserialize(std::istream& stream, GoalPercept& representation)
{
// clear the percept befor reading from stream
representation.reset();
// deserialize
naothmessages::GoalPercept g;
google::protobuf::io::IstreamInputStream buf(&stream);
g.ParseFromZeroCopyStream(&buf);
// angleToSeenGoal
if(g.has_angletoseengoal())
{
representation.angleToSeenGoal = g.angletoseengoal();
}
// goalCentroid
if(g.has_goalcentroid())
{
representation.goalCentroid.x = g.goalcentroid().x();
representation.goalCentroid.y = g.goalcentroid().y();
representation.goalCentroid.z = g.goalcentroid().z();
}
// numberOfSeenPosts
if(g.has_numberofseenposts())
{
representation.numberOfSeenPosts = g.numberofseenposts();
}
// post
for(unsigned int i=0; i < (unsigned int)g.post_size() && i < representation.numberOfSeenPosts && i < representation.MAXNUMBEROFPOSTS; i++)
{
const naothmessages::GoalPost& p = g.post(i);
GoalPercept::GoalPost& post = representation.post[i];
// basePoint
post.basePoint.x = p.basepoint().x();
post.basePoint.y = p.basepoint().y();
// topPoint
// TODO
// color
post.color = (ColorClasses::Color) p.color();
// type
post.type = (GoalPercept::GoalPost::PostType) p.type();
// positionReliable
post.positionReliable = p.positionreliable();
// seenHeight
post.seenHeight = p.seenheight();
// position
post.position.x = p.position().x();
post.position.y = p.position().y();
}//end for
}//end deserialize | true |
f2c3076f65ea74d07c102bd80390282589c412a2 | C++ | ngangwar962/C_and_Cpp_Programs | /codevita/right_rotation.cpp | UTF-8 | 319 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i,j,k;
int times;
char str[]="abcd";
cin>>times;
cout<<str<<endl;
int len=strlen(str);
for(k=0;k<times;k++)
{
char temp=str[len-1];
for(j=len-1;j>=1;j--)
{
str[j]=str[j-1];
}
str[0]=temp;
}
cout<<str<<endl;
return 0;
}
| true |
5d627cd45af6918c2806f568e575011e98c05d20 | C++ | Kullsno2/C-Cpp-Programs | /FormName.cpp | UTF-8 | 1,010 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<stdio.h>
#include<stack>
#include<vector>
#include<queue>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<map>
#include<algorithm>
#include<utility>
#define ll long long
#define p(a) printf("%d\n",a)
#define s(a) scanf("%d",&a)
#define sll(a) scanf("%lld",&a)
#define sl(a) scanf("%ld",&a)
#define FOR(a,b,it) for( it=a ; it<=b ; ++it)
#define pi pair<int,int>
using namespace std ;
int main() {
int t;
s(t);
while(t--){
int n;
s(n);
string str ;
cin>>str;
int hash[256]={0};
for(int i=0 ;i <256 ; i++)
hash[str[i]]++;
int q;
s(q);
while(q--){
string temp;
cin>>temp;
int thash[256] ;
for(int i=0 ; i<256 ; i++)
thash[i] = hash[i];
bool flag = true;
for(int i=0 ; i<temp.length() ; i++){
if(thash[temp[i]]==0){
flag = false ;
break;
}
else
thash[temp[i]]--;
}
if(flag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
return 0 ;
}
| true |
1421f1d787f4fc7ab4815fbbbabdb55d2ce5c02f | C++ | Joshua-Dunne/SDL2-Command | /include/Game.h | UTF-8 | 1,576 | 2.59375 | 3 | [] | no_license | #include <SDL2/SDL.h>
#include <iostream>
#include <string>
#include "TextureData.h"
#include "MacroCommand.h"
#include "LegoCommand.h"
#include "ClayCommand.h"
#include "ConcreteCommand.h"
#include "TimberCommand.h"
class Game
{
public:
Game();
~Game();
void run();
private:
//Loads media
void loadMedia();
SDL_Texture* loadFromFile(std::string path, SDL_Texture* tex, TextureData& data);
void renderTexture(SDL_Texture* t_tex, TextureData t_data);
//Frees media and shuts down SDL
void close();
void processEvents();
void processMouse(SDL_MouseButtonEvent& b);
void update();
void render();
void cleanUp();
bool m_gameIsRunning;
//Event handler
SDL_Event e;
//Screen dimension constants
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 512;
//The window we'll be rendering to
SDL_Window* window = NULL;
//The surface contained by the window
SDL_Surface* screenSurface = NULL;
// Renders stuff idk?
SDL_Renderer* renderer = NULL;
SDL_Texture* legoButton = NULL;
TextureData legoButtonData;
SDL_Texture* clayButton = NULL;
TextureData clayButtonData;
SDL_Texture* concreteButton = NULL;
TextureData concreteButtonData;
SDL_Texture* timberButton = NULL;
TextureData timberButtonData;
SDL_Texture* undoButton = NULL;
TextureData undoData;
SDL_Texture* redoButton = NULL;
TextureData redoData;
SDL_Texture* executeButton = NULL;
TextureData executeButtonData;
MacroCommand macro;
}; | true |
29bc8a3abc73bf780ce14701e0ca69a729bc25c3 | C++ | Marcussk/CellularAutomaton | /src/cell.h | UTF-8 | 310 | 2.53125 | 3 | [] | no_license | #ifndef CELL_H
#define CELL_H
#include <iostream>
class Cell
{
public:
Cell(){}
Cell(int init_status);
int status;
int slump_id;
int weight;
int time_vacant;
bool isSlump;
};
//Status:
//0 - vacant
//1 - moss
//2 - lichen
//If changed alter update, clear, statecopy
#endif | true |
8d13741ade80fadf8994367540cb867e5e888320 | C++ | not-ed/notmariobros | /notMarioBros/notMarioBros/textrenderer.cpp | UTF-8 | 2,558 | 3.1875 | 3 | [] | no_license | #include "textrenderer.h"
#include <iostream>
namespace Text {
void Initialize(SDL_Renderer* renderer) {
if (!initialized)
{
fonts[FONT::ID::REGULAR] = new Texture2D(renderer);
fonts[FONT::ID::REGULAR]->LoadFromFile("Fonts/font_regular.png");
fonts[FONT::ID::MARIO] = new Texture2D(renderer);
fonts[FONT::ID::MARIO]->LoadFromFile("Fonts/font_mario.png");
fonts[FONT::ID::LUIGI] = new Texture2D(renderer);
fonts[FONT::ID::LUIGI]->LoadFromFile("Fonts/font_luigi.png");
fonts[FONT::ID::GOLD] = new Texture2D(renderer);
fonts[FONT::ID::GOLD]->LoadFromFile("Fonts/font_gold.png");
fonts[FONT::ID::SILVER] = new Texture2D(renderer);
fonts[FONT::ID::SILVER]->LoadFromFile("Fonts/font_silver.png");
// This should not be used in a call, but is here in the event of it being passed by accident as a parameter.
fonts[FONT::ID::count] = new Texture2D(renderer);
fonts[FONT::ID::count]->LoadFromFile("Fonts/font_regular.png");
initialized = true;
}
}
void Shutdown() {
if (initialized)
{
delete fonts[FONT::ID::REGULAR];
delete fonts[FONT::ID::MARIO];
delete fonts[FONT::ID::LUIGI];
delete fonts[FONT::ID::GOLD];
delete fonts[FONT::ID::SILVER];
delete fonts[FONT::ID::count];
initialized = false;
}
}
void Draw(std::string text, IntVector2D position, FONT::ID font, FONT::ALLIGNMENT allignment) {
if (initialized) {
// Convert the string into a c-style string and calculate the width of the whole string in pixels.
int letter_count = strlen(text.c_str());
int text_width = letter_count * CHARACTER_WIDTH;
// Calculate horizontal text position offset
int text_offset = 0;
switch (allignment)
{
case FONT::CENTER:
text_offset = -(text_width / 2);
break;
case FONT::RIGHT:
text_offset = -(text_width);
break;
default:
break;
}
SDL_Rect char_rect{ 0,0,CHARACTER_WIDTH,CHARACTER_HEIGHT };
SDL_Rect dest_rect{ position.x + text_offset,position.y,CHARACTER_WIDTH,CHARACTER_HEIGHT };
for (int i = 0; i < letter_count; i++)
{
// Get the ASCII representation of the relevant character
int char_ascii = (int)text[i];
// Use the ASCII character to index into the font sprite sheet and obtain to corresponding character.
char_rect.x = (char_ascii % CHARACTER_ROW_COUNT)*CHARACTER_WIDTH;
char_rect.y = (char_ascii / CHARACTER_ROW_COUNT)*CHARACTER_HEIGHT;
// Render the character
fonts[font]->Render(char_rect, dest_rect, SDL_FLIP_NONE, 0.0);
dest_rect.x += CHARACTER_WIDTH;
}
}
}
} | true |
5f1a0810fccaf5ea8eb82fc522507aa734248bfe | C++ | clangen/musikcube | /src/musikcore/utfutil.h | UTF-8 | 2,575 | 2.953125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | #pragma once
#include <string>
#include <wchar.h>
#include <algorithm>
#include <memory>
#pragma warning(push, 0)
#include <utf8/utf8.h>
#ifdef WIN32
#include <wcwidth.h>
#endif
#pragma warning(pop)
#ifdef max
#undef max
#endif
inline std::wstring u8to16(const std::string& u8) {
std::wstring result;
utf8::utf8to16(u8.begin(), u8.end(), std::back_inserter(result));
return result;
}
inline std::string u16to8(const std::wstring& u16) {
std::string result;
utf8::utf16to8(u16.begin(), u16.end(), std::back_inserter(result));
return result;
}
static inline size_t u8cols(const std::string& str) {
std::wstring wstr = u8to16(str);
#ifdef WIN32
int result = std::max(0, mk_wcswidth(wstr.c_str(), wstr.size()));
#else
int result = std::max(0, wcswidth(wstr.c_str(), wstr.size()));
#endif
return (result > 0) ? result : str.size();
}
inline static size_t u8len(const std::string& str) {
try {
return utf8::distance(str.begin(), str.end());
}
catch (...) {
return str.length();
}
}
/* get the (raw) character index of the "nth" logical/display character */
inline static size_t u8offset(const std::string& str, int n) {
if (str.size() == 0) {
return std::string::npos;
}
std::string::const_iterator it = str.begin();
int count = 0;
while (count < n && it != str.end()) {
utf8::unchecked::next(it);
++count;
}
return (size_t)(it - str.begin());
}
inline static std::string u8substr(const std::string& in, int offset, int len) {
std::string::const_iterator begin = in.begin() + offset;
std::string::const_iterator it = begin;
int count = 0;
while (count < len && it != in.end()) {
utf8::unchecked::next(it);
++count;
}
return std::string(begin, it);
}
template<typename... Args>
static std::string u8fmt(const std::string& format, Args ... args) {
/* https://stackoverflow.com/a/26221725 */
size_t size = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; /* extra space for '\0' */
std::unique_ptr<char[]> buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args ...);
return std::string(buf.get(), buf.get() + size - 1); /* omit the '\0' */
}
static inline void u8replace(
std::string& input, const std::string& find, const std::string& replace)
{
size_t pos = input.find(find);
while (pos != std::string::npos) {
input.replace(pos, find.size(), replace);
pos = input.find(find, pos + replace.size());
}
}
| true |
3cdd60bbeb6a2226abacb384b967658cb18e3ff4 | C++ | nathard/Palindrome | /Palindrome/Palindrome.cpp | UTF-8 | 1,476 | 4.1875 | 4 | [] | no_license | //
// palindrome.cpp
// Created by Nathan Harding on 11/08/11.
//
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
//Prototype
bool Palindrome(const string &phrase);
int main()
{
// Record input
string temp;
string pal;
cout << "Enter a word or phrase to check for Palindrome: " << endl;
getline(cin, temp);
// Ignore any capitilisation, spacing and punctuation
for(int i = 0; i < temp.length(); ++i) {
temp[i] = tolower(temp[i]);
if (isalpha(temp[i])) {
pal += temp[i];
}
}
// Check if string is a Palindrome
if (Palindrome(pal)) {
cout << "\n" << temp << " is a Palindrome\n";
}
else
cout << "\n" << temp << " is not a Palindrome\n";
return 0;
}
// Function Description: Compare the characters of a string by reversing them with a stack
// Pre-conditions: Push string onto stack, pop chars off stack to build reverse string
// Post-conditions: Compare the 2 strings and return true if they match
bool Palindrome(const string &phrase)
{
stack<char> Stack;
string revString;
for (int i = 0; i < phrase.size(); ++i)
Stack.push(phrase[i]); // Push characters onto stack
while (!Stack.empty())
{
revString += Stack.top(); // Assign top element of stack to string
Stack.pop(); // Remove top element of stack
}
return revString == phrase; // Compare the strings
} | true |
c63ffcd20210ce774b29a2fba2fb9249fe6280bc | C++ | FrancescoTerrosi/chip8emu | /CHIP8/main/game.cpp | UTF-8 | 6,110 | 2.859375 | 3 | [] | no_license | #include "chip8.h"
#include "chip8test.h"
#include "keymap.h"
#include <GL/gl.h>
#include <GL/glut.h>
/*
* Quì definisco le costanti per la finestra opengl
*/
const int PIXEL_SIZE = 10; //ciascun pixel di gfx sarà ripetuto 10 volte in basso e 10 volte a destra
const int SCREEN_ROWS = GMEM_ROWS * PIXEL_SIZE;
const int SCREEN_COLS = GMEM_COLS * PIXEL_SIZE;
//--- utilissima funzione per fare una sleep di usec microsecondi che funziona sia su win che su linux ---//
#include <chrono>
#include <thread>
void sleepMicroseconds(unsigned long usec) //serve per la freq. clock
{
std::this_thread::sleep_for(std::chrono::microseconds(usec));
}
//-------------------------------------------------------------------------------------------------------//
Chip8 myChip8;
/*
* Definisco la matrice RIGHE x COLONNE x 3 che opengl deve renderizzare.
* In realtà è una semplice copia della memoria grafica di chip8
* però per ciascun valore 1/0 dei pixel, definisco i parametri R,G,B per quel pixel:
* Se chip8.gfx[i][j] = 1 -> openGlScreen[i][j][0 = R] = 255, openGlScreen[i][j][1 = G] = 255, openGlScreen[i][j][2 = B] = 255
* Ossia ho messo rosso 255, verde 255, blu 255 = BIANCO
* Se li metto tutti a zero avrò il nero, taac
*/
unsigned char openGlScreen[GMEM_ROWS][GMEM_COLS][3];
unsigned char screenToRenderize[SCREEN_ROWS][SCREEN_COLS][3]; //espansione di openGlScreen
std::chrono::microseconds t0;
void keyPressCallback(unsigned char k, int x, int y) //signatura (:O) che vuole opengl
{
static_cast<void>(x); // giusto per togliere gli warning unused variable
static_cast<void>(y);
int keycode = keymap(k);
if(keycode != -1)
{
myChip8.onKeyPress(keycode);
}
}
void keyReleaseCallback(unsigned char k, int x, int y)
{
static_cast<void>(x);
static_cast<void>(y);
int keycode = keymap(k);
if(keycode != -1)
{
myChip8.onKeyRelease(keycode);
}
}
void renderChip8() //funzione che renderizza nella finestra opengl il contenuto della memoria grafica di chip8
{
//traduco da gfx a openGlScreen
for(int i = 0; i < GMEM_ROWS; i++)
{
for(int j = 0; j < GMEM_COLS; j++)
{
unsigned char col = myChip8.gfx[i][j] == 1 ? 0xFF : 0x00; //questo pixel deve essere bianco o nero
openGlScreen[GMEM_ROWS - 1 - i][j][0] = openGlScreen[GMEM_ROWS - 1 - i][j][1] = openGlScreen[GMEM_ROWS - 1 - i][j][2] = col;
}
}
//espando openGlScreen di PIXEL_SIZE e renderizzo questo
unsigned int act_row = 0;
unsigned int act_col = 0;
for(int i = 0; i < GMEM_ROWS; i++)
{
for(int j = 0; j < GMEM_COLS; j++)
{
unsigned char colour = openGlScreen[i][j][0];
for(int k = 0; k < PIXEL_SIZE; k++)
{
for(int l = 0; l < PIXEL_SIZE; l++)
{
screenToRenderize[act_row + k][act_col + l][0] = screenToRenderize[act_row + k][act_col + l][1] = screenToRenderize[act_row + k][act_col + l][2] = colour;
screenToRenderize[act_row + l][act_col + k][0] = screenToRenderize[act_row + l][act_col + k][1] = screenToRenderize[act_row + l][act_col + k][2] = colour;
}
}
act_col += PIXEL_SIZE;
}
act_col = 0;
act_row += PIXEL_SIZE;
}
glDrawPixels(SCREEN_COLS, SCREEN_ROWS, GL_RGB, GL_UNSIGNED_BYTE, (void *)screenToRenderize); //disegno screenToRenderize
glutSwapBuffers();
}
void reshapeWindowCallback(GLsizei w, GLsizei h)
{
//per ora è vuota poi ci si pensa, viene chiamata quando uno allarga o restringe la finestra
memset((void*)screenToRenderize, 0x00, SCREEN_COLS * SCREEN_ROWS * 3);
glDrawPixels(SCREEN_COLS, SCREEN_ROWS, GL_RGB, GL_UNSIGNED_BYTE, (void *)screenToRenderize);
glutSwapBuffers();
}
void emulationLoop()
{
double clockPeriod_s = 1.0 / myChip8.clockFreq_hz;
unsigned long clockPeriod_us = static_cast<unsigned long>(clockPeriod_s * 1e6);
myChip8.emulateCycle();
if(myChip8.drawFlag)
{
renderChip8();
myChip8.drawFlag = false;
}
std::chrono::microseconds t = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
myChip8.onTickElapsed();
sleepMicroseconds(clockPeriod_us-(t.count()-t0.count()));
t0 = t;
}
void setupOpengl(int argc, char** argv) //funzione di inizializzazione di opengl
{
memset(openGlScreen, 0x00, GMEM_COLS * GMEM_ROWS);
memset(screenToRenderize, 0x00, SCREEN_COLS * SCREEN_ROWS);
glClear(GL_COLOR_BUFFER_BIT);
glutInit(&argc, argv); //passo a opengl eventuali argomenti da tastiera
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); //modo standard per inizializzare un display mode che va bene quasi sempre
glutInitWindowSize(SCREEN_COLS, SCREEN_ROWS); //creo una finestra SCREEN_COLS * SCREEN_ROWS
glutInitWindowPosition(0, 0); //piazzo la finestra in alto a sx
glutCreateWindow("chip8 emulator"); //visualizza la finestra con un titolo
glutDisplayFunc(renderChip8); //assegno renderChip8 alla displayFunc ossia la funzione che viene chiamata per renderizzare la memorya di chip8 (credo che questa debba essere eseguita ogni volta che drawFlag = true)
glutIdleFunc(emulationLoop); //assegno emulationLoop all'idleFunc ossia la funzione che viene ciclicamente eseguita da opengl tipo nei kilobot
glutReshapeFunc(reshapeWindowCallback); //assegno reshapeWindowCallback all'evento reshapeWindow di opengl
glutKeyboardFunc(keyPressCallback); //assegno la funzione keyPressCallback all'evento keyboard di opengl
glutKeyboardUpFunc(keyReleaseCallback); //stessa cosa con keyReleaseCallback
}
int main(int argc, char** argv)
{
run_tests();
setupOpengl(argc, argv);
myChip8.initialize();
myChip8.loadRom(argc > 1 ? argv[argc - 1] : "pong.ch8");
t0 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
glutMainLoop(); //lancio l'emulatore attraverso l'esecuzione della mainloop di opengl
return 0;
}
| true |
5b66a28d3ffee7f7a00fab31495b45ca2fbf0632 | C++ | zhongfei2016/leetcode-cpp | /tree/Common.h | UTF-8 | 909 | 2.9375 | 3 | [] | no_license | //
// leetcode-cpp
//
#ifndef LEETCODE_CPP_COMMON_H
#define LEETCODE_CPP_COMMON_H
#include <clocale>
#include <vector>
#include <string>
#include <queue>
using namespace std;
class Node {
public:
int val;
std::vector<Node *> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, std::vector<Node *> _children) {
val = _val;
children = _children;
}
};
class StrNode {
public:
string val;
std::vector<StrNode *> children;
StrNode() {}
StrNode(string _val) {
val = _val;
}
StrNode(string _val, std::vector<StrNode *> _children) {
val = _val;
children = _children;
}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *convertToTreeNode(vector<int> nodes);
#endif //LEETCODE_CPP_COMMON_H
| true |
d717c640220b4270931f13c0c5680a5de7fb0238 | C++ | manvendrakushwah/Project-Euler | /#005.cpp | UTF-8 | 779 | 2.703125 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t;
cin>>t;
while(t){
int n;
cin>>n;
vector<int> v;
vector<int> v1;
for(int l=2;l<=n;l++){
v.push_back(l);
}
for(int i=2;i<=n;i++){
v1.push_back(v[i-2]);
for(int j=i;j<=n;j++){
if(v[j]%v[i-2]==0){v[j]=v[j]/v[i-2];}
}
}
long long int product =1;
for(int k=0;k<v1.size();k++){
product*=v1[k];
}
cout<<product<<endl;
t--;
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
| true |
da6a2b739527a85d3860a7397537165cd2ef9520 | C++ | banjo13/mflib | /include/mflib/waveformTemplate.hpp | UTF-8 | 9,798 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef MFLIB_WAVEFORMTEMPLATE_HPP
#define MFLIB_WAVEFORMTEMPLATE_HPP
#include <memory>
#include "mflib/enums.hpp"
namespace MFLib
{
class NetworkStationPhase;
/*!
* @brief Defines a waveform template.
* @copyright Ben Baker (University of Utah) distributed under the MIT license.
*/
class WaveformTemplate
{
public:
/*! @name Constructors
* @{
*/
/*!
* @brief Constructor.
*/
WaveformTemplate();
/*!
* @brief Copy constructor.
* @param[in] tplate The template class from which to initialize this
* template.
*/
WaveformTemplate(const WaveformTemplate &tplate);
/*!
* @brief Move constructor.
* @param[in,out] tplate The template class whose memory will be moved
* to this. On exit, tplate's behavior is undefined.
*/
WaveformTemplate(WaveformTemplate &&tplate) noexcept;
/*! } */
/*!
* @brief Copy assignment operator.
* @param[in] tplate The waveform template class to copy.
* @result A deep copy of the inupt waveform template.
*/
WaveformTemplate& operator=(const WaveformTemplate &tplate);
/*!
* @brief Move assignment operator.
* @param[in,out] tplate The waveform template class whose memory will be
* moved to this class. On exit, tplate's behavior
* is undefined.
* @result The memory from tplate moved to this.
*/
WaveformTemplate& operator=(WaveformTemplate &&tplate) noexcept;
/*! @name Destructors
* @{
*/
/*!
* @brief Destructor.
*/
~WaveformTemplate();
/*!
* @brief Clears and resets the memory of the class.
*/
void clear() noexcept;
/*! @} */
/*! @name Signal (Required)
* @{
*/
/*!
* @brief Sets the template waveform signal.
* @param[in] npts The number of samples in the template.
* @param[in] x The template waveform signal. This is an array whose
* dimension is [npts].
* @throws std::invalid_argument if npts is not positive or x is NULL.
* @note This will invalidate the onset time.
*/
void setSignal(int npts, const double x[]);
/*! @coypdoc setSignal */
void setSignal(int npts, const float x[]);
/*!
* @brief Gets the template waveform signal.
* @param[in] maxx The maximum number of samples that x can hold. This
* must be at least \c getSignalLength().
* @param[out] x The waveform template. This is an array whose dimension
* is [maxx] however only the first \c getSignalLength()
* samples are accessed.
* @throws std::invalid_argument if x is NULL or maxx is too small.
* @throws std::runtime_error if the signal was not set.
*/
void getSignal(int maxx, double *x[]) const;
/*! @copydoc getSignal */
void getSignal(int maxx, float *x[]) const;
/*!
* @result The length of the template waveform signal.
* @throws std::runtime_error if the template waveform was not set.
* @sa \c haveSignal()
*/
int getSignalLength() const;
/*!
* @brief Determines if the template waveform signal was set.
* @result True indicates that the template was set.
*/
bool haveSignal() const noexcept;
/*! @} */
/*! @name Sampling Rate (Required)
* @{
*/
/*!
* @brief Sets the sampling rate.
* @param[in] samplingRate The sampling rate in Hz of the template waveform
* signal.
* @throws std::invalid_argument if this is not positive.
* @note This will invalidate the onset time.
*/
void setSamplingRate(double samplingRate);
/*!
* @brief Gets the sampling rate.
* @result The template's sampling rate.
* @throws std::runtime_error if the sampling rate was not set.
*/
double getSamplingRate() const;
/*!
* @brief Determines if the sampling rate was set.
* @result True indicates that the sampling rate was set.
*/
bool haveSamplingRate() const noexcept;
/*! @} */
/*! @name Shift and Sum Weight
* @{
*/
/*!
* @brief Defines the template's weight in the shift and stack operation.
* @param[in] weight The weight of this template during the shift and sum
* operation.
* @throws std::invalid_argument if weight is not in the range [0,1].
*/
void setShiftAndStackWeight(double weight);
/*!
* @brief Gets the template's weight during the shift and stack operation.
* @result The template's weight during the shift and sum operation.
* @note If \c setShiftStackAndWeight() was not called then this will
* be unity.
*/
double getShiftAndStackWeight() const noexcept;
/*! @} */
/*! @name Onset Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the time in seconds relative to the trace where the
* phase onset occurs.
* @param[in] onsetTime The onset time in seconds where the pick occurs.
* For example, if the pick is 2 seconds into the
* the trace, i.e., there is `noise' 2 seconds prior
* to the pick, then this should be 2.
* @throws std::runtime_error if the waveform template signal was not set
* or the sampling rate was not set.
* @throws std::invalid_argument if the onset time is not in the trace.
* @sa \c haveSignal(), \c haveSamplingRate().
* @note This is invalidated whenever the sampling period or signal is set.
*/
void setPhaseOnsetTime(double onsetTime);
/*!
* @brief Gets the phase onset time.
* @result The time, relative to the trace start, where the pick occurs.
* For example, if 2, then 2 seconds into the trace is where the
* pick was made.
* @throws std::runtime_error if the onset time was not set.
* @sa \c havePhaseOnsetTime()
*/
double getPhaseOnsetTime() const;
/*!
* @brief Determines if the onset time was set.
* @result True indicates that the onset time was set.
*/
bool havePhaseOnsetTime() const noexcept;
/*!@ } */
/*! @brief Travel Time (Required for Shifting)
* @{
*/
/*!
* @brief Sets the observed travel time for the pick.
* @param[in] travelTime The observed travel time in seconds for the pick.
* For example, if this is 7, then it took 7 seconds
* for the wave to travel from the source to the
* receiver.
* @throws std::invalid_argument if travelTime is negative
* @note The trace commences travelTime - onsetTime seconds after the origin
* time.
*/
void setTravelTime(double travelTime);
/*!
* @brief Gets the observed travel time for the pick.
* @result The observed travel time for this pick in seconds.
* For example, if this is 7, then it took 7 seconds for the
* wave to travel from the source to the receiver.
* @throws std::runtime_error if the travel time was not set.
* @sa \c haveTravelTime()
*/
double getTravelTime() const;
/*!
* @brief Determines if the travel time was set set.
* @result True indicates that the travel time was set.
*/
bool haveTravelTime() const noexcept;
/*! @} */
/*! @brief Identifier
* @{
*/
/*!
* @brief This is used to give the waveform template an identifier.
* The identifier defines the network, station, and phase
* as well as the event identifier to which the phase was associated
* in the catalog.
* @param[in] id The waveform identifier.
*/
void setIdentifier(const std::pair<NetworkStationPhase, uint64_t> &id) noexcept;
/*!
* @brief Gets the waveform template identifier.
* @result The waveform identifier where result.first is the network,
* station, and phase while result.second is the event identifier.
* @throws std::runtime_error if the waveform identifier was not set.
* @sa \c haveIdentifier()
*/
std::pair<NetworkStationPhase, uint64_t> getIdentifier() const;
/*!
* @brief Determines whether or not the waveform identifier was set.
* @result True indicates that the waveform identifier was set.
*/
bool haveIdentifier() const noexcept;
/*! @} */
/*! @brief Magnitude
* @{
*/
/*!
* @brief Sets the event magnitude associated with this template.
* @param[in] magnitude The magnitude.
*/
void setMagnitude(double magnitude) noexcept;
/*!
* @brief Gets the magnitude associated with this template.
* @result The magnitude associated with this template.
* @throws std::runtime_error if the magnitude was not set.
* @sa \c haveMagnitude()
*/
double getMagnitude() const;
/*!
* @brief Determines whether or not the magnitude was set.
* @result True indicates that the magnitude was set.
*/
bool haveMagnitude() const noexcept;
/*! @} */
/*! @brief Polarity
* @{
*/
/*!
* @brief Sets the onset's polarity.
* @param[in] polarity The arrival's polarity.
*/
void setPolarity(MFLib::Polarity polarity) noexcept;
/*!
* @brief Gets the onset's polarity.
* @result The onset's polarity. By default this is unknown.
*/
MFLib::Polarity getPolarity() const noexcept;
/*! @} */
private:
class WaveformTemplateImpl;
std::unique_ptr<WaveformTemplateImpl> pImpl;
};
}
#endif
| true |
1d8ef51cfc60c05548c136c6628f238e89f1124f | C++ | lifajun/algorithm | /AlgorithmStudy/DataStructure/BingChaJi/poj1988.cpp | GB18030 | 1,241 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
#define MAX 30005
int father[MAX], under[MAX], num[MAX];
//ÿһϣջĴջԪ
//fatherڼ¼
//underڼ¼Ԫصĸ
//numڼ¼ÿеԪصĸ
void init()
{
for(int i=0; i<MAX; i++)
{
father[i] = i;
under[i] = 0;
num[i] = 1;
}
}
int find(int x)
{
if(father[x] != x)
{
int t = father[x];
father[x] = find(father[x]);/*ѹ·*/
under[x] += under[t];/*ݹۼԪصĸ*/
}
return father[x];
}
void union_set(int a, int b)
{
int f1 = find(a), f2 = find(b);/*ϲǰҪһθڵ*/
/*ֻǵİһջĶᵽһջϣڱĶջû¶Ҳ*/
father[f1] = f2;
under[f1] += num[f2];
num[f2] += num[f1];
}
int main()
{
int P, a, b;
char cmd[2];
scanf("%d", &P);
init();
while(P--)
{
scanf("%s", cmd);
if(cmd[0] == 'M')
{
scanf("%d%d", &a, &b);
union_set(a, b);
}
else
{
scanf("%d", &a);
find(a);//Ҫ¶
printf("%d\n", under[a]);
}
}
return 0;
} | true |
165ac5767507df28cf2063d536f6027d493ef5ba | C++ | rcurtis/RedSand | /Cruncher/PTRandom.cpp | UTF-8 | 557 | 2.578125 | 3 | [] | no_license | #include "PTRandom.h"
#include <stdlib.h>
namespace Cruncher
{
PTRandom::PTRandom()
{
}
PTRandom::~PTRandom()
{
}
// TODO: Hook this into our RNG DLL. This is for testing.
void PTRandom::Init(int seed)
{
srand(seed);
}
// TODO: Hook this into our RNG DLL. This is for testing.
int PTRandom::GenRandom(int range)
{
return Range(0, range);
}
// TODO: Hook this into our RNG DLL. This is for testing.
int PTRandom::Range(int minValue, int maxValue)
{
return minValue + (rand() % static_cast<int>(maxValue - minValue + 1));
}
} | true |
c6501e5418de070b16d9498efbfec534429d9073 | C++ | Mugurell/Learning | /C++/C++ Primer 5th ed/Ch 3 - Strings, Vectors, and Arrays/middle_of_vector.cc | UTF-8 | 411 | 3.546875 | 4 | [
"Unlicense"
] | permissive | #include <iostream>
#include <vector>
int main()
{
std::vector<int> numar{1,2,3,4,888,6,7,8,9, 34567};
auto beg = numar.cbegin(), end = numar.cend();
auto mid =beg + (end - beg)/2; //(end-beg)/2 imi da un long int
std::cout << "So we have a vector of ints..\n\t";
for (auto nr : numar)
std::cout << ' ' << nr;
std::cout << std::endl;
std::cout << "The middle of which is " << *mid << std::endl;
} | true |
abe1e6a894aa7d242c9902c77ce69d9106c5f010 | C++ | QLingx/TechieDelight | /DP/ideone_lqsNoq.cpp | UTF-8 | 931 | 3.90625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Partition the set S into two subsets S1, S2 such that the
// difference between the sum of elements in S1 and the sum
// of elements in S2 is minimized
int minPartition(int S[], int n, int S1, int S2)
{
// base case: if list becomes empty, return the absolute
// difference between two sets
if (n < 0)
return abs(S1 - S2);
// Case 1. include current item in the subset S1 and recurse
// for remaining items (n - 1)
int inc = minPartition(S, n - 1, S1 + S[n], S2);
// Case 2. exclude current item from subset S1 and recurse for
// remaining items (n - 1)
int exc = minPartition(S, n - 1, S1, S2 + S[n]);
return min (inc, exc);
}
// main function
int main()
{
// Input: set of items
int S[] = { 10, 20, 15, 5, 25 };
// number of items
int n = sizeof(S) / sizeof(S[0]);
cout << "The minimum difference is " << minPartition(S, n - 1, 0, 0);
return 0;
} | true |
33d2a2b976474086481856b27893f829cb6d09a3 | C++ | Anna-Joe/Coding-Exercise | /codes/LA1153/源.cpp | UTF-8 | 2,872 | 2.765625 | 3 | [] | no_license | #pragma warning(disable:4996)
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct stu
{
string patNo;
string level;
int site;
int date;
int no;
int score;
};
struct siteCnt
{
int no;
int cnt = 0;
};
stu records[10007];
bool cmp1(stu a, stu b)
{
if (a.score != b.score)
return a.score > b.score;
else
return a.patNo < b.patNo;
}
bool cmp2(siteCnt a, siteCnt b)
{
if (a.cnt != b.cnt)
return a.cnt > b.cnt;
else
return a.no < b.no;
}
int main()
{
map<string, vector<stu> >levelMap;
map<int, vector<stu> > siteMap;
map<int, vector<stu> > dateMap;
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
string patNum;
int score;
cin >> patNum >> score;
//scanf("%s %d", &patNum, score);
records[i].patNo = patNum;
records[i].level = patNum.substr(0, 1);
records[i].site = stoi(patNum.substr(1, 3));
records[i].date = stoi(patNum.substr(4, 6));
records[i].no = stoi(patNum.substr(10, 3));
records[i].score = score;
levelMap[records[i].level].push_back(records[i]);
siteMap[records[i].site].push_back(records[i]);
dateMap[records[i].date].push_back(records[i]);
}
for (int i = 1; i <= m; i++)
{
int type;
cin >> type;
switch (type)
{
case 1:
{
string level;
cin >> level;
printf("Case %d: %d %s\n",i, type, level.c_str());
vector<stu> result = levelMap[level];
if (result.empty())
{
cout << "NA\n";
}
else
{
sort(result.begin(), result.end(), cmp1);
for (auto it = result.begin(); it != result.end();it++)
{
stu tmp = *it;
printf("%s %d\n", tmp.patNo.c_str(), tmp.score);
}
}
break;
}
case 2:
{
int site;
cin >> site;
printf("Case %d: %d %d\n", i, type, site);
vector<stu> result = siteMap[site];
if (result.empty())
{
cout << "NA\n";
}
else
{
int sum = 0;
for (auto it = result.begin(); it != result.end(); it++)
{
stu tmp = *it;
sum += tmp.score;
}
printf("%d %d\n", result.size(), sum);
}
break;
}
case 3:
{
int date;
cin >> date;
printf("Case %d: %d %d\n", i, type, date);
vector<stu> result = dateMap[date];
bool isOut[1000] = { false };
if (result.empty())
{
cout << "NA\n";
}
else
{
map<int,int> sites;
vector<siteCnt> siteV;
for (auto it = result.begin(); it != result.end(); it++)
{
stu tmp = *it;
sites[tmp.site]++;
}
for(auto it = sites.begin();it != sites.end();it++)
{
siteCnt t;
t.no = it->first;
t.cnt = it->second;
siteV.push_back(t);
}
sort(siteV.begin(), siteV.end(), cmp2);
for (auto it = siteV.begin(); it != siteV.end(); it++)
{
siteCnt tmp = *it;
printf("%d %d\n", tmp.no, tmp.cnt);
}
}
break;
}
default: break;
}
}
return 0;
} | true |
a5e6d261a7ff68d8b3a22f0eeea948608ceaa8dc | C++ | MattBrooks95/Andiamo | /text_box.h | UTF-8 | 5,419 | 2.828125 | 3 | [] | no_license | /*! \brief \file text_box.h this file describes a struct that
*has the information necessary for text boxes */
#pragma once
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
#include<SDL2/SDL_ttf.h>
#include<iostream>
#include<string>
//#include "sdl_help.h"
#include "cursor.h"
#include "asset_manager.h"
using std::string;
using std::regex;
extern sdl_help* sdl_access;
class field;
//! implements variables and logic for text boxes used by forms & buttons
/*! different from the text boxes used by the field objects in the manager
*class unfortunately. Homogenizing them is a goal. */
struct text_box{
//! constructor initializes the location of the text box
/*! it does so because I believe the default constructor can get called
*before the containing class has been properly set up, causing issues.
*So I've been writing init functions to fix that data
*once the containing class is set up */
text_box(TTF_Font* font_in=NULL, string text_in = "",int xloc_in = 0,
int yloc_in = 0,int width_in = 0, int height_in = 0);
//! prevents double free crashes when text_boxes are pushed into vectors
text_box(const text_box& other);
//! the destructor frees the memory for the sdl surfaces and textures
~text_box();
//! sets up the location of the text box on the screen and the renderer
/* this information should be passed in from whatever tile or button
*is instantiating the text box */
void init(TTF_Font* font_in,string text_in,int xloc_in,
int yloc_in,int width_in, int height_in);
//! sets pointers to the sdl class's scrolling values
/*! this is another initialization step for text boxes
*being used in a context that allows scrolling */
void set_scrolling();
//############## CLICK FUNCTIONS ###########################################
bool was_clicked(SDL_Event& mouse_event);
//##########################################################################
//! loop that modifies the text box's contents based on user input
void edit_loop(SDL_Event& event,string& command,regex* pattern);
//! helper for edit_loop, processes keystrokes
void edit_key_helper(SDL_Keysym& key,bool& text_was_changed,string& command);
//! prints all of this structs information, usually for debugging
void print_me();
//! this function draws the text box to the screen
void draw_me();
//! this version of draw_me draws the text box modified by scrolling
void draw_me(const int x_scroll, const int y_scroll);
//! updates the SDL_Rect storage of the text boxes location, for rendering
void make_rect();
//! update the text of this text box
/*! \param new_text is the test to be added
*\param test is a pointer to the regex pattern to use.
*NULL if not needed. */
void update_text(const string& new_text,regex* test);
//! update the texture when the text is changed
void update_texture();
/*! decides whether or not the input is bad,
*and changes the color of the text box accordingly */
void check_text(const regex& test);
//! this function turns the textbox red
/*! this is usually to indicate that the input is not consistent with
*what is expected by the Fortran code */
void toggle_red();
//! this function calls cursor's right member
void inc_cursor(bool& text_was_changed);
//! this function calls cursor's left member
void dec_cursor(bool& text_was_changed);
//! this removes one character in the string if it is not empty
/*! this deletion is made at the editing location, if the cursor
*is not at the very beginning of the string */
void back_space();
//! this version of back space tests the text string
/*! \param the regular expression which indicates good input */
void back_space(const regex& test);
//! location information stored in an SDL_Rect for rendering
SDL_Rect my_rect;
//! contains the color of the text in the box
SDL_Color text_color;
//! the horizontal coordinate of the upper left corner
int xloc;
//! the vertical coordinate of the upper left corner
int yloc;
//! the width should be set by the init function or the constructor
int width;
//! the height should be set by the init function or the constructor
int height;
//! pointer to current x scrolling value, if it exists
int* x_scroll;
//! pointer to current y scrolling value, if it exists
int* y_scroll;
//! save the absolute dimensions of the text in the button
SDL_Rect text_dims;
//! keep track of the currently shown subsection of the text
SDL_Rect shown_area;
//! class that handles drawing the text editing cursor
cursor my_cursor;
//! keep track of where the insertion point is for text
unsigned int editing_location;
//! the text that is rendered to the screen and changed by the user
string text;
//! keep track of whether this box has been given bad input or not
bool bad_input;
TTF_Font* font;//!< pointer to the font in the sdl_help class
SDL_Texture* text_box_texture;//!< texture for the text box
SDL_Surface* text_surface;//!< surface for the text
SDL_Texture* text_texture;//!< texture for the tex
SDL_Texture* bad_texture;//!< texture for text box to indicate bad input
};
| true |
921e48997c1407ec5bb78c4eef588e721a9829e7 | C++ | gzc/leetcode | /cpp/1001-10000/1781-1790/Maximize the Beauty of the Garden.cpp | UTF-8 | 562 | 2.984375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int maximumBeauty(vector<int>& flowers) {
unordered_map<int, int> mymap;
int res = INT_MIN;
int sum = 0;
for (int beauty : flowers) {
if (mymap.count(beauty) > 0) {
res = max(res, sum - mymap[beauty] + 2 * beauty);
}
if (beauty > 0) {
sum += beauty;
}
if (mymap.count(beauty) == 0) {
mymap[beauty] = sum;
}
}
return res;
}
};
| true |
1c6a5a5dfc08a6843bb548349c85df458d64164b | C++ | aanchal29/Robot-Localization-using-Deep-Learning-and-Particle-Filter | /localization/simulator/nodes/sensing_model_and_map.cpp | UTF-8 | 601 | 2.546875 | 3 | [] | no_license | #include "sensing_model_and_map.hpp"
namespace hmm
{
float gauss(float x, float mu, float sigma)
{
float exp = 0 - (std::pow((x-mu), 2) / (2 * sigma * sigma));
return (1/(sigma * std::sqrt(2*M_PI))) * (std::pow(M_E, exp));
}
float door(float mu, float x)
{
float sigma = 0.75;
float peak = gauss(0, 0, sigma);
return 0.8 * gauss(x, mu, sigma)/peak;
}
float p_door(float x)
{
return 0.1 + door(11, x) + door(18.5, x) + door(41, x);
}
float p_wall(float x)
{
return 1.0 - p_door(x);
}
}
| true |
30cae9b47d6b848bde8211e0af4efcab653e3c3f | C++ | ciupmeister/cplusplus | /Pipe/main.cpp | UTF-8 | 2,652 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>
using namespace std;
const char infile[] = "pipe.in";
const char outfile[] = "pipe.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 32005;
const int oo = 0x3f3f3f3f;
typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
int N, xst, yst, xfn, yfn;
int hor[2][2*MAXN], ver[2][2*MAXN], H, V;
int main() {
fin >> N >> xst >> yst >> xfn >> yfn;
memset(hor[0], oo, sizeof(hor[0]));
memset(ver[0], oo, sizeof(ver[0]));
hor[0][MAXN + xst] = 0;
ver[0][MAXN + yst] = 0;
for(int i = 1 ; i <= N ; ++ i) {
char color; int sz;
fin >> color >> sz;
if(color == 'R') {
++ V;
memset(ver[V & 1], oo, sizeof(ver[V & 1]));
for(int j = -MAXN ; j < MAXN ; ++ j) {
j += MAXN;
ver[V & 1][j] = ver[(V & 1) ^ 1][j]; /// decide not to take i-th piece
if(j - sz >= 0 && ver[(V & 1) ^ 1][j - sz] + sz < ver[V & 1][j]) {
ver[V & 1][j] = ver[(V & 1) ^ 1][j - sz] + sz;
}
if(j + sz < 2*MAXN && ver[(V & 1) ^ 1][j + sz] + sz < ver[V & 1][j])
ver[V & 1][j] = ver[(V & 1) ^ 1][j + sz] + sz;
j -= MAXN;
}
}
if(color == 'A') {
++ H;
memset(hor[H & 1], oo, sizeof(hor[H & 1]));
for(int j = -MAXN ; j < MAXN ; ++ j) {
j += MAXN;
hor[H & 1][j] = hor[(H & 1) ^ 1][j]; /// decide not to take i-th piece
if(hor[(H & 1) ^ 1][j - sz] + sz < hor[H & 1][j])
hor[H & 1][j] = hor[(H & 1) ^ 1][j - sz] + sz;
if(j + sz < 2*MAXN && hor[(H & 1) ^ 1][j + sz] + sz < hor[H & 1][j])
hor[H & 1][j] = hor[(H & 1) ^ 1][j + sz] + sz;
j -= MAXN;
}
}
}
if(hor[H & 1][MAXN + xfn] == oo || ver[V & 1][MAXN + yfn] == oo)
fout << "imposibil\n";
else
fout << hor[H & 1][MAXN + xfn] + ver[V & 1][MAXN + yfn] << '\n';
return 0;
}
| true |
bdf2179eed26099484ac2b8936ecaf33c52c1d26 | C++ | tcrowne3/2036Assignment7 | /TheMatrix.h | UTF-8 | 1,407 | 2.703125 | 3 | [] | no_license | #include <vector>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include "string.h"
#include <stdexcept>
#include "stdlib.h"
#include "Complex.h"
using namespace std;
class Matrix
{
friend Matrix operator-(Matrix &);
friend Matrix operator*(const ComplexNumber &, const Matrix &);
friend Matrix operator*(const double, const Matrix &);
friend Matrix operator~(Matrix &);
friend ostream& operator<<(ostream &, const Matrix &);
friend std::istream &operator>>(std::istream &, Matrix &);
public:
Matrix();
Matrix(const unsigned int);
Matrix(const unsigned int, const vector<ComplexNumber>);
unsigned int size() const;
ComplexNumber operator[](unsigned int) const;
void size(const unsigned int);
ComplexNumber& operator()(const unsigned int, const unsigned int);
Matrix operator+(const Matrix &);
Matrix& operator+=(const Matrix &);
Matrix operator-(const Matrix &);
Matrix operator*( const Matrix & );
Matrix operator*(const ComplexNumber &);
Matrix operator*(const double);
Matrix operator/(const ComplexNumber &);
Matrix operator/(const double);
Matrix& operator=(const Matrix &);
bool operator==(const Matrix &);
private:
vector<ComplexNumber> data;
const ComplexNumber zero;
unsigned int sizeMat;
ComplexNumber** matrix;
}; | true |
c682ca07bf9a98146d5153fe8b4a0b17fedbf2c7 | C++ | Mark-Diedericks/Game-Engine | /GameEngineBase/src/Math/Vector4f.h | UTF-8 | 3,982 | 2.828125 | 3 | [] | no_license | #pragma once
#include <math.h>
#include "Common.h"
#include "Vector3f.h"
#include "Utils.h"
namespace gebase { namespace math {
struct Matrix4f;
class GE_API Vector4f {
public:
float x, y, z, w;
inline Vector4f() : x(0), y(0), z(0), w(0) {}
Vector4f(const float& ix, const float& iy, const float& iz, const float& iw);
Vector4f(const Vector3f& vector, const float& iw);
float getLength() const;
float dot(const Vector4f& Vector4ff) const;
Vector4f normalize();
Vector4f lerp(const Vector4f& Vector4ff, const float& factor) const;
Vector4f refelect(const Vector4f& normal) const;
inline Vector4f* Floor()
{
this->x = floor(x);
this->y = floor(y);
this->z = floor(z);
this->w = floor(w);
return this;
}
inline Vector4f* Ceiling()
{
this->x = ceiling(x);
this->y = ceiling(y);
this->z = ceiling(z);
this->w = ceiling(w);
return this;
}
inline Vector4f* Round()
{
this->x = round(x);
this->y = round(y);
this->z = round(z);
this->w = round(w);
return this;
}
inline void operator =(const float& f) {
this->x = f;
this->y = f;
this->z = f;
this->w = f;
}
inline void operator =(const Vector4f& Vector4ff) {
this->x = Vector4ff.x;
this->y = Vector4ff.y;
this->z = Vector4ff.z;
this->w = Vector4ff.w;
}
inline bool operator ==(const Vector4f& Vector4ff) const {
return this->x == Vector4ff.x && this->y == Vector4ff.y && this->z == Vector4ff.z && this->w == Vector4ff.w;
}
inline Vector4f& operator +=(const float& f) {
this->x += f;
this->y += f;
this->z += f;
this->w += f;
return *this;
}
inline Vector4f& operator +=(const Vector4f& Vector4ff) {
this->x += Vector4ff.x;
this->y += Vector4ff.y;
this->z += Vector4ff.z;
this->w += Vector4ff.w;
return *this;
}
inline Vector4f& operator -=(const float& f) {
this->x -= f;
this->y -= f;
this->z -= f;
this->w -= f;
return *this;
}
inline Vector4f& operator -=(const Vector4f& Vector4ff) {
this->x -= Vector4ff.x;
this->y -= Vector4ff.y;
this->z -= Vector4ff.z;
this->w -= Vector4ff.w;
return *this;
}
inline Vector4f& operator *=(const float& f) {
this->x *= f;
this->y *= f;
this->z *= f;
this->w *= f;
return *this;
}
inline Vector4f& operator *=(const Vector4f& Vector4ff) {
this->x *= Vector4ff.x;
this->y *= Vector4ff.y;
this->z *= Vector4ff.z;
this->w *= Vector4ff.w;
return *this;
}
inline Vector4f& operator /=(const float& f) {
this->x /= f;
this->y /= f;
this->z /= f;
this->w /= f;
return *this;
}
inline Vector4f& operator /=(const Vector4f& Vector4ff) {
this->x /= Vector4ff.x;
this->y /= Vector4ff.y;
this->z /= Vector4ff.z;
this->w /= Vector4ff.w;
return *this;
}
inline Vector4f operator +(const float& f) const {
return Vector4f(x + f, y + f, z + f, w + f);
}
inline Vector4f operator +(const Vector4f& Vector4ff) const {
return Vector4f(x + Vector4ff.x, y + Vector4ff.y, z + Vector4ff.z, w + Vector4ff.w);
}
inline Vector4f operator -(const float& f) const {
return Vector4f(x - f, y - f, z - f, w - f);
}
inline Vector4f operator -(const Vector4f& Vector4ff) const {
return Vector4f(x - Vector4ff.x, y - Vector4ff.y, z - Vector4ff.z, w - Vector4ff.w);
}
inline Vector4f operator *(const float& f) const {
return Vector4f(x * f, y * f, z * f, w * f);
}
inline Vector4f operator *(const Vector4f& Vector4ff) const {
return Vector4f(x * Vector4ff.x, y * Vector4ff.y, z * Vector4ff.z, w * Vector4ff.w);
}
inline Vector4f operator /(const float& f) const {
return Vector4f(x / f, y / f, z / f, w / f);
}
inline Vector4f operator /(const Vector4f& Vector4ff) const {
return Vector4f(x / Vector4ff.x, y / Vector4ff.y, z / Vector4ff.z, w / Vector4ff.w);
}
Vector4f operator *(const Matrix4f& Matrix4ff) const;
Vector4f Mul(const Matrix4f& Matrix4ff) const;
};
} } | true |
cf6acbbdba71f2d41b9f6a4cae088074fad8add1 | C++ | eritry/algorithms | /structure/segment-tree.cpp | UTF-8 | 666 | 2.53125 | 3 | [] | no_license | int tree[4 * MAXN], leave[MAXN], n, k;
void upd(int i, int mod) {
int v = leave[i];
tree[v] = mod;
while (v) {
v = (v - 1) / 2;
tree[v] = tree[2 * v + 1] + tree[2 * v + 2];
}
}
int get(int v, int l, int r, int L, int R) {
if (L <= l && R >= r) return tree[v];
if (l > R || r < L) return 0;
int m = (l + r) / 2;
return get(2 * v + 1, l, m, L, R) + get(2 * v + 2, m + 1, r, L, R);
}
void build(int v, int l, int r) {
tree[v] = r - l + 1;
if (l == r) {
leave[l] = v;
return;
}
int m = (l + r) / 2;
build(2 * v + 1, l, m);
build(2 * v + 2, m + 1, r);
} | true |
229317c75adae4849ee92dc0242c0f92c284ec74 | C++ | atakhalo/rich | /项目源码/大富翁/CardBag.cpp | GB18030 | 1,893 | 3.015625 | 3 | [] | no_license | //***************************************************************************************
// ֣ ̿ * Դļ
// ߣ ¬͢
// ڣ 2017-8-24
// ڣ 2017-8-24
//***************************************************************************************
#include "CardBag.h"
namespace Rich
{
CARD::CARD() : name(std::string("(None)")),weight(0),silver(0),isPopUI(false)
{
}
/*---------------------------------------------------------------------------------*/
RichCardManager* RichCardManager::m_pInstance = nullptr;
RichCardManager * RichCardManager::GetInstance()
{
if (m_pInstance == nullptr)
m_pInstance = new RichCardManager();
return m_pInstance;
}
void RichCardManager::DestroyInstance()
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = nullptr;
}
}
HRESULT RichCardManager::ReadCardFromFile(LPCSTR fileName)
{
std::ifstream in(fileName);
if (!in)
{
::MessageBox(nullptr, L" : Ϣļ", L"", 0);
return E_FAIL;
}
Rich::CARD oneCard;
std::string ignore;
int CardNum = 0;
// ȡƬ
in >> ignore;
in >> CardNum;
// ȡƬϢ
// ֣ƷʣㄻǷUI
in >> ignore;
in >> ignore;
in >> ignore;
in >> ignore;
for (int i = 0; i < CardNum; ++i)
{
in >> oneCard.name;
in >> oneCard.weight;
in >> oneCard.silver;
in >> oneCard.isPopUI;
m_CardBag.push_back(oneCard);
}
in.close();
if (m_CardBag.size() <= 0)
{
::MessageBox(nullptr, L" : ȷϢǷĵʽ", L"", 0);
return E_FAIL;
}
return S_OK;
}
const CARD & RichCardManager::GetCardByEnum(CardType type)
{
int index = static_cast<int>(type);
return m_CardBag[index];
}
} // ռ
| true |
8faeaeafebb76d49670c96d2bbfa4f42ac7330c7 | C++ | arif061126/My-C-plus-plus-Project | /area of triangle.cpp | UTF-8 | 615 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int base, height;
cout<<"Enter the base of triangle: ";
cin>>base;
cout<<"Enter the height of triangle: ";
cin>>height;
//double area=1/2*base*height; //output=0
//cout<<"The area of triangle is: "<<area;
double area=1.0/2*base*height;
cout<<"The area of triangle is: "<<area<<endl;
double area1=(double)1/2*base*height;
cout<<"The area of triangle is: "<<area1<<endl;
double area2=0.5*base*height;
cout<<"The area of triangle is: "<<area2;
getch();
}
| true |
685d3e7b4c503d1596f8822b9830fc045f2e00d1 | C++ | klainqin/LandXmlSDK | /Source/xs_privateinclude/TimingTmpl.h | UTF-8 | 1,653 | 2.515625 | 3 | [] | no_license | #if !defined(__TIMINGTMPL_H)
#define __TIMINGTMPL_H
#include "Timing.h"
#include "LXTypesTmpl.h"
namespace LX
{
// Class : Timing
template<class T>
class TimingTmpl : public ObjectTmpl<T>
{
public:
virtual void toXml (IStream& stream);
public:
// Constructors
TimingTmpl (DocumentImpl* pDoc);
public:
// Destructors
virtual ~TimingTmpl ();
public:
// Collections
public:
// Properties
virtual double getStation() const;
virtual void setStation(double value);
virtual bool hasValue_Station() const;
virtual void resetValue_Station();
virtual int getLegNumber() const;
virtual void setLegNumber(int value);
virtual bool hasValue_LegNumber() const;
virtual void resetValue_LegNumber();
virtual double getProtectedTurnPercent() const;
virtual void setProtectedTurnPercent(double value);
virtual bool hasValue_ProtectedTurnPercent() const;
virtual void resetValue_ProtectedTurnPercent();
virtual double getUnprotectedTurnPercent() const;
virtual void setUnprotectedTurnPercent(double value);
virtual bool hasValue_UnprotectedTurnPercent() const;
virtual void resetValue_UnprotectedTurnPercent();
virtual Object::ValidityEnum validate(IValidationEventSink *pEventSink) const;
protected:
double m_Station;
bool m_bStation_valueSet;
int m_LegNumber;
bool m_bLegNumber_valueSet;
double m_ProtectedTurnPercent;
bool m_bProtectedTurnPercent_valueSet;
double m_UnprotectedTurnPercent;
bool m_bUnprotectedTurnPercent_valueSet;
};
}; // namespace : LX
#endif
| true |
aecab24a1b877ed2f5485e22ce58b9ca721b9b0b | C++ | de-mar-n/robo | /src/custom.cpp | UTF-8 | 2,258 | 3.09375 | 3 | [] | no_license | #include "custom.h"
#ifdef RED_YELLOW_MODE
Mat create_mask_left(InputArray hsv)
{
Mat mask1, mask2;
// Creating masks to detect the upper and lower red color
// Red got 2 inRange because it's a major color while yellow is a minor
inRange(hsv, Scalar(0, 120, 70), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 120, 70), Scalar(180, 255, 255), mask2);
mask1 = mask1 + mask2;
return mask1;
}
Mat create_mask_right(InputArray hsv)
{
// Creating masks to detect the upper and lower yellow color.
Mat mask;
inRange(hsv, Scalar(20, 150, 150), Scalar(50, 255, 255), mask);
return mask;
}
#else
#ifdef GREEN_BLUE_MODE
// Example: here, we use green for LEFT points and blue for RIGHT points.
Mat create_mask_left(InputArray hsv)
{
// H: 97/360 → 48/180
// S: 53/100 → 135/255
// V: 51/100 → 130/255
Mat mask;
inRange(hsv, Scalar(30, 100, 100), Scalar(70, 255, 255), mask);
return mask;
}
Mat create_mask_right(InputArray hsv)
{
// H: 201/360 → 100/180
// S: 60/100 → 153/255
// V: 68/100 → 173/255
Mat mask;
inRange(hsv, Scalar(80, 100, 100), Scalar(120, 255, 255), mask);
return mask;
}
#else
// Example: here, we use red for LEFT points and yellow for RIGHT points.
Mat create_mask_left(InputArray hsv)
{
Mat mask1, mask2;
// Creating masks to detect the upper and lower red color
// Red got 2 inRange because it's a major color while yellow is a minor
inRange(hsv, Scalar(0, 120, 70), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 120, 70), Scalar(180, 255, 255), mask2);
mask1 = mask1 + mask2;
return mask1;
}
Mat create_mask_right(InputArray hsv)
{
// Creating masks to detect the upper and lower yellow color.
Mat mask;
inRange(hsv, Scalar(20, 150, 150), Scalar(50, 255, 255), mask);
return mask;
}
#endif
#endif
| true |
a0ef7f2bb9862824651513592c83a8e201a24543 | C++ | ContraMolinos/CellSim | /voxel.cpp | UTF-8 | 655 | 2.703125 | 3 | [] | no_license | #include "voxel.h"
Voxel::Voxel(qreal _x, qreal _y, qreal _w, qreal _h):shape(new QGraphicsRectItem(0,0,_w,_h)),isOn(false)
{
shape->setPos(_x,_y);
}
Voxel::Voxel(const Voxel& _other):isOn(_other.isOn)
{
shape=new QGraphicsRectItem(_other.shape->rect());
shape->setPos(_other.shape->pos());
}
Voxel::~Voxel()
{
delete shape;
shape=nullptr;
}
bool Voxel::status()
{
return isOn;
}
void Voxel::switchFill()
{
if(shape->brush().style()==Qt::NoBrush)
shape->setBrush(QBrush(Qt::black));
else
shape->setBrush(Qt::NoBrush);
isOn=!isOn;
}
QGraphicsRectItem *Voxel::getShape() const
{
return shape;
}
| true |
f8867facd71525a6e369495261f4f834a8d1e609 | C++ | sysosil-sbny/BYNS-Cinema | /filenrand.cpp | UTF-8 | 3,597 | 2.765625 | 3 | [] | no_license | #include "SeatINFO.hpp"
#include "UserINFO.hpp"
#include <fcntl.h>
#include <iostream>
#include <list>
#include <vector>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_LENGTH 8
#define BUFSIZE 1024
using namespace std;
vector<string> split(string data, char dot){
vector<string> result;
string one = "";
for (int i = 0; i < data.size(); i++){
if (data[i] == dot){
result.push_back(one);
one = "";
} else {
one += data[i];
}
}
result.push_back(one);
return result;
}
list<User> ul;
void write_usr(string name, string resnum, int seatnum) {
User usr(name, resnum, seatnum);
ul.push_back(usr);
string filepath = "./UserList.dat";
int fd = open(filepath.c_str(), O_APPEND | O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
perror("open() error");
}
list<User>::iterator iter;
for (iter = ul.begin();iter!=ul.end() ; ++iter) {
string all = iter->getName() + "," + iter->getResNum() + "," + to_string(iter->getSeatNum()) + "\n";
if (write(fd, all.c_str(), all.size()) == -1) {
perror("write() error");
exit(-2);
}
}
close(fd);
}
void print_user(User test){
cout << "Name \t" << test.getName() << endl;
cout << "ResN \t" << test.getResNum() << endl;
cout << "Seat \t" << test.getSeatNum() << endl;
}
void read_usr(string resNum) {
string filepath = "./UserList.dat";
int fd = open(filepath.c_str(), O_RDONLY);
if (fd == -1) {
perror("open() error");
}
ssize_t rSize = 0;
vector<User> usrList;
vector<int> seatData;
char data[BUFSIZE];
int size = read(fd, data, BUFSIZE);
string stringData = string(data);
vector<string> cutString = split(stringData, '\n');
cutString.pop_back();
for (auto i: cutString){
vector<string> entry = split(i, ',');
string name = entry[0];
string res = entry[1];
string numy = entry[2];
int n = atoi(numy.c_str());
if (name == "") break;
User usr = User(name, res, n);
seatData.push_back(atoi(entry[2].c_str()));
usrList.push_back(usr);
}
close(fd);
cout<<"========="<<endl;
int same=1;
int idx = -1;
for (auto user_data: usrList) {
idx ++;
same = strcmp(user_data.getResNum().c_str(), resNum.c_str());
string str = "";
str.push_back( 'a' + seatData[idx]%8-(seatData[idx]/8));
str.push_back('1' + seatData[idx]/8);
if (same == 0) {
// printf("%s님이 예매하신 좌석은 %s입니다.\n", user_data.getName(), str);
//cout << user_data.getResNum() << " " << endl;
cout<<user_data.getName()<<"님이 예매하신 좌석은 "<<str<<"입니다."<<endl;
return;
}
else {
continue;
}
}
cout << "예매하신 좌석이 없습니다." << endl;
}
string randchar() {
string resnum;
int i;
rand();
for (i = 0; i < MAX_LENGTH / 2; i++) {
char n = rand() % 26 + 'A';
resnum += n;
}
for (i = MAX_LENGTH / 2; i < MAX_LENGTH; i++) {
char n = rand() % 10 + '0';
resnum += n;
}
return resnum;
}
| true |
64494343fad61b898d0e32d922f922f584122fed | C++ | ScaryPG/afina | /src/storage/StripedLRU.h | UTF-8 | 1,687 | 2.6875 | 3 | [] | no_license | #ifndef AFINA_STORAGE_STRIPED_LRU_H
#define AFINA_STORAGE_STRIPED_LRU_H
#include <map>
#include <mutex>
#include <string>
#include <vector>
#include "SimpleLRU.h"
namespace Afina {
namespace Backend {
class StripedLRU : public SimpleLRU {
private:
StripedLRU(size_t memory_limit, size_t stripe_count) : _stripe_count(stripe_count) {
for (size_t i = 0; i < stripe_count; ++i) {
_shards.emplace_back(memory_limit);
}
}
public:
static std::unique_ptr<StripedLRU> BuildStripedLRU(size_t memory_limit, size_t stripe_count);
~StripedLRU() {}
// see SimpleLRU.h
bool Put(const std::string &key, const std::string &value) override {
return _shards[std::hash<std::string>{}(key) % _stripe_count].Put(key, value);
}
// see SimpleLRU.h
bool PutIfAbsent(const std::string &key, const std::string &value) override {
return _shards[std::hash<std::string>{}(key) % _stripe_count].PutIfAbsent(key, value);
}
// see SimpleLRU.h
bool Set(const std::string &key, const std::string &value) override {
return _shards[std::hash<std::string>{}(key) % _stripe_count].Set(key, value);
}
// see SimpleLRU.h
bool Delete(const std::string &key) override {
return _shards[std::hash<std::string>{}(key) % _stripe_count].Delete(key);
}
// see SimpleLRU.h
bool Get(const std::string &key, std::string &value) override {
return _shards[std::hash<std::string>{}(key) % _stripe_count].Get(key, value);
}
private:
size_t _stripe_count = 8;
std::vector<SimpleLRU> _shards;
};
} // namespace Backend
} // namespace Afina
#endif // AFINA_STORAGE_STRIPED_LRU_H
| true |
6ff035afa90fa69d3a905339dd3bef15cad1cef7 | C++ | kaibraaten/swrip-1.5 | /src/commands/examine.cpp | UTF-8 | 9,844 | 2.796875 | 3 | [] | no_license | #include <cstring>
#include "mud.hpp"
#include "board.hpp"
#include "character.hpp"
#include "object.hpp"
#include "triggers.hpp"
void do_examine(std::shared_ptr<Character> ch, std::string arg)
{
char buf[MAX_STRING_LENGTH] = { '\0' };
std::shared_ptr<Object> obj;
std::shared_ptr<Board> board;
short dam = 0;
if(arg.empty())
{
ch->Echo("Examine what?\r\n");
return;
}
sprintf(buf, "%s noprog", arg.c_str());
do_look(ch, buf);
/*
* Support for looking at boards, checking equipment conditions,
* and support for trigger positions by Thoric
*/
if((obj = GetObjectHere(ch, arg)) != NULL)
{
if((board = GetBoardFromObject(obj)) != NULL)
{
const size_t numberOfPosts = board->Notes().size();
if(numberOfPosts > 0)
{
ch->Echo("There are %lu notes posted here.Type 'note list' to list them.\r\n",
numberOfPosts);
}
else
{
ch->Echo("There aren't any notes posted here.\r\n");
}
}
switch(obj->ItemType)
{
default:
break;
case ITEM_ARMOR:
if(obj->Value[OVAL_ARMOR_AC] == 0)
obj->Value[OVAL_ARMOR_AC] = obj->Value[OVAL_ARMOR_CONDITION];
if(obj->Value[OVAL_ARMOR_AC] == 0)
obj->Value[OVAL_ARMOR_AC] = 1;
dam = (short)((obj->Value[OVAL_ARMOR_CONDITION] * 10) / obj->Value[OVAL_ARMOR_AC]);
strcpy(buf, "As you look more closely, you notice that it is ");
if(dam >= 10)
strcat(buf, "in superb condition.");
else if(dam == 9)
strcat(buf, "in very good condition.");
else if(dam == 8)
strcat(buf, "in good shape.");
else if(dam == 7)
strcat(buf, "showing a bit of wear.");
else if(dam == 6)
strcat(buf, "a little run down.");
else if(dam == 5)
strcat(buf, "in need of repair.");
else if(dam == 4)
strcat(buf, "in great need of repair.");
else if(dam == 3)
strcat(buf, "in dire need of repair.");
else if(dam == 2)
strcat(buf, "very badly worn.");
else if(dam == 1)
strcat(buf, "practically worthless.");
else if(dam <= 0)
strcat(buf, "broken.");
strcat(buf, "\r\n");
ch->Echo("%s", buf);
break;
case ITEM_WEAPON:
dam = INIT_WEAPON_CONDITION - obj->Value[OVAL_WEAPON_CONDITION];
strcpy(buf, "As you look more closely, you notice that it is ");
if(dam == 0)
strcat(buf, "in superb condition.");
else if(dam == 1)
strcat(buf, "in excellent condition.");
else if(dam == 2)
strcat(buf, "in very good condition.");
else if(dam == 3)
strcat(buf, "in good shape.");
else if(dam == 4)
strcat(buf, "showing a bit of wear.");
else if(dam == 5)
strcat(buf, "a little run down.");
else if(dam == 6)
strcat(buf, "in need of repair.");
else if(dam == 7)
strcat(buf, "in great need of repair.");
else if(dam == 8)
strcat(buf, "in dire need of repair.");
else if(dam == 9)
strcat(buf, "very badly worn.");
else if(dam == 10)
strcat(buf, "practically worthless.");
else if(dam == 11)
strcat(buf, "almost broken.");
else if(dam == 12)
strcat(buf, "broken.");
strcat(buf, "\r\n");
ch->Echo("%s", buf);
if(obj->Value[OVAL_WEAPON_TYPE] == WEAPON_BLASTER)
{
if(obj->BlasterSetting == BLASTER_FULL)
ch->Echo("It is set on FULL power.\r\n");
else if(obj->BlasterSetting == BLASTER_HIGH)
ch->Echo("It is set on HIGH power.\r\n");
else if(obj->BlasterSetting == BLASTER_NORMAL)
ch->Echo("It is set on NORMAL power.\r\n");
else if(obj->BlasterSetting == BLASTER_HALF)
ch->Echo("It is set on HALF power.\r\n");
else if(obj->BlasterSetting == BLASTER_LOW)
ch->Echo("It is set on LOW power.\r\n");
else if(obj->BlasterSetting == BLASTER_STUN)
ch->Echo("It is set on STUN.\r\n");
ch->Echo("It has from %d to %d shots remaining.\r\n",
obj->Value[OVAL_WEAPON_CHARGE] / 5,
obj->Value[OVAL_WEAPON_CHARGE]);
}
else if((obj->Value[OVAL_WEAPON_TYPE] == WEAPON_LIGHTSABER ||
obj->Value[OVAL_WEAPON_TYPE] == WEAPON_VIBRO_BLADE ||
obj->Value[OVAL_WEAPON_TYPE] == WEAPON_FORCE_PIKE))
{
ch->Echo("It has %d/%d units of charge remaining.\r\n",
obj->Value[OVAL_WEAPON_CHARGE], obj->Value[OVAL_WEAPON_MAX_CHARGE]);
}
break;
case ITEM_FOOD:
if(obj->Timer > 0 && obj->Value[OVAL_FOOD_MAX_CONDITION] > 0)
dam = (obj->Timer * 10) / obj->Value[OVAL_FOOD_MAX_CONDITION];
else
dam = 10;
strcpy(buf, "As you examine it carefully you notice that it ");
if(dam >= 10)
strcat(buf, "is fresh.");
else if(dam == 9)
strcat(buf, "is nearly fresh.");
else if(dam == 8)
strcat(buf, "is perfectly fine.");
else if(dam == 7)
strcat(buf, "looks good.");
else if(dam == 6)
strcat(buf, "looks ok.");
else if(dam == 5)
strcat(buf, "is a little stale.");
else if(dam == 4)
strcat(buf, "is a bit stale.");
else if(dam == 3)
strcat(buf, "smells slightly off.");
else if(dam == 2)
strcat(buf, "smells quite rank.");
else if(dam == 1)
strcat(buf, "smells revolting.");
else if(dam <= 0)
strcat(buf, "is crawling with maggots.");
strcat(buf, "\r\n");
ch->Echo("%s", buf);
break;
case ITEM_SWITCH:
case ITEM_LEVER:
case ITEM_PULLCHAIN:
if(IsBitSet(obj->Value[OVAL_SWITCH_TRIGFLAGS], TRIG_UP))
ch->Echo("You notice that it is in the up position.\r\n");
else
ch->Echo("You notice that it is in the down position.\r\n");
break;
case ITEM_BUTTON:
if(IsBitSet(obj->Value[OVAL_BUTTON_TRIGFLAGS], TRIG_UP))
ch->Echo("You notice that it is depressed.\r\n");
else
ch->Echo("You notice that it is not depressed.\r\n");
break;
case ITEM_CORPSE_PC:
case ITEM_CORPSE_NPC:
{
short timerfrac = obj->Timer;
if(obj->ItemType == ITEM_CORPSE_PC)
timerfrac = (int)obj->Timer / 8 + 1;
switch(timerfrac)
{
default:
ch->Echo("This corpse has recently been slain.\r\n");
break;
case 4:
ch->Echo("This corpse was slain a little while ago.\r\n");
break;
case 3:
ch->Echo("A foul smell rises from the corpse, and it is covered in flies.\r\n");
break;
case 2:
ch->Echo("A writhing mass of maggots and decay, you can barely go near this corpse.\r\n");
break;
case 1:
case 0:
ch->Echo("Little more than bones, there isn't much left of this corpse.\r\n");
break;
}
}
if(obj->Flags.test(Flag::Obj::Covering))
break;
ch->Echo("When you look inside, you see:\r\n");
sprintf(buf, "in %s noprog", arg.c_str());
do_look(ch, buf);
break;
case ITEM_DROID_CORPSE:
{
short timerfrac = obj->Timer;
switch(timerfrac)
{
default:
ch->Echo("These remains are still smoking.\r\n");
break;
case 4:
ch->Echo("The parts of this droid have cooled down completely.\r\n");
break;
case 3:
ch->Echo("The broken droid components are beginning to rust.\r\n");
break;
case 2:
ch->Echo("The pieces are completely covered in rust.\r\n");
break;
case 1:
case 0:
ch->Echo("All that remains of it is a pile of crumbling rust.\r\n");
break;
}
}
case ITEM_CONTAINER:
if(obj->Flags.test(Flag::Obj::Covering))
break;
case ITEM_DRINK_CON:
ch->Echo("When you look inside, you see:\r\n");
sprintf(buf, "in %s noprog", arg.c_str());
do_look(ch, buf);
break;
}
if(obj->Flags.test(Flag::Obj::Covering))
{
sprintf(buf, "under %s noprog", arg.c_str());
do_look(ch, buf);
}
ObjProgExamineTrigger(ch, obj);
if(CharacterDiedRecently(ch) || IsObjectExtracted(obj))
return;
CheckObjectForTrap(ch, obj, TRAP_EXAMINE);
}
}
| true |
1e0c0cac51cd714569fa85bbb3fd7c1c635314df | C++ | w-swift/DX11Demo | /DX11Demo/CubeShader.cpp | UTF-8 | 1,785 | 2.609375 | 3 | [] | no_license | #include "CubeShader.h"
D3D11_INPUT_ELEMENT_DESC cbShaderInputLayoutDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(cbShaderInputLayoutDesc);
CubeShader::CubeShader()
{
cbShaderInputData.WVP = XMMatrixIdentity();
}
CubeShader::~CubeShader()
{
vs->Release();
ps->Release();
vertLayout->Release();
cbShaderInputBuffer->Release();
}
void CubeShader::Initiatilize(D3DCore* d3dCore)
{
//Compile Shaders from shader file
auto VS_Buffer = ReadData("VertexShader.cso");
auto PS_Buffer = ReadData("PixelShader.cso");
//Create the Shader Objects
d3dCore->d3d11Device->CreateVertexShader(VS_Buffer.data(), VS_Buffer.size(), NULL, &vs);
d3dCore->d3d11Device->CreatePixelShader(PS_Buffer.data(), PS_Buffer.size(), NULL, &ps);
d3dCore->d3d11Device->CreateInputLayout(cbShaderInputLayoutDesc, numElements, VS_Buffer.data(),
VS_Buffer.size(), &vertLayout);
D3D11_BUFFER_DESC cbShaderInputBufferDesc;
ZeroMemory(&cbShaderInputBufferDesc, sizeof(D3D11_BUFFER_DESC));
cbShaderInputBufferDesc.Usage = D3D11_USAGE_DEFAULT;
cbShaderInputBufferDesc.ByteWidth = sizeof(cbShaderInputData);
cbShaderInputBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbShaderInputBufferDesc.CPUAccessFlags = 0;
cbShaderInputBufferDesc.MiscFlags = 0;
d3dCore->d3d11Device->CreateBuffer(&cbShaderInputBufferDesc, NULL, &cbShaderInputBuffer);
}
static std::vector<char> ReadData(char const* filename)
{
std::ifstream ifs(filename, std::ios::binary | std::ios::ate);
std::ifstream::pos_type pos = ifs.tellg();
std::vector<char> result(pos);
ifs.seekg(0, std::ios::beg);
ifs.read(&result[0], pos);
return result;
} | true |
3f4101971320a4700e2a675a2453b1934221a057 | C++ | RaduMilici/cpp-tutorial-beginners | /src/practice/fight/Brawl.cpp | UTF-8 | 1,175 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include "Brawl.h"
using namespace std;
//PUBLIC***************************************************************
Brawl::Brawl(Fighter& a, Fighter& b){
fighters[0] = &a;
fighters[1] = &b;
}
//---------------------------------------------------------------------
void Brawl::start(){
cout << "Brawl between " << (*fighters[0]).getName() << flush;
cout << " and " << (*fighters[1]).getName() << flush;
cout << " is about to begin!" << endl;
cout << "------" << endl;
keepFighting();
}
//PRIVATE**************************************************************
void Brawl::keepFighting(){
while(areBothAlive()){
(*fighters[0]).dealDamage(*fighters[1]);
swapPlaces();
cout << "------" << endl;
}
cout << "Brawl over!" << endl;
}
//---------------------------------------------------------------------
bool Brawl::areBothAlive(){
return (*fighters[0]).isAlive() && (*fighters[1]).isAlive();
}
//---------------------------------------------------------------------
void Brawl::swapPlaces(){
Fighter* swap = fighters[0];
fighters[0] = fighters[1];
fighters[1] = swap;
}
//---------------------------------------------------------------------
| true |